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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
/* eslint-disable @typescript-eslint/no-unused-vars */
import React, { useState, useEffect, useCallback } from "react";
import { Box, Text, useInput } from "ink";
import TextInput from "ink-text-input";
import theme from "../styles/gruvbox.js";
import ShortcutsPanel from "./ShortcutsPanel.js";
import CommandPalette from "./CommandPalette.js";
import ToolStatusIndicator from "./ToolStatusIndicator.js";
import StatusDisplay from "./StatusDisplay.js";
import TaskInterruptionHandler from "./TaskInterruptionHandler.js";
import { isCommand } from "../utils/commandUtils.js";

// Import types
import { Message, ToolExecution } from "../types/index.js";

// Messages Display component - memoized to only render when messages change
interface MessagesDisplayProps {
  visibleMessages: Message[];
  formatMessage: (message: Message) => React.ReactNode;
}

const MessagesDisplay: React.FC<MessagesDisplayProps> = React.memo(
  ({ visibleMessages, formatMessage }) => {
    return (
      <Box flexDirection="column" flexGrow={1} padding={1}>
        {visibleMessages.length === 0 ? (
          <Box
            flexGrow={1}
            alignItems="center"
            justifyContent="center"
            flexDirection="column"
            padding={2}
          >
            <Text {...theme.styles.text.highlight}>Ready for input...</Text>
          </Box>
        ) : (
          <Box flexDirection="column" flexGrow={1}>
            {visibleMessages.map((message) => (
              <Box key={message.id} marginY={1}>
                {formatMessage(message)}
              </Box>
            ))}
          </Box>
        )}
      </Box>
    );
  },
);

// Input Area component - memoized to prevent unnecessary renders
interface InputAreaProps {
  input: string;
  setInput: (value: string) => void;
  multilineInput: string;
  setMultilineInput: (value: string) => void;
  commandMode: boolean;
  setCommandMode: (value: boolean) => void;
  showCommandPalette: boolean;
  setShowCommandPalette: (value: boolean) => void;
  commandHistory: string[];
  setCommandHistory: (fn: (prev: string[]) => string[]) => void;
  historyIndex: number;
  setHistoryIndex: (value: number) => void;
  filteredCommands: Array<{ value: string; description: string }>;
  selectedIndex: number;
  showShortcuts: boolean;
  onToggleShortcuts?: () => void;
  onExecuteCommand?: (command: string) => void;
  handleCommandSelect: (command: string) => void;
  handleSubmit: (value: string) => void;
}

