-
Notifications
You must be signed in to change notification settings - Fork 453
Expand file tree
/
Copy pathChatView.tsx
More file actions
460 lines (417 loc) · 17.6 KB
/
ChatView.tsx
File metadata and controls
460 lines (417 loc) · 17.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
'use client';
import { useState, useCallback, useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import type { Message, MessagesResponse, FileAttachment, SessionStreamSnapshot } from '@/types';
import { MessageList } from './MessageList';
import { MessageInput } from './MessageInput';
import { ChatComposerActionBar } from './ChatComposerActionBar';
import { ChatPermissionSelector } from './ChatPermissionSelector';
import { ContextUsageIndicator } from './ContextUsageIndicator';
import { ImageGenToggle } from './ImageGenToggle';
import { Button } from '@/components/ui/button';
import { usePanel } from '@/hooks/usePanel';
import { useTranslation } from '@/hooks/useTranslation';
import { PermissionPrompt } from './PermissionPrompt';
import { BatchExecutionDashboard, BatchContextSync } from './batch-image-gen';
import { setLastGeneratedImages, loadLastGenerated } from '@/lib/image-ref-store';
import { useChatCommands } from '@/hooks/useChatCommands';
import { useAssistantTrigger } from '@/hooks/useAssistantTrigger';
import { useStreamSubscription } from '@/hooks/useStreamSubscription';
import {
startStream,
stopStream,
getSnapshot,
getRewindPoints,
respondToPermission,
} from '@/lib/stream-session-manager';
interface ChatViewProps {
sessionId: string;
initialMessages?: Message[];
initialHasMore?: boolean;
modelName?: string;
initialMode?: string;
providerId?: string;
initialPermissionProfile?: 'default' | 'full_access';
}
export function ChatView({ sessionId, initialMessages = [], initialHasMore = false, modelName, initialMode, providerId, initialPermissionProfile }: ChatViewProps) {
const { setStreamingSessionId, workingDirectory, setPendingApprovalSessionId } = usePanel();
const { t } = useTranslation();
const router = useRouter();
const [messages, setMessages] = useState<Message[]>(initialMessages);
const [permissionProfile, setPermissionProfile] = useState<'default' | 'full_access'>(initialPermissionProfile || 'default');
// Workspace mismatch banner state
const [workspaceMismatchPath, setWorkspaceMismatchPath] = useState<string | null>(null);
const [hasMore, setHasMore] = useState(initialHasMore);
const [loadingMore, setLoadingMore] = useState(false);
const loadingMoreRef = useRef(false);
const [mode, setMode] = useState(initialMode || 'code');
const [currentModel, setCurrentModel] = useState(() => modelName || (typeof window !== 'undefined' ? localStorage.getItem('codepilot:last-model') : null) || 'sonnet');
const [currentProviderId, setCurrentProviderId] = useState(() => providerId || (typeof window !== 'undefined' ? localStorage.getItem('codepilot:last-provider-id') : null) || '');
const [selectedEffort, setSelectedEffort] = useState<string | undefined>(undefined);
const [thinkingMode, setThinkingMode] = useState<string>('adaptive');
const [context1m, setContext1m] = useState(false);
// Sync model/provider when session data loads
useEffect(() => { if (modelName) setCurrentModel(modelName); }, [modelName]);
useEffect(() => { if (providerId) setCurrentProviderId(providerId); }, [providerId]);
// Fetch provider-specific options (with abort to prevent stale responses on fast switch)
useEffect(() => {
const pid = currentProviderId || 'env';
const controller = new AbortController();
fetch(`/api/providers/options?providerId=${encodeURIComponent(pid)}`, { signal: controller.signal })
.then(r => r.ok ? r.json() : null)
.then(data => {
if (!controller.signal.aborted) {
setThinkingMode(data?.options?.thinking_mode || 'adaptive');
setContext1m(!!data?.options?.context_1m);
}
})
.catch(() => {});
return () => controller.abort();
}, [currentProviderId]);
useEffect(() => { if (initialPermissionProfile) setPermissionProfile(initialPermissionProfile); }, [initialPermissionProfile]);
// Restore session-scoped last-generated images from sessionStorage
useEffect(() => { loadLastGenerated(sessionId); }, [sessionId]);
// Stream snapshot from the manager — drives all streaming UI
const [streamSnapshot, setStreamSnapshot] = useState<SessionStreamSnapshot | null>(
() => getSnapshot(sessionId)
);
// Derive rendering state from snapshot
const isStreaming = streamSnapshot?.phase === 'active';
const streamingContent = streamSnapshot?.streamingContent ?? '';
const toolUses = streamSnapshot?.toolUses ?? [];
const toolResults = streamSnapshot?.toolResults ?? [];
const streamingToolOutput = streamSnapshot?.streamingToolOutput ?? '';
const statusText = streamSnapshot?.statusText;
const pendingPermission = streamSnapshot?.pendingPermission ?? null;
const permissionResolved = streamSnapshot?.permissionResolved ?? null;
const rewindPoints = getRewindPoints(sessionId);
// Pending image generation notices
const pendingImageNoticesRef = useRef<string[]>([]);
const sendMessageRef = useRef<(content: string, files?: FileAttachment[]) => Promise<void>>(undefined);
const initMetaRef = useRef<{ tools?: unknown; slash_commands?: unknown; skills?: unknown } | null>(null);
const handleModeChange = useCallback((newMode: string) => {
setMode(newMode);
if (sessionId) {
fetch(`/api/chat/sessions/${sessionId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mode: newMode }),
}).then(() => {
window.dispatchEvent(new CustomEvent('session-updated'));
}).catch(() => { /* silent */ });
fetch('/api/chat/mode', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sessionId, mode: newMode }),
}).catch(() => { /* silent */ });
}
}, [sessionId]);
const handleProviderModelChange = useCallback((newProviderId: string, model: string) => {
setCurrentProviderId(newProviderId);
setCurrentModel(model);
fetch(`/api/chat/sessions/${sessionId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model, provider_id: newProviderId }),
}).catch(() => {});
}, [sessionId]);
// ── Extracted hooks ──
useStreamSubscription({
sessionId,
setStreamSnapshot,
setStreamingSessionId,
setPendingApprovalSessionId,
setMessages,
});
const initializedRef = useRef(false);
useEffect(() => {
if (initialMessages.length > 0 && !initializedRef.current) {
initializedRef.current = true;
setMessages(initialMessages);
}
}, [initialMessages]);
useEffect(() => { if (initialMode) setMode(initialMode); }, [initialMode]);
useEffect(() => { setHasMore(initialHasMore); }, [initialHasMore]);
const buildThinkingConfig = useCallback((): { type: string } | undefined => {
if (!thinkingMode || thinkingMode === 'adaptive') return { type: 'adaptive' };
if (thinkingMode === 'enabled') return { type: 'enabled' };
if (thinkingMode === 'disabled') return { type: 'disabled' };
return undefined;
}, [thinkingMode]);
const checkAssistantTrigger = useAssistantTrigger({
sessionId,
workingDirectory,
isStreaming,
mode,
currentModel,
currentProviderId,
initialMessages,
handleModeChange,
buildThinkingConfig,
sendMessageRef,
initMetaRef,
});
// Detect workspace mismatch
useEffect(() => {
if (!workingDirectory) return;
let cancelled = false;
(async () => {
try {
const res = await fetch('/api/settings/workspace');
if (!res.ok || cancelled) return;
const data = await res.json();
if (cancelled) return;
if (data.path && workingDirectory !== data.path) {
const inspectRes = await fetch(`/api/workspace/inspect?path=${encodeURIComponent(workingDirectory)}`);
if (!inspectRes.ok || cancelled) return;
const inspectData = await inspectRes.json();
if (inspectData.hasAssistantData) {
setWorkspaceMismatchPath(data.path);
} else {
setWorkspaceMismatchPath(null);
}
} else {
setWorkspaceMismatchPath(null);
}
} catch {
// ignore
}
})();
return () => { cancelled = true; };
}, [workingDirectory]);
// Listen for workspace-switched events
useEffect(() => {
const handler = (e: Event) => {
const detail = (e as CustomEvent).detail;
if (detail?.newPath && workingDirectory && workingDirectory === detail.oldPath) {
setWorkspaceMismatchPath(detail.newPath);
}
};
window.addEventListener('assistant-workspace-switched', handler);
return () => window.removeEventListener('assistant-workspace-switched', handler);
}, [workingDirectory]);
const handleOpenNewAssistant = useCallback(async () => {
try {
const model = typeof window !== 'undefined' ? localStorage.getItem('codepilot:last-model') || '' : '';
const provider_id = typeof window !== 'undefined' ? localStorage.getItem('codepilot:last-provider-id') || '' : '';
const res = await fetch('/api/workspace/session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mode: 'checkin', model, provider_id }),
});
if (res.ok) {
const data = await res.json();
window.dispatchEvent(new CustomEvent('session-created'));
router.push(`/chat/${data.session.id}`);
}
} catch (e) {
console.error('[ChatView] Failed to open assistant session:', e);
}
}, [router]);
const loadEarlierMessages = useCallback(async () => {
if (loadingMoreRef.current || !hasMore || messages.length === 0) return;
loadingMoreRef.current = true;
setLoadingMore(true);
try {
const earliest = messages[0];
const earliestRowId = (earliest as Message & { _rowid?: number })._rowid;
if (!earliestRowId) return;
const res = await fetch(`/api/chat/sessions/${sessionId}/messages?limit=100&before=${earliestRowId}`);
if (!res.ok) return;
const data: MessagesResponse = await res.json();
setHasMore(data.hasMore ?? false);
if (data.messages.length > 0) {
setMessages(prev => [...data.messages, ...prev]);
}
} finally {
loadingMoreRef.current = false;
setLoadingMore(false);
}
}, [sessionId, messages, hasMore]);
const stopStreaming = useCallback(() => { stopStream(sessionId); }, [sessionId]);
const handlePermissionResponse = useCallback(
async (decision: 'allow' | 'allow_session' | 'deny', updatedInput?: Record<string, unknown>, denyMessage?: string) => {
setPendingApprovalSessionId('');
await respondToPermission(sessionId, decision, updatedInput, denyMessage);
},
[sessionId, setPendingApprovalSessionId]
);
const sendMessage = useCallback(
async (content: string, files?: FileAttachment[], systemPromptAppend?: string, displayOverride?: string) => {
if (isStreaming) return;
const displayUserContent = displayOverride || content;
let displayContent = displayUserContent;
if (files && files.length > 0) {
const fileMeta = files.map(f => ({ id: f.id, name: f.name, type: f.type, size: f.size }));
displayContent = `<!--files:${JSON.stringify(fileMeta)}-->${displayUserContent}`;
}
const userMessage: Message = {
id: 'temp-' + Date.now(),
session_id: sessionId,
role: 'user',
content: displayContent,
created_at: new Date().toISOString(),
token_usage: null,
};
setMessages((prev) => [...prev, userMessage]);
const notices = pendingImageNoticesRef.current.length > 0
? [...pendingImageNoticesRef.current]
: undefined;
if (notices) pendingImageNoticesRef.current = [];
startStream({
sessionId,
content,
mode,
model: currentModel,
providerId: currentProviderId,
files,
systemPromptAppend,
pendingImageNotices: notices,
effort: selectedEffort,
thinking: buildThinkingConfig(),
context1m,
displayOverride,
onModeChanged: (sdkMode) => {
const uiMode = sdkMode === 'plan' ? 'plan' : 'code';
handleModeChange(uiMode);
},
sendMessageFn: (retryContent: string, retryFiles?: FileAttachment[]) => {
sendMessageRef.current?.(retryContent, retryFiles);
},
onInitMeta: (meta) => {
initMetaRef.current = meta;
console.log('[ChatView] SDK init meta received:', meta);
},
});
},
[sessionId, isStreaming, mode, currentModel, currentProviderId, selectedEffort, context1m, buildThinkingConfig, handleModeChange]
);
sendMessageRef.current = sendMessage;
// Expose widget drill-down bridge: widgets can call window.__widgetSendMessage(text)
// to trigger follow-up questions (e.g. clicking a node to get deeper explanation)
// Hardened: type-checked, length-limited, rate-limited, sanitized.
useEffect(() => {
let lastCallTime = 0;
const RATE_LIMIT_MS = 2000;
const MAX_LENGTH = 500;
const bridge = (text: unknown) => {
if (typeof text !== 'string') return;
const trimmed = text.trim();
if (!trimmed || trimmed.length > MAX_LENGTH) return;
// Rate limit: max one message per 2 seconds
const now = Date.now();
if (now - lastCallTime < RATE_LIMIT_MS) return;
lastCallTime = now;
sendMessageRef.current?.(trimmed);
};
(window as unknown as Record<string, unknown>).__widgetSendMessage = bridge;
return () => {
delete (window as unknown as Record<string, unknown>).__widgetSendMessage;
};
}, []);
const handleCommand = useChatCommands({ sessionId, messages, setMessages, sendMessage });
// Listen for image generation completion
useEffect(() => {
const handler = (e: Event) => {
const detail = (e as CustomEvent).detail;
if (!detail) return;
const paths = (detail.images || [])
.map((img: { localPath?: string }) => img.localPath)
.filter(Boolean);
const pathInfo = paths.length > 0 ? `\nGenerated image file paths:\n${paths.map((p: string) => `- ${p}`).join('\n')}` : '';
const notice = `[Image generation completed]\n- Prompt: "${detail.prompt}"\n- Aspect ratio: ${detail.aspectRatio}\n- Resolution: ${detail.resolution}${pathInfo}`;
if (paths.length > 0) {
setLastGeneratedImages(sessionId, paths);
}
pendingImageNoticesRef.current.push(notice);
const dbNotice = `[__IMAGE_GEN_NOTICE__ prompt: "${detail.prompt}", aspect ratio: ${detail.aspectRatio}, resolution: ${detail.resolution}${paths.length > 0 ? `, file path: ${paths.join(', ')}` : ''}]`;
fetch('/api/chat/messages', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ session_id: sessionId, role: 'user', content: dbNotice }),
}).catch(() => {});
};
window.addEventListener('image-gen-completed', handler);
return () => window.removeEventListener('image-gen-completed', handler);
}, [sessionId]);
return (
<div className="flex h-full min-h-0 flex-col">
{/* Workspace mismatch banner */}
{workspaceMismatchPath && (
<div className="flex items-center justify-between gap-3 border-b border-status-warning/30 bg-status-warning-muted px-4 py-2">
<span className="text-xs text-status-warning-foreground">
{t('assistant.switchedBanner', { path: workspaceMismatchPath })}
</span>
<Button
onClick={handleOpenNewAssistant}
className="shrink-0 rounded-md bg-status-warning px-3 py-1 text-xs font-medium text-white hover:bg-status-warning/80 transition-colors"
>
{t('assistant.openNewAssistant')}
</Button>
</div>
)}
<MessageList
messages={messages}
streamingContent={streamingContent}
isStreaming={isStreaming}
toolUses={toolUses}
toolResults={toolResults}
streamingToolOutput={streamingToolOutput}
statusText={statusText}
onForceStop={stopStreaming}
hasMore={hasMore}
loadingMore={loadingMore}
onLoadMore={loadEarlierMessages}
rewindPoints={rewindPoints}
sessionId={sessionId}
/>
{/* Permission prompt */}
<PermissionPrompt
pendingPermission={pendingPermission}
permissionResolved={permissionResolved}
onPermissionResponse={handlePermissionResponse}
toolUses={toolUses}
permissionProfile={permissionProfile}
/>
{/* Batch image generation panels */}
<BatchExecutionDashboard />
<BatchContextSync />
<MessageInput
key={sessionId}
onSend={sendMessage}
onCommand={handleCommand}
onStop={stopStreaming}
disabled={false}
isStreaming={isStreaming}
sessionId={sessionId}
modelName={currentModel}
onModelChange={setCurrentModel}
providerId={currentProviderId}
onProviderModelChange={handleProviderModelChange}
workingDirectory={workingDirectory}
onAssistantTrigger={checkAssistantTrigger}
effort={selectedEffort}
onEffortChange={setSelectedEffort}
sdkInitMeta={initMetaRef.current}
mode={mode}
onModeChange={handleModeChange}
/>
<ChatComposerActionBar
left={<ImageGenToggle />}
center={
<ChatPermissionSelector
sessionId={sessionId}
permissionProfile={permissionProfile}
onPermissionChange={setPermissionProfile}
/>
}
right={
<ContextUsageIndicator
messages={messages}
modelName={currentModel}
/>
}
/>
</div>
);
}