-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Expand file tree
/
Copy pathApp.tsx
More file actions
3762 lines (3616 loc) · 152 KB
/
Copy pathApp.tsx
File metadata and controls
3762 lines (3616 loc) · 152 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 {
stashOnboardingEntryForProject,
type OnboardingEntry,
} from './onboarding/onboarding-entry';
import {
deriveConfigureGlobals,
projectKindFromMetadataToTracking,
fidelityToTracking,
} from '@open-design/contracts/analytics';
import type {
AmrModelsResponse,
ChatSessionMode,
RunContextSelection,
TeamProject,
WorkspaceTeamProjectsResponse,
WorkspaceCollabContext,
WorkspaceProjectSummary,
} from '@open-design/contracts';
import { DEFAULT_UNSELECTED_SCENARIO_PLUGIN_ID } from '@open-design/contracts';
import { EntryView } from './components/EntryView';
import type { ProjectTitleHint } from './components/EntryShell';
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,
type ProjectNameAuthorityResolution,
} from './components/ProjectView';
import { AmrArtifactUpgradeGate } from './components/AmrArtifactUpgradeGate';
import { AmrArtifactUpgradeHomeCard } from './components/AmrArtifactUpgradeHomeCard';
import { TooltipLayer } from './components/TooltipLayer';
import { UpdateDialog } from './components/UpdateDialog';
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,
openExternalUrl,
uploadProjectFiles,
replaceProjectWorkingDir,
} from './providers/registry';
import { openFirstPartyExternalLinkFromClick } from './first-party-external-link';
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 {
beginWorkspaceScopedRead,
useWorkspaceBilling,
useWorkspaceContext,
workspaceIdentityCacheKey,
} from './collab/useWorkspaceContext';
import { resolvePlanTier } from './collab/team-plan';
import { deriveTabIdentityScope, UNSET_ACCOUNT_BUCKET } from './collab/tab-scope';
import { CommunityView } from './components/CommunityView';
import { seedHomeComposerPrompt } from './components/HomeView';
import { goBack, navigate, useRoute, type Route } 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 { summarizeProjectNameFromPrompt } from './utils/projectName';
import {
amrArtifactUpgradeHomeMockOffer,
type AmrArtifactUpgradeHomeOffer,
} from './runtime/amr-artifact-upgrade';
import {
amrBalanceGateScopeForWorkspaceContext,
amrBalanceGateScopesMatch,
type AmrBalanceGateScope,
} from './runtime/amr-balance-gate';
import { installFontRecovery } from './runtime/font-recovery';
import {
createDesignSystemProjectFromProject,
createProject,
createPluginShareProject,
deleteProject as deleteProjectApi,
duplicateProject,
getProject,
importClaudeDesignZip,
importFolderProject,
listWorkspaceProjectSummaries,
listProjects,
listTemplates,
deleteTemplate,
duplicatePluginAsProject,
patchProject,
resolvedWorkspaceContextForWrite,
} from './state/projects';
import { useModalWindowDragGuard } from './hooks/useModalWindowDragGuard';
import { resumeThumbnailLoads, suspendThumbnailLoads } from './lib/thumbnail-load-gate';
import type {
PluginShareAction,
PluginShareProjectOutcome,
WorkspaceProjectListView,
} from './state/projects';
import { getOpenDesignHost, 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;
/** Exact workspace/member authority checked by the Home AMR preflight. */
amrGatePrecheckWitness?: AmrBalanceGateScope;
requestId?: string;
pendingFiles?: File[];
userWorkingDirToken?: string;
linkedDirs?: string[] | null;
onboardingEntry?: OnboardingEntry;
};
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;
/**
* Whether this launch should hand the user to the first-run onboarding flow.
*
* Two conditions, both about the *user*, neither about where they happen to be
* in the app: they have never completed onboarding (on either the local or the
* daemon copy — `mergeDaemonConfig` ratchets the two before this runs), and
* they did not arrive through an explicit deep link that onboarding must not
* hijack (the collab demo and the community gallery are shareable URLs).
*
* Deliberately a pure predicate over a resolved config: the redirect belongs to
* the one-shot boot pass, and expressing it as a function of "who the user is"
* rather than "what just happened" keeps it from being re-decided mid-session.
*/
export function shouldRouteToFirstRunOnboarding(
config: AppConfig,
pathname: string,
): boolean {
if (config.onboardingCompleted === true) return false;
if (pathname.startsWith('/collab-demo') || pathname.startsWith('/community')) return false;
return true;
}
function workspaceProjectListViewForRoute(route: Route): WorkspaceProjectListView {
if (route.kind === 'home' && route.view === 'all-projects') return 'all';
if (route.kind === 'home' && route.view === 'drafts') return 'drafts';
if (route.kind === 'project') return 'all';
return 'recent';
}
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)
&& (left?.serviceTier ?? null) === (right?.serviceTier ?? null);
}
export function mergeAgentModelChoice(
previous: AgentModelChoice | undefined,
next: { model?: string; reasoning?: string; serviceTier?: string },
): AgentModelChoice {
const merged = { ...(previous ?? {}), ...next };
if (
Object.prototype.hasOwnProperty.call(next, 'serviceTier') &&
next.serviceTier === undefined
) {
delete merged.serviceTier;
}
return merged;
}
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;
scopeKey: string;
};
/**
* The scope key for a caller with NO resolved workspace identity — either the
* context has not landed yet (every fresh boot passes through this) or the
* daemon has no workspace plane at all. It is deliberately NOT treated as "a
* workspace you left": a boot that lists projects before the context resolves
* did not read another workspace's data, so promoting `local` → `ws:member`
* must not discard the list it just loaded.
*/
const UNRESOLVED_PROJECT_LIST_SCOPE = 'local';
function projectListScopeKey(context: WorkspaceCollabContext | null): string {
return context
? `${context.workspaceId}:${context.workspaceMemberId}`
: UNRESOLVED_PROJECT_LIST_SCOPE;
}
export function projectViewAuthorizationLifetimeKey(
projectId: string,
context: WorkspaceCollabContext | null,
): string {
return `${projectListScopeKey(context)}:${projectId}`;
}
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'
);
}
/**
* `isTeamShared` is the hub-backed truth: `/api/workspace/projects/team`
* reads the team's resource-hub catalog directly (see
* `apps/daemon/src/routes/collab-context.ts`), not this daemon's local
* sqlite. It stays true the instant the hub confirms the project is shared
* to the caller's team, well before the pull below has materialized a local
* row. Callers that need to distinguish "not on the hub catalog" (genuinely
* not shared / no access) from "on the catalog but the local mirror hasn't
* landed yet" must branch on `isTeamShared`, not on `pulled` — a pull can
* return `ok: true` with no bytes materialized yet (see collab-sync.ts's
* `/collab/pull` handler, which only registers the local project once
* `pullLatest` resolves a non-null version).
*/
type TeamSharedProjectPullOutcome = {
isTeamShared: boolean;
pulled: boolean;
};
type TeamProjectCatalogLookup =
| { ok: true; project: TeamProject | null }
| { ok: false };
async function fetchTeamProjectCatalogEntry(projectId: string): Promise<TeamProjectCatalogLookup> {
try {
const response = await fetch('/api/workspace/projects/team');
if (!response.ok) return { ok: false };
const body = (await response.json()) as WorkspaceTeamProjectsResponse;
return {
ok: true,
project: (body.projects ?? []).find((project) => project.projectId === projectId) ?? null,
};
} catch {
return { ok: false };
}
}
async function pullTeamSharedProjectIfAvailable(projectId: string): Promise<TeamSharedProjectPullOutcome> {
const lookup = await fetchTeamProjectCatalogEntry(projectId);
if (!lookup.ok || !lookup.project) return { isTeamShared: false, pulled: false };
try {
const pullResponse = await fetch(`/api/projects/${encodeURIComponent(projectId)}/collab/pull`, {
method: 'POST',
});
return { isTeamShared: true, pulled: pullResponse.ok };
} catch {
return { isTeamShared: false, pulled: false };
}
}
// A member's first-ever open of a just-shared project races the daemon's
// local materialization (POST /collab/pull's registerPulledProject, or
// ProjectView's own /collab/status poll firing ensureSharedProjectPlaceholder
// — see collab-sync.ts) against the deep-link bootstrap effect below. Give
// that materialization a bounded window instead of trusting a single
// immediate miss.
//
// 21 attempts * 600ms = ~12s total. The original budget here was 4 * 600ms =
// ~2.4s, sized well under the real /collab/pull latency observed against a
// live vela-backed hub (up to ~10s for a fresh project's first pull) —
// exhausting the window and falling through to "not found" while the pull
// was still genuinely in flight is a false negative, not a correctness
// backstop. ~12s matches the budget ProjectView's own
// CONVERSATION_LOAD_RETRY_DELAYS_MS already established for the identical
// "team-shared project not yet materialized locally" race on the
// conversations-list read, so both retry loops now cover the same worst
// case instead of one giving up 5x sooner than the other. This is still a
// BOUNDED retry, not an unconditional hang: `everConfirmedTeamShared`
// already keeps the caller from navigating home the moment the hub confirms
// team membership even once (see `still-materializing` below), so widening
// this window only helps the case where the hub itself is slow to reflect a
// share, not a genuinely-missing/no-access project — that path still falls
// through to the not-found/navigate-home handling unchanged.
const DEEP_LINK_TEAM_SHARE_RETRY_ATTEMPTS = 21;
const DEEP_LINK_TEAM_SHARE_RETRY_DELAY_MS = 600;
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export type DeepLinkedProjectResolution =
| { kind: 'found'; project: Project }
// The hub confirmed team membership at least once during the retry window:
// the project exists and the caller has access. Local materialization is
// still catching up — the caller must NOT treat this as "not found".
| { kind: 'still-materializing' }
// Never confirmed as team-shared within the retry window (or genuinely not
// shared at all) — the caller's existing not-found handling applies.
| { kind: 'not-found' };
/**
* Resolves a project a member has just deep-linked to but has no local
* record of yet. Bounded-retries `getProject` + `pullTeamSharedProjectIfAvailable`
* so a first-ever open of a freshly team-shared project survives the local
* materialization race instead of being misread as "doesn't exist" on the
* first miss. Pulled out of the App.tsx bootstrap effect as a plain async
* function (no React, no timers beyond the injected `delay`) so the retry
* decision — when does "not found yet" become "still materializing" versus
* "genuinely not found" — is unit-testable without mounting the component.
*/
export async function resolveDeepLinkedTeamSharedProject(
projectId: string,
deps: {
getProject: (id: string) => Promise<Project | null>;
pullTeamSharedProjectIfAvailable: (id: string) => Promise<TeamSharedProjectPullOutcome>;
delay: (ms: number) => Promise<void>;
retryAttempts?: number;
retryDelayMs?: number;
isCancelled?: () => boolean;
},
): Promise<DeepLinkedProjectResolution> {
const attempts = deps.retryAttempts ?? DEEP_LINK_TEAM_SHARE_RETRY_ATTEMPTS;
const retryDelayMs = deps.retryDelayMs ?? DEEP_LINK_TEAM_SHARE_RETRY_DELAY_MS;
const isCancelled = () => deps.isCancelled?.() ?? false;
let everConfirmedTeamShared = false;
for (let attempt = 0; attempt < attempts; attempt += 1) {
if (attempt > 0) {
await deps.delay(retryDelayMs);
if (isCancelled()) return { kind: 'still-materializing' };
}
const project = await deps.getProject(projectId).catch(() => null);
if (isCancelled()) return { kind: 'still-materializing' };
if (project) return { kind: 'found', project };
const { isTeamShared, pulled } = await deps.pullTeamSharedProjectIfAvailable(projectId);
if (isCancelled()) return { kind: 'still-materializing' };
if (isTeamShared) everConfirmedTeamShared = true;
if (pulled) {
const pulledProject = await deps.getProject(projectId).catch(() => null);
if (isCancelled()) return { kind: 'still-materializing' };
if (pulledProject) return { kind: 'found', project: pulledProject };
}
}
return everConfirmedTeamShared ? { kind: 'still-materializing' } : { kind: 'not-found' };
}
export async function hydrateReadyTeamProject(
projectId: string,
workspaceId: string,
deps: {
getWorkspaceContext: () => WorkspaceCollabContext | null;
listWorkspaceProjects: (
context: WorkspaceCollabContext,
) => Promise<WorkspaceProjectSummary[]>;
applyProject: (project: Project) => void;
},
): Promise<Project | null> {
const initialContext = deps.getWorkspaceContext();
if (
!initialContext ||
initialContext.workspaceType !== 'team' ||
initialContext.workspaceId !== workspaceId ||
initialContext.memberStatus !== 'active' ||
initialContext.lifecycleState !== 'active'
) {
return null;
}
const contextMatches = () => {
const context = deps.getWorkspaceContext();
return Boolean(
context &&
context.workspaceType === 'team' &&
context.workspaceId === initialContext.workspaceId &&
context.workspaceMemberId === initialContext.workspaceMemberId &&
context.memberStatus === 'active' &&
context.lifecycleState === 'active' &&
(context.teamId ?? context.workspaceId) ===
(initialContext.teamId ?? initialContext.workspaceId)
);
};
const summaries = await deps.listWorkspaceProjects(initialContext).catch(() => []);
if (!contextMatches()) return null;
const summary = summaries.find((candidate) =>
candidate.id === projectId &&
candidate.project.id === projectId
);
const hasMaterializedTeamBinding = Boolean(
summary &&
summary.workspaceId === workspaceId &&
summary.project.workspaceId === workspaceId &&
summary.visibility === 'team' &&
summary.resourceState === 'active' &&
summary.cloudTombstonedAt == null &&
summary.currentUserAccess.canOpen === true &&
typeof summary.resourceHubResourceId === 'string' &&
summary.resourceHubResourceId.trim() &&
summary.syncState === 'synced'
);
if (!summary || !hasMaterializedTeamBinding) return null;
deps.applyProject(summary.project);
return summary.project;
}
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(), []);
const hostPlatform = useMemo(() => getOpenDesignHost()?.client.platform, []);
useModalWindowDragGuard();
const workspaceContextState = useWorkspaceContext();
const {
context: workspaceContext,
loading: workspaceContextLoading,
} = workspaceContextState;
const currentWorkspaceIdentity = workspaceIdentityCacheKey(workspaceContext);
const workspaceBilling = useWorkspaceBilling();
const workspaceContextRef = useRef<WorkspaceCollabContext | null>(null);
const workspaceContextStateRef = useRef(workspaceContextState);
workspaceContextRef.current = workspaceContext;
workspaceContextStateRef.current = workspaceContextState;
const listCurrentWorkspaceProjects = useCallback(
(options?: { throwOnError?: boolean; workspaceView?: WorkspaceProjectListView }) => {
const context = workspaceContextRef.current;
return listProjects({
...options,
workspaceContext: context,
workspaceView: context ? options?.workspaceView ?? 'recent' : undefined,
});
},
[],
);
useEffect(() => {
const onFirstPartyExternalLink = (event: MouseEvent) => openFirstPartyExternalLinkFromClick(
event,
(url) => { void openExternalUrl(url); },
);
// React handlers append AMR attribution while the event bubbles; bridge the final URL afterwards.
document.addEventListener('click', onFirstPartyExternalLink);
return () => document.removeEventListener('click', onFirstPartyExternalLink);
}, []);
// Icon fonts whose startup fetch lost a race stay tofu forever without
// this — see runtime/font-recovery.ts.
useEffect(() => installFontRecovery(), []);
// 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());
}
}, []);
// Desktop vibrancy focus response: an unfocused window drops the cream
// scrim to let the wallpaper show through more clearly; on focus the scrim
// returns to full strength (app-wash.css keys off this class).
useEffect(() => {
if (
clientType !== 'desktop'
|| hostPlatform !== 'darwin'
|| typeof window === 'undefined'
) return undefined;
const root = document.documentElement;
const sync = () => root.classList.toggle('is-window-blurred', !document.hasFocus());
sync();
window.addEventListener('focus', sync);
window.addEventListener('blur', sync);
return () => {
window.removeEventListener('focus', sync);
window.removeEventListener('blur', sync);
root.classList.remove('is-window-blurred');
};
}, [clientType, hostPlatform]);
const [config, setConfig] = useState<AppConfig>(() => loadConfig());
const configRef = useRef(config);
configRef.current = config;
const latestPersistedConfigRef = useRef(config);
latestPersistedConfigRef.current = config;
const settingsDraftConfigRef = useRef<AppConfig | null>(null);
const [settingsOpen, setSettingsOpen] = useState(false);
const [amrArtifactUpgradeHomeMockConfig] = useState<AmrArtifactUpgradeHomeOffer | null>(
() => process.env.NODE_ENV === 'development' && typeof window !== 'undefined'
? amrArtifactUpgradeHomeMockOffer(window.location.search)
: null,
);
const amrArtifactUpgradeHomeMock = amrArtifactUpgradeHomeMockConfig !== null;
const [amrArtifactUpgradeHomeOffer, setAmrArtifactUpgradeHomeOffer] =
useState<AmrArtifactUpgradeHomeOffer | null>(() => amrArtifactUpgradeHomeMockConfig);
// 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 agentStreamAbortRef = useRef<AbortController | null>(null);
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 [workspaceSkills, setWorkspaceSkills] = useState<{
identity: string;
items: SkillSummary[];
}>(() => ({
identity: currentWorkspaceIdentity,
items: [],
}));
// A workspace-scoped response is safe to render only under the exact
// identity it was fetched for. The replacement read starts in an effect, so
// clearing in that effect would still paint one frame of A's skills under B.
// Derive the visible catalog during render instead: an identity mismatch is
// a fail-closed empty list until B's own response commits.
const skills =
workspaceSkills.identity === currentWorkspaceIdentity
? workspaceSkills.items
: [];
// 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]);
// Project names from another member's team-catalog row are authoritative:
// the local mirror can carry an older real name (not only "共享项目") with a
// newer local timestamp. Scope keys prevent a project id observed in one
// workspace/member context from leaking its title authority into another.
const [authoritativeProjectNames, setAuthoritativeProjectNames] = useState<
Record<string, string>
>({});
const authoritativeProjectNamesRef = useRef(authoritativeProjectNames);
authoritativeProjectNamesRef.current = authoritativeProjectNames;
const projectNameAuthorityRequestGenerationRef = useRef<Map<string, number>>(new Map());
const [petTaskCenter, setPetTaskCenter] = useState<PetTaskCenter>({
running: [],
queued: [],
recent: [],
});
const pendingLocalProjectIdsRef = useRef<Set<string>>(new Set());
const pendingLocalProjectScopeRef = useRef(projectListScopeKey(workspaceContext));
const currentProjectListScope = projectListScopeKey(workspaceContext);
const projectAuthorizationScopeRef = useRef(currentProjectListScope);
const projectAuthorizationGenerationRef = useRef(0);
if (projectAuthorizationScopeRef.current !== currentProjectListScope) {
projectAuthorizationScopeRef.current = currentProjectListScope;
projectAuthorizationGenerationRef.current += 1;
}
if (pendingLocalProjectScopeRef.current !== currentProjectListScope) {
pendingLocalProjectScopeRef.current = currentProjectListScope;
pendingLocalProjectIdsRef.current.clear();
}
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);
// Functional skills and design templates are two independent registry reads
// that gate ONE loader: the EntryView must not stop spinning until both have
// answered, or whichever tab the user is on renders an incomplete catalog as
// if it were final. They are now read from two different places (the boot pass
// reads templates; the workspace-keyed effect reads skills once the caller's
// identity is known), so the pair of flags lives here rather than inside one
// effect's closure.
const skillRegistriesReadyRef = useRef({ functional: false, templates: false });
const markSkillRegistryReady = useCallback((half: 'functional' | 'templates') => {
skillRegistriesReadyRef.current[half] = true;
const { functional, templates } = skillRegistriesReadyRef.current;
if (functional && templates) setSkillsLoading(false);
}, []);
const [dsLoading, setDsLoading] = useState(true);
const [projectsLoading, setProjectsLoading] = useState(true);
// A loaded project list describes exactly ONE workspace identity, so leaving
// that workspace INVALIDATES it — it does not merely make it stale.
//
// Everything downstream of `projects` (the home 最近项目 strip, the 全部项目 and
// 草稿 grids) renders whatever this array holds, and the re-list on switch is
// an effect: effects run after the commit, so the browser paints the previous
// workspace's cards under the new workspace's identity first and only swaps
// them when the new list lands. That is the reported 「总是要慢一拍」 — the
// strip presenting one workspace's projects as another's, which is worse than
// showing nothing. Dropping the list here, during the render that first
// observes the new scope, means no frame ever shows the wrong workspace's
// data. (`reconcileFetchedProjects` already refuses to APPLY a response whose
// scope has moved on; the missing half was discarding what is already on
// screen.)
//
// Nothing is refetched: the switch effect below owns that, and its request is
// already keyed on the resolved workspace, so this is not a backend problem
// and needs no extra round-trip.
const projectListScopeRef = useRef(currentProjectListScope);
if (projectListScopeRef.current !== currentProjectListScope) {
const leftAResolvedWorkspace =
projectListScopeRef.current !== UNRESOLVED_PROJECT_LIST_SCOPE;
projectListScopeRef.current = currentProjectListScope;
if (leftAResolvedWorkspace) {
setProjects([]);
setProjectsLoading(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 workspaceProjectView = workspaceProjectListViewForRoute(route);
// Read-only mirror for the boot effect. The boot pass needs to know which
// project list to seed, but it must NOT restart when that answer changes:
// see the "boot is a one-shot" note on the bootstrap effect below. A
// dedicated effect already re-lists projects whenever the view or the
// workspace changes, so nothing is lost by the boot pass not reacting.
const workspaceProjectViewRef = useRef(workspaceProjectView);
workspaceProjectViewRef.current = workspaceProjectView;
// `listCurrentWorkspaceProjects` already collapses `workspaceView` to
// `undefined` when there is no resolved `workspaceContext` (see its
// `context ? options?.workspaceView ?? 'recent' : undefined` above), so the
// request it sends never actually varies by home tab outside a workspace.
// But the raw route-derived `workspaceProjectView` still changes string
// value on every 最近/全部/草稿 tab switch, and that alone is enough to
// re-run the effect below (dependency arrays compare the value passed in,
// not what the callback does with it) — re-fetching the identical list on
// every click. Mirror the callback's own collapse here so the effect's
// dependency is stable outside a workspace, matching the fetch it triggers.
const effectiveWorkspaceProjectView = workspaceContext ? workspaceProjectView : undefined;
const projectScopeRefreshMountedRef = useRef(false);
const analytics = useAnalytics();
// Single-flight guard for `/api/agents?stream=1`: beginning a new request
// physically aborts the previous stream, not just invalidates its
// callbacks. Stacked live streams are what deadlocked the packaged app —
// each navigation/focus refresh opened another slow cold-probe stream,
// and once they pinned every upstream connection slot the whole od://
// proxy starved (see apps/packaged/src/index.ts ignore-connections-limit
// note for the other half of that fix).
const beginAgentStreamRequest = useCallback(() => {
agentStreamAbortRef.current?.abort();
agentStreamAbortRef.current = new AbortController();
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 handleTeamProjectContentReady = useCallback(async (
projectId: string,
workspaceId: string,
workspaceMemberId: string,
): Promise<boolean> => {
if (workspaceContextRef.current?.workspaceMemberId !== workspaceMemberId) {
return false;
}
const project = await hydrateReadyTeamProject(projectId, workspaceId, {
getWorkspaceContext: () => workspaceContextRef.current,
listWorkspaceProjects: (context) =>
listWorkspaceProjectSummaries({