@kirosnn/mosaic 0.0.91 → 0.73.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 (99) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +2 -6
  3. package/package.json +55 -48
  4. package/src/agent/Agent.ts +353 -131
  5. package/src/agent/context.ts +4 -4
  6. package/src/agent/prompts/systemPrompt.ts +209 -70
  7. package/src/agent/prompts/toolsPrompt.ts +285 -138
  8. package/src/agent/provider/anthropic.ts +109 -105
  9. package/src/agent/provider/google.ts +111 -107
  10. package/src/agent/provider/mistral.ts +95 -95
  11. package/src/agent/provider/ollama.ts +73 -17
  12. package/src/agent/provider/openai.ts +146 -102
  13. package/src/agent/provider/rateLimit.ts +178 -0
  14. package/src/agent/provider/reasoning.ts +29 -0
  15. package/src/agent/provider/xai.ts +108 -104
  16. package/src/agent/tools/definitions.ts +15 -1
  17. package/src/agent/tools/executor.ts +717 -98
  18. package/src/agent/tools/exploreExecutor.ts +20 -22
  19. package/src/agent/tools/fetch.ts +58 -0
  20. package/src/agent/tools/glob.ts +20 -4
  21. package/src/agent/tools/grep.ts +64 -9
  22. package/src/agent/tools/plan.ts +27 -0
  23. package/src/agent/tools/question.ts +7 -1
  24. package/src/agent/tools/read.ts +2 -0
  25. package/src/agent/types.ts +15 -14
  26. package/src/components/App.tsx +50 -8
  27. package/src/components/CustomInput.tsx +461 -77
  28. package/src/components/Main.tsx +1459 -1112
  29. package/src/components/Setup.tsx +1 -1
  30. package/src/components/ShortcutsModal.tsx +11 -8
  31. package/src/components/Welcome.tsx +1 -1
  32. package/src/components/main/ApprovalPanel.tsx +4 -3
  33. package/src/components/main/ChatPage.tsx +858 -516
  34. package/src/components/main/HomePage.tsx +58 -39
  35. package/src/components/main/QuestionPanel.tsx +52 -7
  36. package/src/components/main/ThinkingIndicator.tsx +13 -2
  37. package/src/components/main/types.ts +11 -10
  38. package/src/index.tsx +53 -25
  39. package/src/mcp/approvalPolicy.ts +148 -0
  40. package/src/mcp/cli/add.ts +185 -0
  41. package/src/mcp/cli/doctor.ts +77 -0
  42. package/src/mcp/cli/index.ts +85 -0
  43. package/src/mcp/cli/list.ts +50 -0
  44. package/src/mcp/cli/logs.ts +24 -0
  45. package/src/mcp/cli/manage.ts +99 -0
  46. package/src/mcp/cli/show.ts +53 -0
  47. package/src/mcp/cli/tools.ts +77 -0
  48. package/src/mcp/config.ts +223 -0
  49. package/src/mcp/index.ts +80 -0
  50. package/src/mcp/processManager.ts +299 -0
  51. package/src/mcp/rateLimiter.ts +50 -0
  52. package/src/mcp/registry.ts +151 -0
  53. package/src/mcp/schemaConverter.ts +100 -0
  54. package/src/mcp/servers/navigation.ts +854 -0
  55. package/src/mcp/toolCatalog.ts +169 -0
  56. package/src/mcp/types.ts +95 -0
  57. package/src/utils/approvalBridge.ts +45 -12
  58. package/src/utils/approvalModeBridge.ts +17 -0
  59. package/src/utils/commands/approvals.ts +48 -0
  60. package/src/utils/commands/compact.ts +30 -0
  61. package/src/utils/commands/echo.ts +1 -1
  62. package/src/utils/commands/image.ts +109 -0
  63. package/src/utils/commands/index.ts +9 -7
  64. package/src/utils/commands/new.ts +15 -0
  65. package/src/utils/commands/types.ts +3 -0
  66. package/src/utils/config.ts +3 -1
  67. package/src/utils/diffRendering.tsx +13 -16
  68. package/src/utils/exploreBridge.ts +10 -0
  69. package/src/utils/history.ts +82 -40
  70. package/src/utils/imageBridge.ts +28 -0
  71. package/src/utils/images.ts +31 -0
  72. package/src/utils/markdown.tsx +163 -99
  73. package/src/utils/models.ts +31 -16
  74. package/src/utils/notificationBridge.ts +23 -0
  75. package/src/utils/questionBridge.ts +36 -1
  76. package/src/utils/tokenEstimator.ts +32 -0
  77. package/src/utils/toolFormatting.ts +428 -48
  78. package/src/web/app.tsx +65 -5
  79. package/src/web/assets/css/ChatPage.css +102 -30
  80. package/src/web/assets/css/MessageItem.css +26 -29
  81. package/src/web/assets/css/ThinkingIndicator.css +44 -6
  82. package/src/web/assets/css/ToolMessage.css +36 -14
  83. package/src/web/components/ChatPage.tsx +228 -105
  84. package/src/web/components/HomePage.tsx +3 -3
  85. package/src/web/components/MessageItem.tsx +80 -81
  86. package/src/web/components/QuestionPanel.tsx +72 -12
  87. package/src/web/components/Setup.tsx +1 -1
  88. package/src/web/components/Sidebar.tsx +1 -3
  89. package/src/web/components/ThinkingIndicator.tsx +41 -21
  90. package/src/web/router.ts +1 -1
  91. package/src/web/server.tsx +894 -662
  92. package/src/web/storage.ts +23 -1
  93. package/src/web/types.ts +7 -6
  94. package/src/utils/commands/redo.ts +0 -74
  95. package/src/utils/commands/sessions.ts +0 -129
  96. package/src/utils/commands/undo.ts +0 -75
  97. package/src/utils/undoRedo.ts +0 -429
  98. package/src/utils/undoRedoBridge.ts +0 -45
  99. package/src/utils/undoRedoDb.ts +0 -338
