mu-coding 0.4.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +49 -5
  2. package/bin/mu.js +1 -1
  3. package/package.json +17 -4
  4. package/prompts/SYSTEM.md +16 -0
  5. package/src/app/shutdown.ts +94 -0
  6. package/src/app/startApp.ts +43 -0
  7. package/src/cli/args.ts +131 -0
  8. package/src/{install.ts → cli/install.ts} +19 -15
  9. package/src/config/index.test.ts +77 -0
  10. package/src/config/index.ts +199 -0
  11. package/src/main.ts +4 -0
  12. package/src/plugin.ts +96 -0
  13. package/src/runtime/codingTools/bash.ts +114 -0
  14. package/src/runtime/codingTools/edit-file.ts +60 -0
  15. package/src/runtime/codingTools/index.ts +39 -0
  16. package/src/runtime/codingTools/read-file.ts +83 -0
  17. package/src/runtime/codingTools/utils.ts +21 -0
  18. package/src/runtime/codingTools/write-file.ts +42 -0
  19. package/src/runtime/createRegistry.test.ts +146 -0
  20. package/src/runtime/createRegistry.ts +163 -0
  21. package/src/runtime/messageBus.test.ts +62 -0
  22. package/src/runtime/messageBus.ts +78 -0
  23. package/src/runtime/pluginLoader.ts +122 -0
  24. package/src/sessions/index.test.ts +66 -0
  25. package/src/sessions/index.ts +183 -0
  26. package/src/sessions/peek.test.ts +88 -0
  27. package/src/sessions/project.ts +51 -0
  28. package/src/tui/channel/tuiChannel.test.ts +107 -0
  29. package/src/tui/channel/tuiChannel.ts +49 -0
  30. package/src/tui/{context/chat.ts → chat/ChatContext.ts} +1 -1
  31. package/src/tui/chat/MessageRendererContext.ts +44 -0
  32. package/src/tui/chat/ToolDisplayContext.ts +33 -0
  33. package/src/tui/{useAbort.ts → chat/useAbort.ts} +16 -7
  34. package/src/tui/chat/useAttachment.ts +74 -0
  35. package/src/tui/chat/useChat.ts +106 -0
  36. package/src/tui/chat/useChatPanel.ts +98 -0
  37. package/src/tui/chat/useChatSession.ts +284 -0
  38. package/src/tui/{useModelList.ts → chat/useModels.ts} +12 -2
  39. package/src/tui/chat/usePluginStatus.ts +44 -0
  40. package/src/tui/chat/useSessionPersistence.ts +68 -0
  41. package/src/tui/chat/useStatusSegments.ts +62 -0
  42. package/src/tui/components/chat/ChatPanel.tsx +20 -40
  43. package/src/tui/components/chat/ChatPanelBody.tsx +30 -52
  44. package/src/tui/components/chat/Pickers.tsx +2 -2
  45. package/src/tui/components/messageView.tsx +72 -0
  46. package/src/tui/components/messages/EditOutput.tsx +47 -30
  47. package/src/tui/components/messages/ReadOutput.tsx +27 -22
  48. package/src/tui/components/messages/ToolHeader.tsx +28 -0
  49. package/src/tui/components/messages/WriteOutput.tsx +12 -24
  50. package/src/tui/components/messages/assistantMessage.tsx +17 -2
  51. package/src/tui/components/messages/messageItem.tsx +23 -16
  52. package/src/tui/components/messages/reasoningBlock.tsx +4 -2
  53. package/src/tui/components/messages/streamingOutput.tsx +5 -1
  54. package/src/tui/components/messages/toolCallBlock.tsx +61 -38
  55. package/src/tui/components/messages/userMessage.tsx +21 -6
  56. package/src/tui/components/{ui → primitives}/dropdown.tsx +40 -11
  57. package/src/tui/components/{ui → primitives}/modal.tsx +4 -2
  58. package/src/tui/components/primitives/pickerModal.tsx +47 -0
  59. package/src/tui/components/primitives/scrollbar.tsx +27 -0
  60. package/src/tui/components/{ui → primitives}/toast.tsx +5 -3
  61. package/src/tui/components/statusBar.tsx +32 -0
  62. package/src/tui/components/ui/dialogLayer.tsx +32 -13
  63. package/src/tui/context/ThemeContext.tsx +18 -0
  64. package/src/tui/hooks/useScroll.ts +11 -3
  65. package/src/tui/input/InputBox.tsx +6 -0
  66. package/src/tui/input/InputBoxView.tsx +237 -0
  67. package/src/tui/input/commands.test.ts +51 -0
  68. package/src/tui/input/commands.ts +44 -0
  69. package/src/tui/input/cursor.test.ts +136 -0
  70. package/src/tui/input/cursor.ts +214 -0
  71. package/src/tui/input/dumpContext.ts +107 -0
  72. package/src/tui/input/sanitize.ts +33 -0
  73. package/src/tui/input/useCommandExecutor.ts +32 -0
  74. package/src/tui/input/useInputBox.ts +207 -0
  75. package/src/tui/input/useInputHandler.ts +453 -0
  76. package/src/tui/input/useMentionPicker.ts +121 -0
  77. package/src/tui/input/usePluginShortcuts.ts +29 -0
  78. package/src/tui/plugins/InkApprovalChannel.test.ts +51 -0
  79. package/src/tui/plugins/InkApprovalChannel.ts +30 -0
  80. package/src/tui/{services/uiService.ts → plugins/InkUIService.ts} +68 -35
  81. package/src/tui/renderApp.tsx +43 -0
  82. package/src/tui/theme/index.ts +1 -0
  83. package/src/tui/theme/merge.test.ts +49 -0
  84. package/src/tui/theme/merge.ts +43 -0
  85. package/src/tui/theme/presets.ts +79 -0
  86. package/src/tui/theme/types.ts +116 -0
  87. package/src/utils/clipboard.ts +97 -0
  88. package/src/utils/diff.test.ts +56 -0
  89. package/src/cli.ts +0 -96
  90. package/src/clipboard.ts +0 -62
  91. package/src/config.ts +0 -116
  92. package/src/main.tsx +0 -147
  93. package/src/project.ts +0 -32
  94. package/src/session.ts +0 -95
  95. package/src/tui/commands.ts +0 -33
  96. package/src/tui/components/chatLayout.tsx +0 -192
  97. package/src/tui/components/inputBox.tsx +0 -153
  98. package/src/tui/hooks/useInputHandler.ts +0 -268
  99. package/src/tui/useChat.ts +0 -52
  100. package/src/tui/useChatSession.ts +0 -155
  101. package/src/tui/useChatUI.ts +0 -51
  102. package/tsconfig.json +0 -10
  103. /package/src/{subcommands.ts → cli/subcommands.ts} +0 -0
  104. /package/src/{diff.ts → utils/diff.ts} +0 -0
