Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): retry stable owner reconciliation failures
Yuewei-LL508f1cfbcb84
diff --git a/apps/desktop/src/main/__tests__/stableOwnerPostCommit.test.ts b/apps/desktop/src/main/__tests__/stableOwnerPostCommit.test.tsindex 55f14930b9..32baf01b5e 100644--- a/apps/desktop/src/main/__tests__/stableOwnerPostCommit.test.ts+++ b/apps/desktop/src/main/__tests__/stableOwnerPostCommit.test.ts@@ -41,6 +41,24 @@ describe('StableOwnerPostCommitCoordinator', () => {expect(task).toHaveBeenCalledTimes(1);});+ it('runs and memoizes stable signed-out scopes for account-free post-commit work', async () => {+ const task = vi.fn().mockResolvedValue('completed');+ const coordinator = new StableOwnerPostCommitCoordinator({+ snapshot: () => ({ scopeKey: 'signed-out:none:1', dataOwnerId: null, stable: true }),+ warn: vi.fn(),+ });+ coordinator.setTask(task);++ await expect(coordinator.ensure('signed-out-startup')).resolves.toBe('completed');+ await expect(coordinator.ensure('signed-out-again')).resolves.toBe('completed');+ expect(task).toHaveBeenCalledTimes(1);+ expect(task).toHaveBeenCalledWith({+ reason: 'signed-out-startup',+ scopeKey: 'signed-out:none:1',+ dataOwnerId: null,+ });+ });+it('retries deferred and failed passes instead of caching false success', async () => {const task = vi.fn()diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.tsindex 62b0369240..705ddf7006 100644--- a/apps/desktop/src/main/authManager.ts+++ b/apps/desktop/src/main/authManager.ts@@ -261,8 +261,7 @@ const stableOwnerPostCommitCoordinator = new StableOwnerPostCommitCoordinator({scopeKey: activeOwnerScopeKey(),dataOwnerId: session.dataOwnerId,stable:- session.dataOwnerId !== null- && !isAppSessionBoundaryPending()+ !isAppSessionBoundaryPending()&& isGhostSkillProjectionBoundaryStableForOwner(session.dataOwnerId),};},diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex cbff691984..d89086525e 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -1740,11 +1740,14 @@ setCodexImageAuthBinding({});registerGhostIpc();registerPluginMarketIpc();-authManager.setStableOwnerPostCommitTask(async ({ reason }) => {- const builtinOutcome = await runStableOwnerPostCommitTask(reason);+authManager.setStableOwnerPostCommitTask(async ({ reason, scopeKey, dataOwnerId }) => {+ const builtinOutcome = await runStableOwnerPostCommitTask(reason, { scopeKey, dataOwnerId });if (builtinOutcome === 'deferred') return builtinOutcome;let needsRetry = builtinOutcome === 'retry-pending' || builtinOutcome === 'failed';+ // Signed-out is a real stable scope for account-free bundled provisioning.+ // Market and OAuth are owner-private follow-ups and stay behind this gate.+ if (dataOwnerId === null) return needsRetry ? 'failed' : 'completed';let deferred = false;const marketOutcome = await syncDefaultMarketPlugins();if (marketOutcome === 'failed') needsRetry = true;diff --git a/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.tsindex cd7cd17f54..0db889a69e 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts@@ -206,6 +206,65 @@ describe('builtin provisioning durable state', () => {expect(JSON.parse(await fs.promises.readFile(stateFile, 'utf8'))).toMatchObject({ seeded: [] });});+ it('keeps orphan removal failures retryable for the stable-owner pass', async () => {+ const root = await makeTempDir();+ const seedRoot = path.join(root, 'seeds');+ const repoRoot = path.join(root, 'installed');+ await writeMinimalSeed(seedRoot, 'current-builtin');+ await writeMinimalSeed(repoRoot, 'current-builtin');+ await writeMinimalSeed(repoRoot, 'retired-builtin');+ await fs.promises.writeFile(+ path.join(repoRoot, PROVISIONING_STATE_FILE),+ JSON.stringify({ removed: [], seeded: ['current-builtin', 'retired-builtin'] }),+ );+ const beforeRemove = vi.fn().mockRejectedValue(new Error('mutation journal unavailable'));++ const outcome = await provisionBuiltinGhosts({+ seedRootDirs: [seedRoot],+ repoRootDir: repoRoot,+ beforeRemove,+ });++ expect(outcome.retryPending).toBe(true);+ expect(outcome.removed).toEqual([]);+ expect(fs.existsSync(path.join(repoRoot, 'retired-builtin'))).toBe(true);+ expect(JSON.parse(await fs.promises.readFile(+ path.join(repoRoot, PROVISIONING_STATE_FILE),+ 'utf8',+ ))).toMatchObject({ seeded: ['current-builtin', 'retired-builtin'] });+ });++ it('keeps a failed final seeded-ledger update retryable for the stable-owner pass', async () => {+ const root = await makeTempDir();+ const seedRoot = path.join(root, 'seeds');+ const repoRoot = path.join(root, 'installed');+ await writeMinimalSeed(seedRoot, 'current-builtin');+ await writeMinimalSeed(repoRoot, 'current-builtin');+ await writeMinimalSeed(repoRoot, 'retired-builtin');+ await fs.promises.writeFile(+ path.join(repoRoot, PROVISIONING_STATE_FILE),+ JSON.stringify({ removed: [], seeded: ['current-builtin', 'retired-builtin'] }),+ );+ vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => {+ const error = new Error('state root temporarily busy') as NodeJS.ErrnoException;+ error.code = 'EBUSY';+ throw error;+ });++ const outcome = await provisionBuiltinGhosts({+ seedRootDirs: [seedRoot],+ repoRootDir: repoRoot,+ });++ expect(outcome.retryPending).toBe(true);+ expect(outcome.removed).toEqual(['retired-builtin']);+ expect(fs.existsSync(path.join(repoRoot, 'retired-builtin'))).toBe(false);+ expect(JSON.parse(await fs.promises.readFile(+ path.join(repoRoot, PROVISIONING_STATE_FILE),+ 'utf8',+ ))).toMatchObject({ seeded: ['current-builtin', 'retired-builtin'] });+ });+it('persists seeded ownership before replacing installed bytes', async () => {const root = await makeTempDir();const seedRoot = path.join(root, 'seeds');@@ -223,6 +282,24 @@ describe('builtin provisioning durable state', () => {await provisionBuiltinGhosts({ seedRootDirs: [seedRoot], repoRootDir: repoRoot, beforeReplace });expect(beforeReplace).toHaveBeenCalledTimes(1);});++ it('keeps transient publish failures retryable for the stable-owner pass', async () => {+ const root = await makeTempDir();+ const seedRoot = path.join(root, 'seeds');+ const repoRoot = path.join(root, 'installed');+ await writeMinimalSeed(seedRoot, 'builtin-test');+ const publishSeed = vi.fn().mockRejectedValue(new Error('state root temporarily busy'));++ const outcome = await provisionBuiltinGhosts({+ seedRootDirs: [seedRoot],+ repoRootDir: repoRoot,+ publishSeed,+ });++ expect(outcome.retryPending).toBe(true);+ expect(outcome.installed).toEqual([]);+ expect(publishSeed).toHaveBeenCalledTimes(1);+ });});describe('builtin seed source boundary', () => {@@ -502,6 +579,7 @@ describe('builtinGhostProvisioner 坏种子 fail closed', () => {});expect(outcome.skipped).toContain('bad-seed');+ expect(outcome.retryPending).toBeUndefined();expect(outcome.installed).toEqual([]);expect(outcome.approved).toEqual([]);expect(fs.existsSync(path.join(repoRoot, 'bad-seed'))).toBe(false);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryOrchestration.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryOrchestration.test.tsindex 06e71e7326..eeaf3ecb23 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryOrchestration.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryOrchestration.test.ts@@ -10,7 +10,7 @@ describe('legacy Ghost recovery acknowledgement orchestration', () => {'utf8',).replace(/\r\n?/g, '\n');- expect(source).toContain('stableOwnerPostCommitTask = async (reason) => {');+ expect(source).toContain('stableOwnerPostCommitTask = async (reason, scope) => {');expect(source).not.toContain("scheduleBuiltinReconcile('startup')");expect(source).not.toContain("scheduleBuiltinReconcile('auth-change')");expect(source).not.toContain('ghost oauth startup reconciliation failed');@@ -19,6 +19,10 @@ describe('legacy Ghost recovery acknowledgement orchestration', () => {expect(source).toContain('migrationNeedsRetry ||= approvalNeedsRetry;');expect(source).toContain('approvalNeedsRetry = true;');expect(source).toContain("if (outcome === 'deferred') return outcome;");+ expect(source).toContain('if (dataOwnerId !== null) {');+ expect(source).toContain('activeOwnerScopeKey() !== scope.scopeKey');+ expect(source).toContain('getActiveAppSession().dataOwnerId !== scope.dataOwnerId');+ expect(source).toContain('const activationOutcome = activateGhostsAndMigrateLegacyAccounts();');expect(source).toContain("return outcome === 'failed'");expect(source).toContain("const activateGhostsAndMigrateLegacyAccounts = (): 'completed' | 'retry-pending' => {",diff --git a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.tsindex ea8eea99bb..41f7dfd004 100644--- a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts+++ b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts@@ -142,6 +142,16 @@ export interface ProvisionOutcome {removed: string[];/** 指纹一致 / 墓碑 / 受众不命中 / 种子不合格而跳过的 id(仅日志用途)。 */skipped: string[];+ /** A transient per-seed or state I/O failure keeps the stable-owner pass retryable. */+ retryPending?: boolean;+}++function isRetryableProvisioningError(error: unknown): boolean {+ const message = error instanceof Error ? error.message : String(error);+ // Seed links/non-regular entries are deterministic package violations. Keep+ // them fail-closed without turning a bad bundle into an endless retry loop.+ if (message.includes('non-regular') || message.includes(' rejects link')) return false;+ return true;}/** 播种状态文件形态(墓碑 + seeded 台账;将来组织清单等扩展也落这里)。 */@@ -541,11 +551,13 @@ export async function provisionBuiltinGhosts(deps: ProvisionDeps): Promise<ProvirepoRootDir,});outcome.skipped.push(...allSeedIds);+ outcome.retryPending = true;return outcome;}const stateResult = readState(repoRootDir, log);if (!stateResult.readable) {outcome.skipped.push(...allSeedIds);+ outcome.retryPending = true;return outcome;}const state = stateResult.state;@@ -704,6 +716,7 @@ export async function provisionBuiltinGhosts(deps: ProvisionDeps): Promise<Provi// have partially changed bytes or approval state before throwing.if (!ownedBeforeAttempt && !ownershipClaimPersisted) seeded.delete(id);outcome.skipped.push(id);+ if (isRetryableProvisioningError(err)) outcome.retryPending = true;log?.warn('builtin ghost provisioning failed', {id,error: err instanceof Error ? err.message : String(err),@@ -750,6 +763,7 @@ export async function provisionBuiltinGhosts(deps: ProvisionDeps): Promise<Provioutcome.removed.push(id);log?.info('builtin ghost removed: seed no longer bundled', { id });} catch (err) {+ outcome.retryPending = true;log?.warn('builtin ghost orphan removal failed', {id,error: err instanceof Error ? err.message : String(err),@@ -762,7 +776,9 @@ export async function provisionBuiltinGhosts(deps: ProvisionDeps): Promise<Provi}if (!setsEqual(seeded, seededBefore)) {- writeState(repoRootDir, { removed: [...tombstones], seeded: [...seeded].sort() }, log);+ if (!writeState(repoRootDir, { removed: [...tombstones], seeded: [...seeded].sort() }, log)) {+ outcome.retryPending = true;+ }}return outcome;}diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 4a6644d104..f7fc086d93 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -1035,11 +1035,21 @@ function currentProvisionIdentity(): ProvisionIdentity | null {let builtinReconcileChain: Promise<void> = Promise.resolve();type BuiltinReconcileOutcome = 'completed' | 'deferred' | 'failed' | 'retry-pending';-let stableOwnerPostCommitTask: ((reason: string) => Promise<BuiltinReconcileOutcome>) | null = null;+interface BuiltinReconcileScope {+ scopeKey: string;+ dataOwnerId: string | null;+}++let stableOwnerPostCommitTask:+ ((reason: string, scope: BuiltinReconcileScope) => 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');+export function runStableOwnerPostCommitTask(+ reason: string,+ scope: BuiltinReconcileScope,+): Promise<BuiltinReconcileOutcome> {+ return stableOwnerPostCommitTask?.(reason, scope) ?? Promise.resolve('deferred');}/**@@ -1054,7 +1064,13 @@ export function runStableOwnerPostCommitTask(reason: string): Promise<BuiltinRec*/const quenchedResidentBuiltinIds = new Set<string>();-function scheduleBuiltinReconcile(reason: string): Promise<BuiltinReconcileOutcome> {+function scheduleBuiltinReconcile(+ reason: string,+ expectedScope: BuiltinReconcileScope = {+ scopeKey: activeOwnerScopeKey(),+ dataOwnerId: getActiveAppSession().dataOwnerId,+ },+): Promise<BuiltinReconcileOutcome> {const scheduled = builtinReconcileChain.catch((err) => {log.warn('builtin ghost activation error; reconcile chain resumed', {@@ -1062,8 +1078,16 @@ function scheduleBuiltinReconcile(reason: string): Promise<BuiltinReconcileOutco});}).then(async () => {+ const activeSession = getActiveAppSession();+ if (+ activeOwnerScopeKey() !== expectedScope.scopeKey ||+ activeSession.dataOwnerId !== expectedScope.dataOwnerId+ ) {+ log.info('builtin ghost reconcile skipped: stale owner scope', { reason });+ return 'deferred' as const;+ }try {- return await reconcileBuiltinGhosts(reason);+ return await reconcileBuiltinGhosts(reason, expectedScope.dataOwnerId);} catch (err) {log.warn('builtin ghost reconcile error', {reason,@@ -1146,7 +1170,10 @@ function migrateGhostKvOnRename(fromId: string, toId: string): void {}/** 单轮对账:一次性 legacy 迁移 → 播种 → (有变化时)广播 + 首装停靠 + 常驻点火。 */-async function reconcileBuiltinGhosts(reason: string): Promise<BuiltinReconcileOutcome> {+async function reconcileBuiltinGhosts(+ reason: string,+ dataOwnerId: string | null,+): Promise<BuiltinReconcileOutcome> {// 整轮对账(迁移 backfill + 播种换目录 + 批准 receipt 写入)都是 owner 绑定的// 文件系统写路径,但 GhostManager/ReceiptStore 的根目录是**每次调用现解析**的:// 异步 hash/copy 中途账号切换落定,后半段写入就会漏进新 owner 的状态根(拿 A 的@@ -1163,25 +1190,27 @@ async function reconcileBuiltinGhosts(reason: string): Promise<BuiltinReconcileOlet migrationNeedsRetry = false;try {const manager = getGhostManager();- // 存量插件迁移必须先于播种与授权消费:#1080 之前装的插件没有 receipt,这里从旧安装- // 布局 backfill 出等价批准,让它们升级后无感可用(docs §5 红线)。全局一次性 —— 首次- // 之后 ledger 存在即瞬时 no-op,所以放在每轮 reconcile 前都安全。它自己取事务锁,因此- // 必须在下面 runExclusiveMutation **之外**调用(锁内再取锁会死锁),两次顺序取锁。- try {- 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', {- reason,- error: err instanceof Error ? err.message : String(err),- });+ if (dataOwnerId !== null) {+ // 存量插件迁移必须先于播种与授权消费:#1080 之前装的插件没有 receipt,这里从旧安装+ // 布局 backfill 出等价批准,让它们升级后无感可用(docs §5 红线)。signed-out 的+ // no-session 根只承载本进程的 account-free bundled 投影,绝不扫描或确认 legacy+ // 安装事实。迁移自己取事务锁,因此必须在下面 runExclusiveMutation **之外**调用。+ try {+ 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', {+ reason,+ error: err instanceof Error ? err.message : String(err),+ });+ }}const approvalNeedsRetry = await manager.runExclusiveMutation((mutation) =>- reconcileBuiltinGhostsLocked(reason, manager, mutation),+ reconcileBuiltinGhostsLocked(reason, dataOwnerId, manager, mutation),);migrationNeedsRetry ||= approvalNeedsRetry;} finally {@@ -1192,6 +1221,7 @@ async function reconcileBuiltinGhosts(reason: string): Promise<BuiltinReconcileOasync function reconcileBuiltinGhostsLocked(reason: string,+ dataOwnerId: string | null,manager: GhostManager,mutation: GhostExclusiveMutation,): Promise<boolean> {@@ -1201,14 +1231,16 @@ async function reconcileBuiltinGhostsLocked(// (旧种子已不随包,旧墓碑是死数据;清掉也避免用户日后手动恢复新 id 时被// 本处反复重新盖墓)。停用态:抓在播种前(孤儿回收会删旧目录),装上后补。const renameDisabledCarry = new Map<string, boolean>();- for (const [fromId, toId] of RENAMED_BUILTIN_GHOSTS) {- if (renameBuiltinTombstone(brainRootDir(), fromId, toId, log)) {- log.info('builtin ghost tombstone carried over rename', { fromId, toId });+ if (dataOwnerId !== null) {+ for (const [fromId, toId] of RENAMED_BUILTIN_GHOSTS) {+ if (renameBuiltinTombstone(brainRootDir(), fromId, toId, log)) {+ log.info('builtin ghost tombstone carried over rename', { fromId, toId });+ }+ renameDisabledCarry.set(+ toId,+ hasDisabledMarker(path.join(brainRootDir(), fromId)),+ );}- renameDisabledCarry.set(- toId,- hasDisabledMarker(path.join(brainRootDir(), fromId)),- );}// "播种进行中"胶囊提示:只在真的动手(装/覆盖/回收)时亮起,no-op 对账// 不闪(onApplyStart 整轮至多一次);结束广播放 finally,异常也不留悬挂提示。@@ -1263,36 +1295,39 @@ async function reconcileBuiltinGhostsLocked(// 交互按钮按 ghostId 找主,不迁全废)+ KV 偏好搬家。密钥零迁移(官方别名// 映射到底层同一存储键);媒体账本旧引用保留(历史聊天图继续可读,新任务// 在新 id 名下重新记账)。- for (const [fromId, toId] of RENAMED_BUILTIN_GHOSTS) {- void reassignGhostCards(fromId, toId).catch((err) =>- log.warn('ghost card reassign failed', {- fromId,- toId,- error: err instanceof Error ? err.message : String(err),- }),- );- migrateGhostKvOnRename(fromId, toId);- }- // 退役意识的存量数据清理(孤儿回收只删包不删数据;每轮幂等,见台账注释)- for (const retiredId of RETIRED_BUILTIN_GHOSTS) {- cleanupRetiredGhostData(retiredId);- }- // 改名停用态补挂:新 id 本轮首装且旧 id 此前处于停用 → 新目录补 .disabled- // (播种首装默认启用,这里还原用户选择;放在广播/停靠之前,清单首帧即正确)。- for (const manifest of outcome.installed) {- if (!renameDisabledCarry.get(manifest.id)) continue;- try {- mutation.writeDisabledMarker(manifest.id);- log.info('builtin ghost disabled state carried over rename', { id: manifest.id });- } catch (err) {- log.warn('builtin ghost disabled carry failed', {- id: manifest.id,- error: err instanceof Error ? err.message : String(err),- });+ if (dataOwnerId !== null) {+ for (const [fromId, toId] of RENAMED_BUILTIN_GHOSTS) {+ void reassignGhostCards(fromId, toId).catch((err) =>+ log.warn('ghost card reassign failed', {+ fromId,+ toId,+ error: err instanceof Error ? err.message : String(err),+ }),+ );+ migrateGhostKvOnRename(fromId, toId);+ }+ // 退役插件的凭证、KV 与 fs 槽都是 owner 私有数据;signed-out 不得借+ // no-session 临时命名空间替任何真实 owner 做清理。+ for (const retiredId of RETIRED_BUILTIN_GHOSTS) {+ cleanupRetiredGhostData(retiredId);+ }+ // 改名停用态补挂:新 id 本轮首装且旧 id 此前处于停用 → 新目录补 .disabled+ // (播种首装默认启用,这里还原用户选择;放在广播/停靠之前,清单首帧即正确)。+ for (const manifest of outcome.installed) {+ if (!renameDisabledCarry.get(manifest.id)) continue;+ try {+ mutation.writeDisabledMarker(manifest.id);+ log.info('builtin ghost disabled state carried over rename', { id: manifest.id });+ } catch (err) {+ log.warn('builtin ghost disabled carry failed', {+ id: manifest.id,+ error: err instanceof Error ? err.message : String(err),+ });+ }}}let approvalChanged = false;- let approvalNeedsRetry = false;+ let approvalNeedsRetry = outcome.retryPending === true;const healedResidentIds: string[] = [];for (const manifest of outcome.approved) {try {@@ -5159,9 +5194,18 @@ export function registerGhostIpc(): void {});});- stableOwnerPostCommitTask = async (reason) => {- const outcome = await scheduleBuiltinReconcile(reason);+ stableOwnerPostCommitTask = async (reason, scope) => {+ const outcome = await scheduleBuiltinReconcile(reason, scope);if (outcome === 'deferred') return outcome;+ if (+ activeOwnerScopeKey() !== scope.scopeKey+ || getActiveAppSession().dataOwnerId !== scope.dataOwnerId+ ) {+ return 'deferred';+ }+ // Resident activation is account-free for audience:"all" bundled plugins.+ // The migration body has its own committed-owner gate, so signed-out runs+ // the common activation phase without touching legacy account data.const activationOutcome = activateGhostsAndMigrateLegacyAccounts();return outcome === 'failed'? 'failed'@@ -5645,39 +5689,39 @@ export function registerGhostIpc(): void {);ipcMain.handle('ghosts:cindy-prefs:set', (_event, ghostId: unknown, capability: unknown, model: unknown) => {- if (typeof ghostId !== 'string' || ghostId.trim().length === 0) {- throwIpcError('INVALID_PARAMS', 'ghostId must be a non-empty string');- }- if (!(CINDY_CAPABILITY_KEYS as readonly string[]).includes(capability as string)) {- throwIpcError('INVALID_PARAMS', `unknown capability: ${String(capability)}`);- }- // 白名单按能力键类目分流:image.*/video.*/embed.* 钉各媒体目录模型 id;- // text.*(快问快答)钉轻量档位键或目录钉(cat: 编码)——与消费方(cindySlot- // route)同一判据,否则存进去的值链路不认。刻意不查凭证态(与清单的凭证- // 过滤不同):凭证是瞬态(可以后补/会过期),钉档是持久意图;执行侧- // fail-closed 兜底,不在这层把「暂时没配 key」当成非法值。- if (- !isCindyOverrideModelAllowed(capability as string, model, {- image: getCatalogImageConfig().models,- video: getCatalogVideoConfig().models,- embed: getCatalogEmbedConfig().models,+ if (typeof ghostId !== 'string' || ghostId.trim().length === 0) {+ throwIpcError('INVALID_PARAMS', 'ghostId must be a non-empty string');+ }+ if (!(CINDY_CAPABILITY_KEYS as readonly string[]).includes(capability as string)) {+ throwIpcError('INVALID_PARAMS', `unknown capability: ${String(capability)}`);+ }+ // 白名单按能力键类目分流:image.*/video.*/embed.* 钉各媒体目录模型 id;+ // text.*(快问快答)钉轻量档位键或目录钉(cat: 编码)——与消费方(cindySlot+ // route)同一判据,否则存进去的值链路不认。刻意不查凭证态(与清单的凭证+ // 过滤不同):凭证是瞬态(可以后补/会过期),钉档是持久意图;执行侧+ // fail-closed 兜底,不在这层把「暂时没配 key」当成非法值。+ if (+ !isCindyOverrideModelAllowed(capability as string, model, {+ image: getCatalogImageConfig().models,+ video: getCatalogVideoConfig().models,+ embed: getCatalogEmbedConfig().models,textPinIds: buildTextOneshotPinOptions(getActiveCatalog(), readModelDisableOverrides()).map((o) => o.id,),- })- ) {+ })+ ) {throwIpcError('INVALID_PARAMS', 'model must be null or an allowed model of the capability category');- }- const overrides = writeGhostCindyOverride(- ghostId,- capability as CindyCapabilityKey,- model as string | null,- );- getGhostSetupChangeBus().emit(ghostId, {- source: 'host_config',- ref: `cindy-pref:${String(capability)}`,- });- return { overrides };+ }+ const overrides = writeGhostCindyOverride(+ ghostId,+ capability as CindyCapabilityKey,+ model as string | null,+ );+ getGhostSetupChangeBus().emit(ghostId, {+ source: 'host_config',+ ref: `cindy-pref:${String(capability)}`,+ });+ return { overrides };});// ── agent 槽派活(errand)每插件配置(插件详情页「AI 代办」卡)──diff --git a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.tsindex 803d282340..db8d64a347 100644--- a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts@@ -136,13 +136,21 @@ describe('Plugin Market IPC error boundary', () => {expect(ghostPluginPageSource).toContain('void refreshMarket(true).catch(() => undefined);');const ownerTaskStart = bootstrapSource.indexOf(- 'authManager.setStableOwnerPostCommitTask(async ({ reason }) => {',+ 'authManager.setStableOwnerPostCommitTask(async ({ reason, scopeKey, dataOwnerId }) => {',);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(+ 'await runStableOwnerPostCommitTask(reason, { scopeKey, dataOwnerId })',+ );expect(ownerTaskBody).toContain("if (builtinOutcome === 'deferred') return builtinOutcome;");+ expect(ownerTaskBody).toContain(+ "if (dataOwnerId === null) return needsRetry ? 'failed' : 'completed';",+ );+ expect(ownerTaskBody.indexOf('dataOwnerId === null')).toBeLessThan(+ ownerTaskBody.indexOf('syncDefaultMarketPlugins()'),+ );expect(ownerTaskBody).not.toContain("builtinOutcome === 'failed') return builtinOutcome");expect(ownerTaskBody).toContain("builtinOutcome === 'retry-pending'");expect(ownerTaskBody).toContain("builtinOutcome === 'failed'");diff --git a/apps/desktop/src/main/stableOwnerPostCommit.ts b/apps/desktop/src/main/stableOwnerPostCommit.tsindex 5841cb4cb3..dc5f29f1f7 100644--- a/apps/desktop/src/main/stableOwnerPostCommit.ts+++ b/apps/desktop/src/main/stableOwnerPostCommit.ts@@ -7,7 +7,8 @@ export type StableOwnerPostCommitOutcome =export interface StableOwnerPostCommitContext {reason: string;scopeKey: string;- dataOwnerId: string;+ /** Null identifies the stable signed-out scope, not an unstable boundary. */+ dataOwnerId: string | null;}export type StableOwnerPostCommitTask = (@@ -31,9 +32,11 @@ interface StableOwnerPostCommitCoordinatorOptions {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.+ * Serializes the work that must run after the durable Ghost projection+ * boundary is stable. This includes the signed-out scope: account-free+ * bundled reconciliation still runs there, while the task itself gates work+ * that requires a data owner. 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;@@ -62,7 +65,6 @@ export class StableOwnerPostCommitCoordinator {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');@@ -142,10 +144,10 @@ export class StableOwnerPostCommitCoordinator {const generation = this.taskGeneration;this.retryScopeKey = requested.scopeKey;const schedule = this.options.scheduleRetry ?? ((callback, delay) => {- const handle = setTimeout(callback, delay);- handle.unref?.();- return handle;- });+ const handle = setTimeout(callback, delay);+ handle.unref?.();+ return handle;+ });this.retryHandle = schedule(() => {this.retryHandle = null;if (generation !== this.taskGeneration) return;