@@ -1,1112 +1,1459 @@
1
- import { useState, useEffect, useRef } from "react";
2
- import { useKeyboard } from "@opentui/react";
3
- import { Agent } from "../agent";
4
- import { saveConversation, addInputToHistory, type ConversationHistory, type ConversationStep } from "../utils/history";
5
- import { readConfig } from "../utils/config";
6
- import { DEFAULT_MAX_TOOL_LINES, formatToolMessage, formatErrorMessage, parseToolHeader } from '../utils/toolFormatting';
7
- import { initializeCommands, isCommand, executeCommand } from '../utils/commands';
8
- import type { InputSubmitMeta } from './CustomInput';
9
-
10
- import { subscribeQuestion, type QuestionRequest } from "../utils/questionBridge";
11
- import { subscribeApprovalAccepted, type ApprovalAccepted } from "../utils/approvalBridge";
12
- import { subscribeUndoRedo } from "../utils/undoRedoBridge";
13
- import { setExploreAbortController, setExploreToolCallback, abortExplore } from "../utils/exploreBridge";
14
- import { initializeSession, saveState } from "../utils/undoRedo";
15
- import { resetFileChanges } from "../utils/fileChangeTracker";
16
- import { getCurrentQuestion, cancelQuestion } from "../utils/questionBridge";
17
- import { getCurrentApproval, cancelApproval } from "../utils/approvalBridge";
18
- import { BLEND_WORDS, type MainProps, type Message } from "./main/types";
19
- import { HomePage } from './main/HomePage';
20
- import { ChatPage } from './main/ChatPage';
21
-
22
- function extractTitle(content: string, alreadyResolved: boolean): { title: string | null; cleanContent: string; isPending: boolean; noTitle: boolean } {
23
- const trimmed = content.trimStart();
24
-
25
- const titleMatch = trimmed.match(/^<title>(.*?)<\/title>\s*/s);
26
- if (titleMatch) {
27
- const title = alreadyResolved ? null : (titleMatch[1]?.trim() || null);
28
- const cleanContent = trimmed.replace(/^<title>.*?<\/title>\s*/s, '');
29
- return { title, cleanContent, isPending: false, noTitle: false };
30
- }
31
-
32
- if (alreadyResolved) {
33
- return { title: null, cleanContent: content, isPending: false, noTitle: false };
34
- }
35
-
36
- const partialTitlePattern = /^<(t(i(t(l(e(>.*)?)?)?)?)?)?$/i;
37
- if (partialTitlePattern.test(trimmed) || (trimmed.startsWith('<title>') && !trimmed.includes('</title>'))) {
38
- return { title: null, cleanContent: '', isPending: true, noTitle: false };
39
- }
40
-
41
- return { title: null, cleanContent: content, isPending: false, noTitle: true };
42
- }
43
-
44
- function setTerminalTitle(title: string) {
45
- process.title = `⁘ ${title}`;
46
- }
47
-
48
- export function Main({ pasteRequestId = 0, copyRequestId = 0, onCopy, shortcutsOpen = false, commandsOpen = false, initialMessage }: MainProps) {
49
- const [currentPage, setCurrentPage] = useState<"home" | "chat">(initialMessage ? "chat" : "home");
50
- const [messages, setMessages] = useState<Message[]>([]);
51
- const [isProcessing, setIsProcessing] = useState(false);
52
- const [processingStartTime, setProcessingStartTime] = useState<number | null>(null);
53
- const [currentTokens, setCurrentTokens] = useState(0);
54
- const [scrollOffset, setScrollOffset] = useState(0);
55
- const [terminalHeight, setTerminalHeight] = useState(process.stdout.rows || 24);
56
- const [terminalWidth, setTerminalWidth] = useState(process.stdout.columns || 80);
57
- const [questionRequest, setQuestionRequest] = useState<QuestionRequest | null>(null);
58
- const [currentTitle, setCurrentTitle] = useState<string | null>(null);
59
- const currentTitleRef = useRef<string | null>(null);
60
- const titleExtractedRef = useRef(false);
61
- const shouldAutoScroll = useRef(true);
62
- const abortControllerRef = useRef<AbortController | null>(null);
63
- const currentPageRef = useRef(currentPage);
64
- const shortcutsOpenRef = useRef(shortcutsOpen);
65
- const commandsOpenRef = useRef(commandsOpen);
66
- const questionRequestRef = useRef<QuestionRequest | null>(questionRequest);
67
- const initialMessageProcessed = useRef(false);
68
- const exploreMessageIdRef = useRef<string | null>(null);
69
- const exploreToolsRef = useRef<Array<{ tool: string; info: string; success: boolean }>>([]);
70
- const explorePurposeRef = useRef<string>('');
71
-
72
- const createId = () => `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
73
-
74
- useEffect(() => {
75
- initializeCommands();
76
- initializeSession();
77
- }, []);
78
-
79
- useEffect(() => {
80
- let lastExploreTokens = 0;
81
- setExploreToolCallback((toolName, args, result, totalTokens) => {
82
- const info = (args.path || args.pattern || args.query || '') as string;
83
- const shortInfo = info.length > 40 ? info.substring(0, 37) + '...' : info;
84
- exploreToolsRef.current.push({ tool: toolName, info: shortInfo, success: result.success });
85
-
86
- const tokenDelta = totalTokens - lastExploreTokens;
87
- lastExploreTokens = totalTokens;
88
- if (tokenDelta > 0) {
89
- setCurrentTokens(prev => prev + tokenDelta);
90
- }
91
-
92
- if (exploreMessageIdRef.current) {
93
- setMessages((prev: Message[]) => {
94
- const newMessages = [...prev];
95
- const idx = newMessages.findIndex(m => m.id === exploreMessageIdRef.current);
96
- if (idx !== -1) {
97
- const toolLines = exploreToolsRef.current.map(t => {
98
- const icon = t.success ? '+' : '-';
99
- return ` ${icon} ${t.tool}(${t.info})`;
100
- });
101
- const purpose = explorePurposeRef.current;
102
- const newContent = `Explore (${purpose})\n${toolLines.join('\n')}`;
103
- newMessages[idx] = { ...newMessages[idx]!, content: newContent };
104
- }
105
- return newMessages;
106
- });
107
- }
108
- });
109
-
110
- return () => {
111
- setExploreToolCallback(null);
112
- };
113
- }, []);
114
-
115
- useEffect(() => {
116
- return subscribeUndoRedo((state, action) => {
117
- if (state) {
118
- setMessages(state.messages);
119
- resetFileChanges();
120
- }
121
- });
122
- }, []);
123
-
124
- useEffect(() => {
125
- const handleResize = () => {
126
- const newWidth = process.stdout.columns || 80;
127
- const newHeight = process.stdout.rows || 24;
128
- const oldWidth = terminalWidth;
129
- const oldHeight = terminalHeight;
130
-
131
- setTerminalWidth(newWidth);
132
- setTerminalHeight(newHeight);
133
-
134
- if (shouldAutoScroll.current) {
135
- setScrollOffset(0);
136
- } else if (oldHeight !== newHeight) {
137
- const heightDiff = newHeight - oldHeight;
138
- setScrollOffset(prev => Math.max(0, prev - heightDiff));
139
- }
140
- };
141
- process.stdout.on('resize', handleResize);
142
- return () => {
143
- process.stdout.off('resize', handleResize);
144
- };
145
- }, [terminalWidth, terminalHeight]);
146
-
147
- useEffect(() => {
148
- return subscribeQuestion(setQuestionRequest);
149
- }, []);
150
-
151
- useEffect(() => {
152
- return subscribeApprovalAccepted((accepted) => {
153
- const isBashTool = accepted.toolName === 'bash';
154
-
155
- if (isBashTool) {
156
- const { name: toolDisplayName, info: toolInfo } = parseToolHeader(accepted.toolName, accepted.args);
157
- const runningContent = toolInfo ? `${toolDisplayName} (${toolInfo})` : toolDisplayName;
158
-
159
- setMessages((prev: Message[]) => {
160
- const newMessages = [...prev];
161
- newMessages.push({
162
- id: createId(),
163
- role: "tool",
164
- content: runningContent,
165
- toolName: accepted.toolName,
166
- toolArgs: accepted.args,
167
- success: true,
168
- isRunning: true,
169
- runningStartTime: Date.now()
170
- });
171
- return newMessages;
172
- });
173
- }
174
- });
175
- }, []);
176
-
177
- useEffect(() => {
178
- currentPageRef.current = currentPage;
179
- }, [currentPage]);
180
-
181
- useEffect(() => {
182
- shortcutsOpenRef.current = shortcutsOpen;
183
- }, [shortcutsOpen]);
184
-
185
- useEffect(() => {
186
- commandsOpenRef.current = commandsOpen;
187
- }, [commandsOpen]);
188
-
189
- useEffect(() => {
190
- questionRequestRef.current = questionRequest;
191
- }, [questionRequest]);
192
-
193
- useEffect(() => {
194
- if (questionRequest) {
195
- shouldAutoScroll.current = true;
196
- setScrollOffset(0);
197
- }
198
- }, [questionRequest]);
199
-
200
- useEffect(() => {
201
- if (currentPage !== "chat") return;
202
-
203
- process.stdin.setRawMode(true);
204
- process.stdout.write('\x1b[?1000h');
205
- process.stdout.write('\x1b[?1003h');
206
- process.stdout.write('\x1b[?1006h');
207
-
208
- const handleData = (data: Buffer) => {
209
- const str = data.toString();
210
-
211
- if (str.match(/\x1b\[<(\d+);(\d+);(\d+)([mM])/)) {
212
- const match = str.match(/\x1b\[<(\d+);(\d+);(\d+)([mM])/);
213
- if (match) {
214
- const button = parseInt(match[1] || '0');
215
-
216
- if (button === 64) {
217
- shouldAutoScroll.current = false;
218
- setScrollOffset((prev) => prev + 1);
219
- } else if (button === 65) {
220
- setScrollOffset((prev) => {
221
- const newOffset = Math.max(0, prev - 1);
222
- if (newOffset === 0) {
223
- shouldAutoScroll.current = true;
224
- }
225
- return newOffset;
226
- });
227
- }
228
- }
229
- }
230
- };
231
-
232
- process.stdin.on('data', handleData);
233
-
234
- return () => {
235
- process.stdin.off('data', handleData);
236
- process.stdout.write('\x1b[?1000l');
237
- process.stdout.write('\x1b[?1003l');
238
- process.stdout.write('\x1b[?1006l');
239
- };
240
- }, [currentPage]);
241
-
242
- useEffect(() => {
243
- if (currentPage === "chat") {
244
- setScrollOffset((prevOffset) => {
245
- if (shouldAutoScroll.current || prevOffset < 5) {
246
- shouldAutoScroll.current = true;
247
- return 0;
248
- }
249
- return prevOffset;
250
- });
251
- }
252
- }, [messages, currentPage]);
253
-
254
- useEffect(() => {
255
- if (copyRequestId > 0 && onCopy && messages.length > 0) {
256
- const lastAssistantMessage = messages.slice().reverse().find(m => m.role === 'assistant');
257
- if (lastAssistantMessage) {
258
- onCopy(lastAssistantMessage.content);
259
- }
260
- }
261
- }, [copyRequestId, onCopy, messages]);
262
-
263
- useKeyboard((key) => {
264
- if (key.name === 'escape') {
265
- if (getCurrentQuestion()) {
266
- cancelQuestion();
267
- }
268
- if (getCurrentApproval()) {
269
- cancelApproval();
270
- }
271
- abortControllerRef.current?.abort();
272
- return;
273
- }
274
- });
275
-
276
- const handleSubmit = async (value: string, meta?: InputSubmitMeta) => {
277
- if (isProcessing) return;
278
-
279
- const hasPastedContent = Boolean(meta?.isPaste && meta.pastedContent);
280
- if (!value.trim() && !hasPastedContent) return;
281
-
282
- if (isCommand(value)) {
283
- const result = await executeCommand(value);
284
- if (result) {
285
- if (result.shouldAddToHistory === true) {
286
- addInputToHistory(value.trim());
287
-
288
- saveState(messages);
289
-
290
- const userMessage: Message = {
291
- id: createId(),
292
- role: "user",
293
- content: result.content,
294
- displayContent: value,
295
- };
296
-
297
- setMessages((prev: Message[]) => [...prev, userMessage]);
298
- setIsProcessing(true);
299
- const localStartTime = Date.now();
300
- setProcessingStartTime(localStartTime);
301
- setCurrentTokens(0);
302
- shouldAutoScroll.current = true;
303
-
304
- const conversationId = createId();
305
- const conversationSteps: ConversationStep[] = [];
306
- let totalTokens = { prompt: 0, completion: 0, total: 0 };
307
- let stepCount = 0;
308
- let totalChars = 0;
309
- for (const m of messages) {
310
- if (m.role === 'assistant') {
311
- totalChars += m.content.length;
312
- if (m.thinkingContent) totalChars += m.thinkingContent.length;
313
- } else if (m.role === 'tool') {
314
- totalChars += m.content.length;
315
- }
316
- }
317
-
318
- const estimateTokens = () => Math.ceil(totalChars / 4);
319
- setCurrentTokens(estimateTokens());
320
- const config = readConfig();
321
- const abortController = new AbortController();
322
- abortControllerRef.current = abortController;
323
- let abortNotified = false;
324
- const notifyAbort = () => {
325
- if (abortNotified) return;
326
- abortNotified = true;
327
- setMessages((prev: Message[]) => {
328
- const newMessages = [...prev];
329
- newMessages.push({
330
- id: createId(),
331
- role: "tool",
332
- success: false,
333
- content: "Request interrupted by user. \n↪ What should Mosaic do instead?"
334
- });
335
- return newMessages;
336
- });
337
- };
338
-
339
- conversationSteps.push({
340
- type: 'user',
341
- content: result.content,
342
- timestamp: Date.now()
343
- });
344
-
345
- try {
346
- const providerStatus = await Agent.ensureProviderReady();
347
- if (!providerStatus.ready) {
348
- setMessages((prev: Message[]) => {
349
- const newMessages = [...prev];
350
- newMessages.push({
351
- id: createId(),
352
- role: "assistant",
353
- content: `Ollama error: ${providerStatus.error || 'Could not start Ollama. Make sure Ollama is installed.'}`,
354
- isError: true
355
- });
356
- return newMessages;
357
- });
358
- setIsProcessing(false);
359
- return;
360
- }
361
-
362
- const agent = new Agent();
363
- const conversationHistory = [...messages, userMessage]
364
- .filter((m): m is Message & { role: 'user' | 'assistant' } => m.role === 'user' || m.role === 'assistant')
365
- .map((m) => ({ role: m.role, content: m.content }));
366
- let assistantChunk = '';
367
- let thinkingChunk = '';
368
- const pendingToolCalls = new Map<string, { toolName: string; args: Record<string, unknown>; messageId?: string }>();
369
- let assistantMessageId: string | null = null;
370
- let streamHadError = false;
371
- titleExtractedRef.current = false;
372
-
373
- for await (const event of agent.streamMessages(conversationHistory, { abortSignal: abortController.signal })) {
374
- if (event.type === 'reasoning-delta') {
375
- thinkingChunk += event.content;
376
- totalChars += event.content.length;
377
- setCurrentTokens(estimateTokens());
378
-
379
- if (assistantMessageId === null) {
380
- assistantMessageId = createId();
381
- }
382
-
383
- const currentMessageId = assistantMessageId;
384
- setMessages((prev: Message[]) => {
385
- const newMessages = [...prev];
386
- const messageIndex = newMessages.findIndex(m => m.id === currentMessageId);
387
-
388
- if (messageIndex === -1) {
389
- newMessages.push({ id: currentMessageId, role: "assistant", content: '', thinkingContent: thinkingChunk });
390
- } else {
391
- newMessages[messageIndex] = {
392
- ...newMessages[messageIndex]!,
393
- thinkingContent: thinkingChunk
394
- };
395
- }
396
- return newMessages;
397
- });
398
- } else if (event.type === 'text-delta') {
399
- assistantChunk += event.content;
400
- totalChars += event.content.length;
401
- setCurrentTokens(estimateTokens());
402
-
403
- const { title, cleanContent, isPending, noTitle } = extractTitle(assistantChunk, titleExtractedRef.current);
404
-
405
- if (title) {
406
- titleExtractedRef.current = true;
407
- currentTitleRef.current = title;
408
- setCurrentTitle(title);
409
- setTerminalTitle(title);
410
- } else if (noTitle) {
411
- titleExtractedRef.current = true;
412
- }
413
-
414
- if (isPending) continue;
415
-
416
- if (assistantMessageId === null) {
417
- assistantMessageId = createId();
418
- }
419
-
420
- const displayContent = cleanContent;
421
- const currentMessageId = assistantMessageId;
422
- setMessages((prev: Message[]) => {
423
- const newMessages = [...prev];
424
- const messageIndex = newMessages.findIndex(m => m.id === currentMessageId);
425
-
426
- if (messageIndex === -1) {
427
- newMessages.push({ id: currentMessageId, role: "assistant", content: displayContent, thinkingContent: thinkingChunk });
428
- } else {
429
- newMessages[messageIndex] = {
430
- ...newMessages[messageIndex]!,
431
- content: displayContent
432
- };
433
- }
434
- return newMessages;
435
- });
436
- } else if (event.type === 'step-start') {
437
- stepCount++;
438
- } else if (event.type === 'tool-call-end') {
439
- totalChars += JSON.stringify(event.args).length;
440
- setCurrentTokens(estimateTokens());
441
-
442
- const needsApproval = event.toolName === 'write' || event.toolName === 'edit' || event.toolName === 'bash';
443
- const isExploreTool = event.toolName === 'explore';
444
- const showRunning = event.toolName === 'bash';
445
- let runningMessageId: string | undefined;
446
-
447
- if (isExploreTool) {
448
- setExploreAbortController(abortController);
449
- exploreToolsRef.current = [];
450
- const purpose = (event.args.purpose as string) || 'exploring...';
451
- explorePurposeRef.current = purpose;
452
- }
453
-
454
- if (!needsApproval) {
455
- runningMessageId = createId();
456
- const { name: toolDisplayName, info: toolInfo } = parseToolHeader(event.toolName, event.args);
457
- const runningContent = toolInfo ? `${toolDisplayName} (${toolInfo})` : toolDisplayName;
458
-
459
- if (isExploreTool) {
460
- exploreMessageIdRef.current = runningMessageId;
461
- }
462
-
463
- setMessages((prev: Message[]) => {
464
- const newMessages = [...prev];
465
- newMessages.push({
466
- id: runningMessageId!,
467
- role: "tool",
468
- content: runningContent,
469
- toolName: event.toolName,
470
- toolArgs: event.args,
471
- success: true,
472
- isRunning: showRunning || isExploreTool,
473
- runningStartTime: (showRunning || isExploreTool) ? Date.now() : undefined
474
- });
475
- return newMessages;
476
- });
477
- }
478
-
479
- pendingToolCalls.set(event.toolCallId, {
480
- toolName: event.toolName,
481
- args: event.args,
482
- messageId: runningMessageId
483
- });
484
-
485
- } else if (event.type === 'tool-result') {
486
- const pending = pendingToolCalls.get(event.toolCallId);
487
- const toolName = pending?.toolName ?? event.toolName;
488
- const toolArgs = pending?.args ?? {};
489
- const runningMessageId = pending?.messageId;
490
- pendingToolCalls.delete(event.toolCallId);
491
-
492
- if (toolName === 'explore') {
493
- exploreMessageIdRef.current = null;
494
- setExploreAbortController(null);
495
- }
496
-
497
- const { content: toolContent, success } = formatToolMessage(
498
- toolName,
499
- toolArgs,
500
- event.result,
501
- { maxLines: DEFAULT_MAX_TOOL_LINES }
502
- );
503
-
504
- const toolResultStr = typeof event.result === 'string' ? event.result : JSON.stringify(event.result);
505
- totalChars += toolResultStr.length;
506
- setCurrentTokens(estimateTokens());
507
-
508
- if (assistantChunk.trim()) {
509
- conversationSteps.push({
510
- type: 'assistant',
511
- content: assistantChunk,
512
- timestamp: Date.now()
513
- });
514
- }
515
-
516
- conversationSteps.push({
517
- type: 'tool',
518
- content: toolContent,
519
- toolName,
520
- toolArgs,
521
- toolResult: event.result,
522
- timestamp: Date.now()
523
- });
524
-
525
- setMessages((prev: Message[]) => {
526
- const newMessages = [...prev];
527
-
528
- let runningIndex = -1;
529
- if (runningMessageId) {
530
- runningIndex = newMessages.findIndex(m => m.id === runningMessageId);
531
- } else if (toolName === 'bash' || toolName === 'explore') {
532
- runningIndex = newMessages.findIndex(m => m.toolName === toolName && m.isRunning === true);
533
- }
534
-
535
- if (runningIndex !== -1) {
536
- newMessages[runningIndex] = {
537
- ...newMessages[runningIndex]!,
538
- content: toolContent,
539
- toolArgs: toolArgs,
540
- toolResult: event.result,
541
- success,
542
- isRunning: false,
543
- runningStartTime: undefined,
544
- timestamp: Date.now()
545
- };
546
- return newMessages;
547
- }
548
-
549
- newMessages.push({
550
- id: createId(),
551
- role: "tool",
552
- content: toolContent,
553
- toolName,
554
- toolArgs: toolArgs,
555
- toolResult: event.result,
556
- success: success,
557
- timestamp: Date.now()
558
- });
559
- return newMessages;
560
- });
561
-
562
- assistantChunk = '';
563
- assistantMessageId = null;
564
- } else if (event.type === 'error') {
565
- if (abortController.signal.aborted) {
566
- notifyAbort();
567
- streamHadError = true;
568
- break;
569
- }
570
- if (assistantChunk.trim()) {
571
- conversationSteps.push({
572
- type: 'assistant',
573
- content: assistantChunk,
574
- timestamp: Date.now()
575
- });
576
- }
577
-
578
- const errorContent = formatErrorMessage('API', event.error);
579
- conversationSteps.push({
580
- type: 'assistant',
581
- content: errorContent,
582
- timestamp: Date.now()
583
- });
584
-
585
- setMessages((prev: Message[]) => {
586
- const newMessages = [...prev];
587
- newMessages.push({
588
- id: createId(),
589
- role: 'assistant',
590
- content: errorContent,
591
- isError: true,
592
- });
593
- return newMessages;
594
- });
595
-
596
- assistantChunk = '';
597
- assistantMessageId = null;
598
- streamHadError = true;
599
- break;
600
- } else if (event.type === 'finish') {
601
- if (event.usage && event.usage.totalTokens > 0) {
602
- totalTokens = {
603
- prompt: event.usage.promptTokens,
604
- completion: event.usage.completionTokens,
605
- total: event.usage.totalTokens
606
- };
607
- setCurrentTokens(event.usage.totalTokens);
608
- }
609
- }
610
- }
611
-
612
- if (abortController.signal.aborted) {
613
- notifyAbort();
614
- return;
615
- }
616
-
617
- if (!streamHadError && assistantChunk.trim()) {
618
- conversationSteps.push({
619
- type: 'assistant',
620
- content: assistantChunk,
621
- timestamp: Date.now()
622
- });
623
- }
624
-
625
- const conversationData: ConversationHistory = {
626
- id: conversationId,
627
- timestamp: Date.now(),
628
- steps: conversationSteps,
629
- totalSteps: stepCount,
630
- totalTokens: totalTokens.total > 0 ? totalTokens : undefined,
631
- model: config.model,
632
- provider: config.provider
633
- };
634
-
635
- saveConversation(conversationData);
636
-
637
- } catch (error) {
638
- if (abortController.signal.aborted) {
639
- notifyAbort();
640
- return;
641
- }
642
- const errorMessage = error instanceof Error ? error.message : 'An unknown error occurred';
643
- const errorContent = formatErrorMessage('Mosaic', errorMessage);
644
- setMessages((prev: Message[]) => {
645
- const newMessages = [...prev];
646
- if (newMessages[newMessages.length - 1]?.role === 'assistant' && newMessages[newMessages.length - 1]?.content === '') {
647
- newMessages[newMessages.length - 1] = {
648
- id: newMessages[newMessages.length - 1]!.id,
649
- role: "assistant",
650
- content: errorContent,
651
- isError: true
652
- };
653
- } else {
654
- newMessages.push({
655
- id: createId(),
656
- role: "assistant",
657
- content: errorContent,
658
- isError: true
659
- });
660
- }
661
- return newMessages;
662
- });
663
- } finally {
664
- if (abortControllerRef.current === abortController) {
665
- abortControllerRef.current = null;
666
- }
667
- const duration = Date.now() - localStartTime;
668
- if (duration >= 60000) {
669
- const blendWord = BLEND_WORDS[Math.floor(Math.random() * BLEND_WORDS.length)];
670
- setMessages((prev: Message[]) => {
671
- const newMessages = [...prev];
672
- for (let i = newMessages.length - 1; i >= 0; i--) {
673
- if (newMessages[i]?.role === 'assistant') {
674
- newMessages[i] = { ...newMessages[i]!, responseDuration: duration, blendWord };
675
- break;
676
- }
677
- }
678
- return newMessages;
679
- });
680
- }
681
- setIsProcessing(false);
682
- setProcessingStartTime(null);
683
- }
684
-
685
- return;
686
- }
687
-
688
- const commandMessage: Message = {
689
- id: createId(),
690
- role: "slash",
691
- content: result.content,
692
- isError: !result.success
693
- };
694
-
695
- setMessages((prev: Message[]) => [...prev, commandMessage]);
696
-
697
- if (result.shouldAddToHistory !== false) {
698
- addInputToHistory(value.trim());
699
- }
700
-
701
- return;
702
- }
703
- }
704
-
705
- const composedContent = hasPastedContent
706
- ? `${meta!.pastedContent!}${value.trim() ? `\n\n${value}` : ''}`
707
- : value;
708
-
709
- addInputToHistory(value.trim() || (hasPastedContent ? '[Pasted text]' : value));
710
-
711
- saveState(messages);
712
-
713
- const userMessage: Message = {
714
- id: createId(),
715
- role: "user",
716
- content: composedContent,
717
- displayContent: meta?.isPaste ? '[Pasted text]' : undefined,
718
- };
719
-
720
- setMessages((prev: Message[]) => [...prev, userMessage]);
721
- setIsProcessing(true);
722
- const localStartTime = Date.now();
723
- setProcessingStartTime(localStartTime);
724
- setCurrentTokens(0);
725
- shouldAutoScroll.current = true;
726
-
727
- const conversationId = createId();
728
- const conversationSteps: ConversationStep[] = [];
729
- let totalTokens = { prompt: 0, completion: 0, total: 0 };
730
- let stepCount = 0;
731
- let totalChars = 0;
732
- for (const m of messages) {
733
- if (m.role === 'assistant') {
734
- totalChars += m.content.length;
735
- if (m.thinkingContent) totalChars += m.thinkingContent.length;
736
- } else if (m.role === 'tool') {
737
- totalChars += m.content.length;
738
- }
739
- }
740
-
741
- const estimateTokens = () => Math.ceil(totalChars / 4);
742
- setCurrentTokens(estimateTokens());
743
- const config = readConfig();
744
- const abortController = new AbortController();
745
- abortControllerRef.current = abortController;
746
- let abortNotified = false;
747
- const notifyAbort = () => {
748
- if (abortNotified) return;
749
- abortNotified = true;
750
- setMessages((prev: Message[]) => {
751
- const newMessages = [...prev];
752
- newMessages.push({
753
- id: createId(),
754
- role: "tool",
755
- success: false,
756
- content: "Generation aborted. \n↪ What should Mosaic do instead?"
757
- });
758
- return newMessages;
759
- });
760
- };
761
-
762
- conversationSteps.push({
763
- type: 'user',
764
- content: composedContent,
765
- timestamp: Date.now()
766
- });
767
-
768
- try {
769
- const providerStatus = await Agent.ensureProviderReady();
770
- if (!providerStatus.ready) {
771
- setMessages((prev: Message[]) => {
772
- const newMessages = [...prev];
773
- newMessages.push({
774
- id: createId(),
775
- role: "assistant",
776
- content: `Ollama error: ${providerStatus.error || 'Could not start Ollama. Make sure Ollama is installed.'}`,
777
- isError: true
778
- });
779
- return newMessages;
780
- });
781
- setIsProcessing(false);
782
- return;
783
- }
784
-
785
- const agent = new Agent();
786
- const conversationHistory = [...messages, userMessage]
787
- .filter((m): m is Message & { role: 'user' | 'assistant' } => m.role === 'user' || m.role === 'assistant')
788
- .map((m) => ({ role: m.role, content: m.content }));
789
- let assistantChunk = '';
790
- const pendingToolCalls = new Map<string, { toolName: string; args: Record<string, unknown>; messageId?: string }>();
791
- let assistantMessageId: string | null = null;
792
- let streamHadError = false;
793
- titleExtractedRef.current = false;
794
-
795
- for await (const event of agent.streamMessages(conversationHistory, { abortSignal: abortController.signal })) {
796
- if (event.type === 'text-delta') {
797
- assistantChunk += event.content;
798
- totalChars += event.content.length;
799
- setCurrentTokens(estimateTokens());
800
-
801
- const { title, cleanContent, isPending, noTitle } = extractTitle(assistantChunk, titleExtractedRef.current);
802
-
803
- if (title) {
804
- titleExtractedRef.current = true;
805
- currentTitleRef.current = title;
806
- setCurrentTitle(title);
807
- setTerminalTitle(title);
808
- } else if (noTitle) {
809
- titleExtractedRef.current = true;
810
- }
811
-
812
- if (isPending) continue;
813
-
814
- if (assistantMessageId === null) {
815
- assistantMessageId = createId();
816
- }
817
-
818
- const displayContent = cleanContent;
819
- const currentMessageId = assistantMessageId;
820
- setMessages((prev: Message[]) => {
821
- const newMessages = [...prev];
822
- const messageIndex = newMessages.findIndex(m => m.id === currentMessageId);
823
-
824
- if (messageIndex === -1) {
825
- newMessages.push({ id: currentMessageId, role: "assistant", content: displayContent });
826
- } else {
827
- newMessages[messageIndex] = {
828
- ...newMessages[messageIndex]!,
829
- content: displayContent
830
- };
831
- }
832
- return newMessages;
833
- });
834
- } else if (event.type === 'step-start') {
835
- stepCount++;
836
- } else if (event.type === 'tool-call-end') {
837
- totalChars += JSON.stringify(event.args).length;
838
- setCurrentTokens(estimateTokens());
839
-
840
- const isExploreTool = event.toolName === 'explore';
841
- let runningMessageId: string | undefined;
842
-
843
- if (isExploreTool) {
844
- setExploreAbortController(abortController);
845
- exploreToolsRef.current = [];
846
- const purpose = (event.args.purpose as string) || 'exploring...';
847
- explorePurposeRef.current = purpose;
848
- runningMessageId = createId();
849
- exploreMessageIdRef.current = runningMessageId;
850
- const { name: toolDisplayName, info: toolInfo } = parseToolHeader(event.toolName, event.args);
851
- const runningContent = toolInfo ? `${toolDisplayName} (${toolInfo})` : toolDisplayName;
852
-
853
- setMessages((prev: Message[]) => {
854
- const newMessages = [...prev];
855
- newMessages.push({
856
- id: runningMessageId!,
857
- role: "tool",
858
- content: runningContent,
859
- toolName: event.toolName,
860
- toolArgs: event.args,
861
- success: true,
862
- isRunning: true,
863
- runningStartTime: Date.now()
864
- });
865
- return newMessages;
866
- });
867
- }
868
-
869
- pendingToolCalls.set(event.toolCallId, {
870
- toolName: event.toolName,
871
- args: event.args,
872
- messageId: runningMessageId
873
- });
874
-
875
- } else if (event.type === 'tool-result') {
876
- const pending = pendingToolCalls.get(event.toolCallId);
877
- const toolName = pending?.toolName ?? event.toolName;
878
- const toolArgs = pending?.args ?? {};
879
- const runningMessageId = pending?.messageId;
880
- pendingToolCalls.delete(event.toolCallId);
881
-
882
- if (toolName === 'explore') {
883
- exploreMessageIdRef.current = null;
884
- setExploreAbortController(null);
885
- }
886
-
887
- const { content: toolContent, success } = formatToolMessage(
888
- toolName,
889
- toolArgs,
890
- event.result,
891
- { maxLines: DEFAULT_MAX_TOOL_LINES }
892
- );
893
-
894
- const toolResultStr = typeof event.result === 'string' ? event.result : JSON.stringify(event.result);
895
- totalChars += toolResultStr.length;
896
- setCurrentTokens(estimateTokens());
897
-
898
- if (assistantChunk.trim()) {
899
- conversationSteps.push({
900
- type: 'assistant',
901
- content: assistantChunk,
902
- timestamp: Date.now()
903
- });
904
- }
905
-
906
- conversationSteps.push({
907
- type: 'tool',
908
- content: toolContent,
909
- toolName,
910
- toolArgs,
911
- toolResult: event.result,
912
- timestamp: Date.now()
913
- });
914
-
915
- setMessages((prev: Message[]) => {
916
- const newMessages = [...prev];
917
-
918
- let runningIndex = -1;
919
- if (runningMessageId) {
920
- runningIndex = newMessages.findIndex(m => m.id === runningMessageId);
921
- } else if (toolName === 'bash' || toolName === 'explore') {
922
- runningIndex = newMessages.findIndex(m => m.isRunning && m.toolName === toolName);
923
- }
924
-
925
- if (runningIndex !== -1) {
926
- newMessages[runningIndex] = {
927
- ...newMessages[runningIndex]!,
928
- content: toolContent,
929
- toolArgs: toolArgs,
930
- toolResult: event.result,
931
- success,
932
- isRunning: false,
933
- runningStartTime: undefined
934
- };
935
- return newMessages;
936
- }
937
-
938
- newMessages.push({
939
- id: createId(),
940
- role: "tool",
941
- content: toolContent,
942
- toolName,
943
- toolArgs: toolArgs,
944
- toolResult: event.result,
945
- success: success
946
- });
947
- return newMessages;
948
- });
949
-
950
- assistantChunk = '';
951
- assistantMessageId = null;
952
- } else if (event.type === 'error') {
953
- if (abortController.signal.aborted) {
954
- notifyAbort();
955
- streamHadError = true;
956
- break;
957
- }
958
- if (assistantChunk.trim()) {
959
- conversationSteps.push({
960
- type: 'assistant',
961
- content: assistantChunk,
962
- timestamp: Date.now()
963
- });
964
- }
965
-
966
- const errorContent = formatErrorMessage('API', event.error);
967
- conversationSteps.push({
968
- type: 'assistant',
969
- content: errorContent,
970
- timestamp: Date.now()
971
- });
972
-
973
- setMessages((prev: Message[]) => {
974
- const newMessages = [...prev];
975
- newMessages.push({
976
- id: createId(),
977
- role: 'assistant',
978
- content: errorContent,
979
- isError: true,
980
- });
981
- return newMessages;
982
- });
983
-
984
- assistantChunk = '';
985
- assistantMessageId = null;
986
- streamHadError = true;
987
- break;
988
- } else if (event.type === 'finish') {
989
- if (event.usage && event.usage.totalTokens > 0) {
990
- totalTokens = {
991
- prompt: event.usage.promptTokens,
992
- completion: event.usage.completionTokens,
993
- total: event.usage.totalTokens
994
- };
995
- setCurrentTokens(event.usage.totalTokens);
996
- }
997
- }
998
- }
999
-
1000
- if (abortController.signal.aborted) {
1001
- notifyAbort();
1002
- return;
1003
- }
1004
-
1005
- if (!streamHadError && assistantChunk.trim()) {
1006
- conversationSteps.push({
1007
- type: 'assistant',
1008
- content: assistantChunk,
1009
- timestamp: Date.now()
1010
- });
1011
- }
1012
-
1013
- const conversationData: ConversationHistory = {
1014
- id: conversationId,
1015
- timestamp: Date.now(),
1016
- steps: conversationSteps,
1017
- totalSteps: stepCount,
1018
- totalTokens: totalTokens.total > 0 ? totalTokens : undefined,
1019
- model: config.model,
1020
- provider: config.provider
1021
- };
1022
-
1023
- saveConversation(conversationData);
1024
-
1025
- } catch (error) {
1026
- if (abortController.signal.aborted) {
1027
- notifyAbort();
1028
- return;
1029
- }
1030
- const errorMessage = error instanceof Error ? error.message : 'An unknown error occurred';
1031
- const errorContent = formatErrorMessage('Mosaic', errorMessage);
1032
- setMessages((prev: Message[]) => {
1033
- const newMessages = [...prev];
1034
- if (newMessages[newMessages.length - 1]?.role === 'assistant' && newMessages[newMessages.length - 1]?.content === '') {
1035
- newMessages[newMessages.length - 1] = {
1036
- id: newMessages[newMessages.length - 1]!.id,
1037
- role: "assistant",
1038
- content: errorContent,
1039
- isError: true
1040
- };
1041
- } else {
1042
- newMessages.push({
1043
- id: createId(),
1044
- role: "assistant",
1045
- content: errorContent,
1046
- isError: true
1047
- });
1048
- }
1049
- return newMessages;
1050
- });
1051
- } finally {
1052
- if (abortControllerRef.current === abortController) {
1053
- abortControllerRef.current = null;
1054
- }
1055
- const duration = Date.now() - localStartTime;
1056
- if (duration >= 60000) {
1057
- const blendWord = BLEND_WORDS[Math.floor(Math.random() * BLEND_WORDS.length)];
1058
- setMessages((prev: Message[]) => {
1059
- const newMessages = [...prev];
1060
- for (let i = newMessages.length - 1; i >= 0; i--) {
1061
- if (newMessages[i]?.role === 'assistant') {
1062
- newMessages[i] = { ...newMessages[i]!, responseDuration: duration, blendWord };
1063
- break;
1064
- }
1065
- }
1066
- return newMessages;
1067
- });
1068
- }
1069
- setIsProcessing(false);
1070
- setProcessingStartTime(null);
1071
- }
1072
- };
1073
-
1074
- useEffect(() => {
1075
- if (initialMessage && !initialMessageProcessed.current && currentPage === "chat") {
1076
- initialMessageProcessed.current = true;
1077
- handleSubmit(initialMessage);
1078
- }
1079
- }, [initialMessage, currentPage, handleSubmit]);
1080
-
1081
- if (currentPage === "home") {
1082
- const handleHomeSubmit = (value: string, meta?: InputSubmitMeta) => {
1083
- const hasPastedContent = Boolean(meta?.isPaste && meta.pastedContent);
1084
- if (!value.trim() && !hasPastedContent) return;
1085
- setCurrentPage("chat");
1086
- handleSubmit(value, meta);
1087
- };
1088
-
1089
- return (
1090
- <HomePage
1091
- onSubmit={handleHomeSubmit}
1092
- pasteRequestId={pasteRequestId}
1093
- shortcutsOpen={shortcutsOpen}
1094
- />
1095
- );
1096
- }
1097
-
1098
- return (
1099
- <ChatPage
1100
- messages={messages}
1101
- isProcessing={isProcessing}
1102
- processingStartTime={processingStartTime}
1103
- currentTokens={currentTokens}
1104
- scrollOffset={scrollOffset}
1105
- terminalHeight={terminalHeight}
1106
- terminalWidth={terminalWidth}
1107
- pasteRequestId={pasteRequestId}
1108
- shortcutsOpen={shortcutsOpen}
1109
- onSubmit={handleSubmit}
1110
- />
1111
- );
1112
- }
1
+ import { useState, useEffect, useRef } from "react";
2
+ import type { ImagePart, TextPart, UserContent } from "ai";
3
+ import { useKeyboard } from "@opentui/react";
4
+ import { Agent } from "../agent";
5
+ import { saveConversation, addInputToHistory, type ConversationHistory, type ConversationStep } from "../utils/history";
6
+ import { readConfig } from "../utils/config";
7
+ import { DEFAULT_MAX_TOOL_LINES, formatToolMessage, formatErrorMessage, parseToolHeader } from '../utils/toolFormatting';
8
+ import { initializeCommands, isCommand, executeCommand } from '../utils/commands';
9
+ import type { InputSubmitMeta } from './CustomInput';
10
+
11
+ import { subscribeQuestion, type QuestionRequest } from "../utils/questionBridge";
12
+ import { subscribeApprovalAccepted } from "../utils/approvalBridge";
13
+ import { setExploreAbortController, setExploreToolCallback } from "../utils/exploreBridge";
14
+ import { getCurrentQuestion, cancelQuestion } from "../utils/questionBridge";
15
+ import { getCurrentApproval, cancelApproval } from "../utils/approvalBridge";
16
+ import { BLEND_WORDS, type MainProps, type Message } from "./main/types";
17
+ import { HomePage } from './main/HomePage';
18
+ import { ChatPage } from './main/ChatPage';
19
+ import type { ImageAttachment } from "../utils/images";
20
+ import { subscribeImageCommand, setImageSupport } from "../utils/imageBridge";
21
+ import { findModelsDevModelById, modelAcceptsImages, getModelsDevContextLimit } from "../utils/models";
22
+ import { DEFAULT_SYSTEM_PROMPT, processSystemPrompt } from "../agent/prompts/systemPrompt";
23
+ import { estimateTokensFromText, estimateTokensForContent, getDefaultContextBudget } from "../utils/tokenEstimator";
24
+
25
+ type CompactableMessage = Pick<Message, "role" | "content" | "thinkingContent" | "toolName">;
26
+
27
+ function extractTitle(content: string, alreadyResolved: boolean): { title: string | null; cleanContent: string; isPending: boolean; noTitle: boolean } {
28
+ const trimmed = content.trimStart();
29
+
30
+ const titleMatch = trimmed.match(/^<title>(.*?)<\/title>\s*/s);
31
+ if (titleMatch) {
32
+ const title = alreadyResolved ? null : (titleMatch[1]?.trim() || null);
33
+ const cleanContent = trimmed.replace(/^<title>.*?<\/title>\s*/s, '');
34
+ return { title, cleanContent, isPending: false, noTitle: false };
35
+ }
36
+
37
+ if (alreadyResolved) {
38
+ return { title: null, cleanContent: content, isPending: false, noTitle: false };
39
+ }
40
+
41
+ const partialTitlePattern = /^<(t(i(t(l(e(>.*)?)?)?)?)?)?$/i;
42
+ if (partialTitlePattern.test(trimmed) || (trimmed.startsWith('<title>') && !trimmed.includes('</title>'))) {
43
+ return { title: null, cleanContent: '', isPending: true, noTitle: false };
44
+ }
45
+
46
+ return { title: null, cleanContent: content, isPending: false, noTitle: true };
47
+ }
48
+
49
+ function setTerminalTitle(title: string) {
50
+ process.title = `⁘ ${title}`;
51
+ }
52
+
53
+ export function normalizeWhitespace(text: string): string {
54
+ return text.replace(/\s+/g, " ").trim();
55
+ }
56
+
57
+ export function truncateText(text: string, maxChars: number): string {
58
+ if (text.length <= maxChars) return text;
59
+ return text.slice(0, Math.max(0, maxChars - 3)) + "...";
60
+ }
61
+
62
+ export function estimateTokensForMessage(message: CompactableMessage): number {
63
+ return estimateTokensForContent(message.content || "", message.thinkingContent || undefined);
64
+ }
65
+
66
+ export function estimateTokensForMessages(messages: CompactableMessage[]): number {
67
+ return messages.reduce((sum, message) => sum + estimateTokensForMessage(message), 0);
68
+ }
69
+
70
+ export function estimateTotalTokens(messages: CompactableMessage[], systemPrompt: string): number {
71
+ const systemTokens = estimateTokensFromText(systemPrompt) + 8;
72
+ return systemTokens + estimateTokensForMessages(messages);
73
+ }
74
+
75
+ export function shouldAutoCompact(totalTokens: number, maxContextTokens: number): boolean {
76
+ if (!Number.isFinite(maxContextTokens) || maxContextTokens <= 0) return false;
77
+ const threshold = Math.floor(maxContextTokens * 0.95);
78
+ return totalTokens >= threshold;
79
+ }
80
+
81
+ export function summarizeMessage(message: CompactableMessage, isLastUser: boolean): string {
82
+ if (message.role === "tool") {
83
+ const name = message.toolName || "tool";
84
+ const text = message.content || "";
85
+ const isError = text.toLowerCase().includes('error') || text.toLowerCase().includes('failed');
86
+ const status = isError ? 'FAILED' : 'OK';
87
+ const cleaned = normalizeWhitespace(text);
88
+ return `[tool:${name} ${status}] ${truncateText(cleaned, 120)}`;
89
+ }
90
+
91
+ if (message.role === "assistant") {
92
+ const cleaned = normalizeWhitespace(message.content || "");
93
+ const sentenceMatch = cleaned.match(/^[^.!?\n]{10,}[.!?]/);
94
+ const summary = sentenceMatch ? sentenceMatch[0] : cleaned;
95
+ return `assistant: ${truncateText(summary, 200)}`;
96
+ }
97
+
98
+ const cleaned = normalizeWhitespace(message.content || "");
99
+ const limit = isLastUser ? cleaned.length : 400;
100
+ return `user: ${truncateText(cleaned, limit)}`;
101
+ }
102
+
103
+ export function buildSummary(messages: CompactableMessage[], maxTokens: number): string {
104
+ const maxChars = Math.max(0, maxTokens * 3);
105
+ const header = "Résumé de conversation (compact):";
106
+ let charCount = header.length + 1;
107
+ const lines: string[] = [];
108
+
109
+ let lastUserIndex = -1;
110
+ for (let i = messages.length - 1; i >= 0; i--) {
111
+ if (messages[i]!.role === 'user') { lastUserIndex = i; break; }
112
+ }
113
+
114
+ for (let i = 0; i < messages.length; i++) {
115
+ if (charCount >= maxChars) break;
116
+ const line = `- ${summarizeMessage(messages[i]!, i === lastUserIndex)}`;
117
+ charCount += line.length + 1;
118
+ lines.push(line);
119
+ }
120
+ const body = lines.join("\n");
121
+ const full = `${header}\n${body}`.trim();
122
+ return truncateText(full, maxChars);
123
+ }
124
+
125
+ export function collectContextFiles(messages: Message[]): string[] {
126
+ const files = new Set<string>();
127
+ for (const message of messages) {
128
+ if (message.role !== "tool") continue;
129
+ if (!message.toolArgs) continue;
130
+ const toolName = message.toolName || "";
131
+ if (!["read", "write", "edit", "list", "grep"].includes(toolName)) continue;
132
+ const path = message.toolArgs.path;
133
+ if (typeof path === "string" && path.trim()) {
134
+ files.add(path.trim());
135
+ }
136
+ const pattern = message.toolArgs.pattern;
137
+ if (toolName === "grep" && typeof pattern === "string" && pattern.trim()) {
138
+ files.add(pattern.trim());
139
+ }
140
+ }
141
+ return Array.from(files.values()).sort((a, b) => a.localeCompare(b));
142
+ }
143
+
144
+ export function appendContextFiles(summary: string, files: string[], maxTokens: number): string {
145
+ if (files.length === 0) return summary;
146
+ const maxChars = Math.max(0, maxTokens * 4);
147
+ const list = files.map(f => `- ${f}`).join("\n");
148
+ const block = `\n\nFichiers conservés après compaction:\n${list}`;
149
+ return truncateText(`${summary}${block}`, maxChars);
150
+ }
151
+
152
+ export function compactMessagesForUi(
153
+ messages: Message[],
154
+ systemPrompt: string,
155
+ maxContextTokens: number,
156
+ createId: () => string,
157
+ summaryOnly: boolean
158
+ ): { messages: Message[]; estimatedTokens: number; didCompact: boolean } {
159
+ const systemTokens = estimateTokensFromText(systemPrompt) + 8;
160
+ const totalTokens = systemTokens + estimateTokensForMessages(messages);
161
+ if (totalTokens <= maxContextTokens && !summaryOnly) {
162
+ return { messages, estimatedTokens: totalTokens - systemTokens, didCompact: false };
163
+ }
164
+
165
+ const summaryTokens = Math.min(2000, Math.max(400, Math.floor(maxContextTokens * 0.2)));
166
+ const recentBudget = Math.max(500, maxContextTokens - summaryTokens);
167
+
168
+ let recentTokens = 0;
169
+ const recent: Message[] = [];
170
+ for (let i = messages.length - 1; i >= 0; i--) {
171
+ const message = messages[i]!;
172
+ const msgTokens = estimateTokensForMessage(message);
173
+ if (recentTokens + msgTokens > recentBudget && recent.length > 0) break;
174
+ recent.unshift(message);
175
+ recentTokens += msgTokens;
176
+ }
177
+
178
+ const cutoff = messages.length - recent.length;
179
+ const older = cutoff > 0 ? messages.slice(0, cutoff) : [];
180
+ const files = collectContextFiles(messages);
181
+ const summaryBase = buildSummary(summaryOnly ? messages : (older.length > 0 ? older : messages), summaryTokens);
182
+ const summary = appendContextFiles(summaryBase, files, summaryTokens);
183
+ const summaryMessage: Message = {
184
+ id: createId(),
185
+ role: "assistant",
186
+ content: summary
187
+ };
188
+
189
+ const nextMessages = summaryOnly ? [summaryMessage] : [summaryMessage, ...recent];
190
+ const estimatedTokens = estimateTokensForMessages(nextMessages);
191
+ return { messages: nextMessages, estimatedTokens, didCompact: true };
192
+ }
193
+
194
+ export function Main({ pasteRequestId = 0, copyRequestId = 0, onCopy, shortcutsOpen = false, commandsOpen = false, initialMessage }: MainProps) {
195
+ const [currentPage, setCurrentPage] = useState<"home" | "chat">(initialMessage ? "chat" : "home");
196
+ const [messages, setMessages] = useState<Message[]>([]);
197
+ const [isProcessing, setIsProcessing] = useState(false);
198
+ const [processingStartTime, setProcessingStartTime] = useState<number | null>(null);
199
+ const [currentTokens, setCurrentTokens] = useState(0);
200
+ const [scrollOffset, setScrollOffset] = useState(0);
201
+ const [terminalHeight, setTerminalHeight] = useState(process.stdout.rows || 24);
202
+ const [terminalWidth, setTerminalWidth] = useState(process.stdout.columns || 80);
203
+ const [questionRequest, setQuestionRequest] = useState<QuestionRequest | null>(null);
204
+ const [currentTitle, setCurrentTitle] = useState<string | null>(null);
205
+ const [pendingImages, setPendingImages] = useState<ImageAttachment[]>([]);
206
+ const [imagesSupported, setImagesSupported] = useState(false);
207
+ const currentTitleRef = useRef<string | null>(null);
208
+ const titleExtractedRef = useRef(false);
209
+ const shouldAutoScroll = useRef(true);
210
+ const abortControllerRef = useRef<AbortController | null>(null);
211
+ const currentPageRef = useRef(currentPage);
212
+ const shortcutsOpenRef = useRef(shortcutsOpen);
213
+ const commandsOpenRef = useRef(commandsOpen);
214
+ const questionRequestRef = useRef<QuestionRequest | null>(questionRequest);
215
+ const initialMessageProcessed = useRef(false);
216
+ const lastPromptTokensRef = useRef<number>(0);
217
+ const exploreMessageIdRef = useRef<string | null>(null);
218
+ const exploreToolsRef = useRef<Array<{ tool: string; info: string; success: boolean }>>([]);
219
+ const explorePurposeRef = useRef<string>('');
220
+
221
+ const createId = () => `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
222
+
223
+ useEffect(() => {
224
+ initializeCommands();
225
+ }, []);
226
+
227
+ useEffect(() => {
228
+ const loadSupport = async () => {
229
+ const config = readConfig();
230
+ if (!config.model) {
231
+ setImagesSupported(false);
232
+ setImageSupport(false);
233
+ return;
234
+ }
235
+ try {
236
+ const result = await findModelsDevModelById(config.model);
237
+ const supported = Boolean(result && result.model && modelAcceptsImages(result.model));
238
+ setImagesSupported(supported);
239
+ setImageSupport(supported);
240
+ } catch {
241
+ setImagesSupported(false);
242
+ setImageSupport(false);
243
+ }
244
+ };
245
+ loadSupport();
246
+ }, []);
247
+
248
+ useEffect(() => {
249
+ let lastExploreTokens = 0;
250
+ setExploreToolCallback((toolName, args, result, totalTokens) => {
251
+ const info = (args.path || args.pattern || args.query || '') as string;
252
+ const shortInfo = info.length > 40 ? info.substring(0, 37) + '...' : info;
253
+ exploreToolsRef.current.push({ tool: toolName, info: shortInfo, success: result.success });
254
+
255
+ const tokenDelta = totalTokens - lastExploreTokens;
256
+ lastExploreTokens = totalTokens;
257
+ if (tokenDelta > 0) {
258
+ setCurrentTokens(prev => prev + tokenDelta);
259
+ }
260
+
261
+ if (exploreMessageIdRef.current) {
262
+ setMessages((prev: Message[]) => {
263
+ const newMessages = [...prev];
264
+ const idx = newMessages.findIndex(m => m.id === exploreMessageIdRef.current);
265
+ if (idx !== -1) {
266
+ const toolLines = exploreToolsRef.current.map(t => {
267
+ const icon = t.success ? '→' : '-';
268
+ return ` ${icon} ${t.tool}(${t.info})`;
269
+ });
270
+ const purpose = explorePurposeRef.current;
271
+ const newContent = `Explore (${purpose})\n${toolLines.join('\n')}`;
272
+ newMessages[idx] = { ...newMessages[idx]!, content: newContent };
273
+ }
274
+ return newMessages;
275
+ });
276
+ }
277
+ });
278
+
279
+ return () => {
280
+ setExploreToolCallback(null);
281
+ };
282
+ }, []);
283
+
284
+ useEffect(() => {
285
+ return subscribeImageCommand((event) => {
286
+ if (event.type === "clear") {
287
+ setPendingImages([]);
288
+ return;
289
+ }
290
+ if (event.type === "remove") {
291
+ setPendingImages((prev) => prev.filter((img) => img.id !== event.id));
292
+ return;
293
+ }
294
+ if (!imagesSupported) return;
295
+ setPendingImages((prev) => [...prev, event.image]);
296
+ });
297
+ }, [imagesSupported]);
298
+
299
+ useEffect(() => {
300
+ if (!imagesSupported) {
301
+ setPendingImages([]);
302
+ }
303
+ }, [imagesSupported]);
304
+
305
+ useEffect(() => {
306
+ const handleResize = () => {
307
+ const newWidth = process.stdout.columns || 80;
308
+ const newHeight = process.stdout.rows || 24;
309
+ const oldHeight = terminalHeight;
310
+
311
+ setTerminalWidth(newWidth);
312
+ setTerminalHeight(newHeight);
313
+
314
+ if (shouldAutoScroll.current) {
315
+ setScrollOffset(0);
316
+ } else if (oldHeight !== newHeight) {
317
+ const heightDiff = newHeight - oldHeight;
318
+ setScrollOffset(prev => Math.max(0, prev - heightDiff));
319
+ }
320
+ };
321
+ process.stdout.on('resize', handleResize);
322
+ return () => {
323
+ process.stdout.off('resize', handleResize);
324
+ };
325
+ }, [terminalWidth, terminalHeight]);
326
+
327
+ useEffect(() => {
328
+ return subscribeQuestion(setQuestionRequest);
329
+ }, []);
330
+
331
+ useEffect(() => {
332
+ return subscribeApprovalAccepted((accepted) => {
333
+ const isBashTool = accepted.toolName === 'bash';
334
+
335
+ if (isBashTool) {
336
+ const { name: toolDisplayName, info: toolInfo } = parseToolHeader(accepted.toolName, accepted.args);
337
+ const runningContent = toolInfo ? `${toolDisplayName} (${toolInfo})` : toolDisplayName;
338
+
339
+ setMessages((prev: Message[]) => {
340
+ const newMessages = [...prev];
341
+ newMessages.push({
342
+ id: createId(),
343
+ role: "tool",
344
+ content: runningContent,
345
+ toolName: accepted.toolName,
346
+ toolArgs: accepted.args,
347
+ success: true,
348
+ isRunning: true,
349
+ runningStartTime: Date.now()
350
+ });
351
+ return newMessages;
352
+ });
353
+ }
354
+ });
355
+ }, []);
356
+
357
+ useEffect(() => {
358
+ currentPageRef.current = currentPage;
359
+ }, [currentPage]);
360
+
361
+ useEffect(() => {
362
+ shortcutsOpenRef.current = shortcutsOpen;
363
+ }, [shortcutsOpen]);
364
+
365
+ useEffect(() => {
366
+ commandsOpenRef.current = commandsOpen;
367
+ }, [commandsOpen]);
368
+
369
+ useEffect(() => {
370
+ questionRequestRef.current = questionRequest;
371
+ }, [questionRequest]);
372
+
373
+ useEffect(() => {
374
+ if (questionRequest) {
375
+ shouldAutoScroll.current = true;
376
+ setScrollOffset(0);
377
+ }
378
+ }, [questionRequest]);
379
+
380
+ useEffect(() => {
381
+ if (currentPage !== "chat") return;
382
+
383
+ process.stdin.setRawMode(true);
384
+ process.stdout.write('\x1b[?1000h');
385
+ process.stdout.write('\x1b[?1003h');
386
+ process.stdout.write('\x1b[?1006h');
387
+
388
+ const handleData = (data: Buffer) => {
389
+ const str = data.toString();
390
+
391
+ if (str.match(/\x1b\[<(\d+);(\d+);(\d+)([mM])/)) {
392
+ const match = str.match(/\x1b\[<(\d+);(\d+);(\d+)([mM])/);
393
+ if (match) {
394
+ const button = parseInt(match[1] || '0');
395
+
396
+ if (button === 64) {
397
+ shouldAutoScroll.current = false;
398
+ setScrollOffset((prev) => prev + 1);
399
+ } else if (button === 65) {
400
+ setScrollOffset((prev) => {
401
+ const newOffset = Math.max(0, prev - 1);
402
+ if (newOffset === 0) {
403
+ shouldAutoScroll.current = true;
404
+ }
405
+ return newOffset;
406
+ });
407
+ }
408
+ }
409
+ }
410
+ };
411
+
412
+ process.stdin.on('data', handleData);
413
+
414
+ return () => {
415
+ process.stdin.off('data', handleData);
416
+ process.stdout.write('\x1b[?1000l');
417
+ process.stdout.write('\x1b[?1003l');
418
+ process.stdout.write('\x1b[?1006l');
419
+ };
420
+ }, [currentPage]);
421
+
422
+ useEffect(() => {
423
+ if (currentPage === "chat") {
424
+ setScrollOffset((prevOffset) => {
425
+ if (shouldAutoScroll.current || prevOffset < 5) {
426
+ shouldAutoScroll.current = true;
427
+ return 0;
428
+ }
429
+ return prevOffset;
430
+ });
431
+ }
432
+ }, [messages, currentPage]);
433
+
434
+ useEffect(() => {
435
+ if (copyRequestId > 0 && onCopy && messages.length > 0) {
436
+ const lastAssistantMessage = messages.slice().reverse().find(m => m.role === 'assistant');
437
+ if (lastAssistantMessage) {
438
+ onCopy(lastAssistantMessage.content);
439
+ }
440
+ }
441
+ }, [copyRequestId, onCopy, messages]);
442
+
443
+ useKeyboard((key) => {
444
+ if ((key.name === 'c' && key.ctrl) || key.sequence === '\x03') {
445
+ if (getCurrentQuestion()) {
446
+ cancelQuestion();
447
+ }
448
+ if (getCurrentApproval()) {
449
+ cancelApproval();
450
+ }
451
+ abortControllerRef.current?.abort();
452
+ return;
453
+ }
454
+
455
+ if (key.name === 'escape') {
456
+ if (getCurrentQuestion()) {
457
+ cancelQuestion();
458
+ }
459
+ if (getCurrentApproval()) {
460
+ cancelApproval();
461
+ }
462
+ abortControllerRef.current?.abort();
463
+ return;
464
+ }
465
+ });
466
+
467
+ const buildUserContent = (text: string, images?: ImageAttachment[]): UserContent => {
468
+ if (!images || images.length === 0) return text;
469
+ const parts: Array<TextPart | ImagePart> = [];
470
+ parts.push({ type: "text", text });
471
+ for (const img of images) {
472
+ parts.push({ type: "image", image: img.data, mimeType: img.mimeType });
473
+ }
474
+ return parts;
475
+ };
476
+
477
+ const buildConversationHistory = (base: Message[], includeImages: boolean) => {
478
+ return base
479
+ .filter((m): m is Message & { role: "user" | "assistant" } => m.role === "user" || m.role === "assistant")
480
+ .map((m) => {
481
+ if (m.role === "user") {
482
+ const content = includeImages ? buildUserContent(m.content, m.images) : m.content;
483
+ return { role: "user" as const, content };
484
+ }
485
+ return { role: "assistant" as const, content: m.content };
486
+ });
487
+ };
488
+
489
+ const handleSubmit = async (value: string, meta?: InputSubmitMeta) => {
490
+ if (isProcessing) return;
491
+
492
+ const hasPastedContent = Boolean(meta?.isPaste && meta.pastedContent);
493
+ const hasImages = imagesSupported && pendingImages.length > 0;
494
+ if (!value.trim() && !hasPastedContent && !hasImages) return;
495
+
496
+ if (isCommand(value)) {
497
+ const result = await executeCommand(value);
498
+ if (result) {
499
+ if (result.shouldClearMessages === true) {
500
+ const commandMessage: Message = {
501
+ id: createId(),
502
+ role: "slash",
503
+ content: result.content,
504
+ isError: !result.success
505
+ };
506
+ setMessages([commandMessage]);
507
+ return;
508
+ }
509
+
510
+ if (result.shouldCompactMessages === true) {
511
+ const config = readConfig();
512
+ const rawSystemPrompt = config.systemPrompt || DEFAULT_SYSTEM_PROMPT;
513
+ const systemPrompt = processSystemPrompt(rawSystemPrompt, true);
514
+ let maxContextTokens = result.compactMaxTokens ?? config.maxContextTokens;
515
+ if (!maxContextTokens && config.provider && config.model) {
516
+ const resolved = await getModelsDevContextLimit(config.provider, config.model);
517
+ if (typeof resolved === "number") {
518
+ maxContextTokens = resolved;
519
+ }
520
+ }
521
+ const targetTokens = maxContextTokens ?? getDefaultContextBudget(config.provider);
522
+ let nextTokens = currentTokens;
523
+ setMessages(prev => {
524
+ const compacted = compactMessagesForUi(prev, systemPrompt, targetTokens, createId, true);
525
+ nextTokens = compacted.estimatedTokens;
526
+ return compacted.messages;
527
+ });
528
+ setCurrentTokens(nextTokens);
529
+ return;
530
+ }
531
+
532
+ if (result.shouldAddToHistory === true) {
533
+ addInputToHistory(value.trim());
534
+
535
+ const userMessage: Message = {
536
+ id: createId(),
537
+ role: "user",
538
+ content: result.content,
539
+ displayContent: value,
540
+ };
541
+
542
+ setMessages((prev: Message[]) => [...prev, userMessage]);
543
+ setIsProcessing(true);
544
+ const localStartTime = Date.now();
545
+ setProcessingStartTime(localStartTime);
546
+ setCurrentTokens(0);
547
+ lastPromptTokensRef.current = 0;
548
+ shouldAutoScroll.current = true;
549
+
550
+ const conversationId = createId();
551
+ const conversationSteps: ConversationStep[] = [];
552
+ let totalTokens = { prompt: 0, completion: 0, total: 0 };
553
+ let stepCount = 0;
554
+ let totalChars = 0;
555
+ for (const m of messages) {
556
+ if (m.role === 'assistant') {
557
+ totalChars += m.content.length;
558
+ if (m.thinkingContent) totalChars += m.thinkingContent.length;
559
+ } else if (m.role === 'tool') {
560
+ totalChars += m.content.length;
561
+ }
562
+ }
563
+
564
+ const estimateTokens = () => Math.ceil(totalChars / 4);
565
+ setCurrentTokens(estimateTokens());
566
+ const config = readConfig();
567
+ const abortController = new AbortController();
568
+ abortControllerRef.current = abortController;
569
+ let abortNotified = false;
570
+ const notifyAbort = () => {
571
+ if (abortNotified) return;
572
+ abortNotified = true;
573
+ setMessages((prev: Message[]) => {
574
+ const newMessages = [...prev];
575
+ newMessages.push({
576
+ id: createId(),
577
+ role: "tool",
578
+ success: false,
579
+ content: "Request interrupted by user. \n↪ What should Mosaic do instead?"
580
+ });
581
+ return newMessages;
582
+ });
583
+ };
584
+
585
+ conversationSteps.push({
586
+ type: 'user',
587
+ content: result.content,
588
+ timestamp: Date.now()
589
+ });
590
+
591
+ let responseDuration: number | null = null;
592
+ let responseBlendWord: string | undefined = undefined;
593
+
594
+ try {
595
+ const providerStatus = await Agent.ensureProviderReady();
596
+ if (!providerStatus.ready) {
597
+ setMessages((prev: Message[]) => {
598
+ const newMessages = [...prev];
599
+ newMessages.push({
600
+ id: createId(),
601
+ role: "assistant",
602
+ content: `Ollama error: ${providerStatus.error || 'Could not start Ollama. Make sure Ollama is installed.'}`,
603
+ isError: true
604
+ });
605
+ return newMessages;
606
+ });
607
+ setIsProcessing(false);
608
+ return;
609
+ }
610
+
611
+ const agent = new Agent();
612
+ const conversationHistory = buildConversationHistory([...messages, userMessage], imagesSupported);
613
+ let assistantChunk = '';
614
+ let thinkingChunk = '';
615
+ const pendingToolCalls = new Map<string, { toolName: string; args: Record<string, unknown>; messageId?: string }>();
616
+ let assistantMessageId: string | null = null;
617
+ let streamHadError = false;
618
+ titleExtractedRef.current = false;
619
+
620
+ for await (const event of agent.streamMessages(conversationHistory, { abortSignal: abortController.signal })) {
621
+ if (event.type === 'reasoning-delta') {
622
+ thinkingChunk += event.content;
623
+ totalChars += event.content.length;
624
+ setCurrentTokens(estimateTokens());
625
+
626
+ if (assistantMessageId === null) {
627
+ assistantMessageId = createId();
628
+ }
629
+
630
+ const currentMessageId = assistantMessageId;
631
+ setMessages((prev: Message[]) => {
632
+ const newMessages = [...prev];
633
+ const messageIndex = newMessages.findIndex(m => m.id === currentMessageId);
634
+
635
+ if (messageIndex === -1) {
636
+ newMessages.push({ id: currentMessageId, role: "assistant", content: '', thinkingContent: thinkingChunk });
637
+ } else {
638
+ newMessages[messageIndex] = {
639
+ ...newMessages[messageIndex]!,
640
+ thinkingContent: thinkingChunk
641
+ };
642
+ }
643
+ return newMessages;
644
+ });
645
+ } else if (event.type === 'text-delta') {
646
+ assistantChunk += event.content;
647
+ totalChars += event.content.length;
648
+ setCurrentTokens(estimateTokens());
649
+
650
+ const { title, cleanContent, isPending, noTitle } = extractTitle(assistantChunk, titleExtractedRef.current);
651
+
652
+ if (title) {
653
+ titleExtractedRef.current = true;
654
+ currentTitleRef.current = title;
655
+ setCurrentTitle(title);
656
+ setTerminalTitle(title);
657
+ } else if (noTitle) {
658
+ titleExtractedRef.current = true;
659
+ }
660
+
661
+ if (isPending) continue;
662
+
663
+ if (assistantMessageId === null) {
664
+ assistantMessageId = createId();
665
+ }
666
+
667
+ const displayContent = cleanContent;
668
+ const currentMessageId = assistantMessageId;
669
+ setMessages((prev: Message[]) => {
670
+ const newMessages = [...prev];
671
+ const messageIndex = newMessages.findIndex(m => m.id === currentMessageId);
672
+
673
+ if (messageIndex === -1) {
674
+ newMessages.push({ id: currentMessageId, role: "assistant", content: displayContent, thinkingContent: thinkingChunk });
675
+ } else {
676
+ newMessages[messageIndex] = {
677
+ ...newMessages[messageIndex]!,
678
+ content: displayContent
679
+ };
680
+ }
681
+ return newMessages;
682
+ });
683
+ } else if (event.type === 'step-start') {
684
+ stepCount++;
685
+ } else if (event.type === 'tool-call-end') {
686
+ totalChars += JSON.stringify(event.args).length;
687
+ setCurrentTokens(estimateTokens());
688
+
689
+ const needsApproval = event.toolName === 'write' || event.toolName === 'edit' || event.toolName === 'bash';
690
+ const isExploreTool = event.toolName === 'explore';
691
+ const showRunning = event.toolName === 'bash';
692
+ let runningMessageId: string | undefined;
693
+
694
+ if (isExploreTool) {
695
+ setExploreAbortController(abortController);
696
+ exploreToolsRef.current = [];
697
+ const purpose = (event.args.purpose as string) || 'exploring...';
698
+ explorePurposeRef.current = purpose;
699
+ }
700
+
701
+ if (!needsApproval) {
702
+ runningMessageId = createId();
703
+ const { name: toolDisplayName, info: toolInfo } = parseToolHeader(event.toolName, event.args);
704
+ const runningContent = toolInfo ? `${toolDisplayName} (${toolInfo})` : toolDisplayName;
705
+
706
+ if (isExploreTool) {
707
+ exploreMessageIdRef.current = runningMessageId;
708
+ }
709
+
710
+ setMessages((prev: Message[]) => {
711
+ const newMessages = [...prev];
712
+ newMessages.push({
713
+ id: runningMessageId!,
714
+ role: "tool",
715
+ content: runningContent,
716
+ toolName: event.toolName,
717
+ toolArgs: event.args,
718
+ success: true,
719
+ isRunning: showRunning || isExploreTool,
720
+ runningStartTime: (showRunning || isExploreTool) ? Date.now() : undefined
721
+ });
722
+ return newMessages;
723
+ });
724
+ }
725
+
726
+ pendingToolCalls.set(event.toolCallId, {
727
+ toolName: event.toolName,
728
+ args: event.args,
729
+ messageId: runningMessageId
730
+ });
731
+
732
+ } else if (event.type === 'tool-result') {
733
+ const pending = pendingToolCalls.get(event.toolCallId);
734
+ const toolName = pending?.toolName ?? event.toolName;
735
+ const toolArgs = pending?.args ?? {};
736
+ const runningMessageId = pending?.messageId;
737
+ pendingToolCalls.delete(event.toolCallId);
738
+
739
+ if (toolName === 'explore') {
740
+ exploreMessageIdRef.current = null;
741
+ setExploreAbortController(null);
742
+ }
743
+
744
+ const { content: toolContent, success } = formatToolMessage(
745
+ toolName,
746
+ toolArgs,
747
+ event.result,
748
+ { maxLines: DEFAULT_MAX_TOOL_LINES }
749
+ );
750
+
751
+ const toolResultStr = typeof event.result === 'string' ? event.result : JSON.stringify(event.result);
752
+ totalChars += toolResultStr.length;
753
+ setCurrentTokens(estimateTokens());
754
+
755
+ if (assistantChunk.trim()) {
756
+ conversationSteps.push({
757
+ type: 'assistant',
758
+ content: assistantChunk,
759
+ timestamp: Date.now()
760
+ });
761
+ }
762
+
763
+ conversationSteps.push({
764
+ type: 'tool',
765
+ content: toolContent,
766
+ toolName,
767
+ toolArgs,
768
+ toolResult: event.result,
769
+ timestamp: Date.now()
770
+ });
771
+
772
+ setMessages((prev: Message[]) => {
773
+ const newMessages = [...prev];
774
+
775
+ let runningIndex = -1;
776
+ if (runningMessageId) {
777
+ runningIndex = newMessages.findIndex(m => m.id === runningMessageId);
778
+ } else if (toolName === 'bash' || toolName === 'explore') {
779
+ runningIndex = newMessages.findIndex(m => m.toolName === toolName && m.isRunning === true);
780
+ }
781
+
782
+ if (runningIndex !== -1) {
783
+ newMessages[runningIndex] = {
784
+ ...newMessages[runningIndex]!,
785
+ content: toolContent,
786
+ toolArgs: toolArgs,
787
+ toolResult: event.result,
788
+ success,
789
+ isRunning: false,
790
+ runningStartTime: undefined,
791
+ timestamp: Date.now()
792
+ };
793
+ return newMessages;
794
+ }
795
+
796
+ newMessages.push({
797
+ id: createId(),
798
+ role: "tool",
799
+ content: toolContent,
800
+ toolName,
801
+ toolArgs: toolArgs,
802
+ toolResult: event.result,
803
+ success: success,
804
+ timestamp: Date.now()
805
+ });
806
+ return newMessages;
807
+ });
808
+
809
+ assistantChunk = '';
810
+ assistantMessageId = null;
811
+ } else if (event.type === 'error') {
812
+ if (abortController.signal.aborted) {
813
+ notifyAbort();
814
+ streamHadError = true;
815
+ break;
816
+ }
817
+ if (assistantChunk.trim()) {
818
+ conversationSteps.push({
819
+ type: 'assistant',
820
+ content: assistantChunk,
821
+ timestamp: Date.now()
822
+ });
823
+ }
824
+
825
+ const errorContent = formatErrorMessage('API', event.error);
826
+ conversationSteps.push({
827
+ type: 'assistant',
828
+ content: errorContent,
829
+ timestamp: Date.now()
830
+ });
831
+
832
+ setMessages((prev: Message[]) => {
833
+ const newMessages = [...prev];
834
+ newMessages.push({
835
+ id: createId(),
836
+ role: 'assistant',
837
+ content: errorContent,
838
+ isError: true,
839
+ });
840
+ return newMessages;
841
+ });
842
+
843
+ assistantChunk = '';
844
+ assistantMessageId = null;
845
+ streamHadError = true;
846
+ break;
847
+ } else if (event.type === 'finish') {
848
+ if (event.usage && event.usage.totalTokens > 0) {
849
+ totalTokens = {
850
+ prompt: event.usage.promptTokens,
851
+ completion: event.usage.completionTokens,
852
+ total: event.usage.totalTokens
853
+ };
854
+ lastPromptTokensRef.current = event.usage.promptTokens;
855
+ setCurrentTokens(event.usage.totalTokens);
856
+ }
857
+ }
858
+ }
859
+
860
+ if (abortController.signal.aborted) {
861
+ notifyAbort();
862
+ return;
863
+ }
864
+
865
+ if (!streamHadError && assistantChunk.trim()) {
866
+ conversationSteps.push({
867
+ type: 'assistant',
868
+ content: assistantChunk,
869
+ timestamp: Date.now()
870
+ });
871
+ }
872
+
873
+ responseDuration = Date.now() - localStartTime;
874
+ if (responseDuration >= 60000) {
875
+ responseBlendWord = BLEND_WORDS[Math.floor(Math.random() * BLEND_WORDS.length)];
876
+ for (let i = conversationSteps.length - 1; i >= 0; i--) {
877
+ if (conversationSteps[i]?.type === 'assistant') {
878
+ conversationSteps[i] = {
879
+ ...conversationSteps[i]!,
880
+ responseDuration,
881
+ blendWord: responseBlendWord
882
+ };
883
+ break;
884
+ }
885
+ }
886
+ }
887
+
888
+ const conversationData: ConversationHistory = {
889
+ id: conversationId,
890
+ timestamp: Date.now(),
891
+ steps: conversationSteps,
892
+ totalSteps: stepCount,
893
+ title: currentTitleRef.current ?? currentTitle ?? null,
894
+ workspace: process.cwd(),
895
+ totalTokens: totalTokens.total > 0 ? totalTokens : undefined,
896
+ model: config.model,
897
+ provider: config.provider
898
+ };
899
+
900
+ saveConversation(conversationData);
901
+
902
+ } catch (error) {
903
+ if (abortController.signal.aborted) {
904
+ notifyAbort();
905
+ return;
906
+ }
907
+ const errorMessage = error instanceof Error ? error.message : 'An unknown error occurred';
908
+ const errorContent = formatErrorMessage('Mosaic', errorMessage);
909
+ setMessages((prev: Message[]) => {
910
+ const newMessages = [...prev];
911
+ if (newMessages[newMessages.length - 1]?.role === 'assistant' && newMessages[newMessages.length - 1]?.content === '') {
912
+ newMessages[newMessages.length - 1] = {
913
+ id: newMessages[newMessages.length - 1]!.id,
914
+ role: "assistant",
915
+ content: errorContent,
916
+ isError: true
917
+ };
918
+ } else {
919
+ newMessages.push({
920
+ id: createId(),
921
+ role: "assistant",
922
+ content: errorContent,
923
+ isError: true
924
+ });
925
+ }
926
+ return newMessages;
927
+ });
928
+ } finally {
929
+ if (abortControllerRef.current === abortController) {
930
+ abortControllerRef.current = null;
931
+ }
932
+ const duration = responseDuration ?? (Date.now() - localStartTime);
933
+ if (duration >= 60000) {
934
+ const blendWord = responseBlendWord ?? BLEND_WORDS[Math.floor(Math.random() * BLEND_WORDS.length)];
935
+ setMessages((prev: Message[]) => {
936
+ const newMessages = [...prev];
937
+ for (let i = newMessages.length - 1; i >= 0; i--) {
938
+ if (newMessages[i]?.role === 'assistant') {
939
+ newMessages[i] = { ...newMessages[i]!, responseDuration: duration, blendWord };
940
+ break;
941
+ }
942
+ }
943
+ return newMessages;
944
+ });
945
+ }
946
+ setIsProcessing(false);
947
+ setProcessingStartTime(null);
948
+ }
949
+
950
+ return;
951
+ }
952
+
953
+ const commandMessage: Message = {
954
+ id: createId(),
955
+ role: "slash",
956
+ content: result.content,
957
+ isError: !result.success
958
+ };
959
+
960
+ setMessages((prev: Message[]) => [...prev, commandMessage]);
961
+
962
+ if (result.shouldAddToHistory !== false) {
963
+ addInputToHistory(value.trim());
964
+ }
965
+
966
+ return;
967
+ }
968
+ }
969
+
970
+ const composedContent = hasPastedContent
971
+ ? `${meta!.pastedContent!}${value.trim() ? `\n\n${value}` : ''}`
972
+ : value;
973
+
974
+ addInputToHistory(value.trim() || (hasPastedContent ? '[Pasted text]' : (hasImages ? '[Image]' : value)));
975
+
976
+ const imagesForMessage = imagesSupported ? pendingImages : [];
977
+
978
+ const userMessage: Message = {
979
+ id: createId(),
980
+ role: "user",
981
+ content: composedContent,
982
+ displayContent: meta?.isPaste ? '[Pasted text]' : undefined,
983
+ images: imagesForMessage.length > 0 ? imagesForMessage : undefined,
984
+ };
985
+
986
+ if (imagesForMessage.length > 0) {
987
+ setPendingImages([]);
988
+ }
989
+
990
+ setMessages((prev: Message[]) => [...prev, userMessage]);
991
+ setIsProcessing(true);
992
+ const localStartTime = Date.now();
993
+ setProcessingStartTime(localStartTime);
994
+ setCurrentTokens(0);
995
+ lastPromptTokensRef.current = 0;
996
+ shouldAutoScroll.current = true;
997
+
998
+ const conversationId = createId();
999
+ const conversationSteps: ConversationStep[] = [];
1000
+ let totalTokens = { prompt: 0, completion: 0, total: 0 };
1001
+ let stepCount = 0;
1002
+ let totalChars = 0;
1003
+ for (const m of messages) {
1004
+ if (m.role === 'assistant') {
1005
+ totalChars += m.content.length;
1006
+ if (m.thinkingContent) totalChars += m.thinkingContent.length;
1007
+ } else if (m.role === 'tool') {
1008
+ totalChars += m.content.length;
1009
+ }
1010
+ }
1011
+
1012
+ const estimateTokens = () => Math.ceil(totalChars / 4);
1013
+ setCurrentTokens(estimateTokens());
1014
+ const config = readConfig();
1015
+ const resolveMaxContextTokens = async () => {
1016
+ if (config.maxContextTokens) return config.maxContextTokens;
1017
+ if (config.provider && config.model) {
1018
+ const resolved = await getModelsDevContextLimit(config.provider, config.model);
1019
+ if (typeof resolved === "number") return resolved;
1020
+ }
1021
+ return undefined;
1022
+ };
1023
+ const buildSystemPrompt = () => {
1024
+ const rawSystemPrompt = config.systemPrompt || DEFAULT_SYSTEM_PROMPT;
1025
+ return processSystemPrompt(rawSystemPrompt, true);
1026
+ };
1027
+ const abortController = new AbortController();
1028
+ abortControllerRef.current = abortController;
1029
+ let abortNotified = false;
1030
+ const notifyAbort = () => {
1031
+ if (abortNotified) return;
1032
+ abortNotified = true;
1033
+ setMessages((prev: Message[]) => {
1034
+ const newMessages = [...prev];
1035
+ newMessages.push({
1036
+ id: createId(),
1037
+ role: "tool",
1038
+ success: false,
1039
+ content: "Generation aborted. \n↪ What should Mosaic do instead?"
1040
+ });
1041
+ return newMessages;
1042
+ });
1043
+ };
1044
+
1045
+ conversationSteps.push({
1046
+ type: 'user',
1047
+ content: composedContent,
1048
+ timestamp: Date.now(),
1049
+ images: imagesForMessage.length > 0 ? imagesForMessage : undefined
1050
+ });
1051
+
1052
+ let responseDuration: number | null = null;
1053
+ let responseBlendWord: string | undefined = undefined;
1054
+
1055
+ try {
1056
+ const providerStatus = await Agent.ensureProviderReady();
1057
+ if (!providerStatus.ready) {
1058
+ setMessages((prev: Message[]) => {
1059
+ const newMessages = [...prev];
1060
+ newMessages.push({
1061
+ id: createId(),
1062
+ role: "assistant",
1063
+ content: `Ollama error: ${providerStatus.error || 'Could not start Ollama. Make sure Ollama is installed.'}`,
1064
+ isError: true
1065
+ });
1066
+ return newMessages;
1067
+ });
1068
+ setIsProcessing(false);
1069
+ return;
1070
+ }
1071
+
1072
+ const agent = new Agent();
1073
+ const conversationHistory = buildConversationHistory([...messages, userMessage], imagesSupported);
1074
+ let assistantChunk = '';
1075
+ let thinkingChunk = '';
1076
+ const pendingToolCalls = new Map<string, { toolName: string; args: Record<string, unknown>; messageId?: string }>();
1077
+ let assistantMessageId: string | null = null;
1078
+ let streamHadError = false;
1079
+ titleExtractedRef.current = false;
1080
+
1081
+ for await (const event of agent.streamMessages(conversationHistory, { abortSignal: abortController.signal })) {
1082
+ if (event.type === 'reasoning-delta') {
1083
+ thinkingChunk += event.content;
1084
+ totalChars += event.content.length;
1085
+ setCurrentTokens(estimateTokens());
1086
+
1087
+ if (assistantMessageId === null) {
1088
+ assistantMessageId = createId();
1089
+ }
1090
+
1091
+ const currentMessageId = assistantMessageId;
1092
+ setMessages((prev: Message[]) => {
1093
+ const newMessages = [...prev];
1094
+ const messageIndex = newMessages.findIndex(m => m.id === currentMessageId);
1095
+
1096
+ if (messageIndex === -1) {
1097
+ newMessages.push({ id: currentMessageId, role: "assistant", content: '', thinkingContent: thinkingChunk });
1098
+ } else {
1099
+ newMessages[messageIndex] = {
1100
+ ...newMessages[messageIndex]!,
1101
+ thinkingContent: thinkingChunk
1102
+ };
1103
+ }
1104
+ return newMessages;
1105
+ });
1106
+ } else if (event.type === 'text-delta') {
1107
+ assistantChunk += event.content;
1108
+ totalChars += event.content.length;
1109
+ setCurrentTokens(estimateTokens());
1110
+
1111
+ const { title, cleanContent, isPending, noTitle } = extractTitle(assistantChunk, titleExtractedRef.current);
1112
+
1113
+ if (title) {
1114
+ titleExtractedRef.current = true;
1115
+ currentTitleRef.current = title;
1116
+ setCurrentTitle(title);
1117
+ setTerminalTitle(title);
1118
+ } else if (noTitle) {
1119
+ titleExtractedRef.current = true;
1120
+ }
1121
+
1122
+ if (isPending) continue;
1123
+
1124
+ if (assistantMessageId === null) {
1125
+ assistantMessageId = createId();
1126
+ }
1127
+
1128
+ const displayContent = cleanContent;
1129
+ const currentMessageId = assistantMessageId;
1130
+ setMessages((prev: Message[]) => {
1131
+ const newMessages = [...prev];
1132
+ const messageIndex = newMessages.findIndex(m => m.id === currentMessageId);
1133
+
1134
+ if (messageIndex === -1) {
1135
+ newMessages.push({ id: currentMessageId, role: "assistant", content: displayContent, thinkingContent: thinkingChunk });
1136
+ } else {
1137
+ newMessages[messageIndex] = {
1138
+ ...newMessages[messageIndex]!,
1139
+ content: displayContent,
1140
+ thinkingContent: thinkingChunk
1141
+ };
1142
+ }
1143
+ return newMessages;
1144
+ });
1145
+ } else if (event.type === 'step-start') {
1146
+ stepCount++;
1147
+ } else if (event.type === 'tool-call-end') {
1148
+ totalChars += JSON.stringify(event.args).length;
1149
+ setCurrentTokens(estimateTokens());
1150
+
1151
+ const isExploreTool = event.toolName === 'explore';
1152
+ let runningMessageId: string | undefined;
1153
+
1154
+ if (isExploreTool) {
1155
+ setExploreAbortController(abortController);
1156
+ exploreToolsRef.current = [];
1157
+ const purpose = (event.args.purpose as string) || 'exploring...';
1158
+ explorePurposeRef.current = purpose;
1159
+ runningMessageId = createId();
1160
+ exploreMessageIdRef.current = runningMessageId;
1161
+ const { name: toolDisplayName, info: toolInfo } = parseToolHeader(event.toolName, event.args);
1162
+ const runningContent = toolInfo ? `${toolDisplayName} (${toolInfo})` : toolDisplayName;
1163
+
1164
+ setMessages((prev: Message[]) => {
1165
+ const newMessages = [...prev];
1166
+ newMessages.push({
1167
+ id: runningMessageId!,
1168
+ role: "tool",
1169
+ content: runningContent,
1170
+ toolName: event.toolName,
1171
+ toolArgs: event.args,
1172
+ success: true,
1173
+ isRunning: true,
1174
+ runningStartTime: Date.now()
1175
+ });
1176
+ return newMessages;
1177
+ });
1178
+ }
1179
+
1180
+ pendingToolCalls.set(event.toolCallId, {
1181
+ toolName: event.toolName,
1182
+ args: event.args,
1183
+ messageId: runningMessageId
1184
+ });
1185
+
1186
+ } else if (event.type === 'tool-result') {
1187
+ const pending = pendingToolCalls.get(event.toolCallId);
1188
+ const toolName = pending?.toolName ?? event.toolName;
1189
+ const toolArgs = pending?.args ?? {};
1190
+ const runningMessageId = pending?.messageId;
1191
+ pendingToolCalls.delete(event.toolCallId);
1192
+
1193
+ if (toolName === 'explore') {
1194
+ exploreMessageIdRef.current = null;
1195
+ setExploreAbortController(null);
1196
+ }
1197
+
1198
+ const { content: toolContent, success } = formatToolMessage(
1199
+ toolName,
1200
+ toolArgs,
1201
+ event.result,
1202
+ { maxLines: DEFAULT_MAX_TOOL_LINES }
1203
+ );
1204
+
1205
+ const toolResultStr = typeof event.result === 'string' ? event.result : JSON.stringify(event.result);
1206
+ totalChars += toolResultStr.length;
1207
+ setCurrentTokens(estimateTokens());
1208
+
1209
+ if (assistantChunk.trim()) {
1210
+ conversationSteps.push({
1211
+ type: 'assistant',
1212
+ content: assistantChunk,
1213
+ timestamp: Date.now()
1214
+ });
1215
+ }
1216
+
1217
+ conversationSteps.push({
1218
+ type: 'tool',
1219
+ content: toolContent,
1220
+ toolName,
1221
+ toolArgs,
1222
+ toolResult: event.result,
1223
+ timestamp: Date.now()
1224
+ });
1225
+
1226
+ setMessages((prev: Message[]) => {
1227
+ const newMessages = [...prev];
1228
+
1229
+ let runningIndex = -1;
1230
+ if (runningMessageId) {
1231
+ runningIndex = newMessages.findIndex(m => m.id === runningMessageId);
1232
+ } else if (toolName === 'bash' || toolName === 'explore') {
1233
+ runningIndex = newMessages.findIndex(m => m.isRunning && m.toolName === toolName);
1234
+ }
1235
+
1236
+ if (runningIndex !== -1) {
1237
+ newMessages[runningIndex] = {
1238
+ ...newMessages[runningIndex]!,
1239
+ content: toolContent,
1240
+ toolArgs: toolArgs,
1241
+ toolResult: event.result,
1242
+ success,
1243
+ isRunning: false,
1244
+ runningStartTime: undefined
1245
+ };
1246
+ return newMessages;
1247
+ }
1248
+
1249
+ newMessages.push({
1250
+ id: createId(),
1251
+ role: "tool",
1252
+ content: toolContent,
1253
+ toolName,
1254
+ toolArgs: toolArgs,
1255
+ toolResult: event.result,
1256
+ success: success
1257
+ });
1258
+ return newMessages;
1259
+ });
1260
+
1261
+ assistantChunk = '';
1262
+ thinkingChunk = '';
1263
+ assistantMessageId = null;
1264
+ } else if (event.type === 'error') {
1265
+ if (abortController.signal.aborted) {
1266
+ notifyAbort();
1267
+ streamHadError = true;
1268
+ break;
1269
+ }
1270
+ if (assistantChunk.trim()) {
1271
+ conversationSteps.push({
1272
+ type: 'assistant',
1273
+ content: assistantChunk,
1274
+ timestamp: Date.now()
1275
+ });
1276
+ }
1277
+
1278
+ const errorContent = formatErrorMessage('API', event.error);
1279
+ conversationSteps.push({
1280
+ type: 'assistant',
1281
+ content: errorContent,
1282
+ timestamp: Date.now()
1283
+ });
1284
+
1285
+ setMessages((prev: Message[]) => {
1286
+ const newMessages = [...prev];
1287
+ newMessages.push({
1288
+ id: createId(),
1289
+ role: 'assistant',
1290
+ content: errorContent,
1291
+ isError: true,
1292
+ });
1293
+ return newMessages;
1294
+ });
1295
+
1296
+ assistantChunk = '';
1297
+ thinkingChunk = '';
1298
+ assistantMessageId = null;
1299
+ streamHadError = true;
1300
+ break;
1301
+ } else if (event.type === 'finish') {
1302
+ if (event.usage && event.usage.totalTokens > 0) {
1303
+ totalTokens = {
1304
+ prompt: event.usage.promptTokens,
1305
+ completion: event.usage.completionTokens,
1306
+ total: event.usage.totalTokens
1307
+ };
1308
+ lastPromptTokensRef.current = event.usage.promptTokens;
1309
+ setCurrentTokens(event.usage.totalTokens);
1310
+ }
1311
+ }
1312
+ }
1313
+
1314
+ if (abortController.signal.aborted) {
1315
+ notifyAbort();
1316
+ return;
1317
+ }
1318
+
1319
+ if (!streamHadError && assistantChunk.trim()) {
1320
+ conversationSteps.push({
1321
+ type: 'assistant',
1322
+ content: assistantChunk,
1323
+ timestamp: Date.now()
1324
+ });
1325
+ }
1326
+
1327
+ responseDuration = Date.now() - localStartTime;
1328
+ if (responseDuration >= 60000) {
1329
+ responseBlendWord = BLEND_WORDS[Math.floor(Math.random() * BLEND_WORDS.length)];
1330
+ for (let i = conversationSteps.length - 1; i >= 0; i--) {
1331
+ if (conversationSteps[i]?.type === 'assistant') {
1332
+ conversationSteps[i] = {
1333
+ ...conversationSteps[i]!,
1334
+ responseDuration,
1335
+ blendWord: responseBlendWord
1336
+ };
1337
+ break;
1338
+ }
1339
+ }
1340
+ }
1341
+
1342
+ const conversationData: ConversationHistory = {
1343
+ id: conversationId,
1344
+ timestamp: Date.now(),
1345
+ steps: conversationSteps,
1346
+ totalSteps: stepCount,
1347
+ title: currentTitleRef.current ?? currentTitle ?? null,
1348
+ workspace: process.cwd(),
1349
+ totalTokens: totalTokens.total > 0 ? totalTokens : undefined,
1350
+ model: config.model,
1351
+ provider: config.provider
1352
+ };
1353
+
1354
+ saveConversation(conversationData);
1355
+ const resolvedMax = await resolveMaxContextTokens();
1356
+ const maxContextTokens = resolvedMax ?? getDefaultContextBudget(config.provider);
1357
+ if (!abortController.signal.aborted) {
1358
+ const realPromptTokens = lastPromptTokensRef.current;
1359
+ const systemPrompt = buildSystemPrompt();
1360
+ setMessages(prev => {
1361
+ const usedTokens = realPromptTokens > 0
1362
+ ? realPromptTokens
1363
+ : estimateTotalTokens(prev, systemPrompt);
1364
+ if (!shouldAutoCompact(usedTokens, maxContextTokens)) return prev;
1365
+ const compacted = compactMessagesForUi(prev, systemPrompt, maxContextTokens, createId, true);
1366
+ setCurrentTokens(compacted.estimatedTokens);
1367
+ return compacted.messages;
1368
+ });
1369
+ }
1370
+
1371
+ } catch (error) {
1372
+ if (abortController.signal.aborted) {
1373
+ notifyAbort();
1374
+ return;
1375
+ }
1376
+ const errorMessage = error instanceof Error ? error.message : 'An unknown error occurred';
1377
+ const errorContent = formatErrorMessage('Mosaic', errorMessage);
1378
+ setMessages((prev: Message[]) => {
1379
+ const newMessages = [...prev];
1380
+ if (newMessages[newMessages.length - 1]?.role === 'assistant' && newMessages[newMessages.length - 1]?.content === '') {
1381
+ newMessages[newMessages.length - 1] = {
1382
+ id: newMessages[newMessages.length - 1]!.id,
1383
+ role: "assistant",
1384
+ content: errorContent,
1385
+ isError: true
1386
+ };
1387
+ } else {
1388
+ newMessages.push({
1389
+ id: createId(),
1390
+ role: "assistant",
1391
+ content: errorContent,
1392
+ isError: true
1393
+ });
1394
+ }
1395
+ return newMessages;
1396
+ });
1397
+ } finally {
1398
+ if (abortControllerRef.current === abortController) {
1399
+ abortControllerRef.current = null;
1400
+ }
1401
+ const duration = responseDuration ?? (Date.now() - localStartTime);
1402
+ if (duration >= 60000) {
1403
+ const blendWord = responseBlendWord ?? BLEND_WORDS[Math.floor(Math.random() * BLEND_WORDS.length)];
1404
+ setMessages((prev: Message[]) => {
1405
+ const newMessages = [...prev];
1406
+ for (let i = newMessages.length - 1; i >= 0; i--) {
1407
+ if (newMessages[i]?.role === 'assistant') {
1408
+ newMessages[i] = { ...newMessages[i]!, responseDuration: duration, blendWord };
1409
+ break;
1410
+ }
1411
+ }
1412
+ return newMessages;
1413
+ });
1414
+ }
1415
+ setIsProcessing(false);
1416
+ setProcessingStartTime(null);
1417
+ }
1418
+ };
1419
+
1420
+ useEffect(() => {
1421
+ if (initialMessage && !initialMessageProcessed.current && currentPage === "chat") {
1422
+ initialMessageProcessed.current = true;
1423
+ handleSubmit(initialMessage);
1424
+ }
1425
+ }, [initialMessage, currentPage, handleSubmit]);
1426
+
1427
+ if (currentPage === "home") {
1428
+ const handleHomeSubmit = (value: string, meta?: InputSubmitMeta) => {
1429
+ const hasPastedContent = Boolean(meta?.isPaste && meta.pastedContent);
1430
+ if (!value.trim() && !hasPastedContent) return;
1431
+ setCurrentPage("chat");
1432
+ handleSubmit(value, meta);
1433
+ };
1434
+
1435
+ return (
1436
+ <HomePage
1437
+ onSubmit={handleHomeSubmit}
1438
+ pasteRequestId={pasteRequestId}
1439
+ shortcutsOpen={shortcutsOpen}
1440
+ />
1441
+ );
1442
+ }
1443
+
1444
+ return (
1445
+ <ChatPage
1446
+ messages={messages}
1447
+ isProcessing={isProcessing}
1448
+ processingStartTime={processingStartTime}
1449
+ currentTokens={currentTokens}
1450
+ scrollOffset={scrollOffset}
1451
+ terminalHeight={terminalHeight}
1452
+ terminalWidth={terminalWidth}
1453
+ pasteRequestId={pasteRequestId}
1454
+ shortcutsOpen={shortcutsOpen}
1455
+ onSubmit={handleSubmit}
1456
+ pendingImages={pendingImages}
1457
+ />
1458
+ );
1459
+ }