const InputArea: React.FC<InputAreaProps> = React.memo(
  ({
    input,
    setInput,
    multilineInput,
    setMultilineInput,
    commandMode,
    setCommandMode,
    showCommandPalette,
    setShowCommandPalette,
    commandHistory,
    setCommandHistory,
    historyIndex,
    setHistoryIndex,
    filteredCommands,
    selectedIndex,
    showShortcuts,
    onToggleShortcuts,
    onExecuteCommand,
    handleCommandSelect,
    handleSubmit,
  }) => {
    // Handle onChange for input field
    const handleInputChange = useCallback(
      (value: string) => {
        // Handle ? key for shortcuts (already handled in useInput)
        if (input === "" && value === "?") {
          // Don't update input here
          return;
        }

        // Hide shortcuts panel when user starts typing
        if (showShortcuts) {
          onToggleShortcuts?.();
        }

        // Update input value normally
        setInput(value);

        // Check for / command mode
        if (input === "" && value === "/") {
          // Enter command mode
          setCommandMode(true);
          setShowCommandPalette(true);
          // Update input with /
          setInput("/");
          return;
        }

        // Show/hide command palette based on command mode
        if (commandMode && value.startsWith("/")) {
          setShowCommandPalette(true);
        } else if (commandMode && !value.startsWith("/")) {
          // Exit command mode if user removes the slash
          setCommandMode(false);
          setShowCommandPalette(false);
        }
      },
      [input, commandMode, showShortcuts, onToggleShortcuts],
    );

    // Handle input submission
    const handleInputSubmit = useCallback(
      (value: string) => {
        if (value.trim() === "") return;

        // If in command mode and command palette is visible,
        // we use selected command from palette instead of input value
        if (commandMode && showCommandPalette && filteredCommands?.length > 0) {
          // Get the selected command from the command palette
          const selectedCommand = filteredCommands[selectedIndex]?.value;

          // Use the selected command instead of partial input
          if (selectedCommand) {
            // Handle command selection from palette (this will execute the command)
            handleCommandSelect(selectedCommand);
            return;
          }
        }

        // Reset command mode
        if (commandMode) {
          setCommandMode(false);
          setShowCommandPalette(false);
        }

        // Handle non-selected commands (typed fully by user)
        if (isCommand(value)) {
          setCommandHistory((prev) => [...prev, value]);
          setHistoryIndex(-1);

          // Let the dedicated command handler process it
          if (onExecuteCommand) {
            onExecuteCommand(value);

            // Clear input and exit early - command was handled externally
            setInput("");
            return;
          }
        }

        // For non-commands or when onExecuteCommand isn't available
        if (multilineInput) {
          // For multiline input, combine with existing content
          const fullInput = multilineInput + value;
          handleSubmit(fullInput);
          setMultilineInput("");
        } else {
          // Regular input flow
          handleSubmit(value);
        }

        // Clear input explicitly - this works with ink-text-input
        setInput("");
      },
      [
        commandMode,
        showCommandPalette,
        filteredCommands,
        selectedIndex,
        multilineInput,
        setMultilineInput,
        setCommandMode,
        setShowCommandPalette,
        setCommandHistory,
        setHistoryIndex,
        setInput,
        handleCommandSelect,
        handleSubmit,
        onExecuteCommand,
      ],
    );

    return (
      <Box paddingX={2} paddingY={1} flexDirection="column">
        <Box
          borderStyle={commandMode ? "single" : undefined}
          borderColor={theme.colors.dark.green}
          paddingX={1}
          paddingY={commandMode ? 1 : 0}
          flexDirection="column"
        >
          <Box flexDirection="column" flexGrow={1}>
            {/* Previous lines with proper indentation - only show prompt on first line */}
            {multilineInput.split("\n").map((line, i) => (
              <Box key={i} flexDirection="row">
                {/* Only show prompt character on the first line if there's actual content */}
                {i === 0 && line.trim().length > 0 && (
                  <Text
                    color={
                      commandMode
                        ? theme.colors.dark.green
                        : theme.colors.dark.blue
                    }
                    bold
                  >
                    {commandMode ? "/" : ">"}
                  </Text>
                )}
                {/* No prompt for empty first line or continuation lines */}
                {(i !== 0 || line.trim().length === 0) && <Box width={1}></Box>}
                <Box marginLeft={1}>
                  <Text>{line}</Text>
                </Box>
              </Box>
            ))}

            {/* Current input row with prompt - only show if no multiline input */}
            <Box flexDirection="row">
              {/* Only show prompt if we don't have multiline input */}
              {multilineInput.length === 0 && (
                <Text
                  color={
                    commandMode
                      ? theme.colors.dark.green
                      : theme.colors.dark.blue
                  }
                  bold
                >
                  {commandMode ? "/" : ">"}
                </Text>
              )}
              {/* Otherwise keep the spacing consistent */}
              {multilineInput.length > 0 && <Box width={1}></Box>}

              <Box marginLeft={1} flexGrow={1}>
                <TextInput
                  value={input}
                  onChange={handleInputChange}
                  onSubmit={handleInputSubmit}
                  placeholder={
                    commandMode
                      ? "Type a command or use arrows to navigate..."
                      : ""
                  }
                />
              </Box>
            </Box>
          </Box>
        </Box>
      </Box>
    );
  },
);

// Component props
interface ChatInterfaceProps {
  messages: Message[];
  isProcessing: boolean;
  onSubmit: (input: string) => void;
  onInterrupt?: () => void;
  showShortcuts?: boolean;
  onToggleShortcuts?: () => void;
  onClearHistory?: () => void;
  onExecuteCommand?: (command: string) => void;
  toolExecutions?: Map<string, ToolExecution>;
}

