Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): add multi-account switching
xd-bobo728332b8b75d
diff --git a/apps/desktop/src/main/__tests__/authAccountMetadata.test.ts b/apps/desktop/src/main/__tests__/authAccountMetadata.test.tsnew file mode 100644index 0000000000..3a190b7549--- /dev/null+++ b/apps/desktop/src/main/__tests__/authAccountMetadata.test.ts@@ -0,0 +1,130 @@+import { describe, expect, it } from 'vitest';++import { reconcileSavedAccountMetadata, type StoredAccountMetadata } from '../authAccountMetadata';++function metadata(+ membershipId: string,+ passportId: string,+ displayName: string,+ avatarUrl: string | null,+): StoredAccountMetadata {+ return {+ membershipId,+ passportId,+ displayName,+ email: `${membershipId}@example.com`,+ avatarUrl,+ kind: 'personal',+ role: 'owner',+ orgId: null,+ orgName: null,+ orgLogoUrl: null,+ };+}++describe('saved account metadata reconciliation', () => {+ it('patches the matching resource and Passport entry after a profile edit', () => {+ const stale = metadata('membership-1', 'passport-1', 'Old name', 'old-avatar');+ const sibling = metadata('membership-2', 'passport-2', 'Sibling', null);+ const vault = {+ resources: {+ current: { realm: 'global' as const, metadata: stale },+ sibling: { realm: 'global' as const, metadata: sibling },+ },+ passports: {+ current: {+ realm: 'global' as const,+ passportId: 'passport-1',+ memberships: [stale],+ },+ sibling: {+ realm: 'global' as const,+ passportId: 'passport-2',+ memberships: [sibling],+ },+ },+ };+ const latest = metadata('membership-1', 'passport-1', 'New name', 'new-avatar');++ expect(+ reconcileSavedAccountMetadata(vault, {+ realm: 'global',+ passportId: 'passport-1',+ memberships: [latest],+ passportMode: 'patch-known',+ }),+ ).toBe(true);+ expect(vault.resources.current.metadata).toBe(latest);+ expect(vault.passports.current.memberships).toEqual([latest]);+ expect(vault.resources.sibling.metadata).toBe(sibling);+ expect(vault.passports.sibling.memberships).toEqual([sibling]);+ });++ it('uses an authoritative Passport sync to refresh resource metadata without crossing realms', () => {+ const stale = metadata('membership-1', 'passport-1', 'Old name', 'old-avatar');+ const cnStale = metadata('membership-1', 'passport-1', 'CN name', 'cn-avatar');+ const vault = {+ resources: {+ global: {+ realm: 'global' as const,+ refreshToken: 'resource-refresh-token',+ metadata: stale,+ },+ cn: { realm: 'cn' as const, metadata: cnStale },+ },+ passports: {+ global: {+ realm: 'global' as const,+ passportId: 'passport-1',+ accountRefreshToken: 'account-refresh-token',+ memberships: [stale],+ },+ cn: {+ realm: 'cn' as const,+ passportId: 'passport-1',+ memberships: [cnStale],+ },+ },+ };+ const latest = metadata('membership-1', 'passport-1', 'Synced name', 'synced-avatar');+ const added = metadata('membership-3', 'passport-1', 'New membership', null);++ reconcileSavedAccountMetadata(vault, {+ realm: 'global',+ passportId: 'passport-1',+ memberships: [latest, added],+ passportMode: 'replace-passport',+ });++ expect(vault.resources.global.metadata).toBe(latest);+ expect(vault.passports.global.memberships).toEqual([latest, added]);+ expect(vault.resources.global.refreshToken).toBe('resource-refresh-token');+ expect(vault.passports.global.accountRefreshToken).toBe('account-refresh-token');+ expect(vault.resources.cn.metadata).toBe(cnStale);+ expect(vault.passports.cn.memberships).toEqual([cnStale]);+ });++ it('does not add an unknown membership during a profile-edit patch', () => {+ const known = metadata('membership-1', 'passport-1', 'Known', null);+ const vault = {+ resources: {},+ passports: {+ current: {+ realm: 'global' as const,+ passportId: 'passport-1',+ memberships: [known],+ },+ },+ };++ expect(+ reconcileSavedAccountMetadata(vault, {+ realm: 'global',+ passportId: 'passport-1',+ memberships: [metadata('unknown', 'passport-1', 'Unknown', null)],+ passportMode: 'patch-known',+ }),+ ).toBe(false);+ expect(vault.passports.current.memberships).toEqual([known]);+ });+});diff --git a/apps/desktop/src/main/__tests__/authAccountsIpcSecurity.test.ts b/apps/desktop/src/main/__tests__/authAccountsIpcSecurity.test.tsnew file mode 100644index 0000000000..b735e3b32e--- /dev/null+++ b/apps/desktop/src/main/__tests__/authAccountsIpcSecurity.test.ts@@ -0,0 +1,27 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++import { describe, expect, it } from 'vitest';++describe('desktop saved-account IPC boundary', () => {+ const source = readFileSync(resolve(__dirname, '..', 'bootstrap-electron.ts'), 'utf8');+ const channels = [+ 'auth:accounts:list',+ 'auth:accounts:sync',+ 'auth:accounts:switch',+ 'auth:accounts:begin-add',+ 'auth:accounts:cancel-add',+ ];++ it.each(channels)('%s rejects an untrusted renderer before calling authManager', (channel) => {+ const start = source.indexOf(`ipcMain.handle('${channel}'`);+ const end = source.indexOf('\n });', start);+ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);+ const handler = source.slice(start, end);+ expect(handler).toContain('assertTrustedAppRendererEvent(event);');+ expect(handler.indexOf('assertTrustedAppRendererEvent(event);')).toBeLessThan(+ handler.indexOf('authManager.'),+ );+ });+});diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.tsindex a5af26efb6..7ed4d04473 100644--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts@@ -82,18 +82,11 @@ describe('auth login-flow reset', () => {});it('clears stale organization realm state before personal login and a new discovery', () => {- const discoveryStart = source.indexOf(- 'async function discoverOrganizationRealm(org: string)',- );- const discoveryBody = source.slice(- discoveryStart,- source.indexOf('\n}', discoveryStart),- );+ const discoveryStart = source.indexOf('async function discoverOrganizationRealm(org: string)');+ const discoveryBody = source.slice(discoveryStart, source.indexOf('\n}', discoveryStart));expect(discoveryBody).toContain('pendingAuthRealm = null;');- const actionStart = source.indexOf(- 'async function runLoginAction(action: DesktopLoginAction)',- );+ const actionStart = source.indexOf('async function runLoginAction(action: DesktopLoginAction)');const actionPreamble = source.slice(actionStart,source.indexOf('const stateBeforeAction', actionStart),@@ -101,12 +94,8 @@ describe('auth login-flow reset', () => {expect(actionPreamble).toContain("action.type === 'discover'");expect(actionPreamble).toContain("action.type === 'request-code'");expect(actionPreamble).toContain("action.type === 'verify-code'");- expect(actionPreamble).toContain(- "action.type === 'start-browser' && action.kind === 'social'",- );- expect(actionPreamble).toContain(- 'if (startsBuildRealmFlow) pendingAuthRealm = null;',- );+ expect(actionPreamble).toContain("action.type === 'start-browser' && action.kind === 'social'");+ expect(actionPreamble).toContain('if (startsBuildRealmFlow) pendingAuthRealm = null;');});it('does not leave expired private tickets on a screen that can only reuse them', () => {@@ -116,14 +105,16 @@ describe('auth login-flow reset', () => {expect(source).toContain("? { step: 'error', code, recoverTo: 'identifier' }");});- it('keeps the account token in the login flow only and exchanges a resource token', () => {+ it('keeps account access tokens in memory while persisting only encrypted refresh sessions', () => {expect(source).toContain("const LEGACY_ACCOUNT_REFRESH_TOKEN_KEY = 'cindy_auth_account_refresh_token';",);expect(source).toContain('let pendingAccountToken: string | null = null;');expect(source).toContain('client.exchangeAccountMembership(accountToken, action.accountId)');- expect(source).not.toContain('.logoutAccount(');- expect(source).not.toContain('accountSession');+ expect(source).toContain("const AUTH_ACCOUNT_VAULT_KEY = 'cindy_auth_accounts_v1';");+ expect(source).toContain('client.refreshAccount(passport.accountRefreshToken)');+ expect(source).toContain('client.logoutAccount(pair.accountToken)');+ expect(source).toContain('writeSafe(AUTH_ACCOUNT_VAULT_KEY');expect(source).not.toContain('writeSafe(LEGACY_ACCOUNT_REFRESH_TOKEN_KEY');expect(source).not.toContain('accountToken: accountAccessToken');@@ -144,7 +135,24 @@ describe('auth login-flow reset', () => {expect(getterBody).not.toContain('accountAccessToken');});- it('never restores an account session during resource-token initialization', () => {+ it('keeps saved account metadata fresh after profile edits and Passport sync', () => {+ const rememberPassportStart = source.indexOf('function rememberPassportSession(');+ const rememberPassportEnd = source.indexOf(+ '\n}\n\nfunction rememberUpdatedMembershipMetadata',+ rememberPassportStart,+ );+ const rememberPassportBody = source.slice(rememberPassportStart, rememberPassportEnd);+ expect(rememberPassportBody).toContain('reconcileSavedAccountMetadata(vault');+ expect(rememberPassportBody).toContain("passportMode: 'replace-passport'");++ const profileStart = source.indexOf('export async function updateServerProfile(');+ const profileEnd = source.indexOf('\n}\n\nexport async function initialize(', profileStart);+ const profileBody = source.slice(profileStart, profileEnd);+ expect(profileBody).toContain('rememberUpdatedMembershipMetadata(');+ expect(profileBody).toContain('membership.passportId ?? currentUser.passportId');+ });++ it('keeps account refresh out of resource-token cold-start initialization', () => {const initializeStart = source.indexOf('export async function initialize(');const initializeEnd = source.indexOf('\n}\n\n/**\n * 冷启动 refresh 流程本体', initializeStart);const initializeBody = source.slice(initializeStart, initializeEnd);@@ -165,7 +173,9 @@ describe('auth login-flow reset', () => {expect(localGuard).toBeGreaterThan(-1);expect(refreshTokenRead).toBeGreaterThan(localGuard);- expect(initializeBody.slice(localGuard, refreshTokenRead)).toContain('return snapshotAuthState();');+ expect(initializeBody.slice(localGuard, refreshTokenRead)).toContain(+ 'return snapshotAuthState();',+ );});it('activates a restored realm only after the refreshed membership passes build policy', () => {@@ -285,7 +295,10 @@ describe('auth login-flow reset', () => {expect(helperBody).toContain('notifySessionExpired(reason);');const ownerCommitStart = source.indexOf('async function withAccountFreeOwnerCommit(');- const ownerCommitEnd = source.indexOf('\n}\n\nasync function withCloudOwnerCommit(', ownerCommitStart);+ const ownerCommitEnd = source.indexOf(+ '\n}\n\nasync function withCloudOwnerCommit(',+ ownerCommitStart,+ );const ownerCommitBody = source.slice(ownerCommitStart, ownerCommitEnd);expect(ownerCommitBody).toContain('beginAppSessionBoundary()');expect(ownerCommitBody).toContain('notifyRendererAuthBoundaryPending();');diff --git a/apps/desktop/src/main/authAccountMetadata.ts b/apps/desktop/src/main/authAccountMetadata.tsnew file mode 100644index 0000000000..705c1ca3c4--- /dev/null+++ b/apps/desktop/src/main/authAccountMetadata.ts@@ -0,0 +1,84 @@+import type { AuthRegion } from '@cindy/auth-client';++export interface StoredAccountMetadata {+ membershipId: string;+ passportId: string;+ displayName: string;+ email: string | null;+ avatarUrl: string | null;+ kind: 'personal' | 'org';+ role: 'owner' | 'admin' | 'member';+ orgId: string | null;+ orgName: string | null;+ orgLogoUrl: string | null;+}++interface AccountMetadataVault {+ resources: Record<+ string,+ {+ realm: AuthRegion;+ metadata: StoredAccountMetadata;+ }+ >;+ passports: Record<+ string,+ {+ realm: AuthRegion;+ passportId: string;+ memberships: StoredAccountMetadata[];+ }+ >;+}++/**+ * Reconcile public account metadata without touching either refresh-token family.+ *+ * `patch-known` is used after editing one profile: only an already-known membership is updated.+ * `replace-passport` is used after GET /account/memberships: that response is authoritative for+ * the Passport projection, while matching resource sessions keep their tokens and timestamps.+ */+export function reconcileSavedAccountMetadata(+ vault: AccountMetadataVault,+ input: {+ realm: AuthRegion;+ passportId: string;+ memberships: readonly StoredAccountMetadata[];+ passportMode: 'patch-known' | 'replace-passport';+ },+): boolean {+ const latestById = new Map(+ input.memberships+ .filter((metadata) => metadata.passportId === input.passportId)+ .map((metadata) => [metadata.membershipId, metadata] as const),+ );+ if (latestById.size === 0) return false;++ let changed = false;+ for (const resource of Object.values(vault.resources)) {+ if (resource.realm !== input.realm || resource.metadata.passportId !== input.passportId) {+ continue;+ }+ const latest = latestById.get(resource.metadata.membershipId);+ if (!latest) continue;+ resource.metadata = latest;+ changed = true;+ }++ for (const passport of Object.values(vault.passports)) {+ if (passport.realm !== input.realm || passport.passportId !== input.passportId) continue;+ if (input.passportMode === 'replace-passport') {+ passport.memberships = [...latestById.values()];+ changed = true;+ continue;+ }+ passport.memberships = passport.memberships.map((metadata) => {+ const latest = latestById.get(metadata.membershipId);+ if (!latest) return metadata;+ changed = true;+ return latest;+ });+ }++ return changed;+}diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.tsindex 170087be60..0d672ff964 100644--- a/apps/desktop/src/main/authManager.ts+++ b/apps/desktop/src/main/authManager.ts@@ -34,6 +34,7 @@ import {type AuthMembership,type AuthRegion,type AuthTokenPair,+ type AccountMembership,type AccountDeletionAvailability,type AccountDeletionStatus,type LoginMethod,@@ -72,6 +73,7 @@ import {type AuthLoopbackDevBridge,} from './authLoopbackCallback';import { createDesktopPollCredentials, runHostedCallbackPolling } from './authHostedCallback';+import { reconcileSavedAccountMetadata, type StoredAccountMetadata } from './authAccountMetadata';// dev-only 登录 scenario harness(implementation-plan Step 0 WHAT4):静态 import// (main 禁运行时动态 import),生产构建由 vite alias 把整模块替换为空 stub// (vite.main.config.ts),运行时另有 app.isPackaged guard 双保险。@@ -95,7 +97,10 @@ import {} from './clientEndpointsService.js';import {parseDesktopLoginAction,+ parseDesktopAccountKey,type DesktopAccountDeletionChallenge,+ type DesktopAccountSwitcherSnapshot,+ type DesktopSavedAccount,type DesktopLoginAction,type DesktopLoginActionResult,} from '../shared/authIpc';@@ -157,6 +162,7 @@ function authServerUrl(realm: AuthRegion = activeAuthRealm): string {return getClientEndpointForRealm(realm, 'authApiBaseUrl');}const AUTH_SESSION_KEY = 'cindy_auth_session_v1';+const AUTH_ACCOUNT_VAULT_KEY = 'cindy_auth_accounts_v1';const LEGACY_RESOURCE_REFRESH_TOKEN_KEY = 'cindy_auth_refresh_token';const ACCOUNT_DELETION_RECEIPT_KEY = 'cindy_auth_account_deletion_receipt';const LEGACY_ACCOUNT_REFRESH_TOKEN_KEY = 'cindy_auth_account_refresh_token';@@ -204,6 +210,27 @@ interface CurrentUser extends User {membershipDisplayName: string;}+interface StoredResourceSession {+ realm: AuthRegion;+ refreshToken: string;+ metadata: StoredAccountMetadata;+ lastUsedAt: number;+}++interface StoredPassportSession {+ realm: AuthRegion;+ passportId: string;+ accountRefreshToken: string;+ memberships: StoredAccountMetadata[];+}++interface AuthAccountVault {+ version: 1;+ activeAccountKey: string | null;+ resources: Record<string, StoredResourceSession>;+ passports: Record<string, StoredPassportSession>;+}+export interface AuthState {user: User | null;/** Stable application session. Local is an app session, not cloud authentication. */@@ -269,8 +296,8 @@ const stableOwnerPostCommitCoordinator = new StableOwnerPostCommitCoordinator({scopeKey: activeOwnerScopeKey(),dataOwnerId: session.dataOwnerId,stable:- !isAppSessionBoundaryPending()- && isGhostSkillProjectionBoundaryStableForOwner(session.dataOwnerId),+ !isAppSessionBoundaryPending() &&+ isGhostSkillProjectionBoundaryStableForOwner(session.dataOwnerId),};},warn: (message, meta) => log.warn(message, meta),@@ -328,6 +355,8 @@ let discoveredMethods: LoginMethod[] = [];// Account token 仅在一次登录的 Membership 选择阶段存活;兑换 resource token// 后立即清空,不持久化、不续期,也不参与业务请求或正常登出。let pendingAccountToken: string | null = null;+let pendingAccountRefreshToken: string | null = null;+let pendingAccountMemberships: AuthMembership[] = [];let pendingLoginTicket: string | null = null;let pendingBindTicket: string | null = null;let pendingSsoVerificationTicket: string | null = null;@@ -497,6 +526,227 @@ function removeSafe(key: string): void {}}+function emptyAuthAccountVault(): AuthAccountVault {+ return { version: 1, activeAccountKey: null, resources: {}, passports: {} };+}++function accountVaultKey(realm: AuthRegion, membershipId: string): string {+ return JSON.stringify([realm, membershipId]);+}++function passportVaultKey(realm: AuthRegion, passportId: string): string {+ return JSON.stringify([realm, passportId]);+}++function isStoredAccountMetadata(value: unknown): value is StoredAccountMetadata {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;+ const item = value as Partial<StoredAccountMetadata>;+ return (+ typeof item.membershipId === 'string' &&+ typeof item.passportId === 'string' &&+ typeof item.displayName === 'string' &&+ (item.email === null || typeof item.email === 'string') &&+ (item.avatarUrl === null || typeof item.avatarUrl === 'string') &&+ (item.kind === 'personal' || item.kind === 'org') &&+ (item.role === 'owner' || item.role === 'admin' || item.role === 'member') &&+ (item.orgId === null || typeof item.orgId === 'string') &&+ (item.orgName === null || typeof item.orgName === 'string') &&+ (item.orgLogoUrl === null || typeof item.orgLogoUrl === 'string')+ );+}++function readAuthAccountVault(): AuthAccountVault {+ const raw = readSafe(AUTH_ACCOUNT_VAULT_KEY);+ if (!raw) return emptyAuthAccountVault();+ try {+ const parsed = JSON.parse(raw) as Partial<AuthAccountVault>;+ if (+ parsed.version !== 1 ||+ !parsed.resources ||+ typeof parsed.resources !== 'object' ||+ Array.isArray(parsed.resources) ||+ !parsed.passports ||+ typeof parsed.passports !== 'object' ||+ Array.isArray(parsed.passports)+ ) {+ throw new Error('unsupported auth account vault');+ }+ const resources: Record<string, StoredResourceSession> = {};+ for (const [key, candidate] of Object.entries(parsed.resources)) {+ if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) continue;+ const item = candidate as Partial<StoredResourceSession>;+ if (+ (item.realm !== 'cn' && item.realm !== 'global') ||+ typeof item.refreshToken !== 'string' ||+ !isStoredAccountMetadata(item.metadata) ||+ typeof item.lastUsedAt !== 'number'+ )+ continue;+ resources[key] = item as StoredResourceSession;+ }+ const passports: Record<string, StoredPassportSession> = {};+ for (const [key, candidate] of Object.entries(parsed.passports)) {+ if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) continue;+ const item = candidate as Partial<StoredPassportSession>;+ if (+ (item.realm !== 'cn' && item.realm !== 'global') ||+ typeof item.passportId !== 'string' ||+ typeof item.accountRefreshToken !== 'string' ||+ !Array.isArray(item.memberships)+ )+ continue;+ passports[key] = {+ realm: item.realm,+ passportId: item.passportId,+ accountRefreshToken: item.accountRefreshToken,+ memberships: item.memberships.filter(isStoredAccountMetadata),+ };+ }+ return {+ version: 1,+ activeAccountKey:+ typeof parsed.activeAccountKey === 'string' ? parsed.activeAccountKey : null,+ resources,+ passports,+ };+ } catch (error) {+ log.warn('encrypted auth account vault is invalid; ignoring it without deleting', error);+ return emptyAuthAccountVault();+ }+}++function writeAuthAccountVault(vault: AuthAccountVault): boolean {+ return writeSafe(AUTH_ACCOUNT_VAULT_KEY, JSON.stringify(vault));+}++function metadataFromMembership(+ membership: AuthMembership | AccountMembership,+ passportId: string,+): StoredAccountMetadata {+ return {+ membershipId: membership.id,+ passportId,+ displayName: membership.displayName,+ email: membership.email,+ avatarUrl: membership.avatarUrl ?? null,+ kind: membership.kind,+ role: membership.role,+ orgId: membership.orgId,+ orgName: membership.orgName,+ orgLogoUrl: membership.orgLogoUrl ?? null,+ };+}++function rememberResourceSession(+ pair: AuthTokenPair,+ realm: AuthRegion,+ options: { markActive?: boolean; lastUsedAt?: number } = {},+): void {+ const passportId = pair.membership.passportId;+ if (!passportId) {+ log.warn('resource session omitted passportId; keeping only the active compatibility record');+ return;+ }+ const key = accountVaultKey(realm, pair.membership.id);+ const vault = readAuthAccountVault();+ vault.resources[key] = {+ realm,+ refreshToken: pair.refreshToken,+ metadata: metadataFromMembership(pair.membership, passportId),+ lastUsedAt: options.lastUsedAt ?? Date.now(),+ };+ if (options.markActive !== false) vault.activeAccountKey = key;+ writeAuthAccountVault(vault);+}++function rememberPassportSession(input: {+ realm: AuthRegion;+ passportId: string;+ accountRefreshToken: string;+ memberships?: readonly (AuthMembership | AccountMembership | StoredAccountMetadata)[];+}): void {+ const key = passportVaultKey(input.realm, input.passportId);+ const vault = readAuthAccountVault();+ const previous = vault.passports[key];+ const memberships = (input.memberships ?? previous?.memberships ?? []).map((membership) =>+ isStoredAccountMetadata(membership)+ ? membership+ : metadataFromMembership(membership, input.passportId),+ );+ vault.passports[key] = {+ realm: input.realm,+ passportId: input.passportId,+ accountRefreshToken: input.accountRefreshToken,+ memberships,+ };+ reconcileSavedAccountMetadata(vault, {+ realm: input.realm,+ passportId: input.passportId,+ memberships,+ passportMode: 'replace-passport',+ });+ writeAuthAccountVault(vault);+}++function rememberUpdatedMembershipMetadata(+ membership: AuthMembership,+ realm: AuthRegion,+ passportId: string,+): void {+ if (isPassiveSharedUserDataInstance()) return;+ const vault = readAuthAccountVault();+ const changed = reconcileSavedAccountMetadata(vault, {+ realm,+ passportId,+ memberships: [metadataFromMembership(membership, passportId)],+ passportMode: 'patch-known',+ });+ if (changed) writeAuthAccountVault(vault);+}++function removeVaultAccount(accountKey: string): void {+ const vault = readAuthAccountVault();+ delete vault.resources[accountKey];+ if (vault.activeAccountKey === accountKey) vault.activeAccountKey = null;+ writeAuthAccountVault(vault);+}++function bindResourcePairToSavedAccount(+ pair: AuthTokenPair,+ realm: AuthRegion,+ metadata: StoredAccountMetadata,+): AuthTokenPair {+ if (+ accountVaultKey(realm, pair.membership.id) !== accountVaultKey(realm, metadata.membershipId) ||+ (pair.membership.passportId !== undefined && pair.membership.passportId !== metadata.passportId)+ ) {+ throw new AuthApiError(+ 'INVALID_RESPONSE',+ 502,+ 'Refreshed resource session does not match the selected saved account',+ );+ }+ return pair.membership.passportId+ ? pair+ : {+ ...pair,+ membership: { ...pair.membership, passportId: metadata.passportId },+ };+}++function isDefinitiveRefreshError(error: unknown): boolean {+ return (+ error instanceof AuthApiError &&+ [+ 'INVALID_REFRESH_TOKEN',+ 'REFRESH_TOKEN_EXPIRED',+ 'DEVICE_MISMATCH',+ 'ACCOUNT_UNAVAILABLE',+ 'MEMBERSHIP_DISABLED',+ ].includes(error.code)+ );+}+function readPersistedAuthSession() {return parseAuthSessionRecord(readSafe(AUTH_SESSION_KEY));}@@ -1825,6 +2075,8 @@ function resetLoginFlowState(): void {providerConfig = null;discoveredMethods = [];pendingAccountToken = null;+ pendingAccountRefreshToken = null;+ pendingAccountMemberships = [];pendingLoginTicket = null;pendingBindTicket = null;pendingSsoVerificationTicket = null;@@ -1894,6 +2146,8 @@ function clearAuth(credentialStoreHealth.reset();accessToken = null;pendingAccountToken = null;+ pendingAccountRefreshToken = null;+ pendingAccountMemberships = [];currentUser = null;accountDeletionRestoredNoticePending = false;confirmedAccountDeletionCredential = null;@@ -1955,6 +2209,14 @@ async function expireRuntimeAuth(reason: SessionExpiredReason = 'unknown',opts: { preservePersistedRefreshToken?: boolean } = {},): Promise<void> {+ const expiredAccountKey = currentUser ? accountVaultKey(activeAuthRealm, currentUser.id) : null;+ if (+ expiredAccountKey &&+ !opts.preservePersistedRefreshToken &&+ !isPassiveSharedUserDataInstance()+ ) {+ removeVaultAccount(expiredAccountKey);+ }// Raise the owner boundary before clearing auth so queued owner-scoped// continuations see the pending boundary and fail closed, rather than// executing between token clearance and the async teardown (P1,@@ -1999,6 +2261,10 @@ async function expireRuntimeAuth(export function invalidateSession(reason: string): Promise<void> {if (sessionInvalidationPromise) return sessionInvalidationPromise;+ if (currentUser && !isPassiveSharedUserDataInstance()) {+ removeVaultAccount(accountVaultKey(activeAuthRealm, currentUser.id));+ }+// Raise the owner boundary before clearing auth (same P1 fix as// expireRuntimeAuth — see PRRT_kwDOTgdRUs6YaakC).const releaseBoundary = beginAppSessionBoundary();@@ -2085,6 +2351,203 @@ export function getAuthState(): AuthState {return snapshotAuthState();}+function accountSummaryFromMetadata(+ accountKey: string,+ metadata: StoredAccountMetadata,+ activeAccountKey: string | null,+): DesktopSavedAccount {+ return {+ accountKey,+ displayName: metadata.displayName || metadata.email || 'Cindy',+ email: metadata.email,+ avatarUrl: metadata.avatarUrl,+ kind: metadata.kind,+ orgName: metadata.orgName,+ orgLogoUrl: metadata.orgLogoUrl,+ isCurrent: accountKey === activeAccountKey,+ };+}++export function listSavedAccounts(): DesktopAccountSwitcherSnapshot {+ const vault = readAuthAccountVault();+ const byKey = new Map<string, StoredAccountMetadata>();+ for (const [key, resource] of Object.entries(vault.resources)) {+ byKey.set(key, resource.metadata);+ }+ for (const passport of Object.values(vault.passports)) {+ for (const membership of passport.memberships) {+ const key = accountVaultKey(passport.realm, membership.membershipId);+ if (!byKey.has(key)) byKey.set(key, membership);+ }+ }+ const activeKey = currentUser+ ? accountVaultKey(activeAuthRealm, currentUser.id)+ : vault.activeAccountKey;+ const accounts = [...byKey.entries()]+ .map(([key, metadata]) => accountSummaryFromMetadata(key, metadata, activeKey))+ .sort((left, right) => {+ if (left.isCurrent !== right.isCurrent) return left.isCurrent ? -1 : 1;+ const leftUsed = vault.resources[left.accountKey]?.lastUsedAt ?? 0;+ const rightUsed = vault.resources[right.accountKey]?.lastUsedAt ?? 0;+ return rightUsed - leftUsed || left.displayName.localeCompare(right.displayName);+ });+ return { accounts, mutationAllowed: !isPassiveSharedUserDataInstance() };+}++export async function syncSavedAccounts(): Promise<DesktopAccountSwitcherSnapshot> {+ if (isPassiveSharedUserDataInstance()) return listSavedAccounts();+ const initial = readAuthAccountVault();+ for (const [key, passport] of Object.entries(initial.passports)) {+ try {+ await loadClientEndpointsForRealm(passport.realm);+ const client = createAuthClient(passport.realm);+ const pair = await client.refreshAccount(passport.accountRefreshToken);+ // Account refresh has no replay grace. Persist the replacement before+ // making the membership request that consumes its access token.+ rememberPassportSession({+ realm: passport.realm,+ passportId: passport.passportId,+ accountRefreshToken: pair.accountRefreshToken,+ memberships: passport.memberships,+ });+ const memberships = await client.getAccountMemberships(pair.accountToken);+ rememberPassportSession({+ realm: passport.realm,+ passportId: passport.passportId,+ accountRefreshToken: pair.accountRefreshToken,+ memberships,+ });+ } catch (error) {+ if (!isDefinitiveRefreshError(error)) {+ log.warn('saved account membership sync failed transiently', error);+ continue;+ }+ const latest = readAuthAccountVault();+ if (latest.passports[key]?.accountRefreshToken === passport.accountRefreshToken) {+ delete latest.passports[key];+ writeAuthAccountVault(latest);+ }+ }+ }+ return listSavedAccounts();+}++export async function switchSavedAccount(rawAccountKey: unknown): Promise<void> {+ const parsedKey = parseDesktopAccountKey(rawAccountKey);+ if (!parsedKey) throw new AuthApiError('INVALID_AUTH_ACTION', 400, 'Invalid account key');+ if (isPassiveSharedUserDataInstance()) {+ throw new AuthApiError(+ 'PASSIVE_AUTH_MUTATION_BLOCKED',+ 409,+ 'This shared-data instance cannot switch accounts',+ );+ }+ if (currentUser && parsedKey === accountVaultKey(activeAuthRealm, currentUser.id)) return;++ let vault = readAuthAccountVault();+ let resource: StoredResourceSession | undefined = vault.resources[parsedKey];+ let metadata = resource?.metadata;+ if (!metadata) {+ for (const passport of Object.values(vault.passports)) {+ const candidate = passport.memberships.find(+ (membership) => accountVaultKey(passport.realm, membership.membershipId) === parsedKey,+ );+ if (candidate) {+ metadata = candidate;+ break;+ }+ }+ }+ if (!metadata) throw new AuthApiError('ACCOUNT_NOT_FOUND', 404, 'Saved account not found');++ const realm =+ resource?.realm ??+ Object.values(vault.passports).find((passport) =>+ passport.memberships.some(+ (membership) => accountVaultKey(passport.realm, membership.membershipId) === parsedKey,+ ),+ )?.realm;+ if (!realm) throw new AuthApiError('ACCOUNT_NOT_FOUND', 404, 'Saved account realm missing');+ await loadClientEndpointsForRealm(realm);+ const client = createAuthClient(realm);+ let pair: AuthTokenPair | null = null;++ if (resource) {+ try {+ pair = await client.refresh(resource.refreshToken);+ pair = bindResourcePairToSavedAccount(pair, realm, metadata);+ rememberResourceSession(pair, realm, { markActive: false });+ } catch (error) {+ if (!isDefinitiveRefreshError(error)) throw error;+ removeVaultAccount(parsedKey);+ resource = undefined;+ vault = readAuthAccountVault();+ }+ }++ if (!pair) {+ const passport = vault.passports[passportVaultKey(realm, metadata.passportId)];+ if (!passport) {+ throw new AuthApiError('ACCOUNT_REAUTH_REQUIRED', 401, 'Saved account requires login');+ }+ let accountRefreshSucceeded = false;+ try {+ const accountPair = await client.refreshAccount(passport.accountRefreshToken);+ accountRefreshSucceeded = true;+ rememberPassportSession({+ realm,+ passportId: passport.passportId,+ accountRefreshToken: accountPair.accountRefreshToken,+ memberships: passport.memberships,+ });+ pair = await client.exchangeAccountMembership(+ accountPair.accountToken,+ metadata.membershipId,+ );+ pair = bindResourcePairToSavedAccount(pair, realm, metadata);+ rememberResourceSession(pair, realm, { markActive: false });+ } catch (error) {+ // An exchange can fail because one membership was disabled while the+ // Passport session remains healthy. Only an Account-refresh failure+ // invalidates every membership owned by this Passport.+ if (!accountRefreshSucceeded && isDefinitiveRefreshError(error)) {+ const latest = readAuthAccountVault();+ delete latest.passports[passportVaultKey(realm, metadata.passportId)];+ writeAuthAccountVault(latest);+ }+ throw error;+ }+ }++ pendingAuthRealm = realm;+ pendingAccountRefreshToken = null;+ pendingAccountMemberships = [];+ try {+ await completeLogin({ status: 'ok', ...pair });+ } catch (error) {+ pendingAuthRealm = null;+ throw error;+ }+}++export async function beginAddAccountLogin(): Promise<DesktopLoginActionResult> {+ if (isPassiveSharedUserDataInstance()) {+ throw new AuthApiError(+ 'PASSIVE_AUTH_MUTATION_BLOCKED',+ 409,+ 'This shared-data instance cannot add accounts',+ );+ }+ browserAuthorizationSlot.cancelActive();+ resetLoginFlowState();+ return getLoginState();+}++export function cancelAddAccountLogin(): void {+ browserAuthorizationSlot.cancelActive();+ resetLoginFlowState();+}+export function getCurrentDataOwnerId(): string | null {return getActiveAppSession().dataOwnerId;}@@ -2112,7 +2575,8 @@ export function isLocalMode(): boolean {export function hasNoPersistedAuthCredentials(): boolean {return (isPersistedSecretAbsent(AUTH_SESSION_KEY) &&- isPersistedSecretAbsent(LEGACY_RESOURCE_REFRESH_TOKEN_KEY)+ isPersistedSecretAbsent(LEGACY_RESOURCE_REFRESH_TOKEN_KEY) &&+ isPersistedSecretAbsent(AUTH_ACCOUNT_VAULT_KEY));}@@ -2344,6 +2808,19 @@ export function isConfirmedAccountDeletionSessionCurrent(): boolean {export async function clearLocalSessionAfterAccountDeletion(): Promise<boolean> {if (!isConfirmedAccountDeletionSessionCurrent()) return false;const expectedCredential = confirmedAccountDeletionCredential;+ const deletedPassportId = currentUser?.passportId ?? null;+ const deletedRealm = activeAuthRealm;+ if (deletedPassportId && !isPassiveSharedUserDataInstance()) {+ const vault = readAuthAccountVault();+ for (const [key, resource] of Object.entries(vault.resources)) {+ if (resource.realm === deletedRealm && resource.metadata.passportId === deletedPassportId) {+ delete vault.resources[key];+ if (vault.activeAccountKey === key) vault.activeAccountKey = null;+ }+ }+ delete vault.passports[passportVaultKey(deletedRealm, deletedPassportId)];+ writeAuthAccountVault(vault);+ }await withAccountFreeOwnerCommit({reason: 'account-deletion',nextMode: 'signed-out',@@ -2424,6 +2901,11 @@ export async function updateServerProfile(membershipDisplayName: membership.displayName,avatar: membership.avatarUrl ?? null,};+ rememberUpdatedMembershipMetadata(+ membership,+ activeAuthRealm,+ membership.passportId ?? currentUser.passportId,+ );notifyRenderer();notifyAuthListeners();return { ok: true, profile: { name: currentUser.name, avatar: currentUser.avatar } };@@ -2513,12 +2995,10 @@ export async function initialize(options: AuthInitializeOptions = {}): Promise<AcommitVolatileAppSession('signed-out');return snapshotLoggedOutAuthState();}- log.info(- 'relogin marker hit for v%s — clearing persisted auth',- reloginFlag.version,- );+ log.info('relogin marker hit for v%s — clearing persisted auth', reloginFlag.version);lastAcceptedRefreshToken = null;removeSafe(AUTH_SESSION_KEY);+ removeSafe(AUTH_ACCOUNT_VAULT_KEY);removeSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY);pendingAccountToken = null;removeSafe(LEGACY_ACCOUNT_REFRESH_TOKEN_KEY);@@ -2594,10 +3074,7 @@ export async function initialize(options: AuthInitializeOptions = {}): Promise<A// A signed-out fallback is not safe until the shared Ghost projection// has been swept. Otherwise the previous cloud owner's links remain// available to local/anonymous Agent processes during a slow refresh.- await recoverAccountFreeOwnerAtStartup(- 'signed-out',- 'cold-start-timeout-recovery',- );+ await recoverAccountFreeOwnerAtStartup('signed-out', 'cold-start-timeout-recovery');return snapshotLoggedOutAuthState();},onLateResult: (state) =>@@ -2719,6 +3196,7 @@ async function runColdStartRefreshFlow(// Refresh is token-rotating. Preserve the server-issued replacement before// the cross-process projection gate can reject or defer the owner commit.writePersistedAuthSession(refreshData.refreshToken, storedRealm);+ rememberResourceSession(refreshData, storedRealm, { markActive: true });lastAcceptedRefreshToken = refreshData.refreshToken;const previousSession = getActiveAppSession();await withCloudOwnerCommit({@@ -2802,6 +3280,8 @@ async function runColdStartRefreshFlow(async function loadLoginProviders(): Promise<AuthFlowState> {discoveredMethods = [];pendingAccountToken = null;+ pendingAccountRefreshToken = null;+ pendingAccountMemberships = [];pendingLoginTicket = null;pendingBindTicket = null;pendingSsoVerificationTicket = null;@@ -2873,6 +3353,20 @@ async function completeLogin(}const committedRealm = pendingAuthRealm ?? AUTH_REGION;+ const accountRefreshToken = outcome.accountRefreshToken ?? pendingAccountRefreshToken;+ // Resource and Account refresh endpoints rotate credentials. Persist the new+ // target session before tearing down the current owner so a later local+ // boundary failure cannot strand the newly authenticated account.+ rememberResourceSession(outcome, committedRealm, { markActive: true });+ if (accountRefreshToken && nextUser.passportId) {+ rememberPassportSession({+ realm: committedRealm,+ passportId: nextUser.passportId,+ accountRefreshToken,+ memberships:+ pendingAccountMemberships.length > 0 ? pendingAccountMemberships : [outcome.membership],+ });+ }await withCloudOwnerCommit({previousOwnerId: previousSession.dataOwnerId,nextOwnerId: nextUser.id,@@ -2904,6 +3398,8 @@ async function completeLogin(},commit: () => {pendingAccountToken = null;+ pendingAccountRefreshToken = null;+ pendingAccountMemberships = [];pendingAccountDeletionRestored = false;accessToken = outcome.accessToken;persistedRefreshTokenNeedsIdentityCheck = false;@@ -2963,6 +3459,16 @@ async function acceptLoginOutcome(outcome: LoginOutcome): Promise<AuthFlowState>pendingAccountDeletionRestored = true;}pendingAccountToken = outcome.status === 'select_account' ? (outcome.accountToken ?? null) : null;+ pendingAccountRefreshToken =+ outcome.status === 'ok' || outcome.status === 'select_account'+ ? (outcome.accountRefreshToken ?? null)+ : null;+ pendingAccountMemberships =+ outcome.status === 'select_account'+ ? outcome.accounts+ : outcome.status === 'ok'+ ? [outcome.membership]+ : [];if (outcome.status === 'ok') return completeLogin(outcome);if (outcome.status === 'select_account') {@@ -2990,7 +3496,7 @@ async function runLoginAction(action: DesktopLoginAction): Promise<DesktopLoginA(action.type === 'start-browser' && action.kind === 'social');if (startsBuildRealmFlow) pendingAuthRealm = null;const client = createAuthClient(- startsBuildRealmFlow ? AUTH_REGION : pendingAuthRealm ?? activeAuthRealm,+ startsBuildRealmFlow ? AUTH_REGION : (pendingAuthRealm ?? activeAuthRealm),);const stateBeforeAction = loginFlowState?.step === 'error' ? null : loginFlowState;try {@@ -3459,16 +3965,14 @@ export async function refresh(): Promise<boolean> {});} else {resetActiveAuthRealmToBuild();- await recoverAccountFreeOwnerAtStartup(- 'signed-out',- 'runtime-incompatible-membership',- );+ await recoverAccountFreeOwnerAtStartup('signed-out', 'runtime-incompatible-membership');}return false;}// Refresh is token-rotating. Preserve the replacement before any owner// projection transition can defer this process.writePersistedAuthSession(data.refreshToken, refreshRealm);+ rememberResourceSession(data, refreshRealm, { markActive: true });lastAcceptedRefreshToken = data.refreshToken;const needsIdentityCheck =replacementRetries > 0 ||@@ -3601,9 +4105,50 @@ export async function refresh(): Promise<boolean> {}}+function revokeSavedSessionsBestEffort(+ vault: AuthAccountVault,+ currentAccountKey: string | null,+): void {+ void (async () => {+ for (const [key, session] of Object.entries(vault.resources)) {+ if (key === currentAccountKey) continue;+ try {+ await loadClientEndpointsForRealm(session.realm);+ const client = createAuthClient(session.realm);+ const pair = await client.refresh(session.refreshToken);+ await client.logout(pair.accessToken);+ } catch {+ // Logout is local-first. Offline/expired remote sessions age out normally.+ }+ }+ for (const session of Object.values(vault.passports)) {+ try {+ await loadClientEndpointsForRealm(session.realm);+ const client = createAuthClient(session.realm);+ const pair = await client.refreshAccount(session.accountRefreshToken);+ await client.logoutAccount(pair.accountToken);+ } catch {+ // Best effort for the same reason as resource logout above.+ }+ }+ })();+}+export async function logout(): Promise<void> {+ if (isPassiveSharedUserDataInstance()) {+ throw new AuthApiError(+ 'PASSIVE_AUTH_MUTATION_BLOCKED',+ 409,+ 'This shared-data instance cannot log out all accounts',+ );+ }const currentAccessToken = accessToken;const currentAuthBaseUrl = authServerUrl(activeAuthRealm);+ const savedVault = readAuthAccountVault();+ const currentAccountKey = currentUser+ ? accountVaultKey(activeAuthRealm, currentUser.id)+ : savedVault.activeAccountKey;+ removeSafe(AUTH_ACCOUNT_VAULT_KEY);// The shared projection state machine owns the full teardown and only then// publishes the signed-out owner. The bootstrap IPC handler must not wrap a// second independent boundary around this transition.@@ -3641,6 +4186,7 @@ export async function logout(): Promise<void> {baseUrl: currentAuthBaseUrl,}).catch(() => {});}+ revokeSavedSessionsBestEffort(savedVault, currentAccountKey);if (localTransitionError) throw localTransitionError;}diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex b61b829e86..455ccdd7e9 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -5280,6 +5280,31 @@ const registerIpcHandlers = () => {await authManager.logout();});+ ipcMain.handle('auth:accounts:list', (event) => {+ assertTrustedAppRendererEvent(event);+ return authManager.listSavedAccounts();+ });++ ipcMain.handle('auth:accounts:sync', async (event) => {+ assertTrustedAppRendererEvent(event);+ return authManager.syncSavedAccounts();+ });++ ipcMain.handle('auth:accounts:switch', async (event, accountKey: unknown) => {+ assertTrustedAppRendererEvent(event);+ await authManager.switchSavedAccount(accountKey);+ });++ ipcMain.handle('auth:accounts:begin-add', async (event) => {+ assertTrustedAppRendererEvent(event);+ return authManager.beginAddAccountLogin();+ });++ ipcMain.handle('auth:accounts:cancel-add', (event) => {+ assertTrustedAppRendererEvent(event);+ authManager.cancelAddAccountLogin();+ });+ipcMain.handle('auth:enter-local', async () => {if (getActiveAppSession().mode === 'local') {return authManager.getAuthState();diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex b1ef6c8791..52a47e1e9a 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -193,6 +193,7 @@ import type {DesktopAccountDeletionConfirmInput,DesktopAccountDeletionConfirmResult,DesktopAccountDeletionStatusResult,+ DesktopAccountSwitcherSnapshot,DesktopLoginAction,DesktopLoginActionResult,} from '../shared/authIpc';@@ -1868,6 +1869,15 @@ contextBridge.exposeInMainWorld('electronAPI', {authGetCaptchaChallengeUrl: (): Promise<string> =>ipcRenderer.invoke('auth:get-captcha-challenge-url'),authLogout: (): Promise<void> => ipcRenderer.invoke('auth:logout'),+ authListAccounts: (): Promise<DesktopAccountSwitcherSnapshot> =>+ ipcRenderer.invoke('auth:accounts:list'),+ authSyncAccounts: (): Promise<DesktopAccountSwitcherSnapshot> =>+ ipcRenderer.invoke('auth:accounts:sync'),+ authSwitchAccount: (accountKey: string): Promise<void> =>+ ipcRenderer.invoke('auth:accounts:switch', accountKey),+ authBeginAddAccount: (): Promise<DesktopLoginActionResult> =>+ ipcRenderer.invoke('auth:accounts:begin-add'),+ authCancelAddAccount: (): Promise<void> => ipcRenderer.invoke('auth:accounts:cancel-add'),authEnterLocal: () => ipcRenderer.invoke('auth:enter-local'),authExitLocal: () => ipcRenderer.invoke('auth:exit-local'),authRefresh: (): Promise<boolean> => ipcRenderer.invoke('auth:refresh'),diff --git a/apps/desktop/src/renderer/__tests__/iconButtonTooltips.test.ts b/apps/desktop/src/renderer/__tests__/iconButtonTooltips.test.tsindex 9b47774ff0..2e6c75ab69 100644--- a/apps/desktop/src/renderer/__tests__/iconButtonTooltips.test.ts+++ b/apps/desktop/src/renderer/__tests__/iconButtonTooltips.test.ts@@ -312,7 +312,7 @@ describe('icon-only button tooltip coverage', () => {const source = rendererSource('components/sidebar/UserInfoSection.tsx');expect(source).toContain("import { Tip } from '@/components/ui/tooltip';");- expect(source).toContain('<Tip text={settingsLinkLabel} side="right">');+ expect(source).toContain('<Tip text={moreLabel} side="right">');expect(source).toContain("text={t('sidebar.user.downloadMobile')}");expect(source).toMatch(/text=\{\s*isFlameReopen\s*\? t\('sidebar\.user\.reopenUpdateBanner'\)\s*: t\('sidebar\.user\.viewReleaseNotes'\)\s*\}/,diff --git a/apps/desktop/src/renderer/__tests__/userInfoSectionHover.test.ts b/apps/desktop/src/renderer/__tests__/userInfoSectionHover.test.tsindex 559ce8c72d..de5b673e11 100644--- a/apps/desktop/src/renderer/__tests__/userInfoSectionHover.test.ts+++ b/apps/desktop/src/renderer/__tests__/userInfoSectionHover.test.ts@@ -26,6 +26,7 @@ const locale = JSON.parse(readFileSync(localePath, 'utf8')) as {user: {settingsLink: string;settingsLinkBeta: string;+ moreLabel: string;canaryBadge: string;downloadMobile: string;};@@ -101,9 +102,9 @@ describe('UserInfoSection — version label', () => {describe('UserInfoSection — Canary avatar badge', () => {it('shows only the shield decoration when isCanary is true', () => {expect(source).toContain(- "import { Flame, Shield, Smartphone, UserRound } from 'lucide-react';",+ "import { Flame, LogOut, Settings, Shield, Smartphone, UserPlus, UserRound } from 'lucide-react';",);- expect(source).toContain('const { user, mode, isCanary } = useAuth();');+ expect(source).toContain('const { user, mode, isCanary, beginAddAccount } = useAuth();');expect(source).toContain('{isCanary && (');expect(source).toContain("aria-label={t('sidebar.user.canaryBadge')}");expect(source).not.toContain("isCanary && 'ring-[1.5px] ring-foreground'");@@ -149,7 +150,7 @@ describe('UserInfoSection — 未登录态头像兜底', () => {describe('UserInfoSection — mobile download entry', () => {it('uses the local Lucide Smartphone icon in a matching 22x22 capsule action', () => {expect(source).toContain(- "import { Flame, Shield, Smartphone, UserRound } from 'lucide-react';",+ "import { Flame, LogOut, Settings, Shield, Smartphone, UserPlus, UserRound } from 'lucide-react';",);expect(source).toMatch(/'mobile-download-btn',\s*\n\s*'flex h-\[22px\] w-\[22px\]/);expect(source).toContain("!isCollapsed && 'mr-1'");@@ -201,24 +202,22 @@ describe('UserInfoSection — inner main button no longer owns hover background'expect(source).toMatch(/'text-left'/);});- it('main button preserves onClick / role="link" / aria-label (跳转和无障碍不破)', () => {- expect(source).toContain('onClick={handleClick}');- expect(source).toContain('role="link"');+ it('main button opens the accessible More menu instead of navigating directly', () => {+ expect(source).not.toContain('onClick={handleClick}');+ expect(source).not.toContain('role="link"');expect(source).toContain(- "const settingsLinkLabel = t('sidebar.user.settingsLink', { name: displayName });",+ "const moreLabel = t('sidebar.user.moreLabel', { name: displayName });",);- expect(source).toContain('aria-label={settingsLinkLabel}');- expect(locale.sidebar.user.settingsLink).toBe('设置,当前用户:{{name}}');+ expect(source).toContain('aria-label={moreLabel}');+ expect(source).toContain('<DropdownMenuTrigger asChild>');+ expect(locale.sidebar.user.moreLabel).toBe('更多,当前用户:{{name}}');});- it('announces the enabled Beta channel from the expanded settings link', () => {- expect(source).toContain(- "? t('sidebar.user.settingsLinkBeta', { name: displayName })",- );- expect(source).toContain('aria-label={settingsLinkAriaLabel}');- expect(locale.sidebar.user.settingsLinkBeta).toBe(- '设置,当前用户:{{name}},Beta 测试渠道已开启',- );+ it('offers settings, account switching, and logout from the More menu', () => {+ expect(source).toContain("t('sidebar.user.menuSettings')");+ expect(source).toContain("t('sidebar.user.menuAddAccount')");+ expect(source).toContain("t('sidebar.user.menuLogout')");+ expect(source).toContain('setAccountSwitcherOpen(true)');});});diff --git a/apps/desktop/src/renderer/__tests__/userInfoSectionMobileDownload.test.tsx b/apps/desktop/src/renderer/__tests__/userInfoSectionMobileDownload.test.tsxindex 3d16bf6ce1..1922eaa52a 100644--- a/apps/desktop/src/renderer/__tests__/userInfoSectionMobileDownload.test.tsx+++ b/apps/desktop/src/renderer/__tests__/userInfoSectionMobileDownload.test.tsx@@ -39,6 +39,10 @@ vi.mock('@/hooks/useBetaChannelSettings', () => ({useBetaChannelSettings: () => ({ state: betaChannelState }),}));+vi.mock('@/hooks/useLogout', () => ({+ useLogout: () => ({ handleLogout: vi.fn() }),+}));+vi.mock('@/components/sidebar/MobileDownloadDialog', () => ({MobileDownloadDialog: ({open,@@ -89,9 +93,7 @@ describe('UserInfoSection mobile download entry', () => {expect(screen.getByTestId('sidebar-beta-channel-badge').textContent).toBe('settings.betaChannel.badge',);- expect(- screen.getByRole('link', { name: 'sidebar.user.settingsLinkBeta' }),- ).toBeTruthy();+ expect(screen.getByRole('button', { name: 'sidebar.user.moreLabel' })).toBeTruthy();});it.each([diff --git a/apps/desktop/src/renderer/components/login/AddAccountLoginPage.tsx b/apps/desktop/src/renderer/components/login/AddAccountLoginPage.tsxnew file mode 100644index 0000000000..3ea6ea3743--- /dev/null+++ b/apps/desktop/src/renderer/components/login/AddAccountLoginPage.tsx@@ -0,0 +1,56 @@+import { useEffect, useRef } from 'react';+import { useTranslation } from 'react-i18next';+import { useLocation, useNavigate } from 'react-router-dom';++import { useAppShellCover } from '@/contexts/AppShellCoverContext';+import { useAuth } from '@/contexts/AuthContext';+import { toast } from '@/lib/toast';+import { LoginPage } from './LoginPage';++interface AddAccountLocationState {+ returnTo?: string;+}++export function AddAccountLoginPage() {+ const { loginState, beginAddAccount, cancelAddAccount } = useAuth();+ const { reportLocalDbGate } = useAppShellCover();+ const navigate = useNavigate();+ const location = useLocation();+ const { t } = useTranslation();+ const initializedRef = useRef(false);+ const returnTo = (location.state as AddAccountLocationState | null)?.returnTo ?? '/cc-agent';++ useEffect(() => {+ // This protected route intentionally sits outside LocalDbGate: adding another account must+ // remain available even if the current account's database cannot open. After a renderer+ // reload/HMR, AppShellCoverProvider starts at `pending`; without an explicit bypass no gate is+ // mounted to release the startup cover, leaving this page behind “Waking Cindy…” forever.+ // Passive effect ordering matters here: LocalDbGate's unmount cleanup runs before this mount+ // effect, so `ready` wins when navigating from the main app into this route.+ reportLocalDbGate('ready');+ return () => reportLocalDbGate('pending');+ }, [reportLocalDbGate]);++ useEffect(() => {+ if (loginState || initializedRef.current) return;+ initializedRef.current = true;+ void beginAddAccount().catch(() => {+ toast.error(t('sidebar.accountSwitcher.startFailed'));+ navigate(returnTo, { replace: true });+ });+ }, [beginAddAccount, loginState, navigate, returnTo, t]);++ useEffect(() => {+ if (loginState?.step === 'completed') navigate(returnTo, { replace: true });+ }, [loginState?.step, navigate, returnTo]);++ const cancel = async () => {+ try {+ await cancelAddAccount();+ } finally {+ navigate(returnTo, { replace: true });+ }+ };++ return <LoginPage intent="add-account" onClose={() => void cancel()} />;+}diff --git a/apps/desktop/src/renderer/components/login/LoginPage.tsx b/apps/desktop/src/renderer/components/login/LoginPage.tsxindex ab4261f262..dd2f225219 100644--- a/apps/desktop/src/renderer/components/login/LoginPage.tsx+++ b/apps/desktop/src/renderer/components/login/LoginPage.tsx@@ -10,6 +10,7 @@ import {type ReactNode,} from 'react';import { useTranslation } from 'react-i18next';+import { X } from 'lucide-react';import type {AccountDeletionStatus,CaptchaConfig,@@ -22,6 +23,7 @@ import { cn } from '@/lib/utils';import { createLogger } from '@/lib/logger';import { setLoginEmailCaptchaGate } from '@/lib/loginCaptchaGate';import { WindowControls } from '@/components/title-bar/WindowControls';+import { ChromeIconButton } from '@/components/title-bar/ChromeIconButton';import { useLogin } from '@/hooks/useLogin';import { endLoginFirstLaunchLightGate, loginFirstLaunchLightActive } from '@/hooks/useTheme';import { LOGIN_HANDOFF_TIMINGS, useLoginHandoff } from '@/contexts/LoginHandoffContext';@@ -112,7 +114,13 @@ const log = createLogger('LoginPage');* 协议同意链路(radio + 拦截弹窗)与面板内「跳过登录」入口。倒计时契约、* Text_link 全态、错误码映射均已落地(历史施工批次见 git log,不再在注释中引用)。*/-export function LoginPage() {+export function LoginPage({+ intent = 'sign-in',+ onClose,+}: {+ intent?: 'sign-in' | 'add-account';+ onClose?: () => void;+}) {const {isLoading,errorCode,@@ -127,6 +135,7 @@ export function LoginPage() {} = useLogin();const { t } = useTranslation();const handoff = useLoginHandoff();+ const isAddAccount = intent === 'add-account';// 主题跟随(DESIGN.md §16.5):首次打开 Cindy → 亮色登录界面(默认);第二次起// → 跟随用户上一次使用的主题。首启亮色门在 bootstrap 已生效(品牌舞台首帧即@@ -306,7 +315,7 @@ export function LoginPage() {}, [reportLoginPanelMounted, reportLoginPanelUnmounted]);// 「跳过登录」常驻入口在面板内(identifier 视图 SKIP_ENTRY 文字链);footer 仅保留// error 步的逃生入口——登录服务不可用时用户仍能进入本地模式(既有产品保证)。- const showLocalModeFooter = loginState?.step === 'error';+ const showLocalModeFooter = !isAddAccount && loginState?.step === 'error';// 面板底部预留恒取全流程最大值(footer 124;协议行 48 被其覆盖):step 切换时// 面板/品牌层零跳位(规则 7,codex 审查 P1)。browser-redirect/completed 维持 0,// 与迁移前 main 口径一致(该两步由品牌 overlay/跳转态接管)。@@ -363,7 +372,12 @@ export function LoginPage() {);useEffect(() => {- if (!hasAccountDeletionReceipt || !getAccountDeletionStatus || !clearAccountDeletionReceipt) {+ if (+ isAddAccount ||+ !hasAccountDeletionReceipt ||+ !getAccountDeletionStatus ||+ !clearAccountDeletionReceipt+ ) {setAccountDeletionStatus(null);return;}@@ -415,7 +429,12 @@ export function LoginPage() {disposed = true;if (timer) clearTimeout(timer);};- }, [clearAccountDeletionReceipt, getAccountDeletionStatus, hasAccountDeletionReceipt]);+ }, [+ clearAccountDeletionReceipt,+ getAccountDeletionStatus,+ hasAccountDeletionReceipt,+ isAddAccount,+ ]);useEffect(() => {if (loginState?.step !== 'identifier') return;@@ -715,15 +734,17 @@ export function LoginPage() {圆钮;LoginSkipEntry ≠ LoginTextLink,见该组件注释):接既有 local mode链路,过协议门(2026-07-29 拍板)。槽位在 error_text(380..430)之下、与其首尾相接,两者同时可见互不重叠;error 出现不推移本入口(均 absolute)。 */}- <LoginSkipEntry- testId="login-skip-entry"- disabled={isLoading || localModePending}- onClick={() =>- requireConsent(() => void openLocalMode(), { deferConsentPersist: true })- }- >- {t('login.localModeEntry')}- </LoginSkipEntry>+ {!isAddAccount ? (+ <LoginSkipEntry+ testId="login-skip-entry"+ disabled={isLoading || localModePending}+ onClick={() =>+ requireConsent(() => void openLocalMode(), { deferConsentPersist: true })+ }+ >+ {t('login.localModeEntry')}+ </LoginSkipEntry>+ ) : null}</LoginPanel><LoginSocialRow count={providers.social.length + 1}>{providers.social.map((provider) => (@@ -1301,7 +1322,7 @@ export function LoginPage() {不推挤下方内容,z-30 盖过 stage 全部内容(低于拖拽条 z-40 与协议弹窗 z-50);窗口顶 72px 恒定、水平窗口居中、宽 670 恒定,均不随 loginScale 缩放。显隐与面板入场同节奏(只淡入,不参与位移)。 */}- {accountDeletionStatus && (+ {!isAddAccount && accountDeletionStatus && (<AccountDeletionStatusPanelstatus={accountDeletionStatus}onDismiss={@@ -1329,11 +1350,26 @@ export function LoginPage() {className="absolute left-0 top-0 z-40 flex w-full items-center justify-end"style={{ height: DRAG_BAR_HEIGHT, WebkitAppRegion: 'drag' } as React.CSSProperties}>- {!isMac && (- <div style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}>- <WindowControls />+ {(isAddAccount && onClose) || !isMac ? (+ <div+ className="flex h-full items-center"+ style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}+ >+ {isAddAccount && onClose ? (+ <ChromeIconButton+ data-testid="add-account-close"+ className={isMac ? 'mr-2' : 'mr-1'}+ aria-label={t('sidebar.accountSwitcher.close')}+ tooltip={t('sidebar.accountSwitcher.close')}+ tooltipSide="bottom"+ onClick={onClose}+ >+ <X size={14} aria-hidden="true" />+ </ChromeIconButton>+ ) : null}+ {!isMac ? <WindowControls /> : null}</div>- )}+ ) : null}</div>{/* 服务条款和隐私协议确认弹窗(figma 602:822/602:1249):个人登录链路在radio 未勾选时统一拦截;同意=勾选并续接,不同意=留在登录页。diff --git a/apps/desktop/src/renderer/components/login/__tests__/AddAccountLoginPage.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/AddAccountLoginPage.test.tsxnew file mode 100644index 0000000000..bed8a3d55d--- /dev/null+++ b/apps/desktop/src/renderer/components/login/__tests__/AddAccountLoginPage.test.tsx@@ -0,0 +1,91 @@+// @vitest-environment jsdom++import { useState } from 'react';+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { MemoryRouter } from 'react-router-dom';++const auth = vi.hoisted(() => ({+ isInitializing: false,+ canEnterApp: true,+ loginState: { step: 'identifier' },+ beginAddAccount: vi.fn(),+ cancelAddAccount: vi.fn(),+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock('@/contexts/AuthContext', () => ({+ useAuth: () => auth,+}));++vi.mock('@/lib/secondaryWindow', () => ({+ isSecondaryWindow: () => false,+}));+vi.mock('@/lib/sidebarWindow', () => ({+ isSidebarWindow: () => false,+}));+vi.mock('@/lib/ghostPanelWindow', () => ({+ isGhostPanelWindow: () => false,+}));++vi.mock('../LoginPage', () => ({+ LoginPage: ({ onClose }: { onClose?: () => void }) => (+ <button type="button" onClick={onClose}>+ close add-account login+ </button>+ ),+}));++import { AppShellCoverProvider, useAppShellCover } from '@/contexts/AppShellCoverContext';+import { AddAccountLoginPage } from '../AddAccountLoginPage';++function CoverProbe() {+ const { coverHeld, localDbGateStatus } = useAppShellCover();+ return (+ <output data-testid="cover-state">+ {coverHeld ? 'held' : 'open'}:{localDbGateStatus}+ </output>+ );+}++function Harness() {+ const [showAddAccount, setShowAddAccount] = useState(true);+ return (+ <AppShellCoverProvider>+ <MemoryRouter initialEntries={['/add-account']}>+ {showAddAccount ? <AddAccountLoginPage /> : null}+ <CoverProbe />+ <button type="button" onClick={() => setShowAddAccount(false)}>+ leave route+ </button>+ </MemoryRouter>+ </AppShellCoverProvider>+ );+}++afterEach(() => {+ cleanup();+ auth.beginAddAccount.mockReset();+ auth.cancelAddAccount.mockReset();+});++describe('AddAccountLoginPage app-shell cover', () => {+ it('releases a freshly reset cover and restores pending status when leaving', () => {+ render(<Harness />);++ expect(screen.getByTestId('cover-state').textContent).toBe('open:ready');++ fireEvent.click(screen.getByRole('button', { name: 'leave route' }));+ expect(screen.getByTestId('cover-state').textContent).toBe('held:pending');+ });++ it('cancels the add-account flow from the close action', async () => {+ render(<Harness />);++ fireEvent.click(screen.getByRole('button', { name: 'close add-account login' }));+ await waitFor(() => expect(auth.cancelAddAccount).toHaveBeenCalledOnce());+ });+});diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.harness.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.harness.test.tsxindex 3cecfa3180..d11eee8028 100644--- a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.harness.test.tsx+++ b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.harness.test.tsx@@ -93,7 +93,12 @@ async function realmConfirmationState(targetRegion: 'cn' | 'global') {});}-function mount(state: AuthFlowState | null, extra?: Partial<typeof loginHook.value>) {+function mount(+ state: AuthFlowState | null,+ extra?: Partial<typeof loginHook.value>,+ intent: 'sign-in' | 'add-account' = 'sign-in',+ onClose?: () => void,+) {loginHook.value = {isLoading: false,errorCode: null,@@ -109,7 +114,7 @@ function mount(state: AuthFlowState | null, extra?: Partial<typeof loginHook.valreturn render(<><LoginBrandStage />- <LoginPage />+ <LoginPage intent={intent} onClose={onClose} /></>,);}@@ -223,6 +228,32 @@ describe('identifier 态(附录 A providers 场景)', () => {expect(screen.queryByTestId('login-local-mode')).toBeNull();});+ it('登录更多账号流程不提供跳过登录入口', async () => {+ mount(await identifierState('providers:both'), undefined, 'add-account');+ expect(screen.queryByTestId('login-skip-entry')).toBeNull();+ expect(screen.queryByTestId('login-local-mode')).toBeNull();+ });++ it.each([+ ['darwin', 'mr-2'],+ ['win32', 'mr-1'],+ ] as const)('登录更多账号在 %s 标题栏右侧提供关闭按钮', async (platform, marginClass) => {+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: { platform, acceptPrivacyConsent: async () => ({ allowed: true }) },+ });+ const onClose = vi.fn();+ mount(await identifierState('providers:both'), undefined, 'add-account', onClose);++ const dragBar = screen.getByTestId('login-drag-bar');+ const close = screen.getByTestId('add-account-close');+ expect(dragBar.contains(close)).toBe(true);+ expect(close.className).toContain(marginClass);++ fireEvent.click(close);+ expect(onClose).toHaveBeenCalledOnce();+ });+it('「跳过登录」槽与错误提示槽首尾相接且不重叠(error 出现不推移跳过入口)', async () => {mount(await identifierState('providers:both'), { errorCode: 'NETWORK_ERROR' });const error = screen.getByTestId('login-error-text');@@ -392,20 +423,14 @@ describe('ssoOrgMode 子视图', () => {const historyList = screen.getByTestId('login-sso-org-history-list');const panel = screen.getByTestId('login-panel-sso-org');expect(panel.contains(historyList)).toBe(false);- expect(Number.parseFloat(historyList.style.left)).toBe(- Number.parseFloat(input.style.left),- );- expect(Number.parseFloat(historyList.style.width)).toBe(- Number.parseFloat(input.style.width),- );+ expect(Number.parseFloat(historyList.style.left)).toBe(Number.parseFloat(input.style.left));+ expect(Number.parseFloat(historyList.style.width)).toBe(Number.parseFloat(input.style.width));expect(Number.parseFloat(historyList.style.top)).toBe(Number.parseFloat(input.style.top) + Number.parseFloat(input.style.height) + 8,);expect(Number.parseFloat(historyList.style.top) + Number.parseFloat(historyList.style.maxHeight),- ).toBeLessThanOrEqual(- Number.parseFloat(panel.style.height),- );+ ).toBeLessThanOrEqual(Number.parseFloat(panel.style.height));expect(historyList.className).toContain('overflow-y-auto');expect(historyList.className).toContain('[scrollbar-width:none]');expect(historyList.className).toContain('[&::-webkit-scrollbar]:hidden');@@ -433,9 +458,7 @@ describe('ssoOrgMode 子视图', () => {fireEvent.click(screen.getByTestId('login-sso-org-continue'));await waitFor(() => {fireEvent.focus(screen.getByTestId('login-sso-org-input'));- expect(screen.getByTestId('login-sso-org-history-option-0').textContent).toBe(- 'Example-Corp',- );+ expect(screen.getByTestId('login-sso-org-history-option-0').textContent).toBe('Example-Corp');});});diff --git a/apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx b/apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsxnew file mode 100644index 0000000000..61b4989be6--- /dev/null+++ b/apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx@@ -0,0 +1,250 @@+import * as Dialog from '@radix-ui/react-dialog';+import { useEffect, useRef, useState, type CSSProperties, type RefObject } from 'react';+import { Building2, Check, Plus, UserRound, X } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { Spinner } from '@/components/ui/spinner';+import { useOptionalConfirmDialog } from '@/components/ui/confirm-dialog-provider';+import { Tip } from '@/components/ui/tooltip';+import { useAuth } from '@/contexts/AuthContext';+import type { DesktopSavedAccount } from '@/lib/authService';+import { toast } from '@/lib/toast';+import { cn } from '@/lib/utils';++interface AccountSwitcherDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onAddAccount: () => void;+ triggerRef: RefObject<HTMLButtonElement | null>;+}++function AccountAvatar({ account }: { account: DesktopSavedAccount }) {+ const [imageFailed, setImageFailed] = useState(false);+ const imageUrl = account.kind === 'org' ? account.orgLogoUrl : account.avatarUrl;++ useEffect(() => setImageFailed(false), [imageUrl]);++ if (imageUrl && !imageFailed) {+ return (+ <img+ src={imageUrl}+ alt=""+ className="h-10 w-10 shrink-0 rounded-full object-cover"+ onError={() => setImageFailed(true)}+ />+ );+ }++ return (+ <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full border border-[var(--border-default)] bg-[var(--surface-hover)] text-[var(--text-secondary)]">+ {account.kind === 'org' ? (+ <Building2 className="h-5 w-5" aria-hidden="true" />+ ) : (+ <UserRound className="h-5 w-5" aria-hidden="true" />+ )}+ </span>+ );+}++export function AccountSwitcherDialog({+ open,+ onOpenChange,+ onAddAccount,+ triggerRef,+}: AccountSwitcherDialogProps) {+ const { listAccounts, syncAccounts, switchAccount } = useAuth();+ const confirmDialog = useOptionalConfirmDialog();+ const { t } = useTranslation();+ const [accounts, setAccounts] = useState<DesktopSavedAccount[]>([]);+ const [mutationAllowed, setMutationAllowed] = useState(true);+ const [syncing, setSyncing] = useState(false);+ const [switchingKey, setSwitchingKey] = useState<string | null>(null);+ const contentRef = useRef<HTMLDivElement>(null);++ useEffect(() => {+ if (!open) return;+ let active = true;+ setSyncing(true);++ void listAccounts()+ .then((snapshot) => {+ if (!active) return;+ setAccounts(snapshot.accounts);+ setMutationAllowed(snapshot.mutationAllowed);+ })+ .then(() => syncAccounts())+ .then((snapshot) => {+ if (!active) return;+ setAccounts(snapshot.accounts);+ setMutationAllowed(snapshot.mutationAllowed);+ })+ .catch(() => {+ if (active) toast.error(t('sidebar.accountSwitcher.syncFailed'));+ })+ .finally(() => {+ if (active) setSyncing(false);+ });++ return () => {+ active = false;+ };+ }, [listAccounts, open, syncAccounts, t]);++ const handleSwitch = async (account: DesktopSavedAccount) => {+ if (account.isCurrent || switchingKey || !mutationAllowed) return;+ setSwitchingKey(account.accountKey);++ try {+ // Lazy-load the task store only when the user requests a switch. The account+ // dialog is mounted with the sidebar shell, while the chat runtime is not.+ const { makerChatStore } = await import('@/lib/makerChatStore');+ const hasRunningTask = [...makerChatStore.getRunningSnapshot().values()].some(+ (status) => status.isRunning,+ );+ if (hasRunningTask) {+ // Full app windows always provide the shared confirmation host. Standalone+ // story/test mounts fail closed instead of switching without consent.+ if (!confirmDialog) {+ setSwitchingKey(null);+ return;+ }+ const confirmed = await confirmDialog.confirm({+ title: t('sidebar.accountSwitcher.runningTaskTitle'),+ description: t('sidebar.accountSwitcher.runningTaskDescription'),+ confirmText: t('sidebar.accountSwitcher.runningTaskConfirm'),+ cancelText: t('logic.confirm.cancel'),+ confirmVariant: 'destructive',+ });+ if (!confirmed) {+ setSwitchingKey(null);+ return;+ }+ }++ // Main owns the account boundary: it stops and drains the outgoing runtime+ // before committing the selected account, so this await is also the stop barrier.+ await switchAccount(account.accountKey);+ onOpenChange(false);+ } catch {+ toast.error(t('sidebar.accountSwitcher.switchFailed'));+ setSwitchingKey(null);+ }+ };++ return (+ <Dialog.Root open={open} onOpenChange={onOpenChange}>+ <Dialog.Portal>+ <Dialog.Overlay+ className="fixed inset-0 z-[10000] bg-[var(--overlay-modal)] data-[state=open]:animate-confirm-overlay-in data-[state=closed]:animate-confirm-overlay-out"+ style={{ WebkitAppRegion: 'no-drag' } as CSSProperties}+ />+ <Dialog.Content+ ref={contentRef}+ tabIndex={-1}+ className={cn(+ 'fixed left-1/2 top-1/2 z-[10000] w-[420px] max-w-[calc(100vw-32px)] -translate-x-1/2 -translate-y-1/2',+ 'select-none rounded-xl bg-[var(--confirm-bg)] p-5 shadow-[var(--confirm-shadow)]',+ 'data-[state=open]:animate-confirm-content-in data-[state=closed]:animate-confirm-content-out',+ )}+ style={{ WebkitAppRegion: 'no-drag' } as CSSProperties}+ onOpenAutoFocus={(event) => {+ event.preventDefault();+ contentRef.current?.focus();+ }}+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ triggerRef.current?.focus();+ }}+ >+ <Dialog.Title className="pr-10 text-18 font-medium text-[var(--confirm-title)]">+ {t('sidebar.accountSwitcher.title')}+ </Dialog.Title>+ <Dialog.Description className="mt-1 pr-10 text-13 text-[var(--confirm-desc)]">+ {t('sidebar.accountSwitcher.description')}+ </Dialog.Description>+ <Dialog.Close asChild>+ <Tip+ text={t('sidebar.accountSwitcher.close')}+ side="bottom"+ contentClassName="z-[10001]"+ >+ <button+ type="button"+ aria-label={t('sidebar.accountSwitcher.close')}+ className="absolute right-3 top-3 flex h-8 w-8 items-center justify-center rounded-full text-[var(--confirm-desc)] transition-colors hover:bg-[var(--surface-hover)] hover:text-[var(--confirm-title)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"+ >+ <X className="h-4 w-4" aria-hidden="true" />+ </button>+ </Tip>+ </Dialog.Close>++ <div className="mt-4 max-h-[360px] space-y-1 overflow-y-auto" aria-live="polite">+ {accounts.map((account) => {+ const switching = switchingKey === account.accountKey;+ const hasDistinctOrgName =+ account.kind === 'org' &&+ Boolean(account.orgName?.trim()) &&+ account.orgName !== account.displayName;+ const primaryLabel = hasDistinctOrgName ? account.orgName : account.displayName;+ const secondaryLabel =+ account.kind === 'org' && hasDistinctOrgName ? account.displayName : account.email;+ return (+ <button+ key={account.accountKey}+ type="button"+ disabled={+ account.isCurrent || syncing || switchingKey !== null || !mutationAllowed+ }+ onClick={() => void handleSwitch(account)}+ className={cn(+ 'flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left transition-colors',+ 'hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',+ 'disabled:cursor-default disabled:opacity-100',+ )}+ >+ <AccountAvatar account={account} />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-14 font-medium text-[var(--text-primary)]">+ {primaryLabel}+ </span>+ {secondaryLabel ? (+ <span className="mt-0.5 block truncate text-12 text-[var(--text-secondary)]">+ {secondaryLabel}+ </span>+ ) : null}+ </span>+ {switching ? (+ <Spinner size={16} className="text-[var(--text-secondary)]" />+ ) : account.isCurrent ? (+ <Check+ className="h-4 w-4 shrink-0 text-[var(--text-primary)]"+ aria-hidden="true"+ />+ ) : null}+ </button>+ );+ })}+ {syncing ? (+ <div className="flex items-center justify-center gap-2 py-3 text-12 text-[var(--text-secondary)]">+ <Spinner size={14} />+ {t('sidebar.accountSwitcher.syncing')}+ </div>+ ) : null}+ </div>++ <div className="mt-4 border-t border-[var(--border-default)] pt-4">+ <button+ type="button"+ disabled={!mutationAllowed || syncing || switchingKey !== null}+ onClick={onAddAccount}+ className="flex w-full items-center justify-center gap-2 rounded-lg border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-2.5 text-14 font-medium text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:cursor-not-allowed disabled:opacity-60"+ >+ <Plus className="h-4 w-4" aria-hidden="true" />+ {t('sidebar.accountSwitcher.addAccount')}+ </button>+ </div>+ </Dialog.Content>+ </Dialog.Portal>+ </Dialog.Root>+ );+}diff --git a/apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx b/apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsxindex 6450d4bfe6..5a5fc8ba8e 100644--- a/apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx+++ b/apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx@@ -1,7 +1,7 @@-import { useEffect, useRef, useState } from 'react';+import { useEffect, useRef, useState, type ReactNode } from 'react';import { useNavigate, useLocation } from 'react-router-dom';import { useTranslation } from 'react-i18next';-import { Flame, Shield, Smartphone, UserRound } from 'lucide-react';+import { Flame, LogOut, Settings, Shield, Smartphone, UserPlus, UserRound } from 'lucide-react';import { cn } from '@/lib/utils';import { useAuth } from '@/contexts/AuthContext';@@ -9,9 +9,18 @@ import { useUpdateStatus } from '@/hooks/useUpdateStatus';import { useUpdateBannerDismiss } from '@/hooks/useUpdateBannerDismiss';import { useBetaChannelSettings } from '@/hooks/useBetaChannelSettings';import { Tip } from '@/components/ui/tooltip';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import { useLogout } from '@/hooks/useLogout';import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';import { shouldLabelRegion } from '../../../shared/regionCode';import { MobileDownloadDialog } from './MobileDownloadDialog';+import { AccountSwitcherDialog } from './AccountSwitcherDialog';interface UserInfoSectionProps {isCollapsed: boolean;@@ -19,12 +28,15 @@ interface UserInfoSectionProps {}export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSectionProps) {- const { user, mode, isCanary } = useAuth();+ const { user, mode, isCanary, beginAddAccount } = useAuth();+ const { handleLogout } = useLogout();const navigate = useNavigate();const location = useLocation();const [avatarError, setAvatarError] = useState(false);const [mobileDownloadOpen, setMobileDownloadOpen] = useState(false);+ const [accountSwitcherOpen, setAccountSwitcherOpen] = useState(false);const mobileDownloadButtonRef = useRef<HTMLButtonElement>(null);+ const moreButtonRef = useRef<HTMLButtonElement>(null);const { t } = useTranslation();// 火焰按钮双职责:@@ -42,10 +54,7 @@ export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSec// 让新地址有机会渲染,而不是永远停在首字母兜底。const isLocal = mode === 'local';const displayName = user?.name ?? (isLocal ? t('settings.userProfile.local.name') : '');- const settingsLinkLabel = t('sidebar.user.settingsLink', { name: displayName });- const settingsLinkAriaLabel = showBetaBadge- ? t('sidebar.user.settingsLinkBeta', { name: displayName })- : settingsLinkLabel;+ const moreLabel = t('sidebar.user.moreLabel', { name: displayName });const avatarUrl = user?.avatar ?? null;useEffect(() => {setAvatarError(false);@@ -79,12 +88,47 @@ export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSec: appDisplayVersionDetail;const remoteAvailable = mode === 'cloud';- const handleClick = () => {- if (location.pathname !== '/settings') {- navigate('/settings');- }+ const openSettings = () => {+ if (location.pathname !== '/settings') navigate('/settings');};+ const openAddAccount = async () => {+ const result = await beginAddAccount();+ if (!result.success) return;+ setAccountSwitcherOpen(false);+ navigate('/add-account', {+ state: { returnTo: `${location.pathname}${location.search}` },+ });+ };++ const renderMoreMenu = (trigger: ReactNode) => (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>{trigger}</DropdownMenuTrigger>+ <DropdownMenuContent side="top" align="start" sideOffset={8} className="min-w-[190px]">+ <DropdownMenuItem onSelect={openSettings} className="gap-2.5">+ <Settings className="h-4 w-4" aria-hidden="true" />+ {t('sidebar.user.menuSettings')}+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={() => setAccountSwitcherOpen(true)} className="gap-2.5">+ <UserPlus className="h-4 w-4" aria-hidden="true" />+ {t('sidebar.user.menuAddAccount')}+ </DropdownMenuItem>+ {mode === 'cloud' ? (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onSelect={() => void handleLogout()}+ className="gap-2.5 text-[var(--error-fg-strong)] focus:text-[var(--error-fg-strong)]"+ >+ <LogOut className="h-4 w-4" aria-hidden="true" />+ {t('sidebar.user.menuLogout')}+ </DropdownMenuItem>+ </>+ ) : null}+ </DropdownMenuContent>+ </DropdownMenu>+ );+const openRemoteSettings = () => {setMobileDownloadOpen(false);navigate('/settings?tab=remote-control');@@ -120,11 +164,10 @@ export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSecreturn (<><div className="mt-auto flex h-[66px] flex-col items-center justify-center gap-1 px-3">- <Tip text={settingsLinkLabel} side="right">- <button- onClick={handleClick}- role="link"- aria-label={settingsLinkLabel}+ <Tip text={moreLabel} side="right">+ {renderMoreMenu(<button+ ref={moreButtonRef}+ aria-label={moreLabel}className="flex min-w-0 items-center justify-center text-left"><div className="relative h-9 w-9 shrink-0">@@ -162,7 +205,7 @@ export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSec</span>)}</div>- </button>+ </button>)}</Tip>{mobileDownloadEntry}</div>@@ -174,6 +217,12 @@ export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSeconOpenDevices={openLinkedDevices}triggerRef={mobileDownloadButtonRef}/>+ <AccountSwitcherDialog+ open={accountSwitcherOpen}+ onOpenChange={setAccountSwitcherOpen}+ onAddAccount={() => void openAddAccount()}+ triggerRef={moreButtonRef}+ /></>);}@@ -190,10 +239,9 @@ export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSec'has-[.mobile-download-btn:hover]:bg-[var(--sidebar-user-card-bg)]',)}>- <button- onClick={handleClick}- role="link"- aria-label={settingsLinkAriaLabel}+ {renderMoreMenu(<button+ ref={moreButtonRef}+ aria-label={moreLabel}className={cn('flex min-w-0 flex-1 items-center gap-[10px]', 'text-left')}>{/* Avatar — admin 用户加 1.5px 反色描边 + 右下角盾牌角标 */}@@ -266,7 +314,7 @@ export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSec) : null}</p></div>- </button>+ </button>)}{mobileDownloadEntry}@@ -326,6 +374,12 @@ export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSeconOpenDevices={openLinkedDevices}triggerRef={mobileDownloadButtonRef}/>+ <AccountSwitcherDialog+ open={accountSwitcherOpen}+ onOpenChange={setAccountSwitcherOpen}+ onAddAccount={() => void openAddAccount()}+ triggerRef={moreButtonRef}+ /></div>);}diff --git a/apps/desktop/src/renderer/components/sidebar/__tests__/AccountSwitcherDialog.test.tsx b/apps/desktop/src/renderer/components/sidebar/__tests__/AccountSwitcherDialog.test.tsxnew file mode 100644index 0000000000..e0a7640de2--- /dev/null+++ b/apps/desktop/src/renderer/components/sidebar/__tests__/AccountSwitcherDialog.test.tsx@@ -0,0 +1,177 @@+// @vitest-environment jsdom++import { createRef } from 'react';+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const { confirm, listAccounts, runningSnapshot, syncAccounts, switchAccount, translate } =+ vi.hoisted(() => ({+ confirm: vi.fn(),+ listAccounts: vi.fn(),+ runningSnapshot: new Map<string, { isRunning: boolean }>(),+ syncAccounts: vi.fn(),+ switchAccount: vi.fn(),+ translate: (key: string, values?: { name?: string }) =>+ values?.name ? `${key}:${values.name}` : key,+ }));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: translate }),+}));++vi.mock('@/contexts/AuthContext', () => ({+ useAuth: () => ({ listAccounts, syncAccounts, switchAccount }),+}));+vi.mock('@/components/ui/confirm-dialog-provider', () => ({+ useOptionalConfirmDialog: () => ({ confirm }),+}));+vi.mock('@/lib/makerChatStore', () => ({+ makerChatStore: { getRunningSnapshot: () => runningSnapshot },+}));++import { AccountSwitcherDialog } from '../AccountSwitcherDialog';++const snapshot = {+ mutationAllowed: true,+ accounts: [+ {+ accountKey: 'personal-key',+ displayName: 'Personal Cindy',+ email: '[email protected]',+ avatarUrl: 'https://example.com/user-avatar.png',+ kind: 'personal' as const,+ orgName: null,+ orgLogoUrl: null,+ isCurrent: true,+ },+ {+ accountKey: 'org-key',+ displayName: 'Organization Cindy',+ email: '[email protected]',+ avatarUrl: 'https://example.com/org-user-avatar.png',+ kind: 'org' as const,+ orgName: 'Example Corp',+ orgLogoUrl: 'https://example.com/org-logo.png',+ isCurrent: false,+ },+ ],+};++beforeEach(() => {+ confirm.mockReset().mockResolvedValue(true);+ listAccounts.mockReset().mockResolvedValue(snapshot);+ runningSnapshot.clear();+ syncAccounts.mockReset().mockResolvedValue(snapshot);+ switchAccount.mockReset().mockResolvedValue(undefined);+});++afterEach(cleanup);++describe('AccountSwitcherDialog', () => {+ it('focuses the dialog surface on open instead of triggering the close tooltip', async () => {+ render(+ <AccountSwitcherDialog+ open+ onOpenChange={vi.fn()}+ onAddAccount={vi.fn()}+ triggerRef={createRef<HTMLButtonElement>()}+ />,+ );++ const dialog = screen.getByRole('dialog');+ await waitFor(() => expect(document.activeElement).toBe(dialog));+ expect(screen.getByRole('button', { name: 'sidebar.accountSwitcher.close' })).not.toBe(+ document.activeElement,+ );+ });++ it('shows organization name above the username, uses its logo, and switches by saved key', async () => {+ const onOpenChange = vi.fn();+ render(+ <AccountSwitcherDialog+ open+ onOpenChange={onOpenChange}+ onAddAccount={vi.fn()}+ triggerRef={createRef<HTMLButtonElement>()}+ />,+ );++ expect(await screen.findByText('Personal Cindy')).toBeTruthy();+ expect(screen.getByText('[email protected]')).toBeTruthy();+ expect(screen.getByText('Example Corp')).toBeTruthy();+ expect(screen.getByText('Organization Cindy')).toBeTruthy();+ expect(document.querySelector('img[src="https://example.com/org-logo.png"]')).toBeTruthy();+ expect(document.querySelector('img[src="https://example.com/org-user-avatar.png"]')).toBeNull();+ expect(screen.queryByText(/组织账号|Organization account/)).toBeNull();+ expect(screen.queryByText('sidebar.accountSwitcher.current')).toBeNull();+ await waitFor(() => expect(syncAccounts).toHaveBeenCalledOnce());++ fireEvent.click(screen.getByRole('button', { name: /Example CorpOrganization Cindy/ }));+ await waitFor(() => expect(switchAccount).toHaveBeenCalledWith('org-key'));+ expect(confirm).not.toHaveBeenCalled();+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });++ it('starts the full sign-in flow from the add-account action', async () => {+ const onAddAccount = vi.fn();+ render(+ <AccountSwitcherDialog+ open+ onOpenChange={vi.fn()}+ onAddAccount={onAddAccount}+ triggerRef={createRef<HTMLButtonElement>()}+ />,+ );++ await waitFor(() => expect(syncAccounts).toHaveBeenCalledOnce());+ fireEvent.click(screen.getByRole('button', { name: 'sidebar.accountSwitcher.addAccount' }));+ expect(onAddAccount).toHaveBeenCalledOnce();+ });++ it('asks before switching when a task is running and keeps the account dialog open on cancel', async () => {+ const onOpenChange = vi.fn();+ runningSnapshot.set('running-session', { isRunning: true });+ confirm.mockResolvedValue(false);+ render(+ <AccountSwitcherDialog+ open+ onOpenChange={onOpenChange}+ onAddAccount={vi.fn()}+ triggerRef={createRef<HTMLButtonElement>()}+ />,+ );++ fireEvent.click(await screen.findByRole('button', { name: /Example CorpOrganization Cindy/ }));++ await waitFor(() =>+ expect(confirm).toHaveBeenCalledWith({+ title: 'sidebar.accountSwitcher.runningTaskTitle',+ description: 'sidebar.accountSwitcher.runningTaskDescription',+ confirmText: 'sidebar.accountSwitcher.runningTaskConfirm',+ cancelText: 'logic.confirm.cancel',+ confirmVariant: 'destructive',+ }),+ );+ expect(switchAccount).not.toHaveBeenCalled();+ expect(onOpenChange).not.toHaveBeenCalled();+ });++ it('switches only after the user confirms interruption of running tasks', async () => {+ const onOpenChange = vi.fn();+ runningSnapshot.set('running-session', { isRunning: true });+ render(+ <AccountSwitcherDialog+ open+ onOpenChange={onOpenChange}+ onAddAccount={vi.fn()}+ triggerRef={createRef<HTMLButtonElement>()}+ />,+ );++ fireEvent.click(await screen.findByRole('button', { name: /Example CorpOrganization Cindy/ }));++ await waitFor(() => expect(confirm).toHaveBeenCalledOnce());+ await waitFor(() => expect(switchAccount).toHaveBeenCalledWith('org-key'));+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });+});diff --git a/apps/desktop/src/renderer/contexts/AuthContext.tsx b/apps/desktop/src/renderer/contexts/AuthContext.tsxindex 7781f1ea11..c139a82c38 100644--- a/apps/desktop/src/renderer/contexts/AuthContext.tsx+++ b/apps/desktop/src/renderer/contexts/AuthContext.tsx@@ -24,6 +24,7 @@ import {type AuthFlowState,type DesktopLoginAction,type DesktopLoginActionResult,+ type DesktopAccountSwitcherSnapshot,type User,} from '@/lib/authService';import {@@ -79,6 +80,11 @@ export interface AuthContextValue {loadLoginState: () => Promise<DesktopLoginActionResult>;dispatchLoginAction: (action: DesktopLoginAction) => Promise<DesktopLoginActionResult>;logout: () => Promise<void>;+ listAccounts: () => Promise<DesktopAccountSwitcherSnapshot>;+ syncAccounts: () => Promise<DesktopAccountSwitcherSnapshot>;+ switchAccount: (accountKey: string) => Promise<void>;+ beginAddAccount: () => Promise<DesktopLoginActionResult>;+ cancelAddAccount: () => Promise<void>;enterLocalMode: () => Promise<void>;exitLocalMode: () => Promise<void>;hasAccountDeletionReceipt: boolean;@@ -409,6 +415,27 @@ export function AuthProvider({clearWorkersCache();}, [runDataOwnerBoundary]);+ const listAccounts = useCallback(() => authServiceRef.current!.listAccounts(), []);++ const syncAccounts = useCallback(() => authServiceRef.current!.syncAccounts(), []);++ const switchAccount = useCallback(+ (accountKey: string) =>+ runDataOwnerBoundary(() => authServiceRef.current!.switchAccount(accountKey)),+ [runDataOwnerBoundary],+ );++ const beginAddAccount = useCallback(async () => {+ const result = await authServiceRef.current!.beginAddAccount();+ setLoginState(result.state);+ return result;+ }, []);++ const cancelAddAccount = useCallback(async () => {+ await authServiceRef.current!.cancelAddAccount();+ setLoginState(null);+ }, []);+const enterLocalMode = useCallback(async () => {// 本地模式也是一次 dataOwnerId 切换。必须走 applyIncomingState,不能自己拼半套// setter:漏接草稿 / prompt / 模型可见性 / 记忆分区会让跳过登录进主界面后仍读写@@ -475,6 +502,11 @@ export function AuthProvider({loadLoginState,dispatchLoginAction,logout,+ listAccounts,+ syncAccounts,+ switchAccount,+ beginAddAccount,+ cancelAddAccount,enterLocalMode,exitLocalMode,hasAccountDeletionReceipt,@@ -501,6 +533,11 @@ export function AuthProvider({loadLoginState,dispatchLoginAction,logout,+ listAccounts,+ syncAccounts,+ switchAccount,+ beginAddAccount,+ cancelAddAccount,enterLocalMode,exitLocalMode,hasAccountDeletionReceipt,diff --git a/apps/desktop/src/renderer/hooks/useLogout.ts b/apps/desktop/src/renderer/hooks/useLogout.tsindex f4138f734e..e93bce8e2a 100644--- a/apps/desktop/src/renderer/hooks/useLogout.ts+++ b/apps/desktop/src/renderer/hooks/useLogout.ts@@ -15,6 +15,7 @@ export function useLogout(): { handleLogout: () => Promise<void> } {description: t('logic.confirm.logoutDescription'),confirmText: t('logic.confirm.logoutConfirm'),cancelText: t('logic.confirm.cancel'),+ confirmVariant: 'destructive',});if (confirmed) {await logout();diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex d39b6a1f45..ea89ac3538 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -6501,6 +6501,10 @@"user": {"settingsLink": "Settings, current user: {{name}}","settingsLinkBeta": "Settings, current user: {{name}}, Beta channel enabled",+ "moreLabel": "More, current user: {{name}}",+ "menuSettings": "Settings",+ "menuAddAccount": "Sign in to another account",+ "menuLogout": "Log out","canaryBadge": "Canary user","regionCodeCn": "CN","regionCodeDev": "Dev",@@ -6508,6 +6512,20 @@"reopenUpdateBanner": "Update ready — click to review","downloadMobile": "Download Cindy Mobile"},+ "accountSwitcher": {+ "title": "Switch account",+ "description": "Choose an account used on this device",+ "syncing": "Checking sign-in status…",+ "syncFailed": "Some account statuses could not be updated",+ "switchFailed": "Could not switch accounts. Sign in to that account again",+ "runningTaskTitle": "Stop running tasks and switch accounts?",+ "runningTaskDescription": "Tasks are currently running. Switching accounts will stop them first, and unfinished work will not continue.",+ "runningTaskConfirm": "Stop Tasks and Switch",+ "startFailed": "Could not open the sign-in page. Try again later",+ "addAccount": "Sign in to another account",+ "back": "Back",+ "close": "Close"+ },"mobileDownload": {"title": "Control Cindy Remotely","subtitle": "Connect your phone to this desktop",@@ -10386,7 +10404,7 @@},"confirm": {"logoutTitle": "Log out",- "logoutDescription": "Log out of the current account?",+ "logoutDescription": "Log out of all accounts on this device?","logoutConfirm": "Log out","cancel": "Cancel","sessionExpiredTitle": "Login expired",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 06de50cac3..7363e05ba0 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -6499,6 +6499,10 @@"user": {"settingsLink": "設定, 現在のユーザー: {{name}}","settingsLinkBeta": "設定, 現在のユーザー: {{name}}, Beta チャンネル有効",+ "moreLabel": "その他、現在のユーザー:{{name}}",+ "menuSettings": "設定",+ "menuAddAccount": "別のアカウントでログイン",+ "menuLogout": "ログアウト","canaryBadge": "Canary ユーザー","regionCodeCn": "CN","regionCodeDev": "Dev",@@ -6506,6 +6510,20 @@"reopenUpdateBanner": "更新の準備完了 — クリックして確認","downloadMobile": "Cindy モバイル版をダウンロード"},+ "accountSwitcher": {+ "title": "アカウントを切り替え",+ "description": "このデバイスでログインしたアカウントを選択します",+ "syncing": "ログイン状態を確認中…",+ "syncFailed": "一部のアカウント状態を更新できませんでした",+ "switchFailed": "切り替えに失敗しました。このアカウントに再度ログインしてください",+ "runningTaskTitle": "実行中のセッションを停止してアカウントを切り替えますか?",+ "runningTaskDescription": "現在実行中のセッションがあります。アカウントを切り替えると先に停止され、未完了の処理は続行されません。",+ "runningTaskConfirm": "停止して切り替え",+ "startFailed": "ログイン画面を開けませんでした。しばらくしてからお試しください",+ "addAccount": "別のアカウントでログイン",+ "back": "戻る",+ "close": "閉じる"+ },"mobileDownload": {"title": "Cindy をリモート操作","subtitle": "モバイルからデスクトップへ接続",@@ -10373,7 +10391,7 @@},"confirm": {"logoutTitle": "ログアウト",- "logoutDescription": "現在のアカウントからログアウトしますか?",+ "logoutDescription": "このデバイス上のすべてのアカウントからログアウトしますか?","logoutConfirm": "ログアウト","cancel": "キャンセル","sessionExpiredTitle": "ログインの有効期限が切れました",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 271ec38024..7d4bc6661f 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -6499,6 +6499,10 @@"user": {"settingsLink": "설정, 현재 사용자: {{name}}","settingsLinkBeta": "설정, 현재 사용자: {{name}}, 베타 채널 활성화됨",+ "moreLabel": "더 보기, 현재 사용자: {{name}}",+ "menuSettings": "설정",+ "menuAddAccount": "다른 계정으로 로그인",+ "menuLogout": "로그아웃","canaryBadge": "Canary 사용자","regionCodeCn": "CN","regionCodeDev": "Dev",@@ -6506,6 +6510,20 @@"reopenUpdateBanner": "업데이트 준비됨 — 클릭하여 확인","downloadMobile": "Cindy 모바일 다운로드"},+ "accountSwitcher": {+ "title": "계정 전환",+ "description": "이 기기에서 로그인한 계정을 선택하세요",+ "syncing": "로그인 상태 확인 중…",+ "syncFailed": "일부 계정 상태를 업데이트할 수 없습니다",+ "switchFailed": "계정을 전환할 수 없습니다. 해당 계정으로 다시 로그인하세요",+ "runningTaskTitle": "실행 중인 세션을 중지하고 계정을 전환할까요?",+ "runningTaskDescription": "현재 실행 중인 세션이 있습니다. 계정을 전환하면 먼저 중지되며 완료되지 않은 작업은 계속되지 않습니다.",+ "runningTaskConfirm": "중지하고 전환",+ "startFailed": "로그인 화면을 열 수 없습니다. 나중에 다시 시도하세요",+ "addAccount": "다른 계정으로 로그인",+ "back": "뒤로",+ "close": "닫기"+ },"mobileDownload": {"title": "Cindy 원격 제어","subtitle": "모바일에서 데스크톱으로 연결",@@ -10373,7 +10391,7 @@},"confirm": {"logoutTitle": "로그아웃",- "logoutDescription": "현재 계정에서 로그아웃하시겠습니까?",+ "logoutDescription": "이 기기의 모든 계정에서 로그아웃하시겠습니까?","logoutConfirm": "로그아웃","cancel": "취소","sessionExpiredTitle": "로그인이 만료됨",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex b8ff79a4a9..e7522ba07f 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -6491,6 +6491,10 @@"user": {"settingsLink": "设置,当前用户:{{name}}","settingsLinkBeta": "设置,当前用户:{{name}},Beta 测试渠道已开启",+ "moreLabel": "更多,当前用户:{{name}}",+ "menuSettings": "设置",+ "menuAddAccount": "登录更多账号",+ "menuLogout": "退出","canaryBadge": "灰度用户","regionCodeCn": "CN","regionCodeDev": "Dev",@@ -6498,6 +6502,20 @@"reopenUpdateBanner": "有更新待重启,点击查看","downloadMobile": "下载 Cindy 移动端"},+ "accountSwitcher": {+ "title": "切换账号",+ "description": "选择这台设备上登录过的账号",+ "syncing": "正在检查登录状态…",+ "syncFailed": "部分账号状态暂时无法更新",+ "switchFailed": "切换失败,请重新登录该账号",+ "runningTaskTitle": "中断任务并切换账号?",+ "runningTaskDescription": "当前有任务正在运行。切换账号会先中断这些任务,未完成的执行不会继续。",+ "runningTaskConfirm": "中断任务并切换",+ "startFailed": "无法打开登录页面,请稍后重试",+ "addAccount": "登录更多账号",+ "back": "返回",+ "close": "关闭"+ },"mobileDownload": {"title": "远程控制 Cindy","subtitle": "移动端连接桌面端",@@ -10365,7 +10383,7 @@},"confirm": {"logoutTitle": "退出登录",- "logoutDescription": "确定要退出当前账号吗?",+ "logoutDescription": "确定要退出这台设备上的所有账号吗?","logoutConfirm": "退出","cancel": "取消","sessionExpiredTitle": "登录已过期",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex cbde914e0a..f159d513b4 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -6491,6 +6491,10 @@"user": {"settingsLink": "設定,當前使用者:{{name}}","settingsLinkBeta": "設定,當前使用者:{{name}},Beta 測試管道已開啟",+ "moreLabel": "更多,當前使用者:{{name}}",+ "menuSettings": "設定",+ "menuAddAccount": "登入更多帳號",+ "menuLogout": "退出","canaryBadge": "灰度使用者","regionCodeCn": "CN","regionCodeDev": "Dev",@@ -6498,6 +6502,20 @@"reopenUpdateBanner": "有更新待重啟,點選檢視","downloadMobile": "下載 Cindy 移動端"},+ "accountSwitcher": {+ "title": "切換帳號",+ "description": "選擇這台裝置上登入過的帳號",+ "syncing": "正在檢查登入狀態…",+ "syncFailed": "部分帳號狀態暫時無法更新",+ "switchFailed": "切換失敗,請重新登入該帳號",+ "runningTaskTitle": "中斷任務並切換帳號?",+ "runningTaskDescription": "目前有任務正在執行。切換帳號會先中斷這些任務,未完成的執行不會繼續。",+ "runningTaskConfirm": "中斷任務並切換",+ "startFailed": "無法開啟登入頁面,請稍後再試",+ "addAccount": "登入更多帳號",+ "back": "返回",+ "close": "關閉"+ },"mobileDownload": {"title": "遠端控制 Cindy","subtitle": "移動端連線桌面端",@@ -10365,7 +10383,7 @@},"confirm": {"logoutTitle": "退出登入",- "logoutDescription": "確定要退出當前帳號嗎?",+ "logoutDescription": "確定要退出這台裝置上的所有帳號嗎?","logoutConfirm": "退出","cancel": "取消","sessionExpiredTitle": "登入已過期",diff --git a/apps/desktop/src/renderer/lib/authService.ts b/apps/desktop/src/renderer/lib/authService.tsindex 04d0c567c0..dd98e233e0 100644--- a/apps/desktop/src/renderer/lib/authService.ts+++ b/apps/desktop/src/renderer/lib/authService.ts@@ -6,9 +6,11 @@ import type {DesktopAccountDeletionConfirmInput,DesktopAccountDeletionConfirmResult,DesktopAccountDeletionStatusResult,+ DesktopAccountSwitcherSnapshot,DesktopLoginAction,DesktopLoginActionResult,} from '../../shared/authIpc';+export type { DesktopSavedAccount } from '../../shared/authIpc';import type { Effort } from '@/lib/userPreferences.types';/** Renderer-safe projection of the authenticated auth-server membership. */@@ -52,6 +54,11 @@ export interface AuthService {getLoginState(): Promise<DesktopLoginActionResult>;dispatchLoginAction(action: DesktopLoginAction): Promise<DesktopLoginActionResult>;logout(): Promise<void>;+ listAccounts(): Promise<DesktopAccountSwitcherSnapshot>;+ syncAccounts(): Promise<DesktopAccountSwitcherSnapshot>;+ switchAccount(accountKey: string): Promise<void>;+ beginAddAccount(): Promise<DesktopLoginActionResult>;+ cancelAddAccount(): Promise<void>;enterLocalMode(): Promise<AuthState>;exitLocalMode(): Promise<AuthState>;getAccountDeletionAvailability(): Promise<DesktopAccountDeletionAvailabilityResult>;@@ -114,6 +121,26 @@ export function createAuthService(): AuthService {await window.electronAPI.authLogout();},+ listAccounts() {+ return window.electronAPI.authListAccounts();+ },++ syncAccounts() {+ return window.electronAPI.authSyncAccounts();+ },++ switchAccount(accountKey) {+ return window.electronAPI.authSwitchAccount(accountKey);+ },++ beginAddAccount() {+ return window.electronAPI.authBeginAddAccount();+ },++ cancelAddAccount() {+ return window.electronAPI.authCancelAddAccount();+ },+async enterLocalMode(): Promise<AuthState> {return window.electronAPI.authEnterLocal() as Promise<AuthState>;},@@ -156,6 +183,7 @@ export function createAuthService(): AuthService {export type {AuthFlowState,DesktopAccountDeletionChallenge,+ DesktopAccountSwitcherSnapshot,DesktopLoginAction,DesktopLoginActionResult,};diff --git a/apps/desktop/src/renderer/router.tsx b/apps/desktop/src/renderer/router.tsxindex 9c755e19dd..0051e3b7b7 100644--- a/apps/desktop/src/renderer/router.tsx+++ b/apps/desktop/src/renderer/router.tsx@@ -6,6 +6,7 @@ import { SidebarWindowLayout } from '@/components/layout/SidebarWindowLayout';import { GhostPanelWindowLayout } from '@/components/layout/GhostPanelWindowLayout';import { SettingsView } from '@/components/settings/SettingsView';import { LoginPage } from '@/components/login/LoginPage';+import { AddAccountLoginPage } from '@/components/login/AddAccountLoginPage';import { ProtectedRoute } from '@/components/auth/ProtectedRoute';import { GuestRoute } from '@/components/auth/GuestRoute';import { LocalDbGate } from '@/components/auth/LocalDbGate';@@ -56,6 +57,10 @@ export const router = createHashRouter([// 冒泡到这里,全屏展示可恢复错误页(2026-07-09 React #130 事故的直接止血层)。errorElement: <RouteErrorFallback />,children: [+ {+ path: 'add-account',+ element: <AddAccountLoginPage />,+ },{// 主功能区入口 —— 经过 LocalDbGate(localDb 就绪)才能进element: <LocalDbGate />,diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 82fcaba8c5..befb5f0419 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -64,6 +64,7 @@ type DesktopAccountDeletionConfirmResult =import('../shared/authIpc').DesktopAccountDeletionConfirmResult;type DesktopAccountDeletionStatusResult =import('../shared/authIpc').DesktopAccountDeletionStatusResult;+type DesktopAccountSwitcherSnapshot = import('../shared/authIpc').DesktopAccountSwitcherSnapshot;type PendingRemotePrecreatedWorktree =import('../shared/remotePrecreatedWorktreeLedger').PendingRemotePrecreatedWorktree;type PendingRemotePrecreatedWorktreeTarget =@@ -2050,6 +2051,11 @@ interface ElectronAPI {/** 登录 captcha 托管挑战页地址(不含 query);LoginCaptchaOverlay 装载 webview 用。 */authGetCaptchaChallengeUrl: () => Promise<string>;authLogout: () => Promise<void>;+ authListAccounts: () => Promise<DesktopAccountSwitcherSnapshot>;+ authSyncAccounts: () => Promise<DesktopAccountSwitcherSnapshot>;+ authSwitchAccount: (accountKey: string) => Promise<void>;+ authBeginAddAccount: () => Promise<DesktopLoginActionResult>;+ authCancelAddAccount: () => Promise<void>;authEnterLocal: () => Promise<AuthStateChangePayload>;authExitLocal: () => Promise<AuthStateChangePayload>;authRefresh: () => Promise<boolean>;diff --git a/apps/desktop/src/shared/__tests__/authIpc.test.ts b/apps/desktop/src/shared/__tests__/authIpc.test.tsindex 862a28d8be..dc373e99bd 100644--- a/apps/desktop/src/shared/__tests__/authIpc.test.ts+++ b/apps/desktop/src/shared/__tests__/authIpc.test.ts@@ -1,8 +1,19 @@import { describe, expect, it } from 'vitest';-import { parseDesktopAccountDeletionConfirmInput, parseDesktopLoginAction } from '../authIpc';+import {+ parseDesktopAccountDeletionConfirmInput,+ parseDesktopAccountKey,+ parseDesktopLoginAction,+} from '../authIpc';describe('desktop auth IPC validation', () => {+ it('accepts bounded opaque account keys and rejects malformed values', () => {+ expect(parseDesktopAccountKey('["global","membership-1"]')).toBe('["global","membership-1"]');+ expect(parseDesktopAccountKey('')).toBeNull();+ expect(parseDesktopAccountKey('x'.repeat(513))).toBeNull();+ expect(parseDesktopAccountKey({ accountKey: 'membership-1' })).toBeNull();+ });+it('projects recognized actions onto their typed fields', () => {expect(parseDesktopLoginAction({diff --git a/apps/desktop/src/shared/authIpc.ts b/apps/desktop/src/shared/authIpc.tsindex e6b8a4edbe..a5edf66242 100644--- a/apps/desktop/src/shared/authIpc.ts+++ b/apps/desktop/src/shared/authIpc.ts@@ -31,6 +31,23 @@ export type DesktopLoginActionResult =| { success: true; state: AuthFlowState }| { success: false; code: string; state: AuthFlowState | null };+export interface DesktopSavedAccount {+ /** Opaque main-owned identifier. Renderer must not derive realm or membership ids from it. */+ accountKey: string;+ displayName: string;+ email: string | null;+ avatarUrl: string | null;+ kind: 'personal' | 'org';+ orgName: string | null;+ orgLogoUrl: string | null;+ isCurrent: boolean;+}++export interface DesktopAccountSwitcherSnapshot {+ accounts: DesktopSavedAccount[];+ mutationAllowed: boolean;+}+/** The receipt token stays in Electron main; renderer only receives display-safe fields. */export interface DesktopAccountDeletionChallenge {challengeId: string;@@ -64,6 +81,7 @@ const MAX_CODE_LENGTH = 32;const MAX_CAPTCHA_TOKEN_LENGTH = 2048;// 与 auth-server 的企业 ID / slug / 已验证域名统一上限对齐。const MAX_ORG_IDENTIFIER_LENGTH = 253;+const MAX_ACCOUNT_KEY_LENGTH = 512;function isRecord(value: unknown): value is Record<string, unknown> {return typeof value === 'object' && value !== null && !Array.isArray(value);@@ -168,6 +186,10 @@ export function parseDesktopLoginAction(value: unknown): DesktopLoginAction | nu}}+export function parseDesktopAccountKey(value: unknown): string | null {+ return isBoundedString(value, MAX_ACCOUNT_KEY_LENGTH) ? value : null;+}+/** Runtime validation for the irreversible account-deletion confirmation boundary. */export function parseDesktopAccountDeletionConfirmInput(value: unknown,diff --git a/packages/auth-client/src/__tests__/client.test.ts b/packages/auth-client/src/__tests__/client.test.tsindex 2171426ba4..86b42aed18 100644--- a/packages/auth-client/src/__tests__/client.test.ts+++ b/packages/auth-client/src/__tests__/client.test.ts@@ -133,10 +133,9 @@ describe("CindyAuthClient", () => {it("carries captchaToken in the email request-code body only when provided", async () => {const fetch = vi.fn(async () => response(200, { status: "sent" }));await client(fetch).requestCode("email", "[email protected]");- const bare = JSON.parse((fetch.mock.calls[0]?.[1] as { body: string }).body) as Record<- string,- unknown- >;+ const bare = JSON.parse(+ (fetch.mock.calls[0]?.[1] as { body: string }).body,+ ) as Record<string, unknown>;expect(bare).toEqual({ email: "[email protected]", locale: "zh-CN" });await client(fetch).requestCode("email", "[email protected]", {captchaToken: "captcha-token-1",@@ -333,22 +332,40 @@ describe("CindyAuthClient", () => {orgName: "Corp",},}),- );+ )+ .mockResolvedValueOnce(+ response(200, {+ accountToken: "rotated-account-access",+ accountRefreshToken: "rotated-account-refresh",+ }),+ )+ .mockResolvedValueOnce(response(200, { status: "ok" }));const auth = client(fetch);- expect(auth).not.toHaveProperty("refreshAccount");- expect(auth).not.toHaveProperty("logoutAccount");await expect(auth.getAccountMemberships("account-access"),).resolves.toHaveLength(1);await expect(auth.exchangeAccountMembership("account-access", "org-membership"),).resolves.toMatchObject({ accessToken: "org-access" });+ await expect(auth.refreshAccount("account-refresh")).resolves.toEqual({+ accountToken: "rotated-account-access",+ accountRefreshToken: "rotated-account-refresh",+ });+ await expect(+ auth.logoutAccount("rotated-account-access"),+ ).resolves.toBeUndefined();expect(fetch.mock.calls[0]?.[1]?.headers).toMatchObject({Authorization: "Bearer account-access",});expect(fetch.mock.calls[1]?.[1]?.headers).toMatchObject({Authorization: "Bearer account-access",});+ expect(fetch.mock.calls[2]?.[0]).toBe(+ "https://auth.example.com/api/auth/account/refresh",+ );+ expect(fetch.mock.calls[3]?.[1]?.headers).toMatchObject({+ Authorization: "Bearer rotated-account-access",+ });});it("maps server errors without leaking malformed responses", async () => {diff --git a/packages/auth-client/src/client.ts b/packages/auth-client/src/client.tsindex d5cff74ebf..f11794c803 100644--- a/packages/auth-client/src/client.ts+++ b/packages/auth-client/src/client.ts@@ -5,6 +5,7 @@ import {accountDeletionChallengeSchema,accountDeletionStatusSchema,accountMembershipSchema,+ accountTokenPairSchema,authRegionSchema,desktopAuthorizationPollSchema,loginMethodSchema,@@ -18,6 +19,7 @@ import {type AccountDeletionChallenge,type AccountDeletionStatus,type AccountMembership,+ type AccountTokenPair,type AuthMe,type AuthTokenPair,type AuthRegion,@@ -321,6 +323,24 @@ export class CindyAuthClient {);}+ refreshAccount(accountRefreshToken: string): Promise<AccountTokenPair> {+ return this.request(+ "/api/auth/account/refresh",+ accountTokenPairSchema,+ { accountRefreshToken, deviceId: this.options.deviceId },+ { timeoutMs: 0 },+ );+ }++ async logoutAccount(accountToken: string): Promise<void> {+ await this.request(+ "/api/auth/account/logout",+ z.object({ status: z.literal("ok") }),+ undefined,+ { token: accountToken },+ );+ }+async requestSsoVerificationCode(verificationTicket: string): Promise<void> {await this.request("/api/auth/sso/verification/request-code",diff --git a/packages/auth-client/src/index.ts b/packages/auth-client/src/index.tsindex aefe6fce1e..83577e76fd 100644--- a/packages/auth-client/src/index.ts+++ b/packages/auth-client/src/index.ts@@ -36,6 +36,7 @@ export {accountDeletionChallengeSchema,accountDeletionStatusSchema,accountMembershipSchema,+ accountTokenPairSchema,authRegionSchema,CAPTCHA_CHALLENGE_PAGE_PATH,captchaConfigSchema,@@ -61,6 +62,7 @@ export type {AccountDeletionChallenge,AccountDeletionStatus,AccountMembership,+ AccountTokenPair,AuthClientType,AuthFlowAction,AuthFlowState,diff --git a/packages/auth-client/src/types.ts b/packages/auth-client/src/types.tsindex 4bb5d397f1..de27fbf58a 100644--- a/packages/auth-client/src/types.ts+++ b/packages/auth-client/src/types.ts@@ -152,6 +152,12 @@ export const tokenPairSchema = z.object({});export type AuthTokenPair = z.infer<typeof tokenPairSchema>;+export const accountTokenPairSchema = z.object({+ accountToken: z.string().min(1),+ accountRefreshToken: z.string().min(1),+});+export type AccountTokenPair = z.infer<typeof accountTokenPairSchema>;+const optionalAccountTokenFields = {accountToken: z.string().min(1).optional(),accountRefreshToken: z.string().min(1).optional(),