oli-server 0.1.4

A simple, blazingly fast AI coding assistant server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
import React, { useEffect, useState, useCallback, useMemo } from "react";
import { Box } from "ink";
import { BackendService } from "../services/backend.js";
import ChatInterface from "./ChatInterface.js";
import ModelSelector from "./ModelSelector.js";
import StatusBar from "./StatusBar.js";
import HeaderBox from "./HeaderBox.js";
// Theme is used by imported components

import { AppState, ToolExecution, ToolStatusUpdate } from "../types/index.js";
import { isCommand } from "../utils/commandUtils.js";
import {
  executeCommand,
  processUserMessage,
} from "../utils/commandHandlers.js";

// App props interface
interface AppProps {
  backend: BackendService;
  noHeader?: boolean; // Flag to disable the header rendering
}

// Main app component
const App: React.FC<AppProps> = ({ backend, noHeader = false }) => {
  // App state
  const [state, setState] = useState<AppState>({
    models: [],
    selectedModel: 0,
    messages: [],
    isProcessing: false,
    error: null,
    backendConnected: false,
    appMode: "setup", // Start in setup mode
    useAgent: true, // Agent mode is always enabled
  });

  // Tool executions state - separate to avoid re-rendering the entire app on tool updates
  const [toolExecutions, setToolExecutions] = useState<
    Map<string, ToolExecution>
  >(new Map());

  // UI state
  const [showShortcuts, setShowShortcuts] = useState(false);

  // Subscribe to tool status events
  useEffect(() => {
    // Setup tool status subscription when backend is available
    const setupToolStatusSubscription = async () => {
      try {
        await backend.subscribe("tool_status");
        // Subscribed successfully
      } catch (error) {
        console.error("Failed to subscribe to tool status updates:", error);
      }
    };

    // Handle tool status events
    const handleToolStatus = (params: ToolStatusUpdate) => {
      const { type, execution } = params;

      setToolExecutions((prev) => {
        // Create a new Map to avoid mutating state
        const newMap = new Map(prev);

        if (type === "started") {
          // Add new tool execution to the map
          newMap.set(execution.id, execution);
        } else if (type === "updated") {
          // Update existing tool in the map
          newMap.set(execution.id, execution);

          // When a tool completes, add a message to the chat history
          if (execution.status !== "running" && execution.endTime) {
            setState((prev) => {
              // Add a tool result message to the messages array
              return {
                ...prev,
                messages: [
                  ...prev.messages,
                  {
                    id: `tool-result-${execution.id}`,
                    role: "tool",
                    content: `[${execution.name}] ${execution.message}`,
                    timestamp: Date.now(),
                    task_id: execution.task_id,
                    tool: execution.name,
                    tool_status:
                      execution.status === "success" ? "success" : "error",
                    tool_data: {
                      name: execution.name,
                      file_path: execution.metadata.file_path as
                        | string
                        | undefined,
                      lines: execution.metadata.lines as number | undefined,
                      description:
                        execution.message ||
                        (execution.metadata.description as string | undefined),
                    },
                  },
                ],
              };
            });

            // Remove completed tool from the map after a short delay
            setTimeout(() => {
              setToolExecutions((current) => {
                const updatedMap = new Map(current);
                updatedMap.delete(execution.id);
                return updatedMap;
              });
            }, 3000);
          }
        }

        return newMap;
      });
    };

    // Subscribe when component mounts
    backend.on("tool_status", handleToolStatus);
    setupToolStatusSubscription();

    // Unsubscribe when component unmounts
    return () => {
      backend.off("tool_status", handleToolStatus);
      backend.unsubscribe("tool_status").catch(console.error);
    };
  }, [backend]);

  // Load initial data
  useEffect(() => {
    // Listen for backend connection events
    backend.on("backend_connected", (params) => {
      setState((prev) => ({
        ...prev,
        models: params.models || [],
        backendConnected: true,
        backendInfo: {
          ...params,
        },
      }));
    });

    backend.on("backend_connection_error", (params) => {
      setState((prev) => ({
        ...prev,
        error: params.error,
        backendConnected: false,
        messages: [
          ...prev.messages,
          {
            id: `system-${Date.now()}`,
            role: "system",
            content: `Failed to connect to backend: ${params.error}`,
            timestamp: Date.now(),
          },
        ],
      }));
    });

    // Register event listeners for backend notifications
    backend.on("processing_started", (params) => {
      setState((prev) => ({
        ...prev,
        isProcessing: true,
        // If agent mode is specified in the event, update state
        ...(params.use_agent !== undefined
          ? { useAgent: params.use_agent }
          : {}),
      }));
    });

    backend.on("processing_progress", (params) => {
      // Add progress message if it's not already in the list
      setState((prev) => {
        // Only add the message if it's not a duplicate
        if (!prev.messages.some((m) => m.content === params.message)) {
          return {
            ...prev,
            messages: [
              ...prev.messages,
              {
                id: `progress-${Date.now()}`,
                role: "system",
                content: params.message,
                timestamp: Date.now(),
                task_id: params.task_id,
              },
            ],
          };
        }
        return prev;
      });
    });

    backend.on("processing_complete", () => {
      setState((prev) => ({
        ...prev,
        isProcessing: false,
      }));
    });

    backend.on("processing_error", (params) => {
      setState((prev) => ({
        ...prev,
        isProcessing: false,
        error: params.error,
        messages: [
          ...prev.messages,
          {
            id: `error-${Date.now()}`,
            role: "system",
            content: `Error: ${params.error}`,
            timestamp: Date.now(),
          },
        ],
      }));
    });

    // Handle legacy tool execution events by converting them to the new format
    backend.on("tool_execution", (params) => {
      // Generate a unique identifier for this tool execution
      const toolId = `tool-${params.tool}-${Date.now()}`;

      // Bridge old tool_execution events to the new tool_status system
      setToolExecutions((prev) => {
        const newMap = new Map(prev);
        const execution: ToolExecution = {
          id: toolId,
          task_id: params.task_id || "",
          name: params.tool,
          status: params.status || "running",
          startTime: Date.now(),
          endTime: params.status !== "running" ? Date.now() : undefined,
          message: params.message,
          metadata: {
            file_path: params.file_path,
            lines: params.lines,
            description: params.description,
          },
        };

        // Add to tool executions map
        newMap.set(toolId, execution);

        return newMap;
      });

      // Add a message to the state for the tool execution
      setState((prev) => {
        return {
          ...prev,
          messages: [
            ...prev.messages,
            {
              id: toolId,
              role: "tool",
              content: `[${params.tool}] ${params.message}`,
              timestamp: Date.now(),
              task_id: params.task_id,
              tool: params.tool,
              tool_status: params.status || "running",
              tool_data: {
                name: params.tool,
                file_path: params.file_path,
                lines: params.lines,
                description: params.description,
              },
            },
          ],
          // Task tracking is now handled through toolExecutions Map
        };
      });

      // If the tool is now complete, remove it from active tools after a delay
      if (params.status && params.status !== "running") {
        setTimeout(() => {
          setToolExecutions((current) => {
            const updatedMap = new Map(current);
            updatedMap.delete(toolId);
            return updatedMap;
          });
        }, 3000);
      }
    });

    backend.on("log_message", () => {
      // Silent log handling
    });

    // Clean up event listeners on component unmount
    return () => {
      backend.removeAllListeners();
    };
  }, [backend]);

  // Handle model selection - memoized to prevent unnecessary rerenders
  const handleModelSelect = useCallback((index: number) => {
    setState((prev) => ({
      ...prev,
      selectedModel: index,
    }));
  }, []);

  // Memoize the clear history handler
  const handleClearHistory = useCallback(() => {
    // Clear all messages from the UI state
    setState((prev) => ({
      ...prev,
      messages: [], // Clear all messages
      error: null, // Also clear any error state
    }));
  }, []);

  // Memoize command execution handler to reduce rerenders
  const handleExecuteCommand = useCallback(
    (command: string) => {
      // First try to execute as a built-in command
      const wasHandled = executeCommand(command, state, setState, backend, {
        handleClearHistory,
        handleModelSelect,
      });

      // If not a built-in command, handle as regular input
      if (!wasHandled) {
        processUserMessage(command, state, setState, backend);
      }
    },
    [state, backend, handleClearHistory, handleModelSelect],
  );

  // Handle regular user input (non-commands)
  const handleRegularInput = useCallback(
    async (input: string) => {
      // Process user message without command handling
      await processUserMessage(input, state, setState, backend);
    },
    [state, setState, backend],
  );

  // Combined handler for all user input
  const handleUserInput = useCallback(
    async (input: string) => {
      // If this is a command, handle it separately through the command handler
      if (isCommand(input)) {
        handleExecuteCommand(input);
        return;
      }

      // This is a regular user message - send it to the backend
      await handleRegularInput(input);
    },
    [handleExecuteCommand, handleRegularInput],
  );

  // Handle model confirmation and switch to chat mode - memoized to prevent unnecessary rerenders
  const handleModelConfirm = useCallback(() => {
    // Only proceed if we have models and backend is connected
    if (state.models.length > 0 && state.backendConnected) {
      setState((prev) => ({
        ...prev,
        appMode: "chat",
      }));
    }
  }, [state.models, state.backendConnected]);

  // Memoize the toggle shortcuts handler
  const handleToggleShortcuts = useCallback(() => {
    setShowShortcuts((prev) => !prev);
  }, []);

  // Memoize components to prevent unnecessary rerenders
  const modelSelectorComponent = useMemo(
    () => (
      <ModelSelector
        models={state.models}
        selectedIndex={state.selectedModel}
        onSelect={handleModelSelect}
        onConfirm={handleModelConfirm}
        isLoading={!state.backendConnected || state.models.length === 0}
      />
    ),
    [
      state.models,
      state.selectedModel,
      state.backendConnected,
      handleModelSelect,
      handleModelConfirm,
    ],
  );

  // Handle task interruption
  const handleInterrupt = useCallback(() => {
    // Call the backend to interrupt the current task
    if (state.isProcessing) {
      backend
        .call("interrupt_processing", {})
        .then(() => {
          setState((prev) => ({
            ...prev,
            isProcessing: false,
            messages: [
              ...prev.messages,
              {
                id: `system-${Date.now()}`,
                role: "system",
                content: "Task interrupted by user",
                timestamp: Date.now(),
              },
            ],
          }));
        })
        .catch((err) => {
          console.error("Failed to interrupt task:", err);
          // Set processing to false anyway to update UI
          setState((prev) => ({
            ...prev,
            isProcessing: false,
            messages: [
              ...prev.messages,
              {
                id: `system-${Date.now()}`,
                role: "system",
                content: "Attempted to interrupt task but encountered an error",
                timestamp: Date.now(),
              },
            ],
          }));
        });
    }
  }, [state.isProcessing, backend]);

  // Clean up message history to prevent duplicates
  const filteredMessages = useMemo(() => {
    // Track seen user messages to remove duplicates
    const seenUserMessages = new Set<string>();

    // Filter for a clean chat history
    return state.messages.filter((msg) => {
      // Keep all assistant messages
      if (msg.role === "assistant") return true;

      // For user messages, check for duplicates
      if (msg.role === "user") {
        // Skip duplicates based on content
        if (seenUserMessages.has(msg.content)) {
          return false;
        }

        // Mark as seen and keep
        seenUserMessages.add(msg.content);
        return true;
      }

      // For tools and system messages, keep them all
      return true;
    });
  }, [state.messages]);

  const chatInterfaceComponent = useMemo(
    () => (
      <ChatInterface
        messages={filteredMessages}
        isProcessing={state.isProcessing}
        onSubmit={handleUserInput}
        onInterrupt={handleInterrupt}
        showShortcuts={showShortcuts}
        onToggleShortcuts={handleToggleShortcuts}
        onClearHistory={handleClearHistory}
        onExecuteCommand={handleExecuteCommand}
        toolExecutions={toolExecutions}
      />
    ),
    [
      filteredMessages,
      state.isProcessing,
      toolExecutions,
      handleUserInput,
      handleInterrupt,
      showShortcuts,
      handleToggleShortcuts,
      handleClearHistory,
      handleExecuteCommand,
    ],
  );

  const statusBarComponent = useMemo(
    () => (
      <StatusBar
        modelName={state.models[state.selectedModel]?.name || "AI Assistant"}
        isProcessing={state.isProcessing}
        backendConnected={state.backendConnected}
        showShortcuts={showShortcuts}
      />
    ),
    [
      state.models,
      state.selectedModel,
      state.isProcessing,
      state.backendConnected,
      showShortcuts,
    ],
  );

  // Render with memoized components for better performance
  if (state.appMode === "setup") {
    // Setup mode - directly render the model selector without any container
    return modelSelectorComponent;
  }

  // Get the current model name
  const modelName = state.models[state.selectedModel]?.name || "AI Assistant";

  // Single column layout with component-based architecture
  return (
    <Box flexDirection="column" width="100%" height="100%">
      {/* Only render header if not disabled */}
      {!noHeader && <HeaderBox modelName={modelName} />}

      {/* Chat area with extra margin when header is disabled */}
      <Box flexGrow={1} flexDirection="column" marginTop={noHeader ? 1 : 0}>
        {chatInterfaceComponent}
      </Box>

      {/* Status bar */}
      {statusBarComponent}
    </Box>
  );
};

export default App;