Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 将插件初始化移出登录等待并隔离后台超时 (#6028)

Chris Zhang0f9e076a9cba
diff --git a/apps/desktop/src/main/__tests__/authCredentialRecoveryWiring.test.ts b/apps/desktop/src/main/__tests__/authCredentialRecoveryWiring.test.ts
index e14b8fb293..0691fca7de 100644
--- a/apps/desktop/src/main/__tests__/authCredentialRecoveryWiring.test.ts
+++ b/apps/desktop/src/main/__tests__/authCredentialRecoveryWiring.test.ts
@@ -88,7 +88,7 @@ describe('production credential recovery wiring', () => {
},
authManager: {
initialize: () => (rejects ? Promise.reject(outcome) : Promise.resolve(outcome)),
- ensureStableOwnerPostCommitTasks: vi.fn(async () => {}),
+ requestStableOwnerPostCommit: vi.fn(),
},
authCredentialRecovery: { request },
app: { isPackaged: true },
diff --git a/apps/desktop/src/main/__tests__/authPostCommitStartup.test.ts b/apps/desktop/src/main/__tests__/authPostCommitStartup.test.ts
new file mode 100644
index 0000000000..9a69ff4771
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/authPostCommitStartup.test.ts
@@ -0,0 +1,161 @@
+import { readFileSync } from 'node:fs';
+import { createSourceFile, isFunctionDeclaration, ScriptTarget, transpileModule } from 'typescript';
+import { describe, expect, it, vi } from 'vitest';
+import { StableOwnerPostCommitCoordinator } from '../stableOwnerPostCommit';
+
+// Run the production auth entrypoints with the real post-commit coordinator,
+// without loading Electron, credentials or another account's files.
+const source = readFileSync(new URL('../authManager.ts', import.meta.url), 'utf8');
+const parsed = createSourceFile('authManager.ts', source, ScriptTarget.ES2022, true);
+function productionFunction(name: string): string {
+ const declaration = parsed.statements.find(
+ (node) => isFunctionDeclaration(node) && node.name?.text === name,
+ );
+ if (!declaration) throw new Error(`Missing production function: ${name}`);
+ return declaration.getText(parsed).replace(/^export /, '');
+}
+
+function setup(mode: 'cloud' | 'local' | 'signed-out', passive = false) {
+ const state = {
+ mode,
+ dataOwnerId: mode === 'signed-out' ? null : 'owner',
+ canEnterApp: mode !== 'signed-out',
+ };
+ let stable = true;
+ let finish: ((outcome: 'completed') => void) | undefined;
+ const task = vi.fn(
+ () =>
+ new Promise<'completed'>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const coordinator = new StableOwnerPostCommitCoordinator({
+ snapshot: () => ({ scopeKey: `${mode}:1`, dataOwnerId: state.dataOwnerId, stable }),
+ warn: vi.fn(),
+ });
+ coordinator.setTask(task);
+ const commit = vi.fn(async () => {
+ stable = true;
+ });
+ const deps = {
+ stableOwnerPostCommitCoordinator: coordinator,
+ isPassiveSharedUserDataInstance: () => passive,
+ getActiveAppSession: () => state,
+ isOwnerChangeShellPending: () => !stable,
+ isGhostSkillProjectionBoundaryStableForOwner: () => stable,
+ accessToken: mode === 'cloud' ? 'test-only-token' : null,
+ currentUser: mode === 'cloud' ? { id: 'owner' } : null,
+ LOCAL_DATA_OWNER_ID: 'owner',
+ snapshotAuthState: () => state,
+ snapshotLoggedOutAuthState: () => ({ canEnterApp: false }),
+ repairStableCloudOwnerDataReservations: vi.fn(async () => true),
+ migrateLocalProviderBindingsAfterCloudCommit: vi.fn(async () => {}),
+ commitCloudAppSession: vi.fn(),
+ withAccountFreeOwnerCommit: commit,
+ };
+ const compiled = transpileModule(
+ [
+ productionFunction('requestStableOwnerPostCommit'),
+ productionFunction('recoverAccountFreeOwnerAtStartup'),
+ productionFunction('initialize'),
+ 'return { initialize, recoverAccountFreeOwnerAtStartup, requestStableOwnerPostCommit };',
+ ].join('\n'),
+ { compilerOptions: { target: ScriptTarget.ES2022 } },
+ ).outputText;
+ const entrypoints = new Function(...Object.keys(deps), compiled)(...Object.values(deps)) as {
+ initialize(): Promise<unknown>;
+ recoverAccountFreeOwnerAtStartup(mode: string, reason: string): Promise<void>;
+ requestStableOwnerPostCommit(reason: string): void;
+ };
+ return {
+ ...entrypoints,
+ state,
+ task,
+ coordinator,
+ deps,
+ finish: () => finish?.('completed'),
+ setStable: (value: boolean) => {
+ stable = value;
+ },
+ };
+}
+
+describe('authentication does not wait for optional plugin provisioning', () => {
+ it('returns through the real startup IPC while the owner task remains pending', async () => {
+ const run = setup('cloud');
+ const bootstrap = readFileSync(new URL('../bootstrap-electron.ts', import.meta.url), 'utf8');
+ const start = bootstrap.indexOf("ipcMain.handle('auth:initialize',");
+ const end = bootstrap.indexOf("ipcMain.handle('auth:get-login-state',", start);
+ const compiled = transpileModule(bootstrap.slice(start, end), {
+ compilerOptions: { target: ScriptTarget.ES2022 },
+ }).outputText;
+ let initialize!: () => Promise<unknown>;
+ const deps = {
+ ipcMain: {
+ handle: (_channel: string, handler: typeof initialize) => {
+ initialize = handler;
+ },
+ },
+ authManager: run,
+ authCredentialRecovery: { request: vi.fn() },
+ app: { isPackaged: true },
+ isCindyVersionLaunchPending: () => false,
+ noteAuthColdStartState: vi.fn(),
+ };
+ new Function(...Object.keys(deps), compiled)(...Object.values(deps));
+ try {
+ await expect(initialize()).resolves.toBe(run.state);
+ expect(run.task).toHaveBeenCalledTimes(1);
+ expect(deps.noteAuthColdStartState).toHaveBeenCalledWith(run.state, null);
+ } finally {
+ run.finish();
+ }
+ });
+
+ it.each(['cloud', 'local'] as const)(
+ 'returns the %s session while provisioning is still pending',
+ async (mode) => {
+ const run = setup(mode);
+ try {
+ await expect(run.initialize()).resolves.toBe(run.state);
+ await expect(run.initialize()).resolves.toBe(run.state);
+ expect(run.task).toHaveBeenCalledTimes(1);
+ // Explicit completion consumers still wait; only authentication was detached.
+ const completed = vi.fn();
+ const completion = run.coordinator.ensure('observer').then(completed);
+ await Promise.resolve();
+ expect(completed).not.toHaveBeenCalled();
+ run.finish();
+ await completion;
+ expect(completed).toHaveBeenCalledWith('completed');
+ } finally {
+ run.finish();
+ }
+ },
+ );
+
+ it('returns signed-out recovery without waiting for bundled provisioning', async () => {
+ const run = setup('signed-out');
+ try {
+ await run.recoverAccountFreeOwnerAtStartup('signed-out', 'startup');
+ await vi.waitFor(() => expect(run.task).toHaveBeenCalledTimes(1));
+ } finally {
+ run.finish();
+ }
+ });
+
+ it('keeps a real owner transition fenced', async () => {
+ const run = setup('cloud');
+ run.setStable(false);
+ await expect(run.initialize()).resolves.toEqual({ canEnterApp: false });
+ expect(run.task).not.toHaveBeenCalled();
+ });
+
+ it('does not provision from a passive shared profile', async () => {
+ const run = setup('cloud', true);
+ await expect(run.initialize()).resolves.toBe(run.state);
+ run.requestStableOwnerPostCommit('ipc-fallback');
+ await Promise.resolve();
+ expect(run.task).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/stableOwnerPostCommitStep.test.ts b/apps/desktop/src/main/__tests__/stableOwnerPostCommitStep.test.ts
new file mode 100644
index 0000000000..98e0ad813b
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/stableOwnerPostCommitStep.test.ts
@@ -0,0 +1,188 @@
+import { readFileSync } from 'node:fs';
+import { ScriptTarget, transpileModule } from 'typescript';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ StableOwnerPostCommitCoordinator,
+ StableOwnerPostCommitStep,
+} from '../stableOwnerPostCommit';
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('bounded owner background steps', () => {
+ it('times out without releasing a pending writer, then permits recovery after settlement', async () => {
+ vi.useFakeTimers();
+ const work = deferred<'completed'>();
+ const task = vi.fn(() => work.promise);
+ const warn = vi.fn();
+ const step = new StableOwnerPostCommitStep({ name: 'market', timeoutMs: 100, warn });
+ const first = step.run('owner:1', task);
+ expect(step.run('owner:1', task)).toBe(first);
+ await vi.advanceTimersByTimeAsync(100);
+ await expect(first).resolves.toBe('failed');
+ await expect(step.run('owner:1', task)).resolves.toBe('failed');
+ await expect(step.run('owner:2', task)).resolves.toBe('deferred');
+ expect(task).toHaveBeenCalledTimes(1);
+ expect(warn).toHaveBeenCalledTimes(1);
+ work.resolve('completed');
+ await vi.advanceTimersByTimeAsync(0);
+ const recovered = vi.fn(async () => 'completed' as const);
+ await expect(step.run('owner:2', recovered)).resolves.toBe('completed');
+ expect(recovered).toHaveBeenCalledTimes(1);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it.each(['throw', 'reject', 'late-reject'] as const)(
+ 'observes %s and remains retryable',
+ async (mode) => {
+ vi.useFakeTimers();
+ const work = deferred<'completed'>();
+ const warn = vi.fn();
+ const step = new StableOwnerPostCommitStep({ name: 'oauth', timeoutMs: 100, warn });
+ const pending = step.run('owner:1', () => {
+ if (mode === 'throw') throw new Error('failed');
+ return work.promise;
+ });
+ if (mode === 'late-reject') await vi.advanceTimersByTimeAsync(100);
+ if (mode !== 'throw') work.reject(new Error('failed'));
+ await expect(pending).resolves.toBe('failed');
+ await vi.advanceTimersByTimeAsync(0);
+ await expect(step.run('owner:1', async () => 'completed')).resolves.toBe('completed');
+ expect(warn).toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ },
+ );
+});
+
+// Exercise the actual bootstrap pipeline and its timer/wakeup market entrypoint,
+// not a second copy of the orchestration used only by tests.
+function pipeline() {
+ const source = readFileSync(new URL('../bootstrap-electron.ts', import.meta.url), 'utf8');
+ const setup = source.slice(
+ source.indexOf('const ownerBackgroundLog ='),
+ source.indexOf('// ── Custom protocol registration'),
+ );
+ const sync = source.slice(
+ source.indexOf('function syncPluginMarketForActiveOwner('),
+ source.indexOf('function parseOptionalDeviceLinkDeviceId('),
+ );
+ let scope = 'cloud:first:1';
+ let owner: string | null = 'first';
+ const market = deferred<'completed'>();
+ const builtin = vi.fn(async () => 'completed' as const);
+ const syncMarket = vi.fn(() => market.promise);
+ const oauth = vi.fn(async () => true);
+ const warn = vi.fn();
+ const coordinator = new StableOwnerPostCommitCoordinator({
+ snapshot: () => ({ scopeKey: scope, dataOwnerId: owner, stable: true }),
+ warn,
+ });
+ const deps = {
+ StableOwnerPostCommitStep,
+ createLogger: () => ({ warn }),
+ authManager: {
+ setStableOwnerPostCommitTask: (task: Parameters<typeof coordinator.setTask>[0]) =>
+ coordinator.setTask(task),
+ },
+ isAppSessionBoundaryPending: () => false,
+ activeOwnerScopeKey: () => scope,
+ getActiveAppSession: () => ({ dataOwnerId: owner }),
+ runStableOwnerPostCommitTask: builtin,
+ syncDefaultMarketPlugins: syncMarket,
+ reconcileGhostOauthAccountsForActiveOwner: oauth,
+ };
+ const compiled = transpileModule(
+ `
+ ${setup}
+ let pluginMarketSyncInFlightScope = null;
+ let lastPluginMarketSyncScope = null;
+ let lastPluginMarketSyncAt = 0;
+ ${sync}
+ return { syncPluginMarketForActiveOwner };
+ `,
+ { compilerOptions: { target: ScriptTarget.ES2022 } },
+ ).outputText;
+ const entry = new Function(...Object.keys(deps), compiled)(...Object.values(deps));
+ return {
+ ...entry,
+ coordinator,
+ market,
+ syncMarket,
+ builtin,
+ oauth,
+ warn,
+ switchOwner: (next: string | null) => {
+ owner = next;
+ scope = `scope:${next}:2`;
+ },
+ };
+}
+
+describe('production background pipeline', () => {
+ it('continues OAuth after market timeout and shares its pending writer with wakeup/periodic retries', async () => {
+ vi.useFakeTimers();
+ const run = pipeline();
+ const result = run.coordinator.ensure('startup');
+ await vi.advanceTimersByTimeAsync(180_000);
+ await expect(result).resolves.toBe('failed');
+ expect(run.oauth).toHaveBeenCalledTimes(1);
+ run.syncPluginMarketForActiveOwner();
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(run.syncMarket).toHaveBeenCalledTimes(1);
+ expect(run.oauth).toHaveBeenCalledTimes(2);
+ run.market.resolve('completed');
+ await vi.advanceTimersByTimeAsync(5_000);
+ await expect(run.coordinator.ensure('after-recovery')).resolves.toBe('completed');
+ expect(run.syncMarket).toHaveBeenCalledTimes(2);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('does not run a later stage under a replaced owner', async () => {
+ vi.useFakeTimers();
+ const run = pipeline();
+ const first = run.coordinator.ensure('first');
+ await vi.advanceTimersByTimeAsync(0);
+ run.switchOwner('second');
+ const second = run.coordinator.ensure('second');
+ await vi.advanceTimersByTimeAsync(180_000);
+ await expect(first).resolves.toBe('deferred');
+ await expect(second).resolves.toBe('deferred');
+ expect(run.syncMarket).toHaveBeenCalledTimes(1);
+ expect(run.oauth).toHaveBeenCalledTimes(1);
+ run.market.resolve('completed');
+ await vi.advanceTimersByTimeAsync(1_000);
+ await expect(run.coordinator.ensure('recovered')).resolves.toBe('completed');
+ expect(run.syncMarket).toHaveBeenCalledTimes(2);
+ });
+
+ it('bounds builtin and OAuth stages as well, and does not run private stages signed out', async () => {
+ vi.useFakeTimers();
+ const run = pipeline();
+ const builtin = deferred<'completed'>();
+ run.builtin.mockImplementation(() => builtin.promise);
+ run.oauth.mockImplementation(() => new Promise<boolean>(() => {}));
+ run.market.resolve('completed');
+ const result = run.coordinator.ensure('startup');
+ await vi.advanceTimersByTimeAsync(60_000);
+ await expect(result).resolves.toBe('failed');
+ expect(run.syncMarket).toHaveBeenCalledTimes(1);
+ expect(run.oauth).toHaveBeenCalledTimes(1);
+ builtin.resolve('completed');
+ await vi.advanceTimersByTimeAsync(0);
+ run.switchOwner(null);
+ await expect(run.coordinator.ensure('signed-out')).resolves.toBe('completed');
+ expect(run.syncMarket).toHaveBeenCalledTimes(1);
+ expect(run.oauth).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index c080f496b6..d2ce3309d3 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -358,16 +358,12 @@ const stableOwnerPostCommitCoordinator = new StableOwnerPostCommitCoordinator({
warn: (message, meta) => log.warn(message, meta),
});
-function requestStableOwnerPostCommit(reason: string): void {
+/** Queue optional owner-scoped provisioning without holding authentication or the app shell. */
+export function requestStableOwnerPostCommit(reason: string): void {
if (isPassiveSharedUserDataInstance()) return;
void stableOwnerPostCommitCoordinator.ensure(reason);
}
-async function ensureStableOwnerPostCommit(reason: string): Promise<void> {
- if (isPassiveSharedUserDataInstance()) return;
- await stableOwnerPostCommitCoordinator.ensure(reason);
-}
-
// ── Module-level state ──────────────────────────────────────────────────────
let accessToken: string | null = null;
@@ -2622,7 +2618,7 @@ async function recoverAccountFreeOwnerAtStartup(
commitActiveAppSession(mode);
}
}
- await ensureStableOwnerPostCommit('owner-already-stable');
+ requestStableOwnerPostCommit('owner-already-stable');
return;
}
await withAccountFreeOwnerCommit({
@@ -2864,11 +2860,6 @@ export function setStableOwnerPostCommitTask(task: StableOwnerPostCommitTask | n
stableOwnerPostCommitCoordinator.setTask(task);
}
-/** Pull-based startup fallback for an owner that was already stable before registration. */
-export async function ensureStableOwnerPostCommitTasks(reason: string): Promise<void> {
- await ensureStableOwnerPostCommit(reason);
-}
-
// ── User-level API key sync ─────────────────────────────────────────────────
//
// 已移除。XD 网关 key / Mivo key 均为 **本地 only**(Electron safeStorage),
@@ -4538,7 +4529,7 @@ export async function initialize(options: AuthInitializeOptions = {}): Promise<A
commitCloudAppSession(currentUser.id);
}
await migrateLocalProviderBindingsAfterCloudCommit(currentUser.id);
- await ensureStableOwnerPostCommit('auth-initialize-stable-cloud');
+ requestStableOwnerPostCommit('auth-initialize-stable-cloud');
return snapshotAuthState();
}
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index da9cf38bcb..6f3cca742f 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -1119,6 +1119,7 @@ import { registerRelaunchBusyActivityIpc } from './relaunchBusyActivityIpc.js';
import { getGhostSetupChangeBus } from './cindy-brain/ghostSetupChangeBus.js';
import { getGhostSetupInteractionBridge } from './cindy-brain/ghostSetupInteractionBridge.js';
import { registerPluginMarketIpc, syncDefaultMarketPlugins } from './plugin-market/registerIpc.js';
+import { StableOwnerPostCommitStep } from './stableOwnerPostCommit.js';
import { registerPluginPublisherIpc } from './plugin-publisher/registerIpc.js';
import { findCindyFileInArgv } from './cindy-brain/argv.js';
import { handleIncomingCindyFile } from './cindy-brain/openFileInstall.js';
@@ -2466,29 +2467,55 @@ setAppSessionCommitBoundaryHook(() => {
clearAllSessionRuntimeAxes();
clearAllSessionRuntimeControlStates();
});
+const ownerBackgroundLog = createLogger('owner-background');
+const builtinPostCommitStep = new StableOwnerPostCommitStep({
+ name: 'builtin-plugins', timeoutMs: 30_000,
+ warn: (message, meta) => ownerBackgroundLog.warn(message, meta),
+});
+// Each package already has a 120s transport limit. This bounds our wait for
+// the entire batch (catalog/auth/locks included), not the lifetime of a write.
+const marketPostCommitStep = new StableOwnerPostCommitStep({
+ name: 'plugin-market', timeoutMs: 180_000,
+ warn: (message, meta) => ownerBackgroundLog.warn(message, meta),
+});
+const oauthPostCommitStep = new StableOwnerPostCommitStep({
+ name: 'plugin-oauth', timeoutMs: 30_000,
+ warn: (message, meta) => ownerBackgroundLog.warn(message, meta),
+});
authManager.setStableOwnerPostCommitTask(async ({ reason, scopeKey, dataOwnerId }) => {
- const builtinOutcome = await runStableOwnerPostCommitTask(reason, { scopeKey, dataOwnerId });
+ const isCurrent = () => !isAppSessionBoundaryPending()
+ && activeOwnerScopeKey() === scopeKey
+ && getActiveAppSession().dataOwnerId === dataOwnerId;
+ if (!isCurrent()) return 'deferred';
+ const builtinOutcome = await builtinPostCommitStep.run(scopeKey, async () => {
+ if (!isCurrent()) return 'deferred';
+ const outcome = await runStableOwnerPostCommitTask(reason, { scopeKey, dataOwnerId });
+ return outcome === 'retry-pending' ? 'failed' : outcome;
+ });
if (builtinOutcome === 'deferred') return builtinOutcome;
+ if (!isCurrent()) return 'deferred';
- let needsRetry = builtinOutcome === 'retry-pending' || builtinOutcome === 'failed';
+ let needsRetry = builtinOutcome === 'failed';
// Signed-out is a real stable scope for account-free bundled provisioning.
// Market and OAuth are owner-private follow-ups and stay behind this gate.
if (dataOwnerId === null) return needsRetry ? 'failed' : 'completed';
let deferred = false;
- const marketOutcome = await syncDefaultMarketPlugins();
+ const marketOutcome = await marketPostCommitStep.run(scopeKey, async () => {
+ if (!isCurrent()) return 'deferred';
+ return syncDefaultMarketPlugins();
+ });
+ if (!isCurrent()) return 'deferred';
if (marketOutcome === 'failed') needsRetry = true;
if (marketOutcome === 'deferred') deferred = true;
- try {
+ const oauthOutcome = await oauthPostCommitStep.run(scopeKey, async () => {
+ if (!isCurrent()) return 'deferred';
const oauthCompleted = await reconcileGhostOauthAccountsForActiveOwner();
- if (!oauthCompleted) deferred = true;
- } catch (error) {
- createLogger('ghost-oauth-owner-reconcile').warn(
- 'OAuth account reconciliation for active owner failed',
- { error: error instanceof Error ? error.message : String(error) },
- );
- needsRetry = true;
- }
+ return oauthCompleted ? 'completed' : 'deferred';
+ });
+ if (!isCurrent()) return 'deferred';
+ if (oauthOutcome === 'failed') needsRetry = true;
+ if (oauthOutcome === 'deferred') deferred = true;
return needsRetry ? 'failed' : deferred ? 'deferred' : 'completed';
});
@@ -4245,7 +4272,10 @@ function syncPluginMarketForActiveOwner(minIntervalMs = 0): void {
pluginMarketSyncInFlightScope = scope;
lastPluginMarketSyncScope = scope;
lastPluginMarketSyncAt = now;
- void syncDefaultMarketPlugins().finally(() => {
+ void marketPostCommitStep.run(scope, async () => {
+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== scope) return 'deferred';
+ return syncDefaultMarketPlugins();
+ }).finally(() => {
if (pluginMarketSyncInFlightScope === scope) pluginMarketSyncInFlightScope = null;
});
}
@@ -5835,7 +5865,9 @@ const registerIpcHandlers = () => {
},
})
.finally(() => authCredentialRecovery.request());
- await authManager.ensureStableOwnerPostCommitTasks('auth-initialize');
+ // Plugin downloads/reconciliation retain their owner-scoped retries, but
+ // must not delay AuthContext starting the owner DB or showing the app.
+ authManager.requestStableOwnerPostCommit('auth-initialize');
if (!app.isPackaged || isCindyVersionLaunchPending()) {
recordDesktopDevAuthStartupResult(state, pendingCompletion, () =>
authManager.getAuthState(),
diff --git a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
index 4c743fc3d2..82adb43adb 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
@@ -165,9 +165,10 @@ describe('Plugin Market IPC error boundary', () => {
ownerTaskBody.indexOf('syncDefaultMarketPlugins()'),
);
expect(ownerTaskBody).not.toContain("builtinOutcome === 'failed') return builtinOutcome");
- expect(ownerTaskBody).toContain("builtinOutcome === 'retry-pending'");
+ expect(ownerTaskBody).toContain("outcome === 'retry-pending' ? 'failed' : outcome");
expect(ownerTaskBody).toContain("builtinOutcome === 'failed'");
- expect(ownerTaskBody).toContain('const marketOutcome = await syncDefaultMarketPlugins()');
+ expect(ownerTaskBody).toContain('const marketOutcome = await marketPostCommitStep.run(');
+ expect(ownerTaskBody).toContain('return syncDefaultMarketPlugins();');
expect(ownerTaskBody).toContain("marketOutcome === 'failed'");
expect(ownerTaskBody).toContain("marketOutcome === 'deferred'");
expect(ownerTaskBody).toContain('await reconcileGhostOauthAccountsForActiveOwner()');
@@ -175,7 +176,7 @@ describe('Plugin Market IPC error boundary', () => {
"return needsRetry ? 'failed' : deferred ? 'deferred' : 'completed';",
);
expect(bootstrapSource).toContain(
- "await authManager.ensureStableOwnerPostCommitTasks('auth-initialize');",
+ "authManager.requestStableOwnerPostCommit('auth-initialize');",
);
expect(authManagerSource).toContain("requestStableOwnerPostCommit('owner-commit');");
expect(authManagerSource).not.toContain("await ensureStableOwnerPostCommit('owner-commit');");
@@ -191,7 +192,7 @@ describe('Plugin Market IPC error boundary', () => {
'if (!session.dataOwnerId || isAppSessionBoundaryPending()) return;',
);
expect(ownerSyncBody).toContain('if (scope === pluginMarketSyncInFlightScope) return;');
- expect(ownerSyncBody).toContain('void syncDefaultMarketPlugins().finally(() => {');
+ expect(ownerSyncBody).toContain('void marketPostCommitStep.run(scope,');
expect(ownerSyncBody).toContain('pluginMarketSyncInFlightScope = null;');
expect(bootstrapSource).toContain('PLUGIN_MARKET_PERIODIC_SYNC_MS = 30 * 60 * 1000');
expect(bootstrapSource).toContain('syncPluginMarketForActiveOwner(30_000);');
diff --git a/apps/desktop/src/main/stableOwnerPostCommit.ts b/apps/desktop/src/main/stableOwnerPostCommit.ts
index dc5f29f1f7..2ece7b69f6 100644
--- a/apps/desktop/src/main/stableOwnerPostCommit.ts
+++ b/apps/desktop/src/main/stableOwnerPostCommit.ts
@@ -1,8 +1,4 @@
-export type StableOwnerPostCommitOutcome =
- | 'completed'
- | 'deferred'
- | 'failed'
- | 'not-applicable';
+export type StableOwnerPostCommitOutcome = 'completed' | 'deferred' | 'failed' | 'not-applicable';
export interface StableOwnerPostCommitContext {
reason: string;
@@ -31,6 +27,83 @@ interface StableOwnerPostCommitCoordinatorOptions {
const DEFAULT_RETRY_DELAYS_MS = [1_000, 5_000, 15_000, 60_000] as const;
+/**
+ * Bounds a background provisioning stage without pretending to cancel a disk
+ * transaction. A timed-out operation keeps its slot until it actually settles:
+ * retries and another owner cannot start a second writer behind its back.
+ * Other stages may continue, and late failures are always observed.
+ */
+export class StableOwnerPostCommitStep {
+ private inFlight: {
+ scopeKey: string;
+ result: Promise<Exclude<StableOwnerPostCommitOutcome, 'not-applicable'>>;
+ } | null = null;
+
+ constructor(
+ private readonly options: {
+ name: string;
+ timeoutMs: number;
+ warn: (message: string, meta: Record<string, unknown>) => void;
+ },
+ ) {}
+
+ run(
+ scopeKey: string,
+ task: () => Promise<Exclude<StableOwnerPostCommitOutcome, 'not-applicable'>>,
+ ): Promise<Exclude<StableOwnerPostCommitOutcome, 'not-applicable'>> {
+ if (this.inFlight) {
+ return this.inFlight.scopeKey === scopeKey
+ ? this.inFlight.result
+ : Promise.resolve('deferred');
+ }
+ let finish!: (outcome: Exclude<StableOwnerPostCommitOutcome, 'not-applicable'>) => void;
+ const result = new Promise<Exclude<StableOwnerPostCommitOutcome, 'not-applicable'>>(
+ (resolve) => {
+ finish = resolve;
+ },
+ );
+ const flight = { scopeKey, result };
+ this.inFlight = flight;
+ let timedOut = false;
+ const timer = setTimeout(() => {
+ timedOut = true;
+ this.options.warn('owner background stage timed out; operation remains in flight', {
+ stage: this.options.name,
+ timeoutMs: this.options.timeoutMs,
+ });
+ finish('failed');
+ }, this.options.timeoutMs);
+ timer.unref?.();
+ // Observe synchronous throws too. No retry timer releases the actual writer.
+ void Promise.resolve()
+ .then(task)
+ .then(
+ (outcome) => {
+ clearTimeout(timer);
+ if (this.inFlight === flight) this.inFlight = null;
+ if (timedOut) {
+ this.options.warn('owner background stage settled after timeout', {
+ stage: this.options.name,
+ outcome,
+ });
+ }
+ finish(outcome);
+ },
+ (error: unknown) => {
+ clearTimeout(timer);
+ if (this.inFlight === flight) this.inFlight = null;
+ this.options.warn('owner background stage failed', {
+ stage: this.options.name,
+ timedOut,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ finish('failed');
+ },
+ );
+ return result;
+ }
+}
+
/**
* Serializes the work that must run after the durable Ghost projection
* boundary is stable. This includes the signed-out scope: account-free