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): 同账号代次推进后恢复模型就绪门闩 (#2863)

Dash907eb3d6fabd
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 86c8433ce3..18d82ff850 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -541,8 +541,24 @@ import {
requestProviderModelAutoRefresh,
resetProviderModelAutoRefreshCooldowns,
} from './maker-host/provider-model-auto-refresh.js';
-import { refreshProviderModelsAfterAccountReady } from './maker-host/account-provider-model-refresh.js';
-import { accountProviderReadinessBarrier } from './maker-host/account-provider-readiness-barrier.js';
+import {
+ discoverAccountProviderModels,
+ resetAccountProviderRuntimes,
+} from './maker-host/account-provider-model-refresh.js';
+import {
+ accountProviderReadinessBarrier,
+ shouldClearCatalogAfterJoiningPreviousScope,
+} from './maker-host/account-provider-readiness-barrier.js';
+import {
+ accountProviderReadinessArm,
+ shouldFirePendingReadinessStart,
+ shouldKeepPendingReadinessStart,
+} from './maker-host/account-provider-readiness-arm.js';
+import {
+ ensureCurrentAccountProviderReadiness,
+ setAccountProviderReadinessReadyHandler,
+ shouldStartReadinessConsumers,
+} from './maker-host/account-provider-readiness-ensure.js';
import {
readImDefaultSettingsState,
resetImDefaultSettings,
@@ -821,19 +837,33 @@ import { registerGoalHandlers, broadcastGoalStatus } from './maker-ipc/goal.js';
import { createLogger as createSchedulerLogger } from './logger.js';
let makerProviderRefreshConfigured = false;
-let startPendingAccountProviderReadiness: (() => void) | null = null;
+let startPendingAccountProviderReadiness: { ownerId: string; start: () => void } | null = null;
function markMakerProviderRefreshConfigured(): void {
makerProviderRefreshConfigured = true;
const startPending = startPendingAccountProviderReadiness;
startPendingAccountProviderReadiness = null;
- startPending?.();
+ if (!startPending) return;
+ const decision = {
+ pendingOwnerId: startPending.ownerId,
+ currentOwnerId: getActiveAppSession().dataOwnerId,
+ boundaryPending: isAppSessionBoundaryPending(),
+ };
+ if (shouldFirePendingReadinessStart(decision)) {
+ startPending.start();
+ return;
+ }
+ // Same-owner Ghost repair holds the boundary while this one-shot callback
+ // fires. Put the pending start back so a later unchanged ensureReady / arm
+ // start can still launch discovery after the window closes.
+ if (shouldKeepPendingReadinessStart(decision)) {
+ startPendingAccountProviderReadiness = startPending;
+ }
}
async function waitForCurrentAccountProviderModelsReady(): Promise<void> {
- const scopeKey = activeOwnerScopeKey();
- const ready = await accountProviderReadinessBarrier.waitForScope(scopeKey);
- if (!ready || activeOwnerScopeKey() !== scopeKey || isAppSessionBoundaryPending()) {
+ const ready = await ensureCurrentAccountProviderReadiness();
+ if (!ready) {
throwIpcError(
'PRECONDITION_FAILED',
'Account provider models are not ready for this app session; retry.',
@@ -1198,6 +1228,9 @@ async function teardownAuthAccountBoundary(reason: string): Promise<void> {
// before any Agent route can start. A failed DB read therefore stays fail-closed (empty)
// instead of retaining the previous owner's endpoint or model entries.
setCustomProviders([]);
+ accountProviderReadinessArm.clear();
+ startPendingAccountProviderReadiness = null;
+ accountProviderReadinessBarrier.invalidateAdoption();
clearModelVisibilityMirror();
// 远程会话的镜像冷缓存里是别的设备的聊天内容。owner 命名空间已经保证下一个账号读不到
// 它,但登出后不该在盘上留着 —— 这里 owner 还指向**旧账号**(commitActiveAppSession 在
@@ -6859,12 +6892,22 @@ app.on('ready', async () => {
// Provider discovery is detached from DB read readiness for the same owner, but a
// different owner must not replace the DB while the previous account task can still
// update owner-scoped catalogs or agent environments.
+ const nextProviderScopeKey = activeOwnerScopeKey();
const previousProviderTaskSettled =
- await accountProviderReadinessBarrier.waitForPreviousScope(activeOwnerScopeKey());
+ await accountProviderReadinessBarrier.waitForPreviousScope(nextProviderScopeKey);
// The old task may have completed its owner-scoped DB read after teardown cleared the
- // process-global catalog. Clear once more after joining it so a failed next-owner reload
- // cannot inherit the old endpoint/model snapshot. Same-scope ensure retries skip this.
- if (previousProviderTaskSettled) setCustomProviders([]);
+ // process-global catalog. Clear once more after joining a *different owner* so a
+ // failed next-owner reload cannot inherit the old snapshot. Same-owner generation
+ // bumps also wait here, but must keep the current account's custom providers.
+ if (
+ shouldClearCatalogAfterJoiningPreviousScope({
+ waited: previousProviderTaskSettled,
+ currentSameOwnerAsNext:
+ accountProviderReadinessBarrier.hasSameOwnerIdentity(nextProviderScopeKey),
+ })
+ ) {
+ setCustomProviders([]);
+ }
const user = authManager.getAuthState().user;
if (user == null || user.id !== userId) return;
// 首登轻量迁移(老 xdt-maker userData → Cindy):内部自带 marker 防重入与
@@ -6915,6 +6958,11 @@ app.on('ready', async () => {
userId,
});
}
+ // Same-owner generation bump also lands here. Ensure adopts a settled
+ // discovery task, starts one if it never launched (pending start was
+ // held across a Ghost boundary), and starts consumers if the original
+ // then() skipped them while boundaryPending.
+ void ensureCurrentAccountProviderReadiness();
return;
}
// Phase 1.1: file worker 接管 DB 连接后,释放 main 端的 _db + optimize 定时器。
@@ -7023,12 +7071,60 @@ app.on('ready', async () => {
//
// 模型发现必须排在 Codex 重启序列之后:后者末尾会按 auth 边界重读
// models_cache(cache miss 即清空防串号),并发跑会让刚发现的清单被空快照覆盖。
- const providerScopeKey = activeOwnerScopeKey();
+ const resumeIncompleteDiscovery = async (): Promise<void> => {
+ const handle = accountProviderReadinessBarrier.currentHandle();
+ if (
+ !handle ||
+ getActiveAppSession().dataOwnerId !== userId ||
+ !accountProviderReadinessBarrier.needsIncompleteDiscoveryResume(handle.scopeKey)
+ ) {
+ return;
+ }
+ const catalogMayWrite = () =>
+ handle.isLive() &&
+ accountProviderReadinessBarrier.isCurrentAdoptable() &&
+ getActiveAppSession().dataOwnerId === userId;
+ await discoverAccountProviderModels(
+ {
+ loadXaiLkg: loadXaiModelsFromDiskCache,
+ refreshProviderModels: requestProviderModelAutoRefresh,
+ log: accountSwitchLog,
+ },
+ catalogMayWrite,
+ );
+ if (catalogMayWrite()) handle.markDiscoveryComplete();
+ };
const startProviderReadiness = (): void => {
- if (activeOwnerScopeKey() !== providerScopeKey || isAppSessionBoundaryPending()) return;
+ if (!makerProviderRefreshConfigured) {
+ startPendingAccountProviderReadiness = { ownerId: userId, start: startProviderReadiness };
+ return;
+ }
+ const providerScopeKey = activeOwnerScopeKey();
+ const currentOwnerId = getActiveAppSession().dataOwnerId;
+ if (!currentOwnerId || currentOwnerId !== userId) {
+ return;
+ }
+ if (isAppSessionBoundaryPending()) {
+ startPendingAccountProviderReadiness = {
+ ownerId: userId,
+ start: startProviderReadiness,
+ };
+ return;
+ }
+ if (accountProviderReadinessBarrier.needsIncompleteDiscoveryResume(providerScopeKey)) {
+ void resumeIncompleteDiscovery();
+ return;
+ }
+ if (
+ accountProviderReadinessBarrier.hasScope(providerScopeKey) ||
+ (accountProviderReadinessBarrier.hasAdoptableSameOwner(providerScopeKey) &&
+ accountProviderReadinessBarrier.isDiscoveryComplete())
+ ) {
+ return;
+ }
const providerReadiness = accountProviderReadinessBarrier.start(
providerScopeKey,
- async () => {
+ async (handle) => {
const startedAt = performance.now();
try {
// 自定义 MCP 与自定义供应商都只服务 Agent 路由,不应该阻塞任务列表。
@@ -7045,16 +7141,43 @@ app.on('ready', async () => {
error: err instanceof Error ? err.message : String(err),
});
}
- await refreshCustomProvidersIntoCatalog(
- () => activeOwnerScopeKey() === providerScopeKey && !isAppSessionBoundaryPending(),
- );
- await refreshProviderModelsAfterAccountReady({
- restartCodex: restartCodexAfterAuthModeChange,
- shutdownCodexEnvironment,
- loadXaiLkg: loadXaiModelsFromDiskCache,
- refreshProviderModels: requestProviderModelAutoRefresh,
- log: accountSwitchLog,
- });
+ // Cleanup is owed to this start() entry, not the process-wide boundary
+ // flag. Same-owner Ghost repair holds beginAppSessionBoundary() across
+ // teardown + commit; if that flag gated reset/Pi shutdown, an in-flight
+ // A→B restartCodex would skip shutdownCodexEnvironment forever while
+ // discovery still marked the entry complete and adoptable.
+ const entryStillLive = () => handle.isLive();
+ // Catalog writes die with a real owner teardown (`invalidateAdoption`).
+ // Codex/Pi cleanup stays owed to this entry across a same-owner bump.
+ const catalogMayWrite = () =>
+ handle.isLive() && accountProviderReadinessBarrier.isCurrentAdoptable();
+ await refreshCustomProvidersIntoCatalog(catalogMayWrite);
+ // A new start() is already a new incarnation (same-owner rollover adopts
+ // instead). Bind reset/discovery/Pi teardown to this entry so a later
+ // generation bump cannot skip A→B cleanup, and a replaced entry cannot
+ // mark the next incarnation complete.
+ if (entryStillLive()) {
+ await resetAccountProviderRuntimes(
+ {
+ restartCodex: restartCodexAfterAuthModeChange,
+ shutdownCodexEnvironment,
+ log: accountSwitchLog,
+ },
+ entryStillLive,
+ );
+ }
+ if (catalogMayWrite()) {
+ await discoverAccountProviderModels(
+ {
+ loadXaiLkg: loadXaiModelsFromDiskCache,
+ refreshProviderModels: requestProviderModelAutoRefresh,
+ log: accountSwitchLog,
+ },
+ catalogMayWrite,
+ );
+ handle.markDiscoveryComplete();
+ }
+ if (!entryStillLive()) return;
// Pi bridge 与 Codex 同源(HTTP bridge + gateway key),账号切换后也必须
// 清掉旧账号环境,让下一次 Pi 会话按新账号凭证重建。
try {
@@ -7103,8 +7226,20 @@ app.on('ready', async () => {
// them only after discovery settles. The Maker lifecycle hook remains the final guard for
// every direct create path. The scope check prevents an old completion from reviving hosts
// after an account boundary.
+ const startedHandle = accountProviderReadinessBarrier.currentHandle();
void providerReadiness.then(() => {
- if (activeOwnerScopeKey() !== providerScopeKey || isAppSessionBoundaryPending()) return;
+ if (
+ !startedHandle?.isLive() ||
+ !shouldStartReadinessConsumers({
+ capturedScopeKey: providerScopeKey,
+ currentScopeKey: activeOwnerScopeKey(),
+ boundaryPending: isAppSessionBoundaryPending(),
+ adoptable: accountProviderReadinessBarrier.isCurrentAdoptable(),
+ }) ||
+ !accountProviderReadinessBarrier.markConsumersStarted()
+ ) {
+ return;
+ }
startAccountIntegrationsAfterOwnerDbReady(userId, {
isOwnerCurrent: (ownerId) =>
isLocalDbOwnerCurrent(
@@ -7122,8 +7257,24 @@ app.on('ready', async () => {
};
// localDb 与 splash 可以任意先后完成。协调器已配置就立即开后台任务;
// 否则只登记当前 scope 的启动闭包,不创建一个可能永久 pending 的 Promise。
+ setAccountProviderReadinessReadyHandler((ownerId) => {
+ startAccountIntegrationsAfterOwnerDbReady(ownerId, {
+ isOwnerCurrent: (id) =>
+ isLocalDbOwnerCurrent(
+ authManager.getAuthState(),
+ id,
+ isAppSessionBoundaryPending(),
+ ),
+ startHookControlAccount,
+ startImConnection,
+ log: dbClientLog,
+ });
+ attemptStartScheduler();
+ attemptStartEmbeddingHost();
+ });
+ accountProviderReadinessArm.publish(userId, startProviderReadiness, resumeIncompleteDiscovery);
if (makerProviderRefreshConfigured) startProviderReadiness();
- else startPendingAccountProviderReadiness = startProviderReadiness;
+ else startPendingAccountProviderReadiness = { ownerId: userId, start: startProviderReadiness };
logStartupPhase('post-db-hooks-scheduled');
},
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/accountProviderModelRefresh.test.ts b/apps/desktop/src/main/maker-host/__tests__/accountProviderModelRefresh.test.ts
index 488a0a92fe..d5c1b085cf 100644
--- a/apps/desktop/src/main/maker-host/__tests__/accountProviderModelRefresh.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/accountProviderModelRefresh.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it, vi } from 'vitest';
-import { refreshProviderModelsAfterAccountReady } from '../account-provider-model-refresh.js';
+import {
+ discoverAccountProviderModels,
+ refreshProviderModelsAfterAccountReady,
+ resetAccountProviderRuntimes,
+} from '../account-provider-model-refresh.js';
function deferred() {
let resolve!: () => void;
@@ -10,6 +14,61 @@ function deferred() {
return { promise, resolve };
}
+describe('resetAccountProviderRuntimes', () => {
+ it('stops before later destructive steps when the scope changes', async () => {
+ const shutdownCodexEnvironment = vi.fn(async () => {});
+ let allow = true;
+ await resetAccountProviderRuntimes(
+ {
+ restartCodex: async () => {
+ allow = false;
+ },
+ shutdownCodexEnvironment,
+ log: { warn: vi.fn() },
+ },
+ () => allow,
+ );
+ expect(shutdownCodexEnvironment).not.toHaveBeenCalled();
+ });
+
+ it('still shuts down Codex when only a transient boundary flips during restart', async () => {
+ const shutdownCodexEnvironment = vi.fn(async () => {});
+ let handleLive = true;
+ let boundaryPending = false;
+ await resetAccountProviderRuntimes(
+ {
+ restartCodex: async () => {
+ boundaryPending = true;
+ },
+ shutdownCodexEnvironment,
+ log: { warn: vi.fn() },
+ },
+ () => handleLive,
+ );
+ expect(boundaryPending).toBe(true);
+ expect(shutdownCodexEnvironment).toHaveBeenCalledOnce();
+ });
+});
+
+describe('discoverAccountProviderModels', () => {
+ it('does not start provider refresh after shouldContinue flips', async () => {
+ const refreshProviderModels = vi.fn(async () => {});
+ let allow = true;
+ await discoverAccountProviderModels(
+ {
+ loadXaiLkg: async () => {
+ allow = false;
+ return true;
+ },
+ refreshProviderModels,
+ log: { warn: vi.fn() },
+ },
+ () => allow,
+ );
+ expect(refreshProviderModels).not.toHaveBeenCalled();
+ });
+});
+
describe('refreshProviderModelsAfterAccountReady', () => {
it('keeps all account-scoped provider refreshes inside readiness', async () => {
const anthropicRefresh = deferred();
diff --git a/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessArm.test.ts b/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessArm.test.ts
new file mode 100644
index 0000000000..3d7b0e71b3
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessArm.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ createAccountProviderReadinessArmBinding,
+ shouldFirePendingReadinessStart,
+ shouldKeepPendingReadinessStart,
+} from '../account-provider-readiness-arm.js';
+
+describe('createAccountProviderReadinessArmBinding', () => {
+ it('starts only when the bound owner still matches', () => {
+ const start = vi.fn();
+ const arm = createAccountProviderReadinessArmBinding();
+ arm.publish('owner-a', start);
+
+ expect(arm.startIfOwnerMatches('owner-a')).toBe(true);
+ expect(start).toHaveBeenCalledOnce();
+
+ expect(arm.startIfOwnerMatches('owner-b')).toBe(false);
+ expect(start).toHaveBeenCalledOnce();
+ });
+
+ it('does not let a stale owner closure start after clear or owner change', () => {
+ const oldStart = vi.fn();
+ const newStart = vi.fn();
+ const arm = createAccountProviderReadinessArmBinding();
+ arm.publish('owner-a', oldStart);
+ arm.clear();
+
+ expect(arm.startIfOwnerMatches('owner-a')).toBe(false);
+ expect(oldStart).not.toHaveBeenCalled();
+
+ arm.publish('owner-a', oldStart);
+ arm.publish('owner-b', newStart);
+ expect(arm.startIfOwnerMatches('owner-b')).toBe(true);
+ expect(arm.startIfOwnerMatches('owner-a')).toBe(false);
+ expect(oldStart).not.toHaveBeenCalled();
+ expect(newStart).toHaveBeenCalledOnce();
+ });
+
+ it('resumes incomplete discovery only for the bound owner', async () => {
+ const resume = vi.fn(async () => {});
+ const arm = createAccountProviderReadinessArmBinding();
+ arm.publish('owner-a', vi.fn(), resume);
+
+ await expect(arm.resumeIncompleteIfOwnerMatches('owner-b')).resolves.toBe(false);
+ expect(resume).not.toHaveBeenCalled();
+ await expect(arm.resumeIncompleteIfOwnerMatches('owner-a')).resolves.toBe(true);
+ expect(resume).toHaveBeenCalledOnce();
+ arm.clear();
+ await expect(arm.resumeIncompleteIfOwnerMatches('owner-a')).resolves.toBe(false);
+ });
+});
+
+describe('shouldFirePendingReadinessStart', () => {
+ it('does not fire a leftover pending start after logout or owner change', () => {
+ expect(
+ shouldFirePendingReadinessStart({
+ pendingOwnerId: 'owner-a',
+ currentOwnerId: 'owner-a',
+ boundaryPending: false,
+ }),
+ ).toBe(true);
+ expect(
+ shouldFirePendingReadinessStart({
+ pendingOwnerId: 'owner-a',
+ currentOwnerId: null,
+ boundaryPending: false,
+ }),
+ ).toBe(false);
+ expect(
+ shouldFirePendingReadinessStart({
+ pendingOwnerId: 'owner-a',
+ currentOwnerId: 'owner-a',
+ boundaryPending: true,
+ }),
+ ).toBe(false);
+ });
+
+ it('keeps a same-owner pending start across a transient Ghost boundary', () => {
+ expect(
+ shouldKeepPendingReadinessStart({
+ pendingOwnerId: 'owner-a',
+ currentOwnerId: 'owner-a',
+ boundaryPending: true,
+ }),
+ ).toBe(true);
+ expect(
+ shouldKeepPendingReadinessStart({
+ pendingOwnerId: 'owner-a',
+ currentOwnerId: 'owner-a',
+ boundaryPending: false,
+ }),
+ ).toBe(false);
+ expect(
+ shouldKeepPendingReadinessStart({
+ pendingOwnerId: 'owner-a',
+ currentOwnerId: 'owner-b',
+ boundaryPending: true,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessBarrier.test.ts b/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessBarrier.test.ts
index 749b31abbb..f25c7748cb 100644
--- a/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessBarrier.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessBarrier.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it, vi } from 'vitest';
-import { createAccountProviderReadinessBarrier } from '../account-provider-readiness-barrier.js';
+import {
+ createAccountProviderReadinessBarrier,
+ isSameOwnerScopeKey,
+ ownerIdentityFromScopeKey,
+ shouldClearCatalogAfterJoiningPreviousScope,
+} from '../account-provider-readiness-barrier.js';
function deferred() {
let resolve!: () => void;
@@ -24,6 +29,7 @@ describe('createAccountProviderReadinessBarrier', () => {
await expect(barrier.waitForScope('cloud:owner-b:2')).resolves.toBe(false);
expect(scopeAReady).toBe(false);
+ barrier.markDiscoveryComplete();
task.resolve();
await vi.waitFor(() => expect(scopeAReady).toBe(true));
});
@@ -31,9 +37,23 @@ describe('createAccountProviderReadinessBarrier', () => {
it('fails closed before readiness has been registered for a scope', async () => {
const barrier = createAccountProviderReadinessBarrier();
+ expect(barrier.hasScope('cloud:owner-a:1')).toBe(false);
await expect(barrier.waitForScope('cloud:owner-a:1')).resolves.toBe(false);
});
+ it('tracks only the current readiness scope', () => {
+ const barrier = createAccountProviderReadinessBarrier();
+ barrier.start('cloud:owner-a:1', () => Promise.resolve(), vi.fn());
+
+ expect(barrier.hasScope('cloud:owner-a:1')).toBe(true);
+ expect(barrier.hasScope('cloud:owner-b:2')).toBe(false);
+ expect(barrier.hasSameOwnerIdentity('cloud:owner-a:3')).toBe(true);
+
+ barrier.start('cloud:owner-b:2', () => Promise.resolve(), vi.fn());
+ expect(barrier.hasScope('cloud:owner-a:1')).toBe(false);
+ expect(barrier.hasScope('cloud:owner-b:2')).toBe(true);
+ });
+
it('keeps a new scope behind the previous scope task, including the same owner relogin', async () => {
const task = deferred();
const barrier = createAccountProviderReadinessBarrier();
@@ -101,10 +121,186 @@ describe('createAccountProviderReadinessBarrier', () => {
await Promise.resolve();
expect(scopeBReady).toBe(false);
+ barrier.markDiscoveryComplete();
second.resolve();
await vi.waitFor(() => expect(scopeBReady).toBe(true));
});
+ it('clears the process catalog only after joining a different owner', () => {
+ expect(
+ shouldClearCatalogAfterJoiningPreviousScope({
+ waited: true,
+ currentSameOwnerAsNext: true,
+ }),
+ ).toBe(false);
+ expect(
+ shouldClearCatalogAfterJoiningPreviousScope({
+ waited: true,
+ currentSameOwnerAsNext: false,
+ }),
+ ).toBe(true);
+ expect(
+ shouldClearCatalogAfterJoiningPreviousScope({
+ waited: false,
+ currentSameOwnerAsNext: false,
+ }),
+ ).toBe(false);
+ });
+
+ it('parses owner identity from the app-session scope key format', () => {
+ expect(ownerIdentityFromScopeKey('cloud:owner-a:1')).toBe('cloud:owner-a');
+ expect(ownerIdentityFromScopeKey('cloud:owner-a:3')).toBe('cloud:owner-a');
+ expect(isSameOwnerScopeKey('cloud:owner-a:1', 'cloud:owner-a:3')).toBe(true);
+ expect(isSameOwnerScopeKey('cloud:owner-a:1', 'cloud:owner-b:2')).toBe(false);
+ });
+
+ it('adopts a deferred same-owner generation without starting another task', async () => {
+ const task = deferred();
+ const runTask = vi.fn(() => task.promise);
+ const barrier = createAccountProviderReadinessBarrier();
+ barrier.start('cloud:owner-a:1', runTask, vi.fn());
+ await vi.waitFor(() => expect(runTask).toHaveBeenCalledOnce());
+
+ const adopting = barrier.adoptSameOwnerAfterPreviousSettles('cloud:owner-a:3');
+ expect(barrier.hasScope('cloud:owner-a:3')).toBe(false);
+ expect(runTask).toHaveBeenCalledOnce();
+
+ barrier.markDiscoveryComplete();
+ task.resolve();
+ await expect(adopting).resolves.toBe(true);
+ expect(barrier.hasScope('cloud:owner-a:3')).toBe(true);
+ expect(barrier.hasScope('cloud:owner-a:1')).toBe(false);
+ expect(runTask).toHaveBeenCalledOnce();
+ await expect(barrier.waitForScope('cloud:owner-a:3')).resolves.toBe(true);
+ expect(barrier.start('cloud:owner-a:3', runTask, vi.fn())).toBeDefined();
+ expect(runTask).toHaveBeenCalledOnce();
+ });
+
+ it('does not let a late same-owner start replace an adopted generation', async () => {
+ const first = deferred();
+ const lateTask = vi.fn(() => Promise.resolve());
+ const barrier = createAccountProviderReadinessBarrier();
+ barrier.start('cloud:owner-a:1', () => first.promise, vi.fn());
+ const adopting = barrier.adoptSameOwnerAfterPreviousSettles('cloud:owner-a:3');
+
+ barrier.markDiscoveryComplete();
+ first.resolve();
+ await expect(adopting).resolves.toBe(true);
+ await expect(barrier.waitForScope('cloud:owner-a:1')).resolves.toBe(false);
+
+ barrier.start('cloud:owner-a:4', lateTask, vi.fn());
+ expect(lateTask).not.toHaveBeenCalled();
+ expect(barrier.hasScope('cloud:owner-a:3')).toBe(true);
+ await expect(barrier.waitForScope('cloud:owner-a:3')).resolves.toBe(true);
+ });
+
+ it('refuses to adopt a different owner onto the settled task', async () => {
+ const task = deferred();
+ const barrier = createAccountProviderReadinessBarrier();
+ barrier.start('cloud:owner-a:1', () => task.promise, vi.fn());
+
+ await expect(barrier.adoptSameOwnerAfterPreviousSettles('cloud:owner-b:2')).resolves.toBe(
+ false,
+ );
+ expect(barrier.hasScope('cloud:owner-a:1')).toBe(true);
+ task.resolve();
+ await task.promise;
+ });
+
+ it('refuses to adopt an incomplete or invalidated same-owner task', async () => {
+ const task = deferred();
+ const barrier = createAccountProviderReadinessBarrier();
+ barrier.start('cloud:owner-a:1', () => task.promise, vi.fn());
+ task.resolve();
+ await expect(barrier.adoptSameOwnerAfterPreviousSettles('cloud:owner-a:3')).resolves.toBe(
+ false,
+ );
+
+ barrier.markDiscoveryComplete();
+ await expect(barrier.adoptSameOwnerAfterPreviousSettles('cloud:owner-a:3')).resolves.toBe(
+ true,
+ );
+ barrier.invalidateAdoption();
+ await expect(barrier.adoptSameOwnerAfterPreviousSettles('cloud:owner-a:4')).resolves.toBe(
+ false,
+ );
+ });
+
+ it('identifies an adoptable entry that settled without completing discovery', async () => {
+ const task = deferred();
+ const barrier = createAccountProviderReadinessBarrier();
+ barrier.start('cloud:owner-a:1', () => task.promise, vi.fn());
+ task.resolve();
+ await task.promise;
+
+ expect(barrier.needsIncompleteDiscoveryResume('cloud:owner-a:3')).toBe(true);
+ expect(barrier.needsIncompleteDiscoveryResume('cloud:owner-b:2')).toBe(false);
+ barrier.invalidateAdoption();
+ expect(barrier.needsIncompleteDiscoveryResume('cloud:owner-a:3')).toBe(false);
+ });
+
+ it('does not let a replaced entry mark the next incarnation complete', async () => {
+ const firstWork = deferred();
+ const barrier = createAccountProviderReadinessBarrier();
+ const first = barrier.start(
+ 'cloud:owner-a:1',
+ async (handle) => {
+ await firstWork.promise;
+ handle.markDiscoveryComplete();
+ },
+ vi.fn(),
+ );
+
+ barrier.invalidateAdoption();
+ barrier.start('cloud:owner-a:5', async () => {}, vi.fn());
+ firstWork.resolve();
+ await first;
+
+ expect(barrier.hasScope('cloud:owner-a:5')).toBe(true);
+ expect(barrier.isDiscoveryComplete()).toBe(false);
+ expect(barrier.currentHandle()?.isLive()).toBe(true);
+ });
+
+ it('keeps a live handle across a same-owner generation bump until adopt', async () => {
+ const work = deferred();
+ const barrier = createAccountProviderReadinessBarrier();
+ let seenLiveAfterBump = false;
+ barrier.start(
+ 'cloud:owner-a:1',
+ async (handle) => {
+ await work.promise;
+ seenLiveAfterBump = handle.isLive();
+ handle.markDiscoveryComplete();
+ },
+ vi.fn(),
+ );
+ const handle = barrier.currentHandle();
+ expect(handle?.isLive()).toBe(true);
+ work.resolve();
+ await barrier.waitForPreviousScope('cloud:owner-a:3');
+ expect(seenLiveAfterBump).toBe(true);
+ await expect(barrier.adoptSameOwnerAfterPreviousSettles('cloud:owner-a:3')).resolves.toBe(
+ true,
+ );
+ expect(handle?.isLive()).toBe(false);
+ expect(barrier.currentHandle()?.isLive()).toBe(true);
+ });
+
+ it('starts a new task after teardown invalidates the previous incarnation', async () => {
+ const first = vi.fn(async () => {});
+ const second = vi.fn(async () => {});
+ const barrier = createAccountProviderReadinessBarrier();
+ barrier.start('cloud:owner-a:1', first, vi.fn());
+ await vi.waitFor(() => expect(first).toHaveBeenCalledOnce());
+ barrier.markDiscoveryComplete();
+ barrier.invalidateAdoption();
+
+ barrier.start('cloud:owner-a:5', second, vi.fn());
+ await vi.waitFor(() => expect(second).toHaveBeenCalledOnce());
+ expect(barrier.hasScope('cloud:owner-a:5')).toBe(true);
+ expect(barrier.hasAdoptableSameOwner('cloud:owner-a:5')).toBe(true);
+ });
+
it('fails a waiter whose scope was replaced before its task settled', async () => {
const first = deferred();
const second = deferred();
diff --git a/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessEnsure.test.ts b/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessEnsure.test.ts
new file mode 100644
index 0000000000..448d15f1b8
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessEnsure.test.ts
@@ -0,0 +1,140 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createAccountProviderReadinessArmBinding } from '../account-provider-readiness-arm.js';
+import { createAccountProviderReadinessBarrier } from '../account-provider-readiness-barrier.js';
+import {
+ ensureCurrentAccountProviderReadiness,
+ shouldStartReadinessConsumers,
+} from '../account-provider-readiness-ensure.js';
+
+function deferred() {
+ let resolve!: () => void;
+ const promise = new Promise<void>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+describe('ensureCurrentAccountProviderReadiness', () => {
+ it('starts a new incarnation after logout instead of adopting the pre-logout task', async () => {
+ const barrier = createAccountProviderReadinessBarrier();
+ const first = vi.fn(async () => {
+ barrier.markDiscoveryComplete();
+ });
+ const second = vi.fn(async () => {
+ barrier.markDiscoveryComplete();
+ });
+ const arm = createAccountProviderReadinessArmBinding();
+ arm.publish('owner-a', () => {
+ barrier.start('cloud:owner-a:5', second, vi.fn());
+ });
+
+ barrier.start('cloud:owner-a:1', first, vi.fn());
+ await vi.waitFor(() => expect(first).toHaveBeenCalledOnce());
+ barrier.invalidateAdoption();
+
+ const ready = await ensureCurrentAccountProviderReadiness({
+ barrier,
+ startIfOwnerMatches: (ownerId) => arm.startIfOwnerMatches(ownerId),
+ getScopeKey: () => 'cloud:owner-a:5',
+ getOwnerId: () => 'owner-a',
+ isBoundaryPending: () => false,
+ });
+
+ expect(ready).toBe(true);
+ expect(second).toHaveBeenCalledOnce();
+ expect(barrier.hasScope('cloud:owner-a:5')).toBe(true);
+ });
+
+ it('resumes incomplete same-owner discovery instead of launching a blocked full start', async () => {
+ const task = deferred();
+ const start = vi.fn(() => {
+ throw new Error('full start must not run while an adoptable same-owner entry exists');
+ });
+ const barrier = createAccountProviderReadinessBarrier();
+ barrier.start('cloud:owner-a:1', () => task.promise, vi.fn());
+ task.resolve();
+ await task.promise;
+
+ const resume = vi.fn(async () => {
+ expect(barrier.hasAdoptableSameOwner('cloud:owner-a:3')).toBe(true);
+ expect(barrier.isDiscoveryComplete()).toBe(false);
+ barrier.markDiscoveryComplete();
+ return true;
+ });
+
+ const ready = await ensureCurrentAccountProviderReadiness({
+ barrier,
+ startIfOwnerMatches: start,
+ resumeIncompleteDiscovery: resume,
+ getScopeKey: () => 'cloud:owner-a:3',
+ getOwnerId: () => 'owner-a',
+ isBoundaryPending: () => false,
+ });
+
+ expect(resume).toHaveBeenCalledOnce();
+ expect(start).not.toHaveBeenCalled();
+ expect(ready).toBe(true);
+ expect(barrier.hasScope('cloud:owner-a:3')).toBe(true);
+ });
+
+ it('notifies consumers once after a successful same-owner adopt', async () => {
+ const barrier = createAccountProviderReadinessBarrier();
+ const task = deferred();
+ barrier.start('cloud:owner-a:1', () => task.promise, vi.fn());
+ barrier.markDiscoveryComplete();
+ task.resolve();
+
+ const onReady = vi.fn();
+ const first = ensureCurrentAccountProviderReadiness({
+ barrier,
+ startIfOwnerMatches: vi.fn(),
+ getScopeKey: () => 'cloud:owner-a:3',
+ getOwnerId: () => 'owner-a',
+ isBoundaryPending: () => false,
+ onReady,
+ });
+ const second = ensureCurrentAccountProviderReadiness({
+ barrier,
+ startIfOwnerMatches: vi.fn(),
+ getScopeKey: () => 'cloud:owner-a:3',
+ getOwnerId: () => 'owner-a',
+ isBoundaryPending: () => false,
+ onReady,
+ });
+
+ await expect(first).resolves.toBe(true);
+ await expect(second).resolves.toBe(true);
+ expect(onReady).toHaveBeenCalledOnce();
+ expect(onReady).toHaveBeenCalledWith('owner-a');
+ });
+});
+
+describe('shouldStartReadinessConsumers', () => {
+ it('allows same-owner generation rollover and rejects a real owner change', () => {
+ expect(
+ shouldStartReadinessConsumers({
+ capturedScopeKey: 'cloud:owner-a:1',
+ currentScopeKey: 'cloud:owner-a:3',
+ boundaryPending: false,
+ adoptable: true,
+ }),
+ ).toBe(true);
+ expect(
+ shouldStartReadinessConsumers({
+ capturedScopeKey: 'cloud:owner-a:1',
+ currentScopeKey: 'cloud:owner-b:2',
+ boundaryPending: false,
+ adoptable: true,
+ }),
+ ).toBe(false);
+ expect(
+ shouldStartReadinessConsumers({
+ capturedScopeKey: 'cloud:owner-a:1',
+ currentScopeKey: 'cloud:owner-a:3',
+ boundaryPending: false,
+ adoptable: false,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessWiring.test.ts b/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessWiring.test.ts
index f32f862da7..620dc28b65 100644
--- a/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessWiring.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/accountProviderReadinessWiring.test.ts
@@ -50,7 +50,7 @@ describe('account provider readiness wiring', () => {
);
expect(bootstrapSource).not.toContain('await makerProviderRefreshConfigured');
expect(bootstrapSource).toContain(
- 'else startPendingAccountProviderReadiness = startProviderReadiness',
+ 'startPendingAccountProviderReadiness = { ownerId: userId, start: startProviderReadiness }',
);
const barrierStart = bootstrapSource.indexOf('accountProviderReadinessBarrier.start(');
@@ -67,17 +67,22 @@ describe('account provider readiness wiring', () => {
'await refreshCustomProvidersIntoCatalog(',
customMcpRefresh,
);
- const providerRefresh = bootstrapSource.indexOf(
- 'await refreshProviderModelsAfterAccountReady',
+ const runtimeReset = bootstrapSource.indexOf(
+ 'await resetAccountProviderRuntimes(',
customProviderRefresh,
);
+ const providerRefresh = bootstrapSource.indexOf(
+ 'await discoverAccountProviderModels(',
+ runtimeReset,
+ );
const piShutdown = bootstrapSource.indexOf('await shutdownPiEnvironment()', providerRefresh);
expect(makerRecreated).toBeGreaterThanOrEqual(0);
expect(initialMcpRefresh).toBeGreaterThan(makerRecreated);
expect(customMcpRefresh).toBeGreaterThan(initialMcpRefresh);
expect(customProviderRefresh).toBeGreaterThan(customMcpRefresh);
- expect(providerRefresh).toBeGreaterThan(customProviderRefresh);
+ expect(runtimeReset).toBeGreaterThan(customProviderRefresh);
+ expect(providerRefresh).toBeGreaterThan(runtimeReset);
expect(piShutdown).toBeGreaterThan(providerRefresh);
});
@@ -113,7 +118,7 @@ describe('account provider readiness wiring', () => {
const prepareStartOptions = makerHostSource.indexOf('prepareStartOptions: async');
const hostGate = makerHostSource.indexOf(
- 'await accountProviderReadinessBarrier.waitForScope(providerScopeKey)',
+ 'await ensureCurrentAccountProviderReadiness()',
prepareStartOptions,
);
const failClosed = makerHostSource.indexOf('!providerReady', hostGate);
@@ -126,6 +131,53 @@ describe('account provider readiness wiring', () => {
expect(persistedOrca).toBeGreaterThan(hostGate);
});
+ it('adopts same-owner generation rollover instead of restarting account-switch discovery', () => {
+ const waitFn = bootstrapSource.indexOf(
+ 'async function waitForCurrentAccountProviderModelsReady',
+ );
+ expect(waitFn).toBeGreaterThanOrEqual(0);
+ expect(
+ bootstrapSource.indexOf('ensureCurrentAccountProviderReadiness()', waitFn),
+ ).toBeGreaterThan(waitFn);
+
+ const unchanged = bootstrapSource.indexOf("dbClientTakeover.mode === 'unchanged'");
+ const unchangedEnsure = bootstrapSource.indexOf(
+ 'ensureCurrentAccountProviderReadiness()',
+ unchanged,
+ );
+ const unchangedReturn = bootstrapSource.indexOf('return;', unchangedEnsure);
+ expect(unchanged).toBeGreaterThanOrEqual(0);
+ expect(unchangedEnsure).toBeGreaterThan(unchanged);
+ expect(unchangedReturn).toBeGreaterThan(unchangedEnsure);
+ expect(bootstrapSource).toContain('shouldKeepPendingReadinessStart');
+ expect(bootstrapSource).toContain('shouldClearCatalogAfterJoiningPreviousScope');
+ expect(bootstrapSource).toMatch(
+ /handle\.isLive\(\)\s*&&\s*accountProviderReadinessBarrier\.isCurrentAdoptable\(\)/,
+ );
+
+ expect(bootstrapSource).toContain(
+ 'accountProviderReadinessArm.publish(userId, startProviderReadiness, resumeIncompleteDiscovery)',
+ );
+ expect(bootstrapSource).toContain('accountProviderReadinessArm.clear()');
+ expect(bootstrapSource).toContain('startPendingAccountProviderReadiness = null');
+ expect(bootstrapSource).toContain('invalidateAdoption()');
+ expect(bootstrapSource).toContain('needsIncompleteDiscoveryResume');
+ expect(bootstrapSource).toContain('shouldFirePendingReadinessStart');
+ expect(bootstrapSource).toContain('handle.isLive()');
+ expect(bootstrapSource).toContain('const entryStillLive = () => handle.isLive();');
+ expect(bootstrapSource).toContain(
+ 'handle.isLive() && accountProviderReadinessBarrier.isCurrentAdoptable()',
+ );
+ expect(bootstrapSource).not.toContain(
+ 'handle.isLive() && !isAppSessionBoundaryPending()',
+ );
+ expect(bootstrapSource).toContain('handle.markDiscoveryComplete()');
+ expect(bootstrapSource).toContain('startedHandle?.isLive()');
+ expect(bootstrapSource).toContain('markDiscoveryComplete()');
+ expect(bootstrapSource).toContain('discoverAccountProviderModels(');
+ expect(bootstrapSource).toContain('resetAccountProviderRuntimes(');
+ });
+
it('starts autonomous route consumers only after provider readiness settles', () => {
const settledContinuation = bootstrapSource.indexOf('void providerReadiness.then(() =>');
const integrations = bootstrapSource.indexOf(
@@ -149,7 +201,7 @@ describe('account provider readiness wiring', () => {
makerShutdown,
);
const clearAfterJoin = bootstrapSource.indexOf(
- 'if (previousProviderTaskSettled) setCustomProviders([])',
+ 'shouldClearCatalogAfterJoiningPreviousScope(',
joinPrevious,
);
diff --git a/apps/desktop/src/main/maker-host/account-provider-model-refresh.ts b/apps/desktop/src/main/maker-host/account-provider-model-refresh.ts
index f1230f81b0..366d80f3ff 100644
--- a/apps/desktop/src/main/maker-host/account-provider-model-refresh.ts
+++ b/apps/desktop/src/main/maker-host/account-provider-model-refresh.ts
@@ -27,9 +27,14 @@ export interface AccountProviderModelRefreshDeps {
* 刷新且纳入同一账号 barrier,防止切号后旧账号的迟到结果覆盖全局目录;各步骤保持
* best-effort,失败会留日志,不会把可用的本地 DB 误判成初始化失败。
*/
-export async function refreshProviderModelsAfterAccountReady(
- deps: AccountProviderModelRefreshDeps,
+export async function resetAccountProviderRuntimes(
+ deps: Pick<
+ AccountProviderModelRefreshDeps,
+ 'restartCodex' | 'shutdownCodexEnvironment' | 'log'
+ >,
+ shouldContinue: () => boolean = () => true,
): Promise<void> {
+ if (!shouldContinue()) return;
let codexRestarted = false;
try {
await deps.restartCodex();
@@ -40,16 +45,21 @@ export async function refreshProviderModelsAfterAccountReady(
});
}
- if (codexRestarted) {
- try {
- await deps.shutdownCodexEnvironment();
- } catch (error) {
- deps.log.warn('shutdownCodexEnvironment on account switch failed', {
- error: error instanceof Error ? error.message : String(error),
- });
- }
+ if (!shouldContinue() || !codexRestarted) return;
+ try {
+ await deps.shutdownCodexEnvironment();
+ } catch (error) {
+ deps.log.warn('shutdownCodexEnvironment on account switch failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
}
+}
+export async function discoverAccountProviderModels(
+ deps: Pick<AccountProviderModelRefreshDeps, 'loadXaiLkg' | 'refreshProviderModels' | 'log'>,
+ shouldContinue: () => boolean = () => true,
+): Promise<void> {
+ if (!shouldContinue()) return;
try {
// Account readiness is also the owner boundary. Restore this owner's authoritative xAI LKG
// before the HTTP refresh so an offline/timeout result never exposes the generic fallback in
@@ -61,6 +71,8 @@ export async function refreshProviderModelsAfterAccountReady(
});
}
+ if (!shouldContinue()) return;
+
const backgroundRefresh = deps
.refreshProviderModels('startup', ['xd', 'openai', 'xai'])
.catch((error) => {
@@ -77,3 +89,10 @@ export async function refreshProviderModelsAfterAccountReady(
await Promise.all([backgroundRefresh, anthropicRefresh]);
}
+
+export async function refreshProviderModelsAfterAccountReady(
+ deps: AccountProviderModelRefreshDeps,
+): Promise<void> {
+ await resetAccountProviderRuntimes(deps);
+ await discoverAccountProviderModels(deps);
+}
diff --git a/apps/desktop/src/main/maker-host/account-provider-readiness-arm.ts b/apps/desktop/src/main/maker-host/account-provider-readiness-arm.ts
new file mode 100644
index 0000000000..4527378cbc
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/account-provider-readiness-arm.ts
@@ -0,0 +1,65 @@
+export interface AccountProviderReadinessArmBinding {
+ publish(ownerId: string, start: () => void, resume?: () => Promise<void>): void;
+ clear(): void;
+ startIfOwnerMatches(currentOwnerId: string | null): boolean;
+ resumeIncompleteIfOwnerMatches(currentOwnerId: string | null): Promise<boolean>;
+}
+
+/**
+ * Process-local handle for the latest owner-db start() closure.
+ * Real account switches must clear() during teardown so a stale closure cannot
+ * start discovery for the next owner. Same-owner generation rollover keeps the
+ * binding and must not call start() — adopt the settled barrier instead.
+ */
+export function createAccountProviderReadinessArmBinding(): AccountProviderReadinessArmBinding {
+ let bound: { ownerId: string; start: () => void; resume?: () => Promise<void> } | null =
+ null;
+
+ return {
+ publish(ownerId, start, resume) {
+ bound = { ownerId, start, resume };
+ },
+ clear() {
+ bound = null;
+ },
+ startIfOwnerMatches(currentOwnerId) {
+ if (!bound || !currentOwnerId || bound.ownerId !== currentOwnerId) return false;
+ bound.start();
+ return true;
+ },
+ async resumeIncompleteIfOwnerMatches(currentOwnerId) {
+ if (!bound?.resume || !currentOwnerId || bound.ownerId !== currentOwnerId) return false;
+ await bound.resume();
+ return true;
+ },
+ };
+}
+
+export function shouldFirePendingReadinessStart(opts: {
+ pendingOwnerId: string | null;
+ currentOwnerId: string | null;
+ boundaryPending: boolean;
+}): boolean {
+ return Boolean(
+ opts.pendingOwnerId &&
+ opts.currentOwnerId &&
+ opts.pendingOwnerId === opts.currentOwnerId &&
+ !opts.boundaryPending,
+ );
+}
+
+/** Keep the one-shot pending start across a same-owner Ghost repair window. */
+export function shouldKeepPendingReadinessStart(opts: {
+ pendingOwnerId: string | null;
+ currentOwnerId: string | null;
+ boundaryPending: boolean;
+}): boolean {
+ return Boolean(
+ opts.boundaryPending &&
+ opts.pendingOwnerId &&
+ opts.currentOwnerId &&
+ opts.pendingOwnerId === opts.currentOwnerId,
+ );
+}
+
+export const accountProviderReadinessArm = createAccountProviderReadinessArmBinding();
diff --git a/apps/desktop/src/main/maker-host/account-provider-readiness-barrier.ts b/apps/desktop/src/main/maker-host/account-provider-readiness-barrier.ts
index 06250995a2..d630324751 100644
--- a/apps/desktop/src/main/maker-host/account-provider-readiness-barrier.ts
+++ b/apps/desktop/src/main/maker-host/account-provider-readiness-barrier.ts
@@ -5,20 +5,140 @@
* create or send to an agent waits for the current app-session scope. A new generation
* also waits for the previous scope before replacing the DB, so detached refresh work
* cannot write account-scoped catalog state after the ownership boundary has moved on.
+ *
+ * Same-owner generation rollover is not an account switch: adopt a *completed*
+ * discovery task onto the new key. A real teardown invalidates adoption so
+ * A → signed-out → A cannot reuse the pre-logout catalog, while the old
+ * promise remains joinable for waitForPreviousScope.
*/
+
+/** Matches `activeOwnerScopeKey()`: `${mode}:${dataOwnerId ?? 'none'}:${generation}`. */
+export function ownerIdentityFromScopeKey(scopeKey: string): string {
+ const lastColon = scopeKey.lastIndexOf(':');
+ return lastColon === -1 ? scopeKey : scopeKey.slice(0, lastColon);
+}
+
+export function isSameOwnerScopeKey(left: string, right: string): boolean {
+ return ownerIdentityFromScopeKey(left) === ownerIdentityFromScopeKey(right);
+}
+
+/** Clear the process catalog only after joining a *different owner*, not a generation bump. */
+export function shouldClearCatalogAfterJoiningPreviousScope(opts: {
+ waited: boolean;
+ currentSameOwnerAsNext: boolean;
+}): boolean {
+ return opts.waited && !opts.currentSameOwnerAsNext;
+}
+
+interface ReadinessEntry {
+ scopeKey: string;
+ promise: Promise<void>;
+ adoptable: boolean;
+ discoveryComplete: boolean;
+ consumersStarted: boolean;
+}
+
+export interface AccountProviderReadinessHandle {
+ readonly scopeKey: string;
+ isLive(): boolean;
+ markDiscoveryComplete(): boolean;
+}
+
+export type AccountProviderReadinessBarrier = ReturnType<
+ typeof createAccountProviderReadinessBarrier
+>;
+
+function createHandle(
+ readCurrent: () => ReadinessEntry | null,
+ entry: ReadinessEntry,
+): AccountProviderReadinessHandle {
+ return {
+ get scopeKey() {
+ return entry.scopeKey;
+ },
+ isLive() {
+ return readCurrent() === entry;
+ },
+ markDiscoveryComplete() {
+ if (readCurrent() !== entry) return false;
+ entry.discoveryComplete = true;
+ return true;
+ },
+ };
+}
+
export function createAccountProviderReadinessBarrier() {
- let current: { scopeKey: string; promise: Promise<void> } | null = null;
+ let current: ReadinessEntry | null = null;
return {
+ hasScope(scopeKey: string): boolean {
+ return current?.scopeKey === scopeKey;
+ },
+
+ hasSameOwnerIdentity(scopeKey: string): boolean {
+ return current != null && isSameOwnerScopeKey(current.scopeKey, scopeKey);
+ },
+
+ hasAdoptableSameOwner(scopeKey: string): boolean {
+ return current?.adoptable === true && isSameOwnerScopeKey(current.scopeKey, scopeKey);
+ },
+
+ isCurrentAdoptable(): boolean {
+ return current?.adoptable === true;
+ },
+
+ isDiscoveryComplete(): boolean {
+ return current?.discoveryComplete === true;
+ },
+
+ needsIncompleteDiscoveryResume(scopeKey: string): boolean {
+ return (
+ current?.adoptable === true &&
+ current.discoveryComplete === false &&
+ isSameOwnerScopeKey(current.scopeKey, scopeKey)
+ );
+ },
+
+ invalidateAdoption(): void {
+ if (current) current.adoptable = false;
+ },
+
+ currentHandle(): AccountProviderReadinessHandle | null {
+ return current ? createHandle(() => current, current) : null;
+ },
+
+ markDiscoveryComplete(): void {
+ if (current) current.discoveryComplete = true;
+ },
+
+ markConsumersStarted(): boolean {
+ if (!current || current.consumersStarted) return false;
+ current.consumersStarted = true;
+ return true;
+ },
+
start(
scopeKey: string,
- task: () => Promise<void>,
+ task: (handle: AccountProviderReadinessHandle) => Promise<void>,
onError: (error: unknown) => void,
): Promise<void> {
if (current?.scopeKey === scopeKey) return current.promise;
+ // Only suppress a second task while this owner incarnation is still live.
+ // After a real teardown, adoptable is false so A → signed-out → A starts fresh.
+ if (current?.adoptable && isSameOwnerScopeKey(current.scopeKey, scopeKey)) {
+ return current.promise;
+ }
- const promise = Promise.resolve()
- .then(task)
+ const entry: ReadinessEntry = {
+ scopeKey,
+ promise: Promise.resolve(),
+ adoptable: true,
+ discoveryComplete: false,
+ consumersStarted: false,
+ };
+ const handle = createHandle(() => current, entry);
+ entry.promise = Promise.resolve()
+ .then(() => task(handle))
.catch((error) => {
try {
onError(error);
@@ -26,15 +146,15 @@ export function createAccountProviderReadinessBarrier() {
// The barrier must always settle: logging failure cannot block future owners.
}
});
- current = { scopeKey, promise };
- return promise;
+ current = entry;
+ return entry.promise;
},
async waitForScope(scopeKey: string): Promise<boolean> {
const snapshot = current;
if (snapshot?.scopeKey !== scopeKey) return false;
await snapshot.promise;
- return current === snapshot;
+ return current === snapshot && snapshot.discoveryComplete;
},
async waitForPreviousScope(nextScopeKey: string): Promise<boolean> {
@@ -47,6 +167,30 @@ export function createAccountProviderReadinessBarrier() {
}
return waited;
},
+
+ async adoptSameOwnerAfterPreviousSettles(nextScopeKey: string): Promise<boolean> {
+ if (current?.scopeKey === nextScopeKey) {
+ const snapshot = current;
+ await snapshot.promise;
+ return current === snapshot && snapshot.adoptable && snapshot.discoveryComplete;
+ }
+ if (!current?.adoptable || !isSameOwnerScopeKey(current.scopeKey, nextScopeKey)) {
+ return false;
+ }
+ const snapshot = current;
+ await snapshot.promise;
+ if (current !== snapshot || !snapshot.adoptable || !snapshot.discoveryComplete) {
+ return false;
+ }
+ current = {
+ scopeKey: nextScopeKey,
+ promise: snapshot.promise,
+ adoptable: snapshot.adoptable,
+ discoveryComplete: snapshot.discoveryComplete,
+ consumersStarted: snapshot.consumersStarted,
+ };
+ return true;
+ },
};
}
diff --git a/apps/desktop/src/main/maker-host/account-provider-readiness-ensure.ts b/apps/desktop/src/main/maker-host/account-provider-readiness-ensure.ts
new file mode 100644
index 0000000000..1bdee162c7
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/account-provider-readiness-ensure.ts
@@ -0,0 +1,77 @@
+import { activeOwnerScopeKey, getActiveAppSession, isAppSessionBoundaryPending } from '../appSessionState.js';
+import { accountProviderReadinessArm } from './account-provider-readiness-arm.js';
+import {
+ accountProviderReadinessBarrier,
+ isSameOwnerScopeKey,
+ type AccountProviderReadinessBarrier,
+} from './account-provider-readiness-barrier.js';
+
+export interface EnsureAccountProviderReadinessDeps {
+ barrier: AccountProviderReadinessBarrier;
+ startIfOwnerMatches(ownerId: string | null): boolean;
+ resumeIncompleteDiscovery?(ownerId: string | null): Promise<boolean>;
+ getScopeKey(): string;
+ getOwnerId(): string | null;
+ isBoundaryPending(): boolean;
+ onReady?(ownerId: string): void;
+}
+
+let readyHandler: ((ownerId: string) => void) | undefined;
+
+export function setAccountProviderReadinessReadyHandler(
+ handler: ((ownerId: string) => void) | undefined,
+): void {
+ readyHandler = handler;
+}
+
+const defaultDeps: EnsureAccountProviderReadinessDeps = {
+ barrier: accountProviderReadinessBarrier,
+ startIfOwnerMatches: (ownerId) => accountProviderReadinessArm.startIfOwnerMatches(ownerId),
+ resumeIncompleteDiscovery: (ownerId) =>
+ accountProviderReadinessArm.resumeIncompleteIfOwnerMatches(ownerId),
+ getScopeKey: activeOwnerScopeKey,
+ getOwnerId: () => getActiveAppSession().dataOwnerId,
+ isBoundaryPending: isAppSessionBoundaryPending,
+};
+
+/**
+ * Adopt a completed same-owner discovery task, or start one for this owner
+ * incarnation. Shared by renderer send/create and the Maker start hook.
+ */
+export async function ensureCurrentAccountProviderReadiness(
+ deps: EnsureAccountProviderReadinessDeps = defaultDeps,
+): Promise<boolean> {
+ const scopeKey = deps.getScopeKey();
+ const ownerId = deps.getOwnerId();
+ if (!ownerId || deps.isBoundaryPending()) return false;
+
+ let adopted = await deps.barrier.adoptSameOwnerAfterPreviousSettles(scopeKey);
+ if (deps.barrier.needsIncompleteDiscoveryResume(scopeKey)) {
+ await deps.resumeIncompleteDiscovery?.(ownerId);
+ adopted = await deps.barrier.adoptSameOwnerAfterPreviousSettles(scopeKey);
+ } else if (!adopted && !deps.barrier.hasScope(scopeKey)) {
+ deps.startIfOwnerMatches(ownerId);
+ }
+
+ const ready = await deps.barrier.waitForScope(scopeKey);
+ if (!ready || deps.getScopeKey() !== scopeKey || deps.isBoundaryPending()) {
+ return false;
+ }
+ if (deps.barrier.markConsumersStarted()) {
+ (deps.onReady ?? readyHandler)?.(ownerId);
+ }
+ return true;
+}
+
+export function shouldStartReadinessConsumers(opts: {
+ capturedScopeKey: string;
+ currentScopeKey: string;
+ boundaryPending: boolean;
+ adoptable: boolean;
+}): boolean {
+ return (
+ opts.adoptable &&
+ !opts.boundaryPending &&
+ isSameOwnerScopeKey(opts.capturedScopeKey, opts.currentScopeKey)
+ );
+}
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 0c85acdf63..c97737d035 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -135,7 +135,7 @@ import {
AUTO_REVIEW_ROUTER_GUARD_TIMEOUT_MS,
createAutoReviewModelRouter,
} from './auto-review-model-router.js';
-import { accountProviderReadinessBarrier } from './account-provider-readiness-barrier.js';
+import { ensureCurrentAccountProviderReadiness } from './account-provider-readiness-ensure.js';
import { hasClaudeAiOAuth } from './claude-credentials-store.js';
import {
armCodexHttpRecovery,
@@ -1941,14 +1941,8 @@ export function getMaker(): Maker {
// 启动前的 Skill 共享与关闭后的清理都由 desktop host 注入。
lifecycleHooks: {
prepareStartOptions: async (sessionId, opts) => {
- const providerScopeKey = activeOwnerScopeKey();
- const providerReady =
- await accountProviderReadinessBarrier.waitForScope(providerScopeKey);
- if (
- !providerReady ||
- activeOwnerScopeKey() !== providerScopeKey ||
- isAppSessionBoundaryPending()
- ) {
+ const providerReady = await ensureCurrentAccountProviderReadiness();
+ if (!providerReady) {
throw new Error('Account provider models are not ready for this app session; retry.');
}
await preparePersistedOrcaSessionStart(sessionId, opts as MakerSessionCreateOpts);