Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugin): close market owner commit race
liugaoweibca02fb7e248
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.tsindex bb87e94581..6e07088a91 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts@@ -37,9 +37,40 @@ describe('market Ghost session boundary', () => {expect(installBody).toContain('const ledger = this.ledgerForOwner(owner);');expect(installBody).toContain('const manager = this.sourceManagerForOwner(owner);');expect(installBody).toContain('requireSameMarketOwner(owner);');+ expect(installBody).toContain(+ 'beforePackagePlacement: () => {\n requireSameMarketOwner(owner);',+ );+ expect(installBody).toContain(+ 'afterCommit: async (_installed, packagedManifest) => {',+ );+ expect(installBody).toContain(+ 'requireSameMarketOwner(owner, { allowPendingBoundary: true });',+ );expect(automaticBody).toContain(' true,\n owner,\n );');});+ it('keeps package placement and market ledger commit in the same owner lease', () => {+ const installStart = source.indexOf(+ 'async function installOrUpdateMarketGhostPackageLocked(',+ );+ const installEnd = source.indexOf('\n}\n\ntype GhostUninstallLedgerCompletion', installStart);+ const installBody = source.slice(installStart, installEnd);+ const firstAfterCommit = installBody.indexOf(+ 'await expected.afterCommitInLock?.(installedGhost);',+ );+ const updateAfterCommit = installBody.indexOf(+ 'await expected.afterCommitInLock?.(result.ghost);',+ );+ const release = installBody.indexOf('releaseMutation?.();');++ expect(firstAfterCommit).toBeGreaterThan(-1);+ expect(updateAfterCommit).toBeGreaterThan(firstAfterCommit);+ expect(release).toBeGreaterThan(updateAfterCommit);+ expect(marketServiceSource).toContain(+ 'afterCommitInLock: async (committed) => {\n requireSameMarketOwner(owner, { allowPendingBoundary: true });',+ );+ });+it('requires the pre-approval session generation when acquiring the mutation lease', () => {const captureStart = source.indexOf('function captureGhostMutationOwner(): ActiveAppSession {',@@ -177,7 +208,7 @@ describe('market Ghost session boundary', () => {expect(initialBranch.indexOf('expected.beforeCommitInLock?.();')).toBeGreaterThan(-1);expect(initialBranch.indexOf('expected.beforeCommitInLock?.();')).toBeLessThan(- initialBranch.indexOf('return installAndDock('),+ initialBranch.indexOf('await installAndDock('),);expect(body.match(/expected\.beforeCommitInLock\?\.\(\);/g)).toHaveLength(2);diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex e5b10567f8..9c7c850f4b 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -5596,6 +5596,8 @@ export async function installOrUpdateMarketGhostPackage(beforeCommitInLock?: () => void;/** 新包已经原子换位;后续异常不能再按落位失败回滚来源路由。 */onPackagePlacedInLock?: () => void;+ /** 包与 receipt 已提交,仍持 owner mutation lease;用于原子写入来源账本。 */+ afterCommitInLock?: (installed: InstalledGhost) => void | Promise<void>;/** 仅 server-market 主机路径可传;custom/local 不传。 */officialCindyGithub?: boolean;},@@ -5620,6 +5622,8 @@ async function installOrUpdateMarketGhostPackageLocked(beforeCommitInLock?: () => void;/** 新包已经原子换位;后续异常不能再按落位失败回滚来源路由。 */onPackagePlacedInLock?: () => void;+ /** 包与 receipt 已提交,仍持 owner mutation lease;用于原子写入来源账本。 */+ afterCommitInLock?: (installed: InstalledGhost) => void | Promise<void>;officialCindyGithub?: boolean;},): Promise<InstalledGhost> {@@ -5693,12 +5697,14 @@ async function installOrUpdateMarketGhostPackageLocked(// 所有前置校验(保留前缀/能力上限/签名/解压上限)都会作用在旧字节上。// 本地 .cindy 装入通道已强制此对账,市场通道同一口径。expected.beforeCommitInLock?.();- return installAndDock(manager, cindyFilePath, {+ const installedGhost = await installAndDock(manager, cindyFilePath, {ghostId: expected.ghostId,enable: true,expectedPackageSha256: inspected.packageSha256,...(trustOverride ? { trustOverride } : {}),});+ await expected.afterCommitInLock?.(installedGhost);+ return installedGhost;}expected.beforeCommitInLock?.();@@ -5774,6 +5780,7 @@ async function installOrUpdateMarketGhostPackageLocked(}}spawnIfResident(result.ghost);+ await expected.afterCommitInLock?.(result.ghost);return result.ghost;} finally {releaseMutation?.();diff --git a/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts b/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.tsindex 22f4f3cd68..c042bd9865 100644--- a/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts@@ -37,7 +37,16 @@ const brain = vi.hoisted(() => ({}));vi.mock('../../cindy-brain/index.js', () => ({getGhostManager: () => ({ inspect: brain.inspect }),- installOrUpdateMarketGhostPackage: brain.installOrUpdateMarketGhostPackage,+ installOrUpdateMarketGhostPackage: async (+ filePath: string,+ options: {+ afterCommitInLock?: (installed: unknown) => void | Promise<void>;+ },+ ) => {+ const installed = await brain.installOrUpdateMarketGhostPackage(filePath, options);+ await options.afterCommitInLock?.(installed);+ return installed;+ },rejectReservedGhostIdForCustomMarket: brain.rejectReservedGhostIdForCustomMarket,}));vi.mock('../../cindy-brain/forge.js', () => ({diff --git a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.tsindex 1bba03ca53..edfe458d28 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts@@ -84,7 +84,16 @@ vi.mock('../../cindy-brain/index.js', () => ({inspect: runtime.inspect,}),isGhostAvailableForActiveSession: vi.fn(() => runtime.accountGhostAvailable),- installOrUpdateMarketGhostPackage: runtime.install,+ installOrUpdateMarketGhostPackage: async (+ filePath: string,+ options: {+ afterCommitInLock?: (installed: unknown) => void | Promise<void>;+ },+ ) => {+ const installed = await runtime.install(filePath, options);+ await options.afterCommitInLock?.(installed);+ return installed;+ },hasPendingGhostCalls: vi.fn(() => runtime.pendingCalls),hasRunningGhostErrand: vi.fn(() => runtime.runningErrand),hasRunningGhostCindyWork: vi.fn(() => runtime.cindyWork),diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.tsindex 25b37179e3..38098f7b23 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts@@ -77,7 +77,16 @@ vi.mock('../../cindy-brain/index.js', () => ({inspect: runtime.inspect,}),isGhostAvailableForActiveSession: vi.fn(() => runtime.accountGhostAvailable),- installOrUpdateMarketGhostPackage: runtime.install,+ installOrUpdateMarketGhostPackage: async (+ filePath: string,+ options: {+ afterCommitInLock?: (installed: unknown) => void | Promise<void>;+ },+ ) => {+ const installed = await runtime.install(filePath, options);+ await options.afterCommitInLock?.(installed);+ return installed;+ },hasPendingGhostCalls: vi.fn(() => runtime.pendingCalls),hasRunningGhostErrand: vi.fn(() => runtime.runningErrand),hasRunningGhostCindyWork: vi.fn(() => runtime.cindyWork),@@ -1147,6 +1156,7 @@ describe('PluginMarketService migration and defaultInstall', () => {ghostId: 'cindy-test',version: '1.0.0',manifestCap: incompatibleManifest,+ afterCommitInLock: expect.any(Function),});});@@ -1219,6 +1229,7 @@ describe('PluginMarketService migration and defaultInstall', () => {ghostId: 'cindy-test',version: '1.0.0',manifestCap: manifest(),+ afterCommitInLock: expect.any(Function),});// 安装入口用目录 summary 做 detail 身份绑定(防止把 A 的确认导向 B 的内容),// 因此手动安装也会先取一次目录,但不做任何 listAll 之外的多余请求。@@ -1370,6 +1381,7 @@ describe('PluginMarketService migration and defaultInstall', () => {ghostId: 'cindy-test',version: '1.0.0',manifestCap: manifest(),+ afterCommitInLock: expect.any(Function),});});@@ -3188,7 +3200,7 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();});- it('records provenance for the captured owner when the owner changes after install', async () => {+ it('rejects provenance commit when the owner changes before the final callback', async () => {const item = summary();const installedGhost = {manifest: manifest(),@@ -3206,14 +3218,10 @@ describe('PluginMarketService migration and defaultInstall', () => {return installedGhost;});- await expect(h.service.install(item.id, reviewedInstallOptions(item))).resolves.toEqual({- ghost: installedGhost,- });- expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({- pluginId: item.id,- releaseId: item.currentRelease.id,- installed: true,- });+ await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow(+ '[PRECONDITION_FAILED]',+ );+ expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();});it('reports a successful market uninstall when the owner changes during cleanup', async () => {diff --git a/apps/desktop/src/main/plugin-market/install.ts b/apps/desktop/src/main/plugin-market/install.tsindex d67d6f0786..997de32ffa 100644--- a/apps/desktop/src/main/plugin-market/install.ts+++ b/apps/desktop/src/main/plugin-market/install.ts@@ -84,7 +84,7 @@ export async function installCustomMarketPlugin(input: {*/withCommitLock?: <T>(fn: () => Promise<T>) => Promise<T>;/**- * 落位成功后、仍在 `withCommitLock` 内执行的溯源写入钩。+ * 落位成功后、仍在 `withCommitLock` 与 owner mutation lease 内执行的溯源写入钩。** 账本写入必须与落位同锁:放在锁外时,另一条路径(本地 .cindy 装入/更新)可以* 插在"包已落位"与"写下溯源"之间换掉同 id 的包,账本随后认领一个其实已被替换@@ -228,9 +228,13 @@ export async function installCustomMarketPlugin(input: {...(input.onPackagePlaced? { onPackagePlacedInLock: input.onPackagePlaced }: {}),+ ...(input.afterCommit+ ? {+ afterCommitInLock: (committed) =>+ input.afterCommit!(committed, packed.manifest),+ }+ : {}),});- // 溯源写入与落位同锁(见 afterCommit 注释)。- await input.afterCommit?.(installed, packed.manifest);return { ghost: installed };};return input.withCommitLock ? input.withCommitLock(run) : run();diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.tsindex 1b9682f7fc..a3bab2e8ab 100644--- a/apps/desktop/src/main/plugin-market/service.ts+++ b/apps/desktop/src/main/plugin-market/service.ts@@ -135,10 +135,13 @@ function canCaptureMarketOwner(): boolean {);}-function requireSameMarketOwner(expected: ActiveAppSession): void {+function requireSameMarketOwner(+ expected: ActiveAppSession,+ options: { allowPendingBoundary?: boolean } = {},+): void {const current = getActiveAppSession();if (- isAppSessionBoundaryPending() ||+ (!options.allowPendingBoundary && isAppSessionBoundaryPending()) ||current.mode !== expected.mode ||current.dataOwnerId !== expected.dataOwnerId ||current.generation !== expected.generation@@ -1367,6 +1370,7 @@ export class PluginMarketService {},expectedInstalledApproval: options.expectedInstalledApproval,beforePackagePlacement: () => {+ requireSameMarketOwner(owner);if (automatic && isGhostBusy(plugin.ghostId)) {throw new SilentUpgradeBusyError('Plugin is busy');}@@ -1406,11 +1410,15 @@ export class PluginMarketService {// 放到锁外时,本地装入能插在"包已落位"与"写下溯源"之间换掉同 id 的包。// 锁序:pluginId → SOURCE_MUTATION_KEY → ghostId → ledgerMutation。afterCommit: async (_installed, packagedManifest) => {+ // owner mutation lease 已阻止切号提交新 generation;boundary 可能已进入+ // pending 并等待本 lease 收尾,此时仍必须把包与原 owner 账本一起提交。+ requireSameMarketOwner(owner, { allowPendingBoundary: true });// packGhostDirToFile 返回的是写入真实临时包的 canonical manifest;// Main 随后复验并用包 SHA 钉死同一文件,因此无需在包已经落位后// 再读一次目录。后置 I/O 失败不应把成功安装误报成失败或漏写来源。const manifestDigest = ghostManifestDigest(packagedManifest);await this.withCapturedLedgerMutation(ledger, () => {+ requireSameMarketOwner(owner, { allowPendingBoundary: true });ledger.upsertInstallation({pluginId,ghostId: plugin.ghostId,@@ -1843,6 +1851,7 @@ export class PluginMarketService {let replacedRouteWasSuppressed = false;let packageLanded = false;const detachPreviousRoute = (): void => {+ requireSameMarketOwner(owner);options.beforeCommitInLock?.();if (!replacingSource || !currentRecordNow) return;replacedRouteWasSuppressed = this.detachMarketRouteForReplacement(@@ -1881,6 +1890,13 @@ export class PluginMarketService {},}: {}),+ afterCommitInLock: async (committed) => {+ requireSameMarketOwner(owner, { allowPendingBoundary: true });+ await this.withCapturedLedgerMutation(ledger, () => {+ requireSameMarketOwner(owner, { allowPendingBoundary: true });+ ledger.upsertInstallation(recordFrom(plugin, 'market', committed));+ });+ },}).catch((error) => {if (routeDetached && !packageLanded && currentRecordNow) {this.restoreMarketRouteAfterFailedReplacement(@@ -1892,9 +1908,6 @@ export class PluginMarketService {}throw error;});- await this.withCapturedLedgerMutation(ledger, () => {- ledger.upsertInstallation(recordFrom(plugin, 'market', installed));- });return installed;});}