@@ -0,0 +1,453 @@
1
+ import { type Key, useInput, useStdin } from 'ink';
2
+ import type { ShortcutHandler } from 'mu-core';
3
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
4
+ import { matchCommands, type SlashCommand } from './commands';
5
+ import {
6
+ type BufferState,
7
+ cursorRowCol,
8
+ deleteBackward,
9
+ deleteForward,
10
+ deleteWordBackward,
11
+ insertAt,
12
+ killToLineEnd,
13
+ killToLineStart,
14
+ moveLeft,
15
+ moveLineDown,
16
+ moveLineEnd,
17
+ moveLineHome,
18
+ moveLineUp,
19
+ moveRight,
20
+ moveWordLeft,
21
+ moveWordRight,
22
+ } from './cursor';
23
+ import { isMouseSequence, sanitizeTerminalInput } from './sanitize';
24
+
25
+ const BACKSPACE_BYTES = new Set(['\x7f', '\x08']);
26
+
27
+ export interface InputActions {
28
+ onCtrlC?: () => void;
29
+ onPaste?: () => void;
30
+ onNew?: () => void;
31
+ onCycleModel?: () => void;
32
+ onTogglePicker?: () => void;
33
+ onToggleSessionPicker?: () => void;
34
+ onShowContext?: () => void;
35
+ onEsc?: () => void;
36
+ onScrollUp?: () => void;
37
+ onScrollDown?: () => void;
38
+ modelCount?: number;
39
+ }
40
+
41
+ interface InputState {
42
+ value: string;
43
+ cursor: number;
44
+ commands: SlashCommand[];
45
+ cmdIndex: number;
46
+ isCommandMode: boolean;
47
+ }
48
+
49
+ /**
50
+ * Optional mention-picker controls. When `active`, navigation keys (↑/↓) and
51
+ * accept keys (Tab / Enter) are routed through this handle instead of the
52
+ * default editing bindings. Read via a ref so the dispatch closure always
53
+ * sees the latest snapshot without forcing a hook re-call.
54
+ */
55
+ export interface MentionMode {
56
+ active: boolean;
57
+ count: number;
58
+ selectedIndex: number;
59
+ next: () => void;
60
+ prev: () => void;
61
+ accept: () => void;
62
+ }
63
+
64
+ interface UseInputHandlerOptions {
65
+ isActive: boolean;
66
+ streaming: boolean;
67
+ history: string[];
68
+ actions: InputActions;
69
+ onSubmit: (text: string) => void;
70
+ availableCommands: SlashCommand[];
71
+ onCommand: (command: SlashCommand, args: string) => void;
72
+ /**
73
+ * Plugin-registered keyboard shortcuts. Consulted before the built-in
74
+ * BINDINGS table; whenever a handler is registered for the pressed key id
75
+ * the default editor binding is skipped entirely. Handlers are fire-and-
76
+ * forget so the input loop never blocks on plugin work.
77
+ */
78
+ pluginShortcuts?: Map<string, ShortcutHandler>;
79
+ /**
80
+ * Ref to the current mention-mode controls. The picker state is computed
81
+ * by the caller (which depends on `value`/`cursor` from this hook) and
82
+ * pushed into the ref every render; the dispatch closure reads it at key
83
+ * time. Avoids calling `useInputHandler` twice to break the dependency.
84
+ */
85
+ mentionRef?: React.RefObject<MentionMode | null>;
86
+ }
87
+
88
+ // Build a stable key identifier from an Ink key event. The id is a flat
89
+ // string so the BINDINGS map can be a plain dictionary and adding a new
90
+ // shortcut means adding one line. Split into two helpers to keep cognitive
91
+ // complexity within Biome's threshold.
92
+ function modifierKeyId(input: string, key: Key): string | null {
93
+ if (key.ctrl && key.shift && input) return `ctrl+shift+${input}`;
94
+ if (key.ctrl && key.leftArrow) return 'ctrl+left';
95
+ if (key.ctrl && key.rightArrow) return 'ctrl+right';
96
+ if (key.ctrl && input) return `ctrl+${input}`;
97
+ if (key.meta && key.leftArrow) return 'alt+left';
98
+ if (key.meta && key.rightArrow) return 'alt+right';
99
+ return null;
100
+ }
101
+
102
+ const DIRECT_KEYS: ReadonlyArray<readonly [keyof Key, string]> = [
103
+ ['escape', 'escape'],
104
+ ['pageUp', 'pageup'],
105
+ ['pageDown', 'pagedown'],
106
+ ['tab', 'tab'],
107
+ ['upArrow', 'up'],
108
+ ['downArrow', 'down'],
109
+ ['leftArrow', 'left'],
110
+ ['rightArrow', 'right'],
111
+ ['home', 'home'],
112
+ ['end', 'end'],
113
+ ['delete', 'delete'],
114
+ ['backspace', 'backspace'],
115
+ ];
116
+
117
+ function keyId(input: string, key: Key): string | null {
118
+ const mod = modifierKeyId(input, key);
119
+ if (mod) return mod;
120
+ if (key.return) return key.shift ? 'shift+return' : 'return';
121
+ for (const [flag, id] of DIRECT_KEYS) {
122
+ if (key[flag]) return id;
123
+ }
124
+ return null;
125
+ }
126
+
127
+ function useHistoryNavigation(state: BufferState, history: string[]) {
128
+ const idx = useRef(-1);
129
+ const draft = useRef('');
130
+
131
+ const up = (): string | null => {
132
+ if (!history.length) return null;
133
+ if (idx.current === -1) {
134
+ draft.current = state.value;
135
+ idx.current = history.length - 1;
136
+ } else if (idx.current > 0) {
137
+ idx.current -= 1;
138
+ }
139
+ return history[idx.current] ?? null;
140
+ };
141
+
142
+ const down = (): string | null => {
143
+ if (idx.current === -1) return null;
144
+ if (idx.current < history.length - 1) {
145
+ idx.current += 1;
146
+ return history[idx.current] ?? null;
147
+ }
148
+ idx.current = -1;
149
+ return draft.current;
150
+ };
151
+
152
+ return { up, down, reset: () => (idx.current = -1) };
153
+ }
154
+
155
+ /**
156
+ * Some terminals (and Ink versions) deliver `\x7f` / `\x08` as raw stdin
157
+ * bytes without firing `useInput`'s `key.backspace`. We listen at the raw
158
+ * level and let the React handler consume the synthetic flag.
159
+ */
160
+ function useRawBackspace(isActive: boolean, onBackspace: () => void) {
161
+ const { stdin } = useStdin();
162
+ const handledRef = useRef(false);
163
+ const callbackRef = useRef(onBackspace);
164
+ callbackRef.current = onBackspace;
165
+
166
+ useEffect(() => {
167
+ if (!(stdin && isActive)) return;
168
+ const onData = (data: Buffer) => {
169
+ if (BACKSPACE_BYTES.has(data.toString())) {
170
+ handledRef.current = true;
171
+ callbackRef.current();
172
+ }
173
+ };
174
+ stdin.on('data', onData);
175
+ return () => {
176
+ stdin.off('data', onData);
177
+ };
178
+ }, [stdin, isActive]);
179
+
180
+ return handledRef;
181
+ }
182
+
183
+ interface BindingCtx {
184
+ state: BufferState;
185
+ setState: React.Dispatch<React.SetStateAction<BufferState>>;
186
+ setCmdIndex: React.Dispatch<React.SetStateAction<number>>;
187
+ desiredColumn: React.MutableRefObject<number | null>;
188
+ nav: ReturnType<typeof useHistoryNavigation>;
189
+ submit: () => void;
190
+ isCommandMode: boolean;
191
+ commands: SlashCommand[];
192
+ actions: InputActions;
193
+ mentionRef?: React.RefObject<MentionMode | null>;
194
+ }
195
+
196
+ function getMention(c: BindingCtx): MentionMode | null {
197
+ return c.mentionRef?.current ?? null;
198
+ }
199
+
200
+ type Binding = (ctx: BindingCtx) => void;
201
+
202
+ // ─── Vertical movement: routed through history when at edges ─────────────────
203
+ //
204
+ // Pressing ↑ on the first row of a multi-line buffer (or single-line) goes to
205
+ // history. Pressing ↑ further up inside the buffer just moves the cursor.
206
+ // Mirroring fish/zsh's behaviour. Same for ↓ on the last row.
207
+
208
+ function handleUp(c: BindingCtx): void {
209
+ const m = getMention(c);
210
+ if (m?.active && m.count > 0) {
211
+ m.prev();
212
+ return;
213
+ }
214
+ if (c.isCommandMode) {
215
+ c.setCmdIndex((i) => (i > 0 ? i - 1 : c.commands.length - 1));
216
+ return;
217
+ }
218
+ const { row, col } = cursorRowCol(c.state.value, c.state.cursor);
219
+ if (row > 0) {
220
+ if (c.desiredColumn.current === null) c.desiredColumn.current = col;
221
+ const next = moveLineUp(c.state, c.desiredColumn.current);
222
+ if (next) c.setState(next);
223
+ return;
224
+ }
225
+ c.desiredColumn.current = null;
226
+ const r = c.nav.up();
227
+ if (r !== null) c.setState({ value: r, cursor: r.length });
228
+ }
229
+
230
+ function handleDown(c: BindingCtx): void {
231
+ const m = getMention(c);
232
+ if (m?.active && m.count > 0) {
233
+ m.next();
234
+ return;
235
+ }
236
+ if (c.isCommandMode) {
237
+ c.setCmdIndex((i) => (i < c.commands.length - 1 ? i + 1 : 0));
238
+ return;
239
+ }
240
+ const { row, col } = cursorRowCol(c.state.value, c.state.cursor);
241
+ const total = c.state.value.split('\n').length;
242
+ if (row < total - 1) {
243
+ if (c.desiredColumn.current === null) c.desiredColumn.current = col;
244
+ const next = moveLineDown(c.state, c.desiredColumn.current);
245
+ if (next) c.setState(next);
246
+ return;
247
+ }
248
+ c.desiredColumn.current = null;
249
+ const r = c.nav.down();
250
+ if (r !== null) c.setState({ value: r, cursor: r.length });
251
+ }
252
+
253
+ function handleTab(c: BindingCtx): void {
254
+ const m = getMention(c);
255
+ if (m?.active && m.count > 0) {
256
+ m.accept();
257
+ return;
258
+ }
259
+ c.setState((s) => insertAt(s, ' '));
260
+ }
261
+
262
+ function handleReturn(c: BindingCtx): void {
263
+ const m = getMention(c);
264
+ if (m?.active && m.count > 0) {
265
+ m.accept();
266
+ return;
267
+ }
268
+ c.submit();
269
+ }
270
+
271
+ // ─── Bindings ────────────────────────────────────────────────────────────────
272
+
273
+ const BINDINGS: Record<string, Binding> = {
274
+ 'ctrl+c': (c) => c.actions.onCtrlC?.(),
275
+ 'ctrl+v': (c) => c.actions.onPaste?.(),
276
+ 'ctrl+o': (c) => c.actions.onTogglePicker?.(),
277
+ 'ctrl+s': (c) => c.submit(),
278
+ 'ctrl+j': (c) => c.setState((s) => insertAt(s, '\n')),
279
+ 'ctrl+a': (c) => c.setState((s) => moveLineHome(s)),
280
+ 'ctrl+e': (c) => c.setState((s) => moveLineEnd(s)),
281
+ 'ctrl+w': (c) => c.setState((s) => deleteWordBackward(s)),
282
+ 'ctrl+u': (c) => c.setState((s) => killToLineStart(s)),
283
+ 'ctrl+k': (c) => c.setState((s) => killToLineEnd(s)),
284
+ 'ctrl+left': (c) => c.setState((s) => moveWordLeft(s)),
285
+ 'ctrl+right': (c) => c.setState((s) => moveWordRight(s)),
286
+ 'alt+left': (c) => c.setState((s) => moveWordLeft(s)),
287
+ 'alt+right': (c) => c.setState((s) => moveWordRight(s)),
288
+ 'ctrl+m': (c) => {
289
+ if (c.actions.modelCount) c.actions.onCycleModel?.();
290
+ },
291
+ 'ctrl+n': (c) => {
292
+ c.actions.onNew?.();
293
+ c.setState({ value: '', cursor: 0 });
294
+ c.nav.reset();
295
+ },
296
+ escape: (c) => c.actions.onEsc?.(),
297
+ pageup: (c) => c.actions.onScrollUp?.(),
298
+ pagedown: (c) => c.actions.onScrollDown?.(),
299
+ 'shift+return': (c) => c.setState((s) => insertAt(s, '\n')),
300
+ return: handleReturn,
301
+ tab: handleTab,
302
+ up: handleUp,
303
+ down: handleDown,
304
+ left: (c) => c.setState((s) => moveLeft(s)),
305
+ right: (c) => c.setState((s) => moveRight(s)),
306
+ home: (c) => c.setState((s) => moveLineHome(s)),
307
+ end: (c) => c.setState((s) => moveLineEnd(s)),
308
+ delete: (c) => {
309
+ c.setState((s) => deleteForward(s));
310
+ c.nav.reset();
311
+ },
312
+ };
313
+
314
+ // Keys that shouldn't reset the sticky vertical column. Anything else
315
+ // (typing, deleting, switching lines explicitly) drops the sticky column.
316
+ const COLUMN_PRESERVING = new Set(['up', 'down']);
317
+
318
+ function applyBackspace(c: BindingCtx): void {
319
+ c.setState((s) => deleteBackward(s));
320
+ c.nav.reset();
321
+ }
322
+
323
+ function handleInsert(input: string, c: BindingCtx): void {
324
+ if (!input) return;
325
+ const sanitized = sanitizeTerminalInput(input);
326
+ if (!sanitized) return;
327
+ c.setState((s) => insertAt(s, sanitized));
328
+ c.nav.reset();
329
+ }
330
+
331
+ export function useInputHandler(
332
+ options: UseInputHandlerOptions,
333
+ ): InputState & { setBuffer: (value: string, cursor: number) => void } {
334
+ const { isActive, streaming, history, actions, onSubmit, availableCommands, onCommand, pluginShortcuts, mentionRef } =
335
+ options;
336
+ const [state, setState] = useState<BufferState>({ value: '', cursor: 0 });
337
+ const [cmdIndex, setCmdIndex] = useState(0);
338
+ const desiredColumn = useRef<number | null>(null);
339
+ const nav = useHistoryNavigation(state, history);
340
+ // Keep the latest map in a ref so the dispatchKey closure (created once
341
+ // per `useInput` call) always sees the freshest handlers without forcing
342
+ // a re-subscribe.
343
+ const pluginShortcutsRef = useRef(pluginShortcuts);
344
+ pluginShortcutsRef.current = pluginShortcuts;
345
+
346
+ const onRawBackspace = useCallback(() => {
347
+ setState((s) => deleteBackward(s));
348
+ nav.reset();
349
+ }, [nav]);
350
+ const backspaceHandledRef = useRawBackspace(isActive, onRawBackspace);
351
+
352
+ const commands = useMemo(
353
+ () => matchCommands(state.value.trim(), availableCommands),
354
+ [state.value, availableCommands],
355
+ );
356
+ const isCommandMode = commands.length > 0 && state.value.trim().startsWith('/');
357
+
358
+ const submit = useCallback(() => {
359
+ if (streaming) return;
360
+ if (isCommandMode) {
361
+ const cmd = commands[cmdIndex];
362
+ if (cmd) {
363
+ const args = state.value.trim().slice(cmd.name.length).trim();
364
+ setState({ value: '', cursor: 0 });
365
+ onCommand(cmd, args);
366
+ }
367
+ return;
368
+ }
369
+ if (!state.value.trim()) return;
370
+ onSubmit(state.value);
371
+ setState({ value: '', cursor: 0 });
372
+ nav.reset();
373
+ }, [streaming, isCommandMode, commands, cmdIndex, state.value, onCommand, onSubmit, nav]);
374
+
375
+ useInput(
376
+ dispatchKey({
377
+ state,
378
+ setState,
379
+ setCmdIndex,
380
+ desiredColumn,
381
+ nav,
382
+ submit,
383
+ isCommandMode,
384
+ commands,
385
+ actions,
386
+ mentionRef,
387
+ backspaceHandledRef,
388
+ pluginShortcutsRef,
389
+ }),
390
+ { isActive },
391
+ );
392
+
393
+ const setBuffer = useCallback(
394
+ (value: string, cursor: number) => {
395
+ setState({ value, cursor });
396
+ nav.reset();
397
+ },
398
+ [nav],
399
+ );
400
+
401
+ return { value: state.value, cursor: state.cursor, commands, cmdIndex, isCommandMode, setBuffer };
402
+ }
403
+
404
+ interface DispatchOptions extends BindingCtx {
405
+ backspaceHandledRef: React.MutableRefObject<boolean>;
406
+ pluginShortcutsRef: React.MutableRefObject<Map<string, ShortcutHandler> | undefined>;
407
+ }
408
+
409
+ /**
410
+ * Try to dispatch a key id to a plugin-registered handler. Returns `true` when
411
+ * the key was claimed (so the default binding shouldn't fire). The async
412
+ * handler is fire-and-forget: plugins typically mutate their own state and
413
+ * surface results via `MessageBus.append`, so we don't need to await here.
414
+ */
415
+ function tryPluginShortcut(id: string, opts: DispatchOptions): boolean {
416
+ const handlers = opts.pluginShortcutsRef.current;
417
+ const handler = handlers?.get(id);
418
+ if (!handler) return false;
419
+ void Promise.resolve(handler()).catch(() => {
420
+ /* swallow handler errors so a misbehaving plugin can't kill the input loop */
421
+ });
422
+ return true;
423
+ }
424
+
425
+ /**
426
+ * Build the key handler for `useInput`. Extracted so the hook body stays
427
+ * under Biome's per-function line cap and so the binding lookup is testable
428
+ * in isolation if we ever need it.
429
+ */
430
+ function dispatchKey(opts: DispatchOptions): (input: string, key: Key) => void {
431
+ return (input, key) => {
432
+ if (isMouseSequence(input)) return;
433
+ const alreadyHandled = opts.backspaceHandledRef.current;
434
+ opts.backspaceHandledRef.current = false;
435
+
436
+ const id = keyId(input, key);
437
+ if (id && !COLUMN_PRESERVING.has(id)) opts.desiredColumn.current = null;
438
+
439
+ if (id === 'backspace') {
440
+ if (!alreadyHandled) applyBackspace(opts);
441
+ else opts.nav.reset();
442
+ return;
443
+ }
444
+ if (id && tryPluginShortcut(id, opts)) {
445
+ return;
446
+ }
447
+ if (id && BINDINGS[id]) {
448
+ BINDINGS[id](opts);
449
+ return;
450
+ }
451
+ handleInsert(input, opts);
452
+ };
453
+ }
@@ -0,0 +1,121 @@
1
+ import type { MentionCompletion, PluginRegistry } from 'mu-core';
2
+ import { useCallback, useEffect, useState } from 'react';
3
+
4
+ export interface MentionPickerState {
5
+ /** Current trigger character (e.g. "@") when the picker is active. */
6
+ trigger: string | null;
7
+ /** Partial text after the trigger (excluding the trigger itself). */
8
+ partial: string;
9
+ /** Suggestions returned by the active provider. Empty array hides the picker. */
10
+ completions: MentionCompletion[];
11
+ /**
12
+ * Cursor offset where the trigger sits in the input. Lets the host replace
13
+ * `[triggerStart, cursor)` when the user accepts a completion.
14
+ */
15
+ triggerStart: number;
16
+ /** 0-based index of the currently highlighted completion. */
17
+ selectedIndex: number;
18
+ setSelectedIndex: (i: number) => void;
19
+ }
20
+
21
+ type BaseState = Omit<MentionPickerState, 'setSelectedIndex' | 'selectedIndex'>;
22
+
23
+ const EMPTY: BaseState = {
24
+ trigger: null,
25
+ partial: '',
26
+ completions: [],
27
+ triggerStart: -1,
28
+ };
29
+
30
+ interface DetectResult {
31
+ trigger: string;
32
+ start: number;
33
+ }
34
+
35
+ /**
36
+ * Detect a `<trigger><partial>` token at the cursor. Triggers are
37
+ * single-character (e.g. `@`) and the partial is anything up to the next
38
+ * whitespace before the cursor. Returns `null` when no trigger is active.
39
+ *
40
+ * Triggers must follow whitespace (or beginning of input) so they don't match
41
+ * inside email addresses.
42
+ */
43
+ function detectTrigger(value: string, cursor: number, triggers: Set<string>): DetectResult | null {
44
+ for (let i = cursor - 1; i >= 0; i--) {
45
+ const ch = value[i];
46
+ if (/\s/.test(ch)) return null;
47
+ if (triggers.has(ch)) {
48
+ const prev = i === 0 ? ' ' : value[i - 1];
49
+ if (!/\s/.test(prev)) return null;
50
+ return { trigger: ch, start: i };
51
+ }
52
+ }
53
+ return null;
54
+ }
55
+
56
+ /**
57
+ * Watch the input and resolve plugin-provided mention completions. Keeps the
58
+ * provider list in sync with `registry.onMentionProvidersChange`.
59
+ */
60
+ export function useMentionPicker(registry: PluginRegistry, value: string, cursor: number): MentionPickerState {
61
+ const [providers, setProviders] = useState(() => registry.getMentionProviders());
62
+ const [base, setBase] = useState<BaseState>(EMPTY);
63
+ const [selectedIndex, setSelectedIndex] = useState(0);
64
+
65
+ useEffect(() => {
66
+ setProviders(registry.getMentionProviders());
67
+ return registry.onMentionProvidersChange(() => setProviders(registry.getMentionProviders()));
68
+ }, [registry]);
69
+
70
+ useEffect(() => {
71
+ if (providers.length === 0) {
72
+ setBase(EMPTY);
73
+ return;
74
+ }
75
+ const triggers = new Set(providers.map((p) => p.trigger));
76
+ const match = detectTrigger(value, cursor, triggers);
77
+ if (!match) {
78
+ setBase(EMPTY);
79
+ return;
80
+ }
81
+ const partial = value.slice(match.start + 1, cursor);
82
+ const provider = providers.find((p) => p.trigger === match.trigger);
83
+ if (!provider) {
84
+ setBase(EMPTY);
85
+ return;
86
+ }
87
+ let cancelled = false;
88
+ Promise.resolve(provider.provider(partial))
89
+ .then((completions) => {
90
+ if (cancelled) return;
91
+ setBase({
92
+ trigger: match.trigger,
93
+ partial,
94
+ completions,
95
+ triggerStart: match.start,
96
+ });
97
+ })
98
+ .catch(() => {
99
+ if (!cancelled) setBase(EMPTY);
100
+ });
101
+ return () => {
102
+ cancelled = true;
103
+ };
104
+ }, [providers, value, cursor]);
105
+
106
+ // Reset highlight whenever the active partial / completion list changes so
107
+ // the cursor tracks the visible options. Depending on `completions.length`
108
+ // (rather than the array reference) keeps the highlight stable when the
109
+ // provider returns equivalent results twice while still re-anchoring on a
110
+ // genuine list change.
111
+ // biome-ignore lint/correctness/useExhaustiveDependencies: trigger reset is intentional
112
+ useEffect(() => {
113
+ setSelectedIndex(0);
114
+ }, [base.partial, base.completions.length, base.trigger]);
115
+
116
+ const setIndex = useCallback((i: number) => {
117
+ setSelectedIndex(i);
118
+ }, []);
119
+
120
+ return { ...base, selectedIndex, setSelectedIndex: setIndex };
121
+ }
@@ -0,0 +1,29 @@
1
+ import type { PluginRegistry, ShortcutHandler } from 'mu-core';
2
+ import { useEffect, useState } from 'react';
3
+
4
+ interface PluginShortcuts {
5
+ /** Map of `keyId` (e.g. "tab", "ctrl+t") to plugin handler. */
6
+ handlers: Map<string, ShortcutHandler>;
7
+ }
8
+
9
+ /**
10
+ * Subscribe to the registry's shortcut bindings and expose a stable map keyed
11
+ * by keyId. Multiple registrations on the same key are last-write-wins; the
12
+ * agent plugin is expected to grab Tab and unregister cleanly on deactivation.
13
+ */
14
+ export function usePluginShortcuts(registry: PluginRegistry): PluginShortcuts {
15
+ const [handlers, setHandlers] = useState<Map<string, ShortcutHandler>>(() => buildMap(registry));
16
+ useEffect(() => {
17
+ setHandlers(buildMap(registry));
18
+ return registry.onShortcutsChange(() => setHandlers(buildMap(registry)));
19
+ }, [registry]);
20
+ return { handlers };
21
+ }
22
+
23
+ function buildMap(registry: PluginRegistry): Map<string, ShortcutHandler> {
24
+ const out = new Map<string, ShortcutHandler>();
25
+ for (const entry of registry.getShortcuts()) {
26
+ out.set(entry.key.toLowerCase(), entry.handler);
27
+ }
28
+ return out;
29
+ }
@@ -0,0 +1,51 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import type { ApprovalRequest } from 'mu-agents';
3
+ import { createInkApprovalChannel } from './InkApprovalChannel';
4
+ import { InkUIService } from './InkUIService';
5
+
6
+ function fakeRequest(extra?: Partial<ApprovalRequest>): ApprovalRequest {
7
+ return {
8
+ id: 'r1',
9
+ token: 't1',
10
+ agentId: 'build',
11
+ toolName: 'bash',
12
+ toolArgs: { cmd: 'echo hi' },
13
+ channelId: 'tui',
14
+ createdAt: 0,
15
+ status: 'pending',
16
+ ...extra,
17
+ };
18
+ }
19
+
20
+ describe('InkApprovalChannel', () => {
21
+ it('returns approved when user confirms', async () => {
22
+ const ui = new InkUIService();
23
+ const channel = createInkApprovalChannel(ui);
24
+ const promise = channel.sendApprovalRequest(fakeRequest());
25
+ // Resolve the dialog with `true` (approve).
26
+ await new Promise((r) => setTimeout(r, 0));
27
+ ui.resolveDialog(true);
28
+ expect(await promise).toBe('approved');
29
+ });
30
+
31
+ it('returns denied when user declines', async () => {
32
+ const ui = new InkUIService();
33
+ const channel = createInkApprovalChannel(ui);
34
+ const promise = channel.sendApprovalRequest(fakeRequest());
35
+ await new Promise((r) => setTimeout(r, 0));
36
+ ui.resolveDialog(false);
37
+ expect(await promise).toBe('denied');
38
+ });
39
+
40
+ it('serialises tool args into the dialog message', async () => {
41
+ const ui = new InkUIService();
42
+ const channel = createInkApprovalChannel(ui);
43
+ const promise = channel.sendApprovalRequest(fakeRequest({ toolArgs: { path: 'src/x.ts' } }));
44
+ await new Promise((r) => setTimeout(r, 0));
45
+ const dialog = ui.currentDialog();
46
+ expect(dialog?.title).toBe('Run `bash`?');
47
+ expect(dialog?.message).toContain('src/x.ts');
48
+ ui.resolveDialog(true);
49
+ await promise;
50
+ });
51
+ });
@@ -0,0 +1,30 @@
1
+ /**
2
+ * InkApprovalChannel — bridges the ApprovalGateway to the Ink confirm
3
+ * dialog. Returns the user's choice synchronously (no token round-trip
4
+ * through HTTP / Telegram); the gateway honours that immediate result.
5
+ */
6
+
7
+ import type { ApprovalChannel, ApprovalRequest, ApprovalResult } from 'mu-agents';
8
+ import type { InkUIService } from './InkUIService';
9
+
10
+ function formatArgs(args: unknown): string {
11
+ if (args === null || args === undefined) return '';
12
+ if (typeof args === 'string') return args;
13
+ try {
14
+ const json = JSON.stringify(args, null, 2);
15
+ return json.length > 800 ? `${json.slice(0, 800)}…` : json;
16
+ } catch {
17
+ return String(args);
18
+ }
19
+ }
20
+
21
+ export function createInkApprovalChannel(ui: InkUIService): ApprovalChannel {
22
+ return {
23
+ async sendApprovalRequest(req: ApprovalRequest): Promise<ApprovalResult | undefined> {
24
+ const title = `Run \`${req.toolName}\`?`;
25
+ const message = formatArgs(req.toolArgs);
26
+ const ok = await ui.confirm(title, message);
27
+ return ok ? 'approved' : 'denied';
28
+ },
29
+ };
30
+ }