Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(auth): preserve local subscriptions across first login (#3478)
Chris Zhange96eea5cff33
diff --git a/apps/desktop/src/main/__tests__/authBoundaryQuarantine.test.ts b/apps/desktop/src/main/__tests__/authBoundaryQuarantine.test.tsindex 506265ad8d..37fa822996 100644--- a/apps/desktop/src/main/__tests__/authBoundaryQuarantine.test.ts+++ b/apps/desktop/src/main/__tests__/authBoundaryQuarantine.test.ts@@ -39,6 +39,7 @@ import {withGhostSkillProjectionOwnerCommit,withGhostSkillProjectionReadOnlyOwner,withGhostSkillProjectionReconcile,+ withStableOwnerBoundaryMutation,} from '../authBoundaryQuarantine.js';function readPersistedState(): unknown {@@ -104,8 +105,8 @@ describe('Ghost skill projection boundary state', () => {previousOwnerId: 'owner-a',nextOwnerId: null,transitionId: 'transition-b',- updatedAt: 124,- });+ updatedAt: 124,+ });expect(__testing.normalizeRecord({version: 1,@@ -241,6 +242,54 @@ describe('Ghost skill projection boundary state', () => {});});+ it('runs owner-commit rollback before publishing the failed pending state', async () => {+ const rollbackStates: Array<{ phase: string; commitApplied: boolean }> = [];+ await expect(+ withGhostSkillProjectionOwnerCommit({+ previousOwnerId: null,+ nextOwnerId: 'owner-a',+ prepareTransition: async () => {},+ commit: () => {+ throw new Error('local commit failed');+ },+ onCommitFailure: ({ commitApplied }) => {+ rollbackStates.push({+ phase: (readPersistedState() as { phase: string }).phase,+ commitApplied,+ });+ },+ }),+ ).rejects.toThrow('local commit failed');++ expect(rollbackStates).toEqual([{ phase: 'pending', commitApplied: false }]);+ });++ it('reports a durable commit when stable-state publication fails afterward', async () => {+ const originalFsync = fs.fsyncSync.bind(fs);+ let fsyncCalls = 0;+ const stableFileFsyncCall = process.platform === 'win32' ? 3 : 5;+ vi.spyOn(fs, 'fsyncSync').mockImplementation((fd) => {+ fsyncCalls += 1;+ if (fsyncCalls === stableFileFsyncCall) throw new Error('stable fsync failed');+ return originalFsync(fd);+ });+ const failures: boolean[] = [];++ await expect(+ withGhostSkillProjectionOwnerCommit({+ previousOwnerId: null,+ nextOwnerId: 'owner-a',+ prepareTransition: async () => {},+ commit: () => undefined,+ onCommitFailure: ({ commitApplied }) => {+ failures.push(commitApplied);+ },+ }),+ ).rejects.toThrow('stable fsync failed');++ expect(failures).toEqual([true]);+ });+it('requires a teardown hook whenever owner state is missing or mismatched', async () => {await expect(withGhostSkillProjectionOwnerCommit({@@ -276,9 +325,9 @@ describe('Ghost skill projection boundary state', () => {});await expect(withGhostSkillProjectionReconcile('owner-a', async () => 42)).resolves.toBe(42);- await expect(- withGhostSkillProjectionReconcile('owner-b', async () => 42),- ).rejects.toThrow('not stable');+ await expect(withGhostSkillProjectionReconcile('owner-b', async () => 42)).rejects.toThrow(+ 'not stable',+ );});it('fails closed when the durable quarantine record is malformed', async () => {@@ -291,9 +340,9 @@ describe('Ghost skill projection boundary state', () => {fs.writeFileSync(__testing.quarantinePath(), '{not-json', 'utf8');expect(isGhostSkillProjectionBoundaryStableForOwner('owner-a')).toBe(false);- await expect(- withGhostSkillProjectionReconcile('owner-a', async () => 42),- ).rejects.toThrow('quarantined');+ await expect(withGhostSkillProjectionReconcile('owner-a', async () => 42)).rejects.toThrow(+ 'quarantined',+ );});it('skips teardown for an exact stable same-owner commit', async () => {@@ -345,10 +394,12 @@ describe('Ghost skill projection boundary state', () => {const before = fs.readFileSync(__testing.filePath(), 'utf8');process.env.XDT_PASSIVE_SHARED_USER_DATA = '1';- await expect(withGhostSkillProjectionReadOnlyOwner('owner-a', async () => 42)).resolves.toBe(42);- await expect(- withGhostSkillProjectionReadOnlyOwner('owner-b', async () => 42),- ).rejects.toThrow('another active session');+ await expect(withGhostSkillProjectionReadOnlyOwner('owner-a', async () => 42)).resolves.toBe(+ 42,+ );+ await expect(withGhostSkillProjectionReadOnlyOwner('owner-b', async () => 42)).rejects.toThrow(+ 'another active session',+ );await expect(withGhostSkillProjectionOwnerCommit({previousOwnerId: 'owner-a',@@ -386,6 +437,41 @@ describe('Ghost skill projection boundary state', () => {await expect(reconcileResult).resolves.toBe(42);});+ it('rejects a stable-owner mutation after a concurrent owner replacement wins', async () => {+ await withGhostSkillProjectionOwnerCommit({+ previousOwnerId: null,+ nextOwnerId: 'owner-a',+ prepareTransition: async () => {},+ commit: () => undefined,+ });+ let releaseCommit!: () => void;+ const commitBlocked = new Promise<void>((resolve) => {+ releaseCommit = resolve;+ });+ const commitStarted = vi.fn();+ const ownerCommit = withGhostSkillProjectionOwnerCommit({+ previousOwnerId: 'owner-a',+ nextOwnerId: 'owner-b',+ prepareTransition: async () => {},+ commit: async () => {+ commitStarted();+ await commitBlocked;+ },+ });+ await vi.waitFor(() => expect(commitStarted).toHaveBeenCalledOnce());+ const mutation = vi.fn(async () => 42);+ const staleOwnerMutation = withStableOwnerBoundaryMutation('owner-a', mutation);+ await Promise.resolve();+ expect(mutation).not.toHaveBeenCalled();++ releaseCommit();+ await ownerCommit;+ await expect(staleOwnerMutation).rejects.toThrow(+ 'Ghost skill projection is not stable for the active owner',+ );+ expect(mutation).not.toHaveBeenCalled();+ });+it('keeps a sticky process quarantine when stable publication is uncertain', async () => {const originalFsync = fs.fsyncSync.bind(fs);let fsyncCalls = 0;diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.tsindex 29660efc52..50b873f532 100644--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts@@ -758,6 +758,122 @@ describe('auth login-flow reset', () => {expect(refreshBody).not.toContain('clearAuth({ notify: false });');});+ it('reserves local namespaces before publishing a cloud owner', () => {+ const cloudStart = source.indexOf('async function withCloudOwnerCommit(');+ const prepareStart = source.indexOf('prepareCommit: async () => {', cloudStart);+ const prepareEnd = source.indexOf('\n },\n commit: async () => {', prepareStart);+ const prepareBody = source.slice(prepareStart, prepareEnd);++ expect(prepareBody).toContain(+ 'rollbackReservation = reserveCloudOwnerData(opts.nextOwnerId, opts.previousOwnerId);',+ );+ expect(prepareBody.indexOf('reserveCloudOwnerData')).toBeLessThan(+ prepareBody.indexOf('await opts.prepareCommit?.();'),+ );+ expect(source).toContain('await repairStableCloudOwnerDataReservations(currentUser.id);');+ expect(source).toContain('if (reservation && !reservation.finalize())');+ expect(source).toContain('if (!reservation.rollback())');+ expect(source).toContain('if (boundaryCommitApplied || commitApplied) return;');++ const failureStart = source.indexOf(+ 'onCommitFailure: ({ commitApplied: boundaryCommitApplied }) => {',+ cloudStart,+ );+ const failureEnd = source.indexOf('\n },\n });', failureStart);+ const failureBody = source.slice(failureStart, failureEnd);+ expect(failureBody).toContain('if (boundaryCommitApplied || commitApplied) return;');+ expect(failureBody.indexOf('if (!reservation.rollback())')).toBeLessThan(+ failureBody.indexOf('rollbackReservation = null;'),+ );+ const finallyStart = source.indexOf(' } finally {', failureEnd);+ const finallyBody = source.slice(finallyStart, source.indexOf('\n }\n', finallyStart));+ expect(finallyBody).toContain('if (!committed && !commitApplied)');++ const repairStart = source.indexOf(+ 'function repairStableCloudOwnerDataReservationsWhileLocked(',+ );+ const repairEnd = source.indexOf(+ '\n}\n\nasync function repairStableCloudOwnerDataReservations(',+ repairStart,+ );+ const repairBody = source.slice(repairStart, repairEnd);+ expect(repairBody).toContain('reserveCommittedLocalProfileDataOwnerDetailed(');+ expect(repairBody).toContain(+ 'const profileReservationOwnerId = resolveProfileReservationOwnerId(ownerId);',+ );+ expect(repairBody).toContain(+ 'reserveCommittedLocalProfileDataOwnerDetailed(\n profileReservationOwnerId,',+ );+ expect(repairBody).toContain(+ 'reserveCommittedLegacyNativeProviderAuthOwner(authoritativeOwnerId)',+ );+ expect(repairBody).not.toContain('reserveLocalProfileDataOwnerDetailed(');+ expect(repairBody).not.toContain('reserveLegacyNativeProviderAuthOwnerDetailed(ownerId)');+ expect(repairBody).toContain('remains authenticated with local adoption fail-closed');+ expect(repairBody).not.toContain('throw new Error');+ const serializedRepairStart = source.indexOf(+ 'async function repairStableCloudOwnerDataReservations(',+ );+ const serializedRepairEnd = source.indexOf(+ '\n}\n\nfunction commitCloudAppSession(',+ serializedRepairStart,+ );+ const serializedRepairBody = source.slice(serializedRepairStart, serializedRepairEnd);+ expect(serializedRepairBody).toContain(+ 'withStableOwnerBoundaryMutation(ownerId',+ );+ expect(serializedRepairBody).toContain(+ 'repairStableCloudOwnerDataReservationsWhileLocked(ownerId)',+ );++ const reserveStart = source.indexOf('function reserveCloudOwnerData(');+ const reserveEnd = source.indexOf(+ '\n}\n\nfunction repairStableCloudOwnerDataReservationsWhileLocked(',+ reserveStart,+ );+ const reserveBody = source.slice(reserveStart, reserveEnd);+ expect(reserveBody).toContain(+ 'const profileReservationOwnerId = resolveProfileReservationOwnerId(ownerId);',+ );+ expect(reserveBody).toContain(+ 'reserveLocalProfileDataOwnerDetailed(\n profileReservationOwnerId,',+ );+ expect(reserveBody).toContain(+ 'releaseLocalProfileDataOwner(\n profileReservationOwnerId,',+ );+ expect(reserveBody).toContain(+ "if (nativeReservation.status === 'claimed' && nativeReservation.claimToken)",+ );+ expect(reserveBody).not.toContain(+ "profileReservation.status === 'claimed' &&\n nativeReservation.status === 'claimed'",+ );+ expect(reserveBody).toContain('const authoritativeOwnerId = profileReservation.ownerId;');+ expect(reserveBody).toContain(+ 'reserveLegacyNativeProviderAuthOwnerDetailed(authoritativeOwnerId)',+ );+ expect(reserveBody).toContain(+ "throw new Error('local profile and native provider ownership reservations disagree')",+ );+ expect(reserveBody).toContain(+ 'finalize: () => recoverCloudOwnerDataReservations(authoritativeOwnerId)',+ );++ const migrationStart = source.indexOf(+ 'async function migrateLocalProviderBindingsAfterCloudCommit(ownerId: string): Promise<void> {',+ );+ const migrationEnd = source.indexOf(+ '\n}\n\nasync function finishColdStartSignedOut(',+ migrationStart,+ );+ const migrationBody = source.slice(migrationStart, migrationEnd);+ expect(migrationBody).toContain(+ 'if (!(await repairStableCloudOwnerDataReservations(ownerId))) return;',+ );+ expect(migrationBody.indexOf('repairStableCloudOwnerDataReservations')).toBeLessThan(+ migrationBody.indexOf('migrateLocalNativeProviderAuthBindings'),+ );+ });+it('synchronizes canary flags on every path that establishes a new auth identity', () => {expect(source).not.toContain('canaryFlagStore.sync(false)');expect(source.match(/scheduleCanaryFlagSync\(\{/g)).toHaveLength(3);diff --git a/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts b/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.tsindex 6354e2158e..b29b5a6f25 100644--- a/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts+++ b/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts@@ -26,6 +26,10 @@ describe('passive shared-userData instance auth isolation', () => {resolve(process.cwd(), 'src/main/authManager.ts'),'utf8',).replace(/\r\n/g, '\n');+ const bootstrapSource = readFileSync(+ resolve(process.cwd(), 'src/main/bootstrap-electron.ts'),+ 'utf8',+ ).replace(/\r\n/g, '\n');const sliceBody = (startAnchor: string, endAnchor: string): string => {const start = authSource.indexOf(startAnchor);@@ -152,6 +156,70 @@ describe('passive shared-userData instance auth isolation', () => {expect(authSource).toContain('passiveLocalSignOut = false;');});+ it('稳定登录的 passive initialize 不修复或消费本机 owner 预留', () => {+ const start = authSource.indexOf('// This owner is already durably authenticated.');+ const end = authSource.indexOf(+ 'migrateLocalProviderBindingsAfterCloudCommit(currentUser.id);',+ start,+ );+ const body = authSource.slice(start, end);++ const passiveGuard = body.indexOf('if (!isPassiveSharedUserDataInstance()) {');+ const repair = body.indexOf('repairStableCloudOwnerDataReservations(currentUser.id);');+ expect(passiveGuard).toBeGreaterThan(-1);+ expect(repair).toBeGreaterThan(passiveGuard);+ expect(body.indexOf('commitCloudAppSession(currentUser.id);')).toBeGreaterThan(repair);++ const migrationHelper = sliceBody(+ 'async function migrateLocalProviderBindingsAfterCloudCommit(ownerId: string): Promise<void> {',+ '\n}\n',+ );+ expect(migrationHelper).toContain('if (isPassiveSharedUserDataInstance()) return;');++ 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()) {',+ );+ expect(dbPassiveGuard).toBeGreaterThan(-1);+ const passivePreflight = beforeEnsureReady.indexOf(+ 'inspectPassiveLocalProfileAdoption(',+ dbPassiveGuard,+ );+ expect(passivePreflight).toBeGreaterThan(dbPassiveGuard);+ const passiveDepsEnd = beforeEnsureReady.indexOf('\n ),', passivePreflight);+ const passiveDeps = beforeEnsureReady.slice(passivePreflight, passiveDepsEnd);+ expect(passiveDeps).toContain('() => hasExclusiveSharedLegacyUserDataAccess()');+ expect(+ beforeEnsureReady.indexOf("if (passivePreflight.status === 'required')", passivePreflight),+ ).toBeGreaterThan(passivePreflight);+ expect(beforeEnsureReady.indexOf('throw new Error(', passivePreflight)).toBeGreaterThan(+ passivePreflight,+ );+ const exclusiveAdoptionGate = beforeEnsureReady.lastIndexOf(+ '() => hasExclusiveSharedLegacyUserDataAccess()',+ );+ expect(exclusiveAdoptionGate).toBeGreaterThan(dbPassiveGuard);+ expect(beforeEnsureReady.indexOf('runLegacyUserDataMigrationForUser(user.id)')).toBeGreaterThan(+ dbPassiveGuard,+ );+ expect(beforeEnsureReady.indexOf('adoptLocalProfileDatabase(')).toBeGreaterThan(+ dbPassiveGuard,+ );+ expect(exclusiveAdoptionGate).toBeGreaterThan(+ beforeEnsureReady.indexOf('adoptLocalProfileDatabase('),+ );+ const adoptionFailure = beforeEnsureReady.indexOf(+ "if (localProfileMigration.status === 'failed') {",+ );+ expect(adoptionFailure).toBeGreaterThan(dbPassiveGuard);+ expect(beforeEnsureReady.indexOf('throw new Error(', adoptionFailure)).toBeGreaterThan(+ adoptionFailure,+ );+ expect(beforeEnsureReady).not.toContain('continuing with cloud database');+ });+it('relogin marker:passive 不消费整机一份的 marker,也不删 primary 的 token', () => {const start = authSource.indexOf('const reloginFlag = readReloginFlag();');const end = authSource.indexOf('// Old Feishu-auth refresh tokens', start);diff --git a/apps/desktop/src/main/__tests__/devStartupStatus.test.ts b/apps/desktop/src/main/__tests__/devStartupStatus.test.tsindex fabbe36545..ba8ca1a7da 100644--- a/apps/desktop/src/main/__tests__/devStartupStatus.test.ts+++ b/apps/desktop/src/main/__tests__/devStartupStatus.test.ts@@ -2,7 +2,7 @@ import fs from 'node:fs';import os from 'node:os';import path from 'node:path';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {beginDesktopDevInstance,@@ -12,6 +12,7 @@ import {recordDesktopDevAuthStartupResult,recordDesktopDevLocalDbStartupResult,} from '../devStartupStatus.js';+import { withLocalProfileMigrationStartupBarrier } from '../localProfileDataMigration.js';describe('devStartupStatus', () => {let tempDir: string;@@ -31,10 +32,11 @@ describe('devStartupStatus', () => {fs.rmSync(tempDir, { recursive: true, force: true });});- it('marks startup ready only after both the window and application are ready', () => {+ it('marks startup ready only after both the window and application are ready', async () => {fs.writeFileSync(statusPath, '{"state":"pending"}\n');- cleanup = beginDesktopDevInstance({+ cleanup = await beginDesktopDevInstance({userDataDir: tempDir,+ dbFilePrefix: 'cindy',rootDir: path.join(tempDir, 'repo'),commit: 'abc123',mode: 'remote',@@ -73,10 +75,11 @@ describe('devStartupStatus', () => {});});- it('supports application readiness arriving before ready-to-show', () => {+ it('supports application readiness arriving before ready-to-show', async () => {fs.writeFileSync(statusPath, '{"state":"pending"}\n');- cleanup = beginDesktopDevInstance({+ cleanup = await beginDesktopDevInstance({userDataDir: tempDir,+ dbFilePrefix: 'cindy',rootDir: tempDir,passive: false,isolated: false,@@ -92,8 +95,9 @@ describe('devStartupStatus', () => {it('keeps restart pending when logged-out is only the auth timeout fallback', async () => {fs.writeFileSync(statusPath, '{"state":"pending"}\n');- cleanup = beginDesktopDevInstance({+ cleanup = await beginDesktopDevInstance({userDataDir: tempDir,+ dbFilePrefix: 'cindy',rootDir: tempDir,passive: false,isolated: false,@@ -122,8 +126,9 @@ describe('devStartupStatus', () => {it('waits for localDb when manual login supersedes the timed-out refresh', async () => {fs.writeFileSync(statusPath, '{"state":"pending"}\n');- cleanup = beginDesktopDevInstance({+ cleanup = await beginDesktopDevInstance({userDataDir: tempDir,+ dbFilePrefix: 'cindy',rootDir: tempDir,passive: false,isolated: false,@@ -155,10 +160,11 @@ describe('devStartupStatus', () => {});});- it('preserves a concrete main-process failure for the restart waiter', () => {+ it('preserves a concrete main-process failure for the restart waiter', async () => {fs.writeFileSync(statusPath, '{"state":"pending"}\n');- cleanup = beginDesktopDevInstance({+ cleanup = await beginDesktopDevInstance({userDataDir: tempDir,+ dbFilePrefix: 'cindy',rootDir: tempDir,mode: 'remote',passive: true,@@ -186,10 +192,11 @@ describe('devStartupStatus', () => {});});- it('forwards the localDb migration code and message to the restart waiter', () => {+ it('forwards the localDb migration code and message to the restart waiter', async () => {fs.writeFileSync(statusPath, '{"state":"pending"}\n');- cleanup = beginDesktopDevInstance({+ cleanup = await beginDesktopDevInstance({userDataDir: tempDir,+ dbFilePrefix: 'cindy',rootDir: tempDir,passive: false,isolated: false,@@ -213,10 +220,11 @@ describe('devStartupStatus', () => {});});- it('does not replace a completed startup with a later runtime failure', () => {+ it('does not replace a completed startup with a later runtime failure', async () => {fs.writeFileSync(statusPath, '{"state":"pending"}\n');- cleanup = beginDesktopDevInstance({+ cleanup = await beginDesktopDevInstance({userDataDir: tempDir,+ dbFilePrefix: 'cindy',rootDir: tempDir,passive: false,isolated: false,@@ -234,9 +242,10 @@ describe('devStartupStatus', () => {))).toMatchObject({ state: 'ready' });});- it('cleanup never deletes a record that has been replaced by another owner', () => {- cleanup = beginDesktopDevInstance({+ it('cleanup never deletes a record that has been replaced by another owner', async () => {+ cleanup = await beginDesktopDevInstance({userDataDir: tempDir,+ dbFilePrefix: 'cindy',rootDir: tempDir,passive: false,isolated: false,@@ -251,4 +260,74 @@ describe('devStartupStatus', () => {expect(fs.existsSync(instancePath)).toBe(true);});++ it('publishes the instance record only after an in-flight adoption releases its barrier', async () => {+ let releaseBarrier!: () => void;+ let barrierEntered!: () => void;+ const entered = new Promise<void>((resolve) => {+ barrierEntered = resolve;+ });+ const holdBarrier = new Promise<void>((resolve) => {+ releaseBarrier = resolve;+ });+ const adoption = withLocalProfileMigrationStartupBarrier(tempDir, 'cindy', async () => {+ barrierEntered();+ await holdBarrier;+ });+ await entered;++ const registration = beginDesktopDevInstance({+ userDataDir: tempDir,+ dbFilePrefix: 'cindy',+ rootDir: tempDir,+ passive: false,+ isolated: false,+ pid: 4250,+ instanceId: 'waited-for-adoption',+ });+ expect(fs.existsSync(path.join(tempDir, '.dev-instances', '4250.json'))).toBe(false);++ releaseBarrier();+ await adoption;+ cleanup = await registration;+ expect(+ JSON.parse(fs.readFileSync(path.join(tempDir, '.dev-instances', '4250.json'), 'utf8')),+ ).toMatchObject({ instanceId: 'waited-for-adoption' });+ });++ it('retries a transient Windows rename lock while publishing the mandatory instance record', async () => {+ const instancePath = path.join(tempDir, '.dev-instances', '4251.json');+ fs.mkdirSync(path.dirname(instancePath), { recursive: true });+ fs.writeFileSync(instancePath, '{"instanceId":"stale-owner"}\n');++ const realRename = fs.renameSync;+ let transientFailures = 2;+ const renameSpy = vi.spyOn(fs, 'renameSync').mockImplementation(((from: string, to: string) => {+ if (String(from).endsWith('.tmp') && String(to) === instancePath && transientFailures > 0) {+ transientFailures -= 1;+ throw Object.assign(new Error('EBUSY'), { code: 'EBUSY' });+ }+ return realRename(from as never, to as never);+ }) as typeof fs.renameSync);++ try {+ cleanup = await beginDesktopDevInstance({+ userDataDir: tempDir,+ dbFilePrefix: 'cindy',+ rootDir: tempDir,+ passive: false,+ isolated: false,+ pid: 4251,+ instanceId: 'replacement-owner',+ });+ } finally {+ renameSpy.mockRestore();+ }++ expect(transientFailures).toBe(0);+ expect(JSON.parse(fs.readFileSync(instancePath, 'utf8'))).toMatchObject({+ instanceId: 'replacement-owner',+ state: 'starting',+ });+ });});diff --git a/apps/desktop/src/main/__tests__/localProfileDataMigration.test.ts b/apps/desktop/src/main/__tests__/localProfileDataMigration.test.tsnew file mode 100644index 0000000000..fb027e7f96--- /dev/null+++ b/apps/desktop/src/main/__tests__/localProfileDataMigration.test.ts@@ -0,0 +1,1319 @@+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import originalFs from 'original-fs';+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ adoptLocalProfileDatabase,+ createProductionLocalProfileDataMigrationDeps,+ inspectPassiveLocalProfileAdoption,+ LOCAL_PROFILE_MIGRATION_LOCK_DB_SUFFIX,+ LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX,+ LOCAL_PROFILE_MIGRATION_TMP_SUFFIX,+ recoverPendingLocalProfileDataOwner,+ reserveCommittedLocalProfileDataOwner,+ reserveCommittedLocalProfileDataOwnerDetailed,+ reserveLocalProfileDataOwner,+ reserveLocalProfileDataOwnerDetailed,+ releaseLocalProfileDataOwner,+ type LocalProfileDataMigrationDeps,+} from '../localProfileDataMigration.js';+import { createBetterSqliteDatabase } from '../localDb/betterSqliteFactory.js';++const roots: string[] = [];++async function fixture(): Promise<{ root: string; deps: LocalProfileDataMigrationDeps }> {+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-local-profile-migration-'));+ roots.push(root);+ return {+ root,+ deps: {+ userDataDir: root,+ dbFilePrefix: 'cindy',+ fs: {+ pathExists: async (file) =>+ fs.access(file).then(+ () => true,+ () => false,+ ),+ readFile: (file) => fs.readFile(file, 'utf8'),+ readDir: (directory) => fs.readdir(directory),+ backupDatabase: (source, target) => fs.copyFile(source, target),+ link: (source, target) => fs.link(source, target),+ copyNoReplace: (source, target) => fs.copyFile(source, target),+ removeIfExists: (file) => fs.rm(file, { force: true }),+ },+ },+ };+}++afterEach(async () => {+ vi.restoreAllMocks();+ await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })));+});++describe('adoptLocalProfileDatabase', () => {+ it('reserves the first cloud owner synchronously and rejects a different owner', async () => {+ const { root } = await fixture();++ expect(reserveLocalProfileDataOwner('owner-a', root, 'cindy')).toBe('claimed');+ expect(reserveLocalProfileDataOwner('owner-a', root, 'cindy')).toBe('already-owned');+ expect(reserveLocalProfileDataOwner('owner-b', root, 'cindy')).toBe('owned-by-other');+ });++ it.each(['', '{'])('fails closed for a malformed owner marker containing %j', async (contents) => {+ const { root } = await fixture();+ const marker = path.join(root, `cindy-local-v1${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`);+ await fs.writeFile(marker, contents);++ expect(reserveLocalProfileDataOwner('owner-a', root, 'cindy')).toBe('failed');+ expect(reserveLocalProfileDataOwner('owner-b', root, 'cindy')).toBe('failed');+ await expect(fs.readFile(marker, 'utf8')).resolves.toBe(contents);+ });++ it('falls back to an exclusive marker copy when hard links are unsupported', async () => {+ const { root } = await fixture();+ const linkSpy = vi.spyOn(originalFs, 'linkSync').mockImplementation(() => {+ throw Object.assign(new Error('hard links unsupported'), { code: 'EOPNOTSUPP' });+ });++ expect(reserveLocalProfileDataOwner('owner-a', root, 'cindy')).toBe('claimed');+ expect(reserveLocalProfileDataOwner('owner-b', root, 'cindy')).toBe('owned-by-other');+ expect(linkSpy).toHaveBeenCalled();+ const marker = path.join(root, `cindy-local-v1${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`);+ await expect(fs.readFile(marker, 'utf8').then(JSON.parse)).resolves.toMatchObject({+ ownerId: 'owner-a',+ });+ });++ it('recovers a truncated fallback marker from its pending publication', async () => {+ const { root } = await fixture();+ const marker = path.join(root, `cindy-local-v1${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`);+ const pending = `${marker}.pending`;+ vi.spyOn(originalFs, 'linkSync').mockImplementation(() => {+ throw Object.assign(new Error('hard links unsupported'), { code: 'EOPNOTSUPP' });+ });+ const originalCopyFileSync = originalFs.copyFileSync;+ let interrupted = true;+ vi.spyOn(originalFs, 'copyFileSync').mockImplementation((...args) => {+ if (interrupted && String(args[1]) === pending) {+ interrupted = false;+ originalFs.writeFileSync(pending, '{"ownerId":');+ throw Object.assign(new Error('marker copy interrupted'), { code: 'EIO' });+ }+ return originalCopyFileSync.apply(originalFs, args);+ });++ expect(reserveLocalProfileDataOwner('owner-a', root, 'cindy')).toBe('failed');+ await expect(fs.access(marker)).rejects.toThrow();+ await expect(fs.readFile(pending, 'utf8')).resolves.toBe('{"ownerId":');++ expect(reserveLocalProfileDataOwner('owner-a', root, 'cindy')).toBe('claimed');+ await expect(fs.readFile(marker, 'utf8').then(JSON.parse)).resolves.toMatchObject({+ ownerId: 'owner-a',+ });+ await expect(fs.access(pending)).rejects.toThrow();+ });++ it('restores an atomic-write backup before deciding ownership', async () => {+ const { root } = await fixture();+ const marker = path.join(root, `cindy-local-v1${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`);+ await fs.writeFile(`${marker}.bak`, JSON.stringify({ ownerId: 'owner-a' }));++ expect(reserveLocalProfileDataOwner('owner-b', root, 'cindy')).toBe('owned-by-other');+ await expect(fs.readFile(marker, 'utf8')).resolves.toContain('owner-a');+ await expect(fs.access(`${marker}.bak`)).rejects.toThrow();+ });++ it('falls back to exclusive snapshot copy when hard links are unsupported', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');+ const fallbackDeps: LocalProfileDataMigrationDeps = {+ ...deps,+ fs: {+ ...deps.fs,+ link: async () => {+ throw Object.assign(new Error('hard links unsupported'), { code: 'EOPNOTSUPP' });+ },+ },+ };++ await expect(adoptLocalProfileDatabase('owner-a', fallbackDeps)).resolves.toMatchObject({+ status: 'adopted',+ });+ await expect(fs.readFile(target, 'utf8')).resolves.toBe('local-db');+ });++ it('keeps the cloud target when exclusive snapshot copy loses the race', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');+ const fallbackDeps: LocalProfileDataMigrationDeps = {+ ...deps,+ fs: {+ ...deps.fs,+ link: async () => {+ throw Object.assign(new Error('hard links unsupported'), { code: 'EXDEV' });+ },+ copyNoReplace: async (_source, destination) => {+ await fs.writeFile(destination, 'cloud-db');+ throw Object.assign(new Error('target already exists'), { code: 'EEXIST' });+ },+ },+ };++ await expect(adoptLocalProfileDatabase('owner-a', fallbackDeps)).resolves.toEqual({+ status: 'target-exists',+ });+ await expect(fs.readFile(target, 'utf8')).resolves.toBe('cloud-db');+ });++ it('retries after an interrupted fallback copy leaves a pending target', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ const pending = `${target}.local-profile-copy-pending`;+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');+ let interrupted = true;+ const recoveringDeps: LocalProfileDataMigrationDeps = {+ ...deps,+ fs: {+ ...deps.fs,+ link: async () => {+ throw Object.assign(new Error('hard links unsupported'), { code: 'EOPNOTSUPP' });+ },+ copyNoReplace: async (source, destination) => {+ if (interrupted) {+ interrupted = false;+ await fs.writeFile(+ pending,+ JSON.stringify({ version: 1, attemptId: 'interrupted', phase: 'copying' }),+ );+ await fs.writeFile(destination, 'partial');+ throw Object.assign(new Error('copy interrupted'), { code: 'EIO' });+ }+ await fs.copyFile(source, destination);+ },+ },+ };++ await expect(adoptLocalProfileDatabase('owner-a', recoveringDeps)).resolves.toMatchObject({+ status: 'failed',+ });+ await expect(adoptLocalProfileDatabase('owner-a', recoveringDeps)).resolves.toMatchObject({+ status: 'adopted',+ });+ await expect(fs.readFile(target, 'utf8')).resolves.toBe('local-db');+ await expect(fs.access(pending)).rejects.toThrow();+ });++ it('preserves a raced cloud target when pending-marker cleanup fails', async () => {+ const { root } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ const pending = `${target}.local-profile-copy-pending`;+ const source = path.join(root, 'cindy-local-v1.db');+ await fs.writeFile(source, 'local-db');+ const productionDeps = createProductionLocalProfileDataMigrationDeps(root, 'cindy');+ const racingDeps: LocalProfileDataMigrationDeps = {+ ...productionDeps,+ fs: {+ ...productionDeps.fs,+ backupDatabase: async (sourcePath, destination) => fs.copyFile(sourcePath, destination),+ link: async () => {+ throw Object.assign(new Error('hard links unsupported'), { code: 'EXDEV' });+ },+ },+ };+ const originalOpen = originalFs.promises.open;+ const originalRemove = originalFs.promises.rm;+ let cleanupFailed = false;+ vi.spyOn(originalFs.promises, 'open').mockImplementation(async (...args) => {+ if (String(args[0]) === target && args[1] === 'wx') {+ await fs.writeFile(target, 'cloud-db');+ throw Object.assign(new Error('target already exists'), { code: 'EEXIST' });+ }+ return originalOpen.apply(originalFs.promises, args);+ });+ vi.spyOn(originalFs.promises, 'rm').mockImplementation(async (...args) => {+ if (String(args[0]) === pending) {+ cleanupFailed = true;+ throw Object.assign(new Error('pending marker is locked'), { code: 'EBUSY' });+ }+ return originalRemove.apply(originalFs.promises, args);+ });++ await expect(adoptLocalProfileDatabase('owner-a', racingDeps)).resolves.toEqual({+ status: 'target-exists',+ });+ await expect(fs.readFile(target, 'utf8')).resolves.toBe('cloud-db');+ expect(cleanupFailed).toBe(true);+ await expect(fs.access(pending)).resolves.toBeUndefined();++ await expect(adoptLocalProfileDatabase('owner-a', racingDeps)).resolves.toEqual({+ status: 'target-exists',+ });+ await expect(fs.readFile(target, 'utf8')).resolves.toBe('cloud-db');+ });++ it('persists the fallback claiming marker before opening the exclusive target', async () => {+ const { root } = await fixture();+ const source = path.join(root, 'cindy-local-v1.db');+ const target = path.join(root, 'cindy-owner-a.db');+ const pending = `${target}.local-profile-copy-pending`;+ const sourceDb = createBetterSqliteDatabase(source);+ sourceDb.exec('CREATE TABLE items (value TEXT NOT NULL)');+ sourceDb.prepare('INSERT INTO items (value) VALUES (?)').run('local');+ sourceDb.close();++ const deps = createProductionLocalProfileDataMigrationDeps(root, 'cindy');+ const fallbackDeps: LocalProfileDataMigrationDeps = {+ ...deps,+ fs: {+ ...deps.fs,+ link: async () => {+ throw Object.assign(new Error('hard links unsupported'), { code: 'EOPNOTSUPP' });+ },+ },+ };+ const originalOpen = originalFs.promises.open;+ let markerBeforeTargetClaim: string | undefined;+ const openSpy = vi.spyOn(originalFs.promises, 'open').mockImplementation(async (...args) => {+ const file = String(args[0]);+ if (file === target && args[1] === 'wx') {+ markerBeforeTargetClaim = await fs.readFile(pending, 'utf8');+ }+ return originalOpen.apply(originalFs.promises, args);+ });++ await expect(adoptLocalProfileDatabase('owner-a', fallbackDeps)).resolves.toMatchObject({+ status: 'adopted',+ });+ expect(JSON.parse(markerBeforeTargetClaim!)).toMatchObject({+ version: 1,+ phase: 'claiming',+ });+ expect(openSpy).toHaveBeenCalled();+ await expect(fs.access(pending)).rejects.toThrow();+ });++ it('fails closed when target ownership is unproven after the fallback claim is interrupted', async () => {+ const { root } = await fixture();+ const source = path.join(root, 'cindy-local-v1.db');+ const target = path.join(root, 'cindy-owner-a.db');+ const pending = `${target}.local-profile-copy-pending`;+ const sourceDb = createBetterSqliteDatabase(source);+ sourceDb.exec('CREATE TABLE items (value TEXT NOT NULL)');+ sourceDb.prepare('INSERT INTO items (value) VALUES (?)').run('local');+ sourceDb.close();++ const deps = createProductionLocalProfileDataMigrationDeps(root, 'cindy');+ const fallbackDeps: LocalProfileDataMigrationDeps = {+ ...deps,+ fs: {+ ...deps.fs,+ link: async () => {+ throw Object.assign(new Error('hard links unsupported'), { code: 'EOPNOTSUPP' });+ },+ },+ };+ const originalOpen = originalFs.promises.open;+ let interruptTargetOpen = true;+ vi.spyOn(originalFs.promises, 'open').mockImplementation(async (...args) => {+ const file = String(args[0]);+ if (interruptTargetOpen && file === target && args[1] === 'wx') {+ interruptTargetOpen = false;+ await fs.writeFile(target, '');+ throw Object.assign(new Error('process interrupted after target claim'), { code: 'EIO' });+ }+ return originalOpen.apply(originalFs.promises, args);+ });++ await expect(adoptLocalProfileDatabase('owner-a', fallbackDeps)).resolves.toMatchObject({+ status: 'failed',+ });+ await expect(fs.readFile(pending, 'utf8').then(JSON.parse)).resolves.toMatchObject({+ phase: 'claiming',+ });+ await expect(fs.readFile(target, 'utf8')).resolves.toBe('');++ await expect(adoptLocalProfileDatabase('owner-a', fallbackDeps)).resolves.toEqual({+ status: 'failed',+ error: 'database copy publication has an unproven target owner',+ });+ await expect(fs.readFile(target, 'utf8')).resolves.toBe('');+ await expect(fs.readFile(pending, 'utf8').then(JSON.parse)).resolves.toMatchObject({+ phase: 'claiming',+ });+ });++ it('does not reclaim an invalid marker while another process holds the migration lock', async () => {+ const { root } = await fixture();+ const marker = path.join(root, `cindy-local-v1${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`);+ const lockDb = createBetterSqliteDatabase(`${marker}${LOCAL_PROFILE_MIGRATION_LOCK_DB_SUFFIX}`);+ await fs.writeFile(marker, '{');+ lockDb.exec('BEGIN IMMEDIATE');+ try {+ expect(reserveLocalProfileDataOwner('owner-a', root, 'cindy')).toBe('failed');+ await expect(fs.readFile(marker, 'utf8')).resolves.toBe('{');+ } finally {+ lockDb.exec('ROLLBACK');+ lockDb.close();+ }++ expect(reserveLocalProfileDataOwner('owner-a', root, 'cindy')).toBe('failed');+ expect(reserveLocalProfileDataOwner('owner-b', root, 'cindy')).toBe('failed');+ await expect(fs.readFile(marker, 'utf8')).resolves.toBe('{');+ });++ it('releases only the marker created by the matching claim token', async () => {+ const { root } = await fixture();+ const reservation = reserveLocalProfileDataOwnerDetailed('owner-a', root, 'cindy');+ expect(reservation).toMatchObject({ status: 'claimed', claimToken: expect.any(String) });+ expect(reserveLocalProfileDataOwnerDetailed('owner-a', root, 'cindy')).toEqual({+ status: 'already-owned',+ ownerId: 'owner-a',+ });+ const marker = path.join(root, `cindy-local-v1${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`);+ const beforeWrongToken = await fs.readFile(marker, 'utf8');+ expect(releaseLocalProfileDataOwner('owner-a', root, 'cindy', 'wrong-token')).toBe(false);+ await expect(fs.readFile(marker, 'utf8')).resolves.toBe(beforeWrongToken);+ expect(reserveLocalProfileDataOwner('owner-b', root, 'cindy')).toBe('owned-by-other');+ expect(releaseLocalProfileDataOwner('owner-a', root, 'cindy', reservation.claimToken!)).toBe(+ true,+ );+ expect(reserveLocalProfileDataOwner('owner-b', root, 'cindy')).toBe('claimed');+ });++ it('fails closed when a released marker cannot be restored atomically', async () => {+ const { root } = await fixture();+ const marker = path.join(root, `cindy-local-v1${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`);+ const candidate = `${marker}.release`;+ const reservation = reserveLocalProfileDataOwnerDetailed('owner-a', root, 'cindy');+ expect(reservation).toMatchObject({ status: 'claimed', claimToken: expect.any(String) });++ const originalRenameSync = originalFs.renameSync;+ vi.spyOn(originalFs, 'renameSync').mockImplementation((source, destination) => {+ if (String(source) === candidate && String(destination) === marker) {+ throw Object.assign(new Error('marker restore temporarily unavailable'), { code: 'EBUSY' });+ }+ return originalRenameSync.apply(originalFs, [source, destination]);+ });++ expect(releaseLocalProfileDataOwner('owner-a', root, 'cindy', 'c1-deadbeef')).toBe(false);+ await expect(fs.access(marker)).rejects.toThrow();+ await expect(fs.access(candidate)).resolves.toBeUndefined();+ expect(reserveLocalProfileDataOwner('owner-b', root, 'cindy')).toBe('failed');+ });++ it('finalizes a pending claim for the committed owner', async () => {+ const { root } = await fixture();+ const marker = path.join(root, `cindy-local-v1${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`);+ const openSpy = vi.spyOn(originalFs, 'openSync');+ const reservation = reserveLocalProfileDataOwnerDetailed('owner-a', root, 'cindy');+ expect(reservation).toMatchObject({ status: 'claimed', claimToken: expect.any(String) });++ expect(recoverPendingLocalProfileDataOwner('owner-a', root, 'cindy')).toBe('finalized');+ expect(openSpy).toHaveBeenCalledWith(marker, 'r+');+ expect(releaseLocalProfileDataOwner('owner-a', root, 'cindy', reservation.claimToken!)).toBe(+ false,+ );+ expect(reserveLocalProfileDataOwner('owner-b', root, 'cindy')).toBe('owned-by-other');+ });++ it('finalizes a committed claim stranded in a release candidate', async () => {+ const { root } = await fixture();+ const marker = path.join(root, `cindy-local-v1${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`);+ const candidate = `${marker}.release`;+ const reservation = reserveLocalProfileDataOwnerDetailed('owner-a', root, 'cindy');+ expect(reservation).toMatchObject({ status: 'claimed', claimToken: expect.any(String) });+ originalFs.renameSync(marker, candidate);++ expect(recoverPendingLocalProfileDataOwner('owner-a', root, 'cindy')).toBe('finalized');+ await expect(fs.access(candidate)).rejects.toThrow();+ expect(JSON.parse(await fs.readFile(marker, 'utf8'))).toMatchObject({ ownerId: 'owner-a' });+ expect(JSON.parse(await fs.readFile(marker, 'utf8'))).not.toHaveProperty('claimToken');+ expect(reserveLocalProfileDataOwner('owner-b', root, 'cindy')).toBe('owned-by-other');+ });++ it('releases an uncommitted claim stranded in a release candidate', async () => {+ const { root } = await fixture();+ const marker = path.join(root, `cindy-local-v1${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`);+ const candidate = `${marker}.release`;+ expect(reserveLocalProfileDataOwner('owner-a', root, 'cindy')).toBe('claimed');+ originalFs.renameSync(marker, candidate);++ expect(recoverPendingLocalProfileDataOwner(null, root, 'cindy')).toBe('released');+ await expect(fs.access(marker)).rejects.toThrow();+ await expect(fs.access(candidate)).rejects.toThrow();+ expect(reserveLocalProfileDataOwner('owner-b', root, 'cindy')).toBe('claimed');+ });++ it('restores a tokenless owner stranded in a release candidate', async () => {+ const { root } = await fixture();+ const marker = path.join(root, `cindy-local-v1${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`);+ const candidate = `${marker}.release`;+ expect(reserveCommittedLocalProfileDataOwner('owner-a', root, 'cindy')).toBe('claimed');+ originalFs.renameSync(marker, candidate);++ expect(recoverPendingLocalProfileDataOwner(null, root, 'cindy')).toBe('none');+ await expect(fs.access(candidate)).rejects.toThrow();+ expect(JSON.parse(await fs.readFile(marker, 'utf8'))).toMatchObject({ ownerId: 'owner-a' });+ expect(reserveLocalProfileDataOwner('owner-b', root, 'cindy')).toBe('owned-by-other');+ });++ it('restores an atomic-write backup before settling a pending claim', async () => {+ const { root } = await fixture();+ const marker = path.join(root, `cindy-local-v1${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`);+ await fs.writeFile(+ `${marker}.bak`,+ JSON.stringify({ ownerId: 'owner-a', claimToken: 'claim-a' }),+ );++ expect(recoverPendingLocalProfileDataOwner('owner-a', root, 'cindy')).toBe('finalized');+ await expect(fs.access(`${marker}.bak`)).rejects.toThrow();+ expect(JSON.parse(await fs.readFile(marker, 'utf8'))).toMatchObject({ ownerId: 'owner-a' });+ expect(JSON.parse(await fs.readFile(marker, 'utf8'))).not.toHaveProperty('claimToken');+ expect(reserveLocalProfileDataOwner('owner-b', root, 'cindy')).toBe('owned-by-other');+ });++ it('creates a tokenless claim for an already durable cloud owner', async () => {+ const { root } = await fixture();+ expect(reserveCommittedLocalProfileDataOwner('owner-a', root, 'cindy')).toBe('claimed');+ const marker = JSON.parse(+ await fs.readFile(+ path.join(root, `cindy-local-v1${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`),+ 'utf8',+ ),+ );+ expect(marker).toMatchObject({ ownerId: 'owner-a' });+ expect(marker).not.toHaveProperty('claimToken');+ expect(recoverPendingLocalProfileDataOwner(null, root, 'cindy')).toBe('none');+ expect(reserveLocalProfileDataOwner('owner-b', root, 'cindy')).toBe('owned-by-other');+ });++ it('reports the authoritative owner when a later cloud owner is rejected', async () => {+ const { root } = await fixture();+ expect(reserveCommittedLocalProfileDataOwner('owner-a', root, 'cindy')).toBe('claimed');++ expect(reserveCommittedLocalProfileDataOwnerDetailed('owner-b', root, 'cindy')).toEqual({+ status: 'owned-by-other',+ ownerId: 'owner-a',+ });+ });++ it('recovers an interrupted pending claim before a different owner commits', async () => {+ const { root } = await fixture();+ expect(reserveLocalProfileDataOwner('owner-a', root, 'cindy')).toBe('claimed');++ expect(recoverPendingLocalProfileDataOwner(null, root, 'cindy')).toBe('released');+ expect(reserveLocalProfileDataOwner('owner-b', root, 'cindy')).toBe('claimed');+ });++ it('keeps a pending claim recoverable when the migration lock is temporarily busy', async () => {+ const { root } = await fixture();+ const marker = path.join(root, `cindy-local-v1${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`);+ expect(reserveLocalProfileDataOwner('owner-a', root, 'cindy')).toBe('claimed');+ const lockDb = createBetterSqliteDatabase(`${marker}${LOCAL_PROFILE_MIGRATION_LOCK_DB_SUFFIX}`);+ lockDb.exec('BEGIN IMMEDIATE');+ try {+ expect(recoverPendingLocalProfileDataOwner(null, root, 'cindy')).toBe('failed');+ await expect(fs.readFile(marker, 'utf8')).resolves.toContain('owner-a');+ } finally {+ lockDb.exec('ROLLBACK');+ lockDb.close();+ }++ expect(recoverPendingLocalProfileDataOwner(null, root, 'cindy')).toBe('released');+ expect(reserveLocalProfileDataOwner('owner-b', root, 'cindy')).toBe('claimed');+ });++ it('reserves an empty local namespace for the first cloud owner', async () => {+ const { root, deps } = await fixture();++ await expect(adoptLocalProfileDatabase('owner-a', deps)).resolves.toEqual({+ status: 'no-local-db',+ });+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');++ await expect(adoptLocalProfileDatabase('owner-b', deps)).resolves.toEqual({+ status: 'claimed-by-other-owner',+ });+ await expect(fs.access(path.join(root, 'cindy-owner-b.db'))).rejects.toThrow();+ await expect(+ fs.readFile(+ path.join(root, `cindy-local-v1${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`),+ 'utf8',+ ),+ ).resolves.toContain('owner-a');+ });++ it('defers an absent source while another instance could still create it', async () => {+ const { root, deps } = await fixture();++ await expect(+ adoptLocalProfileDatabase('owner-a', {+ ...deps,+ hasExclusiveSourceAccess: () => false,+ }),+ ).resolves.toEqual({+ status: 'failed',+ error: 'local profile database adoption deferred: concurrent live instance',+ });+ await expect(fs.access(path.join(root, 'cindy-owner-a.db'))).rejects.toThrow();+ });++ it('opens an existing cloud database without requiring source exclusivity', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ await fs.writeFile(target, 'cloud-db');++ await expect(+ adoptLocalProfileDatabase('owner-a', {+ ...deps,+ hasExclusiveSourceAccess: () => false,+ }),+ ).resolves.toEqual({ status: 'target-exists' });+ await expect(fs.readFile(target, 'utf8')).resolves.toBe('cloud-db');+ });++ it('blocks initialization when source sidecars exist without the main database', async () => {+ const { root, deps } = await fixture();+ const source = path.join(root, 'cindy-local-v1.db');+ const target = path.join(root, 'cindy-owner-a.db');+ await fs.writeFile(`${source}-wal`, 'orphaned-wal');++ await expect(adoptLocalProfileDatabase('owner-a', deps)).resolves.toEqual({+ status: 'failed',+ error: 'source database sidecar exists without its main database',+ });+ await expect(fs.access(target)).rejects.toThrow();+ await expect(fs.readFile(`${source}-wal`, 'utf8')).resolves.toBe('orphaned-wal');+ });++ it('adopts a standalone snapshot without deleting the local source', async () => {+ const { root, deps } = await fixture();+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');+ await fs.writeFile(path.join(root, 'cindy-local-v1.db-wal'), 'local-wal');+ await fs.writeFile(path.join(root, 'cindy-local-v1.db-shm'), 'local-shm');++ await expect(adoptLocalProfileDatabase('owner-a', deps)).resolves.toMatchObject({+ status: 'adopted',+ });+ await expect(fs.readFile(path.join(root, 'cindy-owner-a.db'), 'utf8')).resolves.toBe(+ 'local-db',+ );+ await expect(fs.access(path.join(root, 'cindy-owner-a.db-wal'))).rejects.toThrow();+ await expect(fs.access(path.join(root, 'cindy-owner-a.db-shm'))).rejects.toThrow();+ await expect(fs.readFile(path.join(root, 'cindy-local-v1.db'), 'utf8')).resolves.toBe(+ 'local-db',+ );+ await expect(+ fs.access(+ path.join(+ root,+ `cindy-local-v1${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}${LOCAL_PROFILE_MIGRATION_LOCK_DB_SUFFIX}`,+ ),+ ),+ ).resolves.toBeUndefined();+ const marker = JSON.parse(+ await fs.readFile(+ path.join(root, `cindy-local-v1${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`),+ 'utf8',+ ),+ );+ expect(marker).not.toHaveProperty('claimToken');+ });++ it('captures committed WAL data through SQLite online backup while the source stays open', async () => {+ const { root } = await fixture();+ const source = path.join(root, 'cindy-local-v1.db');+ const sourceDb = createBetterSqliteDatabase(source);+ const openSpy = vi.spyOn(originalFs, 'openSync');+ try {+ sourceDb.pragma('journal_mode = WAL');+ sourceDb.exec('CREATE TABLE items (value TEXT NOT NULL)');+ sourceDb.prepare('INSERT INTO items (value) VALUES (?)').run('from-wal');+ await expect(fs.access(`${source}-wal`)).resolves.toBeUndefined();++ const deps = createProductionLocalProfileDataMigrationDeps(root, 'cindy');+ await expect(adoptLocalProfileDatabase('owner-a', deps)).resolves.toMatchObject({+ status: 'adopted',+ });+ expect(openSpy).toHaveBeenCalledWith(path.join(root, 'cindy-owner-a.db'), 'r+');+ if (process.platform !== 'win32') {+ expect(openSpy).toHaveBeenCalledWith(root, 'r');+ }+ if (process.platform !== 'win32') {+ expect((await fs.stat(path.join(root, 'cindy-owner-a.db'))).mode & 0o777).toBe(0o600);+ }++ const targetDb = createBetterSqliteDatabase(path.join(root, 'cindy-owner-a.db'), {+ readonly: true,+ fileMustExist: true,+ });+ try {+ expect(targetDb.prepare('SELECT value FROM items').pluck().get()).toBe('from-wal');+ } finally {+ targetDb.close();+ }+ } finally {+ sourceDb.close();+ }+ });++ it('never overwrites an existing cloud database', async () => {+ const { root, deps } = await fixture();+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');+ await fs.writeFile(path.join(root, 'cindy-owner-a.db'), 'cloud-db');++ await expect(adoptLocalProfileDatabase('owner-a', deps)).resolves.toEqual({+ status: 'target-exists',+ });+ await expect(fs.readFile(path.join(root, 'cindy-owner-a.db'), 'utf8')).resolves.toBe(+ 'cloud-db',+ );+ });++ it('does not publish into an existing cloud database file group', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');+ await fs.writeFile(target, 'cloud-db');+ await fs.writeFile(`${target}-wal`, 'cloud-wal');++ await expect(adoptLocalProfileDatabase('owner-a', deps)).resolves.toEqual({+ status: 'target-exists',+ });+ await expect(fs.readFile(target, 'utf8')).resolves.toBe('cloud-db');+ await expect(fs.readFile(`${target}-wal`, 'utf8')).resolves.toBe('cloud-wal');+ });++ it('blocks initialization when target sidecars exist without the main database', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');+ await fs.writeFile(`${target}-wal`, 'orphaned-wal');++ await expect(adoptLocalProfileDatabase('owner-a', deps)).resolves.toMatchObject({+ status: 'failed',+ error: 'target database sidecar exists without its main database',+ });+ await expect(fs.access(target)).rejects.toThrow();+ await expect(fs.readFile(`${target}-wal`, 'utf8')).resolves.toBe('orphaned-wal');+ });++ it('requires the primary instance when the retained source belongs to this owner', async () => {+ const { root, deps } = await fixture();+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');++ await expect(inspectPassiveLocalProfileAdoption('owner-a', deps)).resolves.toEqual({+ status: 'required',+ });+ expect(reserveCommittedLocalProfileDataOwner('owner-a', root, 'cindy')).toBe('claimed');++ await expect(inspectPassiveLocalProfileAdoption('owner-a', deps)).resolves.toEqual({+ status: 'required',+ });+ await expect(fs.access(path.join(root, 'cindy-owner-a.db'))).rejects.toThrow();+ });++ it('allows passive initialization when adoption is not applicable', async () => {+ const { root, deps } = await fixture();++ await expect(inspectPassiveLocalProfileAdoption('owner-a', deps)).resolves.toEqual({+ status: 'not-required',+ reason: 'no-local-db',+ });++ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');+ await fs.writeFile(path.join(root, 'cindy-owner-a.db'), 'cloud-db');+ await expect(inspectPassiveLocalProfileAdoption('owner-a', deps)).resolves.toEqual({+ status: 'not-required',+ reason: 'target-exists',+ });++ await fs.rm(path.join(root, 'cindy-owner-a.db'));+ expect(reserveCommittedLocalProfileDataOwner('owner-b', root, 'cindy')).toBe('claimed');+ await expect(inspectPassiveLocalProfileAdoption('owner-a', deps)).resolves.toEqual({+ status: 'not-required',+ reason: 'claimed-by-other-owner',+ });+ });++ it('blocks passive initialization for orphaned source sidecars', async () => {+ const { root, deps } = await fixture();+ const source = path.join(root, 'cindy-local-v1.db');+ await fs.writeFile(`${source}-shm`, 'orphaned-shm');++ await expect(inspectPassiveLocalProfileAdoption('owner-a', deps)).resolves.toEqual({+ status: 'failed',+ error: 'source database sidecar exists without its main database',+ });+ await expect(fs.readFile(`${source}-shm`, 'utf8')).resolves.toBe('orphaned-shm');+ });++ it('blocks passive initialization while another instance could create the source', async () => {+ const { deps } = await fixture();++ await expect(+ inspectPassiveLocalProfileAdoption('owner-a', {+ ...deps,+ hasExclusiveSourceAccess: () => false,+ }),+ ).resolves.toEqual({+ status: 'failed',+ error: 'local profile database adoption deferred: concurrent live instance',+ });+ });++ it('keeps an existing passive cloud target authoritative when source access is unavailable', async () => {+ const { root, deps } = await fixture();+ await fs.writeFile(path.join(root, 'cindy-owner-a.db'), 'cloud-db');++ await expect(+ inspectPassiveLocalProfileAdoption('owner-a', {+ ...deps,+ hasExclusiveSourceAccess: () => false,+ }),+ ).resolves.toEqual({+ status: 'not-required',+ reason: 'target-exists',+ });+ });++ it('blocks passive initialization when a fallback copy is still in progress', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');+ await fs.writeFile(target, 'partial');+ await fs.writeFile(+ `${target}.local-profile-copy-pending`,+ JSON.stringify({ version: 1, attemptId: 'interrupted', phase: 'copying' }),+ );++ await expect(inspectPassiveLocalProfileAdoption('owner-a', deps)).resolves.toEqual({+ status: 'failed',+ error: 'target database copy is incomplete',+ });+ await expect(fs.readFile(target, 'utf8')).resolves.toBe('partial');+ });++ it('leaves a pending-copy backup for recovery under the migration lock', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ const pending = `${target}.local-profile-copy-pending`;+ const backup = `${pending}.bak`;+ await fs.writeFile(target, 'partial');+ await fs.writeFile(+ backup,+ JSON.stringify({ version: 1, attemptId: 'interrupted-windows-swap', phase: 'copying' }),+ );++ await expect(inspectPassiveLocalProfileAdoption('owner-a', deps)).resolves.toEqual({+ status: 'failed',+ error: 'database copy pending marker recovery requires migration lock',+ });+ await expect(fs.readFile(target, 'utf8')).resolves.toBe('partial');+ await expect(fs.access(pending)).rejects.toThrow();+ await expect(fs.readFile(backup, 'utf8').then(JSON.parse)).resolves.toMatchObject({+ attemptId: 'interrupted-windows-swap',+ phase: 'copying',+ });++ // The lock holder must still be able to publish its replacement marker;+ // passive inspection must not recreate the canonical path first.+ const writerTemp = `${pending}.writer.tmp`;+ await fs.writeFile(+ writerTemp,+ JSON.stringify({ version: 1, attemptId: 'writer', phase: 'copying' }),+ );+ await fs.rename(writerTemp, pending);+ await expect(fs.readFile(pending, 'utf8').then(JSON.parse)).resolves.toMatchObject({+ attemptId: 'writer',+ phase: 'copying',+ });+ });++ it('blocks passive initialization when target ownership is unproven', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ const pending = `${target}.local-profile-copy-pending`;+ await fs.writeFile(target, 'partial');+ await fs.writeFile(+ pending,+ JSON.stringify({ version: 1, attemptId: 'interrupted', phase: 'claiming' }),+ );++ await expect(inspectPassiveLocalProfileAdoption('owner-a', deps)).resolves.toEqual({+ status: 'failed',+ error: 'database copy publication has an unproven target owner',+ });+ await expect(fs.readFile(target, 'utf8')).resolves.toBe('partial');+ await expect(fs.readFile(pending, 'utf8').then(JSON.parse)).resolves.toMatchObject({+ phase: 'claiming',+ });+ });++ it('allows passive initialization after a published fallback copy', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ await fs.writeFile(target, 'cloud-db');+ await fs.writeFile(+ `${target}.local-profile-copy-pending`,+ JSON.stringify({ version: 1, attemptId: 'interrupted', phase: 'published' }),+ );++ await expect(inspectPassiveLocalProfileAdoption('owner-a', deps)).resolves.toEqual({+ status: 'not-required',+ reason: 'target-exists',+ });+ });++ it('allows passive initialization after a raced fallback copy', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ await fs.writeFile(target, 'cloud-db');+ await fs.writeFile(+ `${target}.local-profile-copy-pending`,+ JSON.stringify({ version: 1, attemptId: 'interrupted', phase: 'raced' }),+ );++ await expect(inspectPassiveLocalProfileAdoption('owner-a', deps)).resolves.toEqual({+ status: 'not-required',+ reason: 'target-exists',+ });+ });++ it('blocks passive initialization when the pending copy marker is malformed', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ await fs.writeFile(target, 'cloud-db');+ await fs.writeFile(`${target}.local-profile-copy-pending`, '{');++ await expect(inspectPassiveLocalProfileAdoption('owner-a', deps)).resolves.toEqual({+ status: 'failed',+ error: 'database copy pending marker is malformed',+ });+ });++ it('assigns the retained local source to only the first cloud owner', async () => {+ const { root, deps } = await fixture();+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');++ await expect(adoptLocalProfileDatabase('owner-a', deps)).resolves.toMatchObject({+ status: 'adopted',+ });+ await fs.rm(path.join(root, 'cindy-owner-a.db'));++ await expect(adoptLocalProfileDatabase('owner-b', deps)).resolves.toEqual({+ status: 'claimed-by-other-owner',+ });+ await expect(fs.access(path.join(root, 'cindy-owner-b.db'))).rejects.toThrow();+ });++ it('does not replace a target when same-owner adoption races across processes', async () => {+ const { root, deps } = await fixture();+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');+ await fs.writeFile(path.join(root, 'cindy-local-v1.db-wal'), 'local-wal');+ await fs.writeFile(path.join(root, 'cindy-local-v1.db-shm'), 'local-shm');++ const results = await Promise.all([+ adoptLocalProfileDatabase('owner-a', deps),+ adoptLocalProfileDatabase('owner-a', deps),+ ]);+ expect(results.map((result) => result.status).sort()).toEqual(['adopted', 'target-exists']);+ await expect(fs.readFile(path.join(root, 'cindy-owner-a.db'), 'utf8')).resolves.toBe(+ 'local-db',+ );+ await expect(fs.access(path.join(root, 'cindy-owner-a.db-wal'))).rejects.toThrow();+ await expect(fs.access(path.join(root, 'cindy-owner-a.db-shm'))).rejects.toThrow();+ });++ it('keeps the first same-owner snapshot when concurrent publishers produce different bytes', async () => {+ const { root, deps } = await fixture();+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');+ let backupCount = 0;+ const racingDeps: LocalProfileDataMigrationDeps = {+ ...deps,+ fs: {+ ...deps.fs,+ backupDatabase: async (_source, target) => {+ backupCount += 1;+ await fs.writeFile(target, `snapshot-${backupCount}`);+ },+ },+ };++ const results = await Promise.all([+ adoptLocalProfileDatabase('owner-a', racingDeps),+ adoptLocalProfileDatabase('owner-a', racingDeps),+ ]);++ expect(results.map((result) => result.status).sort()).toEqual(['adopted', 'target-exists']);+ expect(backupCount).toBe(1);+ await expect(fs.readFile(path.join(root, 'cindy-owner-a.db'), 'utf8')).resolves.toBe(+ 'snapshot-1',+ );+ });++ it('does not replace a cloud database created after the target preflight', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');++ const racingDeps: LocalProfileDataMigrationDeps = {+ ...deps,+ fs: {+ ...deps.fs,+ link: async (source, destination) => {+ // Model another initializer winning the target race after the+ // adoption preflight but before publication.+ await fs.writeFile(destination, 'cloud-db');+ return fs.link(source, destination);+ },+ },+ };++ await expect(adoptLocalProfileDatabase('owner-a', racingDeps)).resolves.toEqual({+ status: 'target-exists',+ });+ await expect(fs.readFile(target, 'utf8')).resolves.toBe('cloud-db');+ });++ it('keeps a cloud database created during the online backup', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');++ let backupStarted!: () => void;+ let releaseBackup!: () => void;+ const backupStartedPromise = new Promise<void>((resolve) => {+ backupStarted = resolve;+ });+ const backupRelease = new Promise<void>((resolve) => {+ releaseBackup = resolve;+ });+ const racingDeps: LocalProfileDataMigrationDeps = {+ ...deps,+ fs: {+ ...deps.fs,+ backupDatabase: async (_source, destination) => {+ await fs.writeFile(destination, 'local-snapshot');+ backupStarted();+ await backupRelease;+ },+ },+ };++ const adoption = adoptLocalProfileDatabase('owner-a', racingDeps);+ await backupStartedPromise;+ // A separate initializer can create the cloud target after the adoption+ // preflight; the atomic target claim must preserve that database.+ await fs.writeFile(target, 'cloud-db');+ releaseBackup();++ await expect(adoption).resolves.toEqual({ status: 'target-exists' });+ await expect(fs.readFile(target, 'utf8')).resolves.toBe('cloud-db');+ });++ it('does not publish WAL sidecars when the main target loses the race', async () => {+ const { root, deps } = await fixture();+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');+ await fs.writeFile(path.join(root, 'cindy-local-v1.db-wal'), 'local-wal');+ const racingDeps: LocalProfileDataMigrationDeps = {+ ...deps,+ fs: {+ ...deps.fs,+ link: async (source, target) => {+ if (target === path.join(root, 'cindy-owner-a.db')) {+ await fs.writeFile(target, 'cloud-db');+ const error = Object.assign(new Error('target already exists'), { code: 'EEXIST' });+ throw error;+ }+ return deps.fs.link(source, target);+ },+ },+ };++ await expect(adoptLocalProfileDatabase('owner-a', racingDeps)).resolves.toEqual({+ status: 'target-exists',+ });+ await expect(fs.access(path.join(root, 'cindy-owner-a.db-wal'))).rejects.toThrow();+ await expect(fs.access(path.join(root, 'cindy-owner-a.db-shm'))).rejects.toThrow();+ await expect(fs.readFile(path.join(root, 'cindy-owner-a.db'), 'utf8')).resolves.toBe(+ 'cloud-db',+ );+ });++ it('does not publish a database when the online backup fails', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');+ const failingDeps: LocalProfileDataMigrationDeps = {+ ...deps,+ fs: {+ ...deps.fs,+ backupDatabase: async (_source, destination) => {+ await fs.writeFile(destination, 'partial-snapshot');+ throw Object.assign(new Error('online backup failed'), { code: 'EIO' });+ },+ },+ };++ await expect(adoptLocalProfileDatabase('owner-a', failingDeps)).resolves.toMatchObject({+ status: 'failed',+ error: 'online backup failed',+ });+ await expect(fs.access(target)).rejects.toThrow();+ expect(+ (await fs.readdir(root)).filter((entry) =>+ entry.includes(LOCAL_PROFILE_MIGRATION_TMP_SUFFIX),+ ),+ ).toEqual([]);+ });++ it('blocks initialization when probing the local database fails', async () => {+ const { root, deps } = await fixture();+ const source = path.join(root, 'cindy-local-v1.db');+ const target = path.join(root, 'cindy-owner-a.db');+ await fs.writeFile(source, 'local-db');+ const failingDeps: LocalProfileDataMigrationDeps = {+ ...deps,+ fs: {+ ...deps.fs,+ pathExists: async (file) => {+ if (file === source)+ throw Object.assign(new Error('local database probe failed'), { code: 'EIO' });+ return deps.fs.pathExists(file);+ },+ },+ };++ await expect(adoptLocalProfileDatabase('owner-a', failingDeps)).resolves.toMatchObject({+ status: 'failed',+ error: 'local database probe failed',+ });+ await expect(fs.access(target)).rejects.toThrow();+ });++ it('ignores a stale legacy lease even when its PID has been recycled', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ const legacyLease = `${target}.local-profile-migration-lease`;+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');+ await fs.writeFile(+ legacyLease,+ JSON.stringify({ ownerId: 'owner-a', leaseId: 'stale', pid: process.pid, claimedAt: 1 }),+ );++ await expect(adoptLocalProfileDatabase('owner-a', deps)).resolves.toMatchObject({+ status: 'adopted',+ });+ await expect(fs.access(legacyLease)).resolves.toBeUndefined();+ });++ it('fails promptly when the SQLite migration lock cannot be opened', async () => {+ const { root, deps } = await fixture();+ const marker = path.join(root, `cindy-local-v1${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`);+ const target = path.join(root, 'cindy-owner-a.db');+ const activeSnapshot = `${target}${LOCAL_PROFILE_MIGRATION_TMP_SUFFIX}.active-holder`;+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');+ await fs.writeFile(activeSnapshot, 'active-snapshot');+ await fs.mkdir(`${marker}${LOCAL_PROFILE_MIGRATION_LOCK_DB_SUFFIX}`, { recursive: true });++ await expect(adoptLocalProfileDatabase('owner-a', deps)).resolves.toEqual({+ status: 'failed',+ error: expect.stringContaining('failed to acquire local profile migration lock'),+ });+ await expect(fs.readFile(activeSnapshot, 'utf8')).resolves.toBe('active-snapshot');+ });++ it('defers adoption while another live instance can still write local-v1', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');++ await expect(+ adoptLocalProfileDatabase('owner-a', {+ ...deps,+ hasExclusiveSourceAccess: () => false,+ }),+ ).resolves.toEqual({+ status: 'failed',+ error: 'local profile database adoption deferred: concurrent live instance',+ });+ await expect(fs.access(target)).rejects.toThrow();+ });++ it('keeps the first owner reservation and retries after a legacy packaged instance exits', async () => {+ const { root, deps } = await fixture();+ const source = path.join(root, 'cindy-local-v1.db');+ const target = path.join(root, 'cindy-owner-a.db');+ await fs.writeFile(source, 'local-db');+ let packagedInstanceRunning = true;+ const acquireSourcePublicationBarrier = vi.fn(async () => {+ if (packagedInstanceRunning) {+ throw new Error(+ 'local profile database adoption deferred: legacy packaged instance 4242 is using shared userData',+ );+ }+ return { isHeld: () => true, release: vi.fn(async () => undefined) };+ });++ await expect(+ adoptLocalProfileDatabase('owner-a', { ...deps, acquireSourcePublicationBarrier }),+ ).resolves.toEqual({+ status: 'failed',+ error:+ 'local profile database adoption deferred: legacy packaged instance 4242 is using shared userData',+ });+ await expect(fs.access(target)).rejects.toThrow();+ expect(reserveLocalProfileDataOwner('owner-b', root, 'cindy')).toBe('owned-by-other');++ packagedInstanceRunning = false;+ await expect(+ adoptLocalProfileDatabase('owner-a', { ...deps, acquireSourcePublicationBarrier }),+ ).resolves.toMatchObject({ status: 'adopted', sourceDb: source, targetDb: target });+ await expect(fs.readFile(target, 'utf8')).resolves.toBe('local-db');+ expect(acquireSourcePublicationBarrier).toHaveBeenCalledTimes(2);+ });++ it('holds the packaged startup barrier through snapshot publication', async () => {+ const { root, deps } = await fixture();+ const source = path.join(root, 'cindy-local-v1.db');+ const target = path.join(root, 'cindy-owner-a.db');+ await fs.writeFile(source, 'local-db');+ let held = true;+ const release = vi.fn(async () => {+ held = false;+ });+ const acquireSourcePublicationBarrier = vi.fn(async () => ({+ isHeld: () => held,+ release,+ }));+ const guardedDeps: LocalProfileDataMigrationDeps = {+ ...deps,+ acquireSourcePublicationBarrier,+ fs: {+ ...deps.fs,+ backupDatabase: async (from, to) => {+ expect(held).toBe(true);+ await fs.copyFile(from, to);+ },+ link: async (from, to) => {+ expect(held).toBe(true);+ await fs.link(from, to);+ },+ },+ };++ await expect(adoptLocalProfileDatabase('owner-a', guardedDeps)).resolves.toMatchObject({+ status: 'adopted',+ });+ expect(acquireSourcePublicationBarrier).toHaveBeenCalledOnce();+ expect(release).toHaveBeenCalledOnce();+ expect(held).toBe(false);+ await expect(fs.readFile(target, 'utf8')).resolves.toBe('local-db');+ });++ it('removes its published target when the packaged startup barrier is lost', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');+ let heldChecks = 0;+ const release = vi.fn(async () => undefined);++ await expect(+ adoptLocalProfileDatabase('owner-a', {+ ...deps,+ acquireSourcePublicationBarrier: async () => ({+ // Entry and post-backup checks pass. Losing the helper before the+ // final post-publication check must retract our target.+ isHeld: () => ++heldChecks <= 2,+ release,+ }),+ }),+ ).resolves.toEqual({+ status: 'failed',+ error: 'local profile database adoption deferred: concurrent live instance',+ });+ expect(heldChecks).toBe(3);+ expect(release).toHaveBeenCalledOnce();+ await expect(fs.access(target)).rejects.toThrow();+ });++ it('checks the packaged startup barrier before accepting an absent local database', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ let packagedInstanceRunning = true;+ const release = vi.fn(async () => undefined);+ const acquireSourcePublicationBarrier = vi.fn(async () => {+ if (packagedInstanceRunning) {+ throw new Error(+ 'local profile database adoption deferred: legacy packaged instance 4242 is using shared userData',+ );+ }+ return { isHeld: () => true, release };+ });++ await expect(+ adoptLocalProfileDatabase('owner-a', { ...deps, acquireSourcePublicationBarrier }),+ ).resolves.toMatchObject({+ status: 'failed',+ error: expect.stringContaining('legacy packaged instance 4242'),+ });+ await expect(fs.access(target)).rejects.toThrow();++ packagedInstanceRunning = false;+ await expect(+ adoptLocalProfileDatabase('owner-a', { ...deps, acquireSourcePublicationBarrier }),+ ).resolves.toEqual({ status: 'no-local-db' });+ expect(acquireSourcePublicationBarrier).toHaveBeenCalledTimes(2);+ expect(release).toHaveBeenCalledOnce();+ });++ it('discards the snapshot if exclusive source access is lost before publication', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');+ let accessChecks = 0;++ await expect(+ adoptLocalProfileDatabase('owner-a', {+ ...deps,+ hasExclusiveSourceAccess: () => ++accessChecks === 1,+ }),+ ).resolves.toEqual({+ status: 'failed',+ error: 'local profile database adoption deferred: concurrent live instance',+ });+ expect(accessChecks).toBe(2);+ await expect(fs.access(target)).rejects.toThrow();+ });++ it('cleans interrupted temporary files before retrying', async () => {+ const { root, deps } = await fixture();+ const target = path.join(root, 'cindy-owner-a.db');+ await fs.writeFile(path.join(root, 'cindy-local-v1.db'), 'local-db');+ await fs.writeFile(`${target}${LOCAL_PROFILE_MIGRATION_TMP_SUFFIX}`, 'stale');+ await fs.writeFile(`${target}${LOCAL_PROFILE_MIGRATION_TMP_SUFFIX}.attempt-a`, 'stale-copy');+ await fs.writeFile(`${target}-wal${LOCAL_PROFILE_MIGRATION_TMP_SUFFIX}`, 'stale-wal');+ await fs.writeFile(+ `${target}-shm${LOCAL_PROFILE_MIGRATION_TMP_SUFFIX}.attempt-b`,+ 'stale-shm-copy',+ );++ await expect(adoptLocalProfileDatabase('owner-a', deps)).resolves.toMatchObject({+ status: 'adopted',+ });+ await expect(fs.access(`${target}${LOCAL_PROFILE_MIGRATION_TMP_SUFFIX}`)).rejects.toThrow();+ await expect(+ fs.access(`${target}${LOCAL_PROFILE_MIGRATION_TMP_SUFFIX}.attempt-a`),+ ).rejects.toThrow();+ await expect(fs.access(`${target}-wal${LOCAL_PROFILE_MIGRATION_TMP_SUFFIX}`)).rejects.toThrow();+ await expect(+ fs.access(`${target}-shm${LOCAL_PROFILE_MIGRATION_TMP_SUFFIX}.attempt-b`),+ ).rejects.toThrow();+ });+});diff --git a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.tsindex 08859a13ed..d635bf707c 100644--- a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts+++ b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts@@ -381,6 +381,102 @@ describe('claimLegacyOwnerNamespace', () => {await expect(fs.readFile(path.join(root, 'slack-hook.json'), 'utf-8')).resolves.toBe('legacy-hook');});+ it('rechecks the canonical registry record when its backup vanishes during exchange', async () => {+ const root = await tempRoot();+ await fs.writeFile(path.join(root, 'slack-hook.json'), 'legacy-hook');+ await writeDevInstanceRecord(root, 4242);+ const recordPath = path.join(root, '.dev-instances', '4242.json');+ const backupPath = `${recordPath}.bak`;+ const recordRaw = await fs.readFile(recordPath, 'utf-8');+ let canonicalReads = 0;++ const result = await claimLegacyOwnerNamespace(+ { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },+ realFsDeps(+ root,+ { isPidAlive: (pid) => pid === 4242 },+ {+ readFile: (file: string) => {+ if (file === recordPath) {+ canonicalReads += 1;+ if (canonicalReads === 1) {+ return Promise.reject(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));+ }+ return Promise.resolve(recordRaw);+ }+ if (file === backupPath) {+ return Promise.reject(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));+ }+ return fs.readFile(file, 'utf-8');+ },+ },+ ),+ );++ expect(canonicalReads).toBeGreaterThanOrEqual(2);+ expect(result).toEqual({+ status: 'deferred',+ moved: 0,+ conflicts: 0,+ deferredReason: 'concurrent-live-instances',+ });+ await expect(fs.readFile(path.join(root, 'slack-hook.json'), 'utf-8')).resolves.toBe('legacy-hook');+ });++ it.each([+ ['unparseable', '{not-json'],+ ['missing pid', '{}'],+ ['non-numeric pid', JSON.stringify({ pid: '4242' })],+ ])('fails closed when a registry record payload is %s', async (_label, payload) => {+ const root = await tempRoot();+ await fs.writeFile(path.join(root, 'slack-hook.json'), 'legacy-hook');+ await fs.mkdir(path.join(root, '.dev-instances'), { recursive: true });+ await fs.writeFile(path.join(root, '.dev-instances', '4242.json'), payload, 'utf-8');++ const result = await claimLegacyOwnerNamespace(+ { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },+ realFsDeps(root, { isPidAlive: (pid) => pid === 4242 }),+ );++ expect(result).toEqual({+ status: 'deferred',+ moved: 0,+ conflicts: 0,+ deferredReason: 'concurrent-live-instances',+ });+ await expect(fs.readFile(path.join(root, 'slack-hook.json'), 'utf-8')).resolves.toBe('legacy-hook');+ await expect(+ fs.readFile(path.join(root, '.dev-instances', '4242.json'), 'utf-8'),+ ).resolves.toBe(payload);+ });++ it.each([+ ['current process', process.pid],+ ['dead replacement', 9999],+ ])('uses the registry filename pid when payload names the %s', async (_label, payloadPid) => {+ const root = await tempRoot();+ await fs.writeFile(path.join(root, 'slack-hook.json'), 'legacy-hook');+ await fs.mkdir(path.join(root, '.dev-instances'), { recursive: true });+ await fs.writeFile(+ path.join(root, '.dev-instances', '4242.json'),+ JSON.stringify({ schemaVersion: 1, pid: payloadPid, userDataDir: root, passive: false }),+ 'utf-8',+ );++ const result = await claimLegacyOwnerNamespace(+ { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },+ realFsDeps(root, { isPidAlive: (pid) => pid === 4242 }),+ );++ expect(result).toEqual({+ status: 'deferred',+ moved: 0,+ conflicts: 0,+ deferredReason: 'concurrent-live-instances',+ });+ await expect(fs.readFile(path.join(root, 'slack-hook.json'), 'utf-8')).resolves.toBe('legacy-hook');+ });+it('interrupts mid-claim when an instance registers during the move, then resumes next exclusive start', async () => {const root = await tempRoot();// LEGACY_PATHS 顺序:ghost-cindy-prefs.json 在 slack-hook.json 之前。@@ -670,7 +766,6 @@ describe('claimLegacyOwnerNamespace', () => {await fs.writeFile(path.join(root, 'slack-hook.json'), 'legacy-hook');await writeDevInstanceRecord(root, 4242); // isPidAlive=false → 已退出的残留await writeDevInstanceRecord(root, 5353, '/somewhere/else'); // 异常拷贝进来的他库记录- await fs.writeFile(path.join(root, '.dev-instances', 'torn.json'), '{not-json', 'utf-8');const result = await claimLegacyOwnerNamespace({ mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },@@ -3105,6 +3200,46 @@ describe('hasExclusiveSharedLegacyUserDataAccess', () => {expect(hasExclusiveSharedLegacyUserDataAccess(root, () => false)).toBe(true);});+ it.each([+ ['unparseable', '{not-json'],+ ['missing pid', '{}'],+ ['non-numeric pid', JSON.stringify({ pid: '4242' })],+ ])('fails closed when a shared instance registry payload is %s', async (_label, payload) => {+ const root = await tempRoot();+ await fs.mkdir(path.join(root, '.dev-instances'), { recursive: true });+ await fs.writeFile(path.join(root, '.dev-instances', '4242.json'), payload, 'utf-8');++ expect(hasExclusiveSharedLegacyUserDataAccess(root, (pid) => pid === 4242)).toBe(false);+ expect(hasExclusiveSharedLegacyUserDataAccess(root, () => false)).toBe(true);+ });++ it.each([+ ['current process', process.pid],+ ['dead replacement', 9999],+ ])('uses the registry filename pid when the shared payload names the %s', async (_label, payloadPid) => {+ const root = await tempRoot();+ await fs.mkdir(path.join(root, '.dev-instances'), { recursive: true });+ await fs.writeFile(+ path.join(root, '.dev-instances', '4242.json'),+ JSON.stringify({ schemaVersion: 1, pid: payloadPid, userDataDir: root, passive: false }),+ 'utf-8',+ );++ expect(hasExclusiveSharedLegacyUserDataAccess(root, (pid) => pid === 4242)).toBe(false);+ expect(hasExclusiveSharedLegacyUserDataAccess(root, () => false)).toBe(true);+ });++ it('restores an atomic-write backup before deciding that a live instance vanished', async () => {+ const root = await tempRoot();+ await writeDevInstanceRecord(root, 4242);+ const recordPath = path.join(root, '.dev-instances', '4242.json');+ await fs.rename(recordPath, `${recordPath}.bak`);++ expect(hasExclusiveSharedLegacyUserDataAccess(root, (pid) => pid === 4242)).toBe(false);+ await expect(fs.access(recordPath)).resolves.toBeUndefined();+ await expect(fs.access(`${recordPath}.bak`)).rejects.toThrow();+ });+it('ignores a registry pid that was reused by another app', async () => {const root = await tempRoot();const startedAtMs = 1_000_000;diff --git a/apps/desktop/src/main/__tests__/windowsPackagedInstanceBarrier.test.ts b/apps/desktop/src/main/__tests__/windowsPackagedInstanceBarrier.test.tsnew file mode 100644index 0000000000..e5e7bb0ee8--- /dev/null+++ b/apps/desktop/src/main/__tests__/windowsPackagedInstanceBarrier.test.ts@@ -0,0 +1,72 @@+import os from 'node:os';+import path from 'node:path';+import { describe, expect, it } from 'vitest';++import {+ acquireWindowsPackagedInstanceBarrier,+ __testing,+} from '../windowsPackagedInstanceBarrier.js';++describe('windowsPackagedInstanceBarrier', () => {+ it('parses only complete helper statuses', () => {+ expect(__testing.parseBarrierStatus('{"status":"acquired"}')).toEqual({+ status: 'acquired',+ });+ expect(__testing.parseBarrierStatus('{"status":"busy"}')).toEqual({ status: 'busy' });+ expect(__testing.parseBarrierStatus('{"status":"occupied","pid":4242}')).toEqual({+ status: 'occupied',+ pid: 4242,+ });+ expect(() => __testing.parseBarrierStatus('{"status":"occupied","pid":0}')).toThrow(+ 'invalid status',+ );+ });++ it('uses Electron ProcessSingleton names and a message-only-window probe', () => {+ expect(__testing.processSingletonNames('Cindy')).toEqual({+ mutexName: 'Local\\CindyProcessSingletonStartup',+ windowClass: 'Chrome_MessageWindow',+ });+ expect(__testing.WINDOWS_PACKAGED_INSTANCE_BARRIER_SCRIPT).toContain('FindWindowEx');+ expect(__testing.WINDOWS_PACKAGED_INSTANCE_BARRIER_SCRIPT).toContain(+ 'CINDY_SINGLETON_WINDOW_CLASS',+ );+ expect(__testing.WINDOWS_PACKAGED_INSTANCE_BARRIER_SCRIPT).toContain(+ 'CINDY_SINGLETON_WINDOW_TITLE',+ );+ });++ it.runIf(process.platform === 'win32')(+ 'holds the packaged startup mutex until release and allows a later retry',+ async () => {+ const programName = `CindyBarrierTest${process.pid}`;+ const userDataDir = path.join(os.tmpdir(), programName);+ const first = await acquireWindowsPackagedInstanceBarrier({+ userDataDir,+ programName,+ timeoutMs: 1_000,+ });+ try {+ expect(first.isHeld()).toBe(true);+ await expect(+ acquireWindowsPackagedInstanceBarrier({+ userDataDir,+ programName,+ timeoutMs: 50,+ }),+ ).rejects.toThrow('startup barrier is busy');+ } finally {+ await first.release();+ }+ expect(first.isHeld()).toBe(false);++ const retry = await acquireWindowsPackagedInstanceBarrier({+ userDataDir,+ programName,+ timeoutMs: 1_000,+ });+ expect(retry.isHeld()).toBe(true);+ await retry.release();+ },+ );+});diff --git a/apps/desktop/src/main/authBoundaryQuarantine.ts b/apps/desktop/src/main/authBoundaryQuarantine.tsindex 3fe932a0e4..05f6ba7e3c 100644--- a/apps/desktop/src/main/authBoundaryQuarantine.ts+++ b/apps/desktop/src/main/authBoundaryQuarantine.ts@@ -54,6 +54,7 @@ interface OwnerCommitOptions<T> {nextOwnerId: string | null;prepareTransition?: (context: { ownerChanged: boolean }) => Promise<void>;prepareCommit?: () => Promise<void>;+ onCommitFailure?: (context: { commitApplied: boolean }) => void | Promise<void>;commit: () => T | Promise<T>;}@@ -334,6 +335,7 @@ export async function withGhostSkillProjectionOwnerCommit<T>(const ownerChanged = previousOwnerId !== nextOwnerId;const transitionId = crypto.randomUUID();const prepareTransition = options.prepareTransition;+ let commitApplied = false;if (requiresTransition) {if (!prepareTransition) {@@ -369,6 +371,7 @@ export async function withGhostSkillProjectionOwnerCommit<T>(}await options.prepareCommit?.();const result = await options.commit();+ commitApplied = true;if (requiresTransition) {writeState({version: 1,@@ -382,6 +385,11 @@ export async function withGhostSkillProjectionOwnerCommit<T>(}return result;} catch (error) {+ try {+ await options.onCommitFailure?.({ commitApplied });+ } catch (rollbackError) {+ log.error('Ghost skill projection owner commit rollback failed', rollbackError);+ }if (requiresTransition) {try {writeState({@@ -437,6 +445,17 @@ export async function withSharedGlobalSkillProjectionMutation<T>(if (isPassiveSharedUserDataInstance()) {throw new Error('Passive shared-userData instances cannot mutate global skill projections');}+ return withStableOwnerBoundaryMutation(ownerId, mutation);+}++/** Serialize non-projection state that must agree with the same durable owner. */+export async function withStableOwnerBoundaryMutation<T>(+ ownerId: string | null,+ mutation: () => Promise<T>,+): Promise<T> {+ if (isPassiveSharedUserDataInstance()) {+ throw new Error('Passive shared-userData instances cannot mutate stable owner state');+ }const normalizedOwnerId = normalizeOwnerArgument(ownerId);return withStrictBoundaryLock(async () => {if (processProjectionQuarantined || isDurablyQuarantined()) {diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.tsindex 13884b8fed..628caf0777 100644--- a/apps/desktop/src/main/authManager.ts+++ b/apps/desktop/src/main/authManager.ts@@ -45,6 +45,7 @@ import {import { readReloginFlag, clearReloginFlag, enableUncustomizedBetaChannel } from './updateService';import { probeBetaManifest } from './manifestService';import { isEnableBetaUserCustomized, readUpdateChannelSettings } from './updateChannelStore';+import { BRAND_IDENTITY } from '@cindy/maker-shared/brand-identity';import * as canaryFlagStore from './canaryFlagStore';import { decodeAccessTokenOrgSlug } from './authTokenClaims';import { getProviderSecretStore } from './secrets/providerSecretStore.js';@@ -84,6 +85,7 @@ import {isGhostSkillProjectionBoundaryStableForOwner,withGhostSkillProjectionOwnerCommit,withGhostSkillProjectionReadOnlyOwner,+ withStableOwnerBoundaryMutation,} from './authBoundaryQuarantine.js';import { buildFocusDeepLink } from './deepLink';import { getResolvedMainLocale, t } from './i18n';@@ -121,6 +123,20 @@ import {claimLegacyOwnerNamespace,recordLegacyGhostMigrationResult,} from './ownerNamespaceMigration.js';+import {+ migrateLocalNativeProviderAuthBindings,+ readLegacyNativeProviderAuthOwner,+ recoverPendingLegacyNativeProviderAuthOwner,+ releaseLegacyNativeProviderAuthOwner,+ reserveCommittedLegacyNativeProviderAuthOwner,+ reserveLegacyNativeProviderAuthOwnerDetailed,+} from './maker-host/nativeProviderAuthBinding.js';+import {+ recoverPendingLocalProfileDataOwner,+ releaseLocalProfileDataOwner,+ reserveCommittedLocalProfileDataOwnerDetailed,+ reserveLocalProfileDataOwnerDetailed,+} from './localProfileDataMigration.js';import { buildSafeStorageIssueMeta } from './safeStorageIssueLog.js';import { createCredentialStoreHealth } from './authCredentialStoreHealth';import { withCrossProcessLock } from './device-link/crossProcessLock';@@ -436,7 +452,7 @@ function createAuthClient(* delete 兜底,防 ambient env 污染),线上零影响。env 由解析后的 profileKind* 不是 isolated-sandbox 且 passive 落地,覆盖正式目录与非隔离 custom 共库。*/-function isPassiveSharedUserDataInstance(): boolean {+export function isPassiveSharedUserDataInstance(): boolean {return !app.isPackaged && process.env.XDT_PASSIVE_SHARED_USER_DATA === '1';}@@ -1979,6 +1995,8 @@ async function withCloudOwnerCommit<T>(opts: {let forceBumpGeneration = false;let result!: T;let committed = false;+ let commitApplied = false;+ let rollbackReservation: CloudOwnerDataReservation | null = null;try {result = await withGhostSkillProjectionOwnerCommit({previousOwnerId: opts.previousOwnerId,@@ -2003,9 +2021,18 @@ async function withCloudOwnerCommit<T>(opts: {await projectionRepairTeardown('same-owner-projection-recovery');}},- prepareCommit: opts.prepareCommit,+ prepareCommit: async () => {+ rollbackReservation = reserveCloudOwnerData(opts.nextOwnerId, opts.previousOwnerId);+ await opts.prepareCommit?.();+ },commit: async () => {const result = await opts.commit();+ commitApplied = true;+ const reservation = rollbackReservation as CloudOwnerDataReservation | null;+ if (reservation && !reservation.finalize()) {+ throw new Error('cloud owner data reservation finalization remains pending');+ }+ rollbackReservation = null;// Same-owner repair: advance the owner generation after the real commit// so activeOwnerScopeKey() changes and stale captured scopes are rejected.if (forceBumpGeneration) {@@ -2014,9 +2041,25 @@ async function withCloudOwnerCommit<T>(opts: {}return result;},+ onCommitFailure: ({ commitApplied: boundaryCommitApplied }) => {+ // The cloud session/token commit is already durable at this point. A+ // later projection-state publication failure must keep the first-owner+ // reservations so another account cannot inherit the same local data.+ if (boundaryCommitApplied || commitApplied) return;+ const reservation = rollbackReservation as CloudOwnerDataReservation | null;+ if (!reservation) return;+ if (!reservation.rollback()) {+ throw new Error('cloud owner data reservation rollback remains pending');+ }+ rollbackReservation = null;+ },});committed = true;} finally {+ if (!committed && !commitApplied) {+ const reservation = rollbackReservation as CloudOwnerDataReservation | null;+ if (reservation?.rollback()) rollbackReservation = null;+ }const release = releaseBoundary as (() => void) | null;release?.();if (heldOwnerChangeShell) leaveOwnerChangeShellPending();@@ -2192,6 +2235,174 @@ async function recoverAccountFreeOwnerAtStartup(});}+interface CloudOwnerDataReservation {+ rollback(): boolean;+ finalize(): boolean;+}++function recoverCloudOwnerDataReservations(committedOwnerId: string | null): boolean {+ const profileRecovery = recoverPendingLocalProfileDataOwner(+ committedOwnerId,+ app.getPath('userData'),+ BRAND_IDENTITY.dbFilePrefix,+ );+ const nativeRecovery = recoverPendingLegacyNativeProviderAuthOwner(committedOwnerId);+ return profileRecovery !== 'failed' && nativeRecovery !== 'failed';+}++function resolveProfileReservationOwnerId(ownerId: string): string {+ const nativeOwner = readLegacyNativeProviderAuthOwner();+ if (nativeOwner.status === 'failed') {+ throw new Error('native provider ownership could not be read before profile reservation');+ }+ return nativeOwner.status === 'owned' ? nativeOwner.ownerId : ownerId;+}++function reserveCloudOwnerData(+ ownerId: string,+ previousOwnerId: string | null,+): CloudOwnerDataReservation {+ const rollbackActions: Array<() => void> = [];+ try {+ if (!recoverCloudOwnerDataReservations(previousOwnerId)) {+ throw new Error('pending cloud owner data reservation recovery failed');+ }+ // Older builds could durably assign only the native-provider namespace.+ // Preserve that first owner when introducing the profile marker: a+ // different currently persisted account may authenticate, but must not+ // reinterpret the still-shared local database as its own.+ const profileReservationOwnerId = resolveProfileReservationOwnerId(ownerId);+ const profileReservation = reserveLocalProfileDataOwnerDetailed(+ profileReservationOwnerId,+ app.getPath('userData'),+ BRAND_IDENTITY.dbFilePrefix,+ );+ if (profileReservation.status === 'failed') {+ throw new Error('local profile data reservation failed before cloud owner commit');+ }+ if (profileReservation.status === 'claimed' && profileReservation.claimToken) {+ rollbackActions.push(() => {+ releaseLocalProfileDataOwner(+ profileReservationOwnerId,+ app.getPath('userData'),+ BRAND_IDENTITY.dbFilePrefix,+ profileReservation.claimToken!,+ );+ });+ }++ const authoritativeOwnerId = profileReservation.ownerId;+ if (!authoritativeOwnerId) {+ throw new Error('local profile data reservation did not identify its durable owner');+ }+ // Keep this reservation provisional until the same cloud commit finalizes+ // both namespaces. Even when the profile marker was already durable, a+ // missing native marker must remain rollback-able if this auth transition+ // is superseded before commit.+ const nativeReservation = reserveLegacyNativeProviderAuthOwnerDetailed(authoritativeOwnerId);+ if (nativeReservation.status === 'failed') {+ throw new Error('native provider ownership reservation failed before cloud owner commit');+ }+ if (nativeReservation.status === 'owned-by-other') {+ throw new Error('local profile and native provider ownership reservations disagree');+ }+ if (nativeReservation.status === 'claimed' && nativeReservation.claimToken) {+ rollbackActions.push(() => {+ releaseLegacyNativeProviderAuthOwner(authoritativeOwnerId, nativeReservation.claimToken!);+ });+ }+ if (authoritativeOwnerId !== ownerId) {+ log.info('cloud owner committed without adopting legacy local data', {+ ownerId,+ authoritativeOwnerId,+ profileReservation: profileReservation.status,+ nativeReservation: nativeReservation.status,+ });+ }+ return {+ rollback: () => {+ for (const rollback of rollbackActions.reverse()) rollback();+ return recoverCloudOwnerDataReservations(previousOwnerId);+ },+ finalize: () => recoverCloudOwnerDataReservations(authoritativeOwnerId),+ };+ } catch (error) {+ for (const rollback of rollbackActions.reverse()) rollback();+ throw error;+ }+}++function repairStableCloudOwnerDataReservationsWhileLocked(ownerId: string): boolean {+ let profileReservation: ReturnType<typeof reserveCommittedLocalProfileDataOwnerDetailed> = {+ status: 'failed',+ };+ let nativeReservation: ReturnType<typeof reserveCommittedLegacyNativeProviderAuthOwner> =+ 'failed';++ if (!recoverCloudOwnerDataReservations(ownerId)) {+ log.error('stable cloud owner reservation recovery failed', { ownerId });+ return false;+ }+ try {+ const profileReservationOwnerId = resolveProfileReservationOwnerId(ownerId);+ profileReservation = reserveCommittedLocalProfileDataOwnerDetailed(+ profileReservationOwnerId,+ app.getPath('userData'),+ BRAND_IDENTITY.dbFilePrefix,+ );+ } catch (error) {+ log.warn('stable cloud owner local profile reservation repair failed', {+ ownerId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ if (profileReservation.status === 'failed' || !profileReservation.ownerId) {+ log.warn('stable cloud owner remains authenticated with local adoption fail-closed', {+ ownerId,+ profileReservation: profileReservation.status,+ nativeReservation,+ });+ return false;+ }+ const authoritativeOwnerId = profileReservation.ownerId;+ try {+ nativeReservation = reserveCommittedLegacyNativeProviderAuthOwner(authoritativeOwnerId);+ } catch (error) {+ log.warn('stable cloud owner native provider reservation repair failed', {+ ownerId,+ authoritativeOwnerId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ if (nativeReservation === 'failed' || nativeReservation === 'owned-by-other') {+ log.warn('stable cloud owner remains authenticated with local adoption fail-closed', {+ ownerId,+ authoritativeOwnerId,+ profileReservation: profileReservation.status,+ nativeReservation,+ });+ return false;+ }+ return authoritativeOwnerId === ownerId;+}++async function repairStableCloudOwnerDataReservations(ownerId: string): Promise<boolean> {+ try {+ // Cloud commits already hold this cross-process owner lock from reservation+ // through finalize/rollback. Stable-owner repair must join the same lock so+ // it cannot settle one namespace while a concurrent login settles the other.+ return await withStableOwnerBoundaryMutation(ownerId, async () =>+ repairStableCloudOwnerDataReservationsWhileLocked(ownerId),+ );+ } catch (error) {+ log.warn('stable cloud owner reservation repair could not enter owner transaction', {+ ownerId,+ error: error instanceof Error ? error.message : String(error),+ });+ return false;+ }+}+function commitCloudAppSession(ownerId: string): void {if (isPassiveSharedUserDataInstance()) {commitVolatileAppSession('cloud', ownerId);@@ -2200,6 +2411,29 @@ function commitCloudAppSession(ownerId: string): void {}}+/**+ * Complete the one-way local → cloud native-provider ownership handoff after+ * the durable owner boundary is stable. The binding layer keeps this+ * fail-closed for other cloud owners and corrupted state.+ */+async function migrateLocalProviderBindingsAfterCloudCommit(ownerId: string): Promise<void> {+ if (isPassiveSharedUserDataInstance()) return;+ try {+ // The profile marker is the single durable authority for both retained+ // local namespaces. Reconcile the native marker to that owner before any+ // legacy credential migration can run.+ if (!(await repairStableCloudOwnerDataReservations(ownerId))) return;+ if (migrateLocalNativeProviderAuthBindings(ownerId)) {+ log.info('migrated local native provider bindings to first cloud owner', { ownerId });+ }+ } catch (error) {+ log.warn('local native provider binding migration failed', {+ ownerId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+}+async function finishColdStartSignedOut(reason: string): Promise<AuthState> {await recoverAccountFreeOwnerAtStartup('signed-out', reason);return snapshotLoggedOutAuthState();@@ -3817,8 +4051,15 @@ export async function initialize(options: AuthInitializeOptions = {}): Promise<Acommit: () => commitCloudAppSession(currentUser!.id),});} else {+ // This owner is already durably authenticated. Repair missing first-owner+ // reservations best-effort, but never turn malformed local metadata into+ // a renderer-visible logout while main remains signed in.+ if (!isPassiveSharedUserDataInstance()) {+ await repairStableCloudOwnerDataReservations(currentUser.id);+ }commitCloudAppSession(currentUser.id);}+ await migrateLocalProviderBindingsAfterCloudCommit(currentUser.id);await ensureStableOwnerPostCommit('auth-initialize-stable-cloud');return snapshotAuthState();}@@ -4158,6 +4399,7 @@ async function runColdStartRefreshFlow(clearReplacementIntegrationReloadTimers();},});+ await migrateLocalProviderBindingsAfterCloudCommit(refreshData.membership.id);scheduleCanaryFlagSync({token: refreshData.accessToken,expectedAuthEpoch: epochAtStart,@@ -4382,6 +4624,7 @@ async function completeLogin(},},);+ await migrateLocalProviderBindingsAfterCloudCommit(nextUser.id);scheduleCanaryFlagSync({token: outcome.accessToken,expectedAuthEpoch: loginEpoch,@@ -5018,6 +5261,7 @@ export async function refresh(): Promise<boolean> {commitCloudAppSession(currentUser.id);},});+ await migrateLocalProviderBindingsAfterCloudCommit(nextUser.id);persistedRefreshTokenNeedsIdentityCheck = false;getProviderSecretStore().reconcileOwner(nextUser.id);if (accountSwitched) {@@ -5075,6 +5319,7 @@ export async function refresh(): Promise<boolean> {commitCloudAppSession(currentUser.id);},});+ await migrateLocalProviderBindingsAfterCloudCommit(nextUser.id);persistedRefreshTokenNeedsIdentityCheck = false;scheduleRefresh(data.accessToken);notifyRenderer();diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 70d744baca..2531074fd4 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -233,7 +233,10 @@ import {import { setTelegramRemoteSource } from './device-link/telegramRemoteControl';import * as authManager from './authManager';import { hasPersistedSessionHint } from './authSessionHint';-import { warmStaleProcessProvenance } from './ownerNamespaceMigration.js';+import {+ hasExclusiveSharedLegacyUserDataAccess,+ warmStaleProcessProvenance,+} from './ownerNamespaceMigration.js';import { createAccountDeletionIpcHandlers } from './accountDeletionIpc';import * as profileEdit from './profileEdit';import { uploadPublicAsset } from './ossPublicUpload';@@ -281,7 +284,10 @@ import {stageLocalFileToCache,} from './file-browser/remote-file-cache';import { sweepLegacyDialogueWorkingDirs } from './localDb/dialogueWorkdirSelfHeal';-import { legacyDialogueUserDataDirNames } from '@cindy/maker-shared/brand-identity';+import {+ BRAND_IDENTITY,+ legacyDialogueUserDataDirNames,+} from '@cindy/maker-shared/brand-identity';import * as videoCacheStore from './videoCacheStore';import { imageSchemePrivilege, registerImageProtocolHandler } from './imageProtocol';import { videoSchemePrivilege, registerVideoProtocolHandler } from './videoProtocol';@@ -327,6 +333,12 @@ import {registerLegacyMigrationIpc,runLegacyUserDataMigrationForUser,} from './legacyUserDataMigration';+import {+ adoptLocalProfileDatabase,+ createProductionLocalProfileDataMigrationDeps,+ inspectPassiveLocalProfileAdoption,+} from './localProfileDataMigration';+import { acquireWindowsPackagedInstanceBarrier } from './windowsPackagedInstanceBarrier';import { registerFsBrowseIpc } from './fsBrowse/ipc';import {ensureReady as localDbEnsureReady,@@ -8038,9 +8050,61 @@ app.on('ready', async () => {}const user = authManager.getAuthState().user;if (user == null || user.id !== userId) return;+ if (authManager.isPassiveSharedUserDataInstance()) {+ const passivePreflight = await inspectPassiveLocalProfileAdoption(+ user.id,+ createProductionLocalProfileDataMigrationDeps(+ app.getPath('userData'),+ BRAND_IDENTITY.dbFilePrefix,+ () => hasExclusiveSharedLegacyUserDataAccess(),+ ),+ );+ if (passivePreflight.status === 'required') {+ throw new Error('local profile database adoption is pending in the primary instance');+ }+ if (passivePreflight.status === 'failed') {+ throw new Error(+ `local profile database adoption preflight failed: ${passivePreflight.error}`,+ );+ }+ return;+ }// 首登轻量迁移(老 xdt-maker userData → Cindy):内部自带 marker 防重入与// 全量兜底,绝不 throw,失败不阻塞登录(ensureReady 照常建新库)。await runLegacyUserDataMigrationForUser(user.id);+ // 登录前 local-v1 与登录后的 cloud owner 使用不同数据库文件。目标库不存在时+ // 采用本地库,避免用户刚登录就看到空的任务/项目空间;目标库已存在则保持原样,+ // 绝不覆盖账号已有内容。+ const localProfileMigration = await adoptLocalProfileDatabase(+ user.id,+ createProductionLocalProfileDataMigrationDeps(+ app.getPath('userData'),+ BRAND_IDENTITY.dbFilePrefix,+ () => hasExclusiveSharedLegacyUserDataAccess(),+ process.platform === 'win32'+ ? () =>+ acquireWindowsPackagedInstanceBarrier({+ userDataDir: app.getPath('userData'),+ programName: BRAND_IDENTITY.executableName,+ })+ : undefined,+ ),+ );+ if (localProfileMigration.status === 'failed') {+ dbClientLog.error('local profile database adoption failed; blocking cloud database open', {+ userId,+ error: localProfileMigration.error,+ });+ throw new Error(`local profile database adoption failed: ${localProfileMigration.error}`);+ } else if (localProfileMigration.status === 'claimed-by-other-owner') {+ dbClientLog.warn('local profile database is already reserved for another cloud owner', {+ userId,+ });+ } else if (localProfileMigration.status === 'adopted') {+ dbClientLog.info('local profile database adopted for first cloud owner', {+ userId,+ });+ }},onReady: async (userId) => {const startupHooksStartedAt = performance.now();diff --git a/apps/desktop/src/main/devStartupStatus.ts b/apps/desktop/src/main/devStartupStatus.tsindex eac1b8d300..0affc04646 100644--- a/apps/desktop/src/main/devStartupStatus.ts+++ b/apps/desktop/src/main/devStartupStatus.ts@@ -3,6 +3,8 @@ import fs from 'node:fs';import path from 'node:path';import type { CindyRegion } from '@cindy/maker-shared/brand-identity';import type { DevProfileKind } from './devCliFlags.js';+import { withLocalProfileMigrationStartupBarrier } from './localProfileDataMigration.js';+import { atomicWriteFileSync } from './utils/atomicWriteFile.js';export type DesktopDevMode = 'remote' | 'local' | 'unknown';export type DesktopDevInstanceState = 'starting' | 'ready' | 'failed';@@ -46,6 +48,7 @@ export interface DesktopDevInstanceRecord {export interface BeginDesktopDevInstanceOptions {userDataDir: string;+ dbFilePrefix: string;rootDir: string;commit?: string | null;mode?: DesktopDevMode;@@ -65,15 +68,7 @@ let applicationReady = false;let startupSettled = false;function atomicWriteJson(filePath: string, value: unknown): void {- const tempPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;- try {- fs.mkdirSync(path.dirname(filePath), { recursive: true });- fs.writeFileSync(tempPath, `${JSON.stringify(value)}\n`, { mode: 0o600 });- fs.renameSync(tempPath, filePath);- } catch (error) {- fs.rmSync(tempPath, { force: true });- throw error;- }+ atomicWriteFileSync(filePath, `${JSON.stringify(value)}\n`);}function readJson(filePath: string): Record<string, unknown> | null {@@ -127,9 +122,9 @@ function updateTrackedInstance(* Register this Electron main process before single-instance arbitration.* The returned cleanup only removes the record when its random instanceId still owns it.*/-export function beginDesktopDevInstance(+export async function beginDesktopDevInstance(options: BeginDesktopDevInstanceOptions,-): () => void {+): Promise<() => void> {mainWindowReady = false;applicationReady = false;startupSettled = false;@@ -155,10 +150,19 @@ export function beginDesktopDevInstance(const filePath = path.join(record.userDataDir, '.dev-instances', `${pid}.json`);try {- atomicWriteJson(filePath, record);- trackedInstance = { filePath, record };- } catch {- trackedInstance = null;+ await withLocalProfileMigrationStartupBarrier(record.userDataDir, options.dbFilePrefix, () => {+ // Initial registration is part of the adoption safety protocol. If it+ // cannot be published, fail startup rather than continuing invisibly and+ // writing local-v1 while another process snapshots it.+ atomicWriteJson(filePath, record);+ trackedInstance = { filePath, record };+ });+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ markDesktopDevStartupFailed('INSTANCE_REGISTRATION_FAILED', message, {+ phase: 'instance-registration',+ });+ throw error;}return () => {diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex ecf1aba7e4..348b9a6bc7 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -5,6 +5,7 @@ import { execFileSync } from 'node:child_process';import path from 'node:path';import { setDefaultAutoSelectFamilyAttemptTimeout } from 'node:net';import { exit, stderr } from 'node:process';+import { BRAND_IDENTITY } from '@cindy/maker-shared/brand-identity';import { CURRENT_CINDY_REGION } from '../shared/brandRegion.js';import { resolveRegionUserDataDirName } from './regionUserData.js';import { createLogger, initLogger } from './logger.js';@@ -220,7 +221,7 @@ if (devFlags.needsIsolatedDeviceId) {// userData 双开是受支持的工作流(bootstrap-electron 单例锁注释),owner-namespace// 迁移的独占检查靠本注册表发现「还有谁共享这份 userData」——packaged 不登记的话,// dev 实例会在 release 实例仍存活时误判独占并搬走 legacy 配置。-{+const desktopDevInstanceOptions = (() => {const rootDir = app.isPackaged? path.resolve(app.getAppPath()): path.resolve(app.getAppPath(), '..', '..');@@ -240,8 +241,9 @@ if (devFlags.needsIsolatedDeviceId) {const mode: DesktopDevMode = declaredMode === 'remote' || declaredMode === 'local'? declaredMode: 'unknown';- const cleanupDevInstance = beginDesktopDevInstance({+ return {userDataDir: app.getPath('userData'),+ dbFilePrefix: BRAND_IDENTITY.dbFilePrefix,rootDir,commit,mode,@@ -250,13 +252,14 @@ if (devFlags.needsIsolatedDeviceId) {isolated: devFlags.profileKind === 'isolated-sandbox',isolationIntent: devFlags.isolated,profileKind: devFlags.profileKind,- });+ };+})();++async function dispatch(): Promise<void> {+ const cleanupDevInstance = await beginDesktopDevInstance(desktopDevInstanceOptions);// Windows updater forceQuit() ends in process.exit(0), which bypasses Electron will-quit.process.once('exit', cleanupDevInstance);app.once('will-quit', cleanupDevInstance);-}--async function dispatch(): Promise<void> {const mod = await import('./bootstrap-electron.js');await mod.bootstrapElectron();}diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/ownerEnsureCoordinator.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/ownerEnsureCoordinator.test.tsindex 7a49986301..9ffcdd743b 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/ownerEnsureCoordinator.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/ownerEnsureCoordinator.test.ts@@ -12,6 +12,26 @@ function deferred<T>() {}describe('createOwnerEnsureCoordinator', () => {+ it('keeps the target unopened when preflight fails and allows a later retry', async () => {+ let failPreflight = true;+ const ensure = vi.fn(async () => ({ ready: true as const }));+ const run = createOwnerEnsureCoordinator({+ isOwnerCurrent: () => true,+ beforeEnsureReady: () => {+ if (failPreflight) throw new Error('local profile adoption failed');+ },+ ensureReady: ensure,+ discardReadyOwner: vi.fn(),+ });++ await expect(run('cloud-a')).rejects.toThrow('local profile adoption failed');+ expect(ensure).not.toHaveBeenCalled();++ failPreflight = false;+ await expect(run('cloud-a')).resolves.toEqual({ ready: true });+ expect(ensure).toHaveBeenCalledOnce();+ });+it('drops an owner superseded while its preflight is pending', async () => {let activeOwner = 'cloud-a';const preflightA = deferred<void>();diff --git a/apps/desktop/src/main/localProfileDataMigration.ts b/apps/desktop/src/main/localProfileDataMigration.tsnew file mode 100644index 0000000000..c13b908323--- /dev/null+++ b/apps/desktop/src/main/localProfileDataMigration.ts@@ -0,0 +1,1189 @@+/**+ * Adopt the account-free local profile database for the first verified cloud+ * owner on this installation.+ *+ * The local and cloud sessions intentionally use different database filenames.+ * On the first local → cloud transition, copying the local database before the+ * cloud DbClient opens preserves the user's conversations and projects without+ * weakening the normal per-owner database boundary. Existing cloud data is+ * never overwritten; a later, explicit merge can handle that conflict.+ */++import fs from 'original-fs';+import { randomUUID } from 'node:crypto';+import { constants as fsConstants } from 'node:fs';+import path from 'node:path';+import { performance } from 'node:perf_hooks';++import {+ createBetterSqliteDatabase,+ restrictDbFilePermissions,+} from './localDb/betterSqliteFactory.js';+import { LOCAL_PROFILE_DATA_OWNER_ID } from './profile/profileRegistryModel.js';+import { atomicWriteFileSync, readAtomicFileSync } from './utils/atomicWriteFile.js';++export const LOCAL_PROFILE_MIGRATION_TMP_SUFFIX = '.local-profile-migration-tmp';+export const LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX = '.local-profile-migration.json';+export const LOCAL_PROFILE_MIGRATION_LOCK_DB_SUFFIX = '.mutation-lock.sqlite';+const DB_COPY_PENDING_SUFFIX = '.local-profile-copy-pending';+const DB_COPY_PENDING_VERSION = 1;++const LOCAL_PROFILE_MIGRATION_LOCK_TIMEOUT_MS = 30_000;+const LOCAL_PROFILE_MIGRATION_LOCK_RETRY_MS = 25;++const DB_SIDECAR_SUFFIXES = ['-wal', '-shm'] as const;++export interface LocalProfileDataMigrationFs {+ pathExists(file: string): Promise<boolean>;+ readFile(file: string): Promise<string>;+ readDir(directory: string): Promise<string[]>;+ backupDatabase(source: string, target: string): Promise<void>;+ link(source: string, target: string): Promise<void>;+ /** Publish a complete snapshot without replacing an existing target. */+ copyNoReplace(source: string, target: string): Promise<void>;+ removeIfExists(file: string): Promise<void>;+}++export interface LocalProfileDataMigrationDeps {+ userDataDir: string;+ dbFilePrefix: string;+ fs: LocalProfileDataMigrationFs;+ /** True only while no other live process can keep writing the local-v1 source. */+ hasExclusiveSourceAccess?: () => boolean;+ /**+ * Optional OS-level startup barrier held across snapshot publication. Windows+ * uses it to exclude packaged builds that predate the runtime registry.+ */+ acquireSourcePublicationBarrier?: () => Promise<{+ isHeld(): boolean;+ release(): Promise<void>;+ }>;+}++export type LocalProfileDataMigrationResult =+ | { status: 'no-local-db' }+ | { status: 'target-exists' }+ | { status: 'claimed-by-other-owner' }+ | { status: 'adopted'; sourceDb: string; targetDb: string }+ | { status: 'failed'; error: string };++const realFs: LocalProfileDataMigrationFs = {+ pathExists: async (file) => {+ try {+ await fs.promises.access(file);+ return true;+ } catch (error) {+ if ((error as NodeJS.ErrnoException | null)?.code === 'ENOENT') return false;+ throw error;+ }+ },+ readFile: (file) => fs.promises.readFile(file, 'utf8'),+ readDir: (directory) => fs.promises.readdir(directory),+ backupDatabase: async (source, target) => {+ // Restrict the destination before SQLite starts its potentially long+ // online backup; chmod-after-backup leaves a readable snapshot window.+ const handle = fs.openSync(target, 'w', 0o600);+ fs.closeSync(handle);+ const db = createBetterSqliteDatabase(source, { readonly: true, fileMustExist: true });+ try {+ await db.backup(target);+ restrictDbFilePermissions(target);+ } finally {+ db.close();+ }+ },+ link: (source, target) => fs.promises.link(source, target),+ copyNoReplace: async (source, target) => {+ const pending = `${target}${DB_COPY_PENDING_SUFFIX}`;+ const attemptId = randomUUID();+ writePendingDatabaseCopyMarker(pending, {+ version: DB_COPY_PENDING_VERSION,+ attemptId,+ phase: 'claiming',+ });+ let sourceHandle: Awaited<ReturnType<typeof fs.promises.open>> | undefined;+ let targetHandle: Awaited<ReturnType<typeof fs.promises.open>> | undefined;+ try {+ sourceHandle = await fs.promises.open(source, 'r');+ try {+ // O_EXCL is the no-replace claim. Keep the marker in `claiming` until+ // wx succeeds; before that point it is only an intention and must not+ // authorize recovery to delete a target created by another process.+ targetHandle = await fs.promises.open(target, 'wx', 0o600);+ // A durable `copying` marker now proves that this process obtained the+ // exclusive target claim. Recovery may remove only targets with that+ // proof after an interrupted copy.+ updatePendingDatabaseCopyMarker(pending, {+ version: DB_COPY_PENDING_VERSION,+ attemptId,+ phase: 'copying',+ });+ } catch (error) {+ if ((error as NodeJS.ErrnoException | null)?.code === 'EEXIST') {+ // The target is authoritative when another initializer won the+ // no-replace claim. Persist that outcome before best-effort cleanup+ // so a restart can never treat this marker as our partial target.+ try {+ updatePendingDatabaseCopyMarker(pending, {+ version: DB_COPY_PENDING_VERSION,+ attemptId,+ phase: 'raced',+ });+ } catch {+ // Keep the original EEXIST as the authoritative result.+ }+ // Cleanup is best effort and must never hide the original EEXIST,+ // because the existing target is authoritative.+ await fs.promises.rm(pending, { force: true }).catch(() => undefined);+ }+ throw error;+ }+ const chunk = Buffer.allocUnsafe(1024 * 1024);+ let position = 0;+ for (;;) {+ const { bytesRead } = await sourceHandle.read(chunk, 0, chunk.length, position);+ if (bytesRead === 0) break;+ let offset = 0;+ while (offset < bytesRead) {+ const { bytesWritten } = await targetHandle.write(+ chunk,+ offset,+ bytesRead - offset,+ position + offset,+ );+ if (bytesWritten <= 0) throw new Error('short write while copying database snapshot');+ offset += bytesWritten;+ }+ position += bytesRead;+ }+ await targetHandle.sync();+ await targetHandle.close();+ targetHandle = undefined;+ await sourceHandle.close();+ sourceHandle = undefined;+ // The open target handle was synced immediately before close; only the+ // parent directory entry still needs an explicit barrier here.+ syncMarkerDirectory(target);+ updatePendingDatabaseCopyMarker(pending, {+ version: DB_COPY_PENDING_VERSION,+ attemptId,+ phase: 'published',+ });+ await fs.promises.rm(pending, { force: true }).catch(() => undefined);+ } finally {+ await targetHandle?.close().catch(() => undefined);+ await sourceHandle?.close().catch(() => undefined);+ }+ },+ removeIfExists: (file) => fs.promises.rm(file, { force: true }),+};++function dbPath(deps: LocalProfileDataMigrationDeps, ownerId: string): string {+ return path.join(deps.userDataDir, `${deps.dbFilePrefix}-${ownerId}.db`);+}++function migrationMarkerPath(deps: LocalProfileDataMigrationDeps): string {+ return path.join(+ deps.userDataDir,+ `${deps.dbFilePrefix}-${LOCAL_PROFILE_DATA_OWNER_ID}${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`,+ );+}++type LocalProfileMigrationLockDb = ReturnType<typeof createBetterSqliteDatabase>;++type PendingDatabaseCopyMarker = {+ version: typeof DB_COPY_PENDING_VERSION;+ attemptId: string;+ phase: 'claiming' | 'copying' | 'raced' | 'published';+};++type LocalProfileMigrationLockAttempt =+ | { status: 'acquired'; db: LocalProfileMigrationLockDb }+ | { status: 'busy' }+ | { status: 'failed'; error: unknown };++function migrationLockPath(marker: string): string {+ return `${marker}${LOCAL_PROFILE_MIGRATION_LOCK_DB_SUFFIX}`;+}++function tryAcquireLocalProfileMigrationLock(marker: string): LocalProfileMigrationLockAttempt {+ const lockDbPath = migrationLockPath(marker);+ let db: LocalProfileMigrationLockDb | null = null;+ try {+ fs.mkdirSync(path.dirname(lockDbPath), { recursive: true });+ db = createBetterSqliteDatabase(lockDbPath);+ db.pragma('busy_timeout = 0');+ db.exec('BEGIN IMMEDIATE');+ return { status: 'acquired', db };+ } catch (error) {+ try {+ db?.close();+ } catch {+ // Preserve the acquisition error; close is best effort on a failed open.+ }+ const code = (error as { code?: string } | null)?.code;+ return code === 'SQLITE_BUSY' || code === 'SQLITE_LOCKED'+ ? { status: 'busy' }+ : { status: 'failed', error };+ }+}++function releaseLocalProfileMigrationLock(db: LocalProfileMigrationLockDb): void {+ try {+ db.exec('ROLLBACK');+ } catch {+ // Closing the connection still releases SQLite's OS-level lock.+ }+ db.close();+}++function withLocalProfileMigrationLock<T>(marker: string, fallback: T, operation: () => T): T {+ const attempt = tryAcquireLocalProfileMigrationLock(marker);+ if (attempt.status !== 'acquired') return fallback;+ try {+ return operation();+ } finally {+ releaseLocalProfileMigrationLock(attempt.db);+ }+}++async function acquireLocalProfileMigrationLock(+ marker: string,+): Promise<LocalProfileMigrationLockDb> {+ const deadline = performance.now() + LOCAL_PROFILE_MIGRATION_LOCK_TIMEOUT_MS;+ for (;;) {+ const attempt = tryAcquireLocalProfileMigrationLock(marker);+ if (attempt.status === 'acquired') return attempt.db;+ if (attempt.status === 'failed') {+ throw new Error(+ `failed to acquire local profile migration lock: ${+ attempt.error instanceof Error ? attempt.error.message : String(attempt.error)+ }`,+ );+ }+ if (performance.now() >= deadline) {+ throw new Error('timed out acquiring local profile migration lock');+ }+ await new Promise<void>((resolve) =>+ setTimeout(resolve, LOCAL_PROFILE_MIGRATION_LOCK_RETRY_MS),+ );+ }+}++/**+ * Serialize process registration with local-profile adoption. Adoption already+ * holds this same crash-released SQLite writer lock through snapshot publication;+ * a new process must publish its runtime record under the lock so it either+ * becomes visible before adoption's exclusivity check or starts after the cloud+ * target is durable.+ */+export async function withLocalProfileMigrationStartupBarrier<T>(+ userDataDir: string,+ dbFilePrefix: string,+ operation: () => T | Promise<T>,+): Promise<T> {+ const marker = path.join(+ userDataDir,+ `${dbFilePrefix}-${LOCAL_PROFILE_DATA_OWNER_ID}${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`,+ );+ const lockDb = await acquireLocalProfileMigrationLock(marker);+ try {+ return await operation();+ } finally {+ releaseLocalProfileMigrationLock(lockDb);+ }+}++export type LocalProfileMigrationReservation =+ 'claimed' | 'already-owned' | 'owned-by-other' | 'failed';++export interface LocalProfileMigrationReservationDetails {+ status: LocalProfileMigrationReservation;+ /** The durable namespace owner observed or created by this attempt. */+ ownerId?: string;+ claimToken?: string;+}++export type PendingLocalProfileReservationRecovery = 'none' | 'finalized' | 'released' | 'failed';++interface LocalProfileMigrationMarker {+ ownerId: string;+ claimToken?: string;+}++function parseLocalProfileMigrationMarker(raw: string): LocalProfileMigrationMarker | null {+ try {+ const parsed = JSON.parse(raw) as Partial<LocalProfileMigrationMarker>;+ if (typeof parsed.ownerId !== 'string' || !parsed.ownerId.trim()) return null;+ if (+ parsed.claimToken !== undefined &&+ (typeof parsed.claimToken !== 'string' || !parsed.claimToken)+ ) {+ return null;+ }+ return {+ ownerId: parsed.ownerId.trim(),+ ...(parsed.claimToken ? { claimToken: parsed.claimToken } : {}),+ };+ } catch {+ return null;+ }+}++function syncMarkerDirectory(marker: string): void {+ let dirFd: number | undefined;+ try {+ dirFd = fs.openSync(path.dirname(marker), 'r');+ fs.fsyncSync(dirFd);+ } catch (error) {+ // Directory handles are not supported by every Windows filesystem. The+ // final-file flush remains the durability barrier there; POSIX errors are+ // surfaced because the directory entry is otherwise not durable.+ if (process.platform !== 'win32') throw error;+ } finally {+ if (dirFd !== undefined) fs.closeSync(dirFd);+ }+}++function flushFile(file: string): void {+ const handle = fs.openSync(file, 'r+');+ try {+ fs.fsyncSync(handle);+ } finally {+ fs.closeSync(handle);+ }+}++function writePendingDatabaseCopyMarker(+ pending: string,+ marker: PendingDatabaseCopyMarker,+): void {+ const handle = fs.openSync(pending, 'wx', 0o600);+ try {+ const bytes = Buffer.from(`${JSON.stringify(marker)}\n`, 'utf8');+ let offset = 0;+ while (offset < bytes.length) {+ const written = fs.writeSync(handle, bytes, offset, bytes.length - offset);+ if (written <= 0) throw new Error('short write while publishing database copy marker');+ offset += written;+ }+ fs.fsyncSync(handle);+ } finally {+ fs.closeSync(handle);+ }+ syncMarkerDirectory(pending);+}++function updatePendingDatabaseCopyMarker(+ pending: string,+ marker: PendingDatabaseCopyMarker,+): void {+ atomicWriteFileSync(pending, `${JSON.stringify(marker)}\n`);+ flushFile(pending);+ syncMarkerDirectory(pending);+}++function parsePendingDatabaseCopyMarker(raw: string): PendingDatabaseCopyMarker | null {+ try {+ const parsed = JSON.parse(raw) as Partial<PendingDatabaseCopyMarker>;+ if (+ parsed.version !== DB_COPY_PENDING_VERSION ||+ typeof parsed.attemptId !== 'string' ||+ !parsed.attemptId ||+ (parsed.phase !== 'claiming' &&+ parsed.phase !== 'copying' &&+ parsed.phase !== 'raced' &&+ parsed.phase !== 'published')+ ) {+ return null;+ }+ return {+ version: DB_COPY_PENDING_VERSION,+ attemptId: parsed.attemptId,+ phase: parsed.phase,+ };+ } catch {+ return null;+ }+}++function flushPublishedDatabase(targetDb: string): void {+ // Hard-link publication is not durable until the published inode and its+ // containing directory have both crossed their filesystem barriers.+ flushFile(targetDb);+ syncMarkerDirectory(targetDb);+}++function publishLocalProfileMigrationMarker(+ marker: string,+ contents: string,+): 'claimed' | 'exists' {+ fs.mkdirSync(path.dirname(marker), { recursive: true });+ const tmp = `${marker}.${randomUUID()}.tmp`;+ let handle: number | undefined;+ try {+ handle = fs.openSync(tmp, 'wx', 0o600);+ const bytes = Buffer.from(contents, 'utf8');+ let offset = 0;+ while (offset < bytes.length) {+ const written = fs.writeSync(handle, bytes, offset, bytes.length - offset);+ if (written <= 0) throw new Error('short write while publishing local profile owner marker');+ offset += written;+ }+ fs.fsyncSync(handle);+ fs.closeSync(handle);+ handle = undefined;+ try {+ fs.linkSync(tmp, marker);+ } catch (error) {+ const code = (error as NodeJS.ErrnoException | null)?.code;+ if (code === 'EEXIST') return 'exists';+ // A few supported userData filesystems do not implement hard links.+ // Copy into a private pending path first. The canonical marker must not+ // become visible until the complete payload is durable; COPYFILE_EXCL+ // directly on the canonical path can leave a truncated marker after a+ // process or machine interruption.+ if (!['EXDEV', 'EPERM', 'EOPNOTSUPP', 'ENOTSUP', 'ENOSYS'].includes(code ?? '')) {+ throw error;+ }+ const pending = `${marker}.pending`;+ try {+ if (fs.existsSync(marker)) return 'exists';+ fs.copyFileSync(tmp, pending, fsConstants.COPYFILE_EXCL);+ flushFile(pending);+ syncMarkerDirectory(pending);+ if (fs.existsSync(marker)) return 'exists';+ fs.renameSync(pending, marker);+ const finalHandle = fs.openSync(marker, 'r+');+ try {+ fs.fsyncSync(finalHandle);+ } finally {+ fs.closeSync(finalHandle);+ }+ syncMarkerDirectory(marker);+ } catch (fallbackError) {+ if ((fallbackError as NodeJS.ErrnoException | null)?.code === 'EEXIST') return 'exists';+ throw fallbackError;+ } finally {+ if (fs.existsSync(pending) && fs.existsSync(marker)) {+ try {+ fs.unlinkSync(pending);+ } catch {+ // The canonical marker is authoritative; leave a complete pending+ // copy for the next recovery pass if cleanup is temporarily busy.+ }+ }+ }+ }+ const finalHandle = fs.openSync(marker, 'r+');+ try {+ fs.fsyncSync(finalHandle);+ } finally {+ fs.closeSync(finalHandle);+ }+ syncMarkerDirectory(marker);+ return 'claimed';+ } finally {+ if (handle !== undefined) {+ try {+ fs.closeSync(handle);+ } catch {+ // Best-effort close before removing the private candidate.+ }+ }+ try {+ fs.unlinkSync(tmp);+ } catch {+ // A random private candidate cannot affect ownership decisions.+ }+ }+}++function replaceLocalProfileMigrationMarker(marker: string, contents: string): void {+ atomicWriteFileSync(marker, contents);+ // Windows requires a writable handle for FlushFileBuffers. The marker is+ // created with owner-only permissions, so r+ is safe on POSIX as well.+ const finalHandle = fs.openSync(marker, 'r+');+ try {+ fs.fsyncSync(finalHandle);+ } finally {+ fs.closeSync(finalHandle);+ }+ syncMarkerDirectory(marker);+}++function restoreClaimedLocalProfileMarker(candidate: string, marker: string): boolean {+ try {+ // Restore only into an absent canonical path; never overwrite a newer+ // reservation that may have appeared after this process claimed candidate.+ if (fs.existsSync(marker)) return false;+ // rename is available on all supported userData filesystems, including+ // those without hard-link support, and publishes the complete candidate+ // in one atomic operation while the migration lock is held.+ fs.renameSync(candidate, marker);+ syncMarkerDirectory(marker);+ return true;+ } catch {+ // Keeping the claimed candidate is safer than deleting ownership evidence.+ return false;+ }+}++function recoverReleasedLocalProfileMigrationMarker(+ marker: string,+ committedOwnerId: string | null,+): Exclude<PendingLocalProfileReservationRecovery, 'none'> | null {+ const candidate = `${marker}.release`;+ if (!fs.existsSync(candidate)) return null;+ // A release candidate is created by renaming the canonical marker while the+ // migration lock is held. Seeing another canonical/pending marker beside it+ // is not a state we can attribute safely, so preserve all evidence.+ if (fs.existsSync(marker) || fs.existsSync(`${marker}.pending`)) return 'failed';++ let parsed: LocalProfileMigrationMarker | null = null;+ try {+ parsed = parseLocalProfileMigrationMarker(fs.readFileSync(candidate, 'utf8'));+ } catch {+ parsed = null;+ }+ if (!parsed) return 'failed';++ // Tokenless markers are already committed ownership records. A release call+ // can only have moved one here before it verified a stale/wrong claim token;+ // restore it regardless of the current account rather than deleting it.+ if (!parsed.claimToken) {+ return restoreClaimedLocalProfileMarker(candidate, marker) ? null : 'failed';+ }+ if (parsed.ownerId === committedOwnerId) {+ if (!restoreClaimedLocalProfileMarker(candidate, marker)) return 'failed';+ replaceLocalProfileMigrationMarker(+ marker,+ `${JSON.stringify({ ownerId: parsed.ownerId, claimedAt: Date.now() })}\n`,+ );+ return 'finalized';+ }++ try {+ fs.unlinkSync(candidate);+ syncMarkerDirectory(marker);+ return 'released';+ } catch {+ return 'failed';+ }+}++function recoverPendingLocalProfileMigrationMarker(marker: string): void {+ const pending = `${marker}.pending`;+ if (!fs.existsSync(pending)) return;+ if (fs.existsSync(marker)) {+ try {+ fs.unlinkSync(pending);+ syncMarkerDirectory(marker);+ } catch {+ // The canonical marker is authoritative; a later pass can retry cleanup.+ }+ return;+ }+ let parsed: LocalProfileMigrationMarker | null = null;+ try {+ parsed = parseLocalProfileMigrationMarker(fs.readFileSync(pending, 'utf8'));+ } catch {+ parsed = null;+ }+ if (!parsed) {+ fs.unlinkSync(pending);+ syncMarkerDirectory(marker);+ return;+ }+ flushFile(pending);+ syncMarkerDirectory(pending);+ if (fs.existsSync(marker)) return;+ fs.renameSync(pending, marker);+ const finalHandle = fs.openSync(marker, 'r+');+ try {+ fs.fsyncSync(finalHandle);+ } finally {+ fs.closeSync(finalHandle);+ }+ syncMarkerDirectory(marker);+}++function reserveLocalProfileDataOwnerWhileLocked(+ normalizedOwnerId: string,+ marker: string,+ provisional: boolean,+): LocalProfileMigrationReservationDetails {+ try {+ recoverPendingLocalProfileMigrationMarker(marker);+ } catch {+ return { status: 'failed' };+ }+ // A previous release may have moved the canonical marker to this candidate+ // and failed to restore it. Treat that stranded ownership evidence as busy;+ // never let a later owner claim the namespace while it is unresolved.+ if (fs.existsSync(`${marker}.release`)) return { status: 'failed' };+ const claimToken = provisional ? randomUUID() : undefined;+ const contents = `${JSON.stringify({+ ownerId: normalizedOwnerId,+ ...(claimToken ? { claimToken } : {}),+ claimedAt: Date.now(),+ })}\n`;+ for (let attempt = 0; attempt < 4; attempt += 1) {+ try {+ // Restore an atomic-write backup before deciding that the namespace is+ // unclaimed. A stranded `.bak` is still a valid ownership snapshot.+ const raw = readAtomicFileSync(marker);+ if (raw === null) throw Object.assign(new Error('marker is absent'), { code: 'ENOENT' });+ const parsed = parseLocalProfileMigrationMarker(raw);+ if (parsed) {+ if (parsed.ownerId !== normalizedOwnerId) {+ return { status: 'owned-by-other', ownerId: parsed.ownerId };+ }+ if (!provisional && parsed.claimToken) {+ replaceLocalProfileMigrationMarker(+ marker,+ `${JSON.stringify({ ownerId: normalizedOwnerId, claimedAt: Date.now() })}\n`,+ );+ }+ return { status: 'already-owned', ownerId: normalizedOwnerId };+ }+ // A malformed marker is not evidence of an unused namespace. It may be+ // a damaged committed owner record, so preserve it and fail closed rather+ // than allowing a later account to adopt the retained local database.+ return { status: 'failed' };+ } catch (error) {+ if ((error as NodeJS.ErrnoException | null)?.code !== 'ENOENT') {+ return { status: 'failed' };+ }+ }+ try {+ if (publishLocalProfileMigrationMarker(marker, contents) === 'claimed') {+ return {+ status: 'claimed',+ ownerId: normalizedOwnerId,+ ...(claimToken ? { claimToken } : {}),+ };+ }+ } catch {+ return { status: 'failed' };+ }+ }+ return { status: 'failed' };+}++/**+ * Reserve local-v1 synchronously at the cloud-owner commit edge. This is a+ * machine-level marker, not user content, so the auth commit can persist the+ * ownership decision before any later renderer/database hook runs.+ */+export function reserveLocalProfileDataOwnerDetailed(+ ownerId: string,+ userDataDir: string,+ dbFilePrefix: string,+): LocalProfileMigrationReservationDetails {+ const normalizedOwnerId = ownerId.trim();+ if (!normalizedOwnerId || normalizedOwnerId === LOCAL_PROFILE_DATA_OWNER_ID) {+ return { status: 'failed' };+ }+ const marker = path.join(+ userDataDir,+ `${dbFilePrefix}-${LOCAL_PROFILE_DATA_OWNER_ID}${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`,+ );+ return withLocalProfileMigrationLock(marker, { status: 'failed' }, () =>+ reserveLocalProfileDataOwnerWhileLocked(normalizedOwnerId, marker, true),+ );+}++/** Reserve or finalize ownership for an owner whose cloud session is already durable. */+export function reserveCommittedLocalProfileDataOwnerDetailed(+ ownerId: string,+ userDataDir: string,+ dbFilePrefix: string,+): LocalProfileMigrationReservationDetails {+ const normalizedOwnerId = ownerId.trim();+ if (!normalizedOwnerId || normalizedOwnerId === LOCAL_PROFILE_DATA_OWNER_ID) {+ return { status: 'failed' };+ }+ const marker = path.join(+ userDataDir,+ `${dbFilePrefix}-${LOCAL_PROFILE_DATA_OWNER_ID}${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`,+ );+ return withLocalProfileMigrationLock<LocalProfileMigrationReservationDetails>(+ marker,+ { status: 'failed' },+ () => reserveLocalProfileDataOwnerWhileLocked(normalizedOwnerId, marker, false),+ );+}++export function reserveCommittedLocalProfileDataOwner(+ ownerId: string,+ userDataDir: string,+ dbFilePrefix: string,+): LocalProfileMigrationReservation {+ return reserveCommittedLocalProfileDataOwnerDetailed(ownerId, userDataDir, dbFilePrefix).status;+}++export function reserveLocalProfileDataOwner(+ ownerId: string,+ userDataDir: string,+ dbFilePrefix: string,+): LocalProfileMigrationReservation {+ return reserveLocalProfileDataOwnerDetailed(ownerId, userDataDir, dbFilePrefix).status;+}++export function releaseLocalProfileDataOwner(+ ownerId: string,+ userDataDir: string,+ dbFilePrefix: string,+ claimToken: string,+): boolean {+ const normalizedOwnerId = ownerId.trim();+ if (!normalizedOwnerId || !claimToken) return false;+ const marker = path.join(+ userDataDir,+ `${dbFilePrefix}-${LOCAL_PROFILE_DATA_OWNER_ID}${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`,+ );+ return withLocalProfileMigrationLock(marker, false, () => {+ const candidate = `${marker}.release`;+ try {+ // Atomically claim the exact marker before checking the token. This+ // prevents a stale read from unlinking another reservation.+ fs.renameSync(marker, candidate);+ const parsed = parseLocalProfileMigrationMarker(fs.readFileSync(candidate, 'utf8'));+ if (!parsed || parsed.ownerId !== normalizedOwnerId || parsed.claimToken !== claimToken) {+ restoreClaimedLocalProfileMarker(candidate, marker);+ return false;+ }+ fs.unlinkSync(candidate);+ syncMarkerDirectory(marker);+ return true;+ } catch {+ if (fs.existsSync(candidate)) restoreClaimedLocalProfileMarker(candidate, marker);+ return false;+ }+ });+}++/**+ * Settle a durable pre-commit claim before another cloud-owner transition.+ * A token belonging to the currently committed owner is finalized in place;+ * any other token is an interrupted reservation and is released. Markers+ * without a token are already committed and are never changed here.+ */+export function recoverPendingLocalProfileDataOwner(+ committedOwnerId: string | null,+ userDataDir: string,+ dbFilePrefix: string,+): PendingLocalProfileReservationRecovery {+ const normalizedCommittedOwnerId = committedOwnerId?.trim() || null;+ const marker = path.join(+ userDataDir,+ `${dbFilePrefix}-${LOCAL_PROFILE_DATA_OWNER_ID}${LOCAL_PROFILE_MIGRATION_MARKER_SUFFIX}`,+ );+ return withLocalProfileMigrationLock<PendingLocalProfileReservationRecovery>(+ marker,+ 'failed',+ () => {+ try {+ const releasedMarkerRecovery = recoverReleasedLocalProfileMigrationMarker(+ marker,+ normalizedCommittedOwnerId,+ );+ if (releasedMarkerRecovery) return releasedMarkerRecovery;+ recoverPendingLocalProfileMigrationMarker(marker);+ // atomicWriteFileSync may leave the only valid snapshot in .bak after+ // an interrupted Windows backup exchange. Restore it before deciding+ // whether a pending claim exists.+ const raw = readAtomicFileSync(marker);+ if (raw === null) return 'none';+ const parsed = parseLocalProfileMigrationMarker(raw);+ if (!parsed) return 'failed';+ if (!parsed.claimToken) return 'none';+ if (parsed.ownerId === normalizedCommittedOwnerId) {+ replaceLocalProfileMigrationMarker(+ marker,+ `${JSON.stringify({ ownerId: parsed.ownerId, claimedAt: Date.now() })}\n`,+ );+ return 'finalized';+ }+ fs.unlinkSync(marker);+ syncMarkerDirectory(marker);+ return 'released';+ } catch {+ return 'failed';+ }+ },+ );+}++async function cleanupTemps(deps: LocalProfileDataMigrationDeps, targetDb: string): Promise<void> {+ const directory = path.dirname(targetDb);+ const targetName = path.basename(targetDb);+ const prefixes = [+ `${targetName}${LOCAL_PROFILE_MIGRATION_TMP_SUFFIX}`,+ ...DB_SIDECAR_SUFFIXES.map(+ (suffix) => `${targetName}${suffix}${LOCAL_PROFILE_MIGRATION_TMP_SUFFIX}`,+ ),+ ];+ const entries = await deps.fs.readDir(directory);+ for (const entry of entries) {+ if (prefixes.some((prefix) => entry === prefix || entry.startsWith(`${prefix}.`))) {+ await deps.fs.removeIfExists(path.join(directory, entry));+ }+ }+}++async function databaseFileGroupState(+ deps: LocalProfileDataMigrationDeps,+ database: string,+): Promise<{ mainExists: boolean; sidecarExists: boolean }> {+ const [mainExists, ...sidecarResults] = await Promise.all([+ deps.fs.pathExists(database),+ ...DB_SIDECAR_SUFFIXES.map((suffix) => deps.fs.pathExists(`${database}${suffix}`)),+ ]);+ return { mainExists, sidecarExists: sidecarResults.some(Boolean) };+}++type DatabasePublicationRecovery = 'clean' | 'ambiguous';++type PassivePendingDatabaseCopyMarkerRead =+ | { status: 'absent' }+ | { status: 'present'; raw: string }+ | { status: 'recovery-required' };++function readPendingDatabaseCopyMarkerForPassivePreflight(+ pending: string,+): PassivePendingDatabaseCopyMarkerRead {+ for (let attempt = 0; attempt < 2; attempt += 1) {+ try {+ return { status: 'present', raw: fs.readFileSync(pending, 'utf8') };+ } catch (error) {+ if ((error as NodeJS.ErrnoException | null)?.code !== 'ENOENT') throw error;+ // Passive preflight is deliberately read-only. During atomicWriteFileSync's+ // Windows backup exchange the canonical marker can be absent while .bak is+ // the writer's only valid snapshot. Restoring it here would race the writer+ // outside the migration lock, so leave both paths untouched and fail closed.+ if (fs.existsSync(`${pending}.bak`)) return { status: 'recovery-required' };+ // The writer may have completed the exchange and removed .bak between the+ // failed read and the backup check. Re-read canonical once before deciding+ // that no publication marker exists.+ if (attempt === 1) return { status: 'absent' };+ }+ }+ return { status: 'absent' };+}++async function recoverIncompleteDatabasePublication(+ deps: LocalProfileDataMigrationDeps,+ targetDb: string,+): Promise<DatabasePublicationRecovery> {+ const pending = `${targetDb}${DB_COPY_PENDING_SUFFIX}`;+ const raw = readAtomicFileSync(pending);+ if (raw === null) return 'clean';+ const marker = parsePendingDatabaseCopyMarker(raw);+ if (!marker) throw new Error('database copy pending marker is malformed');++ const targetState = await databaseFileGroupState(deps, targetDb);+ if (marker.phase === 'claiming') {+ // A competing cloud initializer may have won after our marker was+ // persisted. An ambiguous marker must never authorize deleting or opening+ // that target; leave both files in place and fail closed.+ if (targetState.mainExists || targetState.sidecarExists) return 'ambiguous';+ await deps.fs.removeIfExists(pending);+ return 'clean';+ }+ if (marker.phase === 'published') {+ // The snapshot was fully flushed before marker cleanup. Preserve the+ // target and retire only the bookkeeping marker.+ if (!targetState.mainExists) {+ for (const suffix of DB_SIDECAR_SUFFIXES) {+ await deps.fs.removeIfExists(`${targetDb}${suffix}`);+ }+ }+ await deps.fs.removeIfExists(pending);+ return 'clean';+ }++ if (marker.phase === 'raced') {+ // Another initializer won the no-replace claim. Never remove its target;+ // retire only this process's bookkeeping marker.+ await deps.fs.removeIfExists(pending).catch(() => undefined);+ return 'clean';+ }++ // Only the explicit copying phase proves that this process won the target's+ // O_EXCL claim. It is therefore the only state allowed to remove a partial+ // target and retry adoption after a crash.+ await deps.fs.removeIfExists(targetDb);+ for (const suffix of DB_SIDECAR_SUFFIXES) {+ await deps.fs.removeIfExists(`${targetDb}${suffix}`);+ }+ await deps.fs.removeIfExists(pending);+ return 'clean';+}++export type PassiveLocalProfileAdoptionPreflight =+ | { status: 'not-required'; reason: 'no-local-db' | 'target-exists' | 'claimed-by-other-owner' }+ | { status: 'required' }+ | { status: 'failed'; error: string };++/**+ * Read-only guard for a passive shared-userData process. Passive instances must+ * not claim or copy local-v1, but they also must not create an empty cloud target+ * while the authoritative owner still needs to adopt the retained source.+ */+export async function inspectPassiveLocalProfileAdoption(+ ownerId: string,+ deps: LocalProfileDataMigrationDeps,+): Promise<PassiveLocalProfileAdoptionPreflight> {+ const normalizedOwnerId = ownerId.trim();+ if (!normalizedOwnerId || normalizedOwnerId === LOCAL_PROFILE_DATA_OWNER_ID) {+ return { status: 'failed', error: 'invalid cloud owner for local profile adoption' };+ }++ const sourceDb = dbPath(deps, LOCAL_PROFILE_DATA_OWNER_ID);+ const targetDb = dbPath(deps, normalizedOwnerId);+ try {+ const targetState = await databaseFileGroupState(deps, targetDb);+ if (targetState.sidecarExists && !targetState.mainExists) {+ return {+ status: 'failed',+ error: 'target database sidecar exists without its main database',+ };+ }+ if (targetState.mainExists) {+ const pendingMarker = readPendingDatabaseCopyMarkerForPassivePreflight(+ `${targetDb}${DB_COPY_PENDING_SUFFIX}`,+ );+ if (pendingMarker.status === 'recovery-required') {+ return {+ status: 'failed',+ error: 'database copy pending marker recovery requires migration lock',+ };+ }+ if (pendingMarker.status === 'present') {+ const pending = parsePendingDatabaseCopyMarker(pendingMarker.raw);+ if (!pending) {+ return { status: 'failed', error: 'database copy pending marker is malformed' };+ }+ if (pending.phase === 'claiming') {+ return {+ status: 'failed',+ error: 'database copy publication has an unproven target owner',+ };+ }+ if (pending.phase === 'copying') {+ return { status: 'failed', error: 'target database copy is incomplete' };+ }+ }+ return { status: 'not-required', reason: 'target-exists' };+ }+ const sourceState = await databaseFileGroupState(deps, sourceDb);+ if (sourceState.sidecarExists && !sourceState.mainExists) {+ return {+ status: 'failed',+ error: 'source database sidecar exists without its main database',+ };+ }+ if (!sourceState.mainExists) {+ if (deps.hasExclusiveSourceAccess && !deps.hasExclusiveSourceAccess()) {+ return {+ status: 'failed',+ error: 'local profile database adoption deferred: concurrent live instance',+ };+ }+ return { status: 'not-required', reason: 'no-local-db' };+ }++ try {+ const parsed = parseLocalProfileMigrationMarker(+ await deps.fs.readFile(migrationMarkerPath(deps)),+ );+ if (!parsed) {+ return { status: 'failed', error: 'local profile owner marker is malformed' };+ }+ if (parsed.ownerId !== normalizedOwnerId) {+ return { status: 'not-required', reason: 'claimed-by-other-owner' };+ }+ } catch (error) {+ if ((error as NodeJS.ErrnoException | null)?.code !== 'ENOENT') throw error;+ // A missing marker can be repaired only by the primary instance. Until+ // then, preserve the source by keeping this create-capable path closed.+ }+ return { status: 'required' };+ } catch (error) {+ return {+ status: 'failed',+ error: error instanceof Error ? error.message : String(error),+ };+ }+}++async function copyDatabaseAtomically(+ deps: LocalProfileDataMigrationDeps,+ sourceDb: string,+ targetDb: string,+): Promise<boolean> {+ await cleanupTemps(deps, targetDb);+ const attemptId = randomUUID();+ const dbTmp = `${targetDb}${LOCAL_PROFILE_MIGRATION_TMP_SUFFIX}.${attemptId}`;+ let published = false;+ try {+ // SQLite's online backup API takes one coherent snapshot even while another+ // process is writing the WAL. The resulting standalone database therefore+ // needs no source -wal/-shm files and can be published as one atomic entry.+ await deps.fs.backupDatabase(sourceDb, dbTmp);+ if (deps.hasExclusiveSourceAccess && !deps.hasExclusiveSourceAccess()) {+ throw new Error('local profile database adoption deferred: concurrent live instance');+ }+ // Claim the target with a no-replace filesystem primitive. Never use+ // rename here: a later initializer must lose with EEXIST rather than+ // overwrite the database already published by the first initializer.+ const linked = await claimDatabaseTargetWithoutReplacement(deps, dbTmp, targetDb);+ if (!linked) return false;+ published = true;+ flushPublishedDatabase(targetDb);+ if (deps.hasExclusiveSourceAccess && !deps.hasExclusiveSourceAccess()) {+ throw new Error('local profile database adoption deferred: concurrent live instance');+ }+ return true;+ } catch (error) {+ if (published) await deps.fs.removeIfExists(targetDb);+ throw error;+ } finally {+ await deps.fs.removeIfExists(dbTmp);+ }+}++async function claimDatabaseTargetWithoutReplacement(+ deps: LocalProfileDataMigrationDeps,+ dbTmp: string,+ targetDb: string,+): Promise<boolean> {+ try {+ await deps.fs.link(dbTmp, targetDb);+ return true;+ } catch (error) {+ const code = (error as NodeJS.ErrnoException | null)?.code;+ if (code === 'EEXIST') return false;+ if (!['EXDEV', 'EPERM', 'EOPNOTSUPP', 'ENOTSUP', 'ENOSYS'].includes(code ?? '')) {+ throw error;+ }+ try {+ await deps.fs.copyNoReplace(dbTmp, targetDb);+ return true;+ } catch (fallbackError) {+ if ((fallbackError as NodeJS.ErrnoException | null)?.code === 'EEXIST') return false;+ throw fallbackError;+ }+ }+}++/**+ * Snapshot local-v1's database into the verified cloud owner's database.+ * This function is deliberately pure with respect to application state: the+ * caller must invoke it after owner verification and before opening the target+ * DbClient. It never deletes or overwrites the local source.+ */+export async function adoptLocalProfileDatabase(+ ownerId: string,+ deps: LocalProfileDataMigrationDeps,+): Promise<LocalProfileDataMigrationResult> {+ const normalizedOwnerId = ownerId.trim();+ if (!normalizedOwnerId || normalizedOwnerId === LOCAL_PROFILE_DATA_OWNER_ID) {+ return { status: 'no-local-db' };+ }++ const sourceDb = dbPath(deps, LOCAL_PROFILE_DATA_OWNER_ID);+ const targetDb = dbPath(deps, normalizedOwnerId);+ const marker = migrationMarkerPath(deps);+ let lockDb: LocalProfileMigrationLockDb | null = null;+ let sourcePublicationBarrier: Awaited<+ ReturnType<NonNullable<LocalProfileDataMigrationDeps['acquireSourcePublicationBarrier']>>+ > | null = null;+ try {+ lockDb = await acquireLocalProfileMigrationLock(marker);+ const reservation = reserveLocalProfileDataOwnerWhileLocked(normalizedOwnerId, marker, false);+ if (reservation.status === 'owned-by-other') return { status: 'claimed-by-other-owner' };+ if (reservation.status === 'failed') {+ throw new Error('failed to reserve local profile owner');+ }+ const recovery = await recoverIncompleteDatabasePublication(deps, targetDb);+ if (recovery === 'ambiguous') {+ return {+ status: 'failed',+ error: 'database copy publication has an unproven target owner',+ };+ }+ // Reserve the local namespace even when it is currently empty. Otherwise a+ // later account could create or adopt local content after the first account+ // has already crossed the login boundary.+ // Check the target first: an existing cloud database remains authoritative+ // and must open even while another live instance shares userData.+ const targetState = await databaseFileGroupState(deps, targetDb);+ if (targetState.sidecarExists && !targetState.mainExists) {+ throw new Error('target database sidecar exists without its main database');+ }+ if (targetState.mainExists || targetState.sidecarExists) {+ await cleanupTemps(deps, targetDb);+ return { status: 'target-exists' };+ }+ if (deps.acquireSourcePublicationBarrier) {+ sourcePublicationBarrier = await deps.acquireSourcePublicationBarrier();+ }+ const guardedDeps: LocalProfileDataMigrationDeps = sourcePublicationBarrier+ ? {+ ...deps,+ hasExclusiveSourceAccess: () =>+ sourcePublicationBarrier?.isHeld() === true &&+ (deps.hasExclusiveSourceAccess?.() ?? true),+ }+ : deps;+ const sourceState = await databaseFileGroupState(guardedDeps, sourceDb);+ if (sourceState.sidecarExists && !sourceState.mainExists) {+ throw new Error('source database sidecar exists without its main database');+ }+ if (!sourceState.mainExists) {+ if (guardedDeps.hasExclusiveSourceAccess && !guardedDeps.hasExclusiveSourceAccess()) {+ throw new Error('local profile database adoption deferred: concurrent live instance');+ }+ return { status: 'no-local-db' };+ }+ // The same crash-released SQLite writer lock serializes marker repair and+ // the complete snapshot publication. No PID identity or reclaimable lease+ // file is involved, so a crashed process cannot block adoption forever.+ if (guardedDeps.hasExclusiveSourceAccess && !guardedDeps.hasExclusiveSourceAccess()) {+ throw new Error('local profile database adoption deferred: concurrent live instance');+ }+ const adopted = await copyDatabaseAtomically(guardedDeps, sourceDb, targetDb);+ return adopted ? { status: 'adopted', sourceDb, targetDb } : { status: 'target-exists' };+ } catch (error) {+ // Migration snapshots are shared across processes. Only the SQLite writer+ // lock owner may classify matching UUID files as stale; a contender that+ // timed out before acquiring the lock must not unlink the active holder's+ // snapshot while SQLite is still writing it.+ if (lockDb) await cleanupTemps(deps, targetDb).catch(() => undefined);+ return {+ status: 'failed',+ error: error instanceof Error ? error.message : String(error),+ };+ } finally {+ if (lockDb) releaseLocalProfileMigrationLock(lockDb);+ await sourcePublicationBarrier?.release().catch(() => undefined);+ }+}++export function createProductionLocalProfileDataMigrationDeps(+ userDataDir: string,+ dbFilePrefix: string,+ hasExclusiveSourceAccess?: () => boolean,+ acquireSourcePublicationBarrier?: LocalProfileDataMigrationDeps['acquireSourcePublicationBarrier'],+): LocalProfileDataMigrationDeps {+ return {+ userDataDir,+ dbFilePrefix,+ fs: realFs,+ ...(hasExclusiveSourceAccess ? { hasExclusiveSourceAccess } : {}),+ ...(acquireSourcePublicationBarrier ? { acquireSourcePublicationBarrier } : {}),+ };+}diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.tsindex 943c09b339..a44e63241d 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts@@ -71,6 +71,18 @@ function deferred<T = void>() {return { promise, resolve };}+it('compares Codex hard-link identities without Windows number precision collisions', async () => {+ const { haveSameStableFileIdentity } = await import('../auth-adapters.js');+ expect(+ haveSameStableFileIdentity(+ { dev: 0n, ino: 9_007_199_254_740_992n },+ { dev: 0n, ino: 9_007_199_254_740_993n },+ ),+ ).toBe(false);+ expect(haveSameStableFileIdentity({ dev: 0n, ino: 0n }, { dev: 0n, ino: 0n })).toBe(false);+ expect(haveSameStableFileIdentity({ dev: 7n, ino: 11n }, { dev: 7n, ino: 11n })).toBe(true);+});+async function createRecoveryCandidate(credentialScope: 'system-shared' | 'instance-isolated' | 'unknown',) {@@ -459,7 +471,7 @@ describe('Codex system credential suppression marker', () => {}).finishSuccessfulCodexLogin.bind(adapter);await expect(finishSuccessfulCodexLogin()).resolves.toMatchObject({ authenticated: true });- expect(fs.statSync(localAuth).ino).not.toBe(fs.statSync(systemAuth).ino);+ expect(fs.readFileSync(localAuth, 'utf8')).not.toBe(fs.readFileSync(systemAuth, 'utf8'));expect(JSON.parse(fs.readFileSync(localAuth, 'utf8'))).toMatchObject({tokens: { access_token: 'new-local-token', account_id: 'acct-1' },});@@ -542,7 +554,7 @@ describe('Codex system credential suppression marker', () => {authenticated: true,credentialScope: 'instance-isolated',});- expect(fs.statSync(localAuth).ino).not.toBe(fs.statSync(systemAuth).ino);+ expect(fs.readFileSync(localAuth, 'utf8')).not.toBe(fs.readFileSync(systemAuth, 'utf8'));expect(JSON.parse(fs.readFileSync(localAuth, 'utf8'))).toMatchObject({tokens: { access_token: 'new-cindy-token' },});@@ -876,6 +888,24 @@ describe('Codex system credential suppression marker', () => {expect(fs.existsSync(localAuth)).toBe(false);});+ it('rejects explicit logout when the provider binding mutation lock is unavailable', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-auth-binding-lock-'));+ dirs.push(root);+ h.userDataDir = path.join(root, 'user-data');+ h.dataOwnerId = 'owner-a';+ fs.mkdirSync(+ path.join(h.userDataDir, 'native-provider-auth.json.mutation-lock.db'),+ { recursive: true },+ );++ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');+ const adapter = new DesktopCodexAuthAdapter();++ await expect(adapter.logout()).rejects.toThrow(+ 'failed to acquire native provider binding mutation lock',+ );+ });+it('clears a pending recovery state when the user explicitly logs out', async () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-recovery-logout-'));dirs.push(root);@@ -1117,7 +1147,7 @@ describe('Codex system credential suppression marker', () => {recoveryRequiredReason: 'token_revoked',credentialScope: 'instance-isolated',});- expect(fs.statSync(localAuth).ino).not.toBe(fs.statSync(systemAuth).ino);+ expect(fs.readFileSync(localAuth, 'utf8')).not.toBe(fs.readFileSync(systemAuth, 'utf8'));expect(getActiveInvalidatedSystemCodexAuthMarker(codexHome, systemAuth)).toMatchObject({reason: 'token_revoked',credentialScope: 'instance-isolated',@@ -1337,7 +1367,7 @@ describe('Codex system credential suppression marker', () => {}),);fs.renameSync(replacement, systemAuth);- expect(fs.statSync(localAuth).ino).not.toBe(fs.statSync(systemAuth).ino);+ expect(fs.readFileSync(localAuth, 'utf8')).not.toBe(fs.readFileSync(systemAuth, 'utf8'));const broadcast = vi.fn();adapter.setOnInvalidatedBroadcast(broadcast);diff --git a/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts b/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.tsindex bc5132804b..9ce065abd6 100644--- a/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts@@ -3,6 +3,8 @@ import path from 'node:path';import { afterEach, describe, expect, it, vi } from 'vitest';+import { createBetterSqliteDatabase } from '../../localDb/betterSqliteFactory.js';+const userDataDir = '/tmp/native-provider-auth-binding-test';const session = { dataOwnerId: 'owner-a' as string | null, boundaryPending: false };@@ -11,6 +13,7 @@ vi.mock('electron', () => ({}));vi.mock('../../appSessionState.js', () => ({+ LOCAL_DATA_OWNER_ID: 'local-v1',getActiveAppSession: () => ({mode: session.dataOwnerId ? 'cloud' : 'signed-out',dataOwnerId: session.dataOwnerId,@@ -26,14 +29,23 @@ import {isNativeProviderAuthBound,isNativeProviderAuthRevoked,isNativeProviderAuthSelfAuthorized,+ migrateLocalNativeProviderAuthBindings,migrateLegacyNativeProviderAuthBindings,+ readLegacyNativeProviderAuthOwner,+ recoverPendingLegacyNativeProviderAuthOwner,+ reserveCommittedLegacyNativeProviderAuthOwner,+ reserveLegacyNativeProviderAuthOwner,+ reserveLegacyNativeProviderAuthOwnerDetailed,+ releaseLegacyNativeProviderAuthOwner,restoreNativeProviderAuthForRecovery,unbindNativeProviderAuth,} from '../nativeProviderAuthBinding.js';const bindingFile = path.join(userDataDir, 'native-provider-auth.json');+const bindingLockDb = `${bindingFile}.mutation-lock.db`;afterEach(() => {+ vi.restoreAllMocks();session.dataOwnerId = 'owner-a';session.boundaryPending = false;fs.rmSync(userDataDir, { recursive: true, force: true });@@ -67,6 +79,398 @@ describe('native provider auth legacy binding', () => {expect(isNativeProviderAuthBound('xai')).toBe(false);});++ it('lets the reserved owner finish legacy migration after credentials become available', () => {+ expect(reserveLegacyNativeProviderAuthOwner('owner-a')).toBe('claimed');++ migrateLegacyNativeProviderAuthBindings('owner-a', { xai: true });++ expect(isNativeProviderAuthBound('xai')).toBe(true);+ expect(getNativeProviderAuthSource('xai')).toBe('explicit-provider-oauth');+ expect(isNativeProviderAuthSelfAuthorized('xai')).toBe(true);+ });++ it('does not rewrite an unchanged legacy binding for the reserved owner', () => {+ expect(reserveLegacyNativeProviderAuthOwner('owner-a')).toBe('claimed');+ const renameSpy = vi.spyOn(fs, 'renameSync');+ fs.rmSync(bindingLockDb, { force: true });++ migrateLegacyNativeProviderAuthBindings('owner-a', {});++ expect(renameSpy).not.toHaveBeenCalledWith(expect.any(String), bindingFile);+ expect(fs.existsSync(bindingLockDb)).toBe(false);+ });++ it('treats a malformed provider owner slot as occupied during repeatable migration', () => {+ fs.mkdirSync(userDataDir, { recursive: true });+ fs.writeFileSync(+ bindingFile,+ JSON.stringify({ legacyClaimOwner: 'owner-a', openai: '' }),+ );++ migrateLegacyNativeProviderAuthBindings('owner-a', { openai: true });++ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toEqual({+ legacyClaimOwner: 'owner-a',+ openai: '',+ });+ });++ it('does not acquire the mutation lock for a known no-op claim', () => {+ expect(claimDetectedNativeProviderAuth('openai', () => true)).toBe(true);+ fs.rmSync(bindingLockDb, { force: true });+ const hasCredential = vi.fn(() => true);++ expect(claimDetectedNativeProviderAuth('openai', hasCredential)).toBe(false);++ expect(hasCredential).not.toHaveBeenCalled();+ expect(fs.existsSync(bindingLockDb)).toBe(false);+ });+});++describe('local → cloud native provider binding migration', () => {+ it('flushes the binding file and parent directory before reporting a reservation', () => {+ const openSpy = vi.spyOn(fs, 'openSync');+ const fsyncSpy = vi.spyOn(fs, 'fsyncSync');++ expect(reserveLegacyNativeProviderAuthOwner('owner-a')).toBe('claimed');++ expect(openSpy).toHaveBeenCalledWith(bindingFile, 'r+');+ if (process.platform !== 'win32') {+ expect(openSpy).toHaveBeenCalledWith(userDataDir, 'r');+ }+ expect(fsyncSpy).toHaveBeenCalled();+ });++ it('retries transient Windows-style binding publication locks', () => {+ expect(reserveLegacyNativeProviderAuthOwner('owner-a')).toBe('claimed');+ const originalRenameSync = fs.renameSync.bind(fs);+ let blocked = false;+ const renameSpy = vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => {+ if (!blocked && to === bindingFile) {+ blocked = true;+ throw Object.assign(new Error('file is temporarily busy'), { code: 'EBUSY' });+ }+ return originalRenameSync(from, to);+ });++ expect(recoverPendingLegacyNativeProviderAuthOwner('owner-a')).toBe('finalized');+ expect(blocked).toBe(true);+ expect(renameSpy.mock.calls.filter(([, to]) => to === bindingFile)).toHaveLength(2);+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({+ legacyClaimOwner: 'owner-a',+ });+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).not.toHaveProperty(+ 'legacyClaimToken',+ );+ });++ it('restores the atomic backup before deriving a binding update', () => {+ const retained = {+ openai: 'owner-a',+ legacyClaimOwner: 'owner-a',+ revoked: { anthropic: 'owner-a' },+ };+ fs.mkdirSync(userDataDir, { recursive: true });+ fs.writeFileSync(`${bindingFile}.bak`, JSON.stringify(retained));++ bindNativeProviderAuth('xai');++ expect(fs.existsSync(`${bindingFile}.bak`)).toBe(false);+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({+ ...retained,+ xai: 'owner-a',+ selfAuthorized: { xai: 'owner-a' },+ });+ });++ it('restores a backup only while holding the shared mutation lock', () => {+ fs.mkdirSync(userDataDir, { recursive: true });+ fs.writeFileSync(+ `${bindingFile}.bak`,+ JSON.stringify({ openai: 'owner-a', legacyClaimOwner: 'owner-a' }),+ );+ const originalRenameSync = fs.renameSync.bind(fs);+ const lockObserved: boolean[] = [];+ vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => {+ if (from === `${bindingFile}.bak` && to === bindingFile) {+ const contender = createBetterSqliteDatabase(bindingLockDb);+ contender.pragma('busy_timeout = 1');+ try {+ contender.exec('BEGIN IMMEDIATE');+ contender.exec('ROLLBACK');+ lockObserved.push(false);+ } catch (error) {+ lockObserved.push((error as { code?: string }).code === 'SQLITE_BUSY');+ } finally {+ contender.close();+ }+ }+ return originalRenameSync(from, to);+ });++ expect(isNativeProviderAuthBound('openai')).toBe(true);+ expect(lockObserved).toEqual([true]);+ });++ it('uses a crash-released SQLite transaction lock instead of a reclaimable lease file', () => {+ expect(reserveLegacyNativeProviderAuthOwner('owner-a')).toBe('claimed');++ expect(fs.existsSync(bindingLockDb)).toBe(true);+ expect(fs.existsSync(`${bindingFile}.legacy-claim-lease`)).toBe(false);+ });++ it('surfaces mutation-lock acquisition failure during explicit unbind', () => {+ fs.mkdirSync(bindingLockDb, { recursive: true });++ expect(() => unbindNativeProviderAuth('openai', { revoked: true })).toThrow(+ 'failed to acquire native provider binding mutation lock',+ );+ });++ it('avoids the mutation lock for a known no-op invalidation unbind', () => {+ expect(claimDetectedNativeProviderAuth('openai', () => true)).toBe(true);+ unbindNativeProviderAuth('openai');+ fs.rmSync(bindingLockDb, { force: true });++ unbindNativeProviderAuth('openai');++ expect(fs.existsSync(bindingLockDb)).toBe(false);+ });++ it('removes a stale source field even when the provider slot is already absent', () => {+ fs.mkdirSync(userDataDir, { recursive: true });+ fs.writeFileSync(+ bindingFile,+ JSON.stringify({ sources: { openai: 'native-harness-inherited' } }),+ );++ unbindNativeProviderAuth('openai');++ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toEqual({ sources: {} });+ });++ it('reads every binding mutation while holding the shared SQLite writer lock', () => {+ const originalReadFileSync = fs.readFileSync.bind(fs);+ const leaseObserved: boolean[] = [];+ vi.spyOn(fs, 'readFileSync').mockImplementation(((file, ...args: unknown[]) => {+ if (file === bindingFile) {+ const contender = createBetterSqliteDatabase(bindingLockDb);+ contender.pragma('busy_timeout = 1');+ try {+ contender.exec('BEGIN IMMEDIATE');+ contender.exec('ROLLBACK');+ leaseObserved.push(false);+ } catch (error) {+ leaseObserved.push((error as { code?: string }).code === 'SQLITE_BUSY');+ } finally {+ contender.close();+ }+ }+ return originalReadFileSync(file as fs.PathOrFileDescriptor, ...(args as []));+ }) as typeof fs.readFileSync);++ bindNativeProviderAuth('anthropic');+ unbindNativeProviderAuth('anthropic', { revoked: true });++ expect(leaseObserved.length).toBeGreaterThanOrEqual(2);+ expect(leaseObserved.every(Boolean)).toBe(true);+ });++ it('reserves the first cloud owner even when no local provider slot exists', () => {+ expect(reserveLegacyNativeProviderAuthOwner('owner-a')).toBe('claimed');+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({+ legacyClaimOwner: 'owner-a',+ });+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8')).legacyClaimToken).toEqual(+ expect.any(String),+ );++ session.dataOwnerId = 'owner-b';+ expect(reserveLegacyNativeProviderAuthOwner('owner-b')).toBe('owned-by-other');+ });++ it('releases only the native reservation created by the matching claim token', () => {+ const reservation = reserveLegacyNativeProviderAuthOwnerDetailed('owner-a');+ expect(reservation).toMatchObject({ status: 'claimed', claimToken: expect.any(String) });+ expect(reserveLegacyNativeProviderAuthOwnerDetailed('owner-a')).toEqual({+ status: 'already-owned',+ });+ const beforeWrongToken = fs.readFileSync(bindingFile, 'utf8');+ expect(releaseLegacyNativeProviderAuthOwner('owner-a', 'wrong-token')).toBe(false);+ expect(fs.readFileSync(bindingFile, 'utf8')).toBe(beforeWrongToken);+ session.dataOwnerId = 'owner-b';+ expect(reserveLegacyNativeProviderAuthOwner('owner-b')).toBe('owned-by-other');+ session.dataOwnerId = 'owner-a';+ expect(releaseLegacyNativeProviderAuthOwner('owner-a', reservation.claimToken!)).toBe(true);+ session.dataOwnerId = 'owner-b';+ expect(reserveLegacyNativeProviderAuthOwner('owner-b')).toBe('claimed');+ });++ it('finalizes a pending native reservation for the committed owner', () => {+ const reservation = reserveLegacyNativeProviderAuthOwnerDetailed('owner-a');+ expect(reservation).toMatchObject({ status: 'claimed', claimToken: expect.any(String) });++ expect(recoverPendingLegacyNativeProviderAuthOwner('owner-a')).toBe('finalized');+ expect(releaseLegacyNativeProviderAuthOwner('owner-a', reservation.claimToken!)).toBe(false);+ session.dataOwnerId = 'owner-b';+ expect(reserveLegacyNativeProviderAuthOwner('owner-b')).toBe('owned-by-other');+ });++ it('creates a tokenless native reservation for an already durable cloud owner', () => {+ expect(reserveCommittedLegacyNativeProviderAuthOwner('owner-a')).toBe('claimed');+ const bindings = JSON.parse(fs.readFileSync(bindingFile, 'utf8'));+ expect(bindings).toMatchObject({ legacyClaimOwner: 'owner-a' });+ expect(bindings).not.toHaveProperty('legacyClaimToken');+ expect(recoverPendingLegacyNativeProviderAuthOwner(null)).toBe('none');+ session.dataOwnerId = 'owner-b';+ expect(reserveLegacyNativeProviderAuthOwner('owner-b')).toBe('owned-by-other');+ });++ it('exposes only a valid tokenless native owner for profile-marker bootstrap', () => {+ expect(readLegacyNativeProviderAuthOwner()).toEqual({ status: 'none' });+ expect(reserveCommittedLegacyNativeProviderAuthOwner('owner-a')).toBe('claimed');+ expect(readLegacyNativeProviderAuthOwner()).toEqual({ status: 'owned', ownerId: 'owner-a' });++ fs.writeFileSync(bindingFile, JSON.stringify({ legacyClaimOwner: '' }));+ expect(readLegacyNativeProviderAuthOwner()).toEqual({ status: 'failed' });+ });++ it.each([+ ['owner-a', 'already-owned'],+ ['owner-b', 'owned-by-other'],+ ] as const)('avoids the mutation lock for a stable-owner no-op (%s)', (ownerId, expected) => {+ expect(reserveCommittedLegacyNativeProviderAuthOwner('owner-a')).toBe('claimed');+ fs.rmSync(bindingLockDb, { force: true });++ expect(reserveCommittedLegacyNativeProviderAuthOwner(ownerId)).toBe(expected);+ expect(fs.existsSync(bindingLockDb)).toBe(false);+ });++ it.each([+ ['owner-a', 'already-owned'],+ ['owner-b', 'owned-by-other'],+ ] as const)('avoids the mutation lock for a provisional no-op (%s)', (ownerId, expected) => {+ expect(reserveCommittedLegacyNativeProviderAuthOwner('owner-a')).toBe('claimed');+ fs.rmSync(bindingLockDb, { force: true });++ expect(reserveLegacyNativeProviderAuthOwnerDetailed(ownerId)).toEqual({ status: expected });+ expect(fs.existsSync(bindingLockDb)).toBe(false);+ });++ it('avoids the mutation lock when there is no pending native claim to recover', () => {+ expect(reserveCommittedLegacyNativeProviderAuthOwner('owner-a')).toBe('claimed');+ fs.rmSync(bindingLockDb, { force: true });++ expect(recoverPendingLegacyNativeProviderAuthOwner('owner-a')).toBe('none');+ expect(fs.existsSync(bindingLockDb)).toBe(false);+ });++ it('recovers an interrupted native reservation before a different owner commits', () => {+ expect(reserveLegacyNativeProviderAuthOwner('owner-a')).toBe('claimed');++ expect(recoverPendingLegacyNativeProviderAuthOwner(null)).toBe('released');+ session.dataOwnerId = 'owner-b';+ expect(reserveLegacyNativeProviderAuthOwner('owner-b')).toBe('claimed');+ });++ it('keeps a pending native reservation recoverable after a binding write failure', () => {+ expect(reserveLegacyNativeProviderAuthOwner('owner-a')).toBe('claimed');+ const renameSpy = vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {+ throw Object.assign(new Error('binding write failed'), { code: 'EIO' });+ });++ expect(recoverPendingLegacyNativeProviderAuthOwner(null)).toBe('failed');+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({+ legacyClaimOwner: 'owner-a',+ legacyClaimToken: expect.any(String),+ });++ renameSpy.mockRestore();+ expect(recoverPendingLegacyNativeProviderAuthOwner(null)).toBe('released');+ session.dataOwnerId = 'owner-b';+ expect(reserveLegacyNativeProviderAuthOwner('owner-b')).toBe('claimed');+ });++ it('persists the local claim when the first cloud owner has no credential to migrate', () => {+ expect(migrateLocalNativeProviderAuthBindings('owner-a')).toBe(false);+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toEqual({+ legacyClaimOwner: 'owner-a',+ });++ session.dataOwnerId = 'owner-b';+ expect(claimDetectedNativeProviderAuth('openai', () => true)).toBe(false);+ });++ it('moves local-mode Harness bindings to the first cloud owner and preserves source metadata', () => {+ session.dataOwnerId = 'local-v1';+ expect(claimDetectedNativeProviderAuth('openai', () => true)).toBe(true);+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({+ openai: 'local-v1',+ sources: { openai: 'native-harness-inherited' },+ });++ session.dataOwnerId = 'owner-a';+ expect(migrateLocalNativeProviderAuthBindings('owner-a')).toBe(true);+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({+ openai: 'owner-a',+ legacyClaimOwner: 'owner-a',+ sources: { openai: 'native-harness-inherited' },+ });+ expect(isNativeProviderAuthBound('openai')).toBe(true);+ });++ it('avoids the mutation lock when no local binding can move', () => {+ expect(reserveCommittedLegacyNativeProviderAuthOwner('owner-a')).toBe('claimed');+ fs.rmSync(bindingLockDb, { force: true });++ expect(migrateLocalNativeProviderAuthBindings('owner-a')).toBe(false);+ expect(fs.existsSync(bindingLockDb)).toBe(false);+ });++ it('does not let a later cloud owner migrate local residue after another owner won the claim', () => {+ session.dataOwnerId = 'local-v1';+ expect(claimDetectedNativeProviderAuth('openai', () => true)).toBe(true);+ const current = JSON.parse(fs.readFileSync(bindingFile, 'utf8')) as Record<string, unknown>;+ fs.writeFileSync(+ bindingFile,+ JSON.stringify({ ...current, openai: 'local-v1', legacyClaimOwner: 'owner-a' }),+ );++ session.dataOwnerId = 'owner-b';+ expect(migrateLocalNativeProviderAuthBindings('owner-b')).toBe(false);+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({+ openai: 'local-v1',+ legacyClaimOwner: 'owner-a',+ });+ expect(isNativeProviderAuthBound('openai')).toBe(false);+ });++ it('keeps explicitly revoked local credentials suppressed', () => {+ session.dataOwnerId = 'local-v1';+ expect(claimDetectedNativeProviderAuth('openai', () => true)).toBe(true);+ unbindNativeProviderAuth('openai', { revoked: true });++ session.dataOwnerId = 'owner-a';+ expect(migrateLocalNativeProviderAuthBindings('owner-a')).toBe(false);+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({+ revoked: { openai: 'local-v1' },+ });+ expect(isNativeProviderAuthBound('openai')).toBe(false);+ });++ it('does not write for a different active owner or while the session boundary is pending', () => {+ session.dataOwnerId = 'local-v1';+ expect(claimDetectedNativeProviderAuth('openai', () => true)).toBe(true);+ session.dataOwnerId = 'owner-a';+ session.boundaryPending = true;+ expect(migrateLocalNativeProviderAuthBindings('owner-a')).toBe(false);+ session.boundaryPending = false;+ expect(migrateLocalNativeProviderAuthBindings('owner-b')).toBe(false);+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({+ openai: 'local-v1',+ });+ });});describe('claimDetectedNativeProviderAuth', () => {@@ -301,6 +705,30 @@ describe('claimDetectedNativeProviderAuth', () => {});describe('restoreNativeProviderAuthForRecovery', () => {+ it('avoids the mutation lock when recovery has no credential to restore', () => {+ fs.mkdirSync(userDataDir, { recursive: true });+ fs.writeFileSync(bindingFile, JSON.stringify({ legacyClaimOwner: 'owner-a' }));+ fs.rmSync(bindingLockDb, { force: true });++ expect(restoreNativeProviderAuthForRecovery('openai', 'owner-a', () => false)).toBe(false);+ expect(fs.existsSync(bindingLockDb)).toBe(false);+ });++ it.each([+ ['owner-a', true],+ ['owner-b', false],+ ] as const)(+ 'avoids the mutation lock when recovery finds an existing slot for %s',+ (slotOwner, expected) => {+ fs.mkdirSync(userDataDir, { recursive: true });+ fs.writeFileSync(bindingFile, JSON.stringify({ openai: slotOwner }));+ fs.rmSync(bindingLockDb, { force: true });++ expect(restoreNativeProviderAuthForRecovery('openai', 'owner-a', () => true)).toBe(expected);+ expect(fs.existsSync(bindingLockDb)).toBe(false);+ },+ );+it('restores the invalidated owner even when another owner won the legacy claim', () => {fs.mkdirSync(userDataDir, { recursive: true });fs.writeFileSync(bindingFile, JSON.stringify({ legacyClaimOwner: 'owner-a' }));diff --git a/apps/desktop/src/main/maker-host/auth-adapters.ts b/apps/desktop/src/main/maker-host/auth-adapters.tsindex 73d60631cb..747a33ad1e 100644--- a/apps/desktop/src/main/maker-host/auth-adapters.ts+++ b/apps/desktop/src/main/maker-host/auth-adapters.ts@@ -290,14 +290,37 @@ export function isCodexAuthInheritedFromSystemCli(): boolean {if (shouldSuppressLocalCodexAuth(codexHome, localAuth)) return false;const systemAuth = getSystemCodexAuthPath();if (!existsSync(localAuth) || !existsSync(systemAuth)) return false;- const localStat = fs.statSync(localAuth);- const systemStat = fs.statSync(systemAuth);- return localStat.ino === systemStat.ino && localStat.dev === systemStat.dev;+ return pathsReferToSameFileSync(localAuth, systemAuth);} catch {return false;}}+export function haveSameStableFileIdentity(+ left: { dev: bigint; ino: bigint },+ right: { dev: bigint; ino: bigint },+): boolean {+ // Windows file IDs are 64-bit. Number-valued Stats can round distinct IDs to+ // the same IEEE-754 value, while some filesystems report ino=0 when no stable+ // identity is available. Neither case is proof that two paths are hard links.+ return left.ino !== 0n && right.ino !== 0n && left.dev === right.dev && left.ino === right.ino;+}++function pathsReferToSameFileSync(left: string, right: string): boolean {+ return haveSameStableFileIdentity(+ fs.statSync(left, { bigint: true }),+ fs.statSync(right, { bigint: true }),+ );+}++async function pathsReferToSameFile(left: string, right: string): Promise<boolean> {+ const [leftStat, rightStat] = await Promise.all([+ fsp.stat(left, { bigint: true }),+ fsp.stat(right, { bigint: true }),+ ]);+ return haveSameStableFileIdentity(leftStat, rightStat);+}+/*** 检测 Cindy 当前 Codex OAuth auth.json 能够被**当场证明**的来源。*@@ -310,12 +333,8 @@ function detectCodexCredentialScope(codexHome: string): NonNullable<AuthState['cconst localAuth = path.join(codexHome, 'auth.json');if (!existsSync(localAuth)) return 'unknown';const systemAuth = getSystemCodexAuthPath();- if (existsSync(systemAuth)) {- const localStat = fs.statSync(localAuth);- const systemStat = fs.statSync(systemAuth);- if (localStat.ino === systemStat.ino && localStat.dev === systemStat.dev) {- return 'system-shared';- }+ if (existsSync(systemAuth) && pathsReferToSameFileSync(localAuth, systemAuth)) {+ return 'system-shared';}if (isNativeProviderAuthBound('openai') && isNativeProviderAuthSelfAuthorized('openai')) {return 'instance-isolated';@@ -334,9 +353,7 @@ function detectFinalizedCodexLoginCredentialScope(codexHome: string,): NonNullable<AuthState['credentialScope']> {try {- const localStat = fs.statSync(path.join(codexHome, 'auth.json'));- const systemStat = fs.statSync(getSystemCodexAuthPath());- if (localStat.ino === systemStat.ino && localStat.dev === systemStat.dev) {+ if (pathsReferToSameFileSync(path.join(codexHome, 'auth.json'), getSystemCodexAuthPath())) {return 'system-shared';}} catch {@@ -996,11 +1013,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {const isolatedSystemAuth = getSystemCodexAuthPath();try {if (existsSync(isolatedMyAuth) && existsSync(isolatedSystemAuth)) {- const [sysStat, myStat] = await Promise.all([- fsp.stat(isolatedSystemAuth),- fsp.stat(isolatedMyAuth),- ]);- if (sysStat.ino === myStat.ino && sysStat.dev === myStat.dev) {+ if (await pathsReferToSameFile(isolatedSystemAuth, isolatedMyAuth)) {await fsp.unlink(isolatedMyAuth);log.info('isolated-auth: detached shared codex auth hardlink for this sandbox');}@@ -1035,9 +1048,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {// 热路径: 已经是同 inode 直接返回if (existsSync(myAuth)) {try {- const sysStat = await fsp.stat(systemAuth);- const myStat = await fsp.stat(myAuth);- if (sysStat.ino === myStat.ino && sysStat.dev === myStat.dev) {+ if (await pathsReferToSameFile(systemAuth, myAuth)) {this.lastKnownCodexCredentialScope = 'system-shared';return;}@@ -1815,6 +1826,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {log.warn('late Codex logout intent upgrade failed to revoke provider binding', {error: err instanceof Error ? err.message : String(err),});+ throw err;}}}@@ -1947,6 +1959,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {log.warn('unbind Codex OAuth provider after disconnect failed', {error: err instanceof Error ? err.message : String(err),});+ if (activeIntent.explicitRequested) throw err;}}diff --git a/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts b/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.tsindex e557041e00..4ea3d7cc9c 100644--- a/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts+++ b/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts@@ -1,8 +1,14 @@import { app } from 'electron';+import { randomUUID } from 'node:crypto';import fs from 'node:fs';import path from 'node:path';-import { getActiveAppSession, isAppSessionBoundaryPending } from '../appSessionState.js';+import {+ getActiveAppSession,+ isAppSessionBoundaryPending,+ LOCAL_DATA_OWNER_ID,+} from '../appSessionState.js';+import { createBetterSqliteDatabase } from '../localDb/betterSqliteFactory.js';import {isConnectionSourceKind,NATIVE_PROVIDER_CONNECTION_SOURCE,@@ -10,6 +16,7 @@ import {type NativeHarnessInheritedProviderId,type NativeProviderId,} from './model-discovery/connection-source.js';+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile.js';const NATIVE_PROVIDER_IDS = ['anthropic',@@ -18,6 +25,7 @@ const NATIVE_PROVIDER_IDS = [] as const satisfies readonly NativeProviderId[];type BindingFile = Partial<Record<NativeProviderId, string>> & {legacyClaimOwner?: string;+ legacyClaimToken?: string;/*** 被**显式登出**过、且尚未重新授权的 provider(值 = 执行登出的 owner,仅供诊断)。*@@ -66,14 +74,35 @@ type BindingRead =/** 根有效、各 provider 归属可信,只有 revoked 这个字段被改坏。 */| { ok: false; reason: 'badRevoked'; bindings: Omit<BindingFile, 'revoked'> };+let nativeBindingMutationLockDepth = 0;+function readBindingsOrFail(): BindingRead {+ const file = bindingPath();let raw: string;try {- raw = fs.readFileSync(bindingPath(), 'utf8');- } catch (err) {- // 文件不存在 = 合法的首次状态(还没有任何人绑定过);其它读失败(EACCES / EIO 等)- // 说明归属不明,不能当成空。- if ((err as NodeJS.ErrnoException | null)?.code === 'ENOENT') return { ok: true, bindings: {} };+ if (nativeBindingMutationLockDepth > 0) {+ const restored = readAtomicFileSync(file);+ if (restored === null) return { ok: true, bindings: {} };+ raw = restored;+ } else {+ try {+ // The common read path has no filesystem side effects and therefore+ // stays off the synchronous SQLite writer lock.+ raw = fs.readFileSync(file, 'utf8');+ } catch (error) {+ if ((error as NodeJS.ErrnoException | null)?.code !== 'ENOENT') throw error;+ if (!fs.existsSync(`${file}.bak`)) return { ok: true, bindings: {} };+ // Restoring `<file>.bak` is a mutation. Acquire the same lock as the+ // writer and recheck inside it so a reader cannot interrupt the+ // Windows backup-exchange window.+ return withNativeBindingMutationLock<BindingRead>(+ { ok: false, reason: 'unreadable' },+ () => readBindingsOrFail(),+ );+ }+ }+ } catch {+ // EACCES / EIO / 无法恢复原子备份都说明归属不明,不能当成空。return { ok: false, reason: 'unreadable' };}try {@@ -105,10 +134,260 @@ function readBindingsOrFail(): BindingRead {function writeBindings(value: BindingFile): void {const file = bindingPath();- fs.mkdirSync(path.dirname(file), { recursive: true });- const tmp = `${file}.tmp`;- fs.writeFileSync(tmp, JSON.stringify(value, null, 2), { encoding: 'utf8', mode: 0o600 });- fs.renameSync(tmp, file);+ atomicWriteFileSync(file, JSON.stringify(value, null, 2));+ // Flush the published file on every platform. On Windows this maps to+ // FlushFileBuffers and is the durable barrier available for a renamed+ // file; POSIX additionally flushes the parent directory below.+ // Windows requires a writable handle for FlushFileBuffers. The binding file is+ // created with owner-only permissions, so r+ remains safe on POSIX while also+ // making the post-rename durability barrier work on Windows.+ const finalHandle = fs.openSync(file, 'r+');+ try {+ fs.fsyncSync(finalHandle);+ } finally {+ fs.closeSync(finalHandle);+ }+ syncParentDirectory(file);+}++const BINDING_MUTATION_LOCK_DB_SUFFIX = '.mutation-lock.db';++function syncParentDirectory(file: string): void {+ let dirHandle: number | undefined;+ try {+ dirHandle = fs.openSync(path.dirname(file), 'r');+ fs.fsyncSync(dirHandle);+ } catch (error) {+ // Windows does not support opening directories on every filesystem. The+ // final-file FlushFileBuffers above remains the fallback durability+ // barrier in that case; do not turn a successful binding commit into a+ // logout merely because directory fsync is unavailable.+ if (process.platform !== 'win32') throw error;+ } finally {+ if (dirHandle !== undefined) fs.closeSync(dirHandle);+ }+}++function withNativeBindingMutationLock<T>(+ fallback: T,+ operation: () => T,+ opts?: { throwOnLockFailure?: boolean },+): T {+ const lockDbPath = `${bindingPath()}${BINDING_MUTATION_LOCK_DB_SUFFIX}`;+ fs.mkdirSync(path.dirname(lockDbPath), { recursive: true });+ let lockDb: ReturnType<typeof createBetterSqliteDatabase> | null = null;+ try {+ lockDb = createBetterSqliteDatabase(lockDbPath);+ lockDb.pragma('busy_timeout = 30000');+ lockDb.exec(+ 'CREATE TABLE IF NOT EXISTS binding_mutation_lock (id INTEGER PRIMARY KEY CHECK (id = 1))',+ );+ lockDb.exec('BEGIN IMMEDIATE');+ } catch (error) {+ try {+ lockDb?.close();+ } catch {+ // Preserve the acquisition error; close is best effort on a failed open.+ }+ if (opts?.throwOnLockFailure) {+ throw new Error(+ `failed to acquire native provider binding mutation lock: ${+ error instanceof Error ? error.message : String(error)+ }`,+ );+ }+ return fallback;+ }+ try {+ nativeBindingMutationLockDepth += 1;+ return operation();+ } finally {+ nativeBindingMutationLockDepth -= 1;+ try {+ // The transaction exists only to hold SQLite's cross-process writer+ // lock while the JSON read-modify-write runs; no lock-db state is changed.+ lockDb.exec('ROLLBACK');+ } catch {+ // Closing the connection still releases SQLite's OS-level lock.+ }+ lockDb.close();+ }+}++function withRequiredNativeBindingMutationLock<T>(operation: () => T): T {+ return withNativeBindingMutationLock<T>(undefined as T, operation, {+ throwOnLockFailure: true,+ });+}++export type LegacyNativeProviderAuthReservation =+ 'claimed' | 'already-owned' | 'owned-by-other' | 'failed';++export interface LegacyNativeProviderAuthReservationDetails {+ status: LegacyNativeProviderAuthReservation;+ claimToken?: string;+}++export type PendingLegacyNativeProviderAuthRecovery =+ | 'none'+ | 'finalized'+ | 'released'+ | 'failed';++export type LegacyNativeProviderAuthOwnerRead =+ | { status: 'none' }+ | { status: 'owned'; ownerId: string }+ | { status: 'failed' };++/** Read a durable legacy namespace owner without creating or finalizing a claim. */+export function readLegacyNativeProviderAuthOwner(): LegacyNativeProviderAuthOwnerRead {+ const read = readBindingsOrFail();+ if (!read.ok) return { status: 'failed' };+ const bindings = read.bindings;+ if (!('legacyClaimOwner' in bindings)) return { status: 'none' };+ if ('legacyClaimToken' in bindings) return { status: 'failed' };+ const ownerId =+ typeof bindings.legacyClaimOwner === 'string' ? bindings.legacyClaimOwner.trim() : '';+ if (!ownerId || ownerId === LOCAL_DATA_OWNER_ID) return { status: 'failed' };+ return { status: 'owned', ownerId };+}++function reserveLegacyNativeProviderAuthOwnerWithMode(+ ownerId: string,+ provisional: boolean,+): LegacyNativeProviderAuthReservationDetails {+ const normalizedOwnerId = ownerId.trim();+ if (!normalizedOwnerId || normalizedOwnerId === LOCAL_DATA_OWNER_ID) {+ return { status: 'failed' };+ }+ // Stable repair and ordinary same-owner refresh both reach this helper. A+ // tokenless matching (or different) owner is a definitive no-op in either+ // mode, so avoid blocking the Electron main thread on the synchronous writer+ // lock. Missing or provisional state still enters the lock and is rechecked.+ const snapshot = readBindingsOrFail();+ if (!snapshot.ok) return { status: 'failed' };+ const bindings = snapshot.bindings;+ if ('legacyClaimOwner' in bindings) {+ if (bindings.legacyClaimOwner !== normalizedOwnerId) {+ return { status: 'owned-by-other' };+ }+ if (!('legacyClaimToken' in bindings)) {+ return { status: 'already-owned' };+ }+ }+ return withNativeBindingMutationLock<LegacyNativeProviderAuthReservationDetails>(+ { status: 'failed' },+ () => {+ try {+ const read = readBindingsOrFail();+ if (!read.ok) return { status: 'failed' };+ const bindings = read.bindings;+ if ('legacyClaimOwner' in bindings) {+ if (bindings.legacyClaimOwner !== normalizedOwnerId) {+ return { status: 'owned-by-other' };+ }+ if (!provisional && bindings.legacyClaimToken) {+ const next = { ...bindings };+ delete next.legacyClaimToken;+ writeBindings(next);+ }+ return { status: 'already-owned' };+ }+ const claimToken = provisional ? randomUUID() : undefined;+ writeBindings({+ ...bindings,+ legacyClaimOwner: normalizedOwnerId,+ ...(claimToken ? { legacyClaimToken: claimToken } : {}),+ });+ return { status: 'claimed', ...(claimToken ? { claimToken } : {}) };+ } catch {+ return { status: 'failed' };+ }+ },+ );+}++/** Reserve the one-shot native-provider namespace at the verified cloud commit edge. */+export function reserveLegacyNativeProviderAuthOwnerDetailed(+ ownerId: string,+): LegacyNativeProviderAuthReservationDetails {+ return reserveLegacyNativeProviderAuthOwnerWithMode(ownerId, true);+}++/** Reserve or finalize the namespace for an owner whose cloud session is already durable. */+export function reserveCommittedLegacyNativeProviderAuthOwner(+ ownerId: string,+): LegacyNativeProviderAuthReservation {+ return reserveLegacyNativeProviderAuthOwnerWithMode(ownerId, false).status;+}++export function reserveLegacyNativeProviderAuthOwner(+ ownerId: string,+): LegacyNativeProviderAuthReservation {+ return reserveLegacyNativeProviderAuthOwnerDetailed(ownerId).status;+}++export function releaseLegacyNativeProviderAuthOwner(ownerId: string, claimToken: string): boolean {+ const normalizedOwnerId = ownerId.trim();+ if (!normalizedOwnerId || !claimToken) return false;+ return withNativeBindingMutationLock(false, () => {+ try {+ const read = readBindingsOrFail();+ if (!read.ok) return false;+ const bindings = read.bindings;+ if (+ bindings.legacyClaimOwner !== normalizedOwnerId ||+ bindings.legacyClaimToken !== claimToken+ ) {+ return false;+ }+ const next = { ...bindings };+ delete next.legacyClaimOwner;+ delete next.legacyClaimToken;+ writeBindings(next);+ return true;+ } catch {+ return false;+ }+ });+}++/**+ * Settle a durable pre-commit legacy-namespace claim. The token belonging to+ * the currently committed cloud owner is finalized; a token for any other+ * owner is an interrupted reservation and is released. Tokenless ownership is+ * already committed and remains untouched.+ */+export function recoverPendingLegacyNativeProviderAuthOwner(+ committedOwnerId: string | null,+): PendingLegacyNativeProviderAuthRecovery {+ const normalizedCommittedOwnerId = committedOwnerId?.trim() || null;+ // A tokenless binding is already durable ownership, not pending recovery.+ // Read it without taking the synchronous writer lock so stable-owner+ // initialization cannot block the Electron main thread on a no-op.+ const snapshot = readBindingsOrFail();+ if (!snapshot.ok) return 'failed';+ if (!snapshot.bindings.legacyClaimToken) return 'none';+ return withNativeBindingMutationLock<PendingLegacyNativeProviderAuthRecovery>('failed', () => {+ try {+ const read = readBindingsOrFail();+ if (!read.ok) return 'failed';+ const bindings = read.bindings;+ if (!bindings.legacyClaimToken) return 'none';+ const next = { ...bindings };+ if (bindings.legacyClaimOwner === normalizedCommittedOwnerId) {+ delete next.legacyClaimToken;+ writeBindings(next);+ return 'finalized';+ }+ delete next.legacyClaimOwner;+ delete next.legacyClaimToken;+ writeBindings(next);+ return 'released';+ } catch {+ return 'failed';+ }+ });}/** Return true only when the native OAuth credential is explicitly bound to this owner. */@@ -138,54 +417,58 @@ export function isNativeProviderAuthRevoked(provider: NativeProviderId): booleanexport function bindNativeProviderAuth(provider: NativeProviderId): void {const owner = getActiveAppSession().dataOwnerId;if (!owner) throw new Error('cannot bind native provider auth without an active data owner');- const read = readBindingsOrFail();- if (read.ok) {- const bindings = read.bindings;- // 显式授权 = 用户重新表达了「我要连它」,撤销标记就此作废。- if (bindings.revoked && provider in bindings.revoked) {- const revoked = { ...bindings.revoked };- delete revoked[provider];- bindings.revoked = revoked;+ const written = withNativeBindingMutationLock(false, () => {+ const read = readBindingsOrFail();+ if (read.ok) {+ const bindings = read.bindings;+ // 显式授权 = 用户重新表达了「我要连它」,撤销标记就此作废。+ if (bindings.revoked && provider in bindings.revoked) {+ const revoked = { ...bindings.revoked };+ delete revoked[provider];+ bindings.revoked = revoked;+ }+ // 记下「这是用户自己在 Cindy 里授权的」——继承类文案据此不再对它成立。+ writeBindings({+ ...bindings,+ selfAuthorized: { ...bindings.selfAuthorized, [provider]: owner },+ sources: {+ ...bindings.sources,+ [provider]: 'explicit-provider-oauth',+ },+ [provider]: owner,+ });+ return true;+ }+ // 归属信息有损:用户正在显式授权,不写等于让他连不上,所以必须写;但写法要保守。+ //+ // · badRevoked —— 各 provider 的归属仍然可信,原样保留。直接重写成「只有本次授权的这+ // 一家」会抹掉别人的 owner,那份凭证下一次就被自动认领给当前账号,等于用一次修复换+ // 来一个新的越权口子。+ // · unreadable —— 连 legacyClaimOwner 带各家 owner 一起没了,无可保留;同样不能就这么+ // 写一份「只有我」的干净文件,那会让其余 provider 的残留凭证在文件恢复可读后立刻可被+ // 认领(PR #548 review)。+ //+ // 两种情形共用同一条保守收尾:凡是归属无从确认的 provider,一律按「撤销过」对待,自动继承+ // 就此关闭 —— 无从得知谁被撤销过时,丢弃标记等于给所有残留凭证放行。用户对它们各自显式+ // 授权即可恢复。+ const salvaged = read.reason === 'badRevoked' ? read.bindings : {};+ const suppressed: Partial<Record<NativeProviderId, string>> = {};+ for (const other of NATIVE_PROVIDER_IDS) {+ if (other !== provider) suppressed[other] = owner;}- // 记下「这是用户自己在 Cindy 里授权的」——继承类文案据此不再对它成立。writeBindings({- ...bindings,- selfAuthorized: { ...bindings.selfAuthorized, [provider]: owner },+ ...salvaged,+ revoked: suppressed,+ selfAuthorized: { ...salvaged.selfAuthorized, [provider]: owner },sources: {- ...bindings.sources,+ ...salvaged.sources,[provider]: 'explicit-provider-oauth',},[provider]: owner,});- return;- }- // 归属信息有损:用户正在显式授权,不写等于让他连不上,所以必须写;但写法要保守。- //- // · badRevoked —— 各 provider 的归属仍然可信,原样保留。直接重写成「只有本次授权的这- // 一家」会抹掉别人的 owner,那份凭证下一次就被自动认领给当前账号,等于用一次修复换- // 来一个新的越权口子。- // · unreadable —— 连 legacyClaimOwner 带各家 owner 一起没了,无可保留;同样不能就这么- // 写一份「只有我」的干净文件,那会让其余 provider 的残留凭证在文件恢复可读后立刻可被- // 认领(PR #548 review)。- //- // 两种情形共用同一条保守收尾:凡是归属无从确认的 provider,一律按「撤销过」对待,自动继承- // 就此关闭 —— 无从得知谁被撤销过时,丢弃标记等于给所有残留凭证放行。用户对它们各自显式- // 授权即可恢复。- const salvaged = read.reason === 'badRevoked' ? read.bindings : {};- const suppressed: Partial<Record<NativeProviderId, string>> = {};- for (const other of NATIVE_PROVIDER_IDS) {- if (other !== provider) suppressed[other] = owner;- }- writeBindings({- ...salvaged,- revoked: suppressed,- selfAuthorized: { ...salvaged.selfAuthorized, [provider]: owner },- sources: {- ...salvaged.sources,- [provider]: 'explicit-provider-oauth',- },- [provider]: owner,+ return true;});+ if (!written) throw new Error('cannot acquire native provider binding lease');}/**@@ -234,28 +517,43 @@ export function unbindNativeProviderAuth(// 不写也是安全的:文件读不出来时 isNativeProviderAuthBound 已经一律 false(用户看到的就是// 未连接),claimDetectedNativeProviderAuth 也已在同一条件下拒绝认领 —— 撤销标记要挡的那// 件事,此刻本来就发生不了。凭证删除在调用方,不受这里影响。- const read = readBindingsOrFail();- if (!read.ok) return;- const bindings = read.bindings;- const owner = getActiveAppSession().dataOwnerId;- const marking = opts?.revoked === true && !!owner;- const hadSelfAuthorized = bindings.selfAuthorized?.[provider] !== undefined;- if (!(provider in bindings) && !marking && !hadSelfAuthorized) return;- delete bindings[provider];- // 授权来路随绑定一起作废:登出之后这份凭证若还在本机,它对 Cindy 就重新是「外部已有的- // 凭证」,继承语义(及其文案)重新成立。- if (hadSelfAuthorized) {- const selfAuthorized = { ...bindings.selfAuthorized };- delete selfAuthorized[provider];- bindings.selfAuthorized = selfAuthorized;- }- if (bindings.sources?.[provider] !== undefined) {- const sources = { ...bindings.sources };- delete sources[provider];- bindings.sources = sources;+ // 服务端失效会先做一次 early-unbind,随后 runLogout 再无 revoked 地收口。第二次若+ // snapshot 已证明 slot、来路字段都不存在,就是确定性 no-op,不要在 Electron main+ // thread 上同步等待跨进程 writer lock。显式登出仍必须进锁并持久化 revoked。+ if (opts?.revoked !== true) {+ const snapshot = readBindingsOrFail();+ if (snapshot.ok) {+ const bindings = snapshot.bindings;+ const hasSelfAuthorized = bindings.selfAuthorized?.[provider] !== undefined;+ const hasSource = bindings.sources?.[provider] !== undefined;+ if (!(provider in bindings) && !hasSelfAuthorized && !hasSource) return;+ }}- if (marking) bindings.revoked = { ...(bindings.revoked ?? {}), [provider]: owner as string };- writeBindings(bindings);+ withRequiredNativeBindingMutationLock(() => {+ const read = readBindingsOrFail();+ if (!read.ok) return;+ const bindings = read.bindings;+ const owner = getActiveAppSession().dataOwnerId;+ const marking = opts?.revoked === true && !!owner;+ const hadSelfAuthorized = bindings.selfAuthorized?.[provider] !== undefined;+ const hadSource = bindings.sources?.[provider] !== undefined;+ if (!(provider in bindings) && !marking && !hadSelfAuthorized && !hadSource) return;+ delete bindings[provider];+ // 授权来路随绑定一起作废:登出之后这份凭证若还在本机,它对 Cindy 就重新是「外部已有的+ // 凭证」,继承语义(及其文案)重新成立。+ if (hadSelfAuthorized) {+ const selfAuthorized = { ...bindings.selfAuthorized };+ delete selfAuthorized[provider];+ bindings.selfAuthorized = selfAuthorized;+ }+ if (hadSource) {+ const sources = { ...bindings.sources };+ delete sources[provider];+ bindings.sources = sources;+ }+ if (marking) bindings.revoked = { ...(bindings.revoked ?? {}), [provider]: owner as string };+ writeBindings(bindings);+ });}/**@@ -269,29 +567,128 @@ export function migrateLegacyNativeProviderAuthBindings(): void {// 同 claimDetectedNativeProviderAuth:一次性迁移也是写路径,归属读不出来就不能推进// (还会把 legacyClaimOwner 名额一起消费掉,损失不可逆)。- const read = readBindingsOrFail();- if (!read.ok) return;- const bindings = read.bindings;- if (bindings.legacyClaimOwner) return;-- const next: BindingFile = { ...bindings, legacyClaimOwner: ownerId };- for (const provider of NATIVE_PROVIDER_IDS) {- // 显式登出过的 provider 一律跳过:这条一次性迁移同样不能把用户弃用掉的残留凭证- // 认领回来(PR #548 review)。- if (bindings.revoked && provider in bindings.revoked) continue;- if (available[provider] && !next[provider]) {- next[provider] = ownerId;- next.sources = {- ...next.sources,- [provider]: NATIVE_PROVIDER_CONNECTION_SOURCE[provider],- };- // xAI 的旧 safeStorage blob 也是 Cindy 自己完成的 OAuth,不是本机 CLI 继承。- if (provider === 'xai') {- next.selfAuthorized = { ...next.selfAuthorized, xai: ownerId };+ const snapshot = readBindingsOrFail();+ if (!snapshot.ok) return;+ if (!needsLegacyNativeProviderAuthMigration(snapshot.bindings, ownerId, available)) return;++ withNativeBindingMutationLock(undefined, () => {+ const read = readBindingsOrFail();+ if (!read.ok) return;+ const bindings = read.bindings;+ if ('legacyClaimOwner' in bindings && bindings.legacyClaimOwner !== ownerId) return;++ const next: BindingFile = { ...bindings };+ let changed = false;+ if (!('legacyClaimOwner' in bindings)) {+ next.legacyClaimOwner = ownerId;+ changed = true;+ }+ for (const provider of NATIVE_PROVIDER_IDS) {+ // 显式登出过的 provider 一律跳过:这条一次性迁移同样不能把用户弃用掉的残留凭证+ // 认领回来(PR #548 review)。+ if (bindings.revoked && provider in bindings.revoked) continue;+ if (available[provider] && !(provider in bindings)) {+ next[provider] = ownerId;+ changed = true;+ next.sources = {+ ...next.sources,+ [provider]: NATIVE_PROVIDER_CONNECTION_SOURCE[provider],+ };+ // xAI 的旧 safeStorage blob 也是 Cindy 自己完成的 OAuth,不是本机 CLI 继承。+ if (provider === 'xai') {+ next.selfAuthorized = { ...next.selfAuthorized, xai: ownerId };+ }}}+ if (changed) writeBindings(next);+ });+}++function needsLegacyNativeProviderAuthMigration(+ bindings: BindingFile,+ ownerId: string,+ available: Partial<Record<NativeProviderId, boolean>>,+): boolean {+ if ('legacyClaimOwner' in bindings) {+ if (bindings.legacyClaimOwner !== ownerId) return false;+ } else {+ return true;}- writeBindings(next);+ return NATIVE_PROVIDER_IDS.some(+ (provider) =>+ !(bindings.revoked && provider in bindings.revoked) &&+ available[provider] === true &&+ !(provider in bindings),+ );+}++/**+ * Move native Harness credentials that were claimed by the account-free local+ * session to the first verified cloud owner.+ *+ * Local mode uses a stable synthetic owner (`local-v1`) so provider reads can+ * still be owner-scoped before login. Once a real Cindy account is verified,+ * those same machine-level Claude/Codex credentials must follow that first+ * cloud owner; otherwise the normal owner equality check correctly (but+ * unexpectedly) hides them after login. This path is intentionally narrower+ * than a generic claim: it only rewrites slots explicitly owned by local-v1,+ * and an existing legacy claim owned by another account remains fail-closed.+ */+export function migrateLocalNativeProviderAuthBindings(ownerId: string): boolean {+ const normalizedOwnerId = ownerId.trim();+ if (!normalizedOwnerId || normalizedOwnerId === LOCAL_DATA_OWNER_ID) return false;+ if (getActiveAppSession().dataOwnerId !== normalizedOwnerId) return false;+ // This helper is called after the durable cloud commit. Keep the same floor+ // as other binding writers for callers that accidentally invoke it during a+ // different owner transition.+ if (isAppSessionBoundaryPending()) return false;++ // Stable-owner initialization commonly reaches this helper from ordinary+ // renderer setup. If the snapshot proves that no local-v1 slot can move and+ // the one-shot namespace is already owned, avoid waiting on the synchronous+ // writer lock; the locked path below still rechecks before any write.+ const snapshot = readBindingsOrFail();+ if (!snapshot.ok) return false;+ const snapshotBindings = snapshot.bindings;+ if (+ snapshotBindings.legacyClaimOwner === normalizedOwnerId &&+ !(['anthropic', 'openai'] as const).some(+ (provider) =>+ !(snapshotBindings.revoked && provider in snapshotBindings.revoked) &&+ snapshotBindings[provider] === LOCAL_DATA_OWNER_ID,+ )+ ) {+ return false;+ }++ return withNativeBindingMutationLock(false, () => {+ const read = readBindingsOrFail();+ if (!read.ok) return false;+ const bindings = read.bindings;++ // A prior cloud owner winning the legacy claim is authoritative. Do not let+ // a later account inherit any local residue that was not moved at the time.+ if ('legacyClaimOwner' in bindings && bindings.legacyClaimOwner !== normalizedOwnerId) {+ return false;+ }++ const next: BindingFile = { ...bindings };+ let migrated = false;+ for (const provider of ['anthropic', 'openai'] as const) {+ if (bindings.revoked && provider in bindings.revoked) continue;+ if (bindings[provider] !== LOCAL_DATA_OWNER_ID) continue;+ next[provider] = normalizedOwnerId;+ migrated = true;+ }++ // Reserve the one-shot legacy claim for this first cloud owner. This also+ // prevents a later account from claiming another local credential that+ // appears after the initial login.+ if (!('legacyClaimOwner' in next)) next.legacyClaimOwner = normalizedOwnerId;+ if (!migrated && 'legacyClaimOwner' in bindings) return false;+ writeBindings(next);+ return migrated;+ });}/**@@ -326,27 +723,40 @@ export function claimDetectedNativeProviderAuth(// Callers reached from an async settle (Codex reconcile) additionally pin an// owner+generation snapshot; this guard is the floor every caller gets.if (isAppSessionBoundaryPending()) return false;- // 归属文件读不出来 = 归属不明,一律不认领:这条路径是**写**路径,把损坏当空会把共享- // keychain 里可能属于别人的凭证判给当前账号,并覆盖掉原有归属(PR #548 review)。- const read = readBindingsOrFail();- if (!read.ok) return false;- const bindings = read.bindings;- // Key-presence, not truthiness: a corrupted/empty-string slot must count as- // "claimed by unknown" and fail closed, never as re-claimable (matches- // unbindNativeProviderAuth's `in` pattern).- if (provider in bindings) return false;- if ('legacyClaimOwner' in bindings && bindings.legacyClaimOwner !== owner) return false;- // 被显式登出过就绝不自动认领,且**不比对 owner**:凭证在共享的系统 keychain / CLI 里,- // 换个账号它仍是登出那个账号的凭证 —— 按 owner 比对等于给下一个账号开了继承别人凭证- // 的口子。解除只有「用户再次显式授权」一条路(PR #548 review)。- if (bindings.revoked && provider in bindings.revoked) return false;+ const snapshot = readBindingsOrFail();+ if (!snapshot.ok) return false;+ if (provider in snapshot.bindings) return false;+ if (+ ('legacyClaimOwner' in snapshot.bindings && snapshot.bindings.legacyClaimOwner !== owner) ||+ (snapshot.bindings.revoked && provider in snapshot.bindings.revoked)+ ) {+ return false;+ }if (!hasCredential()) return false;- writeBindings({- ...bindings,- sources: { ...bindings.sources, [provider]: 'native-harness-inherited' },- [provider]: owner,++ return withNativeBindingMutationLock(false, () => {+ // 归属文件读不出来 = 归属不明,一律不认领:这条路径是**写**路径,把损坏当空会把共享+ // keychain 里可能属于别人的凭证判给当前账号,并覆盖掉原有归属(PR #548 review)。+ const read = readBindingsOrFail();+ if (!read.ok) return false;+ const bindings = read.bindings;+ // Key-presence, not truthiness: a corrupted/empty-string slot must count as+ // "claimed by unknown" and fail closed, never as re-claimable (matches+ // unbindNativeProviderAuth's `in` pattern).+ if (provider in bindings) return false;+ if ('legacyClaimOwner' in bindings && bindings.legacyClaimOwner !== owner) return false;+ // 被显式登出过就绝不自动认领,且**不比对 owner**:凭证在共享的系统 keychain / CLI 里,+ // 换个账号它仍是登出那个账号的凭证 —— 按 owner 比对等于给下一个账号开了继承别人凭证+ // 的口子。解除只有「用户再次显式授权」一条路(PR #548 review)。+ if (bindings.revoked && provider in bindings.revoked) return false;+ if (!hasCredential()) return false;+ writeBindings({+ ...bindings,+ sources: { ...bindings.sources, [provider]: 'native-harness-inherited' },+ [provider]: owner,+ });+ return true;});- return true;}/**@@ -362,16 +772,29 @@ export function restoreNativeProviderAuthForRecovery(): boolean {const owner = getActiveAppSession().dataOwnerId;if (!owner || owner !== expectedOwner || isAppSessionBoundaryPending()) return false;- const read = readBindingsOrFail();- if (!read.ok) return false;- const bindings = read.bindings;- if (bindings.revoked && provider in bindings.revoked) return false;+ // Recovery runs on the Electron main thread after Codex reconciliation. Avoid+ // synchronously waiting on the cross-process writer lock when a read-only+ // snapshot already proves that no write is needed. Any potentially writable+ // state is still rechecked under the lock below.+ const snapshot = readBindingsOrFail();+ if (!snapshot.ok) return false;+ const snapshotBindings = snapshot.bindings;+ if (snapshotBindings.revoked && provider in snapshotBindings.revoked) return false;if (!hasCredential()) return false;- if (provider in bindings) return bindings[provider] === expectedOwner;- writeBindings({- ...bindings,- sources: { ...bindings.sources, [provider]: 'native-harness-inherited' },- [provider]: expectedOwner,+ if (provider in snapshotBindings) return snapshotBindings[provider] === expectedOwner;++ return withNativeBindingMutationLock(false, () => {+ const read = readBindingsOrFail();+ if (!read.ok) return false;+ const bindings = read.bindings;+ if (bindings.revoked && provider in bindings.revoked) return false;+ if (!hasCredential()) return false;+ if (provider in bindings) return bindings[provider] === expectedOwner;+ writeBindings({+ ...bindings,+ sources: { ...bindings.sources, [provider]: 'native-harness-inherited' },+ [provider]: expectedOwner,+ });+ return true;});- return true;}diff --git a/apps/desktop/src/main/ownerNamespaceMigration.ts b/apps/desktop/src/main/ownerNamespaceMigration.tsindex 11d295b439..831e2e52db 100644--- a/apps/desktop/src/main/ownerNamespaceMigration.ts+++ b/apps/desktop/src/main/ownerNamespaceMigration.ts@@ -24,6 +24,7 @@ import {readBoundedFileNoFollow,readBoundedFileNoFollowSync,} from './utils/readBoundedFile.js';+import { readAtomicFileSync } from './utils/atomicWriteFile.js';const CLAIM_MARKER = '.owner-namespace-claim-v1.json';const LEGACY_GHOST_RECOVERY_MARKER = '.legacy-ghost-recovery-v1.json';@@ -112,6 +113,13 @@ interface RegisteredInstanceRecord {rootDir?: string;}+interface RegisteredInstanceCandidate {+ pid: number;+ userDataDir: string | undefined;+ recordedAtMs: number | undefined;+ rootDir: string | undefined;+}+interface ProcessIdentitySnapshot {startedAtMs: number;command: string;@@ -581,38 +589,40 @@ function hasConcurrentLiveInstanceSync(recordedAtMs: number | undefined;rootDir: string | undefined;}> = [];- for (const name of names) {- if (!name.endsWith('.json')) continue;+ const recordNames = new Set(+ names.flatMap((name) => {+ if (name.endsWith('.json')) return [name];+ if (name.endsWith('.json.bak')) return [name.slice(0, -'.bak'.length)];+ return [];+ }),+ );+ for (const name of recordNames) {let raw: string;try {- raw = fsSync.readFileSync(path.join(registryDir, name), 'utf-8');+ const restored = readAtomicFileSync(path.join(registryDir, name));+ if (restored === null) continue;+ raw = restored;} catch (error) {+ // A backup that cannot be restored may still be the only live-process+ // record. Fail closed rather than treating the instance as gone.if (isMissing(error)) continue;return true;}- let record: RegisteredInstanceRecord;- try {- record = JSON.parse(raw) as RegisteredInstanceRecord;- } catch {- continue; // torn leftover- }- const pid = record.pid;- if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0 || pid === selfPid) {- continue;- }+ const candidate = parseRegisteredInstanceCandidate(raw, name);+ if (candidate === null || candidate.pid === selfPid) continue;if (- typeof record.userDataDir === 'string' &&- !isSameUserDataDir(record.userDataDir, userDataDir, process.platform)+ candidate.userDataDir !== undefined &&+ !isSameUserDataDir(candidate.userDataDir, userDataDir, process.platform)) {continue;}- if (!isPidAlive(pid)) continue;+ if (!isPidAlive(candidate.pid)) continue;candidates.push({raw,fileName: name,- pid,- recordedAtMs: record.startedAtMs,- rootDir: record.rootDir,+ pid: candidate.pid,+ recordedAtMs: candidate.recordedAtMs,+ rootDir: candidate.rootDir,});}if (readProcessIdentity) {@@ -2424,6 +2434,49 @@ function isSameUserDataDir(a: string, b: string, platform: NodeJS.Platform): boo: ra === rb;}+function instancePidFromRecordName(name: string): number | null {+ const match = /^(\d+)\.json$/.exec(name);+ if (!match) return null;+ const pid = Number(match[1]);+ return Number.isSafeInteger(pid) && pid > 0 ? pid : null;+}++function parseRegisteredInstanceCandidate(+ raw: string,+ fileName: string,+): RegisteredInstanceCandidate | null {+ const filePid = instancePidFromRecordName(fileName);+ try {+ const parsed = JSON.parse(raw) as unknown;+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {+ const record = parsed as RegisteredInstanceRecord;+ if (typeof record.pid === 'number' && Number.isInteger(record.pid) && record.pid > 0) {+ if (filePid !== null && record.pid !== filePid) {+ return {+ pid: filePid,+ userDataDir: undefined,+ recordedAtMs: undefined,+ rootDir: undefined,+ };+ }+ return {+ pid: record.pid,+ userDataDir: typeof record.userDataDir === 'string' ? record.userDataDir : undefined,+ recordedAtMs:+ typeof record.startedAtMs === 'number' ? record.startedAtMs : undefined,+ rootDir: typeof record.rootDir === 'string' ? record.rootDir : undefined,+ };+ }+ }+ } catch {+ // A torn payload still has a process identity in its canonical filename.+ }++ return filePid === null+ ? null+ : { pid: filePid, userDataDir: undefined, recordedAtMs: undefined, rootDir: undefined };+}+/*** Other live Cindy instances sharing this userData, discovered via the* `.dev-instances/<pid>.json` runtime provenance registry (devStartupStatus;@@ -2435,9 +2488,10 @@ function isSameUserDataDir(a: string, b: string, platform: NodeJS.Platform): boo* Error posture is asymmetric on purpose: a record file that VANISHES* (ENOENT) means that instance exited — skip it; a record file that exists* but cannot be READ (EACCES, I/O errors) may hide a live instance — fail- * closed by rethrowing so the caller defers the destructive claim. Only a- * record that reads fine but fails to PARSE is treated as a torn leftover- * (writes are atomic rename, so torn content cannot be a live registration).+ * closed by rethrowing so the caller defers the destructive claim. If a+ * record reads but has an invalid or mismatched payload, its `<pid>.json`+ * filename still keeps a live process visible; dead-PID leftovers remain+ * safely ignorable.*/async function findConcurrentLiveInstancePids(deps: MigrationDeps,@@ -2459,39 +2513,49 @@ async function findConcurrentLiveInstancePids(recordedAtMs: number | undefined;rootDir: string | undefined;}> = [];- for (const name of names) {- if (!name.endsWith('.json')) continue;- let raw: string;- try {- raw = await deps.readFile(path.join(registryDir, name));- } catch (error) {- if (isMissing(error)) continue;- throw error;- }- let record: RegisteredInstanceRecord;- try {- record = JSON.parse(raw) as RegisteredInstanceRecord;- } catch {- continue; // torn leftover, never a live registration- }- const pid = record.pid;- if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0 || pid === selfPid) {- continue;+ const recordNames = new Set(+ names.flatMap((name) => {+ if (name.endsWith('.json')) return [name];+ if (name.endsWith('.json.bak')) return [name.slice(0, -'.bak'.length)];+ return [];+ }),+ );+ for (const name of recordNames) {+ const recordPath = path.join(registryDir, name);+ let raw: string | null = null;+ for (let attempt = 0; attempt < 2 && raw === null; attempt += 1) {+ try {+ raw = await deps.readFile(recordPath);+ } catch (error) {+ if (!isMissing(error)) throw error;+ // During atomic backup exchange the canonical record may be absent+ // while `<pid>.json.bak` is the only snapshot. If the writer finishes+ // and removes the backup before this read, retry canonical once before+ // deciding that the instance exited.+ try {+ raw = await deps.readFile(`${recordPath}.bak`);+ } catch (backupError) {+ if (!isMissing(backupError)) throw backupError;+ }+ }}+ if (raw === null) continue;+ const candidate = parseRegisteredInstanceCandidate(raw, name);+ if (candidate === null || candidate.pid === selfPid) continue;// 只认同一 userData 的记录;userDataDir 不一致说明是异常拷贝进来的残留。if (- typeof record.userDataDir === 'string' &&- !isSameUserDataDir(record.userDataDir, userDataDir, process.platform)+ candidate.userDataDir !== undefined &&+ !isSameUserDataDir(candidate.userDataDir, userDataDir, process.platform)) {continue;}- if (!deps.isPidAlive(pid)) continue;+ if (!deps.isPidAlive(candidate.pid)) continue;candidates.push({raw,fileName: name,- pid,- recordedAtMs: record.startedAtMs,- rootDir: record.rootDir,+ pid: candidate.pid,+ recordedAtMs: candidate.recordedAtMs,+ rootDir: candidate.rootDir,});}diff --git a/apps/desktop/src/main/windowsPackagedInstanceBarrier.ts b/apps/desktop/src/main/windowsPackagedInstanceBarrier.tsnew file mode 100644index 0000000000..5a36b02ce2--- /dev/null+++ b/apps/desktop/src/main/windowsPackagedInstanceBarrier.ts@@ -0,0 +1,267 @@+import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';++const DEFAULT_ACQUIRE_TIMEOUT_MS = 5_000;+const HELPER_EXIT_TIMEOUT_MS = 2_000;+const MAX_HELPER_OUTPUT_BYTES = 16 * 1024;++const WINDOWS_PACKAGED_INSTANCE_BARRIER_SCRIPT = String.raw`+$ErrorActionPreference = 'Stop'+Add-Type -TypeDefinition @'+using System;+using System.Runtime.InteropServices;++public static class CindyProcessSingletonProbe {+ [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]+ public static extern IntPtr FindWindowEx(+ IntPtr parent,+ IntPtr childAfter,+ string className,+ string windowName+ );++ [DllImport("user32.dll", SetLastError = true)]+ public static extern uint GetWindowThreadProcessId(IntPtr window, out uint processId);+}+'@++$mutex = [System.Threading.Mutex]::new($false, $env:CINDY_SINGLETON_MUTEX_NAME)+$acquired = $false+try {+ try {+ $acquired = $mutex.WaitOne([int]$env:CINDY_SINGLETON_WAIT_MS)+ } catch [System.Threading.AbandonedMutexException] {+ $acquired = $true+ }+ if (-not $acquired) {+ [Console]::Out.WriteLine('{"status":"busy"}')+ [Console]::Out.Flush()+ exit 2+ }++ $messageOnlyWindow = [IntPtr]::new(-3)+ $window = [CindyProcessSingletonProbe]::FindWindowEx(+ $messageOnlyWindow,+ [IntPtr]::Zero,+ $env:CINDY_SINGLETON_WINDOW_CLASS,+ $env:CINDY_SINGLETON_WINDOW_TITLE+ )+ if ($window -ne [IntPtr]::Zero) {+ [uint32]$ownerPid = 0+ [void][CindyProcessSingletonProbe]::GetWindowThreadProcessId($window, [ref]$ownerPid)+ if ($ownerPid -ne [uint32]$env:CINDY_SINGLETON_SELF_PID) {+ [Console]::Out.WriteLine((@{ status = 'occupied'; pid = $ownerPid } | ConvertTo-Json -Compress))+ [Console]::Out.Flush()+ exit 3+ }+ }++ [Console]::Out.WriteLine('{"status":"acquired"}')+ [Console]::Out.Flush()+ [void][Console]::In.ReadLine()+} finally {+ if ($acquired) {+ try { [void]$mutex.ReleaseMutex() } catch {}+ }+ $mutex.Dispose()+}+`;++type BarrierStatus =+ { status: 'acquired' } | { status: 'busy' } | { status: 'occupied'; pid: number };++function processSingletonNames(programName: string): {+ mutexName: string;+ windowClass: string;+} {+ return {+ // Electron makes only the startup mutex program-specific. Chromium's+ // message-only window class remains the shared Chrome constant; the+ // userData path in the window title selects this app instance.+ mutexName: `Local\\${programName}ProcessSingletonStartup`,+ windowClass: 'Chrome_MessageWindow',+ };+}++export interface WindowsPackagedInstanceBarrierLease {+ /** False if the helper exited unexpectedly and no longer owns the startup mutex. */+ isHeld(): boolean;+ /** Idempotent; always releases or terminates the helper within a bounded interval. */+ release(): Promise<void>;+}++function powershellPath(): string {+ return `${process.env.SystemRoot ?? 'C:\\Windows'}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;+}++function waitForFirstLine(+ child: ChildProcessWithoutNullStreams,+ timeoutMs: number,+): Promise<{ line: string; stderr: string }> {+ return new Promise((resolve, reject) => {+ let stdout = '';+ let stderr = '';+ let settled = false;+ const finish = (settle: () => void): void => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ child.stdout.off('data', onStdout);+ child.stderr.off('data', onStderr);+ child.off('error', onError);+ child.off('exit', onExit);+ settle();+ };+ const timer = setTimeout(() => {+ finish(() => reject(new Error('timed out acquiring Windows packaged-instance barrier')));+ child.kill();+ }, timeoutMs + 1_000);+ const onStdout = (chunk: Buffer | string): void => {+ stdout += chunk.toString();+ if (stdout.length > MAX_HELPER_OUTPUT_BYTES) {+ finish(() =>+ reject(new Error('Windows packaged-instance barrier emitted too much output')),+ );+ child.kill();+ return;+ }+ const newline = stdout.indexOf('\n');+ if (newline >= 0) {+ const line = stdout.slice(0, newline).trim();+ finish(() => resolve({ line, stderr }));+ }+ };+ const onStderr = (chunk: Buffer | string): void => {+ if (stderr.length < MAX_HELPER_OUTPUT_BYTES) stderr += chunk.toString();+ };+ const onError = (error: Error): void => finish(() => reject(error));+ const onExit = (code: number | null): void =>+ finish(() =>+ reject(+ new Error(+ `Windows packaged-instance barrier exited before readiness (code=${String(code)})${+ stderr.trim() ? `: ${stderr.trim()}` : ''+ }`,+ ),+ ),+ );++ child.stdout.on('data', onStdout);+ child.stderr.on('data', onStderr);+ child.once('error', onError);+ child.once('exit', onExit);+ });+}++function parseBarrierStatus(line: string): BarrierStatus {+ const value = JSON.parse(line) as Partial<BarrierStatus>;+ if (value.status === 'acquired' || value.status === 'busy') return { status: value.status };+ if (+ value.status === 'occupied' &&+ typeof value.pid === 'number' &&+ Number.isInteger(value.pid) &&+ value.pid > 0+ ) {+ return { status: 'occupied', pid: value.pid };+ }+ throw new Error('Windows packaged-instance barrier returned an invalid status');+}++function waitForExit(child: ChildProcessWithoutNullStreams): Promise<void> {+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve();+ return new Promise((resolve) => {+ let settled = false;+ const finish = (): void => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ child.off('exit', finish);+ resolve();+ };+ const timer = setTimeout(() => {+ child.kill();+ finish();+ }, HELPER_EXIT_TIMEOUT_MS);+ child.once('exit', finish);+ });+}++/**+ * Hold Chromium/Electron's packaged-process startup mutex while local-v1 is+ * snapshotted and published. The helper also probes the packaged singleton's+ * message-only window under that mutex, which is the only durable signal left+ * by Windows builds predating `.dev-instances` registration.+ *+ * The mutex closes the scan-to-publication race: an older packaged Cindy that+ * starts after the probe cannot finish ProcessSingleton setup until release.+ * Missing PowerShell, P/Invoke failures, a busy mutex, or malformed output all+ * reject so first-login adoption remains fail-closed.+ */+export async function acquireWindowsPackagedInstanceBarrier(options: {+ userDataDir: string;+ programName: string;+ selfPid?: number;+ timeoutMs?: number;+}): Promise<WindowsPackagedInstanceBarrierLease> {+ const timeoutMs = options.timeoutMs ?? DEFAULT_ACQUIRE_TIMEOUT_MS;+ const singletonNames = processSingletonNames(options.programName);+ const child = spawn(+ powershellPath(),+ ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_PACKAGED_INSTANCE_BARRIER_SCRIPT],+ {+ env: {+ ...process.env,+ CINDY_SINGLETON_MUTEX_NAME: singletonNames.mutexName,+ CINDY_SINGLETON_WINDOW_CLASS: singletonNames.windowClass,+ CINDY_SINGLETON_WINDOW_TITLE: options.userDataDir,+ CINDY_SINGLETON_SELF_PID: String(options.selfPid ?? process.pid),+ CINDY_SINGLETON_WAIT_MS: String(timeoutMs),+ },+ stdio: ['pipe', 'pipe', 'pipe'],+ windowsHide: true,+ },+ );+ let status: BarrierStatus;+ try {+ const { line } = await waitForFirstLine(child, timeoutMs);+ status = parseBarrierStatus(line);+ } catch (error) {+ child.kill();+ await waitForExit(child);+ throw error;+ }+ if (status.status !== 'acquired') {+ await waitForExit(child);+ if (status.status === 'occupied') {+ throw new Error(+ `local profile database adoption deferred: legacy packaged instance ${status.pid} is using shared userData`,+ );+ }+ throw new Error('local profile database adoption deferred: packaged startup barrier is busy');+ }++ let held = child.exitCode === null && child.signalCode === null;+ let released = false;+ child.once('exit', () => {+ held = false;+ });+ return {+ isHeld: () => held,+ release: async () => {+ if (released) return;+ released = true;+ held = false;+ try {+ child.stdin.end('\n');+ } catch {+ child.kill();+ }+ await waitForExit(child);+ },+ };+}++export const __testing = {+ WINDOWS_PACKAGED_INSTANCE_BARRIER_SCRIPT,+ parseBarrierStatus,+ processSingletonNames,+};diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.tsindex 951128abf3..909f885324 100644--- a/packages/device-link/src/__tests__/client.test.ts+++ b/packages/device-link/src/__tests__/client.test.ts@@ -5777,17 +5777,23 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {await relay.settleUntil(() => host.getStatus() === 'online' && controller.getStatus() === 'online');relay.dropNext((senderId, env) => senderId === 'desktop' && env.kind === 'link-accept');- const staleOpenError = controller.openLink('desktop', {+ const staleOpen = controller.openLink('desktop', {controllerName: 'iPhone',protocolVersion: 1,appVersion: '1',- }, 50).catch((error: unknown) => error);+ }, 50);+ // Attach the rejection handler before yielding to the relay/timer. On+ // Windows the short timeout can fire before the later assertion, which+ // turns the expected rejection into an unhandled-rejection failure.+ const staleOpenRejection = expect(staleOpen).rejects.toMatchObject({+ code: 'INVOKE_TIMEOUT',+ });await relay.settle();const staleRequestId = (relay.deliveredTo.get('desktop') ?? []).filter((env) => env.kind === 'link-open').at(-1)?.id;expect(staleRequestId).toBeTruthy();- expect(await staleOpenError).toMatchObject({ code: 'INVOKE_TIMEOUT' });+ await staleOpenRejection;const liveInvoke = host.invoke('ios', {channel: 'maker:cross-generation-request',