-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Expand file tree
/
Copy pathApp.tsx
More file actions
2520 lines (2400 loc) · 95.2 KB
/
Copy pathApp.tsx
File metadata and controls
2520 lines (2400 loc) · 95.2 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, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { flushSync } from 'react-dom';
import { AnimatePresence, motion, MotionConfig } from 'motion/react';
import { useAnalytics } from './analytics/provider';
import {
trackFileUploadResult,
trackProjectCreateResult,
} from './analytics/events';
import { deriveUploadCohort } from './analytics/upload-tracking';
import { setPendingDesignSystemCreateEntry } from './analytics/ds-create-entry';
import { detectClientType } from './analytics/identity';
import {
deriveConfigureGlobals,
projectKindFromMetadataToTracking,
fidelityToTracking,
} from '@open-design/contracts/analytics';
import type { AmrModelsResponse, ChatSessionMode, RunContextSelection } from '@open-design/contracts';
import { DEFAULT_UNSELECTED_SCENARIO_PLUGIN_ID } from '@open-design/contracts';
import { EntryView } from './components/EntryView';
import type { IntegrationTab } from './components/IntegrationsView';
import { MarketplaceView } from './components/MarketplaceView';
import { PluginDetailView } from './components/PluginDetailView';
import type { CreateInput, ImportClaudeDesignOutcome } from './components/NewProjectPanel';
import { MemoryToast } from './components/MemoryToast';
import { Toast } from './components/Toast';
import { CenteredLoader } from './components/Loading';
import { PetOverlay, type PetTaskCenter } from './components/pet/PetOverlay';
import { buildPetTaskCenter } from './components/pet/taskCenter';
import { migrateCustomPetAtlas } from './components/pet/pets';
import { ProjectView } from './components/ProjectView';
import { TooltipLayer } from './components/TooltipLayer';
import { openWorkspaceTab, WorkspaceTabsBar } from './components/WorkspaceTabsBar';
import {
DesignSystemCreationFlow,
DesignSystemDetailView,
} from './components/DesignSystemFlow';
import {
IframeKeepAliveProvider,
useIframeKeepAlivePool,
} from './components/IframeKeepAlivePool';
import {
SettingsDialog,
switchApiProtocolConfig,
updateCurrentApiProtocolConfig,
type SettingsSection,
type SettingsHighlight,
} from './components/SettingsDialog';
import { PrivacyConsentModal } from './components/PrivacyConsentModal';
import {
daemonIsLive,
fetchAppVersionInfo,
fetchAgentsStream,
fetchDesignSystems,
fetchDesignTemplates,
fetchPromptTemplates,
fetchSkills,
uploadProjectFiles,
replaceProjectWorkingDir,
} from './providers/registry';
import {
RUNS_CHANGED_EVENT,
fetchAmrModels,
fetchVelaLoginStatus,
listProjectRuns,
type VelaLoginStatus,
} from './providers/daemon';
import { AMR_LOGIN_STATUS_EVENT } from './components/amrLoginPolling';
import { CollabDemoView } from './collab/CollabDemoView';
import { CommunityView } from './components/CommunityView';
import { seedHomeComposerPrompt } from './components/HomeView';
import { goBack, navigate, useRoute } from './router';
import {
fetchDaemonConfig,
DEFAULT_PET,
fetchMediaProvidersFromDaemon,
hasAnyConfiguredProvider,
fetchComposioConfigFromDaemon,
loadConfig,
mergeDaemonConfig,
mergeDaemonMediaProviders,
saveConfig,
shouldSyncLocalMediaProvidersToDaemon,
syncComposioConfigToDaemon,
syncConfigToDaemon,
syncMediaProvidersToDaemon,
} from './state/config';
import { applyAppearanceToDocument } from './state/appearance';
import { isMacPlatform } from './utils/platform';
import {
createDesignSystemProjectFromProject,
createProject,
createPluginShareProject,
deleteProject as deleteProjectApi,
duplicateProject,
getProject,
importClaudeDesignZip,
importFolderProject,
listProjects,
listTemplates,
deleteTemplate,
patchProject,
} from './state/projects';
import { useModalWindowDragGuard } from './hooks/useModalWindowDragGuard';
import type {
PluginShareAction,
PluginShareProjectOutcome,
} from './state/projects';
import type { OpenDesignHostProjectImportSuccess } from '@open-design/host';
import { useI18n } from './i18n';
import { liveArtifactTabId } from './types';
import type {
AgentInfo,
AgentModelChoice,
ApiProtocol,
AppConfig,
AppVersionInfo,
ChatAttachment,
DesignSystemGenerationJob,
DesignSystemSummary,
Project,
ProjectMetadata,
ProjectTemplate,
ProviderModelOption,
PromptTemplateSummary,
SkillSummary,
} from './types';
type AppCreateProjectInput = Omit<CreateInput, 'metadata'> & {
metadata?: CreateInput['metadata'];
pendingPrompt?: string;
pluginId?: string;
pluginType?: string;
appliedPluginSnapshotId?: string;
pluginInputs?: Record<string, unknown>;
initialRunContext?: RunContextSelection | null;
conversationMode?: ChatSessionMode;
autoSendFirstMessage?: boolean;
requestId?: string;
pendingFiles?: File[];
userWorkingDirToken?: string;
linkedDirs?: string[] | null;
};
const APP_CONFIG_CHANGED_EVENT = 'open-design:app-config-changed';
const AMR_AGENT_ID = 'amr';
const AMR_PROFILE_ENV_KEY = 'OPEN_DESIGN_AMR_PROFILE';
const AGENT_FOCUS_REFRESH_THROTTLE_MS = 10_000;
export function shouldSyncMediaProvidersOnSave(
mediaProviders: AppConfig['mediaProviders'],
options?: { force?: boolean },
): boolean {
return Boolean(options?.force) || hasAnyConfiguredProvider(mediaProviders);
}
function normalizeSavedComposioConfig(config: AppConfig['composio']): AppConfig['composio'] {
const apiKey = config?.apiKey?.trim() ?? '';
if (apiKey) {
return {
...config,
apiKey: '',
apiKeyConfigured: true,
apiKeyTail: apiKey.slice(-4),
};
}
return { ...(config ?? {}) };
}
function amrProfileForConfig(config: AppConfig): string | null {
const profile = config.agentCliEnv?.[AMR_AGENT_ID]?.[AMR_PROFILE_ENV_KEY];
return typeof profile === 'string' && profile ? profile : null;
}
function mergeLinkedDirsIntoMetadata(
metadata: ProjectMetadata | undefined,
linkedDirs?: string[] | null,
): ProjectMetadata | undefined {
const nextDirs = (linkedDirs ?? []).map((dir) => dir.trim()).filter(Boolean);
if (nextDirs.length === 0) return metadata;
const baseMetadata = metadata ?? { kind: 'other' };
return {
...baseMetadata,
linkedDirs: Array.from(new Set([...(baseMetadata.linkedDirs ?? []), ...nextDirs])),
};
}
function sameAgentModelChoice(
left: AgentModelChoice | undefined,
right: AgentModelChoice | undefined,
): boolean {
return (left?.model ?? null) === (right?.model ?? null)
&& (left?.reasoning ?? null) === (right?.reasoning ?? null);
}
function clearStaleAmrModelChoiceOnProfileChange(
previous: AppConfig,
next: AppConfig,
): AppConfig {
if (amrProfileForConfig(previous) === amrProfileForConfig(next)) return next;
const previousChoice = previous.agentModels?.[AMR_AGENT_ID];
const nextChoice = next.agentModels?.[AMR_AGENT_ID];
if (!nextChoice || !sameAgentModelChoice(previousChoice, nextChoice)) return next;
const nextAgentModels = { ...(next.agentModels ?? {}) };
delete nextAgentModels[AMR_AGENT_ID];
return { ...next, agentModels: nextAgentModels };
}
type ProjectListRequest = {
generation: number;
mutationVersion: number;
};
export async function persistComposioConfigChange(
current: AppConfig,
composio: AppConfig['composio'],
sync: (config: AppConfig['composio']) => Promise<boolean> = syncComposioConfigToDaemon,
): Promise<AppConfig> {
const saved = await sync(composio);
if (!saved) throw new Error('Composio config save failed');
return {
...current,
composio: normalizeSavedComposioConfig(composio),
};
}
export function buildPersistedConfig(next: AppConfig, current: AppConfig): AppConfig {
const stalePrivacySnapshot =
current.privacyDecisionAt != null && next.privacyDecisionAt == null;
return {
...next,
onboardingCompleted: current.onboardingCompleted ? true : next.onboardingCompleted,
...(stalePrivacySnapshot
? {
installationId: current.installationId,
privacyDecisionAt: current.privacyDecisionAt,
telemetry: current.telemetry,
}
: {}),
composio: next.composio
? {
apiKey: '',
apiKeyConfigured: Boolean(next.composio.apiKeyConfigured),
apiKeyTail: next.composio.apiKeyTail ?? '',
}
: next.composio,
};
}
/**
* True when `next` and `last` produce an identical persisted shape —
* i.e. the only diffs between them are fields that buildPersistedConfig
* intentionally strips before disk/daemon writes (the Composio API key
* draft today; any future save-on-explicit-confirm secrets later).
*
* The autosave loop in Settings uses this to skip the "All changes
* saved" indicator transition when the user has only typed an unsaved
* secret. Without it, autosave completes a no-op write and flashes
* "Saved" — misleading users into trusting that a sensitive key has
* been persisted when in fact only the section-local "Save key"
* gesture commits it.
*/
export function isAutosaveDraftOnlyChange(next: AppConfig, last: AppConfig): boolean {
return (
JSON.stringify(buildPersistedConfig(next, next))
=== JSON.stringify(buildPersistedConfig(last, last))
);
}
export function resolveSettingsCloseConfig(
rendered: AppConfig,
latestPersisted: AppConfig,
): AppConfig {
const base = latestPersisted === rendered ? rendered : latestPersisted;
return base.onboardingCompleted ? base : { ...base, onboardingCompleted: true };
}
function mergeAmrModelsIntoAgents(
agents: AgentInfo[],
amrModels: AmrModelsResponse | null,
): AgentInfo[] {
if (!amrModels || amrModels.models.length === 0) return agents;
return agents.map((agent) => {
if (agent.id !== 'amr') return agent;
const shouldPreferAgentModels =
amrModels.source === 'preset' &&
Array.isArray(agent.models) &&
agent.models.length > 0;
if (shouldPreferAgentModels) return agent;
return { ...agent, models: amrModels.models, modelsSource: 'live' };
});
}
const CANONICAL_AGENT_ORDER = [
'amr',
'claude',
'codex',
'devin',
'gemini',
'opencode',
'hermes',
'trae-cli',
'grok-build',
'kimi',
'cursor-agent',
'qwen',
'qoder',
'copilot',
'pi',
'kiro',
'kilo',
'vibe',
'deepseek',
'aider',
'antigravity',
'reasonix',
] as const;
const CANONICAL_AGENT_ORDER_INDEX = new Map<string, number>(
CANONICAL_AGENT_ORDER.map((id, index) => [id, index]),
);
function orderAgentsByRegistry(agents: AgentInfo[]): AgentInfo[] {
return agents
.map((agent, index) => ({ agent, index }))
.sort((left, right) => {
const leftRank =
CANONICAL_AGENT_ORDER_INDEX.get(left.agent.id) ??
CANONICAL_AGENT_ORDER.length;
const rightRank =
CANONICAL_AGENT_ORDER_INDEX.get(right.agent.id) ??
CANONICAL_AGENT_ORDER.length;
if (leftRank !== rightRank) return leftRank - rightRank;
return left.index - right.index;
})
.map(({ agent }) => agent);
}
function upsertAgent(agents: AgentInfo[], agent: AgentInfo): AgentInfo[] {
const index = agents.findIndex((item) => item.id === agent.id);
if (index === -1) return [...agents, agent];
const next = agents.slice();
next[index] = agent;
return next;
}
function isAbortError(err: unknown): boolean {
return (
typeof err === 'object' &&
err !== null &&
'name' in err &&
(err as { name?: unknown }).name === 'AbortError'
);
}
export function App() {
// `reducedMotion="user"` makes every motion/react component honor the OS
// `prefers-reduced-motion` setting: transform/layout animations are zeroed
// out while opacity-only changes are kept. The CSS `@media (prefers-reduced-
// motion: reduce)` block covers the CSS-keyframe surfaces, but the dialogs,
// toasts and popovers that moved to motion/react need this gate too — without
// it they keep springing/sliding for users who asked us not to animate.
return (
<MotionConfig reducedMotion="user">
<IframeKeepAliveProvider>
<AppInner />
</IframeKeepAliveProvider>
</MotionConfig>
);
}
function AppInner() {
const { t } = useI18n();
const iframeKeepAlivePool = useIframeKeepAlivePool();
const clientType = useMemo(() => detectClientType(), []);
useModalWindowDragGuard();
// Observability marker. `apps/web/src/observability/white-screen.ts`
// keys its "app actually mounted" success condition on this attribute
// because the dynamic-import loading shell (`<div class="od-loading-shell">
// Loading Open Design…</div>`) is itself >MIN_VISIBLE_TEXT and would
// otherwise be mistaken for a real mount. Survives subsequent render
// crashes — once App has mounted at least once, it's no longer a white
// screen (subsequent failures show up as `$exception`).
useEffect(() => {
if (typeof document !== 'undefined') {
document.documentElement.setAttribute('data-od-app-mounted', '1');
document.querySelectorAll('.od-loading-shell').forEach((node) => node.remove());
}
}, []);
const [config, setConfig] = useState<AppConfig>(() => loadConfig());
const configRef = useRef(config);
configRef.current = config;
const latestPersistedConfigRef = useRef(config);
latestPersistedConfigRef.current = config;
const [settingsOpen, setSettingsOpen] = useState(false);
// Surfaced when a Home-picked working dir could not be applied to a freshly
// created project (expired/invalid desktop token, daemon rejection). Without
// this the failure was swallowed and the user believed their folder was in
// effect while the project actually stayed in the managed root.
const [workingDirError, setWorkingDirError] = useState<string | null>(null);
const [projectOpenError, setProjectOpenError] = useState<string | null>(null);
const [settingsWelcome, setSettingsWelcome] = useState(false);
const [settingsInitialSection, setSettingsInitialSection] = useState<SettingsSection>('execution');
const [settingsHighlight, setSettingsHighlight] = useState<SettingsHighlight>(null);
const [integrationInitialTab, setIntegrationInitialTab] = useState<IntegrationTab>('mcp');
const [daemonLive, setDaemonLive] = useState(false);
const [agents, setAgents] = useState<AgentInfo[]>([]);
const amrModelsRef = useRef<AmrModelsResponse | null>(null);
const amrPollGenerationRef = useRef(0);
const agentStreamRequestSeqRef = useRef(0);
const agentFocusRefreshLastRunRef = useRef(Date.now());
const [amrPollRestartToken, setAmrPollRestartToken] = useState(0);
const [providerModelsCache, setProviderModelsCache] = useState<
Record<string, ProviderModelOption[]>
>({});
// Functional skills (capabilities the agent invokes mid-task) — stays
// small and lives under the Settings → Skills surface.
const [skills, setSkills] = useState<SkillSummary[]>([]);
// Design templates (rendering catalogue: decks, prototypes, image/video/
// audio templates) — sourced from /api/design-templates and shown in the
// EntryView Templates tab. See specs/current/skills-and-design-templates.md.
const [designTemplates, setDesignTemplates] = useState<SkillSummary[]>([]);
const [designSystems, setDesignSystems] = useState<DesignSystemSummary[]>([]);
const [pendingDesignSystemRevisionJobs, setPendingDesignSystemRevisionJobs] = useState<
Record<string, DesignSystemGenerationJob>
>({});
const [projects, setProjects] = useState<Project[]>([]);
const projectsRef = useRef<Project[]>(projects);
useEffect(() => {
projectsRef.current = projects;
}, [projects]);
const [petTaskCenter, setPetTaskCenter] = useState<PetTaskCenter>({
running: [],
queued: [],
recent: [],
});
const pendingLocalProjectIdsRef = useRef<Set<string>>(new Set());
const locallyDeletedProjectIdsRef = useRef<Map<string, number>>(new Map());
const projectListMutationVersionRef = useRef(0);
const projectListRequestGenerationRef = useRef(0);
const latestAppliedProjectListGenerationRef = useRef(0);
const [templates, setTemplates] = useState<ProjectTemplate[]>([]);
const [promptTemplates, setPromptTemplates] = useState<
PromptTemplateSummary[]
>([]);
const [appVersionInfo, setAppVersionInfo] = useState<AppVersionInfo | null>(
null,
);
const [daemonMediaProviders, setDaemonMediaProviders] = useState<
AppConfig['mediaProviders'] | null
>(null);
const [daemonMediaProvidersFetchState, setDaemonMediaProvidersFetchState] = useState<
'idle' | 'ok' | 'error'
>('idle');
const [mediaProvidersNotice, setMediaProvidersNotice] = useState<string | null>(null);
// Per-resource loading flags. Each goes false the moment its own fetch
// resolves so each entry-view tab can render as its data lands instead of
// every tab waiting on the slowest endpoint (typically `/api/agents`,
// which probes CLI versions and can take seconds on cold start). The entry
// view picks the right flag for whichever tab the user is currently on.
const [agentsLoading, setAgentsLoading] = useState(true);
const [skillsLoading, setSkillsLoading] = useState(true);
const [dsLoading, setDsLoading] = useState(true);
const [projectsLoading, setProjectsLoading] = useState(true);
const [promptTemplatesLoading, setPromptTemplatesLoading] = useState(true);
// Goes true once the daemon-persisted config (agentId/designSystemId/etc.)
// has merged into local state. Auto-selection effects below wait on this
// so they don't race ahead of the daemon-stored choice and overwrite it
// with a freshly picked first-available agent.
const [daemonConfigLoaded, setDaemonConfigLoaded] = useState(false);
// Narrower flag dedicated to the Composio API key hydration. The key is
// persisted by the daemon (and only reflected back via apiKeyConfigured
// + apiKeyTail), so after a dev-server restart there is a window where
// the dialog can render an empty Composio input even though a saved key
// exists. Settings → Connectors uses this to render a skeleton over the
// input + buttons instead of an empty input that the user might
// mistake for "no key saved" — and to disable Save/Clear so a misclick
// can't overwrite the saved state with `''` before hydration lands.
const [composioConfigLoading, setComposioConfigLoading] = useState(true);
const route = useRoute();
const analytics = useAnalytics();
const beginAgentStreamRequest = useCallback(() => {
agentStreamRequestSeqRef.current += 1;
return agentStreamRequestSeqRef.current;
}, []);
const isCurrentAgentStreamRequest = useCallback((requestId: number) => {
return agentStreamRequestSeqRef.current === requestId;
}, []);
const restartAmrPolling = useCallback(() => {
amrPollGenerationRef.current += 1;
setAmrPollRestartToken((current) => current + 1);
}, []);
// v2 schema removed the standalone `app_launch` event; the initial
// page_view fires from each top-level page surface (home / projects /
// automations / plugins / design_systems / integrations) instead.
// `detectClientType` still feeds analytics identity via the provider.
void detectClientType;
const rememberLocalProject = useCallback((projectId: string) => {
pendingLocalProjectIdsRef.current.add(projectId);
locallyDeletedProjectIdsRef.current.delete(projectId);
projectListMutationVersionRef.current += 1;
}, []);
const clearLocalProject = useCallback((projectId: string, options?: { deleted?: boolean }) => {
pendingLocalProjectIdsRef.current.delete(projectId);
projectListMutationVersionRef.current += 1;
if (options?.deleted) {
locallyDeletedProjectIdsRef.current.set(
projectId,
projectListMutationVersionRef.current,
);
}
}, []);
const beginProjectListRequest = useCallback((): ProjectListRequest => {
projectListRequestGenerationRef.current += 1;
return {
generation: projectListRequestGenerationRef.current,
mutationVersion: projectListMutationVersionRef.current,
};
}, []);
const reconcileFetchedProjects = useCallback((list: Project[], request: ProjectListRequest) => {
const pendingLocalProjectIds = pendingLocalProjectIdsRef.current;
const locallyDeletedProjectIds = locallyDeletedProjectIdsRef.current;
const fetchedIds = new Set(list.map((project) => project.id));
if (request.generation < latestAppliedProjectListGenerationRef.current) {
const visibleList =
locallyDeletedProjectIds.size > 0
? list.filter((project) => !locallyDeletedProjectIds.has(project.id))
: list;
if (visibleList.length === 0) return false;
const hydratableProjects = visibleList.filter(
(project) =>
pendingLocalProjectIds.has(project.id),
);
if (hydratableProjects.length === 0) return false;
const hydratableById = new Map(
hydratableProjects.map((project) => [project.id, project]),
);
for (const project of hydratableProjects) {
pendingLocalProjectIds.delete(project.id);
}
setProjects((current) => {
let changed = false;
const currentIds = new Set<string>();
const next = current.map((project) => {
currentIds.add(project.id);
const hydrated = hydratableById.get(project.id);
if (!hydrated) return project;
changed = true;
hydratableById.delete(project.id);
return hydrated;
});
for (const project of hydratableById.values()) {
if (currentIds.has(project.id)) continue;
changed = true;
next.push(project);
}
return changed ? next : current;
});
return true;
}
latestAppliedProjectListGenerationRef.current = request.generation;
for (const id of fetchedIds) pendingLocalProjectIds.delete(id);
for (const [id, deletedAtMutationVersion] of locallyDeletedProjectIds) {
if (
request.mutationVersion >= deletedAtMutationVersion
&& !fetchedIds.has(id)
) {
locallyDeletedProjectIds.delete(id);
}
}
const activeDeletedProjectIds = new Set(locallyDeletedProjectIds.keys());
const visibleList =
activeDeletedProjectIds.size > 0
? list.filter((project) => !activeDeletedProjectIds.has(project.id))
: list;
const visibleFetchedIds =
activeDeletedProjectIds.size > 0
? new Set(visibleList.map((project) => project.id))
: fetchedIds;
setProjects((current) => {
const preserved = current.filter(
(project) =>
pendingLocalProjectIds.has(project.id) &&
!visibleFetchedIds.has(project.id) &&
!activeDeletedProjectIds.has(project.id),
);
return preserved.length > 0 ? [...preserved, ...visibleList] : visibleList;
});
return true;
}, []);
// Propagate the Privacy toggle through to PostHog without a reload —
// posthog-js's opt_out_capturing flips a localStorage flag that makes
// every subsequent capture() a no-op. When the user opts back in we
// call opt_in_capturing to resume.
useEffect(() => {
analytics.setConsent(config.telemetry?.metrics === true);
}, [analytics.setConsent, config.telemetry?.metrics]);
// Sync PostHog's distinct_id with the anonymous installationId, both on
// first opt-in (when the daemon stamps a fresh id) and on Delete-my-data
// rotation (when PrivacySection.tsx generates a new one). posthog-js
// caches the previous id in localStorage; identify() alone would stitch
// the two ids together, so applyIdentity() does reset() first to
// guarantee the new session is fully decoupled from the deleted one.
useEffect(() => {
if (config.telemetry?.metrics !== true) return;
analytics.setIdentity(config.installationId ?? null);
}, [analytics.setIdentity, config.installationId, config.telemetry?.metrics]);
// App-level AMR sign-in state — declared here because the configure
// globals effect below reads it; the sync effects live next to the
// other AMR plumbing further down.
const [amrLoginStatus, setAmrLoginStatus] = useState<VelaLoginStatus | null>(null);
// v2 analytics requires every event to carry the configure-state
// triplet (has_available_configure_cli / configure_type /
// configure_availability). We push it into the PostHog global register
// whenever the user's execution-mode config or the detected agent list
// changes; the next capture inherits the fresh values, so dashboards
// can segment by execution setup without per-helper boilerplate.
//
// Gated on `agentsLoading` so the cold-start probe (`fetchAgentsStream()`
// lands asynchronously after this effect's first run) does not stamp
// the first home/projects/plugins page_view with
// has_available_configure_cli=false / configure_availability=unavailable
// on machines that DO have an installed CLI. While the probe is in
// flight we leave the boot defaults ('unknown'/'unknown') in place,
// matching what the helper would return for an empty agent list with
// no mode pinned.
useEffect(() => {
if (agentsLoading) return;
const byokConfigured = (() => {
const protocols = config.apiProtocolConfigs;
if (!protocols) return Boolean(config.apiKey?.trim());
return Object.values(protocols).some(
(cfg) => Boolean(cfg?.apiKey?.trim()),
);
})();
const globals = deriveConfigureGlobals({
mode: config.mode,
agentId: config.agentId,
agents: agents.map((a) => ({ id: a.id, available: a.available })),
byokConfigured,
amrAuthorized: amrLoginStatus?.loggedIn === true,
});
analytics.setConfigureGlobals(globals);
}, [
analytics.setConfigureGlobals,
agentsLoading,
amrLoginStatus,
config.mode,
config.agentId,
config.apiKey,
config.apiProtocolConfigs,
agents,
]);
// Sync theme preference to the <html> element so CSS variables pick it up.
// useLayoutEffect (vs useEffect) fires before the browser paints, so a
// live theme switch in Settings applies atomically — no 1-frame flash of
// the old theme. Safe here because the component tree is ssr:false.
useLayoutEffect(() => {
applyAppearanceToDocument({
theme: config.theme ?? 'system',
accentColor: config.accentColor,
});
}, [config.theme, config.accentColor]);
// Tell the daemon what the user is currently looking at, so the MCP
// server can surface it as `get_active_context` to a coding agent in
// another repo. Best-effort fire-and-forget; the daemon holds it in
// memory with a short TTL and the MCP layer falls back to
// {active:false} if this hasn't run.
const activeProjectId = route.kind === 'project' ? route.projectId : null;
const activeFileName = route.kind === 'project' ? route.fileName : null;
// Gate the privacy banner on three things:
// 1. Daemon config has hydrated (privacyDecisionAt is daemon-owned).
// 2. The user has not yet made a privacy decision.
// 3. Onboarding is complete (Skip and design-system creation both flip
// onboardingCompleted to true; see handleCompleteOnboarding wiring).
// Once onboarding is done the banner is allowed on any route — including
// the project view the design-system finish path drops the user into, so
// they can read and acknowledge the disclosure while the first generation
// is running. Settings is irrelevant to visibility; the banner sits above
// the modal-backdrop layer in index.css so opening Settings does not hide
// it.
const showPrivacyConsent =
daemonConfigLoaded &&
config.privacyDecisionAt == null &&
config.onboardingCompleted === true;
useEffect(() => {
const body = activeProjectId
? { projectId: activeProjectId, fileName: activeFileName }
: { active: false };
fetch('/api/active', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
}).catch(() => {
// Daemon down or transient network — not worth surfacing.
});
}, [activeProjectId, activeFileName]);
useEffect(() => {
if (!daemonLive) return;
let cancelled = false;
let timer: number | null = null;
const pollGeneration = amrPollGenerationRef.current + 1;
amrPollGenerationRef.current = pollGeneration;
const pollDelayMs = 1_000;
const maxPresetPolls = 10;
let presetPolls = 0;
const applyAmrModels = async () => {
const result = await fetchAmrModels();
if (
cancelled ||
amrPollGenerationRef.current !== pollGeneration ||
!result ||
!Array.isArray(result.models) ||
result.models.length === 0
) {
return;
}
amrModelsRef.current = result;
setAgents((current) => mergeAmrModelsIntoAgents(current, result));
const shouldPollPreset =
result.source === 'preset' &&
!result.remoteError &&
presetPolls < maxPresetPolls;
if (shouldPollPreset) {
presetPolls += 1;
timer = window.setTimeout(() => {
void applyAmrModels();
}, pollDelayMs);
}
};
void applyAmrModels();
return () => {
cancelled = true;
if (timer !== null) window.clearTimeout(timer);
};
}, [amrPollRestartToken, daemonLive]);
// App-level AMR sign-in state. Feeds two analytics globals: the
// `amr` configure_type bucket (deriveConfigureGlobals below) and the
// `user_id` public param (the AMR account id is the only join key
// between this PostHog project and the AMR-side one). Child surfaces
// push status changes up via onAmrLoginStatusChange; the global
// AMR_LOGIN_STATUS_EVENT covers logins finishing in surfaces that
// unmounted before their poll settled.
useEffect(() => {
let cancelled = false;
const sync = async () => {
const status = await fetchVelaLoginStatus();
if (!cancelled && status) setAmrLoginStatus(status);
};
void sync();
const onStatusEvent = () => {
void sync();
};
window.addEventListener(AMR_LOGIN_STATUS_EVENT, onStatusEvent);
return () => {
cancelled = true;
window.removeEventListener(AMR_LOGIN_STATUS_EVENT, onStatusEvent);
};
}, [daemonLive]);
useEffect(() => {
analytics.setUserId(
amrLoginStatus?.loggedIn === true ? amrLoginStatus.user?.id ?? null : null,
);
}, [analytics.setUserId, amrLoginStatus]);
const handleAmrLoginStatusChange = useCallback((status: VelaLoginStatus | null) => {
if (status) setAmrLoginStatus(status);
if (status?.loggedIn !== true) return;
restartAmrPolling();
}, [restartAmrPolling]);
// Bootstrap — detect daemon, then fan out independent fetches so each
// entry-view tab can render the moment its own data lands. Earlier this
// was one Promise.all behind a global "Loading workspace…" placeholder,
// which made the slowest endpoint (typically `/api/agents` on cold start)
// gate every tab including the ones that don't need agents at all.
useEffect(() => {
let cancelled = false;
const agentStreamAbort = new AbortController();
(async () => {
const alive = await daemonIsLive();
if (cancelled) return;
setDaemonLive(alive);
if (!alive) {
// No daemon — clear every loading flag so empty states render
// instead of the entry view sitting on indefinite spinners.
setAgentsLoading(false);
setSkillsLoading(false);
setDsLoading(false);
setProjectsLoading(false);
setPromptTemplatesLoading(false);
setDaemonConfigLoaded(true);
// Composio hydration also depends on the daemon. With no daemon
// we just keep whatever localStorage already held; drop the
// skeleton so the Settings → Connectors input reflects state.
setComposioConfigLoading(false);
return;
}
const agentRequestId = beginAgentStreamRequest();
void fetchAgentsStream({
signal: agentStreamAbort.signal,
onAgent: (agent) => {
if (cancelled || !isCurrentAgentStreamRequest(agentRequestId)) return;
setAgents((current) =>
mergeAmrModelsIntoAgents(
upsertAgent(current, agent),
amrModelsRef.current,
),
);
},
})
.then((list) => {
if (cancelled || !isCurrentAgentStreamRequest(agentRequestId)) return;
setAgents(
mergeAmrModelsIntoAgents(
orderAgentsByRegistry(list),
amrModelsRef.current,
),
);
})
.catch((err) => {
if (
cancelled ||
isAbortError(err) ||
!isCurrentAgentStreamRequest(agentRequestId)
) {
return;
}
setAgents([]);
})
.finally(() => {
if (cancelled || !isCurrentAgentStreamRequest(agentRequestId)) return;
setAgentsLoading(false);
});
// Functional skills + design templates land independently. Both
// gate `skillsLoading` together so the EntryView stops rendering
// its loader once both registries respond — neither tab would have
// a complete picture if we cleared the flag on the first reply.
let functionalReady = false;
let templatesReady = false;
const maybeClearLoading = () => {
if (functionalReady && templatesReady) setSkillsLoading(false);
};
void fetchSkills().then((list) => {
if (cancelled) return;
setSkills(list);
functionalReady = true;
maybeClearLoading();
});
void fetchDesignTemplates().then((list) => {
if (cancelled) return;
setDesignTemplates(list);
templatesReady = true;
maybeClearLoading();
});
void fetchDesignSystems().then((list) => {
if (cancelled) return;
setDesignSystems(list);
setDsLoading(false);
});
const request = beginProjectListRequest();
void listProjects().then((list) => {
if (cancelled) return;
reconcileFetchedProjects(list, request);
setProjectsLoading(false);
});
void listTemplates().then((list) => {
if (cancelled) return;
setTemplates(list);
});
void fetchPromptTemplates().then((list) => {
if (cancelled) return;
setPromptTemplates(list);
setPromptTemplatesLoading(false);
});
void fetchAppVersionInfo().then((info) => {
if (cancelled) return;
setAppVersionInfo(info);
});
// Daemon-persisted config + composio config + media provider config land
// together so the welcome-modal decision and daemon-backed settings
// apply in one merge, avoiding a flash where local-only state is shown
// before daemon overrides it.
void Promise.all([
fetchDaemonConfig(),
fetchComposioConfigFromDaemon(),
fetchMediaProvidersFromDaemon(),
]).then(([
daemonConfig,
daemonComposioConfig,
daemonMediaProvidersResult,
]) => {
if (cancelled) return;
const daemonMediaProvidersLoaded =
daemonMediaProvidersResult.status === 'ok'
? daemonMediaProvidersResult.providers
: null;
setDaemonMediaProviders(daemonMediaProvidersLoaded);
setDaemonMediaProvidersFetchState(daemonMediaProvidersResult.status);
setMediaProvidersNotice(
daemonMediaProvidersResult.status === 'error'
? t('settings.mediaProviderLoadError')
: null,
);
// Compute the next config outside the setConfig updater so we can
// both (a) call navigate() after setConfig returns — calling it
// inside the updater would trigger a Router setState during React's
// render phase — and (b) read next.onboardingCompleted synchronously,
// since React batches setConfig and the updater doesn't run until
// the next render. latestPersistedConfigRef is kept in sync with
// the rendered config and is safe to read here.
const baseConfig = latestPersistedConfigRef.current;
const migratedLocalMediaProviders = shouldSyncLocalMediaProvidersToDaemon(
baseConfig.mediaProviders,
daemonMediaProvidersLoaded,
);
const next = mergeDaemonMediaProviders(
clearStaleAmrModelChoiceOnProfileChange(
baseConfig,
mergeDaemonConfig(baseConfig, daemonConfig),
),
daemonMediaProvidersLoaded,
);
const hasLocalComposioKey = Boolean(next.composio?.apiKey?.trim());
if (!hasLocalComposioKey && daemonComposioConfig) {
next.composio = daemonComposioConfig;
}
saveConfig(next);
if (
daemonMediaProvidersResult.status === 'ok' &&
migratedLocalMediaProviders &&
hasAnyConfiguredProvider(next.mediaProviders)
) {
void syncMediaProvidersToDaemon(next.mediaProviders, {
daemonProviders: daemonMediaProvidersLoaded,
});
}
// Migrate localStorage prefs to daemon on first boot with the new
// endpoint. If daemon already had values the merge above used them;
// writing back is idempotent and keeps both sides in sync.
void syncConfigToDaemon(next);
void syncComposioConfigToDaemon(next.composio);
latestPersistedConfigRef.current = next;
setConfig(next);
// Route first-run users through the global onboarding panel.
// The onboarding panel and the privacy banner have independent
// lifecycles: onboarding keys off `onboardingCompleted`, the
// banner keys off `privacyDecisionAt`. They may coexist on the
// first launch; the banner sits above the modal layer so it
// stays actionable regardless of the active view.
// Explicit deep-link entries (collab demo, community gallery) shouldn't be
// hijacked by the first-run onboarding redirect, so they stay reachable.
const path = window.location.pathname;
const exemptFromOnboarding = path.startsWith('/collab-demo') || path.startsWith('/community');
if (!next.onboardingCompleted && !exemptFromOnboarding) {
navigate({ kind: 'home', view: 'onboarding' }, { replace: true });
}
setDaemonConfigLoaded(true);
// Composio key hydration is part of this same daemon-config
// fetch — by the time we land here the daemon has either
// returned the saved-key shape (apiKeyConfigured + tail) or
// it errored and we kept whatever localStorage held. Either
// way it is safe to drop the skeleton.
setComposioConfigLoading(false);
});
})();
return () => {
cancelled = true;
agentStreamAbort.abort();
};