forked from nexu-io/open-design
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProjectView.tsx
More file actions
4718 lines (4531 loc) · 182 KB
/
ProjectView.tsx
File metadata and controls
4718 lines (4531 loc) · 182 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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
useLayoutEffect,
type KeyboardEvent as ReactKeyboardEvent,
type PointerEvent as ReactPointerEvent,
} from 'react';
import { createHtmlArtifactManifest, inferLegacyManifest } from '../artifacts/manifest';
import { resolveHtmlPointerArtifactTarget } from '../artifacts/pointer';
import { validateHtmlArtifact } from '../artifacts/validate';
import { createArtifactParser } from '../artifacts/parser';
import { useI18n } from '../i18n';
import { streamMessage } from '../providers/anthropic';
import {
fetchChatRunStatus,
listActiveChatRuns,
listProjectRuns,
reattachDaemonRun,
reportChatRunFeedback,
streamViaDaemon,
} from '../providers/daemon';
import { fetchElevenLabsVoiceOptions } from '../providers/elevenlabs-voices';
import { normalizeCustomReason } from '@open-design/contracts/analytics';
import {
deletePreviewComment,
fetchConnectorStatuses,
fetchPreviewComments,
fetchDesignSystem,
fetchDesignTemplate,
fetchProjectDesignSystemPackageAudit,
fetchLiveArtifacts,
fetchProjectFiles,
fetchSkill,
patchPreviewCommentStatus,
projectRawUrl,
upsertPreviewComment,
writeProjectTextFile,
} from '../providers/registry';
import { useProjectFileEvents, type ProjectEvent } from '../providers/project-events';
import { useCoalescedCallback } from '../hooks/useCoalescedCallback';
import {
composeSystemPrompt,
type AudioVoiceOption,
type MemorySystemPromptResponse,
type ResearchOptions,
} from '@open-design/contracts';
import { projectKindToTracking } from '@open-design/contracts/analytics';
import type {
TrackingDesignSystemApplyTargetKind,
TrackingDesignSystemOrigin,
TrackingDesignSystemStatusValue,
} from '@open-design/contracts/analytics';
import { useAnalytics } from '../analytics/provider';
import {
trackDesignSystemApplyResult,
trackPageView,
} from '../analytics/events';
import {
clearOnboardingSessionId,
peekOnboardingSessionId,
} from '../analytics/onboarding-session';
import { navigate } from '../router';
import { agentDisplayName, agentModelDisplayName } from '../utils/agentLabels';
import { isMacPlatform } from '../utils/platform';
import {
canAutoRenameProjectFromPrompt,
summarizeProjectNameFromPrompt,
} from '../utils/projectName';
import {
apiProtocolAgentId,
apiProtocolModelLabel,
} from '../utils/apiProtocol';
import { playSound, showCompletionNotification } from '../utils/notifications';
import { randomUUID } from '../utils/uuid';
import { DEFAULT_NOTIFICATIONS } from '../state/config';
import type { TodoItem } from '../runtime/todos';
import { appendErrorStatusEvent } from '../runtime/chat-events';
import {
buildDesignSystemPackageAuditRepairPrompt,
summarizeDesignSystemPackageAudit,
} from '../runtime/design-system-package-audit';
import { isLiveArtifactTabId, liveArtifactTabId } from '../types';
import {
DESIGN_SYSTEM_WORKSPACE_DISPLAY_TITLE,
isDesignSystemWorkspacePrompt,
} from '../design-system-auto-prompt';
import {
createConversation,
deleteConversation as deleteConversationApi,
fetchAppliedPluginSnapshot,
getTemplate,
installGeneratedPluginFolder,
listConversations,
listMessages,
loadTabs,
patchConversation,
patchProject,
saveMessage,
startGeneratedPluginShareTask,
saveTabs,
type SaveMessageOptions,
waitGeneratedPluginShareTask,
} from '../state/projects';
import type { AppliedPluginSnapshot } from '@open-design/contracts';
import type {
AgentEvent,
AgentInfo,
AppConfig,
Artifact,
ChatAttachment,
ChatCommentAttachment,
ChatMessage,
ChatMessageFeedbackChange,
Conversation,
DesignSystemSummary,
OpenTabsState,
Project,
ProjectMetadata,
PreviewComment,
PreviewCommentTarget,
ProjectFile,
ProjectTemplate,
LiveArtifactEventItem,
LiveArtifactSummary,
SkillSummary,
} from '../types';
import { historyWithApiAttachmentContext } from '../api-attachment-context';
import {
commentsToAttachments,
historyWithCommentAttachmentContext,
mergeAttachedComments,
removeAttachedComment,
} from '../comments';
import { buildPptxExportPrompt } from '../lib/build-pptx-export-prompt';
import { AppChromeHeader } from './AppChromeHeader';
import { AvatarMenu } from './AvatarMenu';
import { HandoffButton } from './HandoffButton';
import { ProjectDesignSystemPicker } from './ProjectDesignSystemPicker';
import { ChatPane } from './ChatPane';
import type { ChatSendMeta } from './ChatComposer';
import {
CritiqueTheaterMount,
useCritiqueTheaterEnabled,
} from './Theater';
import { decideAutoOpenAfterWrite } from './auto-open-file';
import { buildRepoImportPrompt, designSystemNeedsRepoConnect } from './design-system-github-evidence';
import { collectReferencedJsxNames } from '../runtime/jsx-module-refs';
import { FileWorkspace } from './FileWorkspace';
import { Icon } from './Icon';
import {
type PluginFolderAgentAction,
} from './design-files/pluginFolderActions';
import { CenteredLoader } from './Loading';
import type { SettingsSection } from './SettingsDialog';
import { Toast } from './Toast';
import { useDesignMdState } from '../hooks/useDesignMdState';
import { useFinalizeProject } from '../hooks/useFinalizeProject';
import { useProjectDetail } from '../hooks/useProjectDetail';
import { useTerminalLaunch } from '../hooks/useTerminalLaunch';
import { buildContinueInCliToast } from '../lib/build-continue-in-cli-toast';
import { buildClipboardPrompt } from '../lib/build-clipboard-prompt';
import { copyToClipboard } from '../lib/copy-to-clipboard';
import { effectiveMaxTokens } from '../state/maxTokens';
type ProjectChatSendMeta = ChatSendMeta & {
retryOfAssistantId?: string;
};
interface Props {
project: Project;
routeFileName: string | null;
/**
* Routed conversation id. When set (the URL is
* `/projects/:id/conversations/:cid[/...]`), the project view picks
* this conversation as active instead of defaulting to `list[0]`.
* Falls through to the default picker if the conversation does not
* exist (e.g. the run was deleted between the route landing and the
* conversation list loading). Issue #1505. Optional so existing
* test harnesses that mount ProjectView with a stub props bag do
* not have to be updated; production callers in `App.tsx` always
* pass the value from `useRoute()`.
*/
routeConversationId?: string | null;
config: AppConfig;
agents: AgentInfo[];
// Mentionable functional skills — already filtered by config.disabledSkills
// upstream, so this drives only the chat composer's @-picker scope. For
// resolving an existing project's `skillId` (which can also point at a
// design template after the skills/design-templates split) use
// `designTemplates` as a fallback in composedSystemPrompt() and in the
// skill-name / skill-mode lookups below.
skills: SkillSummary[];
// All known design templates (unfiltered). Required so projects created
// from the Templates surface keep composing the template body in API
// mode even when the user later disables the template in Settings.
designTemplates: SkillSummary[];
designSystems: DesignSystemSummary[];
daemonLive: boolean;
onModeChange: (mode: AppConfig['mode']) => void;
onAgentChange: (id: string) => void;
onAgentModelChange: (
id: string,
choice: { model?: string; reasoning?: string },
) => void;
onRefreshAgents: () => void;
onOpenSettings: (section?: SettingsSection) => void;
onOpenMcpSettings?: () => void;
// Pet wiring forwarded to the chat composer so users can adopt /
// wake / tuck a pet without leaving the project view.
onAdoptPetInline?: (petId: string) => void;
onTogglePet?: () => void;
onOpenPetSettings?: () => void;
onBack: () => void;
onClearPendingPrompt: () => void;
onTouchProject: () => void;
onProjectChange: (next: Project) => void;
onProjectsRefresh: () => void;
}
let liveArtifactEventSequence = 0;
const CHAT_PANEL_WIDTH_STORAGE_KEY = 'open-design.project.chatPanelWidth';
const DEFAULT_CHAT_PANEL_WIDTH = 460;
const MIN_CHAT_PANEL_WIDTH = 345;
const MAX_CHAT_PANEL_WIDTH = 720;
const MIN_WORKSPACE_PANEL_WIDTH = 400;
const SPLIT_RESIZE_HANDLE_WIDTH = 8;
const CHAT_PANEL_KEYBOARD_STEP = 16;
const DESIGN_SYSTEM_AUDIT_AUTO_REPAIR_ATTEMPTS = 2;
const MIN_NORMAL_SPLIT_WIDTH =
MIN_CHAT_PANEL_WIDTH + SPLIT_RESIZE_HANDLE_WIDTH + MIN_WORKSPACE_PANEL_WIDTH;
type DesignSystemReviewEntry = NonNullable<ProjectMetadata['designSystemReview']>[string];
type DesignSystemReviewAgentTask = NonNullable<DesignSystemReviewEntry['agentTask']>;
interface DesignSystemReviewDetails {
feedback?: string;
files?: string[];
agentTask?: DesignSystemReviewAgentTask;
}
function workspacePanelMinWidthForSplit(splitWidth: number): number {
if (!Number.isFinite(splitWidth) || splitWidth <= 0) return MIN_WORKSPACE_PANEL_WIDTH;
return splitWidth < MIN_NORMAL_SPLIT_WIDTH ? 0 : MIN_WORKSPACE_PANEL_WIDTH;
}
function maxChatPanelWidthForSplit(splitWidth: number): number {
if (!Number.isFinite(splitWidth) || splitWidth <= 0) return MAX_CHAT_PANEL_WIDTH;
const workspaceMinWidth = workspacePanelMinWidthForSplit(splitWidth);
const viewportAwareMax = splitWidth - SPLIT_RESIZE_HANDLE_WIDTH - workspaceMinWidth;
return Math.max(0, Math.min(MAX_CHAT_PANEL_WIDTH, Math.floor(viewportAwareMax)));
}
function clampPreferredChatPanelWidth(width: number): number {
return Math.min(MAX_CHAT_PANEL_WIDTH, Math.max(MIN_CHAT_PANEL_WIDTH, Math.round(width)));
}
function clampChatPanelWidth(width: number, maxWidth = MAX_CHAT_PANEL_WIDTH): number {
const effectiveMax = Math.max(0, Math.min(MAX_CHAT_PANEL_WIDTH, Math.floor(maxWidth)));
const effectiveMin = Math.min(MIN_CHAT_PANEL_WIDTH, effectiveMax);
return Math.min(effectiveMax, Math.max(effectiveMin, Math.round(width)));
}
function designSystemFeedbackAttachments(
projectFiles: ProjectFile[],
sectionFiles: string[],
): ChatAttachment[] {
const fileLookup = new Map(projectFiles.map((file) => [file.name, file]));
return sectionFiles
.map((name) => fileLookup.get(name))
.filter((file): file is ProjectFile => Boolean(file))
.slice(0, 8)
.map((file) => ({
path: file.name,
name: file.name,
kind: file.kind === 'image' ? 'image' : 'file',
size: file.size,
}));
}
function designSystemNeedsWorkPrompt(
sectionTitle: string,
feedback: string,
sectionFiles: string[],
): string {
const fileList =
sectionFiles.length > 0
? sectionFiles.map((name) => `- @${name}`).join('\n')
: '- No generated files are registered for this section yet.';
return (
`Needs work on the design system section "${sectionTitle}".\n\n` +
`User feedback:\n${feedback}\n\n` +
`Relevant section files:\n${fileList}\n\n` +
'Revise the design-system project files directly. Keep DESIGN.md, tokens, previews, UI kit examples, and assets consistent with the feedback. ' +
'After editing, summarize what changed and which files should be reviewed again.'
);
}
function readSavedChatPanelWidth(): number {
if (typeof window === 'undefined') return DEFAULT_CHAT_PANEL_WIDTH;
try {
const raw = window.localStorage.getItem(CHAT_PANEL_WIDTH_STORAGE_KEY);
const parsed = raw ? Number.parseInt(raw, 10) : Number.NaN;
return Number.isFinite(parsed)
? clampPreferredChatPanelWidth(parsed)
: DEFAULT_CHAT_PANEL_WIDTH;
} catch {
return DEFAULT_CHAT_PANEL_WIDTH;
}
}
function saveChatPanelWidth(width: number): void {
if (typeof window === 'undefined') return;
try {
window.localStorage.setItem(
CHAT_PANEL_WIDTH_STORAGE_KEY,
String(clampPreferredChatPanelWidth(width)),
);
} catch {
// localStorage can be unavailable in hardened browser contexts.
}
}
function autoSendFirstMessageKey(projectId: string): string {
return `od:auto-send-first:${projectId}`;
}
function autoSendAttachmentsKey(projectId: string): string {
return `od:auto-send-attachments:${projectId}`;
}
function designSystemAuditAutoRepairKey(projectId: string): string {
return `od:design-system-audit-auto-repair:${projectId}`;
}
function readAutoSendAttachments(projectId: string): ChatAttachment[] {
if (typeof window === 'undefined') return [];
try {
const raw = window.sessionStorage.getItem(autoSendAttachmentsKey(projectId));
if (!raw) return [];
const parsed = JSON.parse(raw) as unknown;
if (!Array.isArray(parsed)) return [];
return parsed.filter(isStoredChatAttachment);
} catch {
return [];
}
}
function clearAutoSendSession(projectId: string): void {
if (typeof window === 'undefined') return;
try {
window.sessionStorage.removeItem(autoSendFirstMessageKey(projectId));
window.sessionStorage.removeItem(autoSendAttachmentsKey(projectId));
} catch {
/* ignore */
}
}
function markDesignSystemAuditAutoRepairEligible(projectId: string): void {
if (typeof window === 'undefined') return;
try {
window.sessionStorage.setItem(
designSystemAuditAutoRepairKey(projectId),
String(DESIGN_SYSTEM_AUDIT_AUTO_REPAIR_ATTEMPTS),
);
} catch {
/* ignore */
}
}
function consumeDesignSystemAuditAutoRepair(projectId: string): boolean {
if (typeof window === 'undefined') return false;
try {
const key = designSystemAuditAutoRepairKey(projectId);
const raw = window.sessionStorage.getItem(key);
const attemptsRemaining = raw ? Number.parseInt(raw, 10) : 0;
if (!Number.isFinite(attemptsRemaining) || attemptsRemaining <= 0) {
window.sessionStorage.removeItem(key);
return false;
}
const nextAttemptsRemaining = attemptsRemaining - 1;
if (nextAttemptsRemaining > 0) {
window.sessionStorage.setItem(key, String(nextAttemptsRemaining));
} else {
window.sessionStorage.removeItem(key);
}
return true;
} catch {
return false;
}
}
function clearDesignSystemAuditAutoRepair(projectId: string): void {
if (typeof window === 'undefined') return;
try {
window.sessionStorage.removeItem(designSystemAuditAutoRepairKey(projectId));
} catch {
/* ignore */
}
}
function isDesignSystemWorkspaceMetadata(metadata: ProjectMetadata | undefined): boolean {
return metadata?.importedFrom === 'design-system';
}
function isStoredChatAttachment(value: unknown): value is ChatAttachment {
if (value === null || typeof value !== 'object') return false;
const record = value as Record<string, unknown>;
return (
typeof record.path === 'string' &&
record.path.length > 0 &&
typeof record.name === 'string' &&
record.name.length > 0 &&
(record.kind === 'image' || record.kind === 'file') &&
(record.size === undefined || typeof record.size === 'number')
);
}
function appendLiveArtifactEventItem(
prev: LiveArtifactEventItem[],
event: LiveArtifactEventItem['event'],
): LiveArtifactEventItem[] {
liveArtifactEventSequence += 1;
const next = [...prev, { id: liveArtifactEventSequence, event }];
return next.length > 50 ? next.slice(next.length - 50) : next;
}
export function projectSplitClassName(workspaceFocused: boolean): string {
return workspaceFocused ? 'split split-focus' : 'split';
}
function shouldFetchElevenLabsVoiceOptions(project: Project): boolean {
const metadata = project.metadata;
return metadata?.kind === 'audio'
&& metadata.audioKind === 'speech'
&& metadata.audioModel === 'elevenlabs-v3'
&& !metadata.voice;
}
function projectEventToAgentEvent(evt: ProjectEvent): LiveArtifactEventItem['event'] | null {
if (evt.type === 'file-changed') return null;
if (evt.type === 'conversation-created') return null;
if (evt.type === 'live_artifact') {
return {
kind: 'live_artifact',
action: evt.action,
projectId: evt.projectId,
artifactId: evt.artifactId,
title: evt.title,
refreshStatus: evt.refreshStatus,
};
}
return {
kind: 'live_artifact_refresh',
phase: evt.phase,
projectId: evt.projectId,
artifactId: evt.artifactId,
refreshId: evt.refreshId,
title: evt.title,
refreshedSourceCount: evt.refreshedSourceCount,
error: evt.error,
};
}
export function ProjectView({
project,
routeFileName,
routeConversationId = null,
config,
agents,
skills,
designTemplates,
designSystems,
daemonLive,
onModeChange,
onAgentChange,
onAgentModelChange,
onRefreshAgents,
onOpenSettings,
onOpenMcpSettings,
onAdoptPetInline,
onTogglePet,
onOpenPetSettings,
onBack,
onClearPendingPrompt,
onTouchProject,
onProjectChange,
onProjectsRefresh,
}: Props) {
const { locale, t } = useI18n();
const analytics = useAnalytics();
// P0 page_view page_name=chat_panel — fire once per project mount.
// ProjectView outlives conversation switches (ChatPane is keyed by
// activeConversationId so it remounts when the user switches chats,
// but this component does not), so page_view stays a "chat-panel
// entry" metric instead of becoming a "conversation switch" count.
// Reviewer #2285 (mrcfps, 2026-05-20 04:08) flagged the previous
// ChatComposer-level emit for skewing the funnel.
const chatPanelPageViewFiredRef = useRef<string | null>(null);
useEffect(() => {
if (chatPanelPageViewFiredRef.current === project.id) return;
chatPanelPageViewFiredRef.current = project.id;
trackPageView(analytics.track, { page_name: 'chat_panel' });
// Onboarding's 4th step ("生成进度页") fires here, not in
// `DesignSystemDetailView`: the Generate path navigates
// straight to the project's chat_panel, not to the design
// system detail surface. If an onboarding session id is still
// in sessionStorage we stamp the funnel's last row here and
// clear so any later DS visit doesn't inherit the attribution.
// E2E (2026-05-21) confirmed this is the only path users
// actually take — observed: page_view chat_panel fires, but
// page_view design_system_project never did because that
// route isn't visited from the embedded onboarding generate.
const onboardingSessionId = peekOnboardingSessionId();
if (onboardingSessionId) {
trackPageView(analytics.track, {
page_name: 'onboarding',
area: 'generation_progress',
step_index: 'progress',
step_name: 'generation',
onboarding_session_id: onboardingSessionId,
});
clearOnboardingSessionId();
}
}, [analytics.track, project.id]);
const [conversations, setConversations] = useState<Conversation[]>([]);
const [activeConversationId, setActiveConversationId] = useState<string | null>(
null,
);
const [messagesConversationId, setMessagesConversationId] = useState<string | null>(null);
const [failedMessagesConversationId, setFailedMessagesConversationId] = useState<string | null>(null);
const [conversationLoadError, setConversationLoadError] = useState<string | null>(null);
const [messageLoadRetryNonce, setMessageLoadRetryNonce] = useState(0);
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [activePluginActionPaths, setActivePluginActionPaths] = useState<Set<string>>(() => new Set());
const [hiddenAssistantPluginActionPaths, setHiddenAssistantPluginActionPaths] = useState<Set<string>>(() => new Set());
const [forceStreamingPluginMessageIds, setForceStreamingPluginMessageIds] = useState<Set<string>>(() => new Set());
// True once the initial DB read for the active conversation has settled.
// Auto-send gates on this so it can't fire before listMessages resolves and
// race-clobber the freshly-pushed user + assistant placeholder. Without
// this, the auto-send writes [user, assistant] into state, then the still
// in-flight listMessages PUT response arrives, runs setMessages(list), and
// wipes both — leaving the daemon's run with no client-side message to
// attach the runId to.
const [messagesInitialized, setMessagesInitialized] = useState(false);
const [previewComments, setPreviewComments] = useState<PreviewComment[]>([]);
const [attachedComments, setAttachedComments] = useState<PreviewComment[]>([]);
const [streaming, setStreaming] = useState(false);
const [streamingConversationId, setStreamingConversationId] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [audioVoiceOptionsError, setAudioVoiceOptionsError] = useState<string | null>(null);
const [artifact, setArtifact] = useState<Artifact | null>(null);
const [filesRefresh, setFilesRefresh] = useState(0);
const [projectFiles, setProjectFiles] = useState<ProjectFile[]>([]);
const projectFilesRef = useRef<ProjectFile[]>([]);
const [liveArtifacts, setLiveArtifacts] = useState<LiveArtifactSummary[]>([]);
const [liveArtifactEvents, setLiveArtifactEvents] = useState<LiveArtifactEventItem[]>([]);
const [workspaceFocused, setWorkspaceFocused] = useState(false);
// Per-session override for the BYOK SenseAudio chat's generate_image
// tool. Seeded once from Settings (config.byokImageModel) so the
// composer dropdown opens on the user's chosen default; subsequent
// selections live only in this component's state — page refresh /
// project switch resets to the Settings default. Persistent defaults
// live in Settings → BYOK → SenseAudio → Image generation model.
const [byokImageModelOverride, setByokImageModelOverride] = useState<string>(
config.byokImageModel ?? '',
);
// `closed` → no surface; `review` → read-only saved-state panel with a
// preview + reopen-to-edit action (#1822); `edit` → the textarea editor.
const [instructionsMode, setInstructionsMode] = useState<'closed' | 'review' | 'edit'>('closed');
const [instructionsDraft, setInstructionsDraft] = useState(project.customInstructions ?? '');
const [instructionsSaving, setInstructionsSaving] = useState(false);
// Keep the draft in sync with the server value while the editor is not
// open (e.g. after an external update or project switch). If the saved
// value disappears while the review panel is showing, collapse the
// surface so it never renders a stale or empty read-back.
useEffect(() => {
if (instructionsMode === 'edit') return;
setInstructionsDraft(project.customInstructions ?? '');
if (instructionsMode === 'review' && !(project.customInstructions ?? '').trim()) {
setInstructionsMode('closed');
}
}, [project.customInstructions, instructionsMode]);
// PR #974 round 7 (mrcfps @ useDesignMdState.ts:131): counter that
// bumps on file-changed SSE events, live_artifact* events, and the
// chat streaming-completion edge so the staleness chip stays in sync
// with the underlying mtimes / conversation updatedAt as the user
// keeps working post-finalize. The hook treats it as a dep and
// recomputes whenever it changes.
const [designMdRefreshKey, setDesignMdRefreshKey] = useState(0);
// ----- Continue in CLI / Finalize design package wiring (#451) -----
// The toast surface is shared between Finalize errors and the
// success/fallback toasts emitted from handleContinueInCli.
const projectDetail = useProjectDetail(project.id);
const designMdState = useDesignMdState(project.id, designMdRefreshKey);
const finalize = useFinalizeProject(project.id);
const terminalLauncher = useTerminalLaunch();
const [projectActionsToast, setProjectActionsToast] = useState<{
message: string;
details: string | null;
code?: string | null;
} | null>(null);
const [chatSeed, setChatSeed] = useState<{ id: string; value: string } | null>(null);
const [autoAuditRepairSeed, setAutoAuditRepairSeed] =
useState<{ id: string; value: string } | null>(null);
const [chatPanelWidth, setChatPanelWidth] = useState(readSavedChatPanelWidth);
const [chatPanelMaxWidth, setChatPanelMaxWidth] = useState(MAX_CHAT_PANEL_WIDTH);
const [workspacePanelMinWidth, setWorkspacePanelMinWidth] = useState(MIN_WORKSPACE_PANEL_WIDTH);
const [resizingChatPanel, setResizingChatPanel] = useState(false);
const splitRef = useRef<HTMLDivElement | null>(null);
const chatPanelWidthRef = useRef(chatPanelWidth);
const preferredChatPanelWidthRef = useRef(chatPanelWidth);
const resizeStartPreferredWidthRef = useRef(chatPanelWidth);
const chatPanelMaxWidthRef = useRef(chatPanelMaxWidth);
const resizeStateRef = useRef<{
startClientX: number;
startWidth: number;
isRtl: boolean;
hasMoved: boolean;
} | null>(null);
const pointerCleanupRef = useRef<(() => void) | null>(null);
const pointerFrameRef = useRef<number | null>(null);
const pendingPointerClientXRef = useRef<number | null>(null);
// The persisted set of open tabs + active tab. Persisted via PUT on every
// change; loaded once when the project mounts.
const [openTabsState, setOpenTabsState] = useState<OpenTabsState>({
tabs: [],
active: null,
});
const tabsLoadedRef = useRef(false);
// Routed to FileWorkspace — bumped whenever the user clicks "open" on a
// tool card, an attachment chip, or a produced-file chip in chat. We
// include a nonce so re-clicking the same name after the user closed the
// tab still focuses it.
const [openRequest, setOpenRequest] = useState<{ name: string; nonce: number } | null>(null);
const abortRef = useRef<AbortController | null>(null);
const cancelRef = useRef<AbortController | null>(null);
const streamingConversationIdRef = useRef<string | null>(null);
const sendTextBufferRef = useRef<BufferedTextUpdates | null>(null);
const reattachTextBuffersRef = useRef<Set<BufferedTextUpdates>>(new Set());
const reattachControllersRef = useRef<Map<string, AbortController>>(new Map());
const reattachCancelControllersRef = useRef<Map<string, AbortController>>(new Map());
const completedReattachRunsRef = useRef<Set<string>>(new Set());
const skillCache = useRef<Map<string, string>>(new Map());
const designCache = useRef<Map<string, string>>(new Map());
const templateCache = useRef<Map<string, ProjectTemplate>>(new Map());
// We auto-save the most recent artifact to the project folder. Track the
// last name we persisted so re-renders during streaming don't spawn
// duplicate writes.
const savedArtifactRef = useRef<string | null>(null);
// Pending Write tool invocations: tool_use_id -> destination basename.
// When the matching tool_result lands we refresh the file list and open
// the file as a tab once. Keying off the tool_use_id (rather than
// diffing the file list at end-of-turn) lets us auto-open the moment
// the agent's Write actually completes, without the previous synthetic
// "live" tab that was causing flicker against manual opens.
const pendingWritesRef = useRef<Map<string, string>>(new Map());
// Track which conversation the current messages belong to, so we can
// correctly gate new-conversation creation even during async loads.
const messagesConversationIdRef = useRef<string | null>(null);
const creatingConversationRef = useRef(false);
// Last conversation id this view pushed into the URL. Lets the
// route -> active-conversation sync tell a genuine external navigation
// apart from the URL merely lagging a local conversation switch.
const lastSyncedConversationIdRef = useRef<string | null>(null);
// Live mirror of the currently-viewed project id. Used to bail out of
// the conversation-created async refresh (#1361) if the user switches
// projects while the refetch is in flight — the existing project-load
// effects use the same kind of cancellation guard.
const projectIdRef = useRef(project.id);
useEffect(() => {
projectIdRef.current = project.id;
}, [project.id]);
useEffect(() => {
setChatSeed(null);
setAutoAuditRepairSeed(null);
}, [project.id]);
// Monotonic token bumped on every `conversation-created` refresh dispatch.
// Two rapid events (e.g. concurrent routine runs against the same reused
// project, #1502) can start overlapping `listConversations` calls; if the
// later request resolves first with N+1 conversations and the earlier
// request resolves afterwards with only N, an unconditional
// `setConversations(list)` would drop the newest conversation. Each
// dispatch captures the token at start; only the dispatch whose token
// still equals `conversationsRefreshTokenRef.current` at await-return is
// allowed to apply its result.
const conversationsRefreshTokenRef = useRef(0);
const [creatingConversation, setCreatingConversation] = useState(false);
const currentConversationHasActiveRun = useMemo(
() => messages.some((m) => m.role === 'assistant' && isActiveRunStatus(m.runStatus)),
[messages],
);
const currentConversationLoading = Boolean(
activeConversationId
&& messagesConversationId !== activeConversationId
&& failedMessagesConversationId !== activeConversationId,
);
const currentConversationStreaming = streaming && streamingConversationId === activeConversationId;
const currentConversationBusy = currentConversationLoading
|| currentConversationStreaming
|| currentConversationHasActiveRun;
const currentConversationSendDisabled = currentConversationLoading
|| currentConversationHasActiveRun
|| failedMessagesConversationId === activeConversationId;
const currentConversationActionDisabled = currentConversationBusy || currentConversationSendDisabled;
const newConversationDisabled = creatingConversation;
const activeCompletionNotificationRunsRef = useRef<Set<string>>(new Set());
const completedNotificationRunsRef = useRef<Set<string>>(new Set());
// Load conversations on project switch. If none exist (older projects
// pre-conversations, or a freshly created one whose default seed got
// dropped), create one on the fly.
useEffect(() => {
let cancelled = false;
setConversations([]);
setActiveConversationId(null);
setMessagesConversationId(null);
setFailedMessagesConversationId(null);
setMessageLoadRetryNonce(0);
setConversationLoadError(null);
setMessages([]);
setPreviewComments([]);
setAttachedComments([]);
setStreaming(false);
streamingConversationIdRef.current = null;
setStreamingConversationId(null);
setError(null);
setAudioVoiceOptionsError(null);
setArtifact(null);
savedArtifactRef.current = null;
pendingWritesRef.current.clear();
(async () => {
try {
const list = await listConversations(project.id);
if (cancelled) return;
if (list.length === 0) {
const fresh = await createConversation(project.id);
if (cancelled) return;
if (fresh) {
setConversations([fresh]);
setActiveConversationId(fresh.id);
} else {
throw new Error('Could not create a conversation for this project.');
}
} else {
setConversations(list);
// Issue #1505: when the URL deep-links to a specific
// conversation, prefer that one. Falls through to list[0]
// when the routed id is null or no longer present (the
// routine row may have been deleted between the route
// landing and the conversation list loading).
const routedMatch = routeConversationId
? list.find((c) => c.id === routeConversationId) ?? null
: null;
setActiveConversationId(routedMatch ? routedMatch.id : list[0]!.id);
}
} catch (err) {
if (cancelled) return;
const message = err instanceof Error ? err.message : 'Could not load conversations for this project.';
setConversations([]);
setActiveConversationId(null);
setConversationLoadError(message);
setError(message);
}
})();
return () => {
cancelled = true;
};
}, [project.id]);
// Issue #1505: when the URL changes the routed conversation id while
// we are already inside the project (e.g. the user clicks "Open
// project" on a different routine history row in the same project),
// switch the active conversation without re-fetching the list.
// Guards: only acts when the routed id is non-null AND present in
// the already-loaded list, and only when it differs from the current
// active id. Falls through to a no-op for stale / missing routes so
// the default picker above keeps its result.
useEffect(() => {
if (!routeConversationId) {
lastSeenRouteConversationIdRef.current = null;
return;
}
if (conversations.length === 0) return;
if (routeConversationId === activeConversationId) return;
// When the route still points at the conversation this view last
// pushed to the URL, the mismatch means a local switch (new
// conversation, history pick) moved activeConversationId ahead and
// the URL sync below has not caught up yet. Following the stale
// route here would fight that sync and remount ChatPane in a loop,
// so only react to a genuinely external navigation.
if (routeConversationId === lastSyncedConversationIdRef.current) return;
if (lastSeenRouteConversationIdRef.current === routeConversationId) return;
lastSeenRouteConversationIdRef.current = routeConversationId;
const match = conversations.find((c) => c.id === routeConversationId);
if (!match) return;
setActiveConversationId(routeConversationId);
}, [routeConversationId, conversations, activeConversationId]);
useEffect(() => {
setWorkspaceFocused(false);
}, [project.id]);
// Load messages whenever the active conversation changes. This happens
// on project mount (after conversations load) and on user-triggered
// conversation switches.
useEffect(() => {
if (!activeConversationId) {
setMessages([]);
setMessagesInitialized(false);
setPreviewComments([]);
setAttachedComments([]);
setMessagesConversationId(null);
setFailedMessagesConversationId(null);
messagesConversationIdRef.current = null;
setStreaming(false);
streamingConversationIdRef.current = null;
setStreamingConversationId(null);
return;
}
// Reset the initialized flag so auto-send waits for the new
// conversation's DB read to settle before checking messages.length.
setMessagesInitialized(false);
let cancelled = false;
setMessages([]);
setPreviewComments([]);
setAttachedComments([]);
setArtifact(null);
setMessagesConversationId(null);
setFailedMessagesConversationId(null);
setStreaming(false);
streamingConversationIdRef.current = null;
setStreamingConversationId(null);
savedArtifactRef.current = null;
pendingWritesRef.current.clear();
if (messagesConversationIdRef.current !== activeConversationId) {
messagesConversationIdRef.current = null;
}
(async () => {
try {
const [list, comments] = await Promise.all([
listMessages(project.id, activeConversationId),
fetchPreviewComments(project.id, activeConversationId),
]);
if (cancelled) return;
setMessages(list);
setMessagesInitialized(true);
setPreviewComments(comments);
setAttachedComments([]);
setArtifact(null);
setError(null);
savedArtifactRef.current = null;
pendingWritesRef.current.clear();
messagesConversationIdRef.current = activeConversationId;
setMessagesConversationId(activeConversationId);
setFailedMessagesConversationId(null);
} catch (err) {
if (cancelled) return;
const message = err instanceof Error ? err.message : 'Could not load messages for this conversation.';
setMessages([]);
setPreviewComments([]);
setAttachedComments([]);
setArtifact(null);
setError(message);
savedArtifactRef.current = null;
pendingWritesRef.current.clear();
messagesConversationIdRef.current = null;
setMessagesConversationId(null);
setFailedMessagesConversationId(activeConversationId);
}
})();
return () => {
cancelled = true;
};
}, [project.id, activeConversationId, messageLoadRetryNonce]);
useEffect(() => {
return () => {
sendTextBufferRef.current?.cancel();
sendTextBufferRef.current = null;
// Unmounts / conversation switches should only detach local stream
// consumers. Aborting the daemon cancel controllers here turns routine
// cleanup into an explicit POST /api/runs/:id/cancel, which can mark a
// live run canceled even when the user never clicked Stop.
abortRef.current?.abort();
abortRef.current = null;
cancelRef.current = null;
for (const textBuffer of reattachTextBuffersRef.current) textBuffer.cancel();
reattachTextBuffersRef.current.clear();
for (const controller of reattachControllersRef.current.values()) {
if (abortRef.current === controller) abortRef.current = null;
controller.abort();
}
for (const controller of reattachCancelControllersRef.current.values()) {
// Route changes should only detach the browser-side SSE listener.
// Aborting this signal maps to POST /cancel, so leave the daemon run alive.
if (cancelRef.current === controller) cancelRef.current = null;
}
reattachControllersRef.current.clear();
reattachCancelControllersRef.current.clear();
};
}, [project.id, activeConversationId]);
const cancelSendTextBuffer = useCallback((flushPending = false) => {
if (flushPending) sendTextBufferRef.current?.flush();
sendTextBufferRef.current?.cancel();
sendTextBufferRef.current = null;
}, []);
const cancelReattachTextBuffers = useCallback((flushPending = false) => {
for (const textBuffer of reattachTextBuffersRef.current) {
if (flushPending) textBuffer.flush();
textBuffer.cancel();
}
reattachTextBuffersRef.current.clear();
}, []);
const notifyCompletedRun = useCallback((last: ChatMessage) => {
// Round 7 (mrcfps @ useDesignMdState.ts:131): a chat turn just
// settled — conversation updatedAt almost certainly moved, so
// recompute DESIGN.md staleness even when the turn produced no
// file mutations or live artifacts.
setDesignMdRefreshKey((n) => n + 1);
const status = last.runStatus;
if (status !== 'succeeded' && status !== 'failed') return;
const cfg = config.notifications ?? DEFAULT_NOTIFICATIONS;
if (cfg.soundEnabled) {
playSound(status === 'succeeded' ? cfg.successSoundId : cfg.failureSoundId);
}
if (cfg.desktopEnabled) {
// Successes only interrupt when the user is on another tab/window.
// Failures alert regardless — losing a long agent run silently is
// worse than a small interruption when the page is in focus.
const isHidden = typeof document !== 'undefined' && document.hidden;
const isFocused = typeof document === 'undefined' ? true : document.hasFocus();
if (status === 'failed' || isHidden || !isFocused) {
const title = status === 'succeeded'
? t('notify.successTitle')
: t('notify.failureTitle');
const fallbackBody = status === 'succeeded'
? t('notify.successBody')
: t('notify.failureBody');
const trimmed = (last.content ?? '').trim();
const body = trimmed ? trimmed.slice(0, 80) : fallbackBody;
void showCompletionNotification({
status,
title,
body,
onClick: () => {
if (typeof window !== 'undefined') window.focus();
},
});
}
}
}, [config.notifications, t]);
// Fire completion feedback from assistant run-status transitions rather than
// from the local SSE listener state. A run can finish while its conversation
// is detached; when the user returns, the terminal status should still produce
// the one completion notification for runs this view previously saw active.
useEffect(() => {
const completedMessages: ChatMessage[] = [];
for (const message of messages) {
if (message.role !== 'assistant') continue;
const keys = message.runId ? [message.runId, message.id] : [message.id];
if (isActiveRunStatus(message.runStatus)) {
for (const key of keys) activeCompletionNotificationRunsRef.current.add(key);
continue;
}
if (message.runStatus !== 'succeeded' && message.runStatus !== 'failed') continue;
if (!keys.some((key) => activeCompletionNotificationRunsRef.current.has(key))) continue;
if (keys.some((key) => completedNotificationRunsRef.current.has(key))) continue;
for (const key of keys) completedNotificationRunsRef.current.add(key);
completedMessages.push(message);
}
for (const message of completedMessages) notifyCompletedRun(message);
}, [messages, notifyCompletedRun]);
// Hydrate the open-tabs state once per project. After this initial
// load, every mutation flows through saveTabsState() which keeps DB +
// local state coherent.
useEffect(() => {
let cancelled = false;
tabsLoadedRef.current = false;
(async () => {
const state = await loadTabs(project.id);
if (cancelled) return;
setOpenTabsState(state);
tabsLoadedRef.current = true;
})();
return () => {
cancelled = true;
};
}, [project.id]);
const persistTabsState = useCallback(