mu-coding 0.13.0 → 0.16.1

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 (118) hide show
  1. package/README.md +9 -123
  2. package/bin/coding-agent.ts +95 -0
  3. package/package.json +10 -21
  4. package/src/config.ts +122 -0
  5. package/src/harness.test.ts +159 -0
  6. package/src/main.ts +53 -3
  7. package/src/plugins.ts +49 -0
  8. package/src/systemPrompt.ts +22 -0
  9. package/src/ui/ChatApp.ts +959 -0
  10. package/src/ui/commands.ts +35 -0
  11. package/src/ui/editor.ts +166 -0
  12. package/src/ui/markdown.ts +363 -0
  13. package/src/ui/picker.ts +126 -0
  14. package/src/ui/status.ts +61 -0
  15. package/src/ui/theme.ts +241 -0
  16. package/src/ui/transcript.test.ts +121 -0
  17. package/src/ui/transcript.ts +399 -0
  18. package/tsconfig.json +8 -0
  19. package/bin/mu.js +0 -2
  20. package/prompts/SYSTEM.md +0 -16
  21. package/src/app/shutdown.ts +0 -94
  22. package/src/app/startApp.ts +0 -49
  23. package/src/cli/args.ts +0 -133
  24. package/src/cli/install.ts +0 -107
  25. package/src/cli/subcommands.ts +0 -29
  26. package/src/cli/update.ts +0 -205
  27. package/src/config/index.test.ts +0 -77
  28. package/src/config/index.ts +0 -199
  29. package/src/plugin.ts +0 -124
  30. package/src/runtime/codingTools/bash.ts +0 -114
  31. package/src/runtime/codingTools/edit-file.ts +0 -60
  32. package/src/runtime/codingTools/index.ts +0 -39
  33. package/src/runtime/codingTools/read-file.ts +0 -83
  34. package/src/runtime/codingTools/utils.ts +0 -21
  35. package/src/runtime/codingTools/write-file.ts +0 -42
  36. package/src/runtime/createRegistry.test.ts +0 -147
  37. package/src/runtime/createRegistry.ts +0 -195
  38. package/src/runtime/fileMentionProvider.ts +0 -117
  39. package/src/runtime/messageBus.test.ts +0 -62
  40. package/src/runtime/messageBus.ts +0 -78
  41. package/src/runtime/pluginLoader.ts +0 -153
  42. package/src/runtime/startupUpdateCheck.ts +0 -163
  43. package/src/runtime/updateCheck.ts +0 -136
  44. package/src/sessions/index.test.ts +0 -66
  45. package/src/sessions/index.ts +0 -183
  46. package/src/sessions/peek.test.ts +0 -88
  47. package/src/sessions/project.ts +0 -51
  48. package/src/tui/channel/tuiChannel.test.ts +0 -107
  49. package/src/tui/channel/tuiChannel.ts +0 -62
  50. package/src/tui/chat/ChatContext.ts +0 -10
  51. package/src/tui/chat/MessageRendererContext.ts +0 -44
  52. package/src/tui/chat/ToolDisplayContext.ts +0 -33
  53. package/src/tui/chat/useAbort.ts +0 -85
  54. package/src/tui/chat/useAttachment.ts +0 -74
  55. package/src/tui/chat/useChat.ts +0 -113
  56. package/src/tui/chat/useChatPanel.ts +0 -119
  57. package/src/tui/chat/useChatSession.ts +0 -382
  58. package/src/tui/chat/useModels.ts +0 -83
  59. package/src/tui/chat/usePluginStatus.ts +0 -44
  60. package/src/tui/chat/useSessionPersistence.ts +0 -84
  61. package/src/tui/chat/useStatusSegments.ts +0 -82
  62. package/src/tui/chat/useSubagentBrowser.ts +0 -133
  63. package/src/tui/components/chat/ChatPanel.tsx +0 -54
  64. package/src/tui/components/chat/ChatPanelBody.tsx +0 -86
  65. package/src/tui/components/chat/Pickers.tsx +0 -44
  66. package/src/tui/components/chat/SubagentBrowserPanel.tsx +0 -145
  67. package/src/tui/components/messageView.tsx +0 -72
  68. package/src/tui/components/messages/EditOutput.tsx +0 -112
  69. package/src/tui/components/messages/ReadOutput.tsx +0 -48
  70. package/src/tui/components/messages/ToolHeader.tsx +0 -30
  71. package/src/tui/components/messages/WebFetchOutput.tsx +0 -30
  72. package/src/tui/components/messages/WriteOutput.tsx +0 -64
  73. package/src/tui/components/messages/assistantMessage.tsx +0 -72
  74. package/src/tui/components/messages/markdown.tsx +0 -407
  75. package/src/tui/components/messages/messageItem.tsx +0 -43
  76. package/src/tui/components/messages/reasoningBlock.tsx +0 -18
  77. package/src/tui/components/messages/streamingOutput.tsx +0 -18
  78. package/src/tui/components/messages/toolCallBlock.tsx +0 -125
  79. package/src/tui/components/messages/userMessage.tsx +0 -44
  80. package/src/tui/components/primitives/dropdown.tsx +0 -125
  81. package/src/tui/components/primitives/modal.tsx +0 -47
  82. package/src/tui/components/primitives/pickerModal.tsx +0 -47
  83. package/src/tui/components/primitives/scrollbar.tsx +0 -27
  84. package/src/tui/components/primitives/toast.tsx +0 -100
  85. package/src/tui/components/statusBar.tsx +0 -41
  86. package/src/tui/components/ui/dialogLayer.tsx +0 -175
  87. package/src/tui/context/ThemeContext.tsx +0 -18
  88. package/src/tui/hooks/useChordKeyboard.ts +0 -87
  89. package/src/tui/hooks/useInputInfoSegments.ts +0 -22
  90. package/src/tui/hooks/useScroll.ts +0 -64
  91. package/src/tui/hooks/useTerminal.ts +0 -40
  92. package/src/tui/hooks/useUI.ts +0 -15
  93. package/src/tui/input/InputBox.tsx +0 -6
  94. package/src/tui/input/InputBoxView.tsx +0 -293
  95. package/src/tui/input/commands.test.ts +0 -71
  96. package/src/tui/input/commands.ts +0 -55
  97. package/src/tui/input/cursor.test.ts +0 -136
  98. package/src/tui/input/cursor.ts +0 -214
  99. package/src/tui/input/dumpContext.ts +0 -107
  100. package/src/tui/input/sanitize.ts +0 -33
  101. package/src/tui/input/useCommandExecutor.ts +0 -32
  102. package/src/tui/input/useInputBox.ts +0 -265
  103. package/src/tui/input/useInputHandler.ts +0 -455
  104. package/src/tui/input/useMentionPicker.ts +0 -133
  105. package/src/tui/input/usePluginShortcuts.ts +0 -29
  106. package/src/tui/plugins/InkApprovalChannel.test.ts +0 -51
  107. package/src/tui/plugins/InkApprovalChannel.ts +0 -30
  108. package/src/tui/plugins/InkUIService.ts +0 -188
  109. package/src/tui/renderApp.tsx +0 -64
  110. package/src/tui/theme/index.ts +0 -1
  111. package/src/tui/theme/merge.test.ts +0 -49
  112. package/src/tui/theme/merge.ts +0 -43
  113. package/src/tui/theme/presets.ts +0 -90
  114. package/src/tui/theme/types.ts +0 -138
  115. package/src/tui/update/runUpdateInTui.ts +0 -127
  116. package/src/utils/clipboard.ts +0 -97
  117. package/src/utils/diff.test.ts +0 -56
  118. package/src/utils/diff.ts +0 -81
