Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 优化多账号登录与切换体验 (#3811)
Dash7f03b74364c5
diff --git a/apps/desktop/src/main/__tests__/authAccountLogoutPolicy.test.ts b/apps/desktop/src/main/__tests__/authAccountLogoutPolicy.test.tsnew file mode 100644index 0000000000..8702b0b5ac--- /dev/null+++ b/apps/desktop/src/main/__tests__/authAccountLogoutPolicy.test.ts@@ -0,0 +1,128 @@+import {+ accountVaultKey,+ passportVaultKey,+ type AuthRegion,+ type StoredAccountMetadata,+} from '@cindy/auth-client';+import { describe, expect, it } from 'vitest';++import {+ isLoggedOutVaultAccount,+ removeLoggedOutVaultAccount,+ restoreLoggedOutVaultAccount,+} from '../authAccountLogoutPolicy';++const realm: AuthRegion = 'global';++function metadata(membershipId: string, passportId: string): StoredAccountMetadata {+ return {+ membershipId,+ passportId,+ displayName: membershipId,+ email: `${membershipId}@example.com`,+ avatarUrl: null,+ kind: 'personal',+ role: 'owner',+ orgId: null,+ orgName: null,+ orgLogoUrl: null,+ };+}++function resource(membershipId: string, passportId: string) {+ return {+ realm,+ refreshToken: `resource-${membershipId}`,+ metadata: metadata(membershipId, passportId),+ lastUsedAt: 1,+ };+}++function passport(passportId: string, membershipIds: string[]) {+ return {+ realm,+ passportId,+ accountRefreshToken: `passport-${passportId}`,+ memberships: membershipIds.map((membershipId) => metadata(membershipId, passportId)),+ };+}++describe('auth account logout policy', () => {+ it('removes only the current membership while a sibling from the same Passport remains', () => {+ const currentKey = accountVaultKey(realm, 'personal');+ const siblingKey = accountVaultKey(realm, 'org');+ const passportKey = passportVaultKey(realm, 'passport-a');+ const vault = {+ activeAccountKey: currentKey,+ resources: {+ [currentKey]: resource('personal', 'passport-a'),+ [siblingKey]: resource('org', 'passport-a'),+ },+ passports: {+ [passportKey]: passport('passport-a', ['personal', 'org']),+ },+ };++ const removedPassport = removeLoggedOutVaultAccount(vault, {+ accountKey: currentKey,+ realm,+ passportId: 'passport-a',+ });++ expect(removedPassport).toBeNull();+ expect(vault.activeAccountKey).toBeNull();+ expect(vault.resources[currentKey]).toBeUndefined();+ expect(vault.resources[siblingKey]).toBeDefined();+ expect(vault.passports[passportKey]).toBeDefined();+ expect(+ vault.passports[passportKey].memberships.map((membership) => membership.membershipId),+ ).toEqual(['org']);+ expect(isLoggedOutVaultAccount(vault, currentKey)).toBe(true);+ expect(isLoggedOutVaultAccount(vault, siblingKey)).toBe(false);+ });++ it('removes and returns the Passport when its last restorable membership logs out', () => {+ const currentKey = accountVaultKey(realm, 'personal');+ const passportKey = passportVaultKey(realm, 'passport-a');+ const storedPassport = passport('passport-a', ['personal']);+ const vault = {+ activeAccountKey: currentKey,+ resources: { [currentKey]: resource('personal', 'passport-a') },+ passports: { [passportKey]: storedPassport },+ };++ const removedPassport = removeLoggedOutVaultAccount(vault, {+ accountKey: currentKey,+ realm,+ passportId: 'passport-a',+ });++ expect(removedPassport).toBe(storedPassport);+ expect(vault.passports[passportKey]).toBeUndefined();+ expect(vault.resources[currentKey]).toBeUndefined();+ expect(isLoggedOutVaultAccount(vault, currentKey)).toBe(true);+ });++ it('keeps an account hidden through repeated logout and restores it only on explicit login', () => {+ const currentKey = accountVaultKey(realm, 'personal');+ const vault: {+ activeAccountKey: string | null;+ resources: Record<string, ReturnType<typeof resource>>;+ passports: Record<string, ReturnType<typeof passport>>;+ loggedOutAccountKeys?: string[];+ } = {+ activeAccountKey: null,+ resources: {},+ passports: {},+ };+ const identity = { accountKey: currentKey, realm, passportId: 'passport-a' };++ removeLoggedOutVaultAccount(vault, identity);+ removeLoggedOutVaultAccount(vault, identity);+ expect(vault.loggedOutAccountKeys).toEqual([currentKey]);++ restoreLoggedOutVaultAccount(vault, currentKey);+ expect(vault.loggedOutAccountKeys).toBeUndefined();+ expect(isLoggedOutVaultAccount(vault, currentKey)).toBe(false);+ });+});diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.tsindex 4da624c3e2..56434335ac 100644--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts@@ -10,6 +10,10 @@ describe('auth login-flow reset', () => {/\r\n/g,'\n',);+ const logoutPolicySource = readFileSync(+ resolve(process.cwd(), 'src/main/authAccountLogoutPolicy.ts'),+ 'utf8',+ ).replace(/\r\n/g, '\n');const deviceLinkSource = readFileSync(resolve(process.cwd(), 'src/main/device-link/index.ts'),'utf8',@@ -136,9 +140,13 @@ describe('auth login-flow reset', () => {const logoutStart = source.indexOf('export async function logout()');const logoutEnd = source.indexOf('\n}\n\n/**\n * Called on system resume', logoutStart);const logoutBody = source.slice(logoutStart, logoutEnd);- expect(logoutBody).toContain('token: currentAccessToken');+ expect(logoutBody).toContain('accessToken: currentAccessToken');expect(logoutBody).not.toContain('pendingAccountToken');+ const revokeStart = source.indexOf('function revokeLoggedOutAccountBestEffort(');+ const revokeEnd = source.indexOf('\n}\n\nexport async function logout()', revokeStart);+ expect(source.slice(revokeStart, revokeEnd)).toContain('token: input.accessToken');+const getterStart = source.indexOf('export function getAccessToken(): string | null {');const getterEnd = source.indexOf('\n}', getterStart);const getterBody = source.slice(getterStart, getterEnd);@@ -147,6 +155,15 @@ describe('auth login-flow reset', () => {});it('keeps saved account metadata fresh after profile edits and Passport sync', () => {+ expect(source).toContain('const AUTH_ACCOUNT_VAULT_VERSION = 2 as const;');+ expect(source).toContain(+ "const AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY = 'cindy_auth_account_logout_tombstones_v1';",+ );+ expect(source).toContain('const AUTH_ACCOUNT_LOGOUT_TOMBSTONES_VERSION = 1 as const;');+ expect(source).toContain('const logoutAuthEpoch = authStateEpoch;');+ expect(source).toContain("'Logout was superseded by a newer auth action'");+ expect(source).toContain('validateBeforeCommit: isLogoutStillCurrent');+ expect(source).toContain('shouldClearOnFailure: isLogoutStillCurrent');const writePassportStart = source.indexOf('function writePassportSessionToVault(');const writePassportEnd = source.indexOf('\n}\n\n/** Persist a rotated Passport',@@ -155,6 +172,52 @@ describe('auth login-flow reset', () => {const writePassportBody = source.slice(writePassportStart, writePassportEnd);expect(writePassportBody).toContain('reconcileSavedAccountMetadata(vault');expect(writePassportBody).toContain("passportMode: 'replace-passport'");+ expect(writePassportBody).toContain('loggedOutKeys.has(accountVaultKey(input.realm');++ const readStart = source.indexOf('function readAuthAccountVault(');+ const readEnd = source.indexOf('\n}\n\nfunction writeAuthAccountVault', readStart);+ const readBody = source.slice(readStart, readEnd);+ expect(readBody).toContain('persistedVersion !== 1');+ expect(readBody).toContain('version: AUTH_ACCOUNT_VAULT_VERSION');++ const writeStart = source.indexOf('function writeAuthAccountVault(');+ const writeEnd = source.indexOf('\n}\n\nfunction writeAuthAccountVaultOrThrow', writeStart);+ const writeBody = source.slice(writeStart, writeEnd);+ expect(writeBody).toContain('JSON.stringify({ ...vault, version: 1 })');+ expect(writeBody).toContain('older client can');+ expect(writeBody).toContain('writeAuthAccountLogoutTombstones(vault)');+ expect(writeBody.indexOf('writeAuthAccountLogoutTombstones(vault)')).toBeLessThan(+ writeBody.indexOf('writeAtomicSafe(AUTH_ACCOUNT_VAULT_KEY'),+ );++ const logoutTombstoneReadStart = source.indexOf('function readAuthAccountLogoutTombstones(');+ const logoutTombstoneReadEnd = source.indexOf(+ '\n}\n\nfunction writeAuthAccountLogoutTombstones',+ logoutTombstoneReadStart,+ );+ const logoutTombstoneReadBody = source.slice(logoutTombstoneReadStart, logoutTombstoneReadEnd);+ expect(logoutTombstoneReadBody).toContain('parseDesktopAccountKey(key)');+ expect(logoutTombstoneReadBody).toContain('isAtomicPersistedSecretAbsent');+ expect(logoutTombstoneReadBody).toContain('if (options.recoverInvalid) return [];');++ const logoutTombstoneWriteStart = source.indexOf('function writeAuthAccountLogoutTombstones(');+ const logoutTombstoneWriteEnd = source.indexOf(+ '\n}\n\nfunction accountVaultKey',+ logoutTombstoneWriteStart,+ );+ expect(source.slice(logoutTombstoneWriteStart, logoutTombstoneWriteEnd)).toContain(+ 'JSON.stringify({ version: AUTH_ACCOUNT_LOGOUT_TOMBSTONES_VERSION, accountKeys })',+ );++ const readLogoutKeysStart = readBody.indexOf('persistedLogoutKeys =');+ expect(readLogoutKeysStart).toBeGreaterThan(-1);+ expect(readBody).toContain('recoverInvalid: options.recoverInvalid');+ expect(readBody).toContain('if (options.allowUnreadable) return emptyAuthAccountVault();');+ expect(readBody).toContain('new Set([...persistedLogoutKeys, ...embeddedLogoutKeys])');+ expect(readBody).not.toContain('loggedOutKeys.delete(active)');+ expect(readBody).toContain(+ 'active && resources[active] && !loggedOutKeys.has(active) ? active : null',+ );const profileStart = source.indexOf('export async function updateServerProfile(');const profileEnd = source.indexOf('\n}\n\nexport async function initialize(', profileStart);@@ -179,14 +242,21 @@ describe('auth login-flow reset', () => {expect(mutationBody.indexOf('const vault = readAuthAccountVault({')).toBeGreaterThan(mutationBody.indexOf('if (!status.held)'),);- expect(mutationBody.indexOf('writeAuthAccountVaultOrThrow(vault);')).toBeGreaterThan(- mutationBody.indexOf('await operation(vault);'),- );- expect(mutationBody.indexOf('await afterPersist(result);')).toBeGreaterThan(- mutationBody.indexOf('writeAuthAccountVaultOrThrow(vault);'),- );+ const vaultWriteAt = mutationBody.indexOf('writeAuthAccountVaultOrThrow(vault');+ expect(vaultWriteAt).toBeGreaterThan(mutationBody.indexOf('await operation(vault);'));+ expect(mutationBody.indexOf('await afterPersist(result);')).toBeGreaterThan(vaultWriteAt);expect(mutationBody).toContain('removeAtomicSafeOrThrow(AUTH_ACCOUNT_VAULT_KEY);');expect(mutationBody).toContain('writeAtomicSafe(AUTH_ACCOUNT_VAULT_KEY, previousRaw)');+ expect(mutationBody).toContain('removeAtomicSafeOrThrow(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY);');+ expect(mutationBody).toContain(+ 'writeAtomicSafe(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY, previousLogoutRaw)',+ );+ expect(mutationBody).toContain('readAtomicSafeCiphertext(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY)');+ expect(mutationBody).toContain('replaceUnreadableLogoutTombstones:');+ expect(mutationBody).toContain('options.replaceUnreadableLogoutTombstones');+ expect(mutationBody).toContain(+ 'writeAtomicSafeCiphertext(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY, previousLogoutCiphertext)',+ );for (const helper of ['async function rememberResourceSession(',@@ -214,8 +284,13 @@ describe('auth login-flow reset', () => {expect(readBody).toContain("throw new Error('invalid saved resource credential')");expect(readBody).toContain("throw new Error('invalid saved Passport credential')");expect(readBody).toContain("throw new Error('invalid saved Passport membership')");+ expect(readBody).toContain("throw new Error('invalid logged-out account key')");expect(readBody).toContain('memberships.length !== item.memberships.length');- expect(readBody).toContain('active && resources[active] ? active : null');+ expect(readBody).toContain('allowUnreadableLogoutTombstones?: boolean');+ expect(readBody).toContain('if (options.allowUnreadableLogoutTombstones) {');+ expect(readBody).toContain(+ 'active && resources[active] && !loggedOutKeys.has(active) ? active : null',+ );});it('recovers invalid Desktop vault content only for a completed explicit login', () => {@@ -252,6 +327,25 @@ describe('auth login-flow reset', () => {);});+ it('replaces unreadable logout tombstones only for explicit login or logout', () => {+ const writeStart = source.indexOf('function writeAuthAccountVault(');+ const writeEnd = source.indexOf('\n}\n\nfunction writeAuthAccountVaultOrThrow', writeStart);+ const writeBody = source.slice(writeStart, writeEnd);+ expect(writeBody).toContain('replaceUnreadableLogoutTombstones?: boolean');+ expect(writeBody).toContain('const previousLogoutUnreadable =');+ expect(writeBody).toContain('previousLogoutCiphertext === null');+ expect(writeBody).toContain('!options.replaceUnreadableLogoutTombstones');+ expect(writeBody).toContain(+ 'writeAtomicSafeCiphertext(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY, previousLogoutCiphertext)',+ );++ const clearStart = source.indexOf('async function clearAuthAccountVault(');+ const clearEnd = source.indexOf('\n}\n\nfunction metadataFromMembership', clearStart);+ expect(source.slice(clearStart, clearEnd)).toContain(+ 'writeAuthAccountVaultOrThrow(vault, { replaceUnreadableLogoutTombstones: true });',+ );+ });+it('atomically replaces the aggregate saved-account vault', () => {const writeStart = source.indexOf('function writeAtomicSafe(');const writeEnd = source.indexOf('\n}\n\nfunction removeAtomicSafeOrThrow', writeStart);@@ -360,7 +454,7 @@ describe('auth login-flow reset', () => {expect(source).toContain("'CREDENTIAL_STORE_UNAVAILABLE'");expect(source).toContain('isPersistedSecretAbsent(AUTH_ACCOUNT_VAULT_KEY)');expect(source).toContain('readAuthAccountVault({ allowUnreadable: true })');- expect(source).toContain('writeAuthAccountVaultOrThrow(vault);');+ expect(source).toContain('writeAuthAccountVaultOrThrow(vault');const syncStart = source.indexOf('export async function syncSavedAccounts()');const syncEnd = source.indexOf('\n}\n\nexport async function switchSavedAccount', syncStart);@@ -384,8 +478,20 @@ describe('auth login-flow reset', () => {expect(switchBody).toContain("'REGION_MISMATCH'");expect(switchBody).toContain('const switchLoginFlowEpoch = loginFlowEpoch;');expect(switchBody).toContain(- "await completeLogin({ status: 'ok', ...pair }, switchLoginFlowEpoch);",+ "await completeLogin({ status: 'ok', ...pair }, switchLoginFlowEpoch, {",+ );+ expect(switchBody).toContain('restoreLoggedOutAccount: false');+ expect(switchBody).toContain('accountToLogOut: options.accountToLogOut');+ expect(switchBody).toContain('validateBeforeCommit: options.validateBeforeCommit');++ const completeLoginStart = source.indexOf('async function completeLogin(');+ const completeLoginEnd = source.indexOf(+ '\n}\n\nasync function runLoginAction',+ completeLoginStart,);+ const completeLoginBody = source.slice(completeLoginStart, completeLoginEnd);+ expect(completeLoginBody).toContain('validateBeforeCommit?: (loginEpoch: number) => void;');+ expect(completeLoginBody).toContain('options.validateBeforeCommit?.(loginEpoch);');const resourceRefreshStart = source.indexOf('async function refreshSavedResourceSession(');const resourceRefreshEnd = source.indexOf(@@ -485,11 +591,11 @@ describe('auth login-flow reset', () => {expect(refreshAt).toBeGreaterThan(reconcileAt);});- it('keeps logout-all durable across a crash between vault and session cleanup', () => {+ it('keeps a durable signed-out owner across a crash between vault and session cleanup', () => {expect(source).toContain('signedOutAt?: number;');const clearStart = source.indexOf('async function clearAuthAccountVault(');- const clearEnd = source.indexOf('\n}\n\nfunction metadataFromMembership', clearStart);+ const clearEnd = source.indexOf('\n}\n\nfunction persistLogoutTombstoneOnly', clearStart);const clearBody = source.slice(clearStart, clearEnd);expect(clearBody).toContain('withCrossProcessLock(');expect(clearBody).toContain("label: 'auth-account-vault-clear'");@@ -502,6 +608,14 @@ describe('auth login-flow reset', () => {clearBody.indexOf('await afterPersist();'),);+ const tombstoneStart = source.indexOf('async function persistLogoutTombstoneOnly(');+ const tombstoneEnd = source.indexOf('\n}\n\nfunction metadataFromMembership', tombstoneStart);+ const tombstoneBody = source.slice(tombstoneStart, tombstoneEnd);+ expect(tombstoneBody).toContain("label: 'auth-account-logout-tombstone'");+ expect(tombstoneBody).toContain('readAuthAccountLogoutTombstones({ recoverInvalid: true })');+ expect(tombstoneBody).toContain('writeAuthAccountLogoutTombstones(vault)');+ expect(tombstoneBody).not.toContain('writeAuthAccountVaultOrThrow');+const reconcileStart = source.indexOf('async function reconcileDesktopActiveAuthSession()');const reconcileEnd = source.indexOf('\n}\n\nfunction readPersistedRefreshToken',@@ -521,8 +635,11 @@ describe('auth login-flow reset', () => {'\n}\n\n/**\n * Account refresh tokens',refreshCommitStart,);- expect(source.slice(refreshCommitStart, refreshCommitEnd)).toContain(- "typeof vault.signedOutAt !== 'number'",+ const refreshCommitBody = source.slice(refreshCommitStart, refreshCommitEnd);+ expect(refreshCommitBody).toContain("typeof vault.signedOutAt !== 'number'");+ expect(refreshCommitBody).toContain('!loggedOutAccountKeySet(vault).has(key)');+ expect(refreshCommitBody.indexOf('!loggedOutAccountKeySet(vault).has(key)')).toBeGreaterThan(+ refreshCommitBody.indexOf('options.allowUnclaimedVault === true'),);const resourceWriteStart = source.indexOf('function writeResourceSessionToVault(');@@ -533,6 +650,9 @@ describe('auth login-flow reset', () => {const resourceWriteBody = source.slice(resourceWriteStart, resourceWriteEnd);expect(resourceWriteBody).toContain('if (options.markActive !== false) {');expect(resourceWriteBody).toContain('delete vault.signedOutAt;');+ expect(resourceWriteBody).toContain(+ 'if (options.restoreLoggedOutAccount) restoreLoggedOutVaultAccount(vault, key);',+ );const loginCommitStart = source.indexOf('async function commitDesktopLoginSessions(');const loginCommitEnd = source.indexOf(@@ -542,18 +662,81 @@ describe('auth login-flow reset', () => {const loginCommitBody = source.slice(loginCommitStart, loginCommitEnd);expect(loginCommitBody).toContain('if (!input.passportId) {');expect(loginCommitBody).toContain('delete vault.signedOutAt;');+ expect(loginCommitBody).toContain('removeLoggedOutVaultAccount(vault, input.accountToLogOut)');const logoutStart = source.indexOf('export async function logout(): Promise<void> {');const logoutEnd = source.indexOf('\n}\n\n/**\n * Called on system resume', logoutStart);const logoutBody = source.slice(logoutStart, logoutEnd);- const tombstoneCommit = logoutBody.indexOf('await clearAuthAccountVault(() => {');+ const tombstoneCommit = logoutBody.indexOf('await mutateAuthAccountVault(');const ownerTeardown = logoutBody.indexOf('await withAccountFreeOwnerCommit({');expect(tombstoneCommit).toBeGreaterThan(-1);+ expect(logoutBody).toContain('savedVaultWasUnreadable');+ expect(logoutBody).toContain('await persistLogoutTombstoneOnly(currentIdentity.accountKey);');+ expect(logoutBody).not.toContain('clearAuthAccountVault((vault) => {');+ expect(logoutBody).toContain('savedVaultHasUnreadableLogoutTombstones');+ expect(logoutBody).toContain(+ 'const candidateAccountKeys = savedVaultHasUnreadableLogoutTombstones',+ );+ expect(logoutBody).toContain(+ 'replaceUnreadableLogoutTombstones: savedVaultHasUnreadableLogoutTombstones',+ );+ expect(logoutBody).toContain('removeLoggedOutVaultAccount(vault, currentIdentity)');+ expect(logoutBody).toContain('vault.signedOutAt = Date.now();');expect(logoutBody.indexOf('removeSafe(AUTH_SESSION_KEY);')).toBeGreaterThan(tombstoneCommit);expect(ownerTeardown).toBeGreaterThan(tombstoneCommit);expect(logoutBody).toContain('preservePersistedRefreshToken: true');});+ it('logs out only the current saved account and advances to the next restorable account', () => {+ expect(source).toContain('loggedOutAccountKeys?: string[];');++ const removalStart = logoutPolicySource.indexOf('export function removeLoggedOutVaultAccount<');+ const removalBody = logoutPolicySource.slice(removalStart);+ expect(removalBody).toContain('delete vault.resources[identity.accountKey];');+ expect(removalBody).toContain('loggedOutKeys.add(identity.accountKey);');+ expect(removalBody).toContain('const hasRestorableSibling =');+ expect(removalBody).toContain('if (hasRestorableSibling) return null;');+ expect(removalBody).toContain('delete vault.passports[passportKey];');++ const summariesStart = source.indexOf('function savedAccountSummaries(');+ const summariesEnd = source.indexOf('\n}\n\nexport function listSavedAccounts', summariesStart);+ const summariesBody = source.slice(summariesStart, summariesEnd);+ expect(summariesBody).toContain('const loggedOutKeys = loggedOutAccountKeySet(vault);');+ expect(summariesBody).toContain(+ 'if (!loggedOutKeys.has(key)) byKey.set(key, resource.metadata);',+ );+ expect(summariesBody).toContain('return rightUsed - leftUsed');++ const logoutStart = source.indexOf('export async function logout(): Promise<void> {');+ const logoutEnd = source.indexOf('\n}\n\n/**\n * Called on system resume', logoutStart);+ const logoutBody = source.slice(logoutStart, logoutEnd);+ const candidateLoop = logoutBody.indexOf(+ 'for (const candidateAccountKey of candidateAccountKeys)',+ );+ const terminalSignOut = logoutBody.indexOf('await mutateAuthAccountVault(');+ expect(candidateLoop).toBeGreaterThan(-1);+ expect(logoutBody).toContain('await switchSavedAccount(candidateAccountKey, {');+ expect(logoutBody).toContain('accountToLogOut: currentIdentity');+ expect(logoutBody).toContain('validateBeforeCommit: (loginEpoch) => {');+ expect(logoutBody).toContain('assertLogoutStillCurrent(loginEpoch);');+ expect(logoutBody).toContain('candidateTransitionEpoch = loginEpoch;');+ expect(logoutBody).toContain('assertLogoutTransitionStillCurrent(candidateTransitionEpoch);');+ expect(logoutBody).toContain('assertLogoutStillCurrent();');+ expect(logoutBody).toContain('if (isUnavailableSavedAccountError(error)) continue;');+ expect(logoutBody).toContain('isRetryableSavedAccountSwitchError(error)');+ const retryableSwitchStart = source.indexOf('function isRetryableSavedAccountSwitchError(');+ const retryableSwitchEnd = source.indexOf(+ '\n}\n\nfunction revokeLoggedOutAccountBestEffort',+ retryableSwitchStart,+ );+ const retryableSwitchBody = source.slice(retryableSwitchStart, retryableSwitchEnd);+ expect(retryableSwitchBody).toContain('error.statusCode === 429');+ expect(retryableSwitchBody).toContain("'RATE_LIMITED'");+ expect(logoutBody.indexOf('return;', candidateLoop)).toBeLessThan(terminalSignOut);+ expect(terminalSignOut).toBeGreaterThan(candidateLoop);+ expect(logoutBody).not.toContain('revokeSavedSessionsBestEffort');+ });+it('activates a restored realm only after the refreshed membership passes build policy', () => {const initializeStart = source.indexOf('export async function initialize(');const initializeEnd = source.indexOf('\n}\n\n/**\n * 冷启动 refresh 流程本体', initializeStart);@@ -607,6 +790,33 @@ describe('auth login-flow reset', () => {expect(refreshBody).toContain('preservePersistedRefreshToken: true');});+ it('retries the vault active account after a stale compatibility token fails on cold start', () => {+ const coldStart = source.indexOf('async function runColdStartRefreshFlow(');+ const coldStartEnd = source.indexOf('\n}\n\n/**\n * Called on system resume', coldStart);+ const coldStartBody = source.slice(coldStart, coldStartEnd);+ expect(coldStartBody).toContain(+ 'const nextActiveCandidate = readActiveVaultRefreshCandidate();',+ );+ expect(coldStartBody).toContain(+ 'cold-start refresh rejected a stale compatibility token; continuing with the vault active account',+ );+ expect(coldStartBody).toContain(+ 'expectedActiveVaultAccountKey: nextActiveCandidate.accountKey',+ );+ const clearDeadTokens = coldStartBody.indexOf('await clearConfirmedDeadRefreshTokens(');+ const staleEpochGuard = coldStartBody.indexOf(+ "epochChanged('after-clearing-confirmed-dead-tokens')",+ clearDeadTokens,+ );+ const ownershipRetry = coldStartBody.indexOf(+ 'return runColdStartRefreshFlow(',+ clearDeadTokens,+ );+ expect(clearDeadTokens).toBeGreaterThan(-1);+ expect(staleEpochGuard).toBeGreaterThan(clearDeadTokens);+ expect(ownershipRetry).toBeGreaterThan(staleEpochGuard);+ });+it('unlocks login preparing with the splash startup gate after 30s', () => {const loadStart = source.indexOf('async function loadLoginProviders(');const loadEnd = source.indexOf('\n}\n\nasync function discoverOrganizationRealm(', loadStart);diff --git a/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts b/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.tsindex b29b5a6f25..116be7ff1c 100644--- a/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts+++ b/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts@@ -63,10 +63,8 @@ describe('passive shared-userData instance auth isolation', () => {const preserveIdx = authSource.indexOf('preservePersistedRefreshToken: true', runtimeIdx);expect(preserveIdx).toBeGreaterThan(runtimeIdx);expect(authSource).toContain('let foreignDeviceLocalSignOut = false');- expect(authSource).toContain("foreignDeviceLocalSignOut = true");- expect(authSource).toContain(- "if (foreignDeviceLocalSignOut) {",- );+ expect(authSource).toContain('foreignDeviceLocalSignOut = true');+ expect(authSource).toContain('if (foreignDeviceLocalSignOut) {');});it('clearAuth:passive 共享实例不删磁盘 refresh token', () => {@@ -88,14 +86,19 @@ describe('passive shared-userData instance auth isolation', () => {expect(body.indexOf('removeSafe(LEGACY_REFRESH_TOKEN_KEY);')).toBeGreaterThan(passiveIdx);});- it('logout:passive 共享实例不调服务端登出(会连坐作废 primary 的 device token)', () => {+ it('logout:passive 共享实例不切号或调服务端登出(会连坐作废 primary 的 device token)', () => {const body = sliceBody('export async function logout(): Promise<void> {', '\n}\n');// refresh token 服务端按 (user, device) 一对一存,passive 与 primary 共用 deviceId:- // 只留本地文件不够,这一发也必须拦,否则 primary 下次续期拿确定性失败被踢。- expect(body).toContain('!isPassiveSharedUserDataInstance()');- const guardIdx = body.indexOf('!isPassiveSharedUserDataInstance()');- expect(body.indexOf("apiFetch('/api/auth/logout'")).toBeGreaterThan(guardIdx);+ // guard 必须在任何账号切换、凭证写入和服务端撤销之前直接拒绝。+ const guardIdx = body.indexOf('if (isPassiveSharedUserDataInstance()) {');+ expect(guardIdx).toBeGreaterThan(-1);+ expect(body.indexOf('await switchSavedAccount(')).toBeGreaterThan(guardIdx);+ expect(body.indexOf('await mutateAuthAccountVault(')).toBeGreaterThan(guardIdx);+ expect(body.indexOf('revokeLoggedOutAccountBestEffort({')).toBeGreaterThan(guardIdx);++ const revokeBody = sliceBody('function revokeLoggedOutAccountBestEffort(', '\n}\n');+ expect(revokeBody).toContain("apiFetch('/api/auth/logout'");});it('续期节奏不设闸门:passive 照常排 timer,否则 access token 过期后无自愈路径', () => {@@ -176,8 +179,13 @@ describe('passive shared-userData instance auth isolation', () => {);expect(migrationHelper).toContain('if (isPassiveSharedUserDataInstance()) return;');- const beforeEnsureReadyStart = bootstrapSource.indexOf('beforeEnsureReady: async (userId) => {');- const beforeEnsureReadyEnd = bootstrapSource.indexOf('\n },\n onReady:', beforeEnsureReadyStart);+ const beforeEnsureReadyStart = bootstrapSource.indexOf(+ 'beforeEnsureReady: async (userId) => {',+ );+ const beforeEnsureReadyEnd = bootstrapSource.indexOf(+ '\n },\n onReady:',+ beforeEnsureReadyStart,+ );const beforeEnsureReady = bootstrapSource.slice(beforeEnsureReadyStart, beforeEnsureReadyEnd);const dbPassiveGuard = beforeEnsureReady.indexOf('if (authManager.isPassiveSharedUserDataInstance()) {',@@ -204,9 +212,7 @@ describe('passive shared-userData instance auth isolation', () => {expect(beforeEnsureReady.indexOf('runLegacyUserDataMigrationForUser(user.id)')).toBeGreaterThan(dbPassiveGuard,);- expect(beforeEnsureReady.indexOf('adoptLocalProfileDatabase(')).toBeGreaterThan(- dbPassiveGuard,- );+ expect(beforeEnsureReady.indexOf('adoptLocalProfileDatabase(')).toBeGreaterThan(dbPassiveGuard);expect(exclusiveAdoptionGate).toBeGreaterThan(beforeEnsureReady.indexOf('adoptLocalProfileDatabase('),);@@ -305,7 +311,10 @@ describe('passive shared-userData instance auth isolation', () => {expect(acceptBody).not.toContain('commitWithClearedAccountDeletionReceipt(');const completeStart = authSource.indexOf('async function completeLogin(');- const completeEnd = authSource.indexOf('\n}\n\nasync function acceptLoginOutcome', completeStart);+ const completeEnd = authSource.indexOf(+ '\n}\n\nasync function acceptLoginOutcome',+ completeStart,+ );const completeBody = authSource.slice(completeStart, completeEnd);const completeGuard = completeBody.indexOf('if (!isPassiveSharedUserDataInstance()) {');expect(completeGuard).toBeGreaterThan(-1);@@ -319,9 +328,7 @@ describe('passive shared-userData instance auth isolation', () => {'function commitWithClearedAccountDeletionReceipt(commit: () => void): void {','\n}\n',);- expect(receiptCommit).toContain(- 'if (isPassiveSharedUserDataInstance()) return commit();',- );+ expect(receiptCommit).toContain('if (isPassiveSharedUserDataInstance()) return commit();');});it('冷启动确定性失效:passive 不删盘,非 passive 也只做 compare-and-delete', () => {diff --git a/apps/desktop/src/main/authAccountLogoutPolicy.ts b/apps/desktop/src/main/authAccountLogoutPolicy.tsnew file mode 100644index 0000000000..d397dd2e88--- /dev/null+++ b/apps/desktop/src/main/authAccountLogoutPolicy.ts@@ -0,0 +1,104 @@+import {+ accountVaultKey,+ passportVaultKey,+ type AuthRegion,+ type StoredAccountMetadata,+} from '@cindy/auth-client';++export interface LoggedOutAccountIdentity {+ accountKey: string;+ realm: AuthRegion;+ passportId: string;+}++interface LogoutPolicyResourceSession {+ realm: AuthRegion;+ metadata: StoredAccountMetadata;+}++interface LogoutPolicyPassportSession {+ realm: AuthRegion;+ passportId: string;+ memberships: StoredAccountMetadata[];+}++interface LogoutPolicyVault<+ TResource extends LogoutPolicyResourceSession,+ TPassport extends LogoutPolicyPassportSession,+> {+ activeAccountKey: string | null;+ resources: Record<string, TResource>;+ passports: Record<string, TPassport>;+ loggedOutAccountKeys?: string[];+}++export function loggedOutAccountKeySet(+ vault: { loggedOutAccountKeys?: string[] } & object,+): Set<string> {+ return new Set(vault.loggedOutAccountKeys ?? []);+}++export function isLoggedOutVaultAccount(+ vault: { loggedOutAccountKeys?: string[] } & object,+ accountKey: string,+): boolean {+ return loggedOutAccountKeySet(vault).has(accountKey);+}++export function restoreLoggedOutVaultAccount(+ vault: { loggedOutAccountKeys?: string[] } & object,+ accountKey: string,+): void {+ if (!vault.loggedOutAccountKeys?.includes(accountKey)) return;+ const remaining = vault.loggedOutAccountKeys.filter((key) => key !== accountKey);+ if (remaining.length > 0) {+ vault.loggedOutAccountKeys = remaining;+ } else {+ delete vault.loggedOutAccountKeys;+ }+}++/** Remove one saved membership while preserving credentials that can restore sibling memberships. */+export function removeLoggedOutVaultAccount<+ TResource extends LogoutPolicyResourceSession,+ TPassport extends LogoutPolicyPassportSession,+>(+ vault: LogoutPolicyVault<TResource, TPassport>,+ identity: LoggedOutAccountIdentity,+): TPassport | null {+ delete vault.resources[identity.accountKey];+ if (vault.activeAccountKey === identity.accountKey) vault.activeAccountKey = null;++ const loggedOutKeys = loggedOutAccountKeySet(vault);+ loggedOutKeys.add(identity.accountKey);+ vault.loggedOutAccountKeys = [...loggedOutKeys];++ const passportKey = passportVaultKey(identity.realm, identity.passportId);+ const passport = vault.passports[passportKey];+ if (!passport) return null;++ // Keep the legacy Passport projection downgrade-safe: older clients do not+ // understand loggedOutAccountKeys, so they must not find this membership in+ // the persisted membership list after a single-account logout.+ passport.memberships = passport.memberships.filter(+ (membership) =>+ accountVaultKey(identity.realm, membership.membershipId) !== identity.accountKey,+ );++ const hasRestorableSibling =+ passport.memberships.some((membership) => {+ const accountKey = accountVaultKey(identity.realm, membership.membershipId);+ return accountKey !== identity.accountKey && !loggedOutKeys.has(accountKey);+ }) ||+ Object.entries(vault.resources).some(+ ([accountKey, resource]) =>+ accountKey !== identity.accountKey &&+ resource.realm === identity.realm &&+ resource.metadata.passportId === identity.passportId &&+ !loggedOutKeys.has(accountKey),+ );+ if (hasRestorableSibling) return null;++ delete vault.passports[passportKey];+ return passport;+}diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.tsindex 0dc7a6faa5..6a91741ddb 100644--- a/apps/desktop/src/main/authManager.ts+++ b/apps/desktop/src/main/authManager.ts@@ -79,6 +79,13 @@ import {} from './authLoopbackCallback';import { createDesktopPollCredentials, runHostedCallbackPolling } from './authHostedCallback';import { reconcileSavedAccountMetadata, type StoredAccountMetadata } from './authAccountMetadata';+import {+ isLoggedOutVaultAccount,+ loggedOutAccountKeySet,+ removeLoggedOutVaultAccount,+ restoreLoggedOutVaultAccount,+ type LoggedOutAccountIdentity,+} from './authAccountLogoutPolicy';// dev-only 登录 scenario harness(implementation-plan Step 0 WHAT4):静态 import// (main 禁运行时动态 import),生产构建由 vite alias 把整模块替换为空 stub// (vite.main.config.ts),运行时另有 app.isPackaged guard 双保险。@@ -93,7 +100,7 @@ import {} from './authBoundaryQuarantine.js';import { buildFocusDeepLink } from './deepLink';import { getResolvedMainLocale, t } from './i18n';-import { atomicWriteFileSync } from './utils/atomicWriteFile.js';+import { atomicWriteFileSync, readAtomicFileSync } from './utils/atomicWriteFile.js';import {activateClientEndpointRealm,getClientEndpoint,@@ -186,6 +193,13 @@ function authServerUrl(realm: AuthRegion = activeAuthRealm): string {const AUTH_SESSION_KEY = 'cindy_auth_session_v1';const AUTH_ACCOUNT_VAULT_KEY = 'cindy_auth_accounts_v1';const AUTH_ACCOUNT_VAULT_LOCK_FILE = '.cindy-auth-accounts-v1.lock';+const AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY = 'cindy_auth_account_logout_tombstones_v1';+// The aggregate vault stays readable by v1 clients for explicit-login+// compatibility. Per-membership logout tombstones live in a separate key that+// older clients never read or rewrite, so their Passport sync cannot resurrect+// an account explicitly logged out by a newer client.+const AUTH_ACCOUNT_VAULT_VERSION = 2 as const;+const AUTH_ACCOUNT_LOGOUT_TOMBSTONES_VERSION = 1 as const;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';@@ -248,14 +262,16 @@ interface StoredPassportSession {}interface AuthAccountVault {- version: 1;+ version: typeof AUTH_ACCOUNT_VAULT_VERSION;activeAccountKey: string | null;resources: Record<string, StoredResourceSession>;passports: Record<string, StoredPassportSession>;+ /** Memberships explicitly logged out on this device stay hidden until a fresh login restores them. */+ loggedOutAccountKeys?: string[];/**- * Durable logout-all marker. The vault is the crash-consistent owner record,- * so this must win over a compatibility session left behind by an interrupted- * logout until a new explicit login commits an active Resource.+ * Durable signed-out owner marker. The vault is the crash-consistent owner+ * record, so this must win over a compatibility session left behind by an+ * interrupted logout until another account is explicitly activated.*/signedOutAt?: number;}@@ -588,6 +604,32 @@ function readAtomicSafe(key: string): string | null {}}+/**+ * Keep an unreadable encrypted record available for an explicit replacement+ * to roll back to. The payload is still ciphertext; it is never parsed or+ * exposed to the renderer.+ */+function readAtomicSafeCiphertext(key: string): string | null {+ try {+ if (!safeStorage.isEncryptionAvailable()) return null;+ return readAtomicFileSync(path.join(SAFE_STORAGE_DIR(), `${key}.enc`));+ } catch (err) {+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return null;+ logSafeStorageIssueOnce('atomic ciphertext snapshot failed', key, err);+ return null;+ }+}++function writeAtomicSafeCiphertext(key: string, ciphertext: string): boolean {+ try {+ atomicWriteFileSync(path.join(SAFE_STORAGE_DIR(), `${key}.enc`), ciphertext);+ return true;+ } catch (err) {+ logSafeStorageIssueOnce('atomic ciphertext restore failed', key, err);+ return false;+ }+}+function isAtomicPersistedSecretAbsent(key: string): boolean {if (!safeStorage.isEncryptionAvailable()) return false;const filepath = path.join(SAFE_STORAGE_DIR(), `${key}.enc`);@@ -717,7 +759,72 @@ function commitWithClearedAccountDeletionReceipt(commit: () => void): void {}function emptyAuthAccountVault(): AuthAccountVault {- return { version: 1, activeAccountKey: null, resources: {}, passports: {} };+ return {+ version: AUTH_ACCOUNT_VAULT_VERSION,+ activeAccountKey: null,+ resources: {},+ passports: {},+ };+}++function readAuthAccountLogoutTombstones(options: { recoverInvalid?: boolean } = {}): string[] {+ const raw = readAtomicSafe(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY);+ if (raw === null) {+ if (isAtomicPersistedSecretAbsent(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY)) return [];+ log.warn('encrypted auth logout tombstones are temporarily unreadable');+ if (options.recoverInvalid) return [];+ throw new AuthApiError(+ 'CREDENTIAL_STORE_UNAVAILABLE',+ 503,+ 'Saved account logout state is temporarily unavailable',+ );+ }+ try {+ const parsed = JSON.parse(raw) as {+ version?: unknown;+ accountKeys?: unknown;+ };+ if (+ parsed.version !== AUTH_ACCOUNT_LOGOUT_TOMBSTONES_VERSION ||+ !Array.isArray(parsed.accountKeys)+ ) {+ throw new Error('unsupported auth logout tombstones');+ }+ const accountKeys = parsed.accountKeys.filter(+ (key): key is string => parseDesktopAccountKey(key) !== null,+ );+ if (accountKeys.length !== parsed.accountKeys.length) {+ throw new Error('invalid auth logout tombstone key');+ }+ return [...new Set(accountKeys)];+ } catch (error) {+ log.warn(+ 'encrypted auth logout tombstones are invalid; refusing to read saved accounts',+ error,+ );+ if (options.recoverInvalid) return [];+ throw new AuthApiError(+ 'CREDENTIAL_STORE_UNAVAILABLE',+ 503,+ 'Saved account logout state could not be read safely',+ );+ }+}++function writeAuthAccountLogoutTombstones(vault: AuthAccountVault): boolean {+ const accountKeys = [...new Set(vault.loggedOutAccountKeys ?? [])];+ if (accountKeys.length === 0) {+ try {+ removeAtomicSafeOrThrow(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY);+ return true;+ } catch {+ return false;+ }+ }+ return writeAtomicSafe(+ AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY,+ JSON.stringify({ version: AUTH_ACCOUNT_LOGOUT_TOMBSTONES_VERSION, accountKeys }),+ );}function accountVaultKey(realm: AuthRegion, membershipId: string): string {@@ -746,11 +853,35 @@ function isStoredAccountMetadata(value: unknown): value is StoredAccountMetadata}function readAuthAccountVault(- options: { allowUnreadable?: boolean; recoverInvalid?: boolean } = {},+ options: {+ allowUnreadable?: boolean;+ recoverInvalid?: boolean;+ allowUnreadableLogoutTombstones?: boolean;+ } = {},): AuthAccountVault {+ let persistedLogoutKeys: string[];+ try {+ persistedLogoutKeys = readAuthAccountLogoutTombstones({+ recoverInvalid: options.recoverInvalid,+ });+ } catch (error) {+ if (options.allowUnreadableLogoutTombstones) {+ // An explicit logout may replace the damaged tombstone record, but must+ // retain every still-readable account in the aggregate vault.+ persistedLogoutKeys = [];+ } else if (options.allowUnreadable) {+ return emptyAuthAccountVault();+ } else {+ throw error;+ }+ }const raw = readAtomicSafe(AUTH_ACCOUNT_VAULT_KEY);if (raw === null) {- if (isAtomicPersistedSecretAbsent(AUTH_ACCOUNT_VAULT_KEY)) return emptyAuthAccountVault();+ if (isAtomicPersistedSecretAbsent(AUTH_ACCOUNT_VAULT_KEY)) {+ return persistedLogoutKeys.length > 0+ ? { ...emptyAuthAccountVault(), loggedOutAccountKeys: persistedLogoutKeys }+ : emptyAuthAccountVault();+ }log.warn('encrypted auth account vault exists but is temporarily unreadable');if (options.allowUnreadable) return emptyAuthAccountVault();throw new AuthApiError(@@ -761,14 +892,16 @@ function readAuthAccountVault(}try {const parsed = JSON.parse(raw) as Partial<AuthAccountVault>;+ const persistedVersion = (parsed as { version?: unknown }).version;if (- parsed.version !== 1 ||+ (persistedVersion !== 1 && persistedVersion !== AUTH_ACCOUNT_VAULT_VERSION) ||!parsed.resources ||typeof parsed.resources !== 'object' ||Array.isArray(parsed.resources) ||!parsed.passports ||typeof parsed.passports !== 'object' ||Array.isArray(parsed.passports) ||+ (parsed.loggedOutAccountKeys !== undefined && !Array.isArray(parsed.loggedOutAccountKeys)) ||(parsed.signedOutAt !== undefined && typeof parsed.signedOutAt !== 'number')) {throw new Error('unsupported auth account vault');@@ -822,18 +955,37 @@ function readAuthAccountVault(memberships,};}+ const embeddedLogoutKeys = (parsed.loggedOutAccountKeys ?? []).filter(+ (key): key is string => parseDesktopAccountKey(key) !== null,+ );+ if (+ !options.allowUnreadable &&+ !options.recoverInvalid &&+ embeddedLogoutKeys.length !== (parsed.loggedOutAccountKeys?.length ?? 0)+ ) {+ throw new Error('invalid logged-out account key');+ }+ const loggedOutKeys = new Set([...persistedLogoutKeys, ...embeddedLogoutKeys]);const active = typeof parsed.activeAccountKey === 'string' ? parsed.activeAccountKey : null;+ // Never infer an explicit restore from an active Resource projection: a+ // crash between the tombstone write and aggregate replacement can leave+ // that projection stale. Only an explicit login transaction may clear a+ // logout tombstone.+ const loggedOutAccountKeys = [...loggedOutKeys];return {- version: 1,- activeAccountKey: active && resources[active] ? active : null,+ version: AUTH_ACCOUNT_VAULT_VERSION,+ activeAccountKey: active && resources[active] && !loggedOutKeys.has(active) ? active : null,resources,passports,+ ...(loggedOutAccountKeys.length > 0 ? { loggedOutAccountKeys } : {}),...(typeof parsed.signedOutAt === 'number' ? { signedOutAt: parsed.signedOutAt } : {}),};} catch (error) {if (options.recoverInvalid) {log.warn('encrypted auth account vault is invalid; recovering it for explicit login', error);- return emptyAuthAccountVault();+ return persistedLogoutKeys.length > 0+ ? { ...emptyAuthAccountVault(), loggedOutAccountKeys: persistedLogoutKeys }+ : emptyAuthAccountVault();}log.warn('encrypted auth account vault is invalid; ignoring it without deleting', error);if (options.allowUnreadable) return emptyAuthAccountVault();@@ -845,12 +997,61 @@ function readAuthAccountVault(}}-function writeAuthAccountVault(vault: AuthAccountVault): boolean {- return writeAtomicSafe(AUTH_ACCOUNT_VAULT_KEY, JSON.stringify(vault));+function writeAuthAccountVault(+ vault: AuthAccountVault,+ options: { replaceUnreadableLogoutTombstones?: boolean } = {},+): boolean {+ const previousLogoutRaw = readAtomicSafe(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY);+ const previousLogoutWasAbsent =+ previousLogoutRaw === null && isAtomicPersistedSecretAbsent(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY);+ const previousLogoutUnreadable = previousLogoutRaw === null && !previousLogoutWasAbsent;+ const previousLogoutCiphertext = previousLogoutUnreadable+ ? readAtomicSafeCiphertext(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY)+ : null;+ if (+ previousLogoutUnreadable &&+ (!options.replaceUnreadableLogoutTombstones || previousLogoutCiphertext === null)+ ) {+ return false;+ }+ // Persist the tombstone before the legacy-compatible aggregate. If the+ // process stops between these writes, a new client fails closed instead of+ // briefly re-enumerating an account that was explicitly logged out.+ if (!writeAuthAccountLogoutTombstones(vault)) return false;+ // Keep the aggregate payload at the legacy version so an older client can+ // still recover an explicit login without discarding the other saved+ // accounts. New clients continue to read the optional logout tombstones,+ // while logout removes the signed-out membership from the stored Passport+ // projection so older clients cannot enumerate it from local data.+ if (writeAtomicSafe(AUTH_ACCOUNT_VAULT_KEY, JSON.stringify({ ...vault, version: 1 }))) {+ return true;+ }+ try {+ if (previousLogoutWasAbsent) {+ removeAtomicSafeOrThrow(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY);+ } else if (+ previousLogoutRaw !== null &&+ !writeAtomicSafe(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY, previousLogoutRaw)+ ) {+ log.warn('failed to restore auth logout tombstones after vault write failure');+ } else if (+ previousLogoutUnreadable &&+ previousLogoutCiphertext !== null &&+ !writeAtomicSafeCiphertext(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY, previousLogoutCiphertext)+ ) {+ log.warn('failed to restore unreadable auth logout tombstones after vault write failure');+ }+ } catch (error) {+ log.warn('failed to restore auth logout tombstones after vault write failure', error);+ }+ return false;}-function writeAuthAccountVaultOrThrow(vault: AuthAccountVault): void {- if (writeAuthAccountVault(vault)) return;+function writeAuthAccountVaultOrThrow(+ vault: AuthAccountVault,+ options: { replaceUnreadableLogoutTombstones?: boolean } = {},+): void {+ if (writeAuthAccountVault(vault, options)) return;throw new AuthApiError('CREDENTIAL_STORE_UNAVAILABLE',503,@@ -881,6 +1082,8 @@ async function transactAuthAccountVault<T>(afterPersist: (result: T) => void | Promise<void> = () => undefined,options: {recoverInvalidForExplicitLogin?: boolean;+ allowUnreadableLogoutTombstones?: boolean;+ replaceUnreadableLogoutTombstones?: boolean;waitWhileBusyAfterRotation?: boolean;} = {},): Promise<T> {@@ -900,11 +1103,23 @@ async function transactAuthAccountVault<T>(const previousRaw = readAtomicSafe(AUTH_ACCOUNT_VAULT_KEY);const previousWasAbsent =previousRaw === null && isAtomicPersistedSecretAbsent(AUTH_ACCOUNT_VAULT_KEY);+ const previousLogoutRaw = readAtomicSafe(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY);+ const previousLogoutWasAbsent =+ previousLogoutRaw === null &&+ isAtomicPersistedSecretAbsent(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY);+ const previousLogoutUnreadable = previousLogoutRaw === null && !previousLogoutWasAbsent;+ const previousLogoutCiphertext = previousLogoutUnreadable+ ? readAtomicSafeCiphertext(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY)+ : null;const vault = readAuthAccountVault({recoverInvalid: options.recoverInvalidForExplicitLogin,+ allowUnreadableLogoutTombstones: options.allowUnreadableLogoutTombstones,});const result = await operation(vault);- writeAuthAccountVaultOrThrow(vault);+ writeAuthAccountVaultOrThrow(vault, {+ replaceUnreadableLogoutTombstones:+ options.replaceUnreadableLogoutTombstones || options.recoverInvalidForExplicitLogin,+ });try {// Keep the shared-userData lock through the active-session write,// runtime teardown and final owner commit. Cancellation or any local@@ -925,6 +1140,28 @@ async function transactAuthAccountVault<T>('Could not restore saved account credentials after a failed account switch',);}+ if (previousLogoutWasAbsent) {+ removeAtomicSafeOrThrow(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY);+ } else if (+ previousLogoutRaw !== null &&+ !writeAtomicSafe(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY, previousLogoutRaw)+ ) {+ throw new AuthApiError(+ 'CREDENTIAL_STORE_UNAVAILABLE',+ 503,+ 'Could not restore saved account logout state after a failed account switch',+ );+ } else if (+ previousLogoutUnreadable &&+ previousLogoutCiphertext !== null &&+ !writeAtomicSafeCiphertext(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY, previousLogoutCiphertext)+ ) {+ throw new AuthApiError(+ 'CREDENTIAL_STORE_UNAVAILABLE',+ 503,+ 'Could not restore unreadable account logout state after a failed account switch',+ );+ }throw error;}},@@ -943,12 +1180,17 @@ async function transactAuthAccountVault<T>(async function mutateAuthAccountVault<T>(operation: (vault: AuthAccountVault) => T | Promise<T>,- options: { waitWhileBusyAfterRotation?: boolean } = {},+ options: {+ allowUnreadableLogoutTombstones?: boolean;+ replaceUnreadableLogoutTombstones?: boolean;+ waitWhileBusyAfterRotation?: boolean;+ } = {},): Promise<T> {return transactAuthAccountVault(operation, () => undefined, options);}async function clearAuthAccountVault(+ customize: (vault: AuthAccountVault) => void = () => undefined,afterPersist: () => void | Promise<void> = () => undefined,): Promise<void> {await withCrossProcessLock(@@ -964,12 +1206,39 @@ async function clearAuthAccountVault(vault.resources = {};vault.passports = {};vault.signedOutAt = Date.now();- writeAuthAccountVaultOrThrow(vault);+ customize(vault);+ writeAuthAccountVaultOrThrow(vault, { replaceUnreadableLogoutTombstones: true });await afterPersist();},);}+/**+ * Persist an explicit logout tombstone without replacing an aggregate vault+ * whose ciphertext cannot currently be decrypted. The opaque vault remains+ * available for a later retry or recovery, while the new client still fails+ * closed for the account being logged out.+ */+async function persistLogoutTombstoneOnly(accountKey: string): Promise<void> {+ await withCrossProcessLock(+ authAccountVaultLockPath(),+ { label: 'auth-account-logout-tombstone', waitMs: 5_000 },+ async (status) => {+ if (!status.held) throw accountVaultLockError(status.reason);+ const existingKeys = readAuthAccountLogoutTombstones({ recoverInvalid: true });+ const vault = emptyAuthAccountVault();+ vault.loggedOutAccountKeys = [...new Set([...existingKeys, accountKey])];+ if (!writeAuthAccountLogoutTombstones(vault)) {+ throw new AuthApiError(+ 'CREDENTIAL_STORE_UNAVAILABLE',+ 503,+ 'Could not persist saved account logout state',+ );+ }+ },+ );+}+function metadataFromMembership(membership: AuthMembership | AccountMembership,passportId: string,@@ -1062,9 +1331,14 @@ function writeResourceSessionToVault(pair: AuthTokenPair,realm: AuthRegion,passportId: string,- options: { markActive?: boolean; lastUsedAt?: number } = {},+ options: {+ markActive?: boolean;+ lastUsedAt?: number;+ restoreLoggedOutAccount?: boolean;+ } = {},): void {const key = accountVaultKey(realm, pair.membership.id);+ if (options.restoreLoggedOutAccount) restoreLoggedOutVaultAccount(vault, key);vault.resources[key] = {realm,refreshToken: pair.refreshToken,@@ -1099,11 +1373,16 @@ function writePassportSessionToVault(): void {const key = passportVaultKey(input.realm, input.passportId);const previous = vault.passports[key];- const memberships = (input.memberships ?? previous?.memberships ?? []).map((membership) =>- isStoredAccountMetadata(membership)- ? membership- : metadataFromMembership(membership, input.passportId),- );+ const loggedOutKeys = loggedOutAccountKeySet(vault);+ const memberships = (input.memberships ?? previous?.memberships ?? [])+ .map((membership) =>+ isStoredAccountMetadata(membership)+ ? membership+ : metadataFromMembership(membership, input.passportId),+ )+ .filter(+ (membership) => !loggedOutKeys.has(accountVaultKey(input.realm, membership.membershipId)),+ );vault.passports[key] = {realm: input.realm,passportId: input.passportId,@@ -1125,6 +1404,9 @@ async function commitDesktopLoginSessions(passportId?: string;accountRefreshToken?: string | null;memberships: readonly (AuthMembership | AccountMembership | StoredAccountMetadata)[];+ restoreLoggedOutAccount?: boolean;+ accountToLogOut?: LoggedOutAccountIdentity;+ onLoggedOutPassportRemoved?: (session: StoredPassportSession) => void;},transition: {commit: () => void | Promise<void>;@@ -1133,14 +1415,27 @@ async function commitDesktopLoginSessions(): Promise<void> {await transactAuthAccountVault((vault) => {+ const targetAccountKey = accountVaultKey(input.realm, input.pair.membership.id);+ if (input.accountToLogOut?.accountKey === targetAccountKey) {+ throw new AuthApiError(+ 'INVALID_AUTH_ACTION',+ 400,+ 'Cannot activate and log out the same saved account',+ );+ }if (!input.passportId) {// Legacy login responses may only be able to persist the compatibility// session. They are still an explicit login and must supersede a prior- // logout-all tombstone so cold start can migrate the Resource later.+ // signed-out marker so cold start can migrate the Resource later.+ if (input.restoreLoggedOutAccount) {+ restoreLoggedOutVaultAccount(vault, targetAccountKey);+ }delete vault.signedOutAt;return;}- writeResourceSessionToVault(vault, input.pair, input.realm, input.passportId);+ writeResourceSessionToVault(vault, input.pair, input.realm, input.passportId, {+ restoreLoggedOutAccount: input.restoreLoggedOutAccount,+ });if (input.accountRefreshToken) {writePassportSessionToVault(vault, {realm: input.realm,@@ -1149,6 +1444,10 @@ async function commitDesktopLoginSessions(memberships: input.memberships,});}+ if (input.accountToLogOut) {+ const removedPassport = removeLoggedOutVaultAccount(vault, input.accountToLogOut);+ if (removedPassport) input.onLoggedOutPassportRemoved?.(removedPassport);+ }},async () => {try {@@ -1260,7 +1559,8 @@ async function commitDesktopRefreshCredentials(options.allowUnclaimedVault === true &&vault.activeAccountKey === null &&typeof vault.signedOutAt !== 'number' &&- Object.keys(vault.resources).length === 0;+ Object.keys(vault.resources).length === 0 &&+ !loggedOutAccountKeySet(vault).has(key);const stillOwnsActiveSession =requestedTokenStillStored && (vault.activeAccountKey === key || canClaimUninitializedVault);const passportId = pair.membership.passportId;@@ -1522,7 +1822,7 @@ async function reconcileDesktopActiveAuthSession(): Promise<const vault = readAuthAccountVault();const session = readPersistedAuthSession();if (typeof vault.signedOutAt === 'number') {- // Logout-all persists this owner tombstone before removing the+ // Account logout persists this owner tombstone before removing the// compatibility projection. If the process stopped between those// writes, finish the projection cleanup without ever refreshing it.removeSafe(AUTH_SESSION_KEY);@@ -3503,28 +3803,38 @@ function accountSummaryFromMetadata(};}-export function listSavedAccounts(): DesktopAccountSwitcherSnapshot {- const vault = readAuthAccountVault({ allowUnreadable: true });+function savedAccountSummaries(+ vault: AuthAccountVault,+ activeAccountKey: string | null,+): DesktopSavedAccount[] {+ const loggedOutKeys = loggedOutAccountKeySet(vault);const byKey = new Map<string, StoredAccountMetadata>();for (const [key, resource] of Object.entries(vault.resources)) {- byKey.set(key, resource.metadata);+ if (!loggedOutKeys.has(key)) 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);+ if (!loggedOutKeys.has(key) && !byKey.has(key)) byKey.set(key, membership);}}- const activeKey = currentUser ? accountVaultKey(activeAuthRealm, currentUser.id) : null;- const accounts = [...byKey.entries()]- .map(([key, metadata]) => accountSummaryFromMetadata(key, metadata, activeKey))+ return [...byKey.entries()]+ .map(([key, metadata]) => accountSummaryFromMetadata(key, metadata, activeAccountKey)).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 function listSavedAccounts(): DesktopAccountSwitcherSnapshot {+ const vault = readAuthAccountVault({ allowUnreadable: true });+ const activeKey = currentUser ? accountVaultKey(activeAuthRealm, currentUser.id) : null;+ return {+ accounts: savedAccountSummaries(vault, activeKey),+ mutationAllowed: !isPassiveSharedUserDataInstance(),+ };}export async function syncSavedAccounts(): Promise<DesktopAccountSwitcherSnapshot> {@@ -3558,7 +3868,14 @@ export async function syncSavedAccounts(): Promise<DesktopAccountSwitcherSnapshoreturn listSavedAccounts();}-export async function switchSavedAccount(rawAccountKey: unknown): Promise<void> {+export async function switchSavedAccount(+ rawAccountKey: unknown,+ options: {+ accountToLogOut?: LoggedOutAccountIdentity;+ onLoggedOutPassportRemoved?: (session: StoredPassportSession) => void;+ validateBeforeCommit?: (loginEpoch: number) => void;+ } = {},+): Promise<void> {const switchLoginFlowEpoch = loginFlowEpoch;const parsedKey = parseDesktopAccountKey(rawAccountKey);if (!parsedKey) throw new AuthApiError('INVALID_AUTH_ACTION', 400, 'Invalid account key');@@ -3572,6 +3889,9 @@ export async function switchSavedAccount(rawAccountKey: unknown): Promise<void>if (currentUser && parsedKey === accountVaultKey(activeAuthRealm, currentUser.id)) return;let vault = readAuthAccountVault();+ if (isLoggedOutVaultAccount(vault, parsedKey)) {+ throw new AuthApiError('ACCOUNT_NOT_FOUND', 404, 'Saved account was logged out');+ }let resource: StoredResourceSession | undefined = vault.resources[parsedKey];let metadata = resource?.metadata;if (!metadata) {@@ -3647,7 +3967,12 @@ export async function switchSavedAccount(rawAccountKey: unknown): Promise<void>pendingAccountRefreshToken = null;pendingAccountMemberships = [];try {- await completeLogin({ status: 'ok', ...pair }, switchLoginFlowEpoch);+ await completeLogin({ status: 'ok', ...pair }, switchLoginFlowEpoch, {+ restoreLoggedOutAccount: false,+ accountToLogOut: options.accountToLogOut,+ onLoggedOutPassportRemoved: options.onLoggedOutPassportRemoved,+ validateBeforeCommit: options.validateBeforeCommit,+ });} catch (error) {pendingAuthRealm = null;throw error;@@ -4314,6 +4639,41 @@ async function runColdStartRefreshFlow(const action: RefreshFailureAction = failureAction ?? { kind: 'transient-failure' };if (action.kind === 'definitive-failure') {lastAcceptedRefreshToken = null;+ const confirmedDeadTokens = rejectedTokens.length > 0 ? rejectedTokens : [storedToken];+ const nextActiveCandidate = readActiveVaultRefreshCandidate();+ const hopsRemaining = ownershipRecovery.hopsRemaining ?? 3;+ if (+ nextActiveCandidate &&+ hopsRemaining > 0 &&+ !attemptedOwnershipTokens.has(nextActiveCandidate.refreshToken)+ ) {+ // A crash can leave the compatibility projection on the previous+ // account after the vault has already committed a switch. Never let+ // the stale projection win cold start: discard only the rejected+ // token(s), then retry the vault's active account.+ if (isPassiveSharedUserDataInstance()) {+ log.warn(+ 'cold-start refresh: passive shared-userData instance keeps rejected compatibility tokens while retrying the vault active account',+ );+ } else {+ await clearConfirmedDeadRefreshTokens(storedRealm, confirmedDeadTokens);+ if (epochChanged('after-clearing-confirmed-dead-tokens')) {+ return snapshotAuthState();+ }+ }+ log.info(+ 'cold-start refresh rejected a stale compatibility token; continuing with the vault active account',+ );+ return runColdStartRefreshFlow(+ nextActiveCandidate.refreshToken,+ nextActiveCandidate.realm,+ {+ attemptedTokens: attemptedOwnershipTokens,+ expectedActiveVaultAccountKey: nextActiveCandidate.accountKey,+ hopsRemaining: hopsRemaining - 1,+ },+ );+ }if (isPassiveSharedUserDataInstance()) {// passive 只对本进程判定失效:磁盘 token 是整机共用的,而 passive 冷启动拿到// INVALID_REFRESH_TOKEN 最常见的原因恰恰是 primary 刚轮换过它。删掉就是把@@ -4326,7 +4686,6 @@ async function runColdStartRefreshFlow(// 来源追赶过(replacement-retry),磁盘上现存的就是清单里较晚的那一枚,只拿最初// 的 token 做 compare-and-delete 会一律 changed,把已确认失效的凭证留在盘上,// 只读 legacy 的旧版实例继续拿它撞 INVALID_REFRESH_TOKEN 被强制重登。- const confirmedDeadTokens = rejectedTokens.length > 0 ? rejectedTokens : [storedToken];await clearConfirmedDeadRefreshTokens(storedRealm, confirmedDeadTokens);}resetActiveAuthRealmToBuild();@@ -4561,6 +4920,12 @@ export async function getLoginState(): Promise<DesktopLoginActionResult> {async function completeLogin(outcome: Extract<LoginOutcome, { status: 'ok' }>,expectedLoginFlowEpoch = loginFlowEpoch,+ options: {+ restoreLoggedOutAccount?: boolean;+ accountToLogOut?: LoggedOutAccountIdentity;+ onLoggedOutPassportRemoved?: (session: StoredPassportSession) => void;+ validateBeforeCommit?: (loginEpoch: number) => void;+ } = {},): Promise<AuthFlowState> {assertLoginFlowCurrent(expectedLoginFlowEpoch);const loginEpoch = ++authStateEpoch;@@ -4593,6 +4958,9 @@ async function completeLogin(accountRefreshToken,memberships:pendingAccountMemberships.length > 0 ? pendingAccountMemberships : [outcome.membership],+ restoreLoggedOutAccount: options.restoreLoggedOutAccount ?? true,+ accountToLogOut: options.accountToLogOut,+ onLoggedOutPassportRemoved: options.onLoggedOutPassportRemoved,},{commit: async () => {@@ -4601,6 +4969,7 @@ async function completeLogin(// Any cancellation before commit restores both durable records while// the cross-process vault lock is still held.assertTransitionCurrent();+ options.validateBeforeCommit?.(loginEpoch);// Capture the compatibility session only after entering the same// cross-process ownership window as the vault write. A concurrent// passive refresh may have rotated it while this login waited on the@@ -5397,30 +5766,54 @@ export async function refresh(): Promise<boolean> {}}-function revokeSavedSessionsBestEffort(- vault: AuthAccountVault,- currentAccountKey: string | null,-): void {+function isUnavailableSavedAccountError(error: unknown): boolean {+ return (+ error instanceof AuthApiError &&+ (isDefinitiveRefreshError(error) ||+ ['ACCOUNT_NOT_FOUND', 'ACCOUNT_REAUTH_REQUIRED', 'REGION_MISMATCH'].includes(error.code))+ );+}++function isRetryableSavedAccountSwitchError(error: unknown): boolean {+ if (!(error instanceof AuthApiError)) return false;+ if (error.code === 'CREDENTIAL_STORE_UNAVAILABLE' || error.code === 'AUTH_FLOW_SUPERSEDED') {+ return false;+ }+ return (+ error.statusCode >= 500 ||+ error.statusCode === 429 ||+ [+ 'NETWORK_ERROR',+ 'REQUEST_TIMEOUT',+ 'INVALID_RESPONSE',+ 'ORG_REALM_UNAVAILABLE',+ 'RATE_LIMITED',+ ].includes(error.code)+ );+}++function revokeLoggedOutAccountBestEffort(input: {+ accessToken: string | null;+ authBaseUrl: string;+ passport: StoredPassportSession | 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.- }+ if (input.accessToken) {+ apiFetch('/api/auth/logout', {+ method: 'POST',+ body: { deviceId },+ token: input.accessToken,+ baseUrl: input.authBaseUrl,+ }).catch(() => {});}- for (const session of Object.values(vault.passports)) {+ if (input.passport) {try {- await loadClientEndpointsForRealm(session.realm);- const client = createAuthClient(session.realm);- const pair = await client.refreshAccount(session.accountRefreshToken);+ await loadClientEndpointsForRealm(input.passport.realm);+ const client = createAuthClient(input.passport.realm);+ const pair = await client.refreshAccount(input.passport.accountRefreshToken);await client.logoutAccount(pair.accountToken);} catch {- // Best effort for the same reason as resource logout above.+ // Logout is local-first. Offline/expired remote sessions age out normally.}}})();@@ -5431,26 +5824,142 @@ export async function logout(): Promise<void> {throw new AuthApiError('PASSIVE_AUTH_MUTATION_BLOCKED',409,- 'This shared-data instance cannot log out all accounts',+ 'This shared-data instance cannot log out the current account',);}const currentAccessToken = accessToken;- const currentAuthBaseUrl = authServerUrl(activeAuthRealm);- // Logout remains available even if the vault cannot be decrypted: local- // credential files are removed directly and remote revocation is best effort.- const savedVault = readAuthAccountVault({ allowUnreadable: true });- const currentAccountKey = currentUser- ? accountVaultKey(activeAuthRealm, currentUser.id)- : savedVault.activeAccountKey;- await clearAuthAccountVault(() => {- // Publish the durable signed-out owner before clearing compatibility- // records. The vault lock remains held across both writes, and startup- // reconciliation completes this cleanup if the process dies in between.- removeSafe(AUTH_SESSION_KEY);- removeSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY);- removeSafe(LEGACY_ACCOUNT_REFRESH_TOKEN_KEY);- removeSafe(LEGACY_REFRESH_TOKEN_KEY);- });+ const currentAuthRealm = activeAuthRealm;+ const currentAuthBaseUrl = authServerUrl(currentAuthRealm);+ const activeUser = currentUser;+ if (!activeUser) {+ throw new AuthApiError('UNAUTHENTICATED', 401, 'No current account to log out');+ }+ const logoutAuthEpoch = authStateEpoch;+ const isLogoutStillCurrent = (expectedAuthEpoch = logoutAuthEpoch): boolean =>+ authStateEpoch === expectedAuthEpoch &&+ currentUser?.id === activeUser.id &&+ activeAuthRealm === currentAuthRealm;+ const assertLogoutStillCurrent = (expectedAuthEpoch = logoutAuthEpoch): void => {+ if (isLogoutStillCurrent(expectedAuthEpoch)) return;+ throw new AuthApiError(+ 'AUTH_FLOW_SUPERSEDED',+ 409,+ 'Logout was superseded by a newer auth action',+ );+ };+ const assertLogoutTransitionStillCurrent = (expectedAuthEpoch: number): void => {+ if (authStateEpoch === expectedAuthEpoch) return;+ throw new AuthApiError(+ 'AUTH_FLOW_SUPERSEDED',+ 409,+ 'Logout was superseded by a newer auth action',+ );+ };++ let savedVault: AuthAccountVault;+ let savedVaultWasUnreadable = false;+ let savedVaultHasUnreadableLogoutTombstones = false;+ try {+ savedVault = readAuthAccountVault();+ } catch (error) {+ if (!(error instanceof AuthApiError && error.code === 'CREDENTIAL_STORE_UNAVAILABLE')) {+ throw error;+ }+ try {+ // A damaged tombstone must not make logout discard an otherwise readable+ // aggregate vault. The explicit action below replaces that tombstone+ // while retaining every other saved account.+ savedVault = readAuthAccountVault({ allowUnreadableLogoutTombstones: true });+ savedVaultHasUnreadableLogoutTombstones = true;+ } catch {+ // The active in-memory session is still authoritative for this explicit+ // user action. Replace an unreadable vault with a fresh fail-closed record+ // below instead of making logout depend on decrypting stale saved accounts.+ savedVault = emptyAuthAccountVault();+ savedVaultWasUnreadable = true;+ }+ }+ const currentAccountKey = accountVaultKey(currentAuthRealm, activeUser.id);+ const currentIdentity: LoggedOutAccountIdentity = {+ accountKey: currentAccountKey,+ realm: currentAuthRealm,+ passportId:+ activeUser.passportId || savedVault.resources[currentAccountKey]?.metadata.passportId || '',+ };+ const candidateAccountKeys = savedVaultHasUnreadableLogoutTombstones+ ? []+ : savedAccountSummaries(savedVault, currentAccountKey)+ .filter((account) => account.accountKey !== currentAccountKey)+ .map((account) => account.accountKey);+ let removedPassport: StoredPassportSession | null = null;++ for (const candidateAccountKey of candidateAccountKeys) {+ assertLogoutStillCurrent();+ let candidateRemovedPassport: StoredPassportSession | null = null;+ let candidateTransitionEpoch: number | null = null;+ try {+ await switchSavedAccount(candidateAccountKey, {+ accountToLogOut: currentIdentity,+ onLoggedOutPassportRemoved: (session) => {+ candidateRemovedPassport = session;+ },+ validateBeforeCommit: (loginEpoch) => {+ assertLogoutStillCurrent(loginEpoch);+ candidateTransitionEpoch = loginEpoch;+ },+ });+ if (candidateTransitionEpoch === null) {+ throw new AuthApiError(+ 'AUTH_FLOW_SUPERSEDED',+ 409,+ 'Logout was superseded by a newer auth action',+ );+ }+ assertLogoutTransitionStillCurrent(candidateTransitionEpoch);+ removedPassport = candidateRemovedPassport;+ revokeLoggedOutAccountBestEffort({+ accessToken: currentAccessToken,+ authBaseUrl: currentAuthBaseUrl,+ passport: removedPassport,+ });+ return;+ } catch (error) {+ if (isUnavailableSavedAccountError(error)) continue;+ if (isRetryableSavedAccountSwitchError(error)) continue;+ throw error;+ }+ }++ // A concurrent renderer may have completed an account switch while the+ // candidate refreshes above were in flight. Never let this stale logout+ // continue into the terminal local-sign-out path and clear the new owner.+ assertLogoutStillCurrent();++ if (savedVaultWasUnreadable) {+ // The aggregate vault may contain other accounts whose ciphertext is still+ // recoverable later. Never replace that opaque payload with an empty vault;+ // persist only the independent tombstone and then clear local sessions.+ await persistLogoutTombstoneOnly(currentIdentity.accountKey);+ } else {+ await mutateAuthAccountVault(+ (vault) => {+ assertLogoutStillCurrent();+ removedPassport = removeLoggedOutVaultAccount(vault, currentIdentity);+ // Commit the signed-out owner before clearing compatibility records. If the+ // process stops between the writes, cold start must not restore this account.+ vault.signedOutAt = Date.now();+ },+ {+ allowUnreadableLogoutTombstones: savedVaultHasUnreadableLogoutTombstones,+ replaceUnreadableLogoutTombstones: savedVaultHasUnreadableLogoutTombstones,+ },+ );+ }+ assertLogoutStillCurrent();+ removeSafe(AUTH_SESSION_KEY);+ removeSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY);+ removeSafe(LEGACY_ACCOUNT_REFRESH_TOKEN_KEY);+ removeSafe(LEGACY_REFRESH_TOKEN_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.@@ -5461,11 +5970,7 @@ export async function logout(): Promise<void> {// 它,primary 随后 confirmAccountDeletion() 直接 ACCOUNT_DELETION_RECEIPT_MISSING。// 闸门只加在这条隐式路径上——renderer 主动调的显式清理仍照常生效(见// clearAccountDeletionReceipt 的注释)。- if (isPassiveSharedUserDataInstance()) {- log.info('passive shared-userData instance keeps the account-deletion receipt on logout');- } else {- clearAccountDeletionReceipt();- }+ clearAccountDeletionReceipt();let localTransitionError: unknown = null;try {await withAccountFreeOwnerCommit({@@ -5473,23 +5978,18 @@ export async function logout(): Promise<void> {nextMode: 'signed-out',clearOnFailure: true,preservePersistedRefreshToken: true,+ validateBeforeCommit: isLogoutStillCurrent,+ shouldClearOnFailure: isLogoutStillCurrent,});} catch (error) {localTransitionError = error;}- // passive 共享实例跳过服务端登出:refresh token 按 (user, device) 一对一存,而它与- // primary 共用同一 deviceId——调这一发会把 primary 的那份一起作废,即使本地文件留着,- // primary 下次续期照样拿到确定性失败被踢。- if (currentAccessToken && !isPassiveSharedUserDataInstance()) {- apiFetch('/api/auth/logout', {- method: 'POST',- body: { deviceId },- token: currentAccessToken,- baseUrl: currentAuthBaseUrl,- }).catch(() => {});- }- revokeSavedSessionsBestEffort(savedVault, currentAccountKey);+ revokeLoggedOutAccountBestEffort({+ accessToken: currentAccessToken,+ authBaseUrl: currentAuthBaseUrl,+ passport: removedPassport,+ });if (localTransitionError) throw localTransitionError;}diff --git a/apps/desktop/src/renderer/__tests__/userInfoSectionHover.test.ts b/apps/desktop/src/renderer/__tests__/userInfoSectionHover.test.tsindex 7633f36033..b6435b9f09 100644--- a/apps/desktop/src/renderer/__tests__/userInfoSectionHover.test.ts+++ b/apps/desktop/src/renderer/__tests__/userInfoSectionHover.test.ts@@ -88,7 +88,9 @@ describe('UserInfoSection — version label', () => {});it('shows the Beta label only after the persisted channel state has loaded', () => {- expect(source).toContain("import { useBetaChannelSettings } from '@/hooks/useBetaChannelSettings';");+ expect(source).toContain(+ "import { useBetaChannelSettings } from '@/hooks/useBetaChannelSettings';",+ );expect(source).toContain('const showBetaLabel = !betaChannelState.loading && betaChannelState.enableBeta;',);@@ -100,10 +102,14 @@ describe('UserInfoSection — version label', () => {describe('UserInfoSection — Canary avatar badge', () => {it('shows only the shield decoration when isCanary is true', () => {+ expect(source).toMatch(+ /import \{[\s\S]*Building2[\s\S]*Check[\s\S]*Flame[\s\S]*UserRound[\s\S]*\} from 'lucide-react';/,+ );+ expect(source).toContain('dataOwnerId');+ expect(source).toContain('isCanary, listAccounts, syncAccounts, switchAccount');expect(source).toContain(- "import { Flame, LogOut, Settings, Shield, Smartphone, UserPlus, UserRound } from 'lucide-react';",+ "if (mode !== 'cloud' || !accountsReadyForOwner || switchableAccounts.length === 0) return null;",);- 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'");@@ -148,9 +154,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, LogOut, Settings, Shield, Smartphone, UserPlus, UserRound } from 'lucide-react';",- );+ expect(source).toContain('Smartphone');expect(source).toMatch(/'mobile-download-btn',\s*\n\s*'flex h-\[22px\] w-\[22px\]/);expect(source).toContain("!isCollapsed && 'mr-1'");expect(source).toContain('<Smartphone className="h-3 w-3" aria-hidden="true" />');@@ -212,11 +216,33 @@ describe('UserInfoSection — inner main button no longer owns hover background'expect(locale.sidebar.user.moreLabel).toBe('更多,当前用户:{{name}}');});- it('offers settings, account switching, and logout from the More menu', () => {+ it('keeps Settings at the bottom of the More menu and leaves logout in Settings', () => {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)');+ expect(source).toContain('{renderSavedAccountItems()}');+ expect(source).toContain('accountsReadyForOwner &&');+ expect(source).toContain('savedAccounts.some((account) => !account.isCurrent)');+ expect(source.indexOf('{renderSavedAccountItems()}')).toBeLessThan(+ source.indexOf("t('sidebar.user.menuSettings')"),+ );+ expect(source).not.toContain("t('sidebar.user.menuLogout')");+ expect(source).not.toContain('useLogout');+ expect(source).not.toContain('<LogOut');+ expect(source).toContain("mode === 'local'");+ expect(source.indexOf("t('sidebar.user.menuAddAccount')")).toBeLessThan(+ source.indexOf("t('sidebar.user.menuSettings')"),+ );+ expect(source).not.toContain('AccountSwitcherDialog');+ });++ it('shows saved accounts directly only when there is more than one', () => {+ expect(source).toContain('dataOwnerId');+ expect(source).toContain('isCanary, listAccounts, syncAccounts, switchAccount');+ expect(source).toContain(+ "if (mode !== 'cloud' || !accountsReadyForOwner || switchableAccounts.length === 0) return null;",+ );+ expect(source).toContain('onSelect={() => void switchSavedAccount(account)}');+ expect(source).toContain('await switchAccount(account.accountKey);');+ expect(source).toContain('onOpenChange={(open) => open && void refreshSavedAccounts()}');});});diff --git a/apps/desktop/src/renderer/__tests__/userInfoSectionMobileDownload.test.tsx b/apps/desktop/src/renderer/__tests__/userInfoSectionMobileDownload.test.tsxindex f655d26d50..9d4eeacb77 100644--- a/apps/desktop/src/renderer/__tests__/userInfoSectionMobileDownload.test.tsx+++ b/apps/desktop/src/renderer/__tests__/userInfoSectionMobileDownload.test.tsx@@ -1,12 +1,22 @@// @vitest-environment jsdom-import { cleanup, fireEvent, render, screen } from '@testing-library/react';+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-const { betaChannelState, navigate } = vi.hoisted(() => ({- betaChannelState: { enableBeta: false, isCustomized: false, loading: false },- navigate: vi.fn(),-}));+const { authState, betaChannelState, listAccounts, navigate, syncAccounts, switchAccount } =+ vi.hoisted(() => ({+ authState: {+ user: { name: 'Cindy user', avatar: null } as { name: string; avatar: string | null } | null,+ mode: 'cloud' as 'cloud' | 'local',+ dataOwnerId: 'owner-a' as string | null,+ isCanary: false,+ },+ betaChannelState: { enableBeta: false, isCustomized: false, loading: false },+ listAccounts: vi.fn(),+ navigate: vi.fn(),+ syncAccounts: vi.fn(),+ switchAccount: vi.fn(),+ }));vi.mock('react-i18next', () => ({useTranslation: () => ({@@ -15,18 +25,27 @@ vi.mock('react-i18next', () => ({}));vi.mock('react-router-dom', () => ({- useLocation: () => ({ pathname: '/' }),+ useLocation: () => ({ pathname: '/', search: '' }),useNavigate: () => navigate,}));vi.mock('@/contexts/AuthContext', () => ({useAuth: () => ({- user: { name: 'Cindy user', avatar: null },- mode: 'cloud',- isCanary: false,+ ...authState,+ listAccounts,+ syncAccounts,+ switchAccount,}),}));+vi.mock('@/components/ui/confirm-dialog-provider', () => ({+ useOptionalConfirmDialog: () => ({ confirm: vi.fn().mockResolvedValue(true) }),+}));++vi.mock('@/lib/makerChatStore', () => ({+ makerChatStore: { getRunningSnapshot: () => new Map() },+}));+vi.mock('@/hooks/useUpdateStatus', () => ({useUpdateStatus: () => ({ status: 'idle' }),}));@@ -72,6 +91,60 @@ import { UserInfoSection } from '@/components/sidebar/UserInfoSection';beforeEach(() => {navigate.mockClear();+ authState.user = { name: 'Cindy user', avatar: null };+ authState.mode = 'cloud';+ authState.dataOwnerId = 'owner-a';+ listAccounts.mockReset().mockResolvedValue({+ mutationAllowed: true,+ accounts: [+ {+ accountKey: 'current',+ displayName: 'Cindy user',+ email: '[email protected]',+ avatarUrl: null,+ kind: 'personal',+ orgName: null,+ orgLogoUrl: null,+ isCurrent: true,+ },+ {+ accountKey: 'other',+ displayName: 'Other user',+ email: '[email protected]',+ avatarUrl: null,+ kind: 'personal',+ orgName: null,+ orgLogoUrl: null,+ isCurrent: false,+ },+ ],+ });+ syncAccounts.mockReset().mockResolvedValue({+ mutationAllowed: true,+ accounts: [+ {+ accountKey: 'current',+ displayName: 'Cindy user',+ email: '[email protected]',+ avatarUrl: null,+ kind: 'personal',+ orgName: null,+ orgLogoUrl: null,+ isCurrent: true,+ },+ {+ accountKey: 'other',+ displayName: 'Other user',+ email: '[email protected]',+ avatarUrl: null,+ kind: 'personal',+ orgName: null,+ orgLogoUrl: null,+ isCurrent: false,+ },+ ],+ });+ switchAccount.mockReset().mockResolvedValue(undefined);betaChannelState.enableBeta = false;betaChannelState.loading = false;Object.defineProperty(window, 'electronAPI', {@@ -127,4 +200,103 @@ describe('UserInfoSection mobile download entry', () => {expect(navigate).toHaveBeenCalledWith('/settings?tab=remote-control§ion=devices');});++ it('shows all saved accounts only in the multi-account menu and switches directly', async () => {+ render(<UserInfoSection isCollapsed={false} />);++ fireEvent.pointerDown(screen.getByRole('button', { name: 'sidebar.user.moreLabel' }), {+ button: 0,+ ctrlKey: false,+ });++ expect(await screen.findByRole('menuitem', { name: /Other user/ })).toBeTruthy();+ expect(screen.getByRole('menuitem', { name: /Cindy user/ }).getAttribute('aria-disabled')).toBe(+ 'true',+ );++ fireEvent.click(screen.getByRole('menuitem', { name: /Other user/ }));+ await waitFor(() => expect(switchAccount).toHaveBeenCalledWith('other'));+ });++ it('drops the previous account menu snapshot as soon as the owner changes', async () => {+ const view = render(<UserInfoSection isCollapsed={false} />);++ fireEvent.pointerDown(screen.getByRole('button', { name: 'sidebar.user.moreLabel' }), {+ button: 0,+ ctrlKey: false,+ });+ expect(await screen.findByRole('menuitem', { name: /Other user/ })).toBeTruthy();++ authState.dataOwnerId = 'owner-b';+ view.rerender(<UserInfoSection isCollapsed={false} />);++ expect(screen.queryByRole('menuitem', { name: /Other user/ })).toBeNull();+ });++ it('does not show an account section when only one account is saved', async () => {+ listAccounts.mockResolvedValueOnce({+ mutationAllowed: true,+ accounts: [+ {+ accountKey: 'current',+ displayName: 'Cindy user',+ email: '[email protected]',+ avatarUrl: null,+ kind: 'personal',+ orgName: null,+ orgLogoUrl: null,+ isCurrent: true,+ },+ ],+ });+ syncAccounts.mockResolvedValueOnce({+ mutationAllowed: true,+ accounts: [+ {+ accountKey: 'current',+ displayName: 'Cindy user',+ email: '[email protected]',+ avatarUrl: null,+ kind: 'personal',+ orgName: null,+ orgLogoUrl: null,+ isCurrent: true,+ },+ ],+ });++ render(<UserInfoSection isCollapsed={false} />);+ fireEvent.pointerDown(screen.getByRole('button', { name: 'sidebar.user.moreLabel' }), {+ button: 0,+ ctrlKey: false,+ });++ await waitFor(() => expect(syncAccounts).toHaveBeenCalledOnce());+ expect(screen.queryByRole('menuitem', { name: /Cindy user/ })).toBeNull();+ });++ it('keeps the add-account entry before Settings when the user is not signed in', async () => {+ authState.user = null;+ authState.mode = 'local';++ render(<UserInfoSection isCollapsed={false} />);+ fireEvent.pointerDown(screen.getByRole('button', { name: 'sidebar.user.moreLabel' }), {+ button: 0,+ ctrlKey: false,+ });++ const addAccount = await screen.findByRole('menuitem', {+ name: 'sidebar.user.menuAddAccount',+ });+ const settings = screen.getByRole('menuitem', { name: 'sidebar.user.menuSettings' });+ expect(addAccount.compareDocumentPosition(settings) & Node.DOCUMENT_POSITION_FOLLOWING).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING,+ );+ expect(listAccounts).not.toHaveBeenCalled();++ fireEvent.click(addAccount);+ await waitFor(() =>+ expect(navigate).toHaveBeenCalledWith('/add-account', { state: { returnTo: '/' } }),+ );+ });});diff --git a/apps/desktop/src/renderer/__tests__/userProfileCardCopyUserId.test.tsx b/apps/desktop/src/renderer/__tests__/userProfileCardCopyUserId.test.tsxindex 60db5669b1..dd0a1900ad 100644--- a/apps/desktop/src/renderer/__tests__/userProfileCardCopyUserId.test.tsx+++ b/apps/desktop/src/renderer/__tests__/userProfileCardCopyUserId.test.tsx@@ -2,7 +2,7 @@import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import React from 'react';-import { MemoryRouter } from 'react-router-dom';+import { MemoryRouter, useLocation } from 'react-router-dom';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({@@ -10,11 +10,13 @@ const mocks = vi.hoisted(() => ({toastSuccess: vi.fn(),toastError: vi.fn(),exitLocalMode: vi.fn(),+ handleLogout: vi.fn(),authState: {user: {id: 'user-123',name: 'Lizi',avatar: null,+ email: '[email protected]',membershipKind: 'personal' as 'personal' | 'org',membershipRole: 'owner' as 'owner' | 'admin' | 'member',orgName: null as string | null,@@ -23,6 +25,7 @@ const mocks = vi.hoisted(() => ({id: string;name: string;avatar: string | null;+ email: string | null;membershipKind: 'personal' | 'org';membershipRole: 'owner' | 'admin' | 'member';orgName: string | null;@@ -45,6 +48,14 @@ vi.mock('@/contexts/AuthContext', () => ({useAuth: () => mocks.authState,}));+vi.mock('@/hooks/useLogout', () => ({+ useLogout: () => ({ handleLogout: mocks.handleLogout }),+}));++vi.mock('@/lib/makerChatStore', () => ({+ makerChatStore: { getRunningSnapshot: () => new Map() },+}));+vi.mock('@/lib/toast', () => ({toast: { success: mocks.toastSuccess, error: mocks.toastError },}));@@ -60,10 +71,16 @@ function renderCard() {return render(<MemoryRouter><UserProfileCard />+ <LocationProbe /></MemoryRouter>,);}+function LocationProbe() {+ const location = useLocation();+ return <div data-testid="location-probe">{location.pathname}</div>;+}+describe('UserProfileCard copy user ID', () => {beforeEach(() => {Object.defineProperty(navigator, 'clipboard', {@@ -75,6 +92,7 @@ describe('UserProfileCard copy user ID', () => {id: 'user-123',name: 'Lizi',avatar: null,+ email: '[email protected]',membershipKind: 'personal',membershipRole: 'owner',orgName: null,@@ -82,6 +100,7 @@ describe('UserProfileCard copy user ID', () => {};mocks.authState.mode = 'cloud';mocks.authState.exitLocalMode.mockReset();+ mocks.handleLogout.mockReset();});afterEach(() => {@@ -89,16 +108,21 @@ describe('UserProfileCard copy user ID', () => {vi.clearAllMocks();});- it('shows the user ID and copies it with a success toast when the ID row is clicked', async () => {+ it('shows the email prominently and keeps a compact copyable user ID', async () => {renderCard();- // ID 显式展示在卡片上,且名字本身不再是可点击控件。- expect(screen.getByText('settings.userProfile.copyUserId.display:user-123')).toBeTruthy();+ expect(screen.getByText('[email protected]')).toBeTruthy();+ expect(screen.getByTitle('[email protected]')).toBeTruthy();+ expect(screen.getByText('settings.userProfile.copyUserId.display:…-123')).toBeTruthy();expect(screen.getByText('Lizi').closest('button')).toBeNull();+ const email = screen.getByText('[email protected]');const idButton = screen.getByRole('button', {name: 'settings.userProfile.copyUserId.action',});+ expect(email.parentElement).toBe(idButton.parentElement);+ expect(email.nextElementSibling).toBe(idButton);+ expect(email.className).not.toContain('flex-1');expect(idButton.className).toContain('cursor-pointer');expect(idButton.className).toContain('hover:bg-[var(--settings-profile-avatar-bg)]');// 交互件圆角走 pill 档(DESIGN.md Border Radius Scale,无 6px 档)。@@ -107,7 +131,7 @@ describe('UserProfileCard copy user ID', () => {const describedById = idButton.getAttribute('aria-describedby');expect(describedById).toBeTruthy();expect(document.getElementById(describedById!)?.textContent).toBe(- 'settings.userProfile.copyUserId.display:user-123',+ 'settings.userProfile.copyUserId.display:…-123',);fireEvent.click(idButton);@@ -116,12 +140,11 @@ describe('UserProfileCard copy user ID', () => {expect(mocks.toastSuccess).toHaveBeenCalledWith('settings.userProfile.copyUserId.success');});- it('abbreviates a long user ID in the display while copying the full value', async () => {+ it('shows only the final four ID characters while copying the full value', async () => {mocks.authState.user!.id = 'mem_0123456789abcdef0123456789abcdef';renderCard();- // 展示只露头 6 + 尾 4,完整值不直接渲染。- expect(screen.getByText('settings.userProfile.copyUserId.display:mem_01…cdef')).toBeTruthy();+ expect(screen.getByText('settings.userProfile.copyUserId.display:…cdef')).toBeTruthy();expect(screen.queryByText('settings.userProfile.copyUserId.display:mem_0123456789abcdef0123456789abcdef',@@ -135,6 +158,14 @@ describe('UserProfileCard copy user ID', () => {);});+ it('keeps the compact ID available when an account has no email', () => {+ mocks.authState.user!.email = null;+ renderCard();++ expect(screen.queryByText('[email protected]')).toBeNull();+ expect(screen.getByText('settings.userProfile.copyUserId.display:…-123')).toBeTruthy();+ });+it('opens the profile edit dialog when the avatar is clicked', () => {renderCard();@@ -152,6 +183,36 @@ describe('UserProfileCard copy user ID', () => {expect(mocks.writeText).not.toHaveBeenCalled();});+ it('keeps cloud account actions on the right side of the profile card', async () => {+ renderCard();++ const logoutButton = screen.getByRole('button', { name: 'settings.logout.aria' });+ const addAccountButton = screen.getByRole('button', {+ name: 'sidebar.user.menuAddAccount',+ });+ expect(logoutButton).toBeTruthy();+ expect(addAccountButton).toBeTruthy();++ fireEvent.click(logoutButton);+ expect(mocks.handleLogout).toHaveBeenCalledOnce();++ fireEvent.click(addAccountButton);+ await waitFor(() =>+ expect(screen.getByTestId('location-probe').textContent).toBe('/add-account'),+ );+ expect(screen.queryByTestId('account-switcher-dialog')).toBeNull();+ expect(addAccountButton.parentElement?.className).toContain('flex-col');+ });++ it('does not show cloud account actions in the not-signed-in card', () => {+ mocks.authState.user = null;+ mocks.authState.mode = 'local';+ renderCard();++ expect(screen.queryByRole('button', { name: 'settings.logout.aria' })).toBeNull();+ expect(screen.queryByRole('button', { name: 'sidebar.user.menuAddAccount' })).toBeNull();+ });+it('shows an error toast when clipboard access fails', async () => {mocks.writeText.mockRejectedValueOnce(new Error('clipboard denied'));renderCard();diff --git a/apps/desktop/src/renderer/components/login/AddAccountLoginPage.tsx b/apps/desktop/src/renderer/components/login/AddAccountLoginPage.tsxindex d884442033..b0aa7ce3b4 100644--- a/apps/desktop/src/renderer/components/login/AddAccountLoginPage.tsx+++ b/apps/desktop/src/renderer/components/login/AddAccountLoginPage.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef } from 'react';+import { useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { useLocation, useNavigate } from 'react-router-dom';@@ -20,6 +20,7 @@ export function AddAccountLoginPage() {const initializedRef = useRef(false);const flowFinishedRef = useRef(false);const closeStartedRef = useRef(false);+ const [flowInitialized, setFlowInitialized] = useState(false);const returnTo = (location.state as AddAccountLocationState | null)?.returnTo ?? '/cc-agent';useEffect(() => {@@ -34,19 +35,21 @@ export function AddAccountLoginPage() {}, [reportLocalDbGate]);useEffect(() => {- if (loginState || initializedRef.current) return;+ if (initializedRef.current) return;initializedRef.current = true;- void beginAddAccount().catch(() => {- toast.error(t('sidebar.accountSwitcher.startFailed'));- navigate(returnTo, { replace: true });- });- }, [beginAddAccount, loginState, navigate, returnTo, t]);+ void beginAddAccount()+ .then(() => setFlowInitialized(true))+ .catch(() => {+ toast.error(t('sidebar.accountSwitcher.startFailed'));+ navigate(returnTo, { replace: true });+ });+ }, [beginAddAccount, navigate, returnTo, t]);useEffect(() => {- if (loginState?.step !== 'completed') return;+ if (!flowInitialized || loginState?.step !== 'completed') return;flowFinishedRef.current = true;navigate(returnTo, { replace: true });- }, [loginState?.step, navigate, returnTo]);+ }, [flowInitialized, loginState?.step, navigate, returnTo]);useEffect(() => () => {diff --git a/apps/desktop/src/renderer/components/login/__tests__/AddAccountLoginPage.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/AddAccountLoginPage.test.tsxindex 19e1523591..ee074299f3 100644--- a/apps/desktop/src/renderer/components/login/__tests__/AddAccountLoginPage.test.tsx+++ b/apps/desktop/src/renderer/components/login/__tests__/AddAccountLoginPage.test.tsx@@ -3,14 +3,17 @@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';+import { MemoryRouter, useLocation } from 'react-router-dom';const auth = vi.hoisted(() => ({isInitializing: false,canEnterApp: true,loginState: { step: 'identifier' },- beginAddAccount: vi.fn(),- cancelAddAccount: vi.fn(),+ beginAddAccount: vi.fn(async () => ({+ success: true,+ state: { step: 'identifier' },+ })),+ cancelAddAccount: vi.fn(async () => undefined),}));vi.mock('react-i18next', () => ({@@ -51,13 +54,20 @@ function CoverProbe() {);}+function LocationProbe() {+ return <output data-testid="location-probe">{useLocation().pathname}</output>;+}+function Harness() {const [showAddAccount, setShowAddAccount] = useState(true);return (<AppShellCoverProvider>- <MemoryRouter initialEntries={['/add-account']}>+ <MemoryRouter+ initialEntries={[{ pathname: '/add-account', state: { returnTo: '/settings' } }]}+ >{showAddAccount ? <AddAccountLoginPage /> : null}<CoverProbe />+ <LocationProbe /><button type="button" onClick={() => setShowAddAccount(false)}>leave route</button>@@ -69,7 +79,13 @@ function Harness() {afterEach(() => {cleanup();auth.beginAddAccount.mockReset();+ auth.beginAddAccount.mockResolvedValue({+ success: true,+ state: { step: 'identifier' },+ });auth.cancelAddAccount.mockReset();+ auth.cancelAddAccount.mockResolvedValue(undefined);+ auth.loginState = { step: 'identifier' };});describe('AddAccountLoginPage app-shell cover', () => {@@ -89,4 +105,19 @@ describe('AddAccountLoginPage app-shell cover', () => {fireEvent.click(screen.getByRole('button', { name: 'close add-account login' }));await waitFor(() => expect(auth.cancelAddAccount).toHaveBeenCalledOnce());});++ it('starts a fresh flow before honoring a stale completed state', async () => {+ auth.loginState = { step: 'completed' };+ auth.beginAddAccount.mockImplementation(async () => {+ auth.loginState = { step: 'identifier' };+ return { success: true, state: auth.loginState };+ });++ render(<Harness />);++ await waitFor(() => expect(auth.beginAddAccount).toHaveBeenCalledOnce());+ await waitFor(() =>+ expect(screen.getByTestId('location-probe').textContent).toBe('/add-account'),+ );+ });});diff --git a/apps/desktop/src/renderer/components/settings/LogoutSection.tsx b/apps/desktop/src/renderer/components/settings/LogoutSection.tsxindex 55e94e257b..f47fb76c24 100644--- a/apps/desktop/src/renderer/components/settings/LogoutSection.tsx+++ b/apps/desktop/src/renderer/components/settings/LogoutSection.tsx@@ -1,37 +1,13 @@-import { useTranslation } from 'react-i18next';--import { cn } from '@/lib/utils';import { useAuth } from '@/contexts/AuthContext';-import { useLogout } from '@/hooks/useLogout';import { AccountDeletionSection } from './AccountDeletionSection';export function LogoutSection() {const { mode } = useAuth();- const { handleLogout } = useLogout();- const { t } = useTranslation();- // Local mode has no Cindy account or credentials to revoke. Keep logout and- // account-deletion controls exclusive to authenticated cloud sessions.+ // Local mode has no Cindy account or credentials to revoke. Keep account+ // deletion exclusive to authenticated cloud sessions; the logout action now+ // lives beside the profile card so account actions stay together.if (mode !== 'cloud') return null;- return (- <div className="flex flex-col gap-2.5">- <button- type="button"- onClick={handleLogout}- aria-label={t('settings.logout.aria')}- className={cn(- 'flex h-[42px] w-full items-center justify-center rounded-full',- 'bg-[var(--settings-logout-bg)]',- 'border border-[var(--settings-logout-border)]',- 'text-13 font-medium text-[var(--settings-logout-text)]',- 'hover:bg-[var(--settings-logout-hover-bg)]',- 'transition-colors',- )}- >- {t('settings.logout.button')}- </button>- <AccountDeletionSection />- </div>- );+ return <AccountDeletionSection />;}diff --git a/apps/desktop/src/renderer/components/settings/UserProfileCard.tsx b/apps/desktop/src/renderer/components/settings/UserProfileCard.tsxindex 13bd342ce1..6766292260 100644--- a/apps/desktop/src/renderer/components/settings/UserProfileCard.tsx+++ b/apps/desktop/src/renderer/components/settings/UserProfileCard.tsx@@ -1,11 +1,13 @@import { useEffect, useId, useState } from 'react';import { useTranslation } from 'react-i18next';-import { Building2, Copy, Pencil, UserRound } from 'lucide-react';-import { useNavigate } from 'react-router-dom';+import { Building2, Copy, LogOut, Pencil, UserPlus, UserRound } from 'lucide-react';+import { useLocation, useNavigate } from 'react-router-dom';import { cn } from '@/lib/utils';import { toast } from '@/lib/toast';import { useAuth } from '@/contexts/AuthContext';+import { useOptionalConfirmDialog } from '@/components/ui/confirm-dialog-provider';+import { useLogout } from '@/hooks/useLogout';import { ProfileEditDialog } from './ProfileEditDialog';const ORGANIZATION_ROLE_I18N_KEYS = {@@ -24,14 +26,17 @@ function getOrganizationRoleI18nKey(role: string) {return ORGANIZATION_ROLE_I18N_KEYS[isOrganizationRole(role) ? role : 'member'];}-// 展示用缩写:长 ID 只露头尾便于目视比对,点击复制的仍是完整值。+// ID 只是邮箱旁的辅助标识:只露末 4 位,点击复制的仍是完整值。function abbreviateUserId(id: string): string {- return id.length > 14 ? `${id.slice(0, 6)}…${id.slice(-4)}` : id;+ return id.length > 4 ? `…${id.slice(-4)}` : id;}export function UserProfileCard() {const { user, mode, exitLocalMode } = useAuth();+ const confirmDialog = useOptionalConfirmDialog();+ const { handleLogout } = useLogout();const navigate = useNavigate();+ const location = useLocation();const [avatarError, setAvatarError] = useState(false);const [orgLogoError, setOrgLogoError] = useState(false);const [editOpen, setEditOpen] = useState(false);@@ -120,6 +125,29 @@ export function UserProfileCard() {}};+ const confirmRunningTaskInterruption = async (): Promise<boolean> => {+ const { makerChatStore } = await import('@/lib/makerChatStore');+ const hasRunningTask = [...makerChatStore.getRunningSnapshot().values()].some(+ (status) => status.isRunning,+ );+ if (!hasRunningTask) return true;+ if (!confirmDialog) return false;+ return confirmDialog.confirm({+ title: t('sidebar.accountSwitcher.runningTaskTitle'),+ description: t('sidebar.accountSwitcher.runningTaskDescription'),+ confirmText: t('sidebar.accountSwitcher.runningTaskConfirm'),+ cancelText: t('logic.confirm.cancel'),+ confirmVariant: 'destructive',+ });+ };++ const openAddAccount = async () => {+ if (!(await confirmRunningTaskInterruption())) return;+ navigate('/add-account', {+ state: { returnTo: `${location.pathname}${location.search}` },+ });+ };+return (<divclassName={cn(@@ -166,28 +194,52 @@ export function UserProfileCard() {</button><div className="min-w-0 flex-1">- <p className="min-w-0 truncate text-18 font-medium leading-[1.2] text-[var(--settings-profile-name)]">- {displayName}- </p>- {/* User ID — 显式展示,整行点击复制;常驻小图标明示可复制。 */}- <button- type="button"- onClick={() => void handleCopyUserId()}- aria-label={t('settings.userProfile.copyUserId.action')}- aria-describedby={userIdDescriptionId}- title={t('settings.userProfile.copyUserId.action')}- className={cn(- '-ml-1.5 mt-0.5 flex min-w-0 max-w-full cursor-pointer items-center gap-1 rounded-full px-1.5 py-0.5 text-left',- 'text-12 text-[var(--text-tertiary)] transition-colors',- 'hover:bg-[var(--settings-profile-avatar-bg)] hover:text-[var(--text-secondary)]',- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',- )}- >- <span id={userIdDescriptionId} className="min-w-0 truncate">- {t('settings.userProfile.copyUserId.display', { id: abbreviateUserId(user.id) })}- </span>- <Copy aria-hidden="true" size={11} className="shrink-0" />- </button>+ <div className="flex min-w-0 items-center gap-1">+ <p className="min-w-0 truncate text-18 font-medium leading-[1.2] text-[var(--settings-profile-name)]">+ {displayName}+ </p>+ {/* 编辑名字 / 头像(直写服务端,弹窗见 ProfileEditDialog) */}+ <button+ type="button"+ onClick={() => setEditOpen(true)}+ aria-label={t('settings.userProfile.edit.open')}+ title={t('settings.userProfile.edit.open')}+ className={cn(+ 'flex h-7 w-7 shrink-0 items-center justify-center rounded-full',+ 'text-[var(--text-tertiary)] transition-colors',+ 'hover:bg-[var(--settings-profile-avatar-bg)] hover:text-[var(--text-primary)]',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',+ )}+ >+ <Pencil size={14} />+ </button>+ </div>+ <div className="mt-0.5 flex min-w-0 items-center gap-2">+ {user.email ? (+ <p className="min-w-0 truncate text-12 text-[var(--text-secondary)]" title={user.email}>+ {user.email}+ </p>+ ) : null}+ {/* User ID 仅作辅助核对:只显示末 4 位,点击仍复制完整值。 */}+ <button+ type="button"+ onClick={() => void handleCopyUserId()}+ aria-label={t('settings.userProfile.copyUserId.action')}+ aria-describedby={userIdDescriptionId}+ title={t('settings.userProfile.copyUserId.action')}+ className={cn(+ 'flex shrink-0 cursor-pointer items-center gap-1 rounded-full px-1.5 py-0.5 text-left',+ 'text-10 text-[var(--text-tertiary)] transition-colors',+ 'hover:bg-[var(--settings-profile-avatar-bg)] hover:text-[var(--text-secondary)]',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',+ )}+ >+ <span id={userIdDescriptionId}>+ {t('settings.userProfile.copyUserId.display', { id: abbreviateUserId(user.id) })}+ </span>+ <Copy aria-hidden="true" size={10} className="shrink-0" />+ </button>+ </div>{organizationName && organizationRole && (<div className="mt-1 flex min-w-0 items-center gap-1.5 text-sm leading-5 text-[var(--text-secondary)]">{orgLogoUrl && !orgLogoError ? (@@ -216,21 +268,38 @@ export function UserProfileCard() {)}</div>- {/* 编辑名字 / 头像(直写服务端,弹窗见 ProfileEditDialog) */}- <button- type="button"- onClick={() => setEditOpen(true)}- aria-label={t('settings.userProfile.edit.open')}- title={t('settings.userProfile.edit.open')}- className={cn(- 'flex h-8 w-8 shrink-0 items-center justify-center rounded-full',- 'text-[var(--text-tertiary)] transition-colors',- 'hover:bg-[var(--settings-profile-avatar-bg)] hover:text-[var(--text-primary)]',- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',- )}- >- <Pencil size={15} />- </button>+ {mode === 'cloud' && (+ <div className="flex shrink-0 flex-col items-stretch gap-2">+ <button+ type="button"+ onClick={() => void handleLogout()}+ aria-label={t('settings.logout.aria')}+ className={cn(+ 'flex h-8 items-center justify-center gap-1.5 rounded-full border px-3 text-12 font-medium',+ 'border-[var(--settings-logout-border)] bg-[var(--settings-logout-bg)]',+ 'text-[var(--settings-logout-text)] transition-colors hover:bg-[var(--settings-logout-hover-bg)]',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',+ )}+ >+ <LogOut size={14} aria-hidden="true" />+ {t('settings.logout.button')}+ </button>+ <button+ type="button"+ onClick={() => void openAddAccount()}+ aria-label={t('sidebar.user.menuAddAccount')}+ className={cn(+ 'flex h-8 items-center justify-center gap-1.5 rounded-full border px-3 text-12 font-medium',+ 'border-[var(--settings-btn-secondary-border)] bg-[var(--settings-btn-secondary-bg)]',+ 'text-[var(--settings-btn-secondary-text)] transition-colors hover:bg-[var(--settings-btn-secondary-hover-bg)]',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]',+ )}+ >+ <UserPlus size={14} aria-hidden="true" />+ {t('sidebar.user.menuAddAccount')}+ </button>+ </div>+ )}<ProfileEditDialog open={editOpen} onOpenChange={setEditOpen} /></div>diff --git a/apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx b/apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsxindex b77665af83..754e1bec39 100644--- a/apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx+++ b/apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx@@ -1,14 +1,25 @@import { useEffect, useRef, useState, type ReactNode } from 'react';import { useNavigate, useLocation } from 'react-router-dom';import { useTranslation } from 'react-i18next';-import { Flame, LogOut, Settings, Shield, Smartphone, UserPlus, UserRound } from 'lucide-react';+import {+ Building2,+ Check,+ Flame,+ Settings,+ Shield,+ Smartphone,+ UserPlus,+ UserRound,+} from 'lucide-react';import { cn } from '@/lib/utils';import { useAuth } from '@/contexts/AuthContext';+import { useOptionalConfirmDialog } from '@/components/ui/confirm-dialog-provider';import { useUpdateStatus } from '@/hooks/useUpdateStatus';import { useUpdateBannerDismiss } from '@/hooks/useUpdateBannerDismiss';import { useBetaChannelSettings } from '@/hooks/useBetaChannelSettings';import { Tip } from '@/components/ui/tooltip';+import { Spinner } from '@/components/ui/spinner';import {DropdownMenu,DropdownMenuContent,@@ -16,28 +27,63 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from '@/components/ui/dropdown-menu';-import { useLogout } from '@/hooks/useLogout';+import { toast } from '@/lib/toast';+import type { DesktopSavedAccount } from '@/lib/authService';import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';import { shouldLabelRegion } from '../../../shared/regionCode';import { MobileDownloadDialog } from './MobileDownloadDialog';-import { AccountSwitcherDialog } from './AccountSwitcherDialog';interface UserInfoSectionProps {isCollapsed: boolean;onOpenUpdateNotice?: () => void;}+function AccountMenuAvatar({ 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-7 w-7 shrink-0 rounded-full object-cover"+ onError={() => setImageFailed(true)}+ />+ );+ }++ return (+ <span className="flex h-7 w-7 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-3.5 w-3.5" aria-hidden="true" />+ ) : (+ <UserRound className="h-3.5 w-3.5" aria-hidden="true" />+ )}+ </span>+ );+}+export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSectionProps) {- const { user, mode, isCanary, beginAddAccount } = useAuth();- const { handleLogout } = useLogout();+ const { user, mode, dataOwnerId, isCanary, listAccounts, syncAccounts, switchAccount } =+ useAuth();+ const confirmDialog = useOptionalConfirmDialog();const navigate = useNavigate();const location = useLocation();const [avatarError, setAvatarError] = useState(false);const [mobileDownloadOpen, setMobileDownloadOpen] = useState(false);- const [accountSwitcherOpen, setAccountSwitcherOpen] = useState(false);+ const [savedAccounts, setSavedAccounts] = useState<DesktopSavedAccount[]>([]);+ const [savedAccountsOwnerKey, setSavedAccountsOwnerKey] = useState<string | null>(null);+ const [accountsMutationAllowed, setAccountsMutationAllowed] = useState(true);+ const [accountsSyncing, setAccountsSyncing] = useState(false);+ const [switchingAccountKey, setSwitchingAccountKey] = useState<string | null>(null);const mobileDownloadButtonRef = useRef<HTMLButtonElement>(null);- const moreButtonRef = useRef<HTMLButtonElement>(null);+ const accountsLoadGenerationRef = useRef(0);const { t } = useTranslation();+ const accountsOwnerKey = mode === 'cloud' ? dataOwnerId : null;+ const accountsReadyForOwner = savedAccountsOwnerKey === accountsOwnerKey;// 火焰按钮双职责:// - 正常情况(无 pending update 或 banner 未 dismiss)→ 弹更新历史 Dialog。@@ -60,6 +106,18 @@ export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSecsetAvatarError(false);}, [avatarUrl]);+ // Account snapshots belong to the active data owner. Invalidate them as+ // soon as ownership changes so a reopened menu can never act on the prior+ // account while the fresh list is loading.+ useEffect(() => {+ accountsLoadGenerationRef.current += 1;+ setSavedAccountsOwnerKey(null);+ setSavedAccounts([]);+ setAccountsMutationAllowed(false);+ setAccountsSyncing(false);+ setSwitchingAccountKey(null);+ }, [accountsOwnerKey]);+if (!user && !isLocal) return null;const initial = displayName.charAt(0).toUpperCase();@@ -93,38 +151,146 @@ export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSec};const openAddAccount = async () => {- const result = await beginAddAccount();- if (!result.success) return;- setAccountSwitcherOpen(false);+ if (!(await confirmRunningTaskInterruption())) return;navigate('/add-account', {state: { returnTo: `${location.pathname}${location.search}` },});};+ const refreshSavedAccounts = async () => {+ if (mode !== 'cloud') return;+ const generation = ++accountsLoadGenerationRef.current;+ setSavedAccountsOwnerKey(null);+ setSavedAccounts([]);+ setAccountsMutationAllowed(false);+ setAccountsSyncing(true);+ try {+ const initialSnapshot = await listAccounts();+ if (generation !== accountsLoadGenerationRef.current) return;+ setSavedAccounts(initialSnapshot.accounts);+ setAccountsMutationAllowed(initialSnapshot.mutationAllowed);+ setSavedAccountsOwnerKey(accountsOwnerKey);++ const syncedSnapshot = await syncAccounts();+ if (generation !== accountsLoadGenerationRef.current) return;+ setSavedAccounts(syncedSnapshot.accounts);+ setAccountsMutationAllowed(syncedSnapshot.mutationAllowed);+ setSavedAccountsOwnerKey(accountsOwnerKey);+ } catch {+ if (generation === accountsLoadGenerationRef.current) {+ toast.error(t('sidebar.accountSwitcher.syncFailed'));+ }+ } finally {+ if (generation === accountsLoadGenerationRef.current) setAccountsSyncing(false);+ }+ };++ const confirmRunningTaskInterruption = async (): Promise<boolean> => {+ const { makerChatStore } = await import('@/lib/makerChatStore');+ const hasRunningTask = [...makerChatStore.getRunningSnapshot().values()].some(+ (status) => status.isRunning,+ );+ if (!hasRunningTask) return true;+ if (!confirmDialog) return false;+ return confirmDialog.confirm({+ title: t('sidebar.accountSwitcher.runningTaskTitle'),+ description: t('sidebar.accountSwitcher.runningTaskDescription'),+ confirmText: t('sidebar.accountSwitcher.runningTaskConfirm'),+ cancelText: t('logic.confirm.cancel'),+ confirmVariant: 'destructive',+ });+ };++ const switchSavedAccount = async (account: DesktopSavedAccount) => {+ if (+ account.isCurrent ||+ switchingAccountKey ||+ !accountsMutationAllowed ||+ !accountsReadyForOwner+ )+ return;+ setSwitchingAccountKey(account.accountKey);+ try {+ if (!(await confirmRunningTaskInterruption())) return;+ await switchAccount(account.accountKey);+ } catch {+ toast.error(t('sidebar.accountSwitcher.switchFailed'));+ } finally {+ setSwitchingAccountKey(null);+ }+ };++ const renderSavedAccountItems = () => {+ const switchableAccounts = savedAccounts.filter((account) => !account.isCurrent);+ if (mode !== 'cloud' || !accountsReadyForOwner || switchableAccounts.length === 0) return null;++ return (+ <>+ {savedAccounts.map((account) => {+ 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;+ const switching = switchingAccountKey === account.accountKey;++ return (+ <DropdownMenuItem+ key={account.accountKey}+ disabled={+ account.isCurrent || switchingAccountKey !== null || !accountsMutationAllowed+ }+ onSelect={() => void switchSavedAccount(account)}+ className="gap-2.5 py-2"+ >+ <AccountMenuAvatar account={account} />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-13 font-medium">{primaryLabel}</span>+ {secondaryLabel ? (+ <span className="mt-0.5 block truncate text-11 text-[var(--text-secondary)]">+ {secondaryLabel}+ </span>+ ) : null}+ </span>+ {switching ? (+ <Spinner size={14} className="shrink-0 text-[var(--text-secondary)]" />+ ) : account.isCurrent ? (+ <Check className="h-4 w-4 shrink-0" aria-hidden="true" />+ ) : null}+ </DropdownMenuItem>+ );+ })}+ {accountsSyncing ? (+ <div className="px-2 py-1 text-11 text-[var(--text-secondary)]">+ {t('sidebar.accountSwitcher.syncing')}+ </div>+ ) : null}+ </>+ );+ };+const renderMoreMenu = (trigger: ReactNode) => (- <DropdownMenu>+ <DropdownMenu onOpenChange={(open) => open && void refreshSavedAccounts()}><DropdownMenuTrigger asChild>{trigger}</DropdownMenuTrigger><DropdownMenuContent side="top" align="start" sideOffset={8} className="min-w-[190px]">+ {renderSavedAccountItems()}+ {mode === 'cloud' &&+ accountsReadyForOwner &&+ savedAccounts.some((account) => !account.isCurrent) ? (+ <DropdownMenuSeparator />+ ) : null}+ {mode === 'local' ? (+ <DropdownMenuItem onSelect={() => void openAddAccount()} className="gap-2.5">+ <UserPlus className="h-4 w-4" aria-hidden="true" />+ {t('sidebar.user.menuAddAccount')}+ </DropdownMenuItem>+ ) : null}<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>);@@ -165,47 +331,48 @@ export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSec<><div className="mt-auto flex h-[66px] flex-col items-center justify-center gap-1 px-3"><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">- {user?.avatar && !avatarError ? (- <img- src={user.avatar}- alt={displayName}- className="h-9 w-9 rounded-full object-cover"- onError={() => setAvatarError(true)}- />- ) : (- <div- className={cn(- 'flex h-9 w-9 items-center justify-center rounded-full',- 'border border-sidebar-border bg-sidebar-item-hover text-base font-medium text-foreground',- )}- >- {showNotSignedInGlyph ? (- <UserRound aria-hidden="true" size={18} strokeWidth={1.75} />- ) : (- initial- )}- </div>- )}- {isCanary && (- <span- aria-label={t('sidebar.user.canaryBadge')}- className={cn(- 'absolute -bottom-0.5 -right-0.5',- 'flex h-3 w-3 items-center justify-center rounded-full',- 'bg-foreground text-background ring-2 ring-sidebar',- )}- >- <Shield size={8} strokeWidth={2.5} />- </span>- )}- </div>- </button>)}+ {renderMoreMenu(+ <button+ aria-label={moreLabel}+ className="flex min-w-0 items-center justify-center text-left"+ >+ <div className="relative h-9 w-9 shrink-0">+ {user?.avatar && !avatarError ? (+ <img+ src={user.avatar}+ alt={displayName}+ className="h-9 w-9 rounded-full object-cover"+ onError={() => setAvatarError(true)}+ />+ ) : (+ <div+ className={cn(+ 'flex h-9 w-9 items-center justify-center rounded-full',+ 'border border-sidebar-border bg-sidebar-item-hover text-base font-medium text-foreground',+ )}+ >+ {showNotSignedInGlyph ? (+ <UserRound aria-hidden="true" size={18} strokeWidth={1.75} />+ ) : (+ initial+ )}+ </div>+ )}+ {isCanary && (+ <span+ aria-label={t('sidebar.user.canaryBadge')}+ className={cn(+ 'absolute -bottom-0.5 -right-0.5',+ 'flex h-3 w-3 items-center justify-center rounded-full',+ 'bg-foreground text-background ring-2 ring-sidebar',+ )}+ >+ <Shield size={8} strokeWidth={2.5} />+ </span>+ )}+ </div>+ </button>,+ )}</Tip>{mobileDownloadEntry}</div>@@ -217,12 +384,6 @@ export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSeconOpenDevices={openLinkedDevices}triggerRef={mobileDownloadButtonRef}/>- <AccountSwitcherDialog- open={accountSwitcherOpen}- onOpenChange={setAccountSwitcherOpen}- onAddAccount={() => void openAddAccount()}- triggerRef={moreButtonRef}- /></>);}@@ -239,82 +400,83 @@ export function UserInfoSection({ isCollapsed, onOpenUpdateNotice }: UserInfoSec'has-[.mobile-download-btn:hover]:bg-[var(--sidebar-user-card-bg)]',)}>- {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 反色描边 + 右下角盾牌角标 */}- <div- className="relative h-[27px] w-[27px] shrink-0"- title={isCanary ? t('sidebar.user.canaryBadge') : undefined}- >- {user?.avatar && !avatarError ? (- <img- src={user.avatar}- alt={displayName}- className={cn('h-[27px] w-[27px] rounded-full object-cover')}- onError={() => setAvatarError(true)}- />- ) : (- <div- className={cn(- 'flex h-[27px] w-[27px] items-center justify-center rounded-full',- 'border border-[var(--sidebar-user-card-border)] bg-[var(--sidebar-user-card-bg)] text-14 font-medium text-[var(--sidebar-user-card-text)]',- )}- >- {showNotSignedInGlyph ? (- <UserRound aria-hidden="true" size={15} strokeWidth={1.75} />- ) : (- initial- )}- </div>- )}- {isCanary && (- // ring-2 ring-sidebar 用 sidebar 背景色作为分隔环,避免角标和头像糊在一起- <span- aria-label={t('sidebar.user.canaryBadge')}- className={cn(- 'absolute -bottom-0.5 -right-0.5',- 'flex h-3 w-3 items-center justify-center rounded-full',- 'bg-[var(--sidebar-user-card-text)] text-background ring-2 ring-sidebar',- )}- >- <Shield size={8} strokeWidth={2.5} />- </span>- )}- </div>-- {/* Name & plan — fade in/out with collapse。- 折叠 rail(64px)下必须整个移出布局(hidden)——flex-1 占位会把- 头像挤出 64px 可视区(旧 w-0 折叠时代 opacity 即可,rail 时代不行)。 */}- <div- className={cn(- 'flex min-w-0 flex-1 flex-col justify-center',- 'transition-opacity duration-200 ease-in-out',- 'opacity-100',- )}+ {renderMoreMenu(+ <button+ aria-label={moreLabel}+ className={cn('flex min-w-0 flex-1 items-center gap-[10px]', 'text-left')}>- <p className="truncate text-14 font-semibold leading-[1.286] text-[var(--sidebar-user-card-text)]">- {displayName}- </p>- {/* 2px gap 与同栏 userNameContainer 保持一致。 */}- <p- className="flex min-w-0 items-center gap-1 text-10 leading-[1.3] text-[var(--sidebar-user-card-text)]"- title={appVersionLabelDetail}+ {/* Avatar — admin 用户加 1.5px 反色描边 + 右下角盾牌角标 */}+ <div+ className="relative h-[27px] w-[27px] shrink-0"+ title={isCanary ? t('sidebar.user.canaryBadge') : undefined}>- <span className="truncate opacity-80">{appVersionLabel}</span>- {showBetaLabel ? (+ {user?.avatar && !avatarError ? (+ <img+ src={user.avatar}+ alt={displayName}+ className={cn('h-[27px] w-[27px] rounded-full object-cover')}+ onError={() => setAvatarError(true)}+ />+ ) : (+ <div+ className={cn(+ 'flex h-[27px] w-[27px] items-center justify-center rounded-full',+ 'border border-[var(--sidebar-user-card-border)] bg-[var(--sidebar-user-card-bg)] text-14 font-medium text-[var(--sidebar-user-card-text)]',+ )}+ >+ {showNotSignedInGlyph ? (+ <UserRound aria-hidden="true" size={15} strokeWidth={1.75} />+ ) : (+ initial+ )}+ </div>+ )}+ {isCanary && (+ // ring-2 ring-sidebar 用 sidebar 背景色作为分隔环,避免角标和头像糊在一起<span- className="shrink-0 select-none opacity-80"- data-testid="sidebar-beta-channel-label"+ aria-label={t('sidebar.user.canaryBadge')}+ className={cn(+ 'absolute -bottom-0.5 -right-0.5',+ 'flex h-3 w-3 items-center justify-center rounded-full',+ 'bg-[var(--sidebar-user-card-text)] text-background ring-2 ring-sidebar',+ )}>- {t('settings.betaChannel.badge')}+ <Shield size={8} strokeWidth={2.5} /></span>- ) : null}- </p>- </div>- </button>)}+ )}+ </div>++ {/* Name & plan — fade in/out with collapse。+ 折叠 rail(64px)下必须整个移出布局(hidden)——flex-1 占位会把+ 头像挤出 64px 可视区(旧 w-0 折叠时代 opacity 即可,rail 时代不行)。 */}+ <div+ className={cn(+ 'flex min-w-0 flex-1 flex-col justify-center',+ 'transition-opacity duration-200 ease-in-out',+ 'opacity-100',+ )}+ >+ <p className="truncate text-14 font-semibold leading-[1.286] text-[var(--sidebar-user-card-text)]">+ {displayName}+ </p>+ {/* 2px gap 与同栏 userNameContainer 保持一致。 */}+ <p+ className="flex min-w-0 items-center gap-1 text-10 leading-[1.3] text-[var(--sidebar-user-card-text)]"+ title={appVersionLabelDetail}+ >+ <span className="truncate opacity-80">{appVersionLabel}</span>+ {showBetaLabel ? (+ <span+ className="shrink-0 select-none opacity-80"+ data-testid="sidebar-beta-channel-label"+ >+ {t('settings.betaChannel.badge')}+ </span>+ ) : null}+ </p>+ </div>+ </button>,+ )}{mobileDownloadEntry}@@ -375,12 +537,6 @@ 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/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex d0f8db4400..035db0d019 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -6834,7 +6834,6 @@"moreLabel": "More, current user: {{name}}","menuSettings": "Settings","menuAddAccount": "Sign in to another account",- "menuLogout": "Log out","canaryBadge": "Canary user","regionCodeCn": "CN","regionCodeDev": "Dev",@@ -10870,7 +10869,7 @@},"confirm": {"logoutTitle": "Log out",- "logoutDescription": "Log out of all accounts on this device?",+ "logoutDescription": "Log out of the current account?","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 ed0a31d800..12ff28c9a7 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -6832,7 +6832,6 @@"moreLabel": "その他、現在のユーザー:{{name}}","menuSettings": "設定","menuAddAccount": "別のアカウントでログイン",- "menuLogout": "ログアウト","canaryBadge": "Canary ユーザー","regionCodeCn": "CN","regionCodeDev": "Dev",@@ -10854,7 +10853,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 5d98787213..e60d8a5a08 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -6832,7 +6832,6 @@"moreLabel": "더 보기, 현재 사용자: {{name}}","menuSettings": "설정","menuAddAccount": "다른 계정으로 로그인",- "menuLogout": "로그아웃","canaryBadge": "Canary 사용자","regionCodeCn": "CN","regionCodeDev": "Dev",@@ -10854,7 +10853,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 0bb914025d..4d3adf4ae9 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -6832,7 +6832,6 @@"moreLabel": "更多,当前用户:{{name}}","menuSettings": "设置","menuAddAccount": "登录更多账号",- "menuLogout": "退出","canaryBadge": "灰度用户","regionCodeCn": "CN","regionCodeDev": "Dev",@@ -10854,7 +10853,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 2b898c28c8..91f511e842 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -6832,7 +6832,6 @@"moreLabel": "更多,當前使用者:{{name}}","menuSettings": "設定","menuAddAccount": "登入更多帳號",- "menuLogout": "退出","canaryBadge": "灰度使用者","regionCodeCn": "CN","regionCodeDev": "Dev",@@ -10854,7 +10853,7 @@},"confirm": {"logoutTitle": "退出登入",- "logoutDescription": "確定要退出這台裝置上的所有帳號嗎?",+ "logoutDescription": "確定要退出目前帳號嗎?","logoutConfirm": "退出","cancel": "取消","sessionExpiredTitle": "登入已過期",diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.mdindex 2a9c8685f0..90f7220a93 100644--- a/docs/design-rules/design-inventory.md+++ b/docs/design-rules/design-inventory.md@@ -37,8 +37,8 @@| `desktop.overlay.toast` | desktop | Toast | App 常驻 ToastContainer(用户可见出口,不展开业务逻辑) | Toast, ToastContainer | apps/desktop/src/renderer/components/ui/toast/Toast.tsx, apps/desktop/src/renderer/components/ui/toast/ToastContainer.tsx, apps/desktop/src/renderer/components/ui/toast/index.ts | 4 | 4 | 2 || `desktop.plugins.app-main` | desktop | 插件主视图 | hash `/apps/:ghostId`(GhostMainViewFeatureLayout) | GhostMainViewFeatureLayout, GhostMainViewHost | apps/desktop/src/renderer/features/plugin/GhostMainViewFeatureLayout.tsx, apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx | 0 | 0 | 0 || `desktop.plugins.installed` | desktop | 已装插件 | hash `/plugins`(GhostPluginPage) | AddMarketplaceDialog, GhostPluginDetailView, GhostPluginPage, MarketPluginDetailView, MyPublishesSection, PluginManagementLayout, PluginScopePicker, UpdateAllDialog | apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx, apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx, apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx, apps/desktop/src/renderer/features/plugin/plugin-motion.css | 49 | 0 | 81 |-| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 143 | 121 | 721 |-| `desktop.shell.main-layout` | desktop | 主窗口壳(标题栏 / 左右栏 / 内容区) | main BrowserWindow → renderer/index.tsx → main-entry.tsx → App → MainLayout (`#/` 受保护壳) | ChromeActions, FeishuConflictDialogHost, GhostMediaLightboxHost, MainLayout, RightSidebar, RightSidebarShell, SessionShareImportWizard, Sidebar, UpdateNoticeDialog, WindowControls | apps/desktop/src/renderer/cindy-brain/GhostMediaLightboxHost.tsx, apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx, apps/desktop/src/renderer/components/layout/BrowserWebviewPool.tsx, apps/desktop/src/renderer/components/layout/ChromeActions.tsx, apps/desktop/src/renderer/components/layout/ContentHeader.tsx, apps/desktop/src/renderer/components/layout/CredentialStoreBanner.tsx, apps/desktop/src/renderer/components/layout/FadeSwitcher.tsx, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx, apps/desktop/src/renderer/components/layout/MainLayout.tsx, apps/desktop/src/renderer/components/layout/RightSidebar.tsx, apps/desktop/src/renderer/components/layout/RightSidebarDetach.tsx, apps/desktop/src/renderer/components/layout/RightSidebarMaximize.tsx, apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/components/layout/chromeActionsGeometry.ts, apps/desktop/src/renderer/components/layout/chromeActionsLayout.ts, apps/desktop/src/renderer/components/layout/railChromeActions.ts, apps/desktop/src/renderer/components/layout/windowDrag.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx, apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx, apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx, apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx, apps/desktop/src/renderer/components/sidebar/Sidebar.tsx, apps/desktop/src/renderer/components/sidebar/SidebarIconButton.tsx, apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx, apps/desktop/src/renderer/components/sidebar/SortableList.tsx, apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx, apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx, apps/desktop/src/renderer/components/sidebar/VendorIcon.tsx, apps/desktop/src/renderer/components/sidebar/VendorReadinessBadge.tsx, apps/desktop/src/renderer/components/sidebar/WorktreeBadge.tsx, apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx, apps/desktop/src/renderer/components/title-bar/MenuButton.tsx, apps/desktop/src/renderer/components/title-bar/WindowControls.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/layout/LayoutRoot.tsx, apps/desktop/src/renderer/layout/PanelDragController.tsx, apps/desktop/src/renderer/layout/PanelDragPrototype.tsx, apps/desktop/src/renderer/layout/collapsePrefs.ts, apps/desktop/src/renderer/layout/layoutDevTools.ts, apps/desktop/src/renderer/layout/panePlacement.tsx, apps/desktop/src/renderer/layout/paneWidths.tsx, apps/desktop/src/renderer/layout/panelMaximize.tsx, apps/desktop/src/renderer/styles/globals.css | 145 | 72 | 286 |+| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 143 | 121 | 722 |+| `desktop.shell.main-layout` | desktop | 主窗口壳(标题栏 / 左右栏 / 内容区) | main BrowserWindow → renderer/index.tsx → main-entry.tsx → App → MainLayout (`#/` 受保护壳) | ChromeActions, FeishuConflictDialogHost, GhostMediaLightboxHost, MainLayout, RightSidebar, RightSidebarShell, SessionShareImportWizard, Sidebar, UpdateNoticeDialog, WindowControls | apps/desktop/src/renderer/cindy-brain/GhostMediaLightboxHost.tsx, apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx, apps/desktop/src/renderer/components/layout/BrowserWebviewPool.tsx, apps/desktop/src/renderer/components/layout/ChromeActions.tsx, apps/desktop/src/renderer/components/layout/ContentHeader.tsx, apps/desktop/src/renderer/components/layout/CredentialStoreBanner.tsx, apps/desktop/src/renderer/components/layout/FadeSwitcher.tsx, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx, apps/desktop/src/renderer/components/layout/MainLayout.tsx, apps/desktop/src/renderer/components/layout/RightSidebar.tsx, apps/desktop/src/renderer/components/layout/RightSidebarDetach.tsx, apps/desktop/src/renderer/components/layout/RightSidebarMaximize.tsx, apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/components/layout/chromeActionsGeometry.ts, apps/desktop/src/renderer/components/layout/chromeActionsLayout.ts, apps/desktop/src/renderer/components/layout/railChromeActions.ts, apps/desktop/src/renderer/components/layout/windowDrag.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx, apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx, apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx, apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx, apps/desktop/src/renderer/components/sidebar/Sidebar.tsx, apps/desktop/src/renderer/components/sidebar/SidebarIconButton.tsx, apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx, apps/desktop/src/renderer/components/sidebar/SortableList.tsx, apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx, apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx, apps/desktop/src/renderer/components/sidebar/VendorIcon.tsx, apps/desktop/src/renderer/components/sidebar/VendorReadinessBadge.tsx, apps/desktop/src/renderer/components/sidebar/WorktreeBadge.tsx, apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx, apps/desktop/src/renderer/components/title-bar/MenuButton.tsx, apps/desktop/src/renderer/components/title-bar/WindowControls.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/layout/LayoutRoot.tsx, apps/desktop/src/renderer/layout/PanelDragController.tsx, apps/desktop/src/renderer/layout/PanelDragPrototype.tsx, apps/desktop/src/renderer/layout/collapsePrefs.ts, apps/desktop/src/renderer/layout/layoutDevTools.ts, apps/desktop/src/renderer/layout/panePlacement.tsx, apps/desktop/src/renderer/layout/paneWidths.tsx, apps/desktop/src/renderer/layout/panelMaximize.tsx, apps/desktop/src/renderer/styles/globals.css | 145 | 72 | 288 || `desktop.skillhub.local` | desktop | SkillHub 本地技能 | hash `/skillhub/local` 及详情 `/skillhub/local/:kind/global/:name`、`/skillhub/local/:kind/project/:projectHash/:name` | InstallTargetPicker, PluginManagementLayout, SkillhubDetailView, SkillhubFeatureLayout, SkillhubHomeView, SkillhubMarketPreviewPanel | apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx | 41 | 0 | 71 || `desktop.skillhub.market` | desktop | SkillHub 市场 | hash `/skillhub/market`(SkillhubMarketListView) | InstallTargetPicker, MarketCard, MarketInfoEditDialog, SkillhubMarketListView, SkillhubMarketPreviewPanel, VisibilityEditorDialog | apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketPreviewPanel.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInfoEditDialog.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketPreviewTree.tsx, apps/desktop/src/renderer/features/skillhub/components/PlatformTagSelector.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillIcon.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillTagList.tsx, apps/desktop/src/renderer/features/skillhub/components/TeamScopePicker.tsx, apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx | 46 | 0 | 59 || `desktop.window.computer-permission-guide` | desktop | 电脑使用权限引导 | `?view=computer-permission-guide` → ComputerPermissionGuideWindow;backdrop 同文件 | ComputerPermissionBackdrop, ComputerPermissionGuideWindow | apps/desktop/src/main/computer-permission-guide/MacComputerPermissionGuideNativeHost.ts, apps/desktop/src/main/computer-permission-guide/placement.ts, apps/desktop/src/main/computer-permission-guide/request.ts, apps/desktop/src/main/computer-permission-guide/switch-target.ts, apps/desktop/src/main/computer-permission-guide/window.ts, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx | 7 | 2 | 9 |