Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(sharing): abort account handover when closure journaling fails
DavidShen1c0a5aa2116a
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 7d5ea6a3ae..fa8e04582b 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -587,6 +587,7 @@ import {handleDeviceLinkSystemResume,} from './device-link';import { closeSharedTasksBeforeLogout } from './device-link/sharedTaskRuntime.js';+import { closeSharedTasksBeforeAccountHandover } from './device-link/sharedTaskAccountBoundary.js';import { registerSharedTaskIpc } from './device-link/sharedTaskIpc.js';import {getUpdateRelaunchControllers,@@ -2048,15 +2049,14 @@ async function teardownAuthAccountBoundary(reason: string): Promise<void> {// device-link 单持有者仲裁:必须在 dispose DbClient **之前**释放持有权行// (dispose 同步 clearCurrentDbClient,之后 store 不可用,只能等 15s+ 心跳// 过期,同机幸存实例接管变慢)。内部带 1.5s 超时,不会卡住登出。- try {- await closeSharedTasksBeforeLogout();- await releaseDeviceLinkOwnershipBeforeLogout();- } catch (err) {- authBoundaryLog.error(- `[bootstrap-electron] release device-link ownership on ${reason} failed (non-fatal):`,- err,- );- }+ await closeSharedTasksBeforeAccountHandover({+ closeSharedTasks: closeSharedTasksBeforeLogout,+ releaseOwnership: releaseDeviceLinkOwnershipBeforeLogout,+ onClosureFailure: () => markAccountBoundaryAbortedMidTeardown(reason),+ onReleaseFailure: (err) => authBoundaryLog.error(+ `[bootstrap-electron] release device-link ownership on ${reason} failed (non-fatal):`, err,+ ),+ });await lifecycleDbClientManager.dispose(reason);} finally {releaseEndedSuppression();@@ -2073,15 +2073,14 @@ async function teardownAuthAccountBoundary(reason: string): Promise<void> {// device-link 单持有者仲裁:必须在 dispose DbClient **之前**释放持有权行// (dispose 同步 clearCurrentDbClient,之后 store 不可用,只能等 15s+ 心跳// 过期,同机幸存实例接管变慢)。内部带 1.5s 超时,不会卡住登出。- try {- await closeSharedTasksBeforeLogout();- await releaseDeviceLinkOwnershipBeforeLogout();- } catch (err) {- authBoundaryLog.error(- `[bootstrap-electron] release device-link ownership on ${reason} failed (non-fatal):`,- err,- );- }+ await closeSharedTasksBeforeAccountHandover({+ closeSharedTasks: closeSharedTasksBeforeLogout,+ releaseOwnership: releaseDeviceLinkOwnershipBeforeLogout,+ onClosureFailure: () => markAccountBoundaryAbortedMidTeardown(reason),+ onReleaseFailure: (err) => authBoundaryLog.error(+ `[bootstrap-electron] release device-link ownership on ${reason} failed (non-fatal):`, err,+ ),+ });try {await lifecycleDbClientManager.dispose(reason);} finally {diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskAccountBoundary.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskAccountBoundary.test.tsnew file mode 100644index 0000000000..676e6b277f--- /dev/null+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskAccountBoundary.test.ts@@ -0,0 +1,90 @@+import { readFileSync } from 'node:fs';+import { describe, expect, it, vi } from 'vitest';+import { closeSharedTasksBeforeAccountHandover } from '../sharedTaskAccountBoundary';++function setup() {+ const events: string[] = [];+ const options = {+ closeSharedTasks: vi.fn(async () => { events.push('close'); }),+ releaseOwnership: vi.fn(async () => { events.push('release'); }),+ onClosureFailure: vi.fn(),+ onReleaseFailure: vi.fn(),+ };+ const disposeDatabase = vi.fn(() => { events.push('dispose'); });+ const commitOwner = vi.fn(() => { events.push('commit'); });+ const handover = async () => {+ await closeSharedTasksBeforeAccountHandover(options);+ disposeDatabase();+ commitOwner();+ };+ return { events, options, disposeDatabase, commitOwner, handover };+}++describe('shared-task account boundary cleanup', () => {+ it('closes shares then releases ownership before database disposal and owner commit', async () => {+ const h = setup();+ await h.handover();+ expect(h.events).toEqual(['close', 'release', 'dispose', 'commit']);+ expect(h.options.onClosureFailure).not.toHaveBeenCalled();+ expect(h.options.onReleaseFailure).not.toHaveBeenCalled();+ });++ it.each([false, true])('releases ownership but preserves the old database on closure failure (release fails=%s)', async (releaseFails) => {+ const h = setup();+ const journalError = new Error('journal unavailable');+ const releaseError = new Error('lease unavailable');+ h.options.closeSharedTasks.mockRejectedValueOnce(journalError);+ if (releaseFails) h.options.releaseOwnership.mockRejectedValueOnce(releaseError);+ await expect(h.handover()).rejects.toBe(journalError);+ expect(h.options.releaseOwnership).toHaveBeenCalledOnce();+ expect(h.options.onClosureFailure).toHaveBeenCalledExactlyOnceWith(journalError);+ expect(h.options.onReleaseFailure.mock.calls).toEqual(releaseFails ? [[releaseError]] : []);+ expect(h.disposeDatabase).not.toHaveBeenCalled();+ expect(h.commitOwner).not.toHaveBeenCalled();+ // The retained outgoing profile can make the closure durable on retry.+ await h.handover();+ expect(h.options.closeSharedTasks).toHaveBeenCalledTimes(2);+ expect(h.disposeDatabase).toHaveBeenCalledOnce();+ expect(h.commitOwner).toHaveBeenCalledOnce();+ });++ it('waits for ownership release even when closure has already failed', async () => {+ const h = setup();+ const error = new Error('disk failed');+ let release!: () => void;+ h.options.closeSharedTasks.mockRejectedValue(error);+ h.options.releaseOwnership.mockImplementation(() => new Promise<void>((resolve) => { release = resolve; }));+ let completed = false;+ const result = h.handover().catch((failure) => { completed = true; return failure; });+ await vi.waitFor(() => expect(h.options.releaseOwnership).toHaveBeenCalledOnce());+ expect(completed).toBe(false);+ release();+ expect(await result).toBe(error);+ expect(h.disposeDatabase).not.toHaveBeenCalled();+ });++ it('keeps lease-release failure best effort after durable closure', async () => {+ const h = setup();+ const error = new Error('lease unavailable');+ h.options.releaseOwnership.mockRejectedValue(error);+ await h.handover();+ expect(h.options.onReleaseFailure).toHaveBeenCalledExactlyOnceWith(error);+ expect(h.disposeDatabase).toHaveBeenCalledOnce();+ expect(h.commitOwner).toHaveBeenCalledOnce();+ });++ it('wires both bootstrap cleanup sites through the blocking closure before disposing the DB', () => {+ const source = readFileSync(new URL('../../bootstrap-electron.ts', import.meta.url), 'utf8');+ const teardown = source.slice(source.indexOf('async function teardownAuthAccountBoundary('), source.indexOf('authManager.setAccountSwitchTeardown('));+ const sites = [...teardown.matchAll(/await closeSharedTasksBeforeAccountHandover\(\{([\s\S]*?)\}\);/g)];+ expect(sites).toHaveLength(2);+ for (const site of sites) {+ expect(site[1]).toContain('closeSharedTasks: closeSharedTasksBeforeLogout');+ expect(site[1]).toContain('releaseOwnership: releaseDeviceLinkOwnershipBeforeLogout');+ expect(site[1]).toContain('onClosureFailure: () => markAccountBoundaryAbortedMidTeardown(reason)');+ const next = teardown.slice(site.index! + site[0].length).trimStart();+ expect(next).toMatch(/^(?:try \{\s*)?await lifecycleDbClientManager\.dispose\(reason\);/);+ }+ expect(teardown).not.toContain('await closeSharedTasksBeforeLogout()');+ });+});diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.tsindex 48cc10e11e..1746bae007 100644--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskHost.test.ts@@ -262,6 +262,26 @@ describe('task host sharedTask lifecycle', () => {expect(canRead()).toBe(false);await expect(host.dispose()).rejects.toThrow('disk failed');});+ it('keeps both guests revoked and retries closure after disk failure and relay disposal', async () => {+ await host.open('session');+ const a = host.capturePeer(sharedTaskGuestPeer('sharedTask', 'member-a', 'phone-a'))!;+ const b = host.capturePeer(sharedTaskGuestPeer('sharedTask', 'member-b', 'phone-b'))!;+ const persist = options.journal.close;+ options.journal.close = vi.fn().mockRejectedValueOnce(new Error('disk failed')).mockImplementation(persist);+ await expect(host.closeLocallyForBoundary()).rejects.toThrow('disk failed');+ expect(a.isCurrent()).toBe(false);+ expect(b.isCurrent()).toBe(false);+ expect(canRead('a')).toBe(false);+ expect(canRead('b')).toBe(false);+ await expect(host.dispose()).rejects.toThrow('disk failed');+ // Relay release clears live entries, but the retained old DB still provides+ // the identity needed to retry the failed close record.+ await expect(host.closeLocallyForBoundary()).resolves.toEqual(['sharedTask']);+ expect(records.get('sharedTask')?.terminal).toBe(true);+ await expect(host.dispose()).resolves.toBeUndefined();+ expect(a.isCurrent()).toBe(false);+ expect(b.isCurrent()).toBe(false);+ });it('invalidates old captures without revoking existing devices when a member adds a device', async () => {await host.open('session');expect(host.capturePeer(sharedTaskHostPeer('sharedTask', 'desktop'))).toBeNull();diff --git a/apps/desktop/src/main/device-link/sharedTaskAccountBoundary.ts b/apps/desktop/src/main/device-link/sharedTaskAccountBoundary.tsnew file mode 100644index 0000000000..6b222e92d7--- /dev/null+++ b/apps/desktop/src/main/device-link/sharedTaskAccountBoundary.ts@@ -0,0 +1,23 @@+/** Keep the outgoing database alive if shared-task closure cannot be made durable. */+export async function closeSharedTasksBeforeAccountHandover(options: {+ closeSharedTasks(): Promise<void>;+ releaseOwnership(): Promise<void>;+ onClosureFailure(error: unknown): void;+ onReleaseFailure(error: unknown): void;+}): Promise<void> {+ try {+ await options.closeSharedTasks();+ } catch (error) {+ options.onClosureFailure(error);+ throw error;+ } finally {+ // Even a failed journal must not leave the outgoing relay accepting peers.+ // A release error retains the existing best-effort semantics, but must not+ // replace a closure error and turn it into a successful account handover.+ try {+ await options.releaseOwnership();+ } catch (error) {+ options.onReleaseFailure(error);+ }+ }+}