// Chat interface component
const ChatInterface: React.FC<ChatInterfaceProps> = ({
  messages,
  isProcessing,
  onSubmit,
  onInterrupt,
  showShortcuts = false,
  onToggleShortcuts,
  onClearHistory,
  onExecuteCommand,
  toolExecutions = new Map(),
}) => {
  const [input, setInput] = useState("");
  const [visibleMessages, setVisibleMessages] = useState<Message[]>([]);
  const [commandMode, setCommandMode] = useState(false);
  // These are used in the handleInputSubmit callback and useInput hook
  const [commandHistory, setCommandHistory] = useState<string[]>([]);
  const [historyIndex, setHistoryIndex] = useState(-1);
  const [showCommandPalette, setShowCommandPalette] = useState(false);
  const [multilineInput, setMultilineInput] = useState("");
  const [filteredCommands, setFilteredCommands] = useState<
    Array<{ value: string; description: string }>
  >([]);
  const [selectedIndex, setSelectedIndex] = useState(0);

  // Handle keyboard shortcuts
  useInput((inputChar, key) => {
    // Handle ? key to toggle shortcuts panel when input is empty
    if (
      inputChar === "?" &&
      input === "" &&
      !isProcessing &&
      !commandMode &&
      !multilineInput
    ) {
      // Toggle shortcuts panel
      onToggleShortcuts?.();

      // Don't add ? to input
      setInput("");

      return;
    }

    // Ctrl+J to insert a newline (a more reliable cross-platform shortcut)
    if (key.ctrl && inputChar === "j" && !commandMode) {
      // Hide shortcuts panel when entering multiline mode
      if (showShortcuts) {
        onToggleShortcuts?.();
      }

      if (input) {
        setMultilineInput((prev) => prev + input + "\n");
        setInput("");
      } else {
        setMultilineInput((prev) => prev + "\n");
      }
      return;
    }

    // Handle / key specially when it's the only input - for command mode
    if (inputChar === "/" && input === "" && !isProcessing && !commandMode) {
      // Let the TextInput's onChange handler process this
      // This avoids interfering with cursor positioning
      return;
    }

    // ESC key to exit command mode
    if (key.escape && commandMode) {
      setCommandMode(false);
      setShowCommandPalette(false);
      setInput("");
      return;
    }

    // Ctrl+L to clear history
    if (key.ctrl && inputChar === "l") {
      onClearHistory?.();
      return;
    }

    // Handle command mode navigation
    if (commandMode) {
      // Tab for autocomplete is now handled in CommandPalette

      // Up/Down for command history when not showing command palette
      if (!showCommandPalette) {
        if (key.upArrow && commandHistory.length > 0) {
          const newIndex = Math.min(
            commandHistory.length - 1,
            historyIndex + 1,
          );
          setHistoryIndex(newIndex);
          setInput(commandHistory[commandHistory.length - 1 - newIndex] || "");
        }

        if (key.downArrow && historyIndex > -1) {
          const newIndex = Math.max(-1, historyIndex - 1);
          setHistoryIndex(newIndex);
          setInput(
            newIndex === -1
              ? "/"
              : commandHistory[commandHistory.length - 1 - newIndex] || "",
          );
        }
      }
    }
  });

  // Update visible messages when messages change, with debouncing
  useEffect(() => {
    // Only show the last 20 messages to prevent terminal overflow
    // Use setTimeout to debounce frequent updates
    const timer = setTimeout(() => {
      setVisibleMessages(messages.slice(-20));
    }, 10);

    return () => clearTimeout(timer);
  }, [messages]);

  // Tool messages are now handled directly by the StatusDisplay component

  // Handle command selection from the command palette
  const handleCommandSelect = (command: string) => {
    setCommandMode(false);
    setShowCommandPalette(false);

    // Execute the selected command
    if (onExecuteCommand) {
      onExecuteCommand(command);
    } else {
      // Handle common commands if onExecuteCommand is not provided
      if (command === "/clear") {
        onClearHistory?.();
      } else if (command === "/exit") {
        process.exit(0);
      } else {
        // Pass as a normal query if not a recognized command
        onSubmit(command);
      }
    }

    // Add to command history
    setCommandHistory((prev) => [...prev, command]);
    setHistoryIndex(-1);
    setInput("");
  };

  // Handle input submission
  const handleSubmit = (value: string) => {
    if (value.trim() === "") return;

    // Double-check for commands - all commands should be handled by handleExecuteCommand
    if (isCommand(value)) {
      console.log(
        "WARNING: Command reached handleSubmit - this should be handled by onExecuteCommand",
      );

      // Use fallback command handling
      if (value === "/clear") {
        onClearHistory?.();
        return;
      } else if (value === "/help") {
        onToggleShortcuts?.();
        return;
      } else if (value === "/exit") {
        process.exit(0);
      }
    }

    // For non-commands and unknown commands, send as normal input to backend
    onSubmit(value);

    // Reset both input states
    setInput("");
    setMultilineInput("");
  };

  // Get Gruvbox style for a message based on its role
  const getMessageStyle = (role: string) => {
    switch (role) {
      case "user":
        return theme.styles.text.user;
      case "assistant":
        return theme.styles.text.assistant;
      case "system":
        return theme.styles.text.system;
      case "tool":
        return theme.styles.text.tool;
      default:
        return {};
    }
  };

  // Format message content with role prefix and styling
  const formatMessage = (message: Message) => {
    const style = getMessageStyle(message.role);

    return (
      <Box marginY={1} paddingX={1} flexDirection="column">
        {message.role === "user" ? (
          <Box flexDirection="row">
            <Text color={theme.colors.dark.blue} bold>
              {">"}
            </Text>
            <Box marginLeft={1} flexGrow={1}>
              <Text {...style} wrap="wrap">
                {message.content}
              </Text>
            </Box>
          </Box>
        ) : message.role === "assistant" ? (
          <Box flexGrow={1}>
            <Text {...style} wrap="wrap">
              {message.content}
            </Text>
          </Box>
        ) : message.role === "tool" &&
          message.tool_status &&
          message.tool_data ? (
          <ToolStatusIndicator
            status={message.tool_status}
            data={message.tool_data}
          />
        ) : (
          <Box flexGrow={1}>
            <Text {...style} wrap="wrap">
              {message.content}
            </Text>
          </Box>
        )}
      </Box>
    );
  };

  // Optimized layout with better spacing and grouping
  return (
    <>
      {/* Messages area */}
      <MessagesDisplay
        visibleMessages={visibleMessages}
        formatMessage={formatMessage}
      />

      {/* Unified status display - only renders while processing is active */}
      <StatusDisplay
        toolExecutions={toolExecutions}
        isProcessing={isProcessing}
        onInterrupt={onInterrupt || (() => {})}
      />

      {/* Invisible handler for interruption */}
      <TaskInterruptionHandler
        isProcessing={isProcessing}
        onInterrupt={onInterrupt || (() => {})}
      />

      {/* Input area */}
      <InputArea
        input={input}
        setInput={setInput}
        multilineInput={multilineInput}
        setMultilineInput={setMultilineInput}
        commandMode={commandMode}
        setCommandMode={setCommandMode}
        showCommandPalette={showCommandPalette}
        setShowCommandPalette={setShowCommandPalette}
        commandHistory={commandHistory}
        setCommandHistory={setCommandHistory}
        historyIndex={historyIndex}
        setHistoryIndex={setHistoryIndex}
        filteredCommands={filteredCommands}
        selectedIndex={selectedIndex}
        showShortcuts={showShortcuts}
        onToggleShortcuts={onToggleShortcuts}
        onExecuteCommand={onExecuteCommand}
        handleCommandSelect={handleCommandSelect}
        handleSubmit={handleSubmit}
      />

      {/* Command palette */}
      <CommandPalette
        visible={showCommandPalette}
        filterText={input}
        onSelect={handleCommandSelect}
        onFilteredCommandsChange={setFilteredCommands}
        onSelectedIndexChange={setSelectedIndex}
      />

      {/* Shortcuts panel */}
      <ShortcutsPanel visible={showShortcuts || false} />
    </>
  );
};

export default ChatInterface;