@@ -1,119 +0,0 @@
1
- import { type DOMElement as InkDOMElement, useInput } from 'ink';
2
- import type { SubagentRunRegistry } from 'mu-agents';
3
- import type { ChatMessage, PluginRegistry, ProviderConfig } from 'mu-core';
4
- import { useEffect, useMemo, useRef } from 'react';
5
- import type { ShutdownFn } from '../../app/shutdown';
6
- import type { SessionPathHolder } from '../../runtime/createRegistry';
7
- import type { HostMessageBus } from '../../runtime/messageBus';
8
- import type { ChatPanelBodyProps } from '../components/chat/ChatPanelBody';
9
- import { useToast } from '../components/primitives/toast';
10
- import { useScroll } from '../hooks/useScroll';
11
- import { useMeasure, useTerminalSize } from '../hooks/useTerminal';
12
- import type { InkUIService, ToastRequest } from '../plugins/InkUIService';
13
- import { useChat } from './useChat';
14
- import { usePluginStatus } from './usePluginStatus';
15
- import { useStatusSegments } from './useStatusSegments';
16
- import { type SubagentBrowserState, useSubagentBrowser } from './useSubagentBrowser';
17
-
18
- const TOAST_LEVEL_COLORS: Record<string, string> = {
19
- info: 'cyan',
20
- success: 'green',
21
- warning: 'yellow',
22
- error: 'red',
23
- };
24
-
25
- interface UseChatPanelOptions {
26
- config: ProviderConfig;
27
- initialMessages?: ChatMessage[];
28
- registry: PluginRegistry;
29
- messageBus?: HostMessageBus;
30
- uiService?: InkUIService;
31
- shutdown?: ShutdownFn;
32
- sessionPathHolder?: SessionPathHolder;
33
- subagentRuns?: SubagentRunRegistry;
34
- }
35
-
36
- export function useChatPanel(options: UseChatPanelOptions) {
37
- const { config, initialMessages, registry, messageBus, uiService, shutdown, sessionPathHolder, subagentRuns } =
38
- options;
39
- const ctx = useChat(
40
- config,
41
- registry,
42
- initialMessages,
43
- shutdown,
44
- uiService,
45
- messageBus,
46
- sessionPathHolder,
47
- subagentRuns,
48
- );
49
- const browser = useSubagentBrowser(subagentRuns);
50
- const { width, height } = useTerminalSize();
51
- const viewRef = useRef<InkDOMElement>(null);
52
- const contentRef = useRef<InkDOMElement>(null);
53
- // The composite key only needs to change when content visible to the layout
54
- // shifts: number of messages or active stream length. Mapping over every
55
- // message's content per render was O(n) wasted work.
56
- const measureKey = useMemo(
57
- () =>
58
- [ctx.session.messages.length, ctx.session.stream.text.length, ctx.session.stream.reasoning?.length ?? 0].join(
59
- '|',
60
- ),
61
- [ctx.session.messages.length, ctx.session.stream.text.length, ctx.session.stream.reasoning?.length],
62
- );
63
- const { viewHeight, contentHeight } = useMeasure(viewRef, contentRef, measureKey);
64
- const { scrollOffset, onScrollUp, onScrollDown } = useScroll(contentHeight, viewHeight);
65
- const anyModalOpen = ctx.toggles.showModelPicker || ctx.toggles.showSessionPicker;
66
- const pluginStatus = usePluginStatus(registry, uiService);
67
- const { toasts, show, dismiss } = useToast();
68
-
69
- useInput((input, key) => key.ctrl && input === 'c' && ctx.abort.onCtrlC(), { isActive: anyModalOpen });
70
-
71
- useEffect(() => {
72
- if (!uiService) return;
73
- return uiService.onToast((toast: ToastRequest) => {
74
- show(toast.message, TOAST_LEVEL_COLORS[toast.level] ?? 'white');
75
- });
76
- }, [uiService, show]);
77
-
78
- const contextLimit = ctx.models.models.find((m) => m.id === ctx.models.currentModel)?.contextLimit;
79
- const statusSegments = useStatusSegments({
80
- streaming: ctx.session.streaming,
81
- abortWarning: ctx.abort.abortWarning,
82
- quitWarning: ctx.abort.quitWarning,
83
- error: ctx.session.error,
84
- modelError: ctx.models.modelError,
85
- totalTokens: ctx.session.stream.totalTokens,
86
- cachedTokens: ctx.session.stream.cachedTokens,
87
- contextLimit,
88
- pluginStatus,
89
- });
90
-
91
- const bodyProps: ChatPanelBodyProps = {
92
- width,
93
- height,
94
- viewRef,
95
- contentRef,
96
- scrollOffset,
97
- viewHeight,
98
- contentHeight,
99
- isActive: !anyModalOpen && browser.mode.kind === 'chat',
100
- onScrollUp,
101
- onScrollDown,
102
- uiService,
103
- messages: ctx.session.messages,
104
- streaming: ctx.session.streaming,
105
- stream: ctx.session.stream,
106
- error: ctx.session.error,
107
- onSubmit: ctx.session.onSend,
108
- model: ctx.models.currentModel,
109
- history: ctx.session.inputHistory,
110
- statusSegments,
111
- toasts,
112
- onDismissToast: dismiss,
113
- browser,
114
- };
115
-
116
- return { ctx, bodyProps };
117
- }
118
-
119
- export type { SubagentBrowserState };
@@ -1,382 +0,0 @@
1
- import type { ChatMessage, ProviderConfig, Session } from 'mu-core';
2
- import { type PluginRegistry, runDecorateMessageHooks, runTransformUserInputHooks } from 'mu-core';
3
- import { useCallback, useEffect, useRef, useState } from 'react';
4
- import type { SessionPathHolder } from '../../runtime/createRegistry';
5
- import type { HostMessageBus } from '../../runtime/messageBus';
6
- import type { AttachmentState } from './useAttachment';
7
- import { useSessionPersistence } from './useSessionPersistence';
8
-
9
- export interface StreamState {
10
- text: string;
11
- reasoning: string;
12
- totalTokens: number;
13
- cachedTokens: number;
14
- }
15
-
16
- const EMPTY_STREAM: StreamState = { text: '', reasoning: '', totalTokens: 0, cachedTokens: 0 };
17
-
18
- export interface ChatSessionState {
19
- messages: ChatMessage[];
20
- streaming: boolean;
21
- error: string | null;
22
- stream: StreamState;
23
- inputHistory: string[];
24
- onSend: (text: string) => Promise<void>;
25
- onNew: () => void;
26
- onLoadSession: (path: string) => void;
27
- /**
28
- * Compact the current transcript: ask the model to summarize the entire
29
- * conversation, then replace the transcript with `[user marker, assistant
30
- * summary]`. Frees context while keeping intent + key decisions in scope.
31
- */
32
- onCompact: () => Promise<void>;
33
- }
34
-
35
- interface SessionDeps {
36
- /**
37
- * mu-core Session instance owned by the host. Authoritative for the
38
- * transcript — this hook only mirrors it into React state and writes
39
- * persistence on each message_changed event.
40
- */
41
- session: Session;
42
- /** Provider config used as `runTurn` override (model lookup happens here). */
43
- config: ProviderConfig;
44
- /** Currently selected model id (may shift across sends). */
45
- currentModel: string;
46
- attachment: AttachmentState;
47
- controllerRef: React.RefObject<AbortController | null>;
48
- initialMessages?: ChatMessage[];
49
- registry: PluginRegistry;
50
- messageBus?: HostMessageBus;
51
- sessionPathHolder?: SessionPathHolder;
52
- }
53
-
54
- /**
55
- * Wire the host MessageBus to the Session: bus.append flows through
56
- * `session.appendSynthetic` so every subscriber (TUI, broadcaster) sees the
57
- * same change. `bus.get()` mirrors the live transcript.
58
- */
59
- function useMessageBusWiring(messageBus: HostMessageBus | undefined, messages: ChatMessage[], session: Session): void {
60
- useEffect(() => {
61
- messageBus?.setMessages(messages);
62
- }, [messageBus, messages]);
63
-
64
- useEffect(() => {
65
- if (!messageBus) return;
66
- messageBus.setAppender((message) => {
67
- session.appendSynthetic(message);
68
- });
69
- return () => {
70
- messageBus.setAppender(null);
71
- };
72
- }, [messageBus, session]);
73
- }
74
-
75
- interface SubscriptionDeps {
76
- session: Session;
77
- setMessages: React.Dispatch<React.SetStateAction<ChatMessage[]>>;
78
- setStream: React.Dispatch<React.SetStateAction<StreamState>>;
79
- setStreaming: React.Dispatch<React.SetStateAction<boolean>>;
80
- setError: React.Dispatch<React.SetStateAction<string | null>>;
81
- saveCurrent: (messages: ChatMessage[]) => void;
82
- }
83
-
84
- /**
85
- * Subscribe React state to mu-core Session events. Session is authoritative;
86
- * this hook only mirrors. Persistence is driven from the same stream so disk
87
- * writes are guaranteed to match what the user sees, but writes are
88
- * coalesced to once per `stream_ended` to keep tool-heavy turns light on I/O.
89
- */
90
- /**
91
- * Build the event handler. Extracted so the cognitive complexity of the
92
- * dispatch lives outside the React effect closure (the effect itself is
93
- * just `session.subscribe(handler)`).
94
- */
95
- function makeSessionEventHandler(
96
- deps: SubscriptionDeps,
97
- lastMessagesRef: React.MutableRefObject<ChatMessage[]>,
98
- ): (event: import('mu-core').SessionEvent) => void {
99
- const { setMessages, setStream, setStreaming, setError, saveCurrent } = deps;
100
- return (event) => {
101
- if (event.type === 'messages_changed') {
102
- lastMessagesRef.current = event.messages;
103
- setMessages(event.messages);
104
- return;
105
- }
106
- if (event.type === 'stream_partial') {
107
- setStream((s) => ({ ...s, text: event.text, reasoning: event.reasoning ?? '' }));
108
- return;
109
- }
110
- if (event.type === 'stream_started') {
111
- setStreaming(true);
112
- setError(null);
113
- return;
114
- }
115
- if (event.type === 'stream_ended') {
116
- setStreaming(false);
117
- setStream((s) => ({ ...s, text: '', reasoning: '' }));
118
- if (lastMessagesRef.current.length > 0) saveCurrent(lastMessagesRef.current);
119
- return;
120
- }
121
- if (event.type === 'usage') {
122
- setStream((s) => ({
123
- ...s,
124
- totalTokens: s.totalTokens + event.totalTokens,
125
- cachedTokens: s.cachedTokens + event.cachedTokens,
126
- }));
127
- return;
128
- }
129
- if (event.type === 'error') {
130
- setError(event.message);
131
- }
132
- };
133
- }
134
-
135
- function useSessionSubscription(deps: SubscriptionDeps): void {
136
- const { session, setMessages, setStream, setStreaming, setError, saveCurrent } = deps;
137
- // The "last completed transcript" buffer survives effect re-subscriptions
138
- // (e.g. if `saveCurrent` identity ever changes mid-stream). Without a ref
139
- // we'd lose the in-flight save target on the next deps change.
140
- const lastMessagesRef = useRef<ChatMessage[]>([]);
141
- useEffect(() => {
142
- const handler = makeSessionEventHandler(
143
- { session, setMessages, setStream, setStreaming, setError, saveCurrent },
144
- lastMessagesRef,
145
- );
146
- return session.subscribe(handler);
147
- }, [session, setMessages, setStream, setStreaming, setError, saveCurrent]);
148
- }
149
-
150
- interface OnSendDeps {
151
- session: Session;
152
- config: ProviderConfig;
153
- currentModel: string;
154
- attachment: AttachmentState;
155
- controllerRef: React.RefObject<AbortController | null>;
156
- registry: PluginRegistry;
157
- messageBus?: HostMessageBus;
158
- appendHistory: (text: string) => void;
159
- streaming: boolean;
160
- }
161
-
162
- interface OnCompactDeps {
163
- streaming: boolean;
164
- session: Session;
165
- config: ProviderConfig;
166
- currentModel: string;
167
- registry: PluginRegistry;
168
- controllerRef: React.RefObject<AbortController | null>;
169
- saveCurrent: (messages: ChatMessage[]) => void;
170
- }
171
-
172
- const COMPACT_INSTRUCTION =
173
- 'Compact this conversation. Produce ONE concise summary that captures: ' +
174
- "1) the user's overall intent, 2) key decisions made, 3) files modified " +
175
- '(paths with line refs where relevant), 4) open tasks / next steps, and ' +
176
- '5) any important context the assistant should retain. Output ONLY the ' +
177
- 'summary text — no preface, no markdown headers.';
178
-
179
- /**
180
- * Walk a transcript backwards starting at `fromIndex` and return the first
181
- * assistant message with non-empty content. Used by the compact flow to
182
- * locate the summary the LLM produced for the freshly-injected request.
183
- */
184
- function findLatestAssistantContent(messages: ChatMessage[], fromIndex: number): string {
185
- for (let i = messages.length - 1; i >= fromIndex; i--) {
186
- const m = messages[i];
187
- if (m.role === 'assistant' && m.content && m.content.trim().length > 0) {
188
- return m.content;
189
- }
190
- }
191
- return '';
192
- }
193
-
194
- function useOnCompact(deps: OnCompactDeps): () => Promise<void> {
195
- const { streaming, session, config, currentModel, registry, controllerRef, saveCurrent } = deps;
196
- return useCallback(async () => {
197
- if (streaming) return;
198
- const before = session.getMessages();
199
- if (before.length === 0) return;
200
- const beforeCount = before.length;
201
-
202
- // Hide the summarization instruction from the on-screen transcript
203
- // (`display.hidden`) but keep it in the LLM payload. Once the run
204
- // completes we replace the entire transcript anyway.
205
- const summaryInstruction: ChatMessage = {
206
- role: 'user',
207
- content: COMPACT_INSTRUCTION,
208
- display: { hidden: true },
209
- };
210
- const controller = new AbortController();
211
- controllerRef.current = controller;
212
- controller.signal.addEventListener('abort', () => session.abort(), { once: true });
213
- try {
214
- await session.runTurn({ userMessage: summaryInstruction, config, model: currentModel, registry });
215
- const summary = findLatestAssistantContent(session.getMessages(), beforeCount);
216
- if (!summary) return;
217
- // Replace the entire history with a single user marker + the assistant
218
- // summary. The next turn runs with a tiny context, "resumed" from
219
- // the compacted state.
220
- const compacted: ChatMessage[] = [
221
- { role: 'user', content: '[Conversation compacted — context below preserves prior intent and decisions]' },
222
- { role: 'assistant', content: summary },
223
- ];
224
- session.setMessages(compacted);
225
- saveCurrent(compacted);
226
- } finally {
227
- controllerRef.current = null;
228
- }
229
- }, [streaming, session, config, currentModel, registry, controllerRef, saveCurrent]);
230
- }
231
-
232
- function useOnSend(deps: OnSendDeps): (text: string) => Promise<void> {
233
- const { session, config, currentModel, attachment, controllerRef, registry, messageBus, appendHistory, streaming } =
234
- deps;
235
- return useCallback(
236
- async (text: string) => {
237
- if (streaming) return;
238
-
239
- const transform = await runTransformUserInputHooks(registry.getHooks(), text);
240
- if (transform.kind === 'intercept') return;
241
-
242
- // `continue` signals the hook handled the user message itself
243
- // (e.g. mu-agents' @-mention dispatch path appends the user msg
244
- // live, runs the subagent live, and queues the synthetic tool
245
- // flow for the upcoming turn). We skip the userMessage push but
246
- // still drain the queue and stream the LLM follow-up.
247
- const isContinue = transform.kind === 'continue';
248
- const finalText = transform.kind === 'transform' ? transform.text : text;
249
-
250
- const userMsg: ChatMessage | undefined = isContinue
251
- ? undefined
252
- : await runDecorateMessageHooks(registry.getHooks(), {
253
- role: 'user',
254
- content: finalText,
255
- ...(attachment.attachment ? { images: [attachment.attachment] } : {}),
256
- });
257
-
258
- const injections = messageBus?.drainNext() ?? [];
259
- for (const inj of injections) session.queueForNextTurn(inj);
260
-
261
- appendHistory(text);
262
- attachment.clear();
263
-
264
- const controller = new AbortController();
265
- controllerRef.current = controller;
266
- controller.signal.addEventListener('abort', () => session.abort(), { once: true });
267
-
268
- try {
269
- await session.runTurn({
270
- userMessage: userMsg,
271
- config,
272
- model: currentModel,
273
- registry,
274
- });
275
- } finally {
276
- controllerRef.current = null;
277
- }
278
- },
279
- [streaming, session, config, currentModel, attachment, controllerRef, registry, messageBus, appendHistory],
280
- );
281
- }
282
-
283
- /**
284
- * Top-level chat-session hook. Composes:
285
- * - mu-core `Session` — single source of truth for the transcript
286
- * - `useSessionPersistence` — disk write + history + session paths
287
- *
288
- * The hook is purely reactive: it subscribes to session events and exposes
289
- * the resulting state, plus thin wrappers around `session.runTurn` /
290
- * `session.setMessages` for user actions.
291
- */
292
- export function useChatSession(deps: SessionDeps): ChatSessionState {
293
- const { session, config, currentModel, attachment, controllerRef, initialMessages, registry, messageBus } = deps;
294
- const persistence = useSessionPersistence(initialMessages, deps.sessionPathHolder);
295
- const { appendHistory, saveCurrent, resetForNew, loadFromPath } = persistence;
296
-
297
- // Initial seed: feed any persisted messages into the session once.
298
- // The session subscription below will then mirror them into React state.
299
- useEffect(() => {
300
- if (initialMessages?.length) session.setMessages(initialMessages);
301
- // Run once per session instance.
302
- // eslint-disable-next-line react-hooks/exhaustive-deps
303
- }, [session, initialMessages?.length, initialMessages]);
304
-
305
- const [messages, setMessages] = useState<ChatMessage[]>(() => initialMessages ?? []);
306
- const [streaming, setStreaming] = useState(false);
307
- const [error, setError] = useState<string | null>(null);
308
- const [stream, setStream] = useState<StreamState>(EMPTY_STREAM);
309
-
310
- useMessageBusWiring(messageBus, messages, session);
311
- useSessionSubscription({ session, setMessages, setStream, setStreaming, setError, saveCurrent });
312
-
313
- const onSend = useOnSend({
314
- session,
315
- config,
316
- currentModel,
317
- attachment,
318
- controllerRef,
319
- registry,
320
- messageBus,
321
- appendHistory,
322
- streaming,
323
- });
324
-
325
- const onNew = useCallback(() => {
326
- // Abort any in-flight turn *before* rotating the session path.
327
- // Without this, the streaming `runTurn` keeps emitting `messages_changed`
328
- // events that are saved to the newly-rotated path via `stream_ended`,
329
- // mixing the old transcript into the brand-new file.
330
- if (controllerRef.current) {
331
- controllerRef.current.abort();
332
- controllerRef.current = null;
333
- }
334
- resetForNew();
335
- // `session.setMessages([])` emits `messages_changed` which the
336
- // subscription mirrors into React state, so we don't double-write here.
337
- session.setMessages([]);
338
- setStream(EMPTY_STREAM);
339
- setError(null);
340
- attachment.clear();
341
- }, [resetForNew, session, attachment, controllerRef]);
342
-
343
- const onCompact = useOnCompact({
344
- streaming,
345
- session,
346
- config,
347
- currentModel,
348
- registry,
349
- controllerRef,
350
- saveCurrent,
351
- });
352
-
353
- const onLoadSession = useCallback(
354
- (path: string) => {
355
- const loaded = loadFromPath(path);
356
- if (loaded.length === 0) return;
357
- // Abort any in-flight turn before replacing the transcript, for the
358
- // same reason as onNew above.
359
- if (controllerRef.current) {
360
- controllerRef.current.abort();
361
- controllerRef.current = null;
362
- }
363
- // setMessages emits messages_changed → React state mirrors it.
364
- session.setMessages(loaded);
365
- setStream(EMPTY_STREAM);
366
- setError(null);
367
- },
368
- [loadFromPath, session, controllerRef],
369
- );
370
-
371
- return {
372
- messages,
373
- streaming,
374
- error,
375
- stream,
376
- inputHistory: persistence.inputHistory,
377
- onSend,
378
- onNew,
379
- onLoadSession,
380
- onCompact,
381
- };
382
- }
@@ -1,83 +0,0 @@
1
- import type { ApiModel } from 'mu-core';
2
- import { fetchModelContextLimit, listModels } from 'mu-openai-provider';
3
- import { useCallback, useEffect, useState } from 'react';
4
- import { saveConfig } from '../../config/index';
5
-
6
- export interface ModelListState {
7
- models: ApiModel[];
8
- currentModel: string;
9
- modelError: string | null;
10
- cycleModel: () => void;
11
- selectModel: (id: string) => void;
12
- }
13
-
14
- export function useModelList(baseUrl: string, preferredModel?: string): ModelListState {
15
- const [models, setModels] = useState<ApiModel[]>([]);
16
- const [currentModel, setCurrentModel] = useState(preferredModel ?? '');
17
- const [error, setError] = useState<string | null>(null);
18
-
19
- useEffect(() => {
20
- // Guard against late resolution: if the user quits or `baseUrl` changes
21
- // before the request settles, swallow the response so we don't call
22
- // setState on an unmounted hook.
23
- let cancelled = false;
24
- listModels(baseUrl)
25
- .then((list) => {
26
- if (cancelled) return;
27
- if (list.length === 0) {
28
- setError(`No models found at ${baseUrl}`);
29
- return;
30
- }
31
- setError(null);
32
- setModels(list);
33
- const target = preferredModel && list.some((m) => m.id === preferredModel) ? preferredModel : list[0].id;
34
- setCurrentModel(target);
35
- })
36
- .catch((err) => {
37
- if (cancelled) return;
38
- setError(err instanceof Error ? err.message : 'Failed to fetch models');
39
- });
40
- return () => {
41
- cancelled = true;
42
- };
43
- }, [baseUrl, preferredModel]);
44
-
45
- // Lazily probe the active model's context window. Fires whenever the
46
- // selection changes; skips if we already know the limit for that id.
47
- // Runs in the background so the UI never blocks waiting for `/props`.
48
- // Triggers a model load on llama-swap-style proxies, but only for the
49
- // model the user has actually picked — same model the next chat would
50
- // load anyway.
51
- useEffect(() => {
52
- if (!(baseUrl && currentModel)) return;
53
- const known = models.find((m) => m.id === currentModel);
54
- if (!known || known.contextLimit !== undefined) return;
55
- let cancelled = false;
56
- fetchModelContextLimit(baseUrl, currentModel)
57
- .then((limit) => {
58
- if (cancelled || !limit) return;
59
- setModels((prev) => prev.map((m) => (m.id === currentModel ? { ...m, contextLimit: limit } : m)));
60
- })
61
- .catch(() => {
62
- /* silently ignore — providers without `/props` just don't get a limit */
63
- });
64
- return () => {
65
- cancelled = true;
66
- };
67
- }, [baseUrl, currentModel, models]);
68
-
69
- const cycleModel = useCallback(() => {
70
- if (models.length === 0) {
71
- return;
72
- }
73
- const idx = models.findIndex((m) => m.id === currentModel);
74
- setCurrentModel(models[(idx + 1) % models.length].id);
75
- }, [models, currentModel]);
76
-
77
- const selectModel = useCallback((id: string) => {
78
- setCurrentModel(id);
79
- saveConfig({ model: id });
80
- }, []);
81
-
82
- return { models, currentModel, cycleModel, selectModel, modelError: error };
83
- }
@@ -1,44 +0,0 @@
1
- import type { PluginRegistry, StatusSegment } from 'mu-core';
2
- import { useEffect, useMemo, useState } from 'react';
3
- import type { InkUIService } from '../plugins/InkUIService';
4
-
5
- /**
6
- * Aggregate plugin status from the two complementary channels into one
7
- * flat segment list:
8
- *
9
- * 1. `registry.onStatusChange` — push-based, structured `StatusSegment[]` per
10
- * plugin (color/dim metadata). Producers use `PluginContext.setStatusLine`.
11
- * 2. `uiService.onStatusChange` — free-form `key → text` map. Producers use
12
- * `UIService.setStatus` (e.g. `mu-repomap` progress, Pi `pi.ui.setStatus`,
13
- * Pi `pi.ui.setWidget`). Rendered as dim text since the API carries no
14
- * color metadata.
15
- *
16
- * The split lets producers pick the right granularity; callers see a single
17
- * pre-merged list ready for the status bar.
18
- */
19
- export function usePluginStatus(registry: PluginRegistry, uiService?: InkUIService): StatusSegment[] {
20
- const [pluginStatus, setPluginStatus] = useState<StatusSegment[]>([]);
21
- const [uiStatus, setUiStatus] = useState<StatusSegment[]>([]);
22
-
23
- useEffect(() => {
24
- setPluginStatus(registry.getStatusSegments());
25
- return registry.onStatusChange(() => {
26
- setPluginStatus(registry.getStatusSegments());
27
- });
28
- }, [registry]);
29
-
30
- useEffect(() => {
31
- if (!uiService) return;
32
- const apply = (entries: Map<string, string>) => {
33
- const segments: StatusSegment[] = [];
34
- for (const [, text] of entries) {
35
- segments.push({ text, dim: true });
36
- }
37
- setUiStatus(segments);
38
- };
39
- apply(uiService.getStatusEntries());
40
- return uiService.onStatusChange(apply);
41
- }, [uiService]);
42
-
43
- return useMemo(() => [...pluginStatus, ...uiStatus], [pluginStatus, uiStatus]);
44
- }