Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugin): preserve retry and ledger authorization
liugaowei9ad782154ecb
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.tsindex 6e07088a91..40df8838f8 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts@@ -43,9 +43,13 @@ describe('market Ghost session boundary', () => {expect(installBody).toContain('afterCommit: async (_installed, packagedManifest) => {',);- expect(installBody).toContain(- 'requireSameMarketOwner(owner, { allowPendingBoundary: true });',+ const afterCommitStart = installBody.indexOf(+ 'afterCommit: async (_installed, packagedManifest) => {',);+ const afterCommitEnd = installBody.indexOf('\n },\n }).catch', afterCommitStart);+ const afterCommitBody = installBody.slice(afterCommitStart, afterCommitEnd);+ expect(afterCommitBody).toContain('this.withCapturedLedgerMutation(ledger, () => {');+ expect(afterCommitBody).not.toContain('requireSameMarketOwner(');expect(automaticBody).toContain(' true,\n owner,\n );');});@@ -66,9 +70,13 @@ describe('market Ghost session boundary', () => {expect(firstAfterCommit).toBeGreaterThan(-1);expect(updateAfterCommit).toBeGreaterThan(firstAfterCommit);expect(release).toBeGreaterThan(updateAfterCommit);- expect(marketServiceSource).toContain(- 'afterCommitInLock: async (committed) => {\n requireSameMarketOwner(owner, { allowPendingBoundary: true });',+ const serverCommitStart = marketServiceSource.indexOf(+ 'afterCommitInLock: async (committed) => {',);+ const serverCommitEnd = marketServiceSource.indexOf('\n },\n }).catch', serverCommitStart);+ const serverCommitBody = marketServiceSource.slice(serverCommitStart, serverCommitEnd);+ expect(serverCommitBody).toContain('this.withCapturedLedgerMutation(ledger, () => {');+ expect(serverCommitBody).not.toContain('requireSameMarketOwner(');});it('requires the pre-approval session generation when acquiring the mutation lease', () => {diff --git a/apps/desktop/src/main/maker-host/__tests__/outboundFetch.test.ts b/apps/desktop/src/main/maker-host/__tests__/outboundFetch.test.tsindex be82567c3e..305b9cb9ff 100644--- a/apps/desktop/src/main/maker-host/__tests__/outboundFetch.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/outboundFetch.test.ts@@ -319,6 +319,11 @@ describe('outboundFetch', () => {const dispatchSpy = vi.spyOn(ProxyAgent.prototype, 'dispatch');const controller = {} as Dispatcher.DispatchController;const responseError = vi.fn();+ let authorizeRetry!: () => void;+ const retryAuthorization = new Promise<void>((resolve) => {+ authorizeRetry = resolve;+ });+ const beforeRetry = vi.fn(() => retryAuthorization);try {dispatchSpy.mockImplementationOnce((_options, handler) => {@@ -339,6 +344,7 @@ describe('outboundFetch', () => {},new URL('https://api.example.com/data'),['203.0.113.10', '203.0.113.11'],+ beforeRetry,);dispatcher.dispatch(@@ -346,7 +352,10 @@ describe('outboundFetch', () => {{ onRequestStart: vi.fn(), onResponseError: responseError },);- expect(dispatchSpy).toHaveBeenCalledTimes(2);+ expect(dispatchSpy).toHaveBeenCalledTimes(1);+ await vi.waitFor(() => expect(beforeRetry).toHaveBeenCalledTimes(1));+ authorizeRetry();+ await vi.waitFor(() => expect(dispatchSpy).toHaveBeenCalledTimes(2));expect(dispatchSpy.mock.calls.map(([options]) => options.origin)).toEqual(['https://203.0.113.10','https://203.0.113.11',@@ -362,6 +371,43 @@ describe('outboundFetch', () => {}});+ it('does not try another proxy target when retry authorization has expired', async () => {+ const dispatchSpy = vi.spyOn(ProxyAgent.prototype, 'dispatch');+ const controller = {} as Dispatcher.DispatchController;+ const responseError = vi.fn();+ const authorizationError = new Error('authorization expired');+ try {+ dispatchSpy.mockImplementationOnce((_options, handler) => {+ handler.onResponseError?.(controller, new Error('first address unreachable'));+ return true;+ });+ const dispatcher = createPinnedProxyDispatcher(+ {+ kind: 'http',+ url: 'http://127.0.0.1:7890',+ hostname: '127.0.0.1',+ port: 7890,+ },+ new URL('https://api.example.com/data'),+ ['203.0.113.10', '203.0.113.11'],+ () => Promise.reject(authorizationError),+ );++ dispatcher.dispatch(+ { origin: 'https://api.example.com', path: '/data', method: 'POST', body: 'payload' },+ { onResponseError: responseError },+ );++ await vi.waitFor(() =>+ expect(responseError).toHaveBeenCalledWith(controller, authorizationError),+ );+ expect(dispatchSpy).toHaveBeenCalledTimes(1);+ await dispatcher.close();+ } finally {+ dispatchSpy.mockRestore();+ }+ });+it.each(['http://127.0.0.1:7890','socks5://127.0.0.1:7891',diff --git a/apps/desktop/src/main/maker-host/outbound-fetch.ts b/apps/desktop/src/main/maker-host/outbound-fetch.tsindex aed0ea88db..ee0503d081 100644--- a/apps/desktop/src/main/maker-host/outbound-fetch.ts+++ b/apps/desktop/src/main/maker-host/outbound-fetch.ts@@ -495,6 +495,7 @@ export function createPinnedProxyDispatcher(proxy: OutboundProxyTarget,upstream: URL,addresses: readonly string[],+ beforeRetry: () => void | Promise<void>,): Dispatcher {if (addresses.length === 0) throw new Error(`Unable to resolve hostname: ${upstream.hostname}`);const base = createProxyDispatcher(@@ -508,67 +509,78 @@ export function createPinnedProxyDispatcher(options: Dispatcher.DispatchOptions,handler: Dispatcher.DispatchHandler,): boolean {- const dispatchFrom = (startIndex: number): boolean => {- let lastError: unknown;- for (let index = startIndex; index < addresses.length; index += 1) {- const address = addresses[index]!;- let requestStarted = false;- const attemptHandler: Dispatcher.DispatchHandler = {- onRequestStart(controller, context) {- requestStarted = true;- handler.onRequestStart?.(controller, context);- },- onRequestUpgrade(controller, statusCode, headers, socket) {- handler.onRequestUpgrade?.(controller, statusCode, headers, socket);- },- onResponseStart(controller, statusCode, headers, statusMessage) {- handler.onResponseStart?.(controller, statusCode, headers, statusMessage);- },- onResponseData(controller, chunk) {- handler.onResponseData?.(controller, chunk);- },- onResponseEnd(controller, trailers) {- handler.onResponseEnd?.(controller, trailers);- },- onResponseError(controller, error) {- // HTTPS CONNECT / SOCKS5 握手失败发生在 onRequestStart 之前;一旦请求开始,- // 就不能为了换 IP 而重放可能产生副作用的 POST。- if (!requestStarted && !controller.aborted && index + 1 < addresses.length) {- try {- dispatchFrom(index + 1);- } catch (nextError) {- handler.onResponseError?.(- controller,- nextError instanceof Error ? nextError : new Error(String(nextError)),- );- }- return;- }- handler.onResponseError?.(controller, error);- },- onResponseStarted() {- handler.onResponseStarted?.();- },- onBodySent(chunk) {- handler.onBodySent?.(chunk);- },- onRequestSent() {- handler.onRequestSent?.();- },- };- try {- return base.dispatch(- rewritePinnedProxyDispatchOptions(options, upstream, address),- attemptHandler,- );- } catch (error) {- lastError = error;- }- }- throw lastError instanceof Error ? lastError : new Error(String(lastError));+ const dispatchAt = (index: number): boolean => {+ const address = addresses[index]!;+ let requestStarted = false;+ const attemptHandler: Dispatcher.DispatchHandler = {+ onRequestStart(controller, context) {+ requestStarted = true;+ handler.onRequestStart?.(controller, context);+ },+ onRequestUpgrade(controller, statusCode, headers, socket) {+ handler.onRequestUpgrade?.(controller, statusCode, headers, socket);+ },+ onResponseStart(controller, statusCode, headers, statusMessage) {+ handler.onResponseStart?.(controller, statusCode, headers, statusMessage);+ },+ onResponseData(controller, chunk) {+ handler.onResponseData?.(controller, chunk);+ },+ onResponseEnd(controller, trailers) {+ handler.onResponseEnd?.(controller, trailers);+ },+ onResponseError(controller, error) {+ // HTTPS CONNECT / SOCKS5 握手失败发生在 onRequestStart 之前;一旦请求开始,+ // 就不能为了换 IP 而重放可能产生副作用的 POST。切换到下一个已审核 IP+ // 也是一次新的真实派发,必须重新确认 callId 仍处于授权窗口。+ if (!requestStarted && !controller.aborted && index + 1 < addresses.length) {+ void Promise.resolve()+ .then(beforeRetry)+ .then(+ () => {+ if (controller.aborted) {+ handler.onResponseError?.(controller, error);+ return;+ }+ try {+ dispatchAt(index + 1);+ } catch (nextError) {+ handler.onResponseError?.(+ controller,+ nextError instanceof Error ? nextError : new Error(String(nextError)),+ );+ }+ },+ (authorizationError: unknown) => {+ handler.onResponseError?.(+ controller,+ authorizationError instanceof Error+ ? authorizationError+ : new Error(String(authorizationError)),+ );+ },+ );+ return;+ }+ handler.onResponseError?.(controller, error);+ },+ onResponseStarted() {+ handler.onResponseStarted?.();+ },+ onBodySent(chunk) {+ handler.onBodySent?.(chunk);+ },+ onRequestSent() {+ handler.onRequestSent?.();+ },+ };+ return base.dispatch(+ rewritePinnedProxyDispatchOptions(options, upstream, address),+ attemptHandler,+ );};- return dispatchFrom(0);+ return dispatchAt(0);}override async close(): Promise<void> {@@ -602,7 +614,7 @@ export async function guardedOutboundFetch(...(proxy? {dispatcherFactory: ({ url: guardedUrl, pinned }) =>- createPinnedProxyDispatcher(proxy, guardedUrl, pinned.addresses),+ createPinnedProxyDispatcher(proxy, guardedUrl, pinned.addresses, beforeDispatch),}: {}),beforeDispatch,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 edfe458d28..0c19c0b38e 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@@ -1421,6 +1421,35 @@ describe('PluginMarketService 自定义市场 detail/install', () => {runtime.session = { mode: 'cloud', dataOwnerId: 'user-1', generation: 1 };});+ it('commits custom provenance to the captured ledger after a terminal switch timeout', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);+ const pluginId = customMarketPluginId('team-lib', 'alpha');+ const detail = await h.service.detail(pluginId);+ runtime.install.mockImplementationOnce(async () => {+ const installed = installedGhost(root, 'alpha');+ // 真实路径中包已经落位且仍持原 owner lease;这里只模拟切号终止等待超时后+ // volatile session 已推进,但旧 owner 的溯源提交尚未执行。+ runtime.session = { mode: 'cloud', dataOwnerId: 'user-2', generation: 2 };+ return installed;+ });++ await expect(+ h.service.install(pluginId, {+ expectedReleaseId: detail.releaseId,+ expectedManifest: detail.manifest,+ }),+ ).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });+ expect(h.ledger.installationForGhost('alpha')).toMatchObject({+ pluginId,+ releaseId: detail.releaseId,+ source: 'local-market',+ installed: true,+ });+ });+it('rejects install when the plugin is uninstalled during packaging (runtime 复核)', async () => {// F1:审阅时 alpha 已装(existing 存在),打包窗口内本地页把它卸载。// beforeCommit 的 runtime 复核必须发现 existing→缺失并拒,避免"更新"被diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.tsindex 1986d00963..5242c1f90b 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts@@ -3235,7 +3235,7 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();});- it('rejects provenance commit when the owner changes before the final callback', async () => {+ it('commits provenance to the captured ledger after a terminal switch timeout', async () => {const item = summary();const installedGhost = {manifest: manifest(),@@ -3253,10 +3253,14 @@ describe('PluginMarketService migration and defaultInstall', () => {return installedGhost;});- await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow(- '[PRECONDITION_FAILED]',- );- expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();+ await expect(h.service.install(item.id, reviewedInstallOptions(item))).resolves.toMatchObject({+ ghost: { manifest: { id: item.ghostId } },+ });+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({+ pluginId: item.id,+ releaseId: item.currentRelease.id,+ installed: true,+ });});it('reports a successful market uninstall when the owner changes during cleanup', async () => {diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.tsindex fbf0b6510d..8a8c98bd3e 100644--- a/apps/desktop/src/main/plugin-market/service.ts+++ b/apps/desktop/src/main/plugin-market/service.ts@@ -1428,15 +1428,14 @@ 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 });+ // 这里已在 owner mutation lease 与同 id 安装锁内,且 ledger 绑定的是操作+ // 开始时捕获的 owner。切号终止等待超时后当前 generation 可能已经推进,+ // 但包既已落位,就仍须把溯源写回旧 owner;不能再读取当前 session 拒绝。// 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,@@ -1913,9 +1912,9 @@ export class PluginMarketService {}: {}),afterCommitInLock: async (committed) => {- requireSameMarketOwner(owner, { allowPendingBoundary: true });+ // 包已落位且仍持原 owner mutation lease;即使切号终止等待超时推进了+ // 当前 generation,也必须把来源写进操作开始时捕获的旧 owner 账本。await this.withCapturedLedgerMutation(ledger, () => {- requireSameMarketOwner(owner, { allowPendingBoundary: true });ledger.upsertInstallation(recordFrom(plugin, 'market', committed));});},