-
Notifications
You must be signed in to change notification settings - Fork 10.4k
Expand file tree
/
Copy pathEntryNavRail.tsx
More file actions
1171 lines (1135 loc) · 53 KB
/
Copy pathEntryNavRail.tsx
File metadata and controls
1171 lines (1135 loc) · 53 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
// Team-edition entry navigation rail (Lovart/Manus-style labeled column).
//
// Structure — faithfully ported from the design demo
// (origin/demo/workspace-team-features) but wired to the REAL workspace context
// (`GET /api/workspace/context`, shared via `useWorkspaceContext`), never the
// demo's hardcoded 琼羽 / Refly / 800 placeholders:
//
// • Account section (top) — real `context.displayName` + an account menu
// (settings / GitHub help / feature request / socials / sign out — theme and
// language live in 设置·通用 only, matching #5517).
// No header block when there is no cloud identity (context === null) —
// the rail starts at the search box; expand/collapse lives in the
// workspace tabs bar's pinned Home toggle.
// • Billing chip — real plan tier + explicitly scoped USD balance when Vela
// billing is available, with upgrade linking out to Vela Web.
// • Search box (opens the ⌘K project search palette via `onOpenSearch`).
// • 最近 (Recents) → home, Community → community.
// • Team block (only when `context.workspaceType === 'team'`): an inline team
// switcher + the team destinations. In-client views: drafts / all projects /
// design systems / 扩展 (plugins). Member management lives in B's vela/web
// console, so 成员 / 数据大盘 / Workspace 设置 link OUT to it (target=_blank),
// derived from `context.workspaceSettingsUrl`.
//
// The gate is `workspaceType` + permissions, never the billing/provider axis — a
// personal_byok workspace still has full team features.
import {
useEffect,
useRef,
useState,
type KeyboardEvent as ReactKeyboardEvent,
type ReactNode,
} from 'react';
import { coalescedGet } from '../lib/coalesced-get';
import type {
WorkspaceActiveResponse,
WorkspaceBillingSummary,
WorkspaceCollabContext,
WorkspaceDirectoryItem,
WorkspaceDirectoryResponse,
} from '@open-design/contracts';
import {
fetchVelaLoginStatus,
formatVelaBalanceUsd,
velaLogout,
} from '../providers/daemon';
import { resetCloudSignInTipDismissal } from './CloudSignInTip';
import { SignOutConfirmDialog } from './SignOutConfirmDialog';
import { notifyAmrLoginStatusChanged } from './amrLoginPolling';
import { Icon } from './Icon';
import { GITHUB_STARS_FALLBACK_LABEL, formatStars, useGithubStars } from './useGithubStars';
import { PlanWordmark, planBadgeTierForLabel } from './PlanWordmark';
import { RemixIcon } from './RemixIcon';
import { InviteDialog } from './InviteDialog';
import { useI18n } from '../i18n';
import { useDismissOnOutsideInteraction } from '../hooks/useDismissOnOutsideInteraction';
import {
notifyTeamProjectsChanged,
notifyWorkspaceBillingRefresh,
notifyWorkspaceContextRefresh,
} from '../collab/useWorkspaceContext';
import { hasTeamPlan, resolvePlanLabelTier } from '../collab/team-plan';
import { amrPlansUrlForProfile } from '../runtime/amr-guidance';
import type { EntryHomeView } from '../router';
const REPO_URL = 'https://github.com/nexu-io/open-design';
const GITHUB_HELP_URL = `${REPO_URL}/issues/new`;
const GITHUB_FEATURE_URL = `${REPO_URL}/pulls`;
const DISCORD_URL = 'https://discord.gg/mHAjSMV6gz';
const X_URL = 'https://x.com/OpenDesignHQ';
const CONTACT_EMAIL_URL = 'mailto:support@open-design.ai';
const externalLinkProps = { target: '_blank', rel: 'noreferrer noopener' } as const;
// Last directory this shell successfully read. `coalescedGet` only collapses
// CONCURRENT reads, so without this every open of the switcher started from an
// empty list and showed a loading row before the same names reappeared. Kept at
// module scope so it survives the rail unmounting (returning from a project).
let cachedWorkspaceDirectory: WorkspaceDirectoryItem[] | null = null;
/** Test seam: clear the module-level directory cache between tests. */
export function resetWorkspaceDirectoryCache(): void {
cachedWorkspaceDirectory = null;
}
// The rail's destination ids are the entry-shell home views (kept in sync with
// the router so `navigate({ kind: 'home', view })` type-checks for every item).
export type EntryView = EntryHomeView;
interface Props {
view: EntryView;
onViewChange: (view: EntryView) => void;
onNewProject: () => void;
/** Opens the project search palette (blurred modal over all projects). */
onOpenSearch?: () => void;
newProjectDisabled?: boolean;
/** When false the rail is collapsed (hidden off-canvas) on the entry view. */
open: boolean;
/** The one shared workspace context; null → local (no cloud identity) state. */
context: WorkspaceCollabContext | null;
/** Account billing metadata (via the vela CLI 收口). Null → the billing
* chip falls back to the context plan-tier hint. */
billing?: WorkspaceBillingSummary | null;
/** Explicitly scoped balance in USD for `context`. Team callers must pass
* only a backend-proven v2 workspace wallet, never account credits. */
balanceUsd?: string | null;
/** Open the app settings dialog. */
onOpenSettings?: () => void;
/** Open the members / invite slot (B's InviteDialog). */
onInvite?: () => void;
/** Start the cloud sign-in / team flow from the local-state callout. */
onSignInCloud?: () => void;
/** Extra controls pinned to the bottom-left of the rail. */
footerExtra?: ReactNode;
/** Optional notice shown above the footer controls. */
footerNotice?: ReactNode;
}
interface NavButtonProps {
active?: boolean;
ariaLabel: string;
label: string;
onClick: () => void;
disabled?: boolean;
testId?: string;
children: ReactNode;
}
// No `data-tooltip` here: every nav item renders its label inline, so the
// rail's hover bubble (entry-layout.css) would only duplicate visible text.
// That bubble stays reserved for the rail's icon-only controls (updater,
// avatar, icon-only sign-out).
function NavButton({ active, ariaLabel, label, onClick, disabled, testId, children }: NavButtonProps) {
return (
<button
type="button"
className={`entry-nav-rail__btn${active ? ' is-active' : ''}`}
onClick={onClick}
disabled={disabled}
aria-label={ariaLabel}
aria-current={active ? 'page' : undefined}
{...(testId ? { 'data-testid': testId } : {})}
>
<span className="entry-nav-rail__btn-icon" aria-hidden>{children}</span>
<span className="entry-nav-rail__btn-label">{label}</span>
</button>
);
}
function handleWorkspaceMenuKeyDown(event: ReactKeyboardEvent<HTMLDivElement>): void {
if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) return;
const items = Array.from(
event.currentTarget.querySelectorAll<HTMLElement>('[role="menuitem"]:not(:disabled)'),
);
if (items.length === 0) return;
const currentIndex = items.indexOf(document.activeElement as HTMLElement);
let nextIndex: number;
if (event.key === 'Home') {
nextIndex = 0;
} else if (event.key === 'End') {
nextIndex = items.length - 1;
} else if (event.key === 'ArrowUp') {
nextIndex = currentIndex <= 0 ? items.length - 1 : currentIndex - 1;
} else {
nextIndex = currentIndex < 0 || currentIndex >= items.length - 1 ? 0 : currentIndex + 1;
}
event.preventDefault();
items[nextIndex]?.focus();
}
// Team management (members, dashboard, settings) lives in B's vela/web console,
// not the local client. We link out to it, deriving the section path from the one
// workspace-settings URL the context carries. Best-effort: swap/append the section
// segment, falling back to the raw settings URL when the path can't be rewritten.
export function teamConsoleUrl(
base: string,
section:
| 'members'
| 'dashboard'
| 'settings'
| 'billing'
| 'upgrade'
| 'create-team'
| 'plans'
| 'invite',
// Only consulted for `section: 'upgrade'` — see the comment below on why the
// deep-link param depends on it.
options?: { hasActivePlan?: boolean },
): string {
// B's console routes: members live at /team, the (global) wallet backs the
// billing entry. The settings URL the context carries includes the
// ?workspaceId deep-link param; URL parsing preserves it, so the target page
// opens on the SAME workspace this client is pinned to (B asks the user to
// confirm if their account-level selection differs).
//
// `upgrade` lands on the team dashboard AND opens a subscription dialog, but
// WHICH dialog depends on whether the team has ever checked out before — B's
// `team-dashboard.tsx` gates them on mutually exclusive conditions:
// - `billing=checkout` opens the first-subscription dialog, gated by
// `canUpgradeTeam`, which requires the team's `subscriptionSummary
// .billingState` to be one of free/inactive/locked (never subscribed, or
// lapsed). For a team that already has an active plan this gate is
// false, so `billing=checkout` silently opens nothing — confirmed via a
// real recording (recvpSQKna0LwR) landing on the bare Overview page for
// an already-subscribed "Team Pro" workspace.
// - `billing=plan` opens the CHANGE-plan dialog, gated by
// `ownerBillingActionsAvailable`, which requires `billingState ===
// 'active'` — the mirror-image condition, for a team that already pays.
// `options.hasActivePlan` (callers pass `hasTeamPlan(context, billing)` from
// `collab/team-plan.ts`) picks the branch that actually matches the team's
// current subscription state instead of hardcoding the never-subscribed one.
// `plans` is the PERSONAL upgrade deep link: the wallet page with B's
// pricing modal auto-opened (`view=plans`) — verified live to auto-open for
// a personal-workspace session (recvpYEiH019cD). For a TEAM workspace B
// redirects this exact URL into `dashboard?billing=checkout` itself
// (vela wallet.tsx `teamWalletCheckoutRedirectPath`), so even a misrouted
// team session degrades to the first-checkout dialog, not a dead page.
const path =
section === 'members' ? 'team'
: section === 'billing' ? 'wallet'
: section === 'plans' ? 'wallet'
: section === 'upgrade' ? 'dashboard'
: section === 'create-team' || section === 'invite' ? 'dashboard'
: section;
try {
const url = new URL(base);
const segments = url.pathname.split('/').filter(Boolean);
if (segments.length > 0 && segments[segments.length - 1] === 'settings') {
segments[segments.length - 1] = path;
} else {
segments.push(path);
}
url.pathname = `/${segments.join('/')}`;
if (section === 'upgrade') {
url.searchParams.set('billing', options?.hasActivePlan ? 'plan' : 'checkout');
}
if (section === 'plans') url.searchParams.set('view', 'plans');
// Vela owns the final invite action because only its dashboard has the
// authoritative subscription + seat state needed to choose between
// upgrading to Team, buying seats, and sending an invite. `invite=auto`
// is consumed one-shot by that dashboard and then removed from the URL.
if (section === 'invite') url.searchParams.set('invite', 'auto');
// recvq725Kx0rM4 / recvqfXzHtY5wg: `create-team` opens B's create-workspace
// dialog via `?workspace=create`. A prior fix (675878434) removed this,
// reasoning that B's route source had no handler for it — true of the repo
// checkout that fix read at the time, but B's `sidebar-actions.tsx` (PR
// #905, commit 501c0069, authored 2026-07-21) added exactly this handler,
// and it is live on `origin/feat/workspace-team` (the branch the
// feature-test deployment serves) as of this fix. Re-verified directly
// against that branch's current source before restoring the param.
if (section === 'create-team') url.searchParams.set('workspace', 'create');
return url.toString();
} catch {
return base;
}
}
/**
* Where an 「升级」/「升级套餐」 affordance sends THIS workspace — the one
* decision point shared by every upgrade entry (EntryNavRail's credits chip
* and invite dialog, AmrBalanceDialog's balance-gate CTA, RecentProjectsStrip's
* invite dialog, SettingsDialog's AMR-card upgrade buttons), so the three
* subscription states cannot drift apart per entry point.
*
* The axis is the WORKSPACE TYPE, never "does a console URL exist": B returns
* `workspaceSettingsUrl` for a personal workspace too (it has a settings page
* like any other), so URL-presence stopped implying "team" — that premise
* routed a $0-balance personal account onto the team dashboard's
* `billing=checkout` deep link, which opens the Upgrade-to-Team dialog in an
* error state ("Team plan unavailable" / 3-seat minimum). recvpYEiH019cD,
* verified live with a real personal-workspace session.
*
* - personal (or type unknown) → `wallet?view=plans`, B's personal pricing
* modal — verified live to auto-open for the same session.
* - team, never subscribed → `dashboard?billing=checkout` (first-checkout
* dialog); team, already subscribed → `dashboard?billing=plan`
* (change-plan dialog). See `teamConsoleUrl` for why B needs the split.
* - a resolved workspace without `canManageBilling` → null. Billing is
* owner-only, so admin/member surfaces hide the action rather than linking
* to an operation B will reject.
*
* Dialog callers pass `fallbackProfile` and receive the profile-keyed personal
* plans deep link when no workspace context exists after loading. An existing
* workspace without billing permission still returns null; callers hide the
* affordance.
*/
export function workspaceUpgradeUrl(
context: WorkspaceCollabContext | null | undefined,
billing: WorkspaceBillingSummary | null | undefined,
options: { fallbackProfile: string | null | undefined },
): string | null;
export function workspaceUpgradeUrl(
context: WorkspaceCollabContext | null | undefined,
billing: WorkspaceBillingSummary | null | undefined,
): string | null;
export function workspaceUpgradeUrl(
context: WorkspaceCollabContext | null | undefined,
billing: WorkspaceBillingSummary | null | undefined,
options?: { fallbackProfile: string | null | undefined },
): string | null {
// Team billing is owner-only. Keep the permission check in the shared
// resolver so every upgrade surface (including dialogs that pass a profile
// fallback) fails closed for admins/members instead of accidentally linking
// them to an action B will reject. A missing context still uses the fallback
// because there is no workspace identity to authorize yet.
if (context && context.permissions?.canManageBilling !== true) return null;
const settingsUrl = context?.workspaceSettingsUrl?.trim() || null;
if (settingsUrl) {
return context?.workspaceType === 'team'
? teamConsoleUrl(settingsUrl, 'upgrade', { hasActivePlan: hasTeamPlan(context, billing) })
: teamConsoleUrl(settingsUrl, 'plans');
}
return options ? amrPlansUrlForProfile(options.fallbackProfile) : null;
}
export type WorkspaceInviteTarget =
| { kind: 'local' }
| { kind: 'vela'; url: string }
| { kind: 'unavailable' };
/**
* Whether this member should discover the invite flow.
*
* Direct invites and billing recovery are separate capabilities. A Personal
* Free owner (or a full Team owner) can still enter Vela's upgrade/seat flow
* without direct invite capability, but an admin never acquires billing power
* from role alone. Unknown seat state fails closed until the context refresh
* supplies an authoritative answer.
*/
export function canAccessWorkspaceInviteFlow(
context: WorkspaceCollabContext | null | undefined,
): boolean {
if (
!context ||
context.memberStatus !== 'active' ||
context.lifecycleState !== 'active' ||
(context.role !== 'owner' && context.role !== 'admin')
) {
return false;
}
const canInviteMembers = context.permissions?.canInviteMembers === true;
const canManageBilling = context.permissions?.canManageBilling === true;
const needsTeamUpgrade =
context.billingState === 'free' || context.billingState === 'inactive';
if (needsTeamUpgrade) {
return context.role === 'owner' && canManageBilling;
}
if (context.workspaceType === 'personal') return canInviteMembers;
const isSeatFull = workspaceSeatFull(context);
if (isSeatFull === undefined) return false;
if (!isSeatFull) return canInviteMembers;
return context.role === 'owner' && canManageBilling;
}
function workspaceSeatFull(
context: WorkspaceCollabContext,
): boolean | undefined {
const availableSeats = context.seatSummary?.availableSeats;
if (availableSeats !== undefined) return availableSeats <= 0;
return context.seatSummary?.isSeatFull;
}
/**
* Chooses the first safe invite surface. The local form is only valid when a
* team is positively known to have direct invite capability and capacity.
* Personal, Free-plan, and full-seat owner states go to Vela, whose dashboard
* owns the authoritative upgrade/seat/invite decision. Missing routing or seat
* data fails closed.
*/
export function resolveWorkspaceInviteTarget(
context: WorkspaceCollabContext | null | undefined,
): WorkspaceInviteTarget {
if (!context || !canAccessWorkspaceInviteFlow(context)) {
return { kind: 'unavailable' };
}
const needsTeamUpgrade =
context.billingState === 'free' || context.billingState === 'inactive';
if (
context.workspaceType === 'team' &&
!needsTeamUpgrade &&
workspaceSeatFull(context) === false &&
context.permissions.canInviteMembers === true
) {
return { kind: 'local' };
}
const settingsUrl = context?.workspaceSettingsUrl?.trim() || null;
if (!settingsUrl) return { kind: 'unavailable' };
return { kind: 'vela', url: teamConsoleUrl(settingsUrl, 'invite') };
}
/**
* Map a raw vela plan id to a display label for the credits card.
*
* B's ids are namespaced by workspace kind and tier (`team_plus`, `team_max`,
* `pro`, …). The card pairs this label with a PlanWordmark badge that already
* carries the tier, so the label names the PLAN FAMILY (团队版 / 免费版 / …)
* and never leaks a raw snake_case id — `team_plus` used to render verbatim
* because only three exact ids were mapped.
*
* NOTE (parked 2026-07-20): membership is per workspace, so one account can
* hold a personal 创作会员 tier AND a team tier at once. How the card should
* present that (one family label, both badges, which one wins in a team) is
* with the designer; see the ledger. Until then this keeps the pre-existing
* single-label behavior.
*/
function formatBillingTier(tier: string, t: ReturnType<typeof useI18n>['t']): string {
const normalized = tier.trim().toLowerCase();
if (!normalized) return t('entry.billingTierFree');
if (normalized === 'team' || normalized.startsWith('team_') || normalized.startsWith('team-')) {
return t('entry.billingTierTeam');
}
if (normalized === 'free') return t('entry.billingTierFree');
if (normalized === 'pro' || normalized === 'plus' || normalized === 'max') {
return t('entry.billingTierPro');
}
// Unknown id: title-case the segments rather than showing `some_new_tier`.
return normalized
.split(/[_-]+/)
.filter(Boolean)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join(' ');
}
export function EntryNavRail({
view,
onViewChange,
onNewProject,
onOpenSearch,
newProjectDisabled,
open,
context,
billing,
balanceUsd,
onOpenSettings,
footerExtra,
footerNotice,
}: Props) {
const { t } = useI18n();
const brandLabel = t('app.brand');
const communityLabel = t('pluginsHome.title');
// #5517 renamed the rail's first item from 最近 (Recents) to 首页 (Home) —
// the key keeps its historical name, the VALUE now reads Home in every
// locale (polish round 2, ref 1db2d00c2).
const homeLabel = t('entry.navRecents');
const isHome = view === 'home';
const isTeam = Boolean(context) && context!.workspaceType === 'team';
const permissions = context?.permissions;
// Demo `canOwnWorkspace` → real owner-level view of workspace settings. Never
// re-derive from role — the permission bits already fold role + lifecycle in.
const canViewWorkspaceSettings = Boolean(permissions?.canViewWorkspaceSettings);
const canInviteMembers = Boolean(permissions?.canInviteMembers);
const canAccessInviteFlow = canAccessWorkspaceInviteFlow(context);
const workspaceSettingsUrl = context?.workspaceSettingsUrl?.trim() || null;
// Account identity (real). No email field on the context → the head shows the
// avatar + name only.
const displayName = context?.displayName?.trim() || '';
const accountName = displayName || brandLabel;
const accountInitial = accountName.charAt(0).toUpperCase() || '·';
// Billing chip: prefer the real summary metadata; fall back to the context
// plan-tier hint when metadata has not loaded. Money is a separate,
// explicitly scoped `balanceUsd` input below.
// The plan id from either source goes through the same formatter — the
// context hint is a raw id too (`team_plus`), and it used to reach the card
// unformatted whenever billing reported an empty tier (which it does today).
const rawTier = billing?.membershipTier?.trim() || context?.planId?.trim() || '';
// The LABEL is a subscription question, never a workspace-kind one: B makes
// every user-created workspace team-typed, so `isTeam` labelled brand-new
// unpaid workspaces 团队版 (#146). `resolvePlanLabelTier` answers 'free' when
// B positively reports an unsubscribed entitlement, and null when it simply
// has not said — only the null case still falls back to the legacy hint, so
// a paying member (whom B tells us nothing about) keeps their team label.
const labelTier = resolvePlanLabelTier({ billing, context });
const tierLabel = labelTier
? formatBillingTier(labelTier, t)
: isTeam
? t('entry.billingTierTeam')
: t('entry.billingTierFree');
const balanceLabel = formatVelaBalanceUsd(balanceUsd);
// #5517: wordmark badge on the account row (replaces the chevron) and a
// small twin inside the menu's billing card. Derive from the raw tier id
// first so "team_plus" maps to the plus badge regardless of display label.
// Feed the RAW id first: the display label is now a plan-family name
// (团队版), which carries no tier word, so deriving the badge from it would
// drop the PLUS/PRO/MAX distinction. `rawTier` already prefers billing over
// the context hint and is empty only when neither reported one.
const planTier = planBadgeTierForLabel(rawTier || tierLabel);
const [accountOpen, setAccountOpen] = useState(false);
// Sign-out confirm gate (recvqgMWpJZqhL): the menu item only ARMS the
// confirmation dialog; the real logout chain runs on explicit confirm.
const [confirmSignOut, setConfirmSignOut] = useState(false);
const githubStars = useGithubStars();
// Signed-in account email for the menu head (#5517 shows it under the
// display name). The workspace context carries no email, so lazily read the
// vela login-status projection the first time the menu opens — never on
// mount, so shells without an open menu spend zero requests on it.
const [accountEmail, setAccountEmail] = useState<string | null>(null);
useEffect(() => {
if (!accountOpen) return;
// Refetch on EVERY open (the previous value stays visible while the read
// is in flight, so there is no flicker). A fetch-once cache here went
// stale the moment the user switched vela accounts mid-session — the menu
// kept showing the first account's email (#102).
let cancelled = false;
void fetchVelaLoginStatus().then((status) => {
if (!cancelled) setAccountEmail(status?.user?.email?.trim() || '');
});
return () => {
cancelled = true;
};
}, [accountOpen]);
// Hover-open for the account menu (#5517 interaction). The popover floats
// above the trigger, so closing is delayed just long enough for the pointer
// to cross the gap; re-entering the container (menu included — it's a DOM
// child even though it renders above) cancels the pending close.
const accountCloseTimer = useRef<number | null>(null);
const cancelAccountClose = () => {
if (accountCloseTimer.current !== null) {
window.clearTimeout(accountCloseTimer.current);
accountCloseTimer.current = null;
}
};
const openAccountMenu = () => {
cancelAccountClose();
setAccountOpen(true);
};
const scheduleAccountClose = () => {
cancelAccountClose();
accountCloseTimer.current = window.setTimeout(() => setAccountOpen(false), 220);
};
useEffect(() => cancelAccountClose, []);
// While open, track the pointer at the document level: anywhere outside the
// account container arms the close timer, back inside disarms it. This is
// deliberately NOT React onMouseLeave — leaving from inside the floating
// menu does not reliably produce a synthetic leave on the container.
const accountContainerRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
if (!accountOpen) return;
const onDocPointerOver = (ev: PointerEvent) => {
const container = accountContainerRef.current;
if (!container) return;
if (container.contains(ev.target as Node)) cancelAccountClose();
else scheduleAccountClose();
};
document.addEventListener('pointerover', onDocPointerOver, true);
return () => document.removeEventListener('pointerover', onDocPointerOver, true);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [accountOpen]);
// Hover-out alone leaves the menu open for anyone who never hovers: a touch
// user, or a click that lands somewhere else without the pointer crossing
// this container. Press-outside closes it now rather than 220ms later, and
// Escape gives the keyboard the same exit. Still a listener, not a backdrop,
// so the pointerover tracking above keeps receiving its events.
useDismissOnOutsideInteraction(accountOpen, accountContainerRef, () => {
cancelAccountClose();
setAccountOpen(false);
});
const [teamOpen, setTeamOpen] = useState(false);
const [workspaceItems, setWorkspaceItems] = useState<WorkspaceDirectoryItem[]>(
() => cachedWorkspaceDirectory ?? [],
);
const [workspaceDirectoryLoading, setWorkspaceDirectoryLoading] = useState(false);
const [workspaceSwitchingId, setWorkspaceSwitchingId] = useState<string | null>(null);
const [inviteOpen, setInviteOpen] = useState(false);
const inviteTarget = resolveWorkspaceInviteTarget(context);
// One decision for both of this rail's upgrade entries (credits chip and
// the invite dialog's seat-gate): personal → the wallet pricing modal,
// team → checkout vs change-plan by subscription state. See
// `workspaceUpgradeUrl` for why the axis is the workspace TYPE.
const upgradeUrl = workspaceUpgradeUrl(context, billing);
const billingUpgradeUrl =
context?.billingRecovery?.recoveryUrl?.trim() || upgradeUrl;
// #62: the 积分 row links straight OUT to B's wallet page (usage detail lives
// there) — no intermediate credits popover in the client, matching #5517.
const billingWalletUrl = workspaceSettingsUrl
? teamConsoleUrl(workspaceSettingsUrl, 'billing')
: null;
// Product decision: plan selection / payment lives in Vela Web. The local
// client opens that billing surface, then refreshes billing + context when
// focus returns so direct web upgrades sync plan, credits, seats and gates.
const canUpgrade = Boolean(billingUpgradeUrl && permissions?.canManageBilling);
const currentWorkspaceItem = context
? workspaceItems.find((item) => item.workspaceId === context.workspaceId) ?? null
: null;
const workspaceName =
currentWorkspaceItem?.workspaceName?.trim() ||
context?.teamName?.trim() ||
context?.teamId ||
(context?.workspaceType === 'personal' ? 'Personal workspace' : '');
const workspaceInitial = workspaceName.charAt(0).toUpperCase() || 'W';
const visibleWorkspaceItems =
workspaceItems.length > 0
? workspaceItems
: context
? [{
workspaceId: context.workspaceId,
workspaceName,
workspaceType: context.workspaceType,
workspaceMemberId: context.workspaceMemberId,
role: context.role,
memberStatus: context.memberStatus,
lifecycleState: context.lifecycleState,
} satisfies WorkspaceDirectoryItem]
: [];
async function loadWorkspaceDirectory() {
// Only show the loading row when there is nothing to show yet. With a warm
// cache the list is already on screen and this read just revalidates it.
if (cachedWorkspaceDirectory === null) setWorkspaceDirectoryLoading(true);
try {
const items = await coalescedGet('workspace-directory', async () => {
const response = await fetch('/api/workspace/directory', { cache: 'no-store' });
if (!response.ok) throw new Error(`directory ${response.status}`);
const body = (await response.json()) as WorkspaceDirectoryResponse;
return body.items ?? [];
});
cachedWorkspaceDirectory = items;
setWorkspaceItems(items);
} catch {
// A failed revalidation must not blank a list the user is looking at —
// keep the last known names and let the next open try again.
if (cachedWorkspaceDirectory === null) setWorkspaceItems([]);
} finally {
setWorkspaceDirectoryLoading(false);
}
}
async function switchWorkspace(workspaceId: string) {
if (workspaceId === context?.workspaceId || workspaceSwitchingId) return;
setWorkspaceSwitchingId(workspaceId);
try {
const response = await fetch('/api/workspace/active', {
method: 'PUT',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ workspaceId }),
});
if (!response.ok) return;
const body = (await response.json()) as WorkspaceActiveResponse;
setTeamOpen(false);
notifyWorkspaceContextRefresh();
notifyWorkspaceBillingRefresh();
notifyTeamProjectsChanged();
selectView('home');
} catch {
// Keep the menu open; the next open/focus refresh can retry the directory.
} finally {
setWorkspaceSwitchingId(null);
}
}
function openBillingUpgrade() {
if (!billingUpgradeUrl) return;
window.open(billingUpgradeUrl, '_blank', 'noopener,noreferrer');
window.setTimeout(() => {
notifyWorkspaceBillingRefresh();
notifyWorkspaceContextRefresh();
}, 3000);
}
const selectView = (next: EntryView) => {
onViewChange(next);
};
// While collapsed the rail is visually hidden but its controls stay mounted;
// mark it `inert` so they leave the tab order and pointer flow entirely.
const railRef = useRef<HTMLElement | null>(null);
useEffect(() => {
const node = railRef.current;
if (!node) return;
if (open) {
node.removeAttribute('inert');
} else {
node.setAttribute('inert', '');
}
}, [open]);
useEffect(() => {
if (!teamOpen) return;
void loadWorkspaceDirectory();
}, [teamOpen]);
return (
<nav
ref={railRef}
className={`entry-nav-rail${open ? ' is-open' : ''}`}
aria-label={t('entry.primaryNavAria')}
aria-hidden={open ? undefined : true}
>
<div className="entry-nav-rail__panel">
<div className="entry-nav-rail__group">
{context ? (
<div
ref={accountContainerRef}
className="entry-nav-rail__account"
onMouseEnter={cancelAccountClose}
onMouseLeave={scheduleAccountClose}
>
<button
type="button"
className="entry-nav-rail__account-trigger"
onClick={() => setAccountOpen((v) => !v)}
onMouseEnter={openAccountMenu}
aria-expanded={accountOpen}
data-testid="entry-nav-account"
>
<span className="entry-nav-rail__account-avatar" aria-hidden>{accountInitial}</span>
<span className="entry-nav-rail__account-name">{accountName}</span>
{/* #5517: the plan badge replaces the chevron when a tier is
known — the standalone credits chip row is gone; credits
live in the account menu's billing card. */}
{planTier ? <PlanWordmark tier={planTier} height={17} /> : <Icon name="chevron-down" size={14} />}
</button>
{accountOpen ? (
<>
{/* No backdrop here (unlike the team menu): hover-open relies
on document-level pointerover to close, and a full-screen
backdrop would swallow those events and insta-close. */}
<div className="entry-nav-rail__account-menu" role="menu">
<div className="entry-nav-rail__account-head">
<span className="entry-nav-rail__account-head-avatar" aria-hidden>{accountInitial}</span>
<span className="entry-nav-rail__account-head-name">{accountName}</span>
{accountEmail ? (
<span className="entry-nav-rail__account-head-email">{accountEmail}</span>
) : null}
</div>
{/* #5517 billing card: plan (+badge) + 升级 CTA + USD balance.
The balance row links out to B's wallet page. It receives
only an explicitly scoped money value; raw credits are
never formatted as dollars here. */}
{billing || balanceLabel ? (
<div className="entry-nav-rail__menu-credits">
<div className="entry-nav-rail__menu-credits-head">
<span className="entry-nav-rail__menu-credits-plan">
{tierLabel}
{planTier ? <PlanWordmark tier={planTier} height={11} /> : null}
</span>
{canUpgrade ? (
<button
type="button"
className="entry-nav-rail__menu-credits-upgrade"
onClick={() => {
setAccountOpen(false);
openBillingUpgrade();
}}
>
{t('entry.creditsUpgrade')}
</button>
) : null}
</div>
{/* #62 (product ruling): clicking the balance jumps straight to
B's web wallet page for the usage detail — there is
NO intermediate credits popover in the client. */}
<button
type="button"
className="entry-nav-rail__menu-credits-row"
data-testid="entry-nav-credits-row"
onClick={() => {
setAccountOpen(false);
if (billingWalletUrl) {
window.open(billingWalletUrl, '_blank', 'noopener,noreferrer');
}
}}
>
<span className="entry-nav-rail__menu-credits-label">
<RemixIcon name="battery-charge-line" size={14} /> {t('entry.credits')}
</span>
<span className="entry-nav-rail__menu-credits-value">
{balanceLabel ?? '—'}
<Icon name="chevron-right" size={14} />
</span>
</button>
</div>
) : null}
<button
type="button"
className="entry-nav-rail__menu-item"
role="menuitem"
onClick={() => {
setAccountOpen(false);
onOpenSettings?.();
}}
>
<Icon name="settings" size={15} /> {t('entry.accountSettings')}
</button>
{/* #5517's account menu goes 设置 → GitHub 帮助 → 功能建议 → 社交行,
with no theme row, no language submenu, and no divider in
between. Both controls still have a home in 设置·通用 (theme
segmented control + language picker), so dropping the
duplicates here costs no capability. */}
<a
className="entry-nav-rail__menu-item"
role="menuitem"
href={GITHUB_HELP_URL}
{...externalLinkProps}
onClick={() => setAccountOpen(false)}
>
<Icon name="comment" size={15} /> {t('entry.accountGithubHelp')}
</a>
<a
className="entry-nav-rail__menu-item"
role="menuitem"
href={GITHUB_FEATURE_URL}
{...externalLinkProps}
onClick={() => setAccountOpen(false)}
>
<Icon name="sparkles" size={15} /> {t('entry.accountFeatureRequest')}
</a>
{/* #5517: the GitHub/Discord/X/mail badges move off the rail
footer into a compact social row inside the account menu. */}
<div className="entry-nav-rail__menu-social">
<a
className="entry-nav-rail__menu-social-btn"
role="menuitem"
href={REPO_URL}
{...externalLinkProps}
aria-label={`GitHub · ${githubStars == null ? GITHUB_STARS_FALLBACK_LABEL : formatStars(githubStars)} stars`}
title={`GitHub · ${githubStars == null ? GITHUB_STARS_FALLBACK_LABEL : formatStars(githubStars)} stars`}
onClick={() => setAccountOpen(false)}
>
<Icon name="github-filled" size={15} />
<span className="entry-nav-rail__menu-social-count">
{githubStars == null ? GITHUB_STARS_FALLBACK_LABEL : formatStars(githubStars)}
</span>
</a>
<a
className="entry-nav-rail__menu-social-btn"
role="menuitem"
href={DISCORD_URL}
{...externalLinkProps}
aria-label={t('entry.discordAria')}
title={t('entry.discordAria')}
onClick={() => setAccountOpen(false)}
>
<Icon name="discord" size={15} />
</a>
<a
className="entry-nav-rail__menu-social-btn"
role="menuitem"
href={X_URL}
{...externalLinkProps}
aria-label="@OpenDesignHQ"
title="@OpenDesignHQ"
onClick={() => setAccountOpen(false)}
>
<span className="entry-nav-rail__menu-x" aria-hidden>X</span>
</a>
<a
className="entry-nav-rail__menu-social-btn"
role="menuitem"
href={CONTACT_EMAIL_URL}
aria-label={t('entry.mailAria')}
title={t('entry.mailAria')}
onClick={() => setAccountOpen(false)}
>
<Icon name="mail" size={15} />
</a>
</div>
<div className="entry-nav-rail__menu-divider" />
<button
type="button"
className="entry-nav-rail__menu-item"
role="menuitem"
onClick={() => {
setAccountOpen(false);
// recvqgMWpJZqhL: never sign out on this click alone —
// arm the confirmation dialog and let it run the logout.
setConfirmSignOut(true);
}}
>
<Icon name="log-out" size={15} /> {t('entry.accountSignOut')}
</button>
</div>
</>
) : null}
{confirmSignOut ? (
<SignOutConfirmDialog
onCancel={() => setConfirmSignOut(false)}
onConfirm={() => {
setConfirmSignOut(false);
// Real sign-out: clear the vela profile auth on the
// daemon, then nudge every workspace surface to re-read
// (the context read now resolves to null → the shell
// falls back to the signed-out local form).
void velaLogout().then(() => {
// recvqbkcLqIFH7: a stale "dismissed" flag on the
// footer's CloudSignInTip must not survive a real
// sign-out, or the rail's only sign-in entry point
// silently disappears with nothing left in its place.
resetCloudSignInTipDismissal();
notifyAmrLoginStatusChanged();
notifyWorkspaceContextRefresh();
notifyWorkspaceBillingRefresh();
notifyTeamProjectsChanged();
});
}}
/>
) : null}
</div>
) : null}
<button
type="button"
className="entry-nav-rail__search"
onClick={() => onOpenSearch?.()}
aria-label={t('common.search')}
data-testid="entry-nav-search"
>
<Icon name="search" size={14} />
<span className="entry-nav-rail__search-placeholder">{t('common.search')}</span>
<span className="entry-nav-rail__search-kbd" aria-hidden>⌘K</span>
</button>
<NavButton
active={isHome}
ariaLabel={homeLabel}
label={homeLabel}
onClick={() => selectView('home')}
testId="entry-nav-home"
>
<Icon name="home" size={16} />
</NavButton>
<NavButton
active={view === 'community'}
ariaLabel={communityLabel}
label={communityLabel}
onClick={() => selectView('community')}
testId="entry-nav-community"
>
<Icon name="globe" size={16} />
</NavButton>
{context ? (
<div className="entry-nav-rail__team-section">
<div className="entry-nav-rail__team-wrap">
<button
type="button"
className="entry-nav-rail__team"
onClick={() => setTeamOpen((v) => !v)}
aria-expanded={teamOpen}
data-testid="workspace-switcher"
>
<span className="entry-nav-rail__team-avatar" aria-hidden>{workspaceInitial}</span>
<span className="entry-nav-rail__team-name">{workspaceName}</span>
<Icon name="chevron-down" size={14} />
</button>
{teamOpen ? (
<>
<div className="entry-nav-rail__menu-backdrop" onClick={() => setTeamOpen(false)} />
<div
className="entry-nav-rail__team-menu"
role="menu"
onKeyDown={handleWorkspaceMenuKeyDown}
>
<div
className="entry-nav-rail__workspace-list"
data-testid="workspace-switcher-list"
>
{visibleWorkspaceItems.map((item) => {
const active = item.workspaceId === context.workspaceId;
const initial = item.workspaceName.trim().charAt(0).toUpperCase() || 'W';
return (
<button
key={item.workspaceId}
type="button"
className={`entry-nav-rail__menu-item${active ? ' is-current' : ''}`}
role="menuitem"
aria-current={active ? 'true' : undefined}
// Only the in-flight switch disables a row. Disabling the
// CURRENT one made the UA grey it out, so the selected
// workspace read as the inactive one and vice versa;
// `.is-current` (bold + accent ✓) is the selected signal.
disabled={workspaceSwitchingId === item.workspaceId}
onClick={() => {
void switchWorkspace(item.workspaceId);
}}
>
<span className="entry-nav-rail__team-avatar" aria-hidden>{initial}</span>
{/* #5517's switcher rows are avatar + full name + ✓ only.
The raw role word ate the name's width and truncated
it; the role is already on 设置·工作区. */}
<span className="entry-nav-rail__workspace-menu-name">{item.workspaceName}</span>
{active ? <Icon name="check" size={14} /> : null}
</button>
);
})}
{workspaceDirectoryLoading && visibleWorkspaceItems.length === 0 ? (
<div className="entry-nav-rail__menu-item is-muted" role="status">
{t('common.loading')}
</div>
) : null}
</div>
<div
className="entry-nav-rail__workspace-actions"
data-testid="workspace-switcher-actions"