-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Expand file tree
/
Copy pathEntryShell.tsx
More file actions
4754 lines (4622 loc) · 183 KB
/
Copy pathEntryShell.tsx
File metadata and controls
4754 lines (4622 loc) · 183 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
// EntryShell — the centered-hero entry layout.
//
// This component owns the entire JSX render and local UI state for
// the redesigned home view (left rail + sticky settings cog + hero +
// recent projects + plugins section + new-project modal). It is
// intentionally a sibling of `EntryView` so that upstream `main`
// changes to `EntryView` (props, connector lifecycle, helpers, exports)
// can be rebased without touching this file. `EntryView` becomes a
// thin wrapper that passes data and callbacks through to this shell.
import {
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
type CSSProperties,
type Dispatch,
type KeyboardEvent as ReactKeyboardEvent,
type ReactNode,
type SetStateAction,
} from 'react';
import {
defaultScenarioPluginIdForProjectMetadata,
PROFILE_MEMORY_ID,
type AmrWalletSnapshot,
type ChatSessionMode,
type ConnectorDetail,
type InstalledPluginRecord,
type RunContextSelection,
type UpsertMemoryRequest,
} from '@open-design/contracts';
import type { OpenDesignHostProjectImportSuccess } from '@open-design/host';
import type { DesignSystemGenerateSnapshot } from './DesignSystemFlow';
import { useAnalytics } from '../analytics/provider';
import {
trackHomeNavClick,
trackHomeToolbarClick,
trackOnboardingClick,
trackOnboardingCompleteResult,
trackOnboardingRuntimeScanResult,
trackPageView,
} from '../analytics/events';
import {
amrHandoffDeviceId,
recordAmrEntry,
syncAmrAttributionWithOnboardingProfile,
type AmrEntryAttribution,
} from '../analytics/amr-attribution';
import { getResolvedDeviceId } from '../analytics/client';
import {
beginAmrAuthTracking,
resolveAmrAuthTracking,
} from '../analytics/amr-auth';
import { setOnboardingAttributionPersonProperties } from '../analytics/source-attribution';
import {
clearOnboardingSessionId,
getOrCreateOnboardingSessionId,
} from '../analytics/onboarding-session';
import type {
TrackingOnboardingArea,
TrackingOnboardingStepIndex,
TrackingOnboardingStepName,
TrackingOnboardingClickElement,
TrackingOnboardingClickAction,
TrackingOnboardingRuntimeType,
TrackingOnboardingCompletionResult,
TrackingOnboardingCompletionType,
TrackingCliProviderId,
} from '@open-design/contracts/analytics';
import { agentIdToTracking } from '@open-design/contracts/analytics';
import { useT } from '../i18n';
import { navigate, useRoute } from '../router';
import { setPendingDesignSystemCreateEntry } from '../analytics/ds-create-entry';
import type {
AgentInfo,
ApiProtocol,
ApiProtocolConfig,
AppConfig,
ConnectionTestResponse,
DesignSystemSummary,
ExecMode,
Project,
ProjectMetadata,
ProjectTemplate,
PromptTemplateSummary,
ProviderModelOption,
ProviderModelsResponse,
SkillSummary,
} from '../types';
import { CenteredLoader } from './Loading';
import { DesignsTab } from './DesignsTab';
import { DesignSystemsTab } from './DesignSystemsTab';
import { BrandsTab } from './BrandsTab';
import { EntryNavRail, type EntryView as EntryViewKind } from './EntryNavRail';
import { ProjectSearchModal } from './ProjectSearchModal';
import { CloudSignInTip, RailAccountSyncTip } from './CloudSignInTip';
import { resolveEntryRailAccountFooterState } from './entry-rail-account-state';
import { LibrarySection } from './LibrarySection';
import { UpdaterPopup } from './UpdaterPopup';
import { WhatsNewPopup } from './WhatsNewPopup';
import { AmrBalanceDialog } from './AmrBalanceDialog';
import { AmrLowBalanceDialog, type AmrLowBalanceDecision } from './AmrLowBalanceDialog';
import {
amrBalanceGateScopeForWorkspaceContext,
amrBalanceGateScopesMatch,
checkAmrBalanceGate,
type AmrBalanceGateScope,
} from '../runtime/amr-balance-gate';
import { isPaidAmrPlan, resolveAmrPlan } from '../runtime/amr-low-balance-plan';
import { HomeView, seedHomeComposerPrompt } from './HomeView';
import { EntryBlankState } from './EntryBlankState';
import { RecentProjectsStrip } from './RecentProjectsStrip';
import {
createPluginAuthoringHandoff,
createPluginUseHandoff,
createSkillUseHandoff,
takeHomePromptHandoff,
type HomePromptHandoff,
} from './home-hero/plugin-authoring';
import {
buildRecommendation,
type Recommendation,
} from '../onboarding/recommendation';
import type { OnboardingEntry } from '../onboarding/onboarding-entry';
import { ONBOARDING_ARTIFACT_CHIP_IDS } from './home-hero/chips';
import { homeHeroChipLabel } from './home-hero/chip-labels';
import type { PluginUseAction } from './plugins-home/useActions';
import { Icon } from './Icon';
import { defaultAgentModelId, effectiveAgentModelChoice } from './agentModelSelection';
import { AgentIcon } from './AgentIcon';
import { CommunityView } from './CommunityView';
import { TeamSlotPlaceholder } from './TeamSlotPlaceholder';
import {
notifyTeamProjectsChanged,
notifyWorkspaceBillingRefresh,
notifyWorkspaceContextRefresh,
useTeamProjects,
useWorkspaceBillingResponse,
useWorkspaceContext,
workspaceBillingBalanceUsd,
workspaceBillingSummaryForContext,
} from '../collab/useWorkspaceContext';
import { useWorkspaceInvalidation } from '../collab/workspace-events';
import {
buildAllProjectsList,
buildDraftsList,
createSharedProjectPredicate,
} from '../collab/all-projects-list';
import {
getModelCapabilityTag,
getModelCostTier,
MODEL_CAPABILITY_TAG_LABEL_KEYS,
MODEL_COST_TIER_LABEL_KEYS,
type ModelCapabilityTag,
} from './modelCapabilityTags';
import { LanguageMenu } from './LanguageMenu';
import { IntegrationsView, type IntegrationTab } from './IntegrationsView';
import { InlineModelSwitcher } from './InlineModelSwitcher';
import { type EntrySettingsSection } from './EntrySettingsMenu';
import { NewProjectModal } from './NewProjectModal';
import { ExtensionsMarketplace } from './PluginsView';
import type { CreateInput, CreateTab, ImportClaudeDesignOutcome } from './NewProjectPanel';
import type { PluginLoopSubmit } from './PluginLoopHome';
import {
createProject,
duplicatePluginAsProject,
patchProject,
resolvedWorkspaceContextForWrite,
type PluginShareAction,
type PluginShareProjectOutcome,
} from '../state/projects';
import { TasksView } from './TasksView';
import {
API_KEY_PLACEHOLDERS,
API_PROTOCOL_TABS,
SUGGESTED_MODELS_BY_PROTOCOL,
} from '../state/apiProtocols';
import {
defaultKnownProviderModel,
KNOWN_PROVIDERS,
} from '../state/config';
import type { KnownProvider } from '../state/config';
import { saveOnboardingProfile } from '../state/onboarding-profile';
import { testAgent, testApiProvider } from '../providers/connection-test';
import { fetchProviderModels } from '../providers/provider-models';
import {
cancelVelaLogin,
fetchVelaLoginStatus,
startVelaLogin,
type VelaLoginStatus,
} from '../providers/daemon';
import {
AMR_LOGIN_POLL_INTERVAL_MS,
amrLoginPollOutcome,
notifyAmrLoginStatusChanged,
} from './amrLoginPolling';
import { closeAmrActivationWindowBestEffort } from './AmrLoginPill';
import { smoothScrollToTop } from '../utils/smoothScrollToTop';
import { summarizeProjectNameFromPrompt } from '../utils/projectName';
import { LIBRARY_UI_VISIBLE } from '../features/libraryUi';
import {
providerModelsCacheKey,
type ProviderModelsCache,
} from './providerModelsCache';
import {
ENTRY_RAIL_STATE_EVENT,
ENTRY_RAIL_TOGGLE_EVENT,
RAIL_OPEN_STORAGE_KEY,
readStoredRailOpen,
} from './entryRailBridge';
import { enterpriseUrl } from './enterpriseUrl';
import { resolveByokModelPreference } from './byok/validation';
// Persist the entry nav-rail open/collapsed state so it survives both a
// home -> project -> home navigation (EntryShell unmounts on the project
// route) and a full reload. Without this the rail always reset to its
// collapsed default on return. The storage key, the rail toggle/state window
// events, and the seed reader live in `entryRailBridge` so the pinned Home
// tab's sidebar toggle (WorkspaceTabsBar, a sibling React tree) can share
// them without importing this module's graph.
export { ENTRY_RAIL_STATE_EVENT, ENTRY_RAIL_TOGGLE_EVENT };
function writeStoredRailOpen(open: boolean): void {
if (typeof window === 'undefined') return;
try {
window.localStorage.setItem(RAIL_OPEN_STORAGE_KEY, open ? 'true' : 'false');
} catch {
/* ignore quota / disabled storage */
}
}
const ONBOARDING_DROPDOWN_OPEN_EVENT = 'open-design:onboarding-dropdown-open';
type OnboardingAgentTestState =
| { status: 'idle' }
| { status: 'running'; inputKey: string }
| { status: 'done'; inputKey: string; result: ConnectionTestResponse };
// The topbar chips (GitHub star, model switcher, Use everywhere)
// collapse into the settings dropdown when the viewport gets
// narrow. The transition is driven entirely by CSS @media queries
// in `entry-layout.css` so server and client render identical
// markup — both surfaces are always present, and CSS toggles
// `display` based on `--compact-topbar` breakpoint (900px).
// Default scenario plugin for each project kind/intent. The mapping
// lives in `@open-design/contracts` so the daemon's `/api/projects`
// and `/api/runs` fallbacks resolve to the same plugin id when no
// `pluginId` is on the request body — plan §3.3 of
// `specs/current/plugin-driven-flow-plan.md`.
// Newsletter signup endpoint. Lives on the marketing site (Cloudflare Pages
// Function backed by KV), so this is a cross-origin POST from the desktop
// client. Overridable at build time via NEXT_PUBLIC_NEWSLETTER_URL — e.g. point
// it at a local `wrangler pages dev` instance during development.
const NEWSLETTER_SUBSCRIBE_URL =
process.env.NEXT_PUBLIC_NEWSLETTER_URL ?? 'https://open-design.ai/subscribe';
const NEWSLETTER_EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const ONBOARDING_BYOK_AUTO_FETCH_DELAY_MS = 300;
const ONBOARDING_BYOK_AUTO_TEST_DELAY_MS = 500;
const ONBOARDING_AMR_MODEL_OPTIONS: NonNullable<AgentInfo['models']> = [
{ id: 'claude-opus-4.8', label: 'Claude Opus 4.8' },
{ id: 'deepseek-v4-flash', label: 'DeepSeek V4 Flash' },
{ id: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash' },
{ id: 'glm-5.1', label: 'GLM 5.1' },
];
type OnboardingProfileState = {
role: string;
orgSize: string;
useCase: string[];
source: string;
// Free-text detail when `source === 'other'`. Kept separate from `source`
// so attribution can still aggregate on the 'other' bucket while capturing
// the raw self-reported channel.
sourceOther: string;
email: string;
};
type EntryCreateProjectInput = 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;
};
function defaultPluginIdForMetadata(metadata: ProjectMetadata): string | null {
return defaultScenarioPluginIdForProjectMetadata(metadata);
}
function defaultPluginInputsForCreate(
input: CreateInput,
pluginId: string | null,
): Record<string, unknown> | null {
const kind = input.metadata.kind;
const projectName = input.name.trim();
if (pluginId === 'example-web-prototype') {
return {
artifactKind: input.metadata.includeLandingPage
? 'landing page'
: 'web prototype',
fidelity: input.metadata.fidelity ?? 'high-fidelity',
audience: 'product evaluators',
designSystem: 'the active project design system',
template: input.metadata.templateLabel ?? 'the bundled web prototype seed',
};
}
if (pluginId === 'example-simple-deck') {
return {
deckType: 'pitch deck',
topic: projectName || 'the user brief',
audience: 'decision makers',
slideCount: '10-15 pages',
speakerNotes: input.metadata.speakerNotes
? 'include speaker notes'
: 'no speaker notes',
designSystem: 'the active project design system',
};
}
if (pluginId === 'od-new-generation') {
const templateLabel = input.metadata.templateLabel?.trim();
const artifactKind =
kind === 'template'
? 'artifact based on a saved template'
: kind === 'other'
? 'custom design artifact'
: `${kind} artifact`;
return {
artifactKind,
audience: 'product and design reviewers',
topic: templateLabel || projectName || 'the user brief',
};
}
if (pluginId !== 'od-media-generation') return null;
if (kind !== 'image' && kind !== 'video' && kind !== 'audio') return null;
const promptTemplate = input.metadata.promptTemplate;
const subject =
promptTemplate?.prompt?.trim()
|| projectName
|| promptTemplate?.title?.trim()
|| `${kind} concept`;
const style =
promptTemplate?.summary?.trim()
|| 'cinematic, high-quality, on-brand';
const aspect =
kind === 'image'
? input.metadata.imageAspect
: kind === 'video'
? input.metadata.videoAspect
: undefined;
return {
mediaKind: kind,
subject,
style,
...(aspect ? { aspect } : {}),
};
}
export interface ProjectTitleHint {
name: string;
/** Workspace whose catalog produced this hint; null for a local-only row. */
workspaceId: string | null;
/** Member authorization lifetime that produced the catalog row. */
workspaceMemberId: string | null;
/**
* The team catalog is the title authority for a project shared by another
* member. Own/private projects may still accept a newer local rename.
*/
authoritative: boolean;
}
interface Props {
skills: SkillSummary[];
designTemplates: SkillSummary[];
designSystems: DesignSystemSummary[];
projects: Project[];
templates: ProjectTemplate[];
onDeleteTemplate?: (id: string) => Promise<boolean>;
promptTemplates: PromptTemplateSummary[];
defaultDesignSystemId: string | null;
connectors: ConnectorDetail[];
connectorsLoading: boolean;
integrationInitialTab?: IntegrationTab;
composioConfigLoading?: boolean;
skillsLoading?: boolean;
designSystemsLoading?: boolean;
projectsLoading?: boolean;
// Execution / model-switching context. Threaded down from `App` so the
// top-bar `InlineModelSwitcher` can render the active mode/agent/model
// and persist changes through the same callbacks the project view uses.
config: AppConfig;
providerModelsCache?: ProviderModelsCache;
onProviderModelsCacheChange?: Dispatch<SetStateAction<ProviderModelsCache>>;
agents: AgentInfo[];
// True while the cold-start agent detection stream is still in flight
// (`fetchAgentsStream` has not reached its terminal `done`). Onboarding
// uses this to show the AMR cloud card in a detecting/skeleton state
// instead of hiding it during the seconds AMR's probe takes to settle.
agentsLoading?: boolean;
// Local credential state is independent from the remote workspace read.
// During a transient Cloud outage it prevents the rail from presenting a
// still-signed-in user as signed out.
amrLoggedIn?: boolean | null;
daemonLive: boolean;
onModeChange: (mode: ExecMode) => void;
onAgentChange: (id: string) => void;
onAgentModelChange: (
id: string,
choice: { model?: string; reasoning?: string; serviceTier?: string },
) => void;
onApiProtocolChange: (protocol: ApiProtocol) => void;
onApiModelChange: (model: string) => void;
onConfigPersist: (cfg: AppConfig) => Promise<void> | void;
onSkillsRefresh?: () => Promise<void> | void;
onSkillsChanged?: (affectedSkillId?: string) => void;
onRefreshAgents: () => Promise<AgentInfo[]> | AgentInfo[];
onCreateProject: (input: EntryCreateProjectInput) => Promise<boolean> | boolean | void;
onCreatePluginShareProject: (
pluginId: string,
action: PluginShareAction,
locale?: string,
) => Promise<PluginShareProjectOutcome>;
onImportClaudeDesign: (
file: File,
) => Promise<ImportClaudeDesignOutcome | void> | ImportClaudeDesignOutcome | void;
onImportFolder?: (baseDir: string) => Promise<void> | void;
onImportFolderResponse?: (response: OpenDesignHostProjectImportSuccess) => Promise<void> | void;
onOpenProject: (
id: string,
fileName?: string,
projectTitleHint?: ProjectTitleHint,
) => Promise<boolean> | boolean | void;
onOpenLiveArtifact: (projectId: string, artifactId: string) => void;
onDeleteProject: (id: string) => Promise<boolean | void> | boolean | void;
onDuplicateProject?: (id: string) => Promise<void> | void;
onRenameProject: (id: string, name: string) => void;
onProjectsRefresh?: () => Promise<void> | void;
onTeamProjectContentReady?: (
projectId: string,
workspaceId: string,
workspaceMemberId: string,
) => Promise<boolean> | boolean;
onChangeDefaultDesignSystem: (id: string) => void;
onCreateDesignSystem?: () => void;
// NOTE: first-run onboarding intentionally no longer hosts guided
// design-system creation. The previous step-3 design-system surface was
// replaced by the newsletter and brand-extraction steps, so EntryShell does
// not accept a `renderDesignSystemCreation` renderer. Guided creation stays
// reachable from the standalone `design-system-create` route and the
// Design Systems tab; do not re-thread an onboarding renderer here.
onOpenDesignSystem?: (id: string) => void;
onDesignSystemsRefresh?: () => Promise<void> | void;
onPersistComposioKey: (composio: AppConfig['composio']) => Promise<void> | void;
onOpenSettings: (section?: EntrySettingsSection) => void;
onCompleteOnboarding: () => void;
artifactUpgradeSlot?: ReactNode;
}
// Map an EntryNavRail view id to the analytics `element` enum on
// `home/nav` ui_click. Returns `null` for views without a dedicated nav
// button (the rail's "Home" target is the brand logo, which gets its own
// element value via the logo click handler — not the changeView path).
function navElementForView(
next: EntryViewKind,
):
| 'home'
| 'projects'
| 'automations'
| 'plugins'
| 'design_systems'
| 'integrations'
| null {
switch (next) {
case 'home':
return 'home';
case 'projects':
return 'projects';
case 'tasks':
return 'automations';
case 'plugins':
return 'plugins';
case 'design-systems':
return 'design_systems';
case 'brands':
// No dedicated brands analytics element yet; reuse the design_systems
// slot since Brands replaces that nav destination.
return 'design_systems';
case 'integrations':
return 'integrations';
default:
return null;
}
}
// Tab views stay mounted (so previews/thumbnails survive a tab switch) but the
// inactive ones must leave layout, the accessibility tree, and tab order.
// `content-visibility: hidden` still reserves the hidden pane's block size,
// which pushes later sidebar destinations far below the sticky topbar.
function inactiveViewProps(active: boolean) {
return {
style: active ? undefined : ({ display: 'none' } as const),
inert: !active,
'aria-hidden': !active,
};
}
export function EntryShell({
skills,
designTemplates,
designSystems,
projects,
templates,
onDeleteTemplate,
promptTemplates,
defaultDesignSystemId,
connectors,
connectorsLoading,
integrationInitialTab = 'mcp',
composioConfigLoading = false,
skillsLoading = false,
designSystemsLoading = false,
projectsLoading = false,
config,
providerModelsCache: sharedProviderModelsCache,
onProviderModelsCacheChange,
agents,
agentsLoading = false,
amrLoggedIn = null,
daemonLive,
onModeChange,
onAgentChange,
onAgentModelChange,
onApiProtocolChange,
onApiModelChange,
onConfigPersist,
onSkillsRefresh,
onSkillsChanged,
onRefreshAgents,
onCreateProject,
onCreatePluginShareProject,
onImportClaudeDesign,
onImportFolder,
onImportFolderResponse,
onOpenProject,
onOpenLiveArtifact,
onDeleteProject,
onDuplicateProject,
onRenameProject,
onProjectsRefresh,
onTeamProjectContentReady,
onChangeDefaultDesignSystem,
onCreateDesignSystem,
onOpenDesignSystem,
onDesignSystemsRefresh,
onPersistComposioKey,
onOpenSettings,
onCompleteOnboarding,
artifactUpgradeSlot,
}: Props) {
const t = useT();
// Each entry sub-view (home / projects / design-systems) is its own
// URL now, so the browser back/forward buttons work and a deep link
// to /design-systems lands on that section. We derive the active
// view from the route rather than keeping it in component state.
const route = useRoute();
const view: EntryViewKind = route.kind === 'home' ? route.view : 'home';
// The one shared workspace context. Any non-null context is a real workspace
// (personal or team); workspace surfaces gate on B's permission bits, not on
// workspaceType.
// The whole state (not just `context`) so workspace-scoped WRITES can go
// through `resolvedWorkspaceContextForWrite`, which refuses to collapse an
// unresolved or unavailable authority into an anonymous, unbound create.
const workspaceContextState = useWorkspaceContext();
const { context: workspaceContext, loading: workspaceLoading } = workspaceContextState;
const accountFooterState = resolveEntryRailAccountFooterState(
workspaceContextState,
amrLoggedIn,
);
const workspaceContextRef = useRef(workspaceContext);
workspaceContextRef.current = workspaceContext;
const workspaceBillingResponse = useWorkspaceBillingResponse();
// Plan and money are both workspace-scoped questions, so both go through a
// context-partitioned projection. `response.summary` on its own is an ACCOUNT
// read (`workspaceId: null` by contract) — feeding it to the rail's plan
// nameplate is what kept a personal Plus badge on a 免费 workspace while the
// 额度 row beside it correctly followed the switch.
const workspaceBilling = workspaceBillingSummaryForContext(
workspaceBillingResponse,
workspaceContext,
);
const workspaceBalanceUsd = workspaceBillingBalanceUsd(
workspaceBillingResponse,
workspaceContext,
);
// Team-wide shared-project discovery for the "全部项目" view. The member's own
// `projects` prop is only their LOCAL list; team-shared projects come from the
// resource hub through the daemon. Empty off-team / when the hub is unconfigured.
const teamProjects = useTeamProjects();
const hasWorkspaceContext = Boolean(workspaceContext);
// The "全部项目" grid is the SAME project-card grid used everywhere; its
// membership rule lives in `buildAllProjectsList`. Rows flow through
// `RecentProjectsStrip` like any other card — no custom section.
const localProjectIds = new Set(projects.map((project) => project.id));
// The optimistic share layer lives HERE, above every project strip, because a
// share has to move TWO things at once: the card's 共享 badge and which grid
// the card sits in. It used to live inside `RecentProjectsStrip`, so the badge
// flipped on click while 草稿 kept the card until the next team-projects poll
// (acceptance: 「转入团队空间, 怎么还显示在草稿里…切到全部项目再切回草稿它才消失」).
const [sharedThisSession, setSharedThisSession] = useState<ReadonlySet<string>>(
() => new Set<string>(),
);
const [unsharedThisSession, setUnsharedThisSession] = useState<ReadonlySet<string>>(
() => new Set<string>(),
);
const markProjectShared = useCallback((projectId: string) => {
setSharedThisSession((prev) => new Set(prev).add(projectId));
setUnsharedThisSession((prev) => {
const next = new Set(prev);
next.delete(projectId);
return next;
});
}, []);
const markProjectUnshared = useCallback((projectId: string) => {
setUnsharedThisSession((prev) => new Set(prev).add(projectId));
setSharedThisSession((prev) => {
const next = new Set(prev);
next.delete(projectId);
return next;
});
}, []);
// The single shared-state answer, handed to the grids AND to every strip.
const isSharedProject = useMemo(
() =>
createSharedProjectPredicate({
teamProjects: teamProjects.projects,
sharedThisSession,
unsharedThisSession,
}),
[teamProjects.projects, sharedThisSession, unsharedThisSession],
);
// 草稿 is the complement of 全部项目: sharing moves a project from one to the
// other, so a shared project must stop appearing here (acceptance #78).
const draftProjectsList: Project[] = buildDraftsList({
projects,
teamProjects: teamProjects.projects,
workspaceContext,
isShared: isSharedProject,
});
const allProjectsList: Project[] = buildAllProjectsList({
projects,
teamProjects: teamProjects.projects,
workspaceContext,
sharedFallbackName: t('recentProjects.sharedProjectFallbackName'),
isShared: isSharedProject,
});
// projectId → sharing member id, so a card in the 全部项目 / 草稿 grids can
// resolve "{creator}创建" against the member directory. A project absent here
// is the member's own local project → "我创建".
const teamProjectOwnerMemberIds = new Map(
teamProjects.projects.map((teamProject) => [teamProject.projectId, teamProject.ownerMemberId]),
);
const contentReadyProjectIdsRef = useRef(new Set<string>());
const pendingContentReadyProjectIdsRef = useRef(
new Map<string, { workspaceId: string; workspaceMemberId: string }>(),
);
const contentReadyHydrationRef = useRef(new Map<string, Promise<boolean>>());
const teamProjectIdsRef = useRef(new Set<string>());
teamProjectIdsRef.current = new Set(
teamProjects.projects.map((project) => project.projectId),
);
const readyWorkspaceId = workspaceContext?.workspaceId ?? null;
const readyWorkspaceMemberId = workspaceContext?.workspaceMemberId ?? null;
const readyScopeKey = readyWorkspaceId && readyWorkspaceMemberId
? `${readyWorkspaceId}:${readyWorkspaceMemberId}`
: null;
const contentReadyScopeKeyRef = useRef<string | null>(null);
if (contentReadyScopeKeyRef.current !== readyScopeKey) {
contentReadyScopeKeyRef.current = readyScopeKey;
contentReadyProjectIdsRef.current.clear();
pendingContentReadyProjectIdsRef.current.clear();
contentReadyHydrationRef.current.clear();
}
const acceptContentReadyProject = useCallback((
projectId: string,
eventWorkspaceId: string,
eventWorkspaceMemberId: string,
): Promise<boolean> => {
const workspaceId = workspaceContext?.workspaceId;
const workspaceMemberId = workspaceContext?.workspaceMemberId;
if (
!workspaceId ||
!workspaceMemberId ||
workspaceContext?.workspaceType !== 'team' ||
workspaceId !== eventWorkspaceId ||
workspaceMemberId !== eventWorkspaceMemberId ||
!teamProjectIdsRef.current.has(projectId)
) {
return Promise.resolve(false);
}
if (contentReadyProjectIdsRef.current.has(projectId)) {
return Promise.resolve(true);
}
const scopeKey = `${workspaceId}:${workspaceMemberId}`;
const key = `${scopeKey}:${projectId}`;
const existing = contentReadyHydrationRef.current.get(key);
if (existing) return existing;
if (!onTeamProjectContentReady) return Promise.resolve(false);
const hydration = Promise.resolve(
onTeamProjectContentReady(projectId, workspaceId, workspaceMemberId),
)
.then((hydrated) => {
if (
hydrated !== true ||
contentReadyScopeKeyRef.current !== scopeKey ||
!teamProjectIdsRef.current.has(projectId)
) {
return false;
}
pendingContentReadyProjectIdsRef.current.delete(projectId);
contentReadyProjectIdsRef.current.add(projectId);
return true;
})
.catch(() => false)
.finally(() => {
if (contentReadyHydrationRef.current.get(key) === hydration) {
contentReadyHydrationRef.current.delete(key);
}
});
contentReadyHydrationRef.current.set(key, hydration);
return hydration;
}, [
onTeamProjectContentReady,
workspaceContext?.workspaceMemberId,
workspaceContext?.workspaceId,
workspaceContext?.workspaceType,
]);
useWorkspaceInvalidation({
'team-project-content-ready': ({ projectId, workspaceId }) => {
const currentWorkspaceId = workspaceContext?.workspaceId;
const currentWorkspaceMemberId = workspaceContext?.workspaceMemberId;
if (
!currentWorkspaceId ||
!currentWorkspaceMemberId ||
currentWorkspaceId !== workspaceId
) {
return;
}
pendingContentReadyProjectIdsRef.current.set(projectId, {
workspaceId,
workspaceMemberId: currentWorkspaceMemberId,
});
void acceptContentReadyProject(
projectId,
workspaceId,
currentWorkspaceMemberId,
);
},
});
useEffect(() => {
if (!readyScopeKey) return;
for (const [projectId, eventScope] of pendingContentReadyProjectIdsRef.current) {
if (
eventScope.workspaceId === readyWorkspaceId &&
eventScope.workspaceMemberId === readyWorkspaceMemberId
) {
void acceptContentReadyProject(
projectId,
eventScope.workspaceId,
eventScope.workspaceMemberId,
);
}
}
}, [
acceptContentReadyProject,
readyScopeKey,
readyWorkspaceId,
readyWorkspaceMemberId,
teamProjects.projects,
]);
// Open handler for the "全部项目" grid. A project already in the member's local
// list opens directly; a team-shared project the member has not pulled yet is
// first pulled + registered on the daemon (materialize content + insert a local
// project record) so it can open read-only — the member is not the owner, so
// the useProjectCollab single-writer path keeps it read-only.
const [pullingProjectId, setPullingProjectId] = useState<string | null>(null);
async function handleOpenAllProjects(id: string): Promise<boolean> {
// The grid already reconciled the local row with the authoritative team
// catalog (notably the owner's current project name). Carry its title and
// provenance into App before navigation. Passing only the id made App reopen its local
// SQLite placeholder ("共享项目"), throwing away data already visible on the
// list and leaving the project header stale until a later metadata event.
const projectName = allProjectsList.find((project) => project.id === id)?.name.trim();
const teamProject = teamProjects.projects.find((project) => project.projectId === id);
const projectTitleHint = projectName
? {
name: projectName,
workspaceId: workspaceContext?.workspaceId ?? null,
workspaceMemberId: workspaceContext?.workspaceMemberId ?? null,
// A member must render the owner's catalog title even when their
// local mirror has a newer timestamp or an older non-placeholder
// title. The owner may rename locally before the catalog catches up.
authoritative: Boolean(
teamProject
&& teamProject.ownerMemberId !== workspaceContext?.workspaceMemberId,
),
}
: undefined;
const open = () => Promise.resolve(onOpenProject(id, undefined, projectTitleHint));
if (localProjectIds.has(id) || contentReadyProjectIdsRef.current.has(id)) {
await open();
return true;
}
const scopeKey = contentReadyScopeKeyRef.current;
const hydration = scopeKey
? contentReadyHydrationRef.current.get(`${scopeKey}:${id}`)
: null;
if (hydration) {
const hydrated = await hydration;
if (hydrated) {
await open();
return true;
}
if (contentReadyScopeKeyRef.current !== scopeKey) return false;
}
// The pull materializes the whole project before it can open; surface it
// on the card (spinner overlay) and swallow re-clicks meanwhile —
// otherwise the first click reads as dead for the entire download.
if (pullingProjectId) return false;
setPullingProjectId(id);
try {
const response = await fetch(`/api/projects/${encodeURIComponent(id)}/collab/pull`, { method: 'POST' });
if (!response.ok) return false;
await Promise.resolve(onProjectsRefresh?.());
} catch {
return false;
} finally {
setPullingProjectId(null);
}
await open();
return true;
}
// Workspace-only destinations. Personal and team workspaces both use these;
// signed-out/local state falls back to home once the context has resolved.
// `community` is allowed in both states, so it is not guarded.
const isWorkspaceOnlyView =
view === 'drafts' ||
view === 'all-projects' ||
view === 'members' ||
view === 'board' ||
view === 'workspace-settings';
useEffect(() => {
if (workspaceLoading) return;
if (isWorkspaceOnlyView && !hasWorkspaceContext) {
navigate({ kind: 'home', view: 'home' }, { replace: true });
}
}, [workspaceLoading, isWorkspaceOnlyView, hasWorkspaceContext]);
const [newProjectOpen, setNewProjectOpen] = useState(false);
// Hard block from the pre-run balance gate on a home submit (empty wallet
// or signed out); non-null renders the AmrBalanceDialog on the home page —
// the project is never created, so the composer draft stays put. The dialog
// resolves the promise the submit handler is awaiting: 'retry' (sign-in
// completed / recharge landed) re-runs the gate and continues the very same
// create-and-run; 'dismiss' hands the composer back to the user.
const [amrBalanceGateBlock, setAmrBalanceGateBlock] = useState<
{
reason: 'insufficient' | 'signed_out';
snapshot: AmrWalletSnapshot;
resolve: (decision: 'retry' | 'dismiss') => void;
} | null
>(null);
// Soft low-balance warning holding a pending home submit: the dialog
// resolves the promise the submit handler is awaiting ('proceed' continues
// the very same create-and-run).
const [amrLowBalanceWarn, setAmrLowBalanceWarn] = useState<
{
snapshot: AmrWalletSnapshot;
resolve: (decision: AmrLowBalanceDecision) => void;
} | null
>(null);
useEffect(() => {
if (view !== 'design-systems') return;
void onDesignSystemsRefresh?.();
}, [onDesignSystemsRefresh, view]);
// The entry nav rail is collapsed by default (Manus-style) so the entry
// view opens clean and full-width; the panel toggle in the topbar opens it
// as an overlay that dismisses on selection / backdrop click / Escape.
// Its open/collapsed state is persisted (localStorage) so it survives a
// home -> project -> home round trip (EntryShell unmounts on the project
// route) and a reload, instead of snapping back to collapsed.
const [railOpen, setRailOpen] = useState<boolean>(readStoredRailOpen);
const [projectSearchOpen, setProjectSearchOpen] = useState(false);
// ⌘K / Ctrl+K opens the project search palette — same as clicking the rail
// search box.
useEffect(() => {
const onKey = (event: KeyboardEvent) => {
if ((event.metaKey || event.ctrlKey) && (event.key === 'k' || event.key === 'K')) {
event.preventDefault();
setProjectSearchOpen(true);
}
};
document.addEventListener('keydown', onKey);
return () => document.removeEventListener('keydown', onKey);
}, []);
useEffect(() => {
writeStoredRailOpen(railOpen);
// Broadcast the state so chrome outside this tree (the pinned Home tab's
// sidebar toggle) can mirror it via aria-expanded.
window.dispatchEvent(
new CustomEvent(ENTRY_RAIL_STATE_EVENT, { detail: { open: railOpen } }),
);
}, [railOpen]);
// The pinned Home tab (WorkspaceTabsBar) carries a sidebar toggle; it lives
// in a sibling tree, so the request arrives as a window event.
useEffect(() => {
const onToggle = () => setRailOpen((v) => !v);
window.addEventListener(ENTRY_RAIL_TOGGLE_EVENT, onToggle);
return () => window.removeEventListener(ENTRY_RAIL_TOGGLE_EVENT, onToggle);
}, []);
const [localProviderModelsCache, setLocalProviderModelsCache] =
useState<ProviderModelsCache>({});
const hasSharedProviderModelsCache =
Boolean(sharedProviderModelsCache) && Boolean(onProviderModelsCacheChange);
const activeProviderModelsCache =
hasSharedProviderModelsCache
? sharedProviderModelsCache!
: localProviderModelsCache;
const activeSetProviderModelsCache =
hasSharedProviderModelsCache
? onProviderModelsCacheChange!
: setLocalProviderModelsCache;
const [newProjectInitialTab, setNewProjectInitialTab] =
useState<CreateTab>('prototype');
const [integrationTab, setIntegrationTab] = useState<IntegrationTab>(integrationInitialTab);
// Lazy initializer, so a handoff published by a surface that then navigated
// here — the `/marketplace/<id>` detail route, which `App` renders outside
// this shell — is claimed on the very first render and reaches HomeView in
// the same commit as the mount. The read is destructive, so it applies once.
const [homePromptHandoff, setHomePromptHandoff] = useState<HomePromptHandoff | null>(
() => takeHomePromptHandoff(),
);
// Personalized first-run starting point. Computed once, in memory, when the
// user finishes the About-you survey with real answers (see
// `finishOnboarding`); null for returning users, skipped/blank surveys, and
// after any page refresh (deliberately not persisted, per onboarding spec
// §7.1). Cleared as soon as the user takes any concrete entry (spec §7.4).
const [onboardingRec, setOnboardingRec] = useState<Recommendation | null>(null);
const entryMainScrollRef = useRef<HTMLElement | null>(null);
// Entry views share this element, so route changes must not inherit the previous view's offset.
useLayoutEffect(() => {
const scrollContainer = entryMainScrollRef.current;
if (!scrollContainer) return;
scrollContainer.scrollTop = 0;
}, [view]);
const analytics = useAnalytics();
function changeView(next: EntryViewKind) {
const navElement = navElementForView(next);
if (navElement) {
trackHomeNavClick(analytics.track, {
page_name: 'home',
area: 'nav',
element: navElement,
});
}
navigate({ kind: 'home', view: next });
}
function startPluginAuthoring(goal?: string) {
setHomePromptHandoff(
createPluginAuthoringHandoff(Date.now(), goal),
);
changeView('home');
}
function usePluginFromLibrary(
record: InstalledPluginRecord,
action: PluginUseAction = 'use',
) {
setHomePromptHandoff(