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): make plugin migration retries owner-stable

Yuewei-LLf378d4d475c2
diff --git a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts
index e46db193c9..8da9debb17 100644
--- a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts
+++ b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts
@@ -1910,6 +1910,35 @@ describe('legacy Ghost plugin recovery', () => {
).toEqual({ state: 'partial', legacyPluginCount: 1, canRetry: true });
});
+ it('recovers fresh legacy plugins in the same pass when the marker only contains reserved ids', async () => {
+ const root = await tempRoot();
+ const ownerId = 'cloud-a';
+ const ownerKey = dataOwnerStorageKey(ownerId);
+ const markerPath = path.join(
+ root,
+ 'owners',
+ ownerKey,
+ __testing.LEGACY_GHOST_RECOVERY_MARKER,
+ );
+ await fs.mkdir(path.dirname(markerPath), { recursive: true });
+ await fs.writeFile(markerPath, JSON.stringify({
+ version: 2,
+ ownerKey,
+ pendingIds: ['cindy-reserved'],
+ failedIds: ['cindy-reserved'],
+ approvalProjectionSha256ById: { 'cindy-reserved': 'a'.repeat(64) },
+ }));
+ await writeGhostDir(root, 'brain', 'later-plugin');
+
+ await expect(
+ recoverLegacyGhostPlugins(
+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },
+ realFsDeps(root),
+ { rejectReservedIds: true },
+ ),
+ ).resolves.toMatchObject({ status: 'migrated', moved: 1, recoveredIds: ['later-plugin'] });
+ });
+
it('moves builtin provisioning state with plugins before reconciliation', async () => {
const root = await tempRoot();
const ownerId = 'cloud-a';
diff --git a/apps/desktop/src/main/__tests__/stableOwnerPostCommit.test.ts b/apps/desktop/src/main/__tests__/stableOwnerPostCommit.test.ts
new file mode 100644
index 0000000000..55f14930b9
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/stableOwnerPostCommit.test.ts
@@ -0,0 +1,130 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { StableOwnerPostCommitCoordinator } from '../stableOwnerPostCommit';
+
+describe('StableOwnerPostCommitCoordinator', () => {
+ it('defers without consuming the scope until its owner boundary is stable', async () => {
+ let stable = false;
+ const task = vi.fn().mockResolvedValue('completed');
+ const coordinator = new StableOwnerPostCommitCoordinator({
+ snapshot: () => ({ scopeKey: 'local:owner:1', dataOwnerId: 'owner', stable }),
+ warn: vi.fn(),
+ });
+ coordinator.setTask(task);
+
+ await expect(coordinator.ensure('early')).resolves.toBe('deferred');
+ expect(task).not.toHaveBeenCalled();
+
+ stable = true;
+ await expect(coordinator.ensure('stable')).resolves.toBe('completed');
+ expect(task).toHaveBeenCalledTimes(1);
+ });
+
+ it('deduplicates concurrent work and memoizes only a completed owner scope', async () => {
+ let resolveTask!: (value: 'completed') => void;
+ const task = vi.fn(() => new Promise<'completed'>((resolve) => {
+ resolveTask = resolve;
+ }));
+ const coordinator = new StableOwnerPostCommitCoordinator({
+ snapshot: () => ({ scopeKey: 'local:owner:1', dataOwnerId: 'owner', stable: true }),
+ warn: vi.fn(),
+ });
+ coordinator.setTask(task);
+
+ const first = coordinator.ensure('first');
+ const second = coordinator.ensure('second');
+ await vi.waitFor(() => expect(resolveTask).toBeTypeOf('function'));
+ resolveTask('completed');
+
+ await expect(Promise.all([first, second])).resolves.toEqual(['completed', 'completed']);
+ await expect(coordinator.ensure('later')).resolves.toBe('completed');
+ expect(task).toHaveBeenCalledTimes(1);
+ });
+
+ it('retries deferred and failed passes instead of caching false success', async () => {
+ const task = vi
+ .fn()
+ .mockResolvedValueOnce('deferred')
+ .mockRejectedValueOnce(new Error('disk busy'))
+ .mockResolvedValueOnce('completed');
+ const warn = vi.fn();
+ const coordinator = new StableOwnerPostCommitCoordinator({
+ snapshot: () => ({ scopeKey: 'local:owner:1', dataOwnerId: 'owner', stable: true }),
+ warn,
+ });
+ coordinator.setTask(task);
+
+ await expect(coordinator.ensure('deferred')).resolves.toBe('deferred');
+ await expect(coordinator.ensure('failed')).resolves.toBe('failed');
+ await expect(coordinator.ensure('retry')).resolves.toBe('completed');
+ expect(task).toHaveBeenCalledTimes(3);
+ expect(warn).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not complete a stale scope when the owner changes during the task', async () => {
+ let scopeKey = 'local:owner:1';
+ const task = vi.fn(async () => {
+ scopeKey = 'cloud:other:2';
+ return 'completed' as const;
+ });
+ const coordinator = new StableOwnerPostCommitCoordinator({
+ snapshot: () => ({ scopeKey, dataOwnerId: scopeKey.includes('other') ? 'other' : 'owner', stable: true }),
+ warn: vi.fn(),
+ });
+ coordinator.setTask(task);
+
+ await expect(coordinator.ensure('owner-change')).resolves.toBe('deferred');
+ });
+
+ it('automatically retries a failed stable scope without another external ensure', async () => {
+ const scheduled: Array<() => void> = [];
+ const task = vi
+ .fn()
+ .mockResolvedValueOnce('failed')
+ .mockResolvedValueOnce('completed');
+ const coordinator = new StableOwnerPostCommitCoordinator({
+ snapshot: () => ({ scopeKey: 'local:owner:1', dataOwnerId: 'owner', stable: true }),
+ warn: vi.fn(),
+ retryDelaysMs: [1],
+ scheduleRetry: (callback) => {
+ scheduled.push(callback);
+ return callback;
+ },
+ cancelRetry: vi.fn(),
+ });
+ coordinator.setTask(task);
+
+ await expect(coordinator.ensure('initial')).resolves.toBe('failed');
+ expect(scheduled).toHaveLength(1);
+ scheduled.shift()?.();
+ await vi.waitFor(() => expect(task).toHaveBeenCalledTimes(2));
+ await expect(coordinator.ensure('after-retry')).resolves.toBe('completed');
+ });
+
+ it('drops a scheduled retry when the owner scope changes', async () => {
+ let scopeKey = 'local:owner:1';
+ const scheduled: Array<() => void> = [];
+ const task = vi.fn().mockResolvedValue('failed');
+ const coordinator = new StableOwnerPostCommitCoordinator({
+ snapshot: () => ({
+ scopeKey,
+ dataOwnerId: scopeKey.includes('other') ? 'other' : 'owner',
+ stable: true,
+ }),
+ warn: vi.fn(),
+ retryDelaysMs: [1],
+ scheduleRetry: (callback) => {
+ scheduled.push(callback);
+ return callback;
+ },
+ cancelRetry: vi.fn(),
+ });
+ coordinator.setTask(task);
+
+ await expect(coordinator.ensure('initial')).resolves.toBe('failed');
+ scopeKey = 'cloud:other:2';
+ scheduled.shift()?.();
+ await Promise.resolve();
+ expect(task).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index f5e4895e09..62b0369240 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -93,6 +93,7 @@ import {
type DesktopLoginActionResult,
} from '../shared/authIpc';
import {
+ activeOwnerScopeKey,
beginAppSessionBoundary,
commitActiveAppSession,
commitVolatileAppSession,
@@ -108,6 +109,10 @@ import {
} from './ownerNamespaceMigration.js';
import { buildSafeStorageIssueMeta } from './safeStorageIssueLog.js';
import { createCredentialStoreHealth } from './authCredentialStoreHealth';
+import {
+ StableOwnerPostCommitCoordinator,
+ type StableOwnerPostCommitTask,
+} from './stableOwnerPostCommit.js';
const log = createLogger('authManager');
@@ -249,6 +254,31 @@ let accountSwitchTeardown: AccountSwitchTeardown | null = null;
let authSessionTeardown: AuthSessionTeardown | null = null;
let projectionRepairTeardown: ProjectionRepairTeardown | null = null;
+const stableOwnerPostCommitCoordinator = new StableOwnerPostCommitCoordinator({
+ snapshot: () => {
+ const session = getActiveAppSession();
+ return {
+ scopeKey: activeOwnerScopeKey(),
+ dataOwnerId: session.dataOwnerId,
+ stable:
+ session.dataOwnerId !== null
+ && !isAppSessionBoundaryPending()
+ && isGhostSkillProjectionBoundaryStableForOwner(session.dataOwnerId),
+ };
+ },
+ warn: (message, meta) => log.warn(message, meta),
+});
+
+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;
@@ -823,8 +853,10 @@ async function withCloudOwnerCommit<T>(opts: {
// captured the pre-repair scope key would then pass the post-release guard.
// Force a generation bump so the scope key changes across the teardown.
let forceBumpGeneration = false;
+ let result!: T;
+ let committed = false;
try {
- return await withGhostSkillProjectionOwnerCommit({
+ result = await withGhostSkillProjectionOwnerCommit({
previousOwnerId: opts.previousOwnerId,
nextOwnerId: opts.nextOwnerId,
prepareTransition: async ({ ownerChanged }) => {
@@ -852,11 +884,14 @@ async function withCloudOwnerCommit<T>(opts: {
return result;
},
});
+ committed = true;
} finally {
const release = releaseBoundary as (() => void) | null;
release?.();
if (release) notifyRenderer();
}
+ if (committed) requestStableOwnerPostCommit('owner-commit');
+ return result;
}
/**
@@ -989,6 +1024,7 @@ async function withAccountFreeOwnerCommit(opts: {
if (release && notify) notifyRenderer();
}
+ requestStableOwnerPostCommit('owner-commit');
if (notify) {
notifyRenderer();
notifyAuthListeners();
@@ -1008,6 +1044,7 @@ async function recoverAccountFreeOwnerAtStartup(
commitActiveAppSession(mode);
}
}
+ await ensureStableOwnerPostCommit('owner-already-stable');
return;
}
await withAccountFreeOwnerCommit({
@@ -1044,6 +1081,16 @@ export function setProjectionRepairTeardown(teardown: ProjectionRepairTeardown |
projectionRepairTeardown = teardown;
}
+/** Register the owner-scoped work that must settle after the durable boundary is stable. */
+export function setStableOwnerPostCommitTask(task: StableOwnerPostCommitTask | null): void {
+ 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),
@@ -2260,6 +2307,7 @@ export async function initialize(options: AuthInitializeOptions = {}): Promise<A
} else {
commitCloudAppSession(currentUser.id);
}
+ await ensureStableOwnerPostCommit('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 b188b5603a..cbff691984 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -759,6 +759,7 @@ import {
reconcileGhostOauthAccountsForActiveOwner,
refreshGhostLocalization,
registerGhostIpc,
+ runStableOwnerPostCommitTask,
setGhostsChangedObserver,
suspendAllGhosts,
waitForGhostMutations,
@@ -1739,6 +1740,29 @@ setCodexImageAuthBinding({
});
registerGhostIpc();
registerPluginMarketIpc();
+authManager.setStableOwnerPostCommitTask(async ({ reason }) => {
+ const builtinOutcome = await runStableOwnerPostCommitTask(reason);
+ if (builtinOutcome === 'deferred') return builtinOutcome;
+
+ let needsRetry = builtinOutcome === 'retry-pending' || builtinOutcome === 'failed';
+ let deferred = false;
+ const marketOutcome = await syncDefaultMarketPlugins();
+ if (marketOutcome === 'failed') needsRetry = true;
+ if (marketOutcome === 'deferred') deferred = true;
+
+ try {
+ 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 needsRetry ? 'failed' : deferred ? 'deferred' : 'completed';
+});
// ── Custom protocol registration (image-local-cache M2) ──────────────────
// MUST run before app.whenReady(), and MUST be a SINGLE call:
@@ -3121,29 +3145,6 @@ const createWindow = () => {
let disposeSkillhubAutoSyncAuthListener: (() => void) | null = null;
let disposeProviderAccessAuthListener: (() => void) | null = null;
-let disposePluginMarketAuthListener: (() => void) | null = null;
-let defaultPluginSyncInFlightScope: string | null = null;
-
-/** Run the existing market reconciliation once for each stable app owner. */
-function syncDefaultPluginsForActiveOwner(): void {
- const session = getActiveAppSession();
- if (!session.dataOwnerId || isAppSessionBoundaryPending()) return;
- const scope = activeOwnerScopeKey();
- if (scope === defaultPluginSyncInFlightScope) return;
- defaultPluginSyncInFlightScope = scope;
- void syncDefaultMarketPlugins().finally(() => {
- if (defaultPluginSyncInFlightScope === scope) defaultPluginSyncInFlightScope = null;
- });
-}
-
-function reconcileGhostOauthForActiveOwner(): void {
- void reconcileGhostOauthAccountsForActiveOwner().catch((error) => {
- createLogger('ghost-oauth-owner-reconcile').warn(
- 'OAuth account reconciliation for active owner failed',
- { error: error instanceof Error ? error.message : String(error) },
- );
- });
-}
function parseOptionalDeviceLinkDeviceId(value: unknown): string | null | undefined {
if (value === undefined) return undefined;
@@ -4357,6 +4358,7 @@ const registerIpcHandlers = () => {
pendingCompletion = completion;
},
});
+ await authManager.ensureStableOwnerPostCommitTasks('auth-initialize');
if (!app.isPackaged) {
recordDesktopDevAuthStartupResult(state, pendingCompletion, () =>
authManager.getAuthState(),
@@ -5269,15 +5271,6 @@ const registerIpcHandlers = () => {
// 默认插件同步不能依赖用户先打开插件页。启动时本地 owner 已经稳定则立刻
// 复用市场快照;云端登录/切号的通知可能早于 owner boundary 释放,因此
// 延迟到当前调用栈结束后再按已提交的新 owner 补跑一次。
- disposePluginMarketAuthListener = authManager.onAuthStateChange(() => {
- queueMicrotask(() => {
- syncDefaultPluginsForActiveOwner();
- reconcileGhostOauthForActiveOwner();
- });
- });
- syncDefaultPluginsForActiveOwner();
- reconcileGhostOauthForActiveOwner();
-
// ── Dialog: 目录选择器(v0.6 新增,与旧 show-open-directory-dialog 并存) ──
ipcMain.handle(
'dialog:show-open-directory',
@@ -7271,15 +7264,6 @@ onQuit(
},
'sync',
);
-onQuit(
- 'plugin-market-auth-listener',
- () => {
- disposePluginMarketAuthListener?.();
- disposePluginMarketAuthListener = null;
- },
- 'sync',
-);
-
// Async 阶段: 并发跑, 6s 超时兜底。
// - shutdown-maker: Layer 1 关 sessions → Layer 2 dispose agents (Codex
// shared app-server 子进程 SIGTERM)。**必须 await** —
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index dff5e578b9..f83c578141 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -1231,6 +1231,11 @@ export class GhostManager {
return this.runExclusiveMutation(() => this.migrateLegacyApprovalsUnlocked());
}
+ /** True only while the durable migration ledger still carries retry work. */
+ hasPendingLegacyApprovalMigration(): boolean {
+ return this.receiptStore.readMigrationLedger()?.state === 'in-progress';
+ }
+
private async migrateLegacyApprovalsUnlocked(): Promise<{
migrated: string[];
skipped: string[];
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/atlassianAccountsMigration.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/atlassianAccountsMigration.test.ts
index 61a3e45eb6..913d95f6c0 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/atlassianAccountsMigration.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/atlassianAccountsMigration.test.ts
@@ -8,10 +8,15 @@ import {
XD_ATLASSIAN_GHOST_ID,
XD_ATLASSIAN_SECRET_KEY,
migrateAtlassianAccounts,
+ migrateAtlassianAccountsWithResult,
type AtlassianAccountsMigrationDeps,
} from '../atlassianAccountsMigration.js';
import type { GhostOauthVault } from '../ghostOauthAccounts.js';
+const available = <T>(value: T) => ({ status: 'available' as const, value });
+const missing = { status: 'missing' as const };
+const retryableFailure = { status: 'retryable-failure' as const };
+
function memoryVault(seed?: Record<string, string>): GhostOauthVault & { data: Map<string, string> } {
const data = new Map<string, string>(
Object.entries(seed ?? {}).map(([k, v]) => [`${XD_ATLASSIAN_GHOST_ID} ${k}`, v]),
@@ -31,8 +36,8 @@ function memoryVault(seed?: Record<string, string>): GhostOauthVault & { data: M
function makeDeps(overrides?: Partial<AtlassianAccountsMigrationDeps>): AtlassianAccountsMigrationDeps {
return {
- readLegacyRefreshToken: () => 'rt-legacy',
- readLegacyConnection: () => ({ email: '[email protected]' }),
+ readLegacyRefreshToken: () => available('rt-legacy'),
+ readLegacyConnection: () => available({ email: '[email protected]' }),
vault: memoryVault(),
...overrides,
};
@@ -73,16 +78,29 @@ describe('migrateAtlassianAccounts', () => {
it('无老存储 / rt 解密失败 → no-op', () => {
const vault = memoryVault();
- expect(migrateAtlassianAccounts(makeDeps({ vault, readLegacyRefreshToken: () => null }))).toBe(0);
+ expect(migrateAtlassianAccounts(makeDeps({ vault, readLegacyRefreshToken: () => missing }))).toBe(0);
expect(readManifest(vault)).toBeNull();
});
it('连接信息缺失或无 email → label 为 null,照迁', () => {
const vault = memoryVault();
- expect(migrateAtlassianAccounts(makeDeps({ vault, readLegacyConnection: () => null }))).toBe(1);
+ expect(migrateAtlassianAccounts(makeDeps({ vault, readLegacyConnection: () => missing }))).toBe(1);
expect(readManifest(vault)?.accounts[0]?.label).toBeNull();
});
+ it('旧 token 或连接读取暂时失败 → 不写目标并保留重试', () => {
+ expect(
+ migrateAtlassianAccountsWithResult(
+ makeDeps({ readLegacyRefreshToken: () => retryableFailure }),
+ ),
+ ).toEqual({ migrated: 0, retryPending: true });
+ expect(
+ migrateAtlassianAccountsWithResult(
+ makeDeps({ readLegacyConnection: () => retryableFailure }),
+ ),
+ ).toEqual({ migrated: 0, retryPending: true });
+ });
+
it('清单写失败 → 回收已搬 rt,保持"没迁过"状态', () => {
const vault = memoryVault();
const failingVault: GhostOauthVault = {
@@ -94,6 +112,10 @@ describe('migrateAtlassianAccounts', () => {
remove: vault.remove,
};
expect(migrateAtlassianAccounts(makeDeps({ vault: failingVault }))).toBe(0);
+ expect(migrateAtlassianAccountsWithResult(makeDeps({ vault: failingVault }))).toEqual({
+ migrated: 0,
+ retryPending: true,
+ });
// rt 已回收,vault 里不残留任何键。
expect(vault.data.size).toBe(0);
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts
index 35b034115b..51a788d5fa 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts
@@ -304,6 +304,50 @@ describe('插件 OAuth clientId 迁移', () => {
});
});
+ it('reports a retry when crash recovery cannot persist the restored account state', () => {
+ const vault = memoryVault({
+ [`${KEY}-accounts`]: JSON.stringify({
+ defaultAccountId: 'acc-1',
+ accounts: [
+ {
+ id: 'acc-1',
+ label: '[email protected]',
+ status: 'expired',
+ expiredReason: 'oauth_client_changed',
+ expiredFromClientId: 'old-client',
+ expiredForClientId: 'new-client',
+ createdAt: 1,
+ },
+ ],
+ }),
+ });
+ const mgr = new GhostOauthAccountManager({
+ vault: { ...vault, store: () => false },
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ openExternal: vi.fn(),
+ });
+
+ expect(mgr.reconcileAccountsForInstalledManifestWithResult(oauthManifest('old-client')))
+ .toEqual({ restored: 0, retryPending: true });
+ });
+
+ it('reports a retry when crash recovery cannot strictly read the account manifest', () => {
+ const vault = memoryVault();
+ const mgr = new GhostOauthAccountManager({
+ vault: {
+ ...vault,
+ readStrict: () => {
+ throw new Error('keychain temporarily unavailable');
+ },
+ },
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ openExternal: vi.fn(),
+ });
+
+ expect(mgr.reconcileAccountsForInstalledManifestWithResult(oauthManifest('old-client')))
+ .toEqual({ restored: 0, retryPending: true });
+ });
+
it('插件切回签发 client 时只在 commit 后复活旧 token,不误复活新 client 账号', () => {
const vault = memoryVault({
[`${KEY}-accounts`]: JSON.stringify({
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthOwnerReconciliation.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthOwnerReconciliation.test.ts
index 492e30abd1..56fd7de3f7 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthOwnerReconciliation.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthOwnerReconciliation.test.ts
@@ -17,15 +17,28 @@ describe('Ghost OAuth owner reconciliation gate', () => {
const ownerATask = gate.run('cloud:owner-a:1', ownerA);
const ownerBTask = gate.run('cloud:owner-b:2', ownerB);
- await ownerBTask;
+ await expect(ownerBTask).resolves.toBe(true);
releaseOwnerA();
await expect(ownerATask).rejects.toThrow('old owner database closed');
expect(ownerB).toHaveBeenCalledOnce();
- await gate.run('cloud:owner-b:2', ownerB);
+ await expect(gate.run('cloud:owner-b:2', ownerB)).resolves.toBe(true);
expect(ownerB).toHaveBeenCalledOnce();
});
+ it('reports deferred work and retries it for the same owner scope', async () => {
+ const gate = createGhostOauthOwnerReconciliationGate();
+ const reconcile = vi.fn()
+ .mockResolvedValueOnce(false)
+ .mockResolvedValueOnce(true);
+
+ await expect(gate.run('cloud:owner-a:1', reconcile)).resolves.toBe(false);
+ await expect(gate.run('cloud:owner-a:1', reconcile)).resolves.toBe(true);
+ await expect(gate.run('cloud:owner-a:1', reconcile)).resolves.toBe(true);
+
+ expect(reconcile).toHaveBeenCalledTimes(2);
+ });
+
it('reruns when returning to a previously reconciled owner scope', async () => {
const gate = createGhostOauthOwnerReconciliationGate();
const ownerA = vi.fn(async () => true);
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/githubAccountsMigration.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/githubAccountsMigration.test.ts
index 72add0b85a..9e05003b4b 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/githubAccountsMigration.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/githubAccountsMigration.test.ts
@@ -10,10 +10,15 @@ import {
LEGACY_GITHUB_TOKEN_FILE,
LEGACY_GITHUB_CONNECTION_FILE,
migrateGithubAccounts,
+ migrateGithubAccountsWithResult,
type GithubAccountsMigrationDeps,
type GithubAccountsMigrationVault,
} from '../githubAccountsMigration.js';
+const available = <T>(value: T) => ({ status: 'available' as const, value });
+const missing = { status: 'missing' as const };
+const retryableFailure = { status: 'retryable-failure' as const };
+
function memoryVault(seed?: Record<string, string>): GithubAccountsMigrationVault & {
data: Map<string, string>;
} {
@@ -33,8 +38,8 @@ function memoryVault(seed?: Record<string, string>): GithubAccountsMigrationVaul
/** 模拟老 safe-storage 存储:记录读取次数,断言迁移对老存储只读不写。 */
function makeDeps(overrides?: Partial<GithubAccountsMigrationDeps>): GithubAccountsMigrationDeps {
return {
- readLegacyToken: () => 'ghp_legacy_token',
- readLegacyConnection: () => ({ host: 'github.com' }),
+ readLegacyToken: () => available('ghp_legacy_token'),
+ readLegacyConnection: () => available({ host: 'github.com' }),
vault: memoryVault(),
...overrides,
};
@@ -63,7 +68,7 @@ describe('migrateGithubAccounts', () => {
vault,
readLegacyToken: () => {
legacyReads += 1;
- return 'ghp_legacy_token';
+ return available('ghp_legacy_token');
},
}),
),
@@ -75,13 +80,13 @@ describe('migrateGithubAccounts', () => {
it('无老 token(未连接过 / 解密失败)→ no-op', () => {
const vault = memoryVault();
- expect(migrateGithubAccounts(makeDeps({ vault, readLegacyToken: () => null }))).toBe(0);
+ expect(migrateGithubAccounts(makeDeps({ vault, readLegacyToken: () => missing }))).toBe(0);
expect(vault.data.size).toBe(0);
});
it('connection.json 缺失(半身位残留)→ 保守不迁,不写库', () => {
const vault = memoryVault();
- expect(migrateGithubAccounts(makeDeps({ vault, readLegacyConnection: () => null }))).toBe(0);
+ expect(migrateGithubAccounts(makeDeps({ vault, readLegacyConnection: () => missing }))).toBe(0);
expect(vault.data.size).toBe(0);
});
@@ -89,7 +94,7 @@ describe('migrateGithubAccounts', () => {
const vault = memoryVault();
expect(
migrateGithubAccounts(
- makeDeps({ vault, readLegacyConnection: () => ({ host: 'ghe.corp.example' }) }),
+ makeDeps({ vault, readLegacyConnection: () => available({ host: 'ghe.corp.example' }) }),
),
).toBe(0);
expect(vault.data.size).toBe(0);
@@ -99,12 +104,21 @@ describe('migrateGithubAccounts', () => {
const vault = memoryVault();
expect(
migrateGithubAccounts(
- makeDeps({ vault, readLegacyConnection: () => ({ host: ' GitHub.COM ' }) }),
+ makeDeps({ vault, readLegacyConnection: () => available({ host: ' GitHub.COM ' }) }),
),
).toBe(1);
expect(vault.read(CINDY_GITHUB_GHOST_ID, CINDY_GITHUB_SECRET_KEY)).toBe('ghp_legacy_token');
});
+ it('旧 token 或连接读取暂时失败 → 不写目标并保留重试', () => {
+ expect(
+ migrateGithubAccountsWithResult(makeDeps({ readLegacyToken: () => retryableFailure })),
+ ).toEqual({ migrated: 0, retryPending: true });
+ expect(
+ migrateGithubAccountsWithResult(makeDeps({ readLegacyConnection: () => retryableFailure })),
+ ).toEqual({ migrated: 0, retryPending: true });
+ });
+
it('vault.store 写失败(safeStorage 不可用)→ 返回 0,下次启动可重试', () => {
const vault = memoryVault();
const failingVault: GithubAccountsMigrationVault = {
@@ -112,6 +126,10 @@ describe('migrateGithubAccounts', () => {
store: () => false,
};
expect(migrateGithubAccounts(makeDeps({ vault: failingVault }))).toBe(0);
+ expect(migrateGithubAccountsWithResult(makeDeps({ vault: failingVault }))).toEqual({
+ migrated: 0,
+ retryPending: true,
+ });
// 没有任何值落库,保持"没迁过"状态。
expect(vault.data.size).toBe(0);
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/gitlabAccountsMigration.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/gitlabAccountsMigration.test.ts
index 81988b4478..2951a0b07b 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/gitlabAccountsMigration.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/gitlabAccountsMigration.test.ts
@@ -11,10 +11,15 @@ import {
LEGACY_GITLAB_TOKEN_FILE,
LEGACY_GITLAB_CONNECTION_FILE,
migrateGitlabAccounts,
+ migrateGitlabAccountsWithResult,
type GitlabAccountsMigrationDeps,
type GitlabAccountsMigrationManager,
} from '../gitlabAccountsMigration.js';
+const available = <T>(value: T) => ({ status: 'available' as const, value });
+const missing = { status: 'missing' as const };
+const retryableFailure = { status: 'retryable-failure' as const };
+
interface FakeRow {
id: string;
host: string;
@@ -64,10 +69,10 @@ function memoryManager(seedRows?: FakeRow[]): GitlabAccountsMigrationManager & {
function makeDeps(overrides?: Partial<GitlabAccountsMigrationDeps>): GitlabAccountsMigrationDeps {
return {
- readLegacyToken: () => 'glpat_legacy_token',
+ readLegacyToken: () => available('glpat_legacy_token'),
// 缺省与 readLegacyToken 一致地"在场";幂等留痕用例单独覆盖两种取值。
legacyTokenExists: () => true,
- readLegacyConnection: () => ({ baseUrl: 'https://gitlab.example.com', username: 'devuser' }),
+ readLegacyConnection: () => available({ baseUrl: 'https://gitlab.example.com', username: 'devuser' }),
manager: memoryManager(),
...overrides,
};
@@ -102,7 +107,7 @@ describe('migrateGitlabAccounts', () => {
manager,
readLegacyToken: () => {
legacyReads += 1;
- return 'glpat_legacy_token';
+ return available('glpat_legacy_token');
},
}),
),
@@ -133,13 +138,13 @@ describe('migrateGitlabAccounts', () => {
it('无老 token(未连接过 / 解密失败)→ no-op', () => {
const manager = memoryManager();
- expect(migrateGitlabAccounts(makeDeps({ manager, readLegacyToken: () => null }))).toBe(0);
+ expect(migrateGitlabAccounts(makeDeps({ manager, readLegacyToken: () => missing }))).toBe(0);
expect(manager.rows).toHaveLength(0);
});
it('connection.json 缺失(半身位残留)→ 保守不迁,不写库', () => {
const manager = memoryManager();
- expect(migrateGitlabAccounts(makeDeps({ manager, readLegacyConnection: () => null }))).toBe(0);
+ expect(migrateGitlabAccounts(makeDeps({ manager, readLegacyConnection: () => missing }))).toBe(0);
expect(manager.rows).toHaveLength(0);
});
@@ -149,7 +154,7 @@ describe('migrateGitlabAccounts', () => {
migrateGitlabAccounts(
makeDeps({
manager,
- readLegacyConnection: () => ({ baseUrl: 'http://gitlab.internal.example', username: 'devuser' }),
+ readLegacyConnection: () => available({ baseUrl: 'http://gitlab.internal.example', username: 'devuser' }),
}),
),
).toBe(0);
@@ -162,7 +167,7 @@ describe('migrateGitlabAccounts', () => {
migrateGitlabAccounts(
makeDeps({
manager,
- readLegacyConnection: () => ({ baseUrl: 'https://git.example.com:8443', username: 'devuser' }),
+ readLegacyConnection: () => available({ baseUrl: 'https://git.example.com:8443', username: 'devuser' }),
}),
),
).toBe(0);
@@ -175,7 +180,7 @@ describe('migrateGitlabAccounts', () => {
migrateGitlabAccounts(
makeDeps({
manager,
- readLegacyConnection: () => ({ baseUrl: 'HTTPS://Git.X.com/', username: 'devuser' }),
+ readLegacyConnection: () => available({ baseUrl: 'HTTPS://Git.X.com/', username: 'devuser' }),
}),
),
).toBe(1);
@@ -189,13 +194,22 @@ describe('migrateGitlabAccounts', () => {
migrateGitlabAccounts(
makeDeps({
manager,
- readLegacyConnection: () => ({ baseUrl: 'https://gitlab.example.com', username: null }),
+ readLegacyConnection: () => available({ baseUrl: 'https://gitlab.example.com', username: null }),
}),
),
).toBe(1);
expect(manager.rows[0].label).toBeNull();
});
+ it('旧 token 或连接读取暂时失败 → 不写目标并保留重试', () => {
+ expect(
+ migrateGitlabAccountsWithResult(makeDeps({ readLegacyToken: () => retryableFailure })),
+ ).toEqual({ migrated: 0, retryPending: true });
+ expect(
+ migrateGitlabAccountsWithResult(makeDeps({ readLegacyConnection: () => retryableFailure })),
+ ).toEqual({ migrated: 0, retryPending: true });
+ });
+
it('manager.upsert 写失败(safeStorage 不可用)→ 返回 0,下次启动可重试', () => {
const manager = memoryManager();
const failingManager: GitlabAccountsMigrationManager = {
@@ -204,6 +218,10 @@ describe('migrateGitlabAccounts', () => {
setDefault: manager.setDefault,
};
expect(migrateGitlabAccounts(makeDeps({ manager: failingManager }))).toBe(0);
+ expect(migrateGitlabAccountsWithResult(makeDeps({ manager: failingManager }))).toEqual({
+ migrated: 0,
+ retryPending: true,
+ });
// 假体的 rows 只经真 upsert 写入,失败路径不落任何行,保持"没迁过"状态。
expect(manager.rows).toHaveLength(0);
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/googleAccountsMigration.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/googleAccountsMigration.test.ts
index 38b574d297..86590be2d2 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/googleAccountsMigration.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/googleAccountsMigration.test.ts
@@ -9,6 +9,7 @@ import {
FILO_GOOGLE_GHOST_ID,
FILO_GOOGLE_SECRET_KEY,
migrateFiloGoogleAccounts,
+ migrateFiloGoogleAccountsWithResult,
type GoogleAccountsMigrationDeps,
type LegacyGoogleAccountRow,
} from '../googleAccountsMigration.js';
@@ -34,11 +35,14 @@ const CURRENT = (id: string, email: string | null): LegacyGoogleAccountRow => ({
credentialProfileId: FILO_CURRENT_PROFILE_ID,
updatedAt: 100,
});
+const available = <T>(value: T) => ({ status: 'available' as const, value });
+const missing = { status: 'missing' as const };
+const retryableFailure = { status: 'retryable-failure' as const };
function deps(over: Partial<GoogleAccountsMigrationDeps>): GoogleAccountsMigrationDeps {
return {
- readLegacyManifest: () => ({ accounts: [CURRENT('acc-1', '[email protected]')] }),
- readLegacyRefreshToken: () => 'rt-legacy',
+ readLegacyManifest: () => available({ accounts: [CURRENT('acc-1', '[email protected]')] }),
+ readLegacyRefreshToken: () => available('rt-legacy'),
vault: memoryVault(),
...over,
};
@@ -63,7 +67,7 @@ describe('migrateFiloGoogleAccounts', () => {
const n = migrateFiloGoogleAccounts(
deps({
vault,
- readLegacyManifest: () => ({
+ readLegacyManifest: () => available({
accounts: [{ id: 'old-1', email: '[email protected]', credentialProfileId: 'filoLegacy', updatedAt: 1 }],
}),
}),
@@ -74,16 +78,16 @@ describe('migrateFiloGoogleAccounts', () => {
it('幂等:意识侧已有账号清单 → 整体跳过,不读老存储', () => {
const vault = memoryVault({ [`${FILO_GOOGLE_GHOST_ID} ${ACCOUNTS_KEY}`]: '{"defaultAccountId":"x","accounts":[]}' });
- const readLegacyManifest = vi.fn(() => ({ accounts: [CURRENT('acc-1', '[email protected]')] }));
+ const readLegacyManifest = vi.fn(() => available({ accounts: [CURRENT('acc-1', '[email protected]')] }));
const n = migrateFiloGoogleAccounts(deps({ vault, readLegacyManifest }));
expect(n).toBe(0);
expect(readLegacyManifest).not.toHaveBeenCalled();
});
it('老存储缺失 / 无 filoCurrent 账号 → 0,不建清单', () => {
- expect(migrateFiloGoogleAccounts(deps({ readLegacyManifest: () => null }))).toBe(0);
+ expect(migrateFiloGoogleAccounts(deps({ readLegacyManifest: () => missing }))).toBe(0);
expect(
- migrateFiloGoogleAccounts(deps({ readLegacyManifest: () => ({ accounts: [] }) })),
+ migrateFiloGoogleAccounts(deps({ readLegacyManifest: () => available({ accounts: [] }) })),
).toBe(0);
});
@@ -92,8 +96,8 @@ describe('migrateFiloGoogleAccounts', () => {
const n = migrateFiloGoogleAccounts(
deps({
vault,
- readLegacyManifest: () => ({ accounts: [CURRENT('acc-1', '[email protected]'), CURRENT('acc-2', '[email protected]')] }),
- readLegacyRefreshToken: (id) => (id === 'acc-1' ? 'rt-1' : null),
+ readLegacyManifest: () => available({ accounts: [CURRENT('acc-1', '[email protected]'), CURRENT('acc-2', '[email protected]')] }),
+ readLegacyRefreshToken: (id) => (id === 'acc-1' ? available('rt-1') : missing),
}),
);
expect(n).toBe(1);
@@ -101,6 +105,31 @@ describe('migrateFiloGoogleAccounts', () => {
expect(manifest.accounts.map((a: { id: string }) => a.id)).toEqual(['acc-1']);
});
+ it('任一旧 token 暂时读失败 → 回滚本轮已写 token 并保留整轮重试', () => {
+ const vault = memoryVault();
+ const result = migrateFiloGoogleAccountsWithResult(
+ deps({
+ vault,
+ readLegacyManifest: () => available({
+ accounts: [CURRENT('acc-1', '[email protected]'), CURRENT('acc-2', '[email protected]')],
+ }),
+ readLegacyRefreshToken: (id) => (id === 'acc-1' ? available('rt-1') : retryableFailure),
+ }),
+ );
+ expect(result).toEqual({ migrated: 0, retryPending: true });
+ expect(vault.data.size).toBe(0);
+ });
+
+ it('旧账号清单暂时读失败 → 不写目标并保留重试', () => {
+ const vault = memoryVault();
+ expect(
+ migrateFiloGoogleAccountsWithResult(
+ deps({ vault, readLegacyManifest: () => retryableFailure }),
+ ),
+ ).toEqual({ migrated: 0, retryPending: true });
+ expect(vault.data.size).toBe(0);
+ });
+
it('清单写失败 → 回收已搬 rt,保持"没迁过"状态', () => {
const vault = memoryVault();
// 清单键写入失败(rt 键正常):模拟 safeStorage 半可用。
@@ -114,5 +143,9 @@ describe('migrateFiloGoogleAccounts', () => {
expect(n).toBe(0);
// 已搬的 rt 被回收,下次启动可干净重试。
expect(vault.read(FILO_GOOGLE_GHOST_ID, RT_KEY('acc-1'))).toBeNull();
+ expect(migrateFiloGoogleAccountsWithResult(deps({ vault: failing }))).toEqual({
+ migrated: 0,
+ retryPending: true,
+ });
});
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryOrchestration.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryOrchestration.test.ts
index e7c9ad1524..06e71e7326 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryOrchestration.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryOrchestration.test.ts
@@ -4,6 +4,41 @@ import path from 'node:path';
import { describe, expect, it } from 'vitest';
describe('legacy Ghost recovery acknowledgement orchestration', () => {
+ it('routes startup migration through the stable-owner task instead of timing callbacks', () => {
+ const source = fs.readFileSync(
+ path.resolve(process.cwd(), 'src/main/cindy-brain/index.ts'),
+ 'utf8',
+ ).replace(/\r\n?/g, '\n');
+
+ expect(source).toContain('stableOwnerPostCommitTask = async (reason) => {');
+ expect(source).not.toContain("scheduleBuiltinReconcile('startup')");
+ expect(source).not.toContain("scheduleBuiltinReconcile('auth-change')");
+ expect(source).not.toContain('ghost oauth startup reconciliation failed');
+ expect(source).not.toContain('queueMicrotask(() => {\n void reconcileGhostOauthAccountsForActiveOwner()');
+ expect(source).toContain("return migrationNeedsRetry ? 'retry-pending' : 'completed';");
+ expect(source).toContain('migrationNeedsRetry ||= approvalNeedsRetry;');
+ expect(source).toContain('approvalNeedsRetry = true;');
+ expect(source).toContain("if (outcome === 'deferred') return outcome;");
+ expect(source).toContain("return outcome === 'failed'");
+ expect(source).toContain(
+ "const activateGhostsAndMigrateLegacyAccounts = (): 'completed' | 'retry-pending' => {",
+ );
+ expect(
+ source.match(/if \(migration\.retryPending\) legacyMigrationNeedsRetry = true;/g),
+ ).toHaveLength(4);
+ expect(
+ source.match(/catch \(err\) \{\n\s+legacyMigrationNeedsRetry = true;/g),
+ ).toHaveLength(4);
+ expect(source).toContain(
+ "return legacyMigrationNeedsRetry ? 'retry-pending' : 'completed';",
+ );
+ expect(source).toContain(
+ "outcome === 'retry-pending' || activationOutcome === 'retry-pending'",
+ );
+ expect(source).toContain("(error as NodeJS.ErrnoException).code === 'ENOENT'");
+ expect(source).toContain('LEGACY_MIGRATION_RETRYABLE_FAILURE');
+ });
+
it('keeps both retry-pending and deterministic backfill failures in the durable marker', () => {
const source = fs.readFileSync(
path.resolve(process.cwd(), 'src/main/cindy-brain/index.ts'),
diff --git a/apps/desktop/src/main/cindy-brain/atlassianAccountsMigration.ts b/apps/desktop/src/main/cindy-brain/atlassianAccountsMigration.ts
index 8b91659912..f369ecb01f 100644
--- a/apps/desktop/src/main/cindy-brain/atlassianAccountsMigration.ts
+++ b/apps/desktop/src/main/cindy-brain/atlassianAccountsMigration.ts
@@ -18,6 +18,7 @@
import { randomUUID } from 'node:crypto';
import type { GhostOauthVault } from './ghostOauthAccounts.js';
+import type { LegacyMigrationRead } from './legacyMigrationRead.js';
/** xd-atlassian 意识与其 oauth 凭证槽(与 ghost.json 声明一致,搬账目的地)。 */
export const XD_ATLASSIAN_GHOST_ID = 'xd-atlassian';
@@ -31,37 +32,53 @@ export const LEGACY_JIRA_RT_FILE = 'jira_refresh_token.enc';
export const LEGACY_JIRA_CONNECTION_FILE = 'jira_connection.json';
export interface AtlassianAccountsMigrationDeps {
- /** 读老 refresh token 明文(safeStorage 解密 jira_refresh_token.enc;不存在 / 解密失败回 null)。 */
- readLegacyRefreshToken(): string | null;
- /** 读老连接信息(jira_connection.json;只消费 email,坏形态回 null)。 */
- readLegacyConnection(): { email?: string | null } | null;
+ /** 读老 refresh token 明文,并区分确实缺失与可重试读取失败。 */
+ readLegacyRefreshToken(): LegacyMigrationRead<string>;
+ /** 读老连接信息,并区分确实缺失与可重试读取失败。 */
+ readLegacyConnection(): LegacyMigrationRead<{ email?: string | null }>;
/** 意识 OAuth 保险库(与 GhostOauthAccountManager 同一本账)。 */
vault: GhostOauthVault;
log?: { info(msg: string, meta?: Record<string, unknown>): void; warn(msg: string, meta?: Record<string, unknown>): void };
}
+export interface AtlassianAccountsMigrationResult {
+ migrated: number;
+ retryPending: boolean;
+}
+
/**
* 执行一次搬账。返回迁移的账号数(老集成是单账号形态,只会是 0 或 1)。
* 在内置意识对账完成后、确认 xd-atlassian 已装入时调用(见 index.ts 启动序列)。
*/
-export function migrateAtlassianAccounts(deps: AtlassianAccountsMigrationDeps): number {
+export function migrateAtlassianAccountsWithResult(
+ deps: AtlassianAccountsMigrationDeps,
+): AtlassianAccountsMigrationResult {
const { readLegacyRefreshToken, readLegacyConnection, vault, log } = deps;
const accountsKey = `${XD_ATLASSIAN_SECRET_KEY}-accounts`;
// 意识侧已有账号(用户手动连过 / 上次已迁)→ 不碰,防重复合并。
- if (vault.read(XD_ATLASSIAN_GHOST_ID, accountsKey) !== null) return 0;
+ if (vault.read(XD_ATLASSIAN_GHOST_ID, accountsKey) !== null) {
+ return { migrated: 0, retryPending: false };
+ }
const refreshToken = readLegacyRefreshToken();
- if (!refreshToken) return 0;
+ if (refreshToken.status === 'retryable-failure') return { migrated: 0, retryPending: true };
+ if (refreshToken.status === 'missing') return { migrated: 0, retryPending: false };
const connection = readLegacyConnection();
- const email = typeof connection?.email === 'string' && connection.email.length > 0 ? connection.email : null;
+ if (connection.status === 'retryable-failure') return { migrated: 0, retryPending: true };
+ const email =
+ connection.status === 'available'
+ && typeof connection.value.email === 'string'
+ && connection.value.email.length > 0
+ ? connection.value.email
+ : null;
const accountId = randomUUID();
// rt 先落库再挂清单(与 GhostOauthAccountManager.connectAccount 同顺序,防半身位)。
- if (!vault.store(XD_ATLASSIAN_GHOST_ID, `${XD_ATLASSIAN_SECRET_KEY}-rt-${accountId}`, refreshToken)) {
+ if (!vault.store(XD_ATLASSIAN_GHOST_ID, `${XD_ATLASSIAN_SECRET_KEY}-rt-${accountId}`, refreshToken.value)) {
log?.warn('xd-atlassian 搬账:refresh token 写入失败,放弃本轮(下次启动重试)');
- return 0;
+ return { migrated: 0, retryPending: true };
}
const manifest = {
defaultAccountId: accountId,
@@ -71,8 +88,13 @@ export function migrateAtlassianAccounts(deps: AtlassianAccountsMigrationDeps):
// 清单写失败:回收已搬的 rt,保持"没迁过"的干净状态,下次启动重试。
vault.remove(XD_ATLASSIAN_GHOST_ID, `${XD_ATLASSIAN_SECRET_KEY}-rt-${accountId}`);
log?.warn('xd-atlassian 搬账:账号清单写入失败,整体回退');
- return 0;
+ return { migrated: 0, retryPending: true };
}
log?.info('xd-atlassian 搬账完成:老 Jira/Confluence 集成账号已迁入意识', { hasEmail: email !== null });
- return 1;
+ return { migrated: 1, retryPending: false };
+}
+
+/** Compatibility wrapper for callers that only need the migrated count. */
+export function migrateAtlassianAccounts(deps: AtlassianAccountsMigrationDeps): number {
+ return migrateAtlassianAccountsWithResult(deps).migrated;
}
diff --git a/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts b/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
index 2244d84a95..4c9ad5da74 100644
--- a/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
@@ -101,6 +101,8 @@ export interface GhostOauthAccountView {
/** 保险库最小面(providerSecretStore 在接线处适配;测试喂内存假体)。 */
export interface GhostOauthVault {
read(ghostId: string, storageKey: string): string | null;
+ /** Optional strict read used only by durable reconciliation. */
+ readStrict?(ghostId: string, storageKey: string): string | null;
/** 返回 false = 写失败(safeStorage 不可用等),调用方折叠结构化错误。 */
store(ghostId: string, storageKey: string, value: string): boolean;
remove(ghostId: string, storageKey: string): void;
@@ -607,15 +609,33 @@ export class GhostOauthAccountManager {
* the update-crash half state and incorrectly reusing that token for a third
* client introduced by a later update.
*/
- reconcileAccountsForInstalledManifest(currentManifest: GhostManifest): number {
+ reconcileAccountsForInstalledManifestWithResult(currentManifest: GhostManifest): {
+ restored: number;
+ retryPending: boolean;
+ } {
const ghostId = currentManifest.id;
let restoredCount = 0;
+ let retryPending = false;
for (const secret of currentManifest.network?.secrets ?? []) {
if (secret.source !== 'oauth' || secret.oauth?.tokenBroker) continue;
if (this.clientCustomized(ghostId, secret.key)) continue;
const currentClientId = secret.oauth?.clientId?.trim();
if (!currentClientId) continue;
- const beforeRaw = this.deps.vault.read(ghostId, accountsKey(secret.key));
+ let beforeRaw: string | null;
+ try {
+ beforeRaw = (this.deps.vault.readStrict ?? this.deps.vault.read)(
+ ghostId,
+ accountsKey(secret.key),
+ );
+ } catch (error) {
+ retryPending = true;
+ this.deps.logger?.warn?.('ghost oauth client migration recovery read failed', {
+ ghostId,
+ secretKey: secret.key,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ continue;
+ }
if (beforeRaw === null) continue;
const manifest = parseManifest(beforeRaw);
let changed = 0;
@@ -636,6 +656,7 @@ export class GhostOauthAccountManager {
}
if (changed === 0) continue;
if (!this.deps.vault.store(ghostId, accountsKey(secret.key), JSON.stringify(manifest))) {
+ retryPending = true;
this.deps.logger?.warn?.('ghost oauth client migration recovery write failed', {
ghostId,
secretKey: secret.key,
@@ -646,7 +667,12 @@ export class GhostOauthAccountManager {
this.clearCachedTokens(ghostId, secret.key);
this.notifyStatusChanged(ghostId, secret.key, 'connected');
}
- return restoredCount;
+ return { restored: restoredCount, retryPending };
+ }
+
+ /** Compatibility wrapper for callers that only need the restored count. */
+ reconcileAccountsForInstalledManifest(currentManifest: GhostManifest): number {
+ return this.reconcileAccountsForInstalledManifestWithResult(currentManifest).restored;
}
/** 返回仍未完成重新授权的 clientId 迁移账号数;普通撤销授权不计入。 */
diff --git a/apps/desktop/src/main/cindy-brain/ghostOauthOwnerReconciliation.ts b/apps/desktop/src/main/cindy-brain/ghostOauthOwnerReconciliation.ts
index a407b9e5ec..23369b786d 100644
--- a/apps/desktop/src/main/cindy-brain/ghostOauthOwnerReconciliation.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostOauthOwnerReconciliation.ts
@@ -11,24 +11,26 @@ export function createGhostOauthOwnerReconciliationGate(): {
run: (
ownerScope: string,
reconcile: () => Promise<boolean>,
- ) => Promise<void>;
+ ) => Promise<boolean>;
} {
let reconciledOwnerScope: string | null = null;
- const inFlightByOwnerScope = new Map<string, Promise<void>>();
+ const inFlightByOwnerScope = new Map<string, Promise<boolean>>();
return {
- async run(ownerScope, reconcile): Promise<void> {
- if (reconciledOwnerScope === ownerScope) return;
+ async run(ownerScope, reconcile): Promise<boolean> {
+ if (reconciledOwnerScope === ownerScope) return true;
const existing = inFlightByOwnerScope.get(ownerScope);
if (existing) return existing;
- let task!: Promise<void>;
+ let task!: Promise<boolean>;
task = (async () => {
- if (await reconcile()) reconciledOwnerScope = ownerScope;
+ const completed = await reconcile();
+ if (completed) reconciledOwnerScope = ownerScope;
+ return completed;
})();
inFlightByOwnerScope.set(ownerScope, task);
try {
- await task;
+ return await task;
} finally {
if (inFlightByOwnerScope.get(ownerScope) === task) {
inFlightByOwnerScope.delete(ownerScope);
diff --git a/apps/desktop/src/main/cindy-brain/ghostSnapshotWorkerProcess.ts b/apps/desktop/src/main/cindy-brain/ghostSnapshotWorkerProcess.ts
index b0e8fa0983..316f84bdff 100644
--- a/apps/desktop/src/main/cindy-brain/ghostSnapshotWorkerProcess.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostSnapshotWorkerProcess.ts
@@ -83,12 +83,20 @@ async function removeVerifiedDirectory(
workingDir: string,
targetPath: string,
parentName: string,
+ expectedTarget?: { realPath: string; dev: bigint; ino: bigint },
): Promise<void> {
const targetStat = await fs.promises.lstat(targetPath, { bigint: true });
if (!targetStat.isDirectory() || targetStat.isSymbolicLink()) {
throw new Error('snapshot target is not a real directory');
}
const targetRealPath = await fs.promises.realpath(targetPath);
+ if (expectedTarget && (
+ targetStat.dev !== expectedTarget.dev ||
+ targetStat.ino !== expectedTarget.ino ||
+ !samePath(targetRealPath, expectedTarget.realPath)
+ )) {
+ throw new Error('snapshot target identity changed before removal');
+ }
const quarantinePath = `${targetPath}.remove-${process.pid}-${Date.now()}`;
await fs.promises.rename(targetPath, quarantinePath);
const movedStat = await fs.promises.lstat(quarantinePath, { bigint: true });
@@ -154,15 +162,36 @@ export async function runGhostSnapshotWorkerRequest(
await verifyParent(request.expectedParent, workingDir);
if (parts.length !== 1) throw new Error('invalid snapshot removal target');
await verifyDirectory(workingDir, parts[0]);
- await removeVerifiedDirectory(request.expectedParent, workingDir, targetPath, parts[0]);
+ const targetStat = await fs.promises.lstat(targetPath, { bigint: true });
+ if (!targetStat.isDirectory() || targetStat.isSymbolicLink()) {
+ throw new Error('snapshot target is not a real directory');
+ }
+ const targetIdentity = {
+ realPath: await fs.promises.realpath(targetPath),
+ dev: targetStat.dev,
+ ino: targetStat.ino,
+ };
+ await removeVerifiedDirectory(
+ request.expectedParent,
+ workingDir,
+ targetPath,
+ parts[0],
+ targetIdentity,
+ );
send({ ok: true }); return;
}
if (!request.receipt || !request.sourceDir) throw new Error('approved skill snapshot is missing');
let exists = false;
+ let existingTargetIdentity: { realPath: string; dev: bigint; ino: bigint } | undefined;
try {
- const stat = await fs.promises.lstat(targetPath);
+ const stat = await fs.promises.lstat(targetPath, { bigint: true });
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('snapshot target is not a real directory');
exists = true;
+ existingTargetIdentity = {
+ realPath: await fs.promises.realpath(targetPath),
+ dev: stat.dev,
+ ino: stat.ino,
+ };
} catch (error) { if (!hasCode(error, 'ENOENT')) throw error; }
if (exists) {
await verifyDirectory(workingDir, parts[0]);
@@ -218,7 +247,15 @@ export async function runGhostSnapshotWorkerRequest(
if (tempBeforePublish !== 'directory') throw new Error('snapshot temp directory was replaced before publish');
await verifyParent(request.expectedParent, workingDir);
await verifyDirectory(workingDir, parts[0]);
- if (exists) await fs.promises.rm(targetPath, { recursive: true, force: true });
+ if (exists) {
+ await removeVerifiedDirectory(
+ request.expectedParent,
+ workingDir,
+ targetPath,
+ parts[0],
+ existingTargetIdentity,
+ );
+ }
await verifyParent(request.expectedParent, workingDir);
await verifyDirectory(workingDir, parts[0]);
try {
diff --git a/apps/desktop/src/main/cindy-brain/githubAccountsMigration.ts b/apps/desktop/src/main/cindy-brain/githubAccountsMigration.ts
index f219bbfae0..1708071f28 100644
--- a/apps/desktop/src/main/cindy-brain/githubAccountsMigration.ts
+++ b/apps/desktop/src/main/cindy-brain/githubAccountsMigration.ts
@@ -21,6 +21,8 @@
* 依赖注入(规则 14):老存储读取 / 意识保险库全经 deps,单测内存假体零 Electron。
*/
+import type { LegacyMigrationRead } from './legacyMigrationRead.js';
+
/** cindy-github 意识与其 user 凭证槽(与 ghost.json 声明一致,搬账目的地)。 */
export const CINDY_GITHUB_GHOST_ID = 'cindy-github';
export const CINDY_GITHUB_SECRET_KEY = 'github_pat';
@@ -40,41 +42,60 @@ export interface GithubAccountsMigrationVault {
}
export interface GithubAccountsMigrationDeps {
- /** 读老 PAT 明文(safeStorage 解密 github_token.enc;不存在 / 解密失败回 null)。 */
- readLegacyToken(): string | null;
- /** 读老连接信息(github_connection.json;只消费 host,坏形态回 null)。 */
- readLegacyConnection(): { host?: string | null } | null;
+ /** 读老 PAT 明文,并区分确实缺失与可重试读取失败。 */
+ readLegacyToken(): LegacyMigrationRead<string>;
+ /** 读老连接信息,并区分确实缺失与可重试读取失败。 */
+ readLegacyConnection(): LegacyMigrationRead<{ host?: string | null }>;
vault: GithubAccountsMigrationVault;
log?: { info(msg: string, meta?: Record<string, unknown>): void; warn(msg: string, meta?: Record<string, unknown>): void };
}
+export interface GithubAccountsMigrationResult {
+ migrated: number;
+ retryPending: boolean;
+}
+
/**
* 执行一次搬账。返回迁移的账号数(老集成是单账号形态,只会是 0 或 1)。
* 在内置意识对账完成后、确认 cindy-github 已装入时调用(见 index.ts 启动序列)。
*/
-export function migrateGithubAccounts(deps: GithubAccountsMigrationDeps): number {
+export function migrateGithubAccountsWithResult(
+ deps: GithubAccountsMigrationDeps,
+): GithubAccountsMigrationResult {
const { readLegacyToken, readLegacyConnection, vault, log } = deps;
// 意识侧已有值(用户手动填过 / 上次已迁)→ 不碰,防覆盖。
- if (vault.read(CINDY_GITHUB_GHOST_ID, CINDY_GITHUB_SECRET_KEY) !== null) return 0;
+ if (vault.read(CINDY_GITHUB_GHOST_ID, CINDY_GITHUB_SECRET_KEY) !== null) {
+ return { migrated: 0, retryPending: false };
+ }
const token = readLegacyToken();
- if (!token) return 0;
+ if (token.status === 'retryable-failure') return { migrated: 0, retryPending: true };
+ if (token.status === 'missing') return { migrated: 0, retryPending: false };
// 老集成 addAccount 必写 connection.json;读不到 = 半身位残留,保守不迁。
const connection = readLegacyConnection();
- const host = typeof connection?.host === 'string' ? connection.host.trim().toLowerCase() : '';
+ if (connection.status === 'retryable-failure') return { migrated: 0, retryPending: true };
+ const host =
+ connection.status === 'available' && typeof connection.value.host === 'string'
+ ? connection.value.host.trim().toLowerCase()
+ : '';
if (host !== 'github.com') {
log?.info('cindy-github 搬账跳过:老连接不是 github.com(意识只支持 github.com)', {
- hasConnection: connection !== null,
+ hasConnection: connection.status === 'available',
});
- return 0;
+ return { migrated: 0, retryPending: false };
}
- if (!vault.store(CINDY_GITHUB_GHOST_ID, CINDY_GITHUB_SECRET_KEY, token)) {
+ if (!vault.store(CINDY_GITHUB_GHOST_ID, CINDY_GITHUB_SECRET_KEY, token.value)) {
log?.warn('cindy-github 搬账:PAT 写入失败,放弃本轮(下次启动重试)');
- return 0;
+ return { migrated: 0, retryPending: true };
}
log?.info('cindy-github 搬账完成:老 GitHub 集成账号已迁入意识');
- return 1;
+ return { migrated: 1, retryPending: false };
+}
+
+/** Compatibility wrapper for callers that only need the migrated count. */
+export function migrateGithubAccounts(deps: GithubAccountsMigrationDeps): number {
+ return migrateGithubAccountsWithResult(deps).migrated;
}
diff --git a/apps/desktop/src/main/cindy-brain/gitlabAccountsMigration.ts b/apps/desktop/src/main/cindy-brain/gitlabAccountsMigration.ts
index 85cb351acd..34768ed7c4 100644
--- a/apps/desktop/src/main/cindy-brain/gitlabAccountsMigration.ts
+++ b/apps/desktop/src/main/cindy-brain/gitlabAccountsMigration.ts
@@ -26,6 +26,7 @@
*/
import { normalizeGhostConnectionHost } from './ghostConnections.js';
+import type { LegacyMigrationRead } from './legacyMigrationRead.js';
/** cindy-gitlab 意识与其多连接声明 key(与 ghost.json network.connections 一致,搬账目的地)。 */
export const CINDY_GITLAB_GHOST_ID = 'cindy-gitlab';
@@ -60,19 +61,27 @@ export interface GitlabAccountsMigrationManager {
}
export interface GitlabAccountsMigrationDeps {
- /** 读老 PAT 明文(safeStorage 解密 gitlab_token.enc;不存在 / 解密失败回 null)。 */
- readLegacyToken(): string | null;
+ /** 读老 PAT 明文,并区分确实缺失与可重试读取失败。 */
+ readLegacyToken(): LegacyMigrationRead<string>;
/**
* 老 token 文件是否在场(existsSync,不解密)。只服务幂等跳过分支的留痕
* 日志——跳过时保持"连老 token 都不解密"的纪律,又不让重试链被静默截断。
*/
legacyTokenExists(): boolean;
- /** 读老连接信息(gitlab_connection.json;消费 baseUrl + username,坏形态回 null)。 */
- readLegacyConnection(): { baseUrl?: string | null; username?: string | null } | null;
+ /** 读老连接信息,并区分确实缺失与可重试读取失败。 */
+ readLegacyConnection(): LegacyMigrationRead<{
+ baseUrl?: string | null;
+ username?: string | null;
+ }>;
manager: GitlabAccountsMigrationManager;
log?: { info(msg: string, meta?: Record<string, unknown>): void; warn(msg: string, meta?: Record<string, unknown>): void };
}
+export interface GitlabAccountsMigrationResult {
+ migrated: number;
+ retryPending: boolean;
+}
+
/**
* 老 baseUrl(形如 `https://git.example.com`)→ 连接清单要求的小写裸域。
* 不可迁形态返回 null:非 https(意识出网仅 https)、带端口(白名单不吃
@@ -113,7 +122,9 @@ function legacyBaseUrlToHost(
* 执行一次搬账。返回迁移的连接数(老集成是单账号形态,只会是 0 或 1)。
* 在内置意识对账完成后、确认 cindy-gitlab 已装入时调用(见 index.ts 启动序列)。
*/
-export function migrateGitlabAccounts(deps: GitlabAccountsMigrationDeps): number {
+export function migrateGitlabAccountsWithResult(
+ deps: GitlabAccountsMigrationDeps,
+): GitlabAccountsMigrationResult {
const { readLegacyToken, readLegacyConnection, manager, log } = deps;
// 该 decl 名下已有连接(用户手动加过 / 上次已迁)→ 不碰,防覆盖。
@@ -123,31 +134,38 @@ export function migrateGitlabAccounts(deps: GitlabAccountsMigrationDeps): number
if (deps.legacyTokenExists()) {
log?.info('cindy-gitlab 搬账跳过:意识侧已有连接清单(老 token 文件仍在,按防覆盖纪律不迁)');
}
- return 0;
+ return { migrated: 0, retryPending: false };
}
const token = readLegacyToken();
- if (!token) return 0;
+ if (token.status === 'retryable-failure') return { migrated: 0, retryPending: true };
+ if (token.status === 'missing') return { migrated: 0, retryPending: false };
// 老集成 addAccount 必写 connection.json;读不到 = 半身位残留,保守不迁。
const connection = readLegacyConnection();
- const baseUrl = typeof connection?.baseUrl === 'string' ? connection.baseUrl : '';
+ if (connection.status === 'retryable-failure') return { migrated: 0, retryPending: true };
+ const baseUrl =
+ connection.status === 'available' && typeof connection.value.baseUrl === 'string'
+ ? connection.value.baseUrl
+ : '';
if (!baseUrl) {
log?.info('cindy-gitlab 搬账跳过:老连接信息缺失(半身位残留,保守不迁)', {
- hasConnection: connection !== null,
+ hasConnection: connection.status === 'available',
});
- return 0;
+ return { migrated: 0, retryPending: false };
}
const host = legacyBaseUrlToHost(baseUrl, log);
- if (host === null) return 0;
+ if (host === null) return { migrated: 0, retryPending: false };
const username =
- typeof connection?.username === 'string' && connection.username.length > 0
- ? connection.username
+ connection.status === 'available'
+ && typeof connection.value.username === 'string'
+ && connection.value.username.length > 0
+ ? connection.value.username
: null;
const result = manager.upsert(CINDY_GITLAB_GHOST_ID, CINDY_GITLAB_CONNECTION_KEY, {
host,
- token,
+ token: token.value,
...(username !== null ? { label: username } : {}),
max: UPSERT_MAX,
});
@@ -155,7 +173,7 @@ export function migrateGitlabAccounts(deps: GitlabAccountsMigrationDeps): number
log?.warn('cindy-gitlab 搬账:连接写入失败,放弃本轮(下次启动重试)', {
error: result.error,
});
- return 0;
+ return { migrated: 0, retryPending: true };
}
// 空清单上的新增本就自动成为默认连接;显式设一次是防御性收口(setDefault
// 幂等),失败也不回退迁移结果(连接已可用,默认位下次启动无从修——但
@@ -164,5 +182,10 @@ export function migrateGitlabAccounts(deps: GitlabAccountsMigrationDeps): number
log?.warn('cindy-gitlab 搬账:设默认连接失败(单连接场景不影响使用)');
}
log?.info('cindy-gitlab 搬账完成:老 GitLab 集成账号已迁入意识', { host });
- return 1;
+ return { migrated: 1, retryPending: false };
+}
+
+/** Compatibility wrapper for callers that only need the migrated count. */
+export function migrateGitlabAccounts(deps: GitlabAccountsMigrationDeps): number {
+ return migrateGitlabAccountsWithResult(deps).migrated;
}
diff --git a/apps/desktop/src/main/cindy-brain/googleAccountsMigration.ts b/apps/desktop/src/main/cindy-brain/googleAccountsMigration.ts
index c183b08ea4..7b110e2fa3 100644
--- a/apps/desktop/src/main/cindy-brain/googleAccountsMigration.ts
+++ b/apps/desktop/src/main/cindy-brain/googleAccountsMigration.ts
@@ -16,6 +16,7 @@
*/
import type { GhostOauthVault } from './ghostOauthAccounts.js';
+import type { LegacyMigrationRead } from './legacyMigrationRead.js';
/** filo-google 意识与其 oauth 凭证槽(与 ghost.json 声明一致,搬账目的地)。 */
export const FILO_GOOGLE_GHOST_ID = 'filo-google';
@@ -30,15 +31,20 @@ export interface LegacyGoogleAccountRow {
}
export interface GoogleAccountsMigrationDeps {
- /** 读老账号清单(userData/safe-storage/google_accounts.json;不存在 / 坏形态回 null)。 */
- readLegacyManifest(): { accounts: LegacyGoogleAccountRow[] } | null;
- /** 读老账号的 refresh token 明文(safeStorage 解密;不存在 / 解密失败回 null)。 */
- readLegacyRefreshToken(accountId: string): string | null;
+ /** 读老账号清单,并区分确实缺失与可重试读取失败。 */
+ readLegacyManifest(): LegacyMigrationRead<{ accounts: LegacyGoogleAccountRow[] }>;
+ /** 读老账号的 refresh token 明文,并区分确实缺失与可重试读取失败。 */
+ readLegacyRefreshToken(accountId: string): LegacyMigrationRead<string>;
/** 意识 OAuth 保险库(与 GhostOauthAccountManager 同一本账)。 */
vault: GhostOauthVault;
log?: { info(msg: string, meta?: Record<string, unknown>): void; warn(msg: string, meta?: Record<string, unknown>): void };
}
+export interface GoogleAccountsMigrationResult {
+ migrated: number;
+ retryPending: boolean;
+}
+
/** 老账号 id 形状(镜像老集成的 SAFE_ACCOUNT_ID_RE;同时满足保险库键名字符集)。 */
const SAFE_ACCOUNT_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
@@ -50,27 +56,47 @@ export const FILO_CURRENT_PROFILE_ID = 'filoCurrent';
* 在内置意识对账完成后调用(见 index.ts 启动序列);同步 IO 量级为个位数
* 小文件,不值得异步化。
*/
-export function migrateFiloGoogleAccounts(deps: GoogleAccountsMigrationDeps): number {
+export function migrateFiloGoogleAccountsWithResult(
+ deps: GoogleAccountsMigrationDeps,
+): GoogleAccountsMigrationResult {
const { readLegacyManifest, readLegacyRefreshToken, vault, log } = deps;
const accountsKey = `${FILO_GOOGLE_SECRET_KEY}-accounts`;
// 意识侧已有账号(用户手动连过 / 上次已迁)→ 不碰,防重复合并。
- if (vault.read(FILO_GOOGLE_GHOST_ID, accountsKey) !== null) return 0;
+ if (vault.read(FILO_GOOGLE_GHOST_ID, accountsKey) !== null) {
+ return { migrated: 0, retryPending: false };
+ }
const legacy = readLegacyManifest();
- if (!legacy || legacy.accounts.length === 0) return 0;
+ if (legacy.status === 'retryable-failure') {
+ return { migrated: 0, retryPending: true };
+ }
+ if (legacy.status === 'missing' || legacy.value.accounts.length === 0) {
+ return { migrated: 0, retryPending: false };
+ }
const rows: Array<{ id: string; label: string | null; status: 'connected'; createdAt: number }> = [];
- for (const account of legacy.accounts) {
+ for (const account of legacy.value.accounts) {
// 只迁 filoCurrent:意识内置同一 client,refresh token 直接通用;
// legacy 档案的令牌换了 client 刷不动,迁了也是死账号,不如引导重连。
if (account.credentialProfileId !== FILO_CURRENT_PROFILE_ID) continue;
if (typeof account.id !== 'string' || !SAFE_ACCOUNT_ID_RE.test(account.id)) continue;
const refreshToken = readLegacyRefreshToken(account.id);
- if (!refreshToken) continue;
- if (!vault.store(FILO_GOOGLE_GHOST_ID, `${FILO_GOOGLE_SECRET_KEY}-rt-${account.id}`, refreshToken)) {
- log?.warn('filo-google 搬账:refresh token 写入失败,跳过该账号', { accountId: account.id });
- continue;
+ if (refreshToken.status === 'retryable-failure') {
+ for (const row of rows) {
+ vault.remove(FILO_GOOGLE_GHOST_ID, `${FILO_GOOGLE_SECRET_KEY}-rt-${row.id}`);
+ }
+ return { migrated: 0, retryPending: true };
+ }
+ if (refreshToken.status === 'missing') continue;
+ if (!vault.store(FILO_GOOGLE_GHOST_ID, `${FILO_GOOGLE_SECRET_KEY}-rt-${account.id}`, refreshToken.value)) {
+ for (const row of rows) {
+ vault.remove(FILO_GOOGLE_GHOST_ID, `${FILO_GOOGLE_SECRET_KEY}-rt-${row.id}`);
+ }
+ log?.warn('filo-google 搬账:refresh token 写入失败,整体回退并等待重试', {
+ accountId: account.id,
+ });
+ return { migrated: 0, retryPending: true };
}
rows.push({
id: account.id,
@@ -79,15 +105,20 @@ export function migrateFiloGoogleAccounts(deps: GoogleAccountsMigrationDeps): nu
createdAt: typeof account.updatedAt === 'number' && Number.isFinite(account.updatedAt) ? account.updatedAt : 0,
});
}
- if (rows.length === 0) return 0;
+ if (rows.length === 0) return { migrated: 0, retryPending: false };
const manifest = { defaultAccountId: rows[0].id, accounts: rows };
if (!vault.store(FILO_GOOGLE_GHOST_ID, accountsKey, JSON.stringify(manifest))) {
// 清单写失败:回收已搬的 rt,保持"没迁过"的干净状态,下次启动重试。
for (const row of rows) vault.remove(FILO_GOOGLE_GHOST_ID, `${FILO_GOOGLE_SECRET_KEY}-rt-${row.id}`);
log?.warn('filo-google 搬账:账号清单写入失败,整体回退');
- return 0;
+ return { migrated: 0, retryPending: true };
}
log?.info('filo-google 搬账完成:老 Google 集成账号已迁入意识', { migrated: rows.length });
- return rows.length;
+ return { migrated: rows.length, retryPending: false };
+}
+
+/** Compatibility wrapper for callers that only need the migrated count. */
+export function migrateFiloGoogleAccounts(deps: GoogleAccountsMigrationDeps): number {
+ return migrateFiloGoogleAccountsWithResult(deps).migrated;
}
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index f814de94d1..58c8dadb15 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -163,7 +163,7 @@ import {
import {
FILO_GOOGLE_GHOST_ID,
FILO_GOOGLE_SECRET_KEY,
- migrateFiloGoogleAccounts,
+ migrateFiloGoogleAccountsWithResult,
type LegacyGoogleAccountRow,
} from './googleAccountsMigration.js';
import { withFiloGoogleBuildClientConfig } from './filoGoogleClientConfig.js';
@@ -172,22 +172,28 @@ import {
LEGACY_JIRA_RT_FILE,
XD_ATLASSIAN_GHOST_ID,
XD_ATLASSIAN_SECRET_KEY,
- migrateAtlassianAccounts,
+ migrateAtlassianAccountsWithResult,
} from './atlassianAccountsMigration.js';
import {
LEGACY_GITHUB_CONNECTION_FILE,
LEGACY_GITHUB_TOKEN_FILE,
CINDY_GITHUB_GHOST_ID,
CINDY_GITHUB_SECRET_KEY,
- migrateGithubAccounts,
+ migrateGithubAccountsWithResult,
} from './githubAccountsMigration.js';
import {
LEGACY_GITLAB_CONNECTION_FILE,
LEGACY_GITLAB_TOKEN_FILE,
CINDY_GITLAB_GHOST_ID,
CINDY_GITLAB_CONNECTION_KEY,
- migrateGitlabAccounts,
+ migrateGitlabAccountsWithResult,
} from './gitlabAccountsMigration.js';
+import {
+ LEGACY_MIGRATION_MISSING,
+ LEGACY_MIGRATION_RETRYABLE_FAILURE,
+ legacyMigrationAvailable,
+ type LegacyMigrationRead,
+} from './legacyMigrationRead.js';
import { GHOST_SCHEME, ghostExternalLinkUrls, parseGhostPartition } from '../../shared/ghost.js';
import { GhostPipeDispatcher } from './pipeDispatcher.js';
import { GhostCardService, parseCardHeightReport } from './cardService.js';
@@ -290,6 +296,7 @@ import { GhostExternalLinkGate, GhostPreviewGate, resolveGhostPanelMedia } from
import {
ghostSecretSaved,
readGhostSecret,
+ readGhostSecretStrict,
getProviderSecretStore,
readGhostSecretTail,
removeGhostSecret,
@@ -787,7 +794,7 @@ async function retryLegacyGhostRecoveryForActiveSession(): Promise<LegacyGhostRe
}
const builtinReconcileSucceeded =
result.deferredReason !== 'concurrent-live-instances' &&
- (await scheduleBuiltinReconcile('legacy-recovery'));
+ (await scheduleBuiltinReconcile('legacy-recovery')) === 'completed';
if (shouldAbort()) return getLegacyGhostRecoveryStatusForActiveSession();
const ghosts = getGhostManager().list();
for (const ghost of ghosts) {
@@ -1019,12 +1026,21 @@ function currentProvisionIdentity(): ProvisionIdentity | null {
}
/**
- * 内置意识对账的串行链:startup 与 auth-change 的触发共用一条 promise 链,
+ * 内置意识对账的串行链:统一由 stable-owner post-commit/ensure 入口调度,
+ * 所有触发共用一条 promise 链,
* 保证任意时刻只有一个 reconcile 在跑(登录抖动 / 快速切号不并发写盘)。
* 单次失败吞掉并 warn(下次触发重试),链永不断。
*/
let builtinReconcileChain: Promise<void> = Promise.resolve();
+type BuiltinReconcileOutcome = 'completed' | 'deferred' | 'failed' | 'retry-pending';
+let stableOwnerPostCommitTask: ((reason: string) => Promise<BuiltinReconcileOutcome>) | null = null;
+
+/** Run the Plugin post-commit pipeline registered during Ghost IPC bootstrap. */
+export function runStableOwnerPostCommitTask(reason: string): Promise<BuiltinReconcileOutcome> {
+ return stableOwnerPostCommitTask?.(reason) ?? Promise.resolve('deferred');
+}
+
/**
* 本会话内因「撤销陈旧批准」被熄灯的常驻随包插件 id。
*
@@ -1037,7 +1053,7 @@ let builtinReconcileChain: Promise<void> = Promise.resolve();
*/
const quenchedResidentBuiltinIds = new Set<string>();
-function scheduleBuiltinReconcile(reason: string): Promise<boolean> {
+function scheduleBuiltinReconcile(reason: string): Promise<BuiltinReconcileOutcome> {
const scheduled = builtinReconcileChain
.catch((err) => {
log.warn('builtin ghost activation error; reconcile chain resumed', {
@@ -1046,14 +1062,13 @@ function scheduleBuiltinReconcile(reason: string): Promise<boolean> {
})
.then(async () => {
try {
- await reconcileBuiltinGhosts(reason);
- return true;
+ return await reconcileBuiltinGhosts(reason);
} catch (err) {
log.warn('builtin ghost reconcile error', {
reason,
error: err instanceof Error ? err.message : String(err),
});
- return false;
+ return 'failed' as const;
}
});
builtinReconcileChain = scheduled.then(() => undefined);
@@ -1130,20 +1145,21 @@ function migrateGhostKvOnRename(fromId: string, toId: string): void {
}
/** 单轮对账:一次性 legacy 迁移 → 播种 → (有变化时)广播 + 首装停靠 + 常驻点火。 */
-async function reconcileBuiltinGhosts(reason: string): Promise<void> {
+async function reconcileBuiltinGhosts(reason: string): Promise<BuiltinReconcileOutcome> {
// 整轮对账(迁移 backfill + 播种换目录 + 批准 receipt 写入)都是 owner 绑定的
// 文件系统写路径,但 GhostManager/ReceiptStore 的根目录是**每次调用现解析**的:
// 异步 hash/copy 中途账号切换落定,后半段写入就会漏进新 owner 的状态根(拿 A 的
// 安装目录字节给 B 的同 id 插件铸批准)。与市场装入同一套约束:开工前捕获 owner、
// 全程持 mutation 租约(账号 teardown 会等租约),边界期一律整轮跳过 —— 对账是
- // 幂等的,下一次触发(startup/auth-change)会补上。
+ // 幂等的;下一次 stable-owner post-commit/ensure 会补上。
let releaseMutation: () => void;
try {
releaseMutation = beginGhostMutation(captureGhostMutationOwner());
} catch {
log.info('builtin ghost reconcile skipped: app session boundary', { reason });
- return;
+ return 'deferred';
}
+ let migrationNeedsRetry = false;
try {
const manager = getGhostManager();
// 存量插件迁移必须先于播种与授权消费:#1080 之前装的插件没有 receipt,这里从旧安装
@@ -1151,8 +1167,11 @@ async function reconcileBuiltinGhosts(reason: string): Promise<void> {
// 之后 ledger 存在即瞬时 no-op,所以放在每轮 reconcile 前都安全。它自己取事务锁,因此
// 必须在下面 runExclusiveMutation **之外**调用(锁内再取锁会死锁),两次顺序取锁。
try {
- await manager.migrateLegacyApprovalsOnce();
+ const migration = await manager.migrateLegacyApprovalsOnce();
+ migrationNeedsRetry =
+ migration.retryPending.length > 0 || manager.hasPendingLegacyApprovalMigration();
} catch (err) {
+ migrationNeedsRetry = true;
// 迁移整体失败(如状态根不可写)不能挡住播种与后续对账:随包插件仍要能装/更新,
// 存量插件保持 fail-closed(列停用、走恢复 UI),下一轮启动再尝试迁移。
log.warn('legacy ghost approval migration pass failed', {
@@ -1160,19 +1179,21 @@ async function reconcileBuiltinGhosts(reason: string): Promise<void> {
error: err instanceof Error ? err.message : String(err),
});
}
- await manager.runExclusiveMutation((mutation) =>
+ const approvalNeedsRetry = await manager.runExclusiveMutation((mutation) =>
reconcileBuiltinGhostsLocked(reason, manager, mutation),
);
+ migrationNeedsRetry ||= approvalNeedsRetry;
} finally {
releaseMutation();
}
+ return migrationNeedsRetry ? 'retry-pending' : 'completed';
}
async function reconcileBuiltinGhostsLocked(
reason: string,
manager: GhostManager,
mutation: GhostExclusiveMutation,
-): Promise<void> {
+): Promise<boolean> {
// 改名前置:用户自主状态(墓碑=卸载过 / .disabled=停用)随改名带到新 id,
// 不能让"明确卸载/停用过"的用户在升级后被以新 id 重新装上并点亮(播种器
// "用户自主权豁免"支柱)。墓碑:旧 id 有 → 给新 id 记墓碑并清掉旧墓碑
@@ -1270,6 +1291,7 @@ async function reconcileBuiltinGhostsLocked(
}
}
let approvalChanged = false;
+ let approvalNeedsRetry = false;
const healedResidentIds: string[] = [];
for (const manifest of outcome.approved) {
try {
@@ -1288,6 +1310,7 @@ async function reconcileBuiltinGhostsLocked(
healedResidentIds.push(manifest.id);
}
} catch (err) {
+ approvalNeedsRetry = true;
// 走到这里内容目录可能已经换成新种子字节,旧 receipt 却还是授权事实 ——
// 留着它就是拿旧批准跑新代码(新版删掉的 slot 仍被授予、版本与技能快照
// 也停在旧 revision)。
@@ -1324,7 +1347,7 @@ async function reconcileBuiltinGhostsLocked(
outcome.removed.length === 0 &&
!approvalChanged
) {
- return;
+ return approvalNeedsRetry;
}
log.info('builtin ghost reconcile applied changes', {
reason,
@@ -1362,6 +1385,7 @@ async function reconcileBuiltinGhostsLocked(
const ghost = manager.list().find((g) => g.manifest.id === id);
if (ghost) spawnIfResident(ghost);
}
+ return approvalNeedsRetry;
}
export function getGhostManager(): GhostManager {
@@ -3660,22 +3684,26 @@ function withActiveOwnerGhostOauthMutationLock<T>(
}
/** Reconcile migration markers once for every committed owner scope. */
-export async function reconcileGhostOauthAccountsForActiveOwner(): Promise<void> {
+export async function reconcileGhostOauthAccountsForActiveOwner(): Promise<boolean> {
const ownerScope = activeOwnerScopeKey();
- await ghostOauthOwnerReconciliationGate.run(ownerScope, async () => {
+ return ghostOauthOwnerReconciliationGate.run(ownerScope, async () => {
if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== ownerScope) return false;
const oauthManager = getGhostOauthAccountManager();
+ let retryPending = false;
for (const ghost of getGhostManager().list()) {
await withActiveOwnerGhostOauthMutationLock(ghost.manifest.id, () => {
if (activeOwnerScopeKey() !== ownerScope) {
throw new Error('Plugin OAuth owner changed during reconciliation');
}
- oauthManager.reconcileAccountsForInstalledManifest(
+ const reconciliation = oauthManager.reconcileAccountsForInstalledManifestWithResult(
withRuntimeFiloGoogleClient(ghost.manifest),
);
+ if (reconciliation.retryPending) retryPending = true;
});
}
- return !isAppSessionBoundaryPending() && activeOwnerScopeKey() === ownerScope;
+ return !retryPending
+ && !isAppSessionBoundaryPending()
+ && activeOwnerScopeKey() === ownerScope;
});
}
@@ -3684,6 +3712,7 @@ function getGhostOauthAccountManager(): GhostOauthAccountManager {
ghostOauthManagerSingleton = new GhostOauthAccountManager({
vault: {
read: (ghostId, storageKey) => readGhostSecret(ghostId, storageKey),
+ readStrict: (ghostId, storageKey) => readGhostSecretStrict(ghostId, storageKey),
store: (ghostId, storageKey, value) => storeGhostSecret(ghostId, storageKey, value),
remove: (ghostId, storageKey) => removeGhostSecret(ghostId, storageKey),
},
@@ -3755,13 +3784,6 @@ function getGhostOauthAccountManager(): GhostOauthAccountManager {
},
withMutationLock: withActiveOwnerGhostOauthMutationLock,
});
- queueMicrotask(() => {
- void reconcileGhostOauthAccountsForActiveOwner().catch((error) => {
- log.warn('ghost oauth startup reconciliation failed', {
- error: error instanceof Error ? error.message : String(error),
- });
- });
- });
}
return ghostOauthManagerSingleton;
}
@@ -4684,6 +4706,36 @@ function spawnIfResident(ghost: InstalledGhost): void {
});
}
+function readLegacyJson<T>(
+ file: string,
+ parse: (raw: unknown) => T | null,
+): LegacyMigrationRead<T> {
+ try {
+ const parsed = parse(JSON.parse(fs.readFileSync(file, 'utf-8')) as unknown);
+ return parsed === null
+ ? LEGACY_MIGRATION_RETRYABLE_FAILURE
+ : legacyMigrationAvailable(parsed);
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === 'ENOENT'
+ ? LEGACY_MIGRATION_MISSING
+ : LEGACY_MIGRATION_RETRYABLE_FAILURE;
+ }
+}
+
+function readLegacyEncryptedSecret(file: string): LegacyMigrationRead<string> {
+ try {
+ if (!safeStorage.isEncryptionAvailable()) return LEGACY_MIGRATION_RETRYABLE_FAILURE;
+ const value = safeStorage.decryptString(Buffer.from(fs.readFileSync(file, 'utf-8'), 'base64'));
+ return value.length > 0
+ ? legacyMigrationAvailable(value)
+ : LEGACY_MIGRATION_RETRYABLE_FAILURE;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === 'ENOENT'
+ ? LEGACY_MIGRATION_MISSING
+ : LEGACY_MIGRATION_RETRYABLE_FAILURE;
+ }
+}
+
export function registerGhostIpc(): void {
if (ipcRegistered) return;
ipcRegistered = true;
@@ -4910,18 +4962,12 @@ export function registerGhostIpc(): void {
getGhostNodeRuntimeBroker().destroyAll();
});
- // 启动序列(必须等 app ready:registerGhostIpc 在 bootstrap 顶层(ready 前)
- // 执行,而沙箱创建(session.fromPartition / new BrowserWindow)在 ready 前会
- // 直接 throw(review P0——早点火会把该意识状态机与协议分区一起打死)):
- // 1) 内置意识播种对账:「永远以最新包为准」+ 受众(provisioning.json)。
- // 启动跑一次(authManager 已在 bootstrap 恢复持久化登录态,此刻身份可读),
- // 此后登录 / 登出 / 切账号每次变化再对账 —— 定向种子登录后装上、登出回收;
- // 'all' 种子与身份无关,登出也在。对账串行化(chain),auth 抖动不并发。
- // 2) 常驻意识开机点火:把"已唤醒 + launch: resident"的电子脑拉起(§4 懒加载
- // 的显式例外——作者声明过、装入确认框摊过牌)。刻意排在首次对账之后,新
- // 播种的常驻意识同一趟点火;后续对账装上的由 reconcile 自己点火。
- const activateGhostsAndMigrateLegacyAccounts = (): void => {
+ // Stable-owner 后处理序列:先完成内置插件对账,再恢复常驻插件和旧账号凭证。
+ // 旧凭证迁移保持 best-effort,不阻塞其他插件;任一迁移异常会把本 owner scope
+ // 保持为 retry-pending,避免被 coordinator 误记为完成。
+ const activateGhostsAndMigrateLegacyAccounts = (): 'completed' | 'retry-pending' => {
for (const ghost of manager.list()) spawnIfResident(ghost);
+ let legacyMigrationNeedsRetry = false;
const activeOwnerId = getActiveAppSession().dataOwnerId;
const canMigrateLegacyAccounts =
getAppCapabilities().canUseCindyAccountServices &&
@@ -4936,30 +4982,19 @@ export function registerGhostIpc(): void {
) {
try {
const legacyDir = path.join(app.getPath('userData'), 'safe-storage');
- const migrated = migrateFiloGoogleAccounts({
+ const migration = migrateFiloGoogleAccountsWithResult({
readLegacyManifest: () => {
- try {
- const raw = JSON.parse(
- fs.readFileSync(path.join(legacyDir, 'google_accounts.json'), 'utf-8'),
- ) as { accounts?: unknown };
- if (!Array.isArray(raw.accounts)) return null;
- return { accounts: raw.accounts as LegacyGoogleAccountRow[] };
- } catch {
- return null;
- }
- },
- readLegacyRefreshToken: (accountId) => {
- try {
- if (!safeStorage.isEncryptionAvailable()) return null;
- const file = path.join(legacyDir, `google_account_refresh_token_${accountId}.enc`);
- if (!fs.existsSync(file)) return null;
- return safeStorage.decryptString(
- Buffer.from(fs.readFileSync(file, 'utf-8'), 'base64'),
- );
- } catch {
- return null;
- }
+ return readLegacyJson(path.join(legacyDir, 'google_accounts.json'), (raw) => {
+ if (!raw || typeof raw !== 'object') return null;
+ const candidate = raw as { accounts?: unknown };
+ if (!Array.isArray(candidate.accounts)) return null;
+ return { accounts: candidate.accounts as LegacyGoogleAccountRow[] };
+ });
},
+ readLegacyRefreshToken: (accountId) =>
+ readLegacyEncryptedSecret(
+ path.join(legacyDir, `google_account_refresh_token_${accountId}.enc`),
+ ),
vault: {
read: (ghostId, storageKey) => readGhostSecret(ghostId, storageKey),
store: (ghostId, storageKey, value) => storeGhostSecret(ghostId, storageKey, value),
@@ -4967,13 +5002,15 @@ export function registerGhostIpc(): void {
},
log,
});
- if (migrated > 0) {
+ if (migration.retryPending) legacyMigrationNeedsRetry = true;
+ if (migration.migrated > 0) {
getGhostSetupChangeBus().emit(FILO_GOOGLE_GHOST_ID, {
source: 'oauth',
ref: FILO_GOOGLE_SECRET_KEY,
});
}
} catch (err) {
+ legacyMigrationNeedsRetry = true;
log.warn('filo-google 搬账意外失败(不阻断启动)', {
err: err instanceof Error ? err.message : String(err),
});
@@ -4988,29 +5025,15 @@ export function registerGhostIpc(): void {
) {
try {
const legacyDir = path.join(app.getPath('userData'), 'safe-storage');
- const migrated = migrateAtlassianAccounts({
- readLegacyRefreshToken: () => {
- try {
- if (!safeStorage.isEncryptionAvailable()) return null;
- const file = path.join(legacyDir, LEGACY_JIRA_RT_FILE);
- if (!fs.existsSync(file)) return null;
- return safeStorage.decryptString(
- Buffer.from(fs.readFileSync(file, 'utf-8'), 'base64'),
- );
- } catch {
- return null;
- }
- },
- readLegacyConnection: () => {
- try {
- const raw = JSON.parse(
- fs.readFileSync(path.join(legacyDir, LEGACY_JIRA_CONNECTION_FILE), 'utf-8'),
- ) as { email?: unknown };
- return { email: typeof raw.email === 'string' ? raw.email : null };
- } catch {
- return null;
- }
- },
+ const migration = migrateAtlassianAccountsWithResult({
+ readLegacyRefreshToken: () =>
+ readLegacyEncryptedSecret(path.join(legacyDir, LEGACY_JIRA_RT_FILE)),
+ readLegacyConnection: () =>
+ readLegacyJson(path.join(legacyDir, LEGACY_JIRA_CONNECTION_FILE), (raw) => {
+ if (!raw || typeof raw !== 'object') return null;
+ const candidate = raw as { email?: unknown };
+ return { email: typeof candidate.email === 'string' ? candidate.email : null };
+ }),
vault: {
read: (ghostId, storageKey) => readGhostSecret(ghostId, storageKey),
store: (ghostId, storageKey, value) => storeGhostSecret(ghostId, storageKey, value),
@@ -5018,13 +5041,15 @@ export function registerGhostIpc(): void {
},
log,
});
- if (migrated > 0) {
+ if (migration.retryPending) legacyMigrationNeedsRetry = true;
+ if (migration.migrated > 0) {
getGhostSetupChangeBus().emit(XD_ATLASSIAN_GHOST_ID, {
source: 'oauth',
ref: XD_ATLASSIAN_SECRET_KEY,
});
}
} catch (err) {
+ legacyMigrationNeedsRetry = true;
log.warn('xd-atlassian 搬账意外失败(不阻断启动)', {
err: err instanceof Error ? err.message : String(err),
});
@@ -5042,42 +5067,30 @@ export function registerGhostIpc(): void {
) {
try {
const legacyDir = path.join(app.getPath('userData'), 'safe-storage');
- const migrated = migrateGithubAccounts({
- readLegacyToken: () => {
- try {
- if (!safeStorage.isEncryptionAvailable()) return null;
- const file = path.join(legacyDir, LEGACY_GITHUB_TOKEN_FILE);
- if (!fs.existsSync(file)) return null;
- return safeStorage.decryptString(
- Buffer.from(fs.readFileSync(file, 'utf-8'), 'base64'),
- );
- } catch {
- return null;
- }
- },
- readLegacyConnection: () => {
- try {
- const raw = JSON.parse(
- fs.readFileSync(path.join(legacyDir, LEGACY_GITHUB_CONNECTION_FILE), 'utf-8'),
- ) as { host?: unknown };
- return { host: typeof raw.host === 'string' ? raw.host : null };
- } catch {
- return null;
- }
- },
+ const migration = migrateGithubAccountsWithResult({
+ readLegacyToken: () =>
+ readLegacyEncryptedSecret(path.join(legacyDir, LEGACY_GITHUB_TOKEN_FILE)),
+ readLegacyConnection: () =>
+ readLegacyJson(path.join(legacyDir, LEGACY_GITHUB_CONNECTION_FILE), (raw) => {
+ if (!raw || typeof raw !== 'object') return null;
+ const candidate = raw as { host?: unknown };
+ return { host: typeof candidate.host === 'string' ? candidate.host : null };
+ }),
vault: {
read: (ghostId, storageKey) => readGhostSecret(ghostId, storageKey),
store: (ghostId, storageKey, value) => storeGhostSecret(ghostId, storageKey, value),
},
log,
});
- if (migrated > 0) {
+ if (migration.retryPending) legacyMigrationNeedsRetry = true;
+ if (migration.migrated > 0) {
getGhostSetupChangeBus().emit(CINDY_GITHUB_GHOST_ID, {
source: 'secret',
ref: CINDY_GITHUB_SECRET_KEY,
});
}
} catch (err) {
+ legacyMigrationNeedsRetry = true;
log.warn('cindy-github 搬账意外失败(不阻断启动)', {
err: err instanceof Error ? err.message : String(err),
});
@@ -5093,19 +5106,9 @@ export function registerGhostIpc(): void {
) {
try {
const legacyDir = path.join(app.getPath('userData'), 'safe-storage');
- const migrated = migrateGitlabAccounts({
- readLegacyToken: () => {
- try {
- if (!safeStorage.isEncryptionAvailable()) return null;
- const file = path.join(legacyDir, LEGACY_GITLAB_TOKEN_FILE);
- if (!fs.existsSync(file)) return null;
- return safeStorage.decryptString(
- Buffer.from(fs.readFileSync(file, 'utf-8'), 'base64'),
- );
- } catch {
- return null;
- }
- },
+ const migration = migrateGitlabAccountsWithResult({
+ readLegacyToken: () =>
+ readLegacyEncryptedSecret(path.join(legacyDir, LEGACY_GITLAB_TOKEN_FILE)),
legacyTokenExists: () => {
try {
return fs.existsSync(path.join(legacyDir, LEGACY_GITLAB_TOKEN_FILE));
@@ -5113,39 +5116,36 @@ export function registerGhostIpc(): void {
return false;
}
},
- readLegacyConnection: () => {
- try {
- const raw = JSON.parse(
- fs.readFileSync(path.join(legacyDir, LEGACY_GITLAB_CONNECTION_FILE), 'utf-8'),
- ) as { baseUrl?: unknown; username?: unknown };
+ readLegacyConnection: () =>
+ readLegacyJson(path.join(legacyDir, LEGACY_GITLAB_CONNECTION_FILE), (raw) => {
+ if (!raw || typeof raw !== 'object') return null;
+ const candidate = raw as { baseUrl?: unknown; username?: unknown };
return {
- baseUrl: typeof raw.baseUrl === 'string' ? raw.baseUrl : null,
- username: typeof raw.username === 'string' ? raw.username : null,
+ baseUrl: typeof candidate.baseUrl === 'string' ? candidate.baseUrl : null,
+ username: typeof candidate.username === 'string' ? candidate.username : null,
};
- } catch {
- return null;
- }
- },
+ }),
manager: getGhostConnectionManager(),
log,
});
- if (migrated > 0) {
+ if (migration.retryPending) legacyMigrationNeedsRetry = true;
+ if (migration.migrated > 0) {
getGhostSetupChangeBus().emit(CINDY_GITLAB_GHOST_ID, {
source: 'connection',
ref: CINDY_GITLAB_CONNECTION_KEY,
});
}
} catch (err) {
+ legacyMigrationNeedsRetry = true;
log.warn('cindy-gitlab 搬账意外失败(不阻断启动)', {
err: err instanceof Error ? err.message : String(err),
});
}
}
+ return legacyMigrationNeedsRetry ? 'retry-pending' : 'completed';
};
void app.whenReady().then(() => {
- void scheduleBuiltinReconcile('startup');
- builtinReconcileChain = builtinReconcileChain.then(activateGhostsAndMigrateLegacyAccounts);
onAuthStateChange(() => {
// Login/logout, Membership switches, and refresh integration all cross
// an auth notification boundary. Discard every short-lived Connection
@@ -5161,11 +5161,20 @@ export function registerGhostIpc(): void {
// 未读账本按 owner 分文件,换账号后必须整表替换,否则账号 A 的绿点与摘要
// 会留在账号 B 的插件入口与卡片上(跨账号残留)。
broadcastGhostUnreadSnapshot();
- void scheduleBuiltinReconcile('auth-change');
- builtinReconcileChain = builtinReconcileChain.then(activateGhostsAndMigrateLegacyAccounts);
});
});
+ stableOwnerPostCommitTask = async (reason) => {
+ const outcome = await scheduleBuiltinReconcile(reason);
+ if (outcome === 'deferred') return outcome;
+ const activationOutcome = activateGhostsAndMigrateLegacyAccounts();
+ return outcome === 'failed'
+ ? 'failed'
+ : outcome === 'retry-pending' || activationOutcome === 'retry-pending'
+ ? 'retry-pending'
+ : 'completed';
+ };
+
// ── 管子(脑机接口)main 侧 handler(docs/dev-rules/plugin-security-and-authoring.md)──────────────
// 身份不信任 sender 自报,一律按 webContents id 反查绑定表验身。
// 上行白名单:tool-result(交卷,派发器配对验身)/ tool-progress(长任务
diff --git a/apps/desktop/src/main/cindy-brain/legacyMigrationRead.ts b/apps/desktop/src/main/cindy-brain/legacyMigrationRead.ts
new file mode 100644
index 0000000000..daccb184aa
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/legacyMigrationRead.ts
@@ -0,0 +1,18 @@
+/**
+ * Distinguishes an absent legacy value from a transient read failure.
+ * Migration callers may safely complete on `missing`, but must keep the
+ * stable-owner scope retryable when the old storage could not be inspected.
+ */
+export type LegacyMigrationRead<T> =
+ | { status: 'available'; value: T }
+ | { status: 'missing' }
+ | { status: 'retryable-failure' };
+
+export function legacyMigrationAvailable<T>(value: T): LegacyMigrationRead<T> {
+ return { status: 'available', value };
+}
+
+export const LEGACY_MIGRATION_MISSING: LegacyMigrationRead<never> = { status: 'missing' };
+export const LEGACY_MIGRATION_RETRYABLE_FAILURE: LegacyMigrationRead<never> = {
+ status: 'retryable-failure',
+};
diff --git a/apps/desktop/src/main/ownerNamespaceMigration.ts b/apps/desktop/src/main/ownerNamespaceMigration.ts
index cca9cfb20d..11d295b439 100644
--- a/apps/desktop/src/main/ownerNamespaceMigration.ts
+++ b/apps/desktop/src/main/ownerNamespaceMigration.ts
@@ -1535,8 +1535,10 @@ export async function recoverLegacyGhostPlugins(
!options.rejectReservedIds || !isOfficialGhostId(id);
const sourceDiscoveryIds = new Set([...discoveredSourceIds].filter(isRecoverableId));
const targetDiscoveryIds = new Set(targetDiscovery.ghosts.map((ghost) => ghost.id));
+ const visiblePendingIds = (recoveryMarker?.pendingIds ?? []).filter(isRecoverableId);
+ const hasVisibleFrozenWhitelist = recoveryMarker !== null && visiblePendingIds.length > 0;
const pendingRecoveryIds = new Set(
- [...(recoveryMarker?.pendingIds ?? sourceDiscoveryIds)].filter(isRecoverableId),
+ [...(hasVisibleFrozenWhitelist ? visiblePendingIds : sourceDiscoveryIds)],
);
const approvalProjectionSha256ById = new Map<string, string>(
Object.entries(recoveryMarker?.approvalProjectionSha256ById ?? {})
@@ -1603,7 +1605,7 @@ export async function recoverLegacyGhostPlugins(
return result;
}
let movableLegacyGhosts: ReturnType<typeof listLegacyGhostDirs> = [];
- const unexpectedFrozenIds = recoveryMarker
+ const unexpectedFrozenIds = hasVisibleFrozenWhitelist
? [...sourceDiscoveryIds].filter((id) => !pendingRecoveryIds.has(id))
: [];
let conflicts = (sharedRecoveryBlocked ? sharedLegacyGhosts.length : 0) +
@@ -1614,7 +1616,7 @@ export async function recoverLegacyGhostPlugins(
conflicts += 1;
continue;
}
- if (recoveryMarker && !pendingRecoveryIds.has(legacy.id)) {
+ if (hasVisibleFrozenWhitelist && !pendingRecoveryIds.has(legacy.id)) {
continue;
}
if (failedRecoveryIds.has(legacy.id)) {
diff --git a/apps/desktop/src/main/plugin-market/__tests__/defaultMarketPluginSyncOutcome.test.ts b/apps/desktop/src/main/plugin-market/__tests__/defaultMarketPluginSyncOutcome.test.ts
new file mode 100644
index 0000000000..c9410844d5
--- /dev/null
+++ b/apps/desktop/src/main/plugin-market/__tests__/defaultMarketPluginSyncOutcome.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PluginMarketSnapshot } from '../../../shared/pluginMarket';
+import { defaultMarketPluginSyncOutcome } from '../registerIpc';
+
+function snapshot(unavailableReason: string | null): PluginMarketSnapshot {
+ return {
+ items: [],
+ unavailableReason,
+ customSourceNames: [],
+ unavailableCustomSourceNames: [],
+ };
+}
+
+describe('defaultMarketPluginSyncOutcome', () => {
+ it('completes when the official market is available or intentionally not configured', () => {
+ expect(defaultMarketPluginSyncOutcome(snapshot(null))).toBe('completed');
+ expect(defaultMarketPluginSyncOutcome(snapshot('not-configured'))).toBe('completed');
+ });
+
+ it('defers while owner authentication is not stable', () => {
+ expect(defaultMarketPluginSyncOutcome(snapshot('session-switching'))).toBe('deferred');
+ expect(defaultMarketPluginSyncOutcome(snapshot('authentication-required'))).toBe('deferred');
+ });
+
+ it('fails retryably when the configured market request is unavailable', () => {
+ expect(defaultMarketPluginSyncOutcome(snapshot('network unavailable'))).toBe('failed');
+ });
+
+ it('fails retryably when an individual default install or upgrade failed', () => {
+ expect(defaultMarketPluginSyncOutcome(snapshot(null), 'failed')).toBe('failed');
+ });
+});
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 bf7cdbccc5..803d282340 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
@@ -21,6 +21,10 @@ describe('Plugin Market IPC error boundary', () => {
resolve(process.cwd(), 'src/main/bootstrap-electron.ts'),
'utf8',
).replace(/\r\n/g, '\n');
+ const authManagerSource = readFileSync(
+ resolve(process.cwd(), 'src/main/authManager.ts'),
+ 'utf8',
+ ).replace(/\r\n/g, '\n');
const ghostPluginPageSource = readFileSync(
resolve(process.cwd(), 'src/renderer/features/plugin/GhostPluginPage.tsx'),
'utf8',
@@ -42,9 +46,8 @@ describe('Plugin Market IPC error boundary', () => {
const body = registerSource.slice(start, end);
expect(body).toContain('isPluginMarketCustomIconKey(expectedIconKey)');
- expect(registerSource).toContain(
- "import { isPluginMarketCustomIconKey } from '../../shared/pluginMarket.js';",
- );
+ expect(registerSource).toContain('isPluginMarketCustomIconKey,');
+ expect(registerSource).toContain("from '../../shared/pluginMarket.js';");
expect(body).toContain('localIconRequestGate.tryRun');
expect(body).toContain(
"throwIpcError('PRECONDITION_FAILED', 'Too many local Plugin icon requests');",
@@ -87,12 +90,27 @@ describe('Plugin Market IPC error boundary', () => {
it('runs default plugin reconciliation on cold start and stable owner changes', () => {
const syncStart = registerSource.indexOf(
- 'export async function syncDefaultMarketPlugins(): Promise<void>',
+ 'export async function syncDefaultMarketPlugins(): Promise<DefaultMarketPluginSyncOutcome>',
);
const syncEnd = registerSource.indexOf('\n}\n\n/**\n * Preserve stable IPC errors', syncStart);
const syncBody = registerSource.slice(syncStart, syncEnd);
- expect(syncBody).toContain('await snapshotAndSignalRemovalNotice();');
+ expect(syncBody).toContain('const snapshot = await snapshotAndSignalRemovalNotice({');
+ expect(syncBody).toContain('onDefaultReconciliationOutcome: (outcome) => {');
+ expect(syncBody).toContain("reconciliationOutcome ?? 'completed'");
+ expect(syncBody).toContain('defaultMarketPluginSyncOutcome(');
expect(syncBody).toContain("log.warn('default plugin startup sync failed'");
+ expect(syncBody).toContain("return 'failed';");
+
+ const outcomeStart = registerSource.indexOf(
+ 'export function defaultMarketPluginSyncOutcome(',
+ );
+ const outcomeEnd = registerSource.indexOf('\n}\n\nexport async function syncDefaultMarketPlugins', outcomeStart);
+ const outcomeBody = registerSource.slice(outcomeStart, outcomeEnd);
+ expect(outcomeBody).toContain("snapshot.unavailableReason === 'not-configured'");
+ expect(outcomeBody).toContain("snapshot.unavailableReason === 'session-switching'");
+ expect(outcomeBody).toContain("snapshot.unavailableReason === 'authentication-required'");
+ expect(outcomeBody).toContain("return 'deferred';");
+ expect(outcomeBody).toContain("return 'failed';");
const snapshotStart = registerSource.indexOf(
'async function snapshotAndSignalRemovalNotice(options?: PluginMarketSnapshotOptions)',
@@ -103,6 +121,13 @@ describe('Plugin Market IPC error boundary', () => {
expect(snapshotBody).toContain('signalRemovalNoticeAvailable();');
expect(snapshotBody).toContain('signalUpgradeNoticeAvailable();');
+ expect(serviceSource).toContain("onDefaultReconciliationOutcome?: (outcome: 'completed' | 'failed') => void;");
+ expect(serviceSource).toContain("const outcome = completed ? 'completed' : 'failed';");
+ expect(serviceSource).toContain('options.onDefaultReconciliationOutcome?.(outcome);');
+ expect(serviceSource).toContain('if (!(await this.applyDefaultInstalls(plugins, owner, ledger))) completed = false;');
+ expect(serviceSource).toContain('if (!(await this.applyDefaultUpgrades(plugins, owner, ledger))) completed = false;');
+ expect(serviceSource).toContain('if (error instanceof SilentUpgradeBusyError) {');
+
expect(registerSource).toContain('deferDefaultReconciliation: true');
expect(registerSource).toContain('onDeferredReconciliationSettled: () => {');
expect(ghostPluginPageSource).toContain(
@@ -110,32 +135,30 @@ describe('Plugin Market IPC error boundary', () => {
);
expect(ghostPluginPageSource).toContain('void refreshMarket(true).catch(() => undefined);');
- const ownerSyncStart = bootstrapSource.indexOf(
- 'function syncDefaultPluginsForActiveOwner(): void',
+ const ownerTaskStart = bootstrapSource.indexOf(
+ 'authManager.setStableOwnerPostCommitTask(async ({ reason }) => {',
);
- const ownerSyncEnd = bootstrapSource.indexOf('\n}\n\nconst registerIpcHandlers', ownerSyncStart);
- const ownerSyncBody = bootstrapSource.slice(ownerSyncStart, ownerSyncEnd);
- expect(ownerSyncBody).toContain(
- 'if (!session.dataOwnerId || isAppSessionBoundaryPending()) return;',
- );
- expect(ownerSyncBody).toContain('if (scope === defaultPluginSyncInFlightScope) return;');
- expect(ownerSyncBody).toContain('void syncDefaultMarketPlugins().finally(() => {');
- expect(ownerSyncBody).toContain('defaultPluginSyncInFlightScope = null;');
-
- const listenerStart = bootstrapSource.indexOf(
- 'disposePluginMarketAuthListener = authManager.onAuthStateChange',
+ const ownerTaskEnd = bootstrapSource.indexOf('\n});', ownerTaskStart);
+ const ownerTaskBody = bootstrapSource.slice(ownerTaskStart, ownerTaskEnd);
+ expect(ownerTaskStart).toBeGreaterThan(-1);
+ expect(ownerTaskBody).toContain('await runStableOwnerPostCommitTask(reason)');
+ expect(ownerTaskBody).toContain("if (builtinOutcome === 'deferred') return builtinOutcome;");
+ expect(ownerTaskBody).not.toContain("builtinOutcome === 'failed') return builtinOutcome");
+ expect(ownerTaskBody).toContain("builtinOutcome === 'retry-pending'");
+ expect(ownerTaskBody).toContain("builtinOutcome === 'failed'");
+ expect(ownerTaskBody).toContain('const marketOutcome = await syncDefaultMarketPlugins()');
+ expect(ownerTaskBody).toContain("marketOutcome === 'failed'");
+ expect(ownerTaskBody).toContain("marketOutcome === 'deferred'");
+ expect(ownerTaskBody).toContain('await reconcileGhostOauthAccountsForActiveOwner()');
+ expect(ownerTaskBody).toContain(
+ "return needsRetry ? 'failed' : deferred ? 'deferred' : 'completed';",
);
- expect(listenerStart).toBeGreaterThan(-1);
- const listenerEnd = bootstrapSource.indexOf(
- '\n syncDefaultPluginsForActiveOwner();',
- listenerStart,
+ expect(bootstrapSource).toContain(
+ "await authManager.ensureStableOwnerPostCommitTasks('auth-initialize');",
);
- const listenerBody = bootstrapSource.slice(listenerStart, listenerEnd);
- expect(listenerBody).toContain('queueMicrotask(() => {');
- expect(listenerBody).toContain('syncDefaultPluginsForActiveOwner();');
- expect(listenerBody).toContain('reconcileGhostOauthForActiveOwner();');
- expect(bootstrapSource.slice(listenerEnd)).toContain('syncDefaultPluginsForActiveOwner();');
- expect(bootstrapSource.slice(listenerEnd)).toContain('reconcileGhostOauthForActiveOwner();');
- expect(bootstrapSource).toContain("'plugin-market-auth-listener'");
+ expect(authManagerSource).toContain("requestStableOwnerPostCommit('owner-commit');");
+ expect(authManagerSource).not.toContain("await ensureStableOwnerPostCommit('owner-commit');");
+ expect(bootstrapSource).not.toContain('disposePluginMarketAuthListener');
+ expect(bootstrapSource).not.toContain('syncDefaultPluginsForActiveOwner');
});
});
diff --git a/apps/desktop/src/main/plugin-market/registerIpc.ts b/apps/desktop/src/main/plugin-market/registerIpc.ts
index 77d42897f0..f8f98c8611 100644
--- a/apps/desktop/src/main/plugin-market/registerIpc.ts
+++ b/apps/desktop/src/main/plugin-market/registerIpc.ts
@@ -4,7 +4,10 @@ import { ipcMain, type WebContents } from 'electron';
import { isIpcError } from '../../shared/ipc-errors.js';
import { isGhostInstallApprovalToken, type GhostManifest } from '../../shared/ghost.js';
-import { isPluginMarketCustomIconKey } from '../../shared/pluginMarket.js';
+import {
+ isPluginMarketCustomIconKey,
+ type PluginMarketSnapshot,
+} from '../../shared/pluginMarket.js';
import { getActiveDataOwnerPushStamp } from '../appSessionState.js';
import {
sendToTrustedAppWindows,
@@ -62,13 +65,50 @@ async function snapshotAndSignalRemovalNotice(options?: PluginMarketSnapshotOpti
* default-install plugins are provisioned as soon as an app owner is ready.
* The Plugins page keeps the same call as a later retry path.
*/
-export async function syncDefaultMarketPlugins(): Promise<void> {
+export type DefaultMarketPluginSyncOutcome = 'completed' | 'deferred' | 'failed';
+
+export function defaultMarketPluginSyncOutcome(
+ snapshot: PluginMarketSnapshot,
+ reconciliationOutcome: 'completed' | 'failed' = 'completed',
+): DefaultMarketPluginSyncOutcome {
+ if (
+ (snapshot.unavailableReason === null || snapshot.unavailableReason === 'not-configured')
+ && reconciliationOutcome === 'completed'
+ ) {
+ return 'completed';
+ }
+ if (
+ snapshot.unavailableReason === 'session-switching'
+ || snapshot.unavailableReason === 'authentication-required'
+ ) {
+ return 'deferred';
+ }
+ return 'failed';
+}
+
+export async function syncDefaultMarketPlugins(): Promise<DefaultMarketPluginSyncOutcome> {
try {
- await snapshotAndSignalRemovalNotice();
+ let reconciliationOutcome: 'completed' | 'failed' | null = null;
+ const snapshot = await snapshotAndSignalRemovalNotice({
+ onDefaultReconciliationOutcome: (outcome) => {
+ reconciliationOutcome = outcome;
+ },
+ });
+ const outcome = defaultMarketPluginSyncOutcome(
+ snapshot,
+ reconciliationOutcome ?? 'completed',
+ );
+ if (outcome === 'failed') {
+ log.warn('default plugin startup sync incomplete', {
+ unavailableReason: snapshot.unavailableReason,
+ });
+ }
+ return outcome;
} catch (error) {
log.warn('default plugin startup sync failed', {
error: error instanceof Error ? error.message : String(error),
});
+ return 'failed';
}
}
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index e2eb703add..f53f0f609d 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -286,6 +286,8 @@ export interface PluginMarketSnapshotOptions {
deferDefaultReconciliation?: boolean;
/** 延后对账完成(成功或失败)后通知 IPC 层刷新一次性提示。 */
onDeferredReconciliationSettled?: () => void;
+ /** Main-only completion signal; it is not part of the Renderer snapshot. */
+ onDefaultReconciliationOutcome?: (outcome: 'completed' | 'failed') => void;
}
/**
@@ -595,11 +597,29 @@ export class PluginMarketService {
// before its ledger write. Wait for queued ledger mutations before deciding
// whether a default plugin should be installed again.
await this.ledgerMutation;
- const reconcileDefaults = async () => {
+ const reconcileDefaults = async (): Promise<'completed' | 'failed'> => {
// 自定义来源只影响自己的目录发现;暂时不可读的来源不能阻塞官方默认安装。
// 已经落地的同 id 插件仍由 applyDefaultInstalls → installDetail 的本地事实检查保护。
- await this.applyDefaultInstalls(plugins, owner, ledger);
- await this.applyDefaultUpgrades(plugins, owner, ledger);
+ let completed = true;
+ try {
+ if (!(await this.applyDefaultInstalls(plugins, owner, ledger))) completed = false;
+ } catch (error) {
+ completed = false;
+ log.warn('default plugin install reconciliation failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ try {
+ if (!(await this.applyDefaultUpgrades(plugins, owner, ledger))) completed = false;
+ } catch (error) {
+ completed = false;
+ log.warn('default plugin upgrade reconciliation failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ const outcome = completed ? 'completed' : 'failed';
+ options.onDefaultReconciliationOutcome?.(outcome);
+ return outcome;
};
if (!options.deferDefaultReconciliation) await reconcileDefaults();
requireSameMarketOwner(owner);
@@ -2151,7 +2171,8 @@ export class PluginMarketService {
plugins: readonly VisiblePluginSummary[],
owner: ActiveAppSession,
ledger: PluginMarketLedger,
- ): Promise<void> {
+ ): Promise<boolean> {
+ let completed = true;
const installSubject = defaultInstallSubject(owner);
const counts = ghostIdCounts(plugins);
const uniqueGhostIds = new Set(
@@ -2225,6 +2246,7 @@ export class PluginMarketService {
} catch (error) {
// 单个默认插件失败不拖垮整个市场;下次同步可重试。
if (!(error instanceof SilentDefaultInstallCancelledError)) {
+ completed = false;
log.warn('default plugin install failed', {
pluginId: summary.id,
error: error instanceof Error ? error.message : String(error),
@@ -2232,13 +2254,15 @@ export class PluginMarketService {
}
}
}
+ return completed;
}
private async applyDefaultUpgrades(
plugins: readonly VisiblePluginSummary[],
owner: ActiveAppSession,
ledger: PluginMarketLedger,
- ): Promise<void> {
+ ): Promise<boolean> {
+ let reconciled = true;
const local = this.localInstallSnapshot(ledger);
const completed: Array<{
name: string | null;
@@ -2251,8 +2275,10 @@ export class PluginMarketService {
hasPendingGhostCalls(summary.ghostId) ||
hasRunningGhostErrand(summary.ghostId) ||
hasRunningGhostCindyWork(summary.ghostId)
- )
+ ) {
+ reconciled = false;
continue;
+ }
try {
await this.withMutation(summary.id, async () => {
requireSameMarketOwner(owner);
@@ -2343,7 +2369,10 @@ export class PluginMarketService {
}
});
} catch (error) {
- if (!(error instanceof SilentUpgradeBusyError)) {
+ if (error instanceof SilentUpgradeBusyError) {
+ reconciled = false;
+ } else {
+ reconciled = false;
log.warn('default plugin upgrade failed', {
pluginId: summary.id,
error: error instanceof Error ? error.message : String(error),
@@ -2365,6 +2394,7 @@ export class PluginMarketService {
hasPermissionExpansion,
});
}
+ return reconciled;
}
private localInstallSnapshot(
diff --git a/apps/desktop/src/main/secrets/providerSecretStore.ts b/apps/desktop/src/main/secrets/providerSecretStore.ts
index 784b944c59..360c5eda60 100644
--- a/apps/desktop/src/main/secrets/providerSecretStore.ts
+++ b/apps/desktop/src/main/secrets/providerSecretStore.ts
@@ -636,6 +636,28 @@ export function readGhostSecret(ghostId: string, secretKey: string): string | nu
}
}
+/**
+ * Strict Ghost secret read for owner-stable repair jobs. Absence is still a
+ * normal null result, while keychain, IO, and decrypt failures remain errors
+ * so the durable coordinator can retry instead of memoizing a false no-op.
+ */
+export function readGhostSecretStrict(ghostId: string, secretKey: string): string | null {
+ const physicalKey = resolveOwnerScopedSecretStorageKey(
+ ghostSecretStorageKey(ghostId, secretKey),
+ );
+ if (!physicalKey) return null;
+ if (!safeStorage.isEncryptionAvailable()) {
+ throw new Error('safeStorage is unavailable');
+ }
+ const filepath = path.join(secretDir(), `${physicalKey}.enc`);
+ try {
+ return safeStorage.decryptString(Buffer.from(fs.readFileSync(filepath, 'utf-8'), 'base64'));
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
+ throw error;
+ }
+}
+
/**
* 只查某意识凭证是否已入库(加密文件存在性,**不解密**)。插件页 setup
* 就绪检查专用:判定只需要「存没存」,解密既无必要,还会把 safeStorage
diff --git a/apps/desktop/src/main/stableOwnerPostCommit.ts b/apps/desktop/src/main/stableOwnerPostCommit.ts
new file mode 100644
index 0000000000..5841cb4cb3
--- /dev/null
+++ b/apps/desktop/src/main/stableOwnerPostCommit.ts
@@ -0,0 +1,176 @@
+export type StableOwnerPostCommitOutcome =
+ | 'completed'
+ | 'deferred'
+ | 'failed'
+ | 'not-applicable';
+
+export interface StableOwnerPostCommitContext {
+ reason: string;
+ scopeKey: string;
+ dataOwnerId: string;
+}
+
+export type StableOwnerPostCommitTask = (
+ context: StableOwnerPostCommitContext,
+) => Promise<Exclude<StableOwnerPostCommitOutcome, 'not-applicable'>>;
+
+interface StableOwnerSnapshot {
+ scopeKey: string;
+ dataOwnerId: string | null;
+ stable: boolean;
+}
+
+interface StableOwnerPostCommitCoordinatorOptions {
+ snapshot: () => StableOwnerSnapshot;
+ warn: (message: string, meta: Record<string, unknown>) => void;
+ retryDelaysMs?: readonly number[];
+ scheduleRetry?: (callback: () => void, delayMs: number) => unknown;
+ cancelRetry?: (handle: unknown) => void;
+}
+
+const DEFAULT_RETRY_DELAYS_MS = [1_000, 5_000, 15_000, 60_000] as const;
+
+/**
+ * Serializes the owner-scoped work that must run after the durable Ghost
+ * projection boundary is stable. A completed scope is memoized, while a
+ * deferred or failed pass remains eligible for the next stable opportunity.
+ */
+export class StableOwnerPostCommitCoordinator {
+ private task: StableOwnerPostCommitTask | null = null;
+ private chain: Promise<void> = Promise.resolve();
+ private inFlight: {
+ scopeKey: string;
+ promise: Promise<StableOwnerPostCommitOutcome>;
+ } | null = null;
+ private completedScopeKey: string | null = null;
+ private retryHandle: unknown = null;
+ private retryScopeKey: string | null = null;
+ private retryAttempt = 0;
+ private taskGeneration = 0;
+
+ constructor(private readonly options: StableOwnerPostCommitCoordinatorOptions) {}
+
+ setTask(task: StableOwnerPostCommitTask | null): void {
+ this.cancelScheduledRetry();
+ this.task = task;
+ this.completedScopeKey = null;
+ this.taskGeneration += 1;
+ }
+
+ ensure(reason: string): Promise<StableOwnerPostCommitOutcome> {
+ const requested = this.options.snapshot();
+ if (this.retryScopeKey && this.retryScopeKey !== requested.scopeKey) {
+ this.cancelScheduledRetry();
+ }
+ if (!requested.dataOwnerId) return Promise.resolve('not-applicable');
+ const dataOwnerId = requested.dataOwnerId;
+ if (!requested.stable || !this.task) return Promise.resolve('deferred');
+ if (this.completedScopeKey === requested.scopeKey) return Promise.resolve('completed');
+ if (this.inFlight?.scopeKey === requested.scopeKey) return this.inFlight.promise;
+
+ const task = this.task;
+ if (!task) return Promise.resolve('deferred');
+ const scheduled = this.chain
+ .catch(() => undefined)
+ .then(async (): Promise<StableOwnerPostCommitOutcome> => {
+ const current = this.options.snapshot();
+ if (
+ !current.stable
+ || current.dataOwnerId !== requested.dataOwnerId
+ || current.scopeKey !== requested.scopeKey
+ ) {
+ return 'deferred';
+ }
+ try {
+ const outcome = await task({
+ reason,
+ scopeKey: requested.scopeKey,
+ dataOwnerId,
+ });
+ const settled = this.options.snapshot();
+ if (
+ outcome === 'completed'
+ && settled.stable
+ && settled.scopeKey === requested.scopeKey
+ && settled.dataOwnerId === requested.dataOwnerId
+ ) {
+ this.cancelScheduledRetry();
+ this.completedScopeKey = requested.scopeKey;
+ return 'completed';
+ }
+ const effectiveOutcome = outcome === 'completed' ? 'deferred' : outcome;
+ this.scheduleAutomaticRetry(requested, reason, effectiveOutcome);
+ return effectiveOutcome;
+ } catch (error) {
+ this.options.warn('stable owner post-commit task failed', {
+ reason,
+ scopeKey: requested.scopeKey,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ this.scheduleAutomaticRetry(requested, reason, 'failed');
+ return 'failed';
+ }
+ });
+
+ this.chain = scheduled.then(() => undefined);
+ this.inFlight = { scopeKey: requested.scopeKey, promise: scheduled };
+ void scheduled.then(() => {
+ if (this.inFlight?.promise === scheduled) this.inFlight = null;
+ });
+ return scheduled;
+ }
+
+ private scheduleAutomaticRetry(
+ requested: StableOwnerSnapshot,
+ reason: string,
+ outcome: Exclude<StableOwnerPostCommitOutcome, 'completed' | 'not-applicable'>,
+ ): void {
+ const current = this.options.snapshot();
+ if (
+ !current.stable
+ || current.scopeKey !== requested.scopeKey
+ || current.dataOwnerId !== requested.dataOwnerId
+ || !this.task
+ ) {
+ this.cancelScheduledRetry();
+ return;
+ }
+ if (this.retryHandle !== null && this.retryScopeKey === requested.scopeKey) return;
+
+ const delays = this.options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
+ const delayMs = delays[Math.min(this.retryAttempt, delays.length - 1)] ?? 60_000;
+ const generation = this.taskGeneration;
+ this.retryScopeKey = requested.scopeKey;
+ const schedule = this.options.scheduleRetry ?? ((callback, delay) => {
+ const handle = setTimeout(callback, delay);
+ handle.unref?.();
+ return handle;
+ });
+ this.retryHandle = schedule(() => {
+ this.retryHandle = null;
+ if (generation !== this.taskGeneration) return;
+ const latest = this.options.snapshot();
+ if (
+ !latest.stable
+ || latest.scopeKey !== requested.scopeKey
+ || latest.dataOwnerId !== requested.dataOwnerId
+ ) {
+ this.retryScopeKey = null;
+ this.retryAttempt = 0;
+ return;
+ }
+ this.retryAttempt += 1;
+ void this.ensure(`automatic-retry:${reason}:${outcome}`);
+ }, delayMs);
+ }
+
+ private cancelScheduledRetry(): void {
+ if (this.retryHandle !== null) {
+ const cancel = this.options.cancelRetry ?? ((handle) => clearTimeout(handle as NodeJS.Timeout));
+ cancel(this.retryHandle);
+ }
+ this.retryHandle = null;
+ this.retryScopeKey = null;
+ this.retryAttempt = 0;
+ }
+}