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
10058 lines (9699 loc) · 414 KB
/
Copy pathProjectView.tsx
File metadata and controls
10058 lines (9699 loc) · 414 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 {
startTransition,
useCallback,
useEffect,
useId,
useMemo,
useRef,
useState,
useLayoutEffect,
type CSSProperties,
type KeyboardEvent as ReactKeyboardEvent,
type PointerEvent as ReactPointerEvent,
} from 'react';
import { AnimatePresence } from 'motion/react';
import { createHtmlArtifactManifest, inferLegacyManifest } from '../artifacts/manifest';
import { resolveHtmlPointerArtifactTarget } from '../artifacts/pointer';
import { validateHtmlArtifact } from '../artifacts/validate';
import { recoverHtmlDocumentFromMarkdownFence, recoverStandaloneHtmlDocument, resolvePersistedArtifactHtml } from '../artifacts/recover';
import { createArtifactParser } from '../artifacts/parser';
import { useI18n } from '../i18n';
import {
fetchChatRunStatus,
GENERIC_DAEMON_DISCONNECT_CODE,
GENERIC_DAEMON_DISCONNECT_MESSAGE,
fetchVelaLoginStatus,
listActiveChatRuns,
listProjectRuns,
publishDaemonRunFinishedEvent,
reattachDaemonRun,
reportChatRunFeedback,
streamViaDaemon,
} from '../providers/daemon';
import { normalizeCustomReason } from '@open-design/contracts/analytics';
import {
deletePreviewComment,
fetchConnectorStatuses,
fetchPreviewComments,
fetchProjectDesignSystemPackageAudit,
fetchLiveArtifacts,
fetchProjectFiles,
fetchProjectFileText,
fetchSkill,
patchPreviewCommentStatus,
projectRawUrl,
uploadProjectFiles,
upsertPreviewComment,
writeProjectTextFile,
} from '../providers/registry';
import { useProjectFileEvents, type ProjectEvent } from '../providers/project-events';
import { claimProjectTurnIndex, claimRunTurnIndex } from '../analytics/identity';
import { useCoalescedCallback } from '../hooks/useCoalescedCallback';
import { requestAmrArtifactUpgrade } from '../runtime/amr-artifact-upgrade';
import {
type AmrWalletSnapshot,
type ByokMediaDefaults,
type ByokChatProviderConfig,
type ByokChatProtocol,
type ResearchOptions,
} from '@open-design/contracts';
import {
anonymizeArtifactId,
artifactKindToTracking,
projectKindFromMetadataToTracking,
projectKindToTracking,
} from '@open-design/contracts/analytics';
import type {
TrackingArtifactKind,
TrackingDesignSystemApplyTargetKind,
TrackingDesignSystemOrigin,
TrackingDesignSystemStatusValue,
} from '@open-design/contracts/analytics';
import { useAnalytics } from '../analytics/provider';
import {
trackArtifactHeaderClick,
trackComposerBarClick,
trackDesignSystemApplyResult,
trackDesignSystemEnrichClick,
trackPageView,
trackOnboardingPromptPrefilled,
trackOnboardingFirstPromptSent,
trackOnboardingFirstGenerationCompleted,
} 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,
usesAnthropicProxy,
} 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,
removeErrorStatusEvent,
runFailureFieldsFromError,
} from '../runtime/chat-events';
import type { RunFailureClassificationFields } from '../runtime/chat-events';
import {
designDeliveryVerificationPending,
isRetryableAssistantTerminalFailure,
resolveDesignDeliveryOutcome,
type DesignDeliveryOutcome,
} from '../runtime/design-delivery';
import { RESUME_CONTINUE_PROMPT } from '../runtime/resume';
import { checkAmrBalanceGate } from '../runtime/amr-balance-gate';
import { isPaidAmrPlan, resolveAmrPlan } from '../runtime/amr-low-balance-plan';
import { AmrBalanceDialog } from './AmrBalanceDialog';
import { AmrLowBalanceDialog, type AmrLowBalanceDecision } from './AmrLowBalanceDialog';
import {
cancelBrandExtraction,
continueBrandExtraction,
extractBrandFromHtml,
finalizeBrandProject,
} from '../runtime/brands';
import { isOpenDesignHostAvailable } from '@open-design/host';
import {
getBrandBrowser,
BRAND_BROWSER_TAB_ID,
type BrandBrowserPageSnapshotResult,
} from '../runtime/brand-browser-bridge';
import {
BROWSER_PAGE_ARCHIVE_INDEX_FILE,
BROWSER_SERIALIZE_HTML_SCRIPT,
BROWSER_SERIALIZE_STYLES_SCRIPT,
isBrowserPageArchiveManifest,
} from './design-browser-tools';
import type { BrandBrowserAssistConfirm, BrandBrowserAssistResult } from './OdCard';
import {
buildBrandEnrichmentPrompt,
installedBrandEnrichmentSkillIds,
isProgrammaticBrandExtractionProject,
} from '../runtime/brand-enrichment';
import { useBrandReadyPrompt } from '../runtime/useBrandReadyPrompt';
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,
duplicatePluginAsProject,
fetchAppliedPluginSnapshot,
installGeneratedPluginFolder,
listConversations,
listMessages,
loadTabs,
patchConversation,
patchProject,
saveMessage,
startGeneratedPluginShareTask,
cacheTabsLocally,
persistTabsToDaemonNow,
listPlugins,
type SaveMessageOptions,
waitGeneratedPluginShareTask,
} from '../state/projects';
import type {
AppliedPluginSnapshot,
BrandStatus,
ChatAnalyticsEntryFrom,
ChatSessionMode,
InstalledPluginRecord,
RunContextSelection,
WorkspaceContextItem,
} from '@open-design/contracts';
import type {
AgentEvent,
AgentInfo,
AppConfig,
Artifact,
ChatAttachment,
ChatCommentAttachment,
ChatMessage,
ChatMessageFeedbackChange,
Conversation,
DesignSystemSummary,
OpenTabsState,
Project,
ProjectMetadata,
PreviewComment,
PreviewCommentAttachment,
PreviewCommentTarget,
ProjectFile,
LiveArtifactEventItem,
LiveArtifactSummary,
SkillSummary,
} from '../types';
import {
commentsToAttachments,
historyWithCommentAttachmentContext,
mergeAttachedComments,
mergePreviewCommentAttachments,
queuedSlideNavTarget,
removeAttachedComment,
} from '../comments';
import { historyWithApiAttachmentContext } from '../api-attachment-context';
import { filterImplicitProducedFiles } from '../produced-files';
import { AvatarMenu } from './AvatarMenu';
import { EntrySettingsMenu } from './EntrySettingsMenu';
import { HandoffButton } from './HandoffButton';
import { Icon } from './Icon';
import { localizePluginTitle } from './plugins-home/localization';
import { DesignSystemPicker } from './DesignSystemPicker';
import { PluginDetailsModal } from './PluginDetailsModal';
import { DesignSystemPreviewModal } from './DesignSystemPreviewModal';
import { ChatPane } from './ChatPane';
import type { ChatSendMeta, ChatSendOutcome } from './ChatComposer';
import {
CritiqueTheaterMount,
useCritiqueTheaterEnabled,
} from './Theater';
import { useIframeKeepAlivePool } from './IframeKeepAlivePool';
import {
decideAutoOpenAfterWrite,
selectAutoOpenProducedArtifact,
selectAutoOpenTurnArtifact,
} from './auto-open-file';
import { buildRepoImportPrompt, designSystemNeedsRepoConnect } from './design-system-github-evidence';
import { isDesignSystemProject, resolveProjectDesignSystemId } from './design-system-project';
import { collectReferencedJsxNames } from '../runtime/jsx-module-refs';
import { KNOWN_PROVIDERS } from '../state/config';
import { DESIGN_SYSTEM_TAB, FileWorkspace, type BrowserOpenRequest } from './FileWorkspace';
import {
type PluginFolderAgentAction,
} from './design-files/pluginFolderActions';
import { SHARE_TO_COMMUNITY_PROMPT } from './share-to-community/shareToCommunityPrompt';
import { CenteredLoader } from './Loading';
import type { SettingsSection } from './SettingsDialog';
import { Toast } from './Toast';
import { FirstArtifactHint } from './FirstArtifactHint';
import {
consumeOnboardingEntryForProject,
hasSentFirstOnboardingPrompt,
markFirstOnboardingPromptSent,
hasCompletedFirstOnboardingGeneration,
markFirstOnboardingGenerationCompleted,
type OnboardingEntry,
} from '../onboarding/onboarding-entry';
import { producedPreviewableArtifact } from '../onboarding/first-generation';
import { sentPrefilledPrompt } from '../onboarding/first-prompt';
import { beginFirstLoop, recordFirstLoopStep } from '../onboarding/first-loop';
import { BrandReadyPrompt } from './BrandReadyPrompt';
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';
import { effectiveAgentModelChoice } from './agentModelSelection';
import { mediaExecutionPolicyForProjectMetadata } from '../media/execution-policy';
import { mediaModelProviderId } from '../media/models';
import { byokProviderRequiresApiKey } from '../utils/byokProvider';
import {
useByokImageModelOptions,
useByokVideoModelOptions,
useByokSpeechModelOptions,
} from '../media/aihubmix-image-models';
import {
buildFinalizeCredentialsMissingToast,
buildFinalizeRequest,
} from '../lib/resolve-finalize-request';
type BrandBrowserSnapshot =
| { status: 'ready'; html: string; css: string; baseUrl: string }
| { status: 'unavailable'; message: string }
| { status: 'read-failed'; message: string };
type BrandBrowserSnapshotExtractionResult =
| { status: 'handled' }
| { status: 'miss'; message: string | null };
type ProjectChatSendMeta = ChatSendMeta & {
queueOnly?: boolean;
retryOfAssistantId?: string;
sessionMode?: ChatSessionMode;
/** Overrides the run_created / run_finished `entry_from` analytics prop for
* this send (e.g. 'resume_continue' from the resumable-failure Continue
* action). Behavior never depends on it; it only shapes PostHog props. */
entryFrom?: ChatAnalyticsEntryFrom;
/** Marks this send as the AI-optimize (deep enrichment) run so the daemon
* can emit design_system_enrich_result + flag the DS as ai_refined on
* success (tracking spec C14/C15). Daemon mode only. */
dsEnrichment?: boolean;
/** Marks a send replayed from the queued-sends drain. Its payload already
* lives in the queue item, so a pre-run block (e.g. the AMR balance gate)
* must NOT re-queue it — only pause further drains. */
queueDrain?: boolean;
/** The Open Design Cloud balance gate already ran for this exact send at
* the home submit (with any soft warning answered there); skip re-gating
* so the user is never double-prompted for one task. */
amrGatePrechecked?: boolean;
};
export function mergeSavedPreviewComment(current: PreviewComment[], saved: PreviewComment): PreviewComment[] {
const existingIndex = current.findIndex((comment) => comment.id === saved.id);
if (existingIndex < 0) return [...current, saved];
return current.map((comment, index) => (index === existingIndex ? saved : comment));
}
function mergeServerMessageWithLocal(server: ChatMessage, local?: ChatMessage): ChatMessage {
if (!local) return server;
const merged: ChatMessage = { ...server };
if (local.role === 'assistant' && server.role === 'assistant') {
if ((local.content?.length ?? 0) > (server.content?.length ?? 0)) {
merged.content = local.content;
}
if ((local.events?.length ?? 0) > (server.events?.length ?? 0)) {
merged.events = local.events;
}
}
if (!server.producedFiles?.length && local.producedFiles?.length) {
merged.producedFiles = local.producedFiles;
}
if (!server.preTurnFileNames?.length && local.preTurnFileNames?.length) {
merged.preTurnFileNames = local.preTurnFileNames;
}
if (!server.lastRunEventId && local.lastRunEventId) {
merged.lastRunEventId = local.lastRunEventId;
}
if (!server.startedAt && local.startedAt) {
merged.startedAt = local.startedAt;
}
if (!server.endedAt && local.endedAt) {
merged.endedAt = local.endedAt;
}
if (!server.runStatus && local.runStatus) {
merged.runStatus = local.runStatus;
}
return merged;
}
export function mergeServerMessagesIntoConversation(
current: ChatMessage[],
serverMessages: ChatMessage[],
): ChatMessage[] {
const currentById = new Map(current.map((message) => [message.id, message]));
const serverIds = new Set(serverMessages.map((message) => message.id));
const merged = serverMessages.map((message) =>
mergeServerMessageWithLocal(message, currentById.get(message.id)),
);
for (const message of current) {
if (!serverIds.has(message.id)) merged.push(message);
}
return merged;
}
function ensureConversationPresent(
conversations: Conversation[],
conversationId: string,
projectId: string,
): Conversation[] {
if (conversations.some((conversation) => conversation.id === conversationId)) {
return conversations;
}
const now = Date.now();
return [
{
id: conversationId,
projectId,
title: null,
createdAt: now,
updatedAt: now,
},
...conversations,
];
}
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 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;
onApiModelChange?: (model: string) => void;
onRefreshAgents: () => void;
onThemeChange?: (theme: AppConfig['theme']) => void;
onOpenSettings: (section?: SettingsSection) => void;
onOpenAmrSettings?: () => void;
onOpenMcpSettings?: () => void;
onBrowsePlugins?: () => void;
onOpenConnectors?: () => 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;
onDeleteProject?: (id: string) => Promise<boolean> | boolean;
onChangeDefaultDesignSystem?: (designSystemId: string | null) => void;
onDesignSystemsRefresh?: () => Promise<void> | void;
onCreateProjectFromDesignSystem?: (designSystemId: string, title: string) => Promise<void> | void;
onCreateDesignSystemFromProject?: (
sourceProjectId: string,
input: { name?: string; pendingPrompt?: string },
) => Promise<void> | void;
onDuplicateProject?: (
sourceProjectId: string,
input?: { name?: string },
) => Promise<void> | void;
}
interface QueuedChatSend {
id: string;
conversationId: string;
prompt: string;
attachments: ChatAttachment[];
commentAttachments: ChatCommentAttachment[];
meta?: ProjectChatSendMeta;
createdAt: number;
}
interface QueuedChatSendUpdate {
prompt: string;
attachments: ChatAttachment[];
commentAttachments: ChatCommentAttachment[];
meta?: ChatSendMeta;
}
let liveArtifactEventSequence = 0;
// The brand-extraction project's design-system (brand kit) preview tab. Mirrors
// the daemon `BRAND_KIT_FILE` (apps/daemon/src/brands/kit-render.ts); kept as a
// local literal to respect the web↔daemon boundary.
const BRAND_KIT_FILE = 'brand.html';
const BRAND_EMPTY_TRANSCRIPT_RETRY_DELAYS_MS = [120, 500, 1_200, 2_000] as const;
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 COMMENT_INSPECTOR_PANEL_WIDTH = 320;
const MIN_WORKSPACE_PANEL_WIDTH = 400;
const SPLIT_RESIZE_HANDLE_WIDTH = 8;
const BYOK_OPENCODE_UNAVAILABLE_MESSAGE =
'BYOK API runs require OpenCode. Install OpenCode, then rescan local agents in Settings before retrying.';
const BEDROCK_BYOK_UNSUPPORTED_MESSAGE =
'AWS Bedrock BYOK chat requires AWS credential signing and is not supported by the current API-key proxy.';
const CHAT_PANEL_KEYBOARD_STEP = 16;
const DESIGN_SYSTEM_AUDIT_AUTO_REPAIR_ATTEMPTS = 2;
// Trailing-debounce window for the canonical (daemon + SQLite) tab-state write.
// Embedded-browser navigation bursts settle well within this; the local cache
// is written immediately so nothing is lost if the daemon write is coalesced.
const TAB_PERSIST_DEBOUNCE_MS = 400;
// The generic browser-side SSE reconnect-budget exhaustion message emitted by
// consumeDaemonRun when the daemon status fetch still shows the run as
// queued/running (providers/daemon.ts). Both the live-stream onError and the
// reattach-stream onError share this message; neither constitutes an
// authoritative terminal failure. Use isGenericDaemonDisconnect() at both
// sites so generic disconnects stay eligible for attachRecoverableRuns to
// re-query daemon authoritative status on the next tick.
function isGenericDaemonDisconnect(err: unknown): boolean {
return err instanceof Error && (
(err as Error & { code?: string }).code === GENERIC_DAEMON_DISCONNECT_CODE ||
err.message === GENERIC_DAEMON_DISCONNECT_MESSAGE
);
}
// A persisted status/error event represents a generic daemon disconnect when
// either its structured `code` matches GENERIC_DAEMON_DISCONNECT_CODE, OR
// (legacy rows persisted before this code was introduced) its `detail`
// equals the canonical GENERIC_DAEMON_DISCONNECT_MESSAGE with no code set.
// Mirrors isGenericDaemonDisconnect() above, which checks the equivalent
// code-or-message pair on live Error objects for the same reason.
function hasGenericDisconnectFailureEvent(message: ChatMessage): boolean {
return (message.events ?? []).some(
(event) =>
event.kind === 'status' &&
event.label === 'error' &&
(event.code === GENERIC_DAEMON_DISCONNECT_CODE ||
event.detail === GENERIC_DAEMON_DISCONNECT_MESSAGE),
);
}
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 brandExtractionPreviewFileName(projectFiles: readonly ProjectFile[]): string {
return (
projectFiles.find((file) => file.name === 'brand.html')?.name ??
projectFiles.find((file) => file.name.endsWith('/brand.html'))?.name ??
'brand.html'
);
}
function buildBrandAgentExtractionContinuationPrompt(input: {
promptSeed?: string | null;
metadata?: ProjectMetadata | null;
projectFiles: readonly ProjectFile[];
}): string {
const trimmed = input.promptSeed?.trim() ?? '';
const brandId = input.metadata?.brandId?.trim() || '(current brand id)';
const sourceUrl = input.metadata?.brandSourceUrl?.trim() || 'the source website';
const base = /DESIGN SYSTEM EXTRACTION|ready design system is NOT guaranteed/i.test(trimmed)
? trimmed
: [
`Continue the AI design-system extraction for ${sourceUrl}.`,
`Brand id: ${brandId}`,
'',
'The programmatic pass has not produced a ready design system yet. Continue from the current brand.html scaffold and saved project files; do not assume the design system is ready, and do not create a duplicate design-system id.',
'',
'Inspect brand.html, brand.json, DESIGN.md, BRAND.md, context/, logos/, imagery/, fonts/, and system assets. Measure the source website when reachable. If the live page is an anti-bot verification interstitial, ask the user to clear it in the Browser tab before continuing.',
'',
`Write valid partial brand.json updates progressively, run od brand preview ${brandId} after meaningful field groups, then run od brand finalize ${brandId} when the kit is complete. Fix validation errors and keep updating the same registered design system in place.`,
].join('\n');
const visibleFiles = input.projectFiles
.filter((file) => file.name.trim())
.slice(0, 80)
.map((file) => ` - ${file.name}${file.size > 0 ? ` (${Math.round(file.size / 1024)}KB)` : ''}`);
if (visibleFiles.length === 0 || base.includes('Current brand extraction continuation context:')) {
return base;
}
return [
base,
'',
'Current brand extraction continuation context:',
`- Source URL: ${sourceUrl}`,
`- Brand id: ${brandId}`,
'- Files visible in the project right now:',
...visibleFiles,
].join('\n');
}
function designSystemNameForSourceProject(project: Project): string {
const sourceName = project.name.trim() || 'Untitled';
return /\bdesign system\b/i.test(sourceName)
? sourceName
: `${sourceName} Design System`;
}
function buildCreateDesignSystemFromProjectPrompt(input: {
project: Project;
projectFiles: readonly ProjectFile[];
activeDesignSystem?: DesignSystemSummary | null;
}): string {
const visibleFiles = input.projectFiles
.filter((file) => file.name.trim())
.slice(0, 140)
.map((file) => ` - ${file.name}${file.size > 0 ? ` (${Math.round(file.size / 1024)}KB)` : ''}`);
const metadataJson = input.project.metadata
? JSON.stringify(input.project.metadata, null, 2)
: '{}';
const activeDesignSystem = input.activeDesignSystem
? [
`- Active design system id: ${input.activeDesignSystem.id}`,
`- Active design system title: ${input.activeDesignSystem.title}`,
]
: ['- Active design system: (none)'];
return [
'Create this project as a complete Open Design design system workspace.',
'',
'Autonomy requirement:',
'- Do not ask setup or clarification questions during design-system generation.',
'- Do not emit `<question-form>`, "Quick brief — 30 seconds", direction cards, choice cards, or any UI that waits for user input.',
'- The source project already contains the evidence. Choose sensible defaults where details are missing and begin generating the design-system artifacts immediately.',
'',
'Source project handoff:',
`- Source project id: ${input.project.id}`,
`- Source project name: ${input.project.name}`,
...activeDesignSystem,
'- Read `context/source-context.md` first. It lists the copied project files and original project metadata.',
'- Treat every copied file, uploaded asset, reference image, browser snapshot, sketch, generated artifact, and context note in this workspace as design-system evidence.',
'- Use the copied project outputs to infer real visual language, components, layout, interaction patterns, copy tone, tokens, typography, spacing, assets, and anti-patterns.',
'- Do not create another project or another design-system id. Update this new design-system project in place.',
'',
'Source project metadata:',
'```json',
metadataJson,
'```',
'',
'Visible copied files to inspect:',
...(visibleFiles.length > 0 ? visibleFiles : [' - (none listed yet; rely on context/source-context.md after the copy finishes)']),
input.projectFiles.length > visibleFiles.length
? ` - ...and ${input.projectFiles.length - visibleFiles.length} more files listed in context/source-context.md`
: '',
'',
'Expected output:',
'- A clear `DESIGN.md` with product context, visual foundations, color, type, spacing, layout, components, motion, voice, and anti-patterns.',
'- A reusable package: `README.md`, `SKILL.md`, `colors_and_type.css`, provenance notes, `assets/`, `build/` when runtime icons exist, optional `fonts/`, focused `preview/` cards, preserved source examples, and `ui_kits/app/`.',
'- Preserve real source assets when evidence provides them: logos, app icons, tray icons, avatars, wordmarks, imagery, and font files belong in `assets/`, `build/`, or `fonts/`, not only in prose.',
'- Preserve high-signal source/component examples outside `context/` when copied files include substantial implementation or artifact code. Do not replace them with tiny stubs.',
'- Split review previews into focused cards for colors, typography, spacing, radius/shadows, components, brand assets, and applied UI surfaces. Preview cards must visibly load preserved files when available.',
'- Build `ui_kits/app/` as an applied interface kit that reflects the source project, with an index page and component files when the evidence supports them. Do not leave it as a generic static mock.',
'- Keep `README.md`, `SKILL.md`, `DESIGN.md`, preview manifest text, and `ui_kits/app/README.md` synchronized with the final file structure.',
'',
'Completion gate:',
'- Finish only after the project contains reviewable design-system artifacts and the right-side Design System tab can inspect them.',
'- Before your final response, run `"$OD_NODE_BIN" "$OD_BIN" tools connectors design-system-package-audit --path . --fail-on-warnings`.',
'- Fix every audit error and design-quality warning. If an issue cannot be fixed because source evidence is missing, explain that blocker instead of claiming the design system is ready.',
'',
'When finished, summarize the generated files and name the first previews reviewers should inspect.',
].filter(Boolean).join('\n');
}
function chatAttachmentsFromPreviewCommentImages(
images: PreviewCommentAttachment[] | undefined,
): ChatAttachment[] {
if (!Array.isArray(images)) return [];
const seen = new Set<string>();
const out: ChatAttachment[] = [];
for (const image of images) {
const path = image.path.trim();
if (!path || seen.has(path)) continue;
seen.add(path);
out.push({
path,
name: image.name.trim() || path.split('/').pop() || path,
kind: 'image',
});
}
return out;
}
function mergeChatAttachments(...groups: ChatAttachment[][]): ChatAttachment[] {
const seen = new Set<string>();
const out: ChatAttachment[] = [];
for (const group of groups) {
for (const attachment of group) {
const path = attachment.path.trim();
if (!path || seen.has(path)) continue;
seen.add(path);
out.push({ ...attachment, path });
}
}
return out;
}
function historyWithWorkspaceContext(
history: ChatMessage[],
messageId: string,
context: ChatSendMeta['context'] | undefined,
): ChatMessage[] {
const items = context?.workspaceItems ?? [];
if (items.length === 0) return history;
const block = [
'',
'',
'<active-workspace-context>',
'Open Design selected or inferred these workspace contexts for this turn. Treat absolute paths as reference context unless the user explicitly asks to edit them.',
...items.map((item, index) => {
const details = [
item.path ? `path: ${item.path}` : null,
item.absolutePath ? `absolute: ${item.absolutePath}` : null,
item.url ? `url: ${item.url}` : null,
item.title ? `title: ${item.title}` : null,
item.tabId ? `tab: ${item.tabId}` : null,
].filter(Boolean).join(' | ');
return `${index + 1}. ${item.kind}: ${item.label}${details ? ` | ${details}` : ''}`;
}),
'</active-workspace-context>',
].join('\n');
return history.map((message) =>
message.id === messageId && message.role === 'user'
? { ...message, content: `${message.content}${block}` }
: message,
);
}
function commentTaskQuery(attachment: ChatCommentAttachment): string {
return (attachment.comment ?? '').trim();
}
function commentTaskContextAttachment(attachment: ChatCommentAttachment): ChatCommentAttachment {
return {
...attachment,
comment: '',
commentContext: 'query',
};
}
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 autoSendContextKey(projectId: string): string {
return `od:auto-send-context:${projectId}`;
}
/** Set by the home create flow when its submit already ran the Open Design
* Cloud balance gate — the first auto-send must not re-prompt the user. */
function autoSendAmrGateOkKey(projectId: string): string {
return `od:auto-send-amr-gate-ok:${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 readAutoSendContext(projectId: string): RunContextSelection | null {
if (typeof window === 'undefined') return null;
try {
const raw = window.sessionStorage.getItem(autoSendContextKey(projectId));
if (!raw) return null;
const parsed = JSON.parse(raw) as unknown;
return isStoredRunContextSelection(parsed) ? parsed : null;
} catch {
return null;
}
}
function clearAutoSendSession(projectId: string): void {
if (typeof window === 'undefined') return;
try {
window.sessionStorage.removeItem(autoSendFirstMessageKey(projectId));
window.sessionStorage.removeItem(autoSendAttachmentsKey(projectId));
window.sessionStorage.removeItem(autoSendContextKey(projectId));
window.sessionStorage.removeItem(autoSendAmrGateOkKey(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') &&
(record.order === undefined || typeof record.order === 'number')
);
}
function isStoredStringArray(value: unknown): value is string[] {
return Array.isArray(value) && value.every((item) => typeof item === 'string');
}
function isStoredWorkspaceContextItem(value: unknown): value is WorkspaceContextItem {
if (value === null || typeof value !== 'object') return false;
const record = value as Record<string, unknown>;
return (
typeof record.id === 'string' &&
record.id.length > 0 &&
typeof record.kind === 'string' &&
record.kind.length > 0 &&
typeof record.label === 'string' &&
record.label.length > 0 &&
(record.tabId === undefined || typeof record.tabId === 'string') &&
(record.path === undefined || typeof record.path === 'string') &&
(record.absolutePath === undefined || typeof record.absolutePath === 'string') &&
(record.url === undefined || typeof record.url === 'string') &&
(record.title === undefined || typeof record.title === 'string')
);
}
function isStoredRunContextSelection(value: unknown): value is RunContextSelection {
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
const record = value as Record<string, unknown>;
return (
(record.skillIds === undefined || isStoredStringArray(record.skillIds)) &&
(record.pluginIds === undefined || isStoredStringArray(record.pluginIds)) &&
(record.mcpServerIds === undefined || isStoredStringArray(record.mcpServerIds)) &&
(record.connectorIds === undefined || isStoredStringArray(record.connectorIds)) &&
(
record.workspaceItems === undefined ||
(Array.isArray(record.workspaceItems) &&
record.workspaceItems.every(isStoredWorkspaceContextItem))
)
);
}
function fallbackDesignSystemSummaryForProject(
project: Project,
designSystemId: string | null,
): DesignSystemSummary | null {
if (!designSystemId || !isDesignSystemProject(project)) return null;
const metadata = project.metadata;
const sourceUrl = metadata?.brandSourceUrl?.trim() || null;
const title =
metadata?.sourceFileName?.trim()
|| project.name.replace(/\s+Design System\s*$/i, '').trim()
|| project.name
|| 'Design system';
return {
id: designSystemId,
title,
category: 'Brands',
summary: sourceUrl ? `Draft design system extracted from ${sourceUrl}.` : '',
swatches: [],
surface: 'web',
source: 'user',
status: 'draft',
isEditable: true,
projectId: project.id,
...(sourceUrl
? { provenance: { sourceUrls: [sourceUrl], sourceNotes: `Extracting from ${sourceUrl}` } }
: {}),
};
}
function isBrandStatusValue(value: unknown): value is BrandStatus {
return value === 'extracting' || value === 'needs_input' || value === 'ready' || value === 'failed';
}
function brandExtractionAllowsEditing(status: BrandStatus | null): boolean {
return status === 'ready' || status === 'failed';