Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugin): 固定分享确认与资源绑定并恢复拒绝后的操作
liugaoweic576f8796c44
diff --git a/apps/desktop/src/main/plugin-market/__tests__/localSharing.test.ts b/apps/desktop/src/main/plugin-market/__tests__/localSharing.test.tsindex 9842ebb021..d32562eef6 100644--- a/apps/desktop/src/main/plugin-market/__tests__/localSharing.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/localSharing.test.ts@@ -39,6 +39,10 @@ const manifest = { schemaVersion: 3, id: 'local-example', name: 'Local Example',const ghost = { manifest, dir: path.join(os.tmpdir(), 'virtual-local-plugin'), namespace: null, namespaceState: 'confirmed', approval: { state: 'approved' as const, revision: '00000000-0000-4000-8000-000000000001' }, builtin: false, publishingSource: { kind: 'local' } };const binding = { version: manifest.version, approvalToken: ghostInstallApprovalToken(ghost.approval) };const prepareLocalPluginShare = async (caller: number, instanceId: string, id: string, options: ShareOptions): Promise<ShareContent> => {+ // Follow the real dialog's check-before-confirm flow. Confirmation must not+ // create a missing operation or choose a new content hash.+ const checked = await prepareShare(caller, instanceId, id, options, binding, false);+ if (!('confirmationRequired' in checked)) return checked;const result = await prepareShare(caller, instanceId, id, options, binding, true);if ('confirmationRequired' in result) throw new Error('Unexpected upload confirmation');return result;@@ -223,10 +227,10 @@ describe('local plugin sharing coordinator', () => {expect(io.api.mock.calls.filter(([url]) => url === '/api/shares')).toHaveLength(2);});- it('rejects a reused snapshot for bytes other than the frozen local package', async () => {+ it('rejects a reused snapshot for content other than the checked local package', async () => {const snapshotId = 'b'.repeat(32);io.api.mockResolvedValueOnce({ status: 'upload_required', contentSha256: digest })- .mockResolvedValueOnce({ snapshotId, status: 'ready', snapshot: { ...details(snapshotId), sha256: '0'.repeat(64) }, expiresAt: new Date(Date.now() + 3600000).toISOString() });+ .mockResolvedValueOnce({ snapshotId, status: 'ready', snapshot: { ...details(snapshotId), contentSha256: '0'.repeat(64) }, expiresAt: new Date(Date.now() + 3600000).toISOString() });// The public coordinator sanitizes upload/binding failures as SHARE_READ_FAILED.await expect(prepareLocalPluginShare(1, 'local-example', operation, { includeAttribution: false })).rejects.toMatchObject({ code: 'SHARE_READ_FAILED' });@@ -234,6 +238,25 @@ describe('local plugin sharing coordinator', () => {expect(io.api.mock.calls.filter(([url]) => url === '/api/shares')).toHaveLength(0);});+ // The server can retain a different ZIP encoding of identical verified content.+ // Its selected ZIP must then stay fixed across material and attribution retries.+ it('accepts the retained ZIP for checked content and rejects later ZIP drift', async () => {+ const respond = io.api.getMockImplementation()!;+ let retainedSha = '1'.repeat(64);+ io.api.mockImplementation(async (url: string, options: { body: Record<string, unknown> }) => {+ const result = await respond(url, options);+ return result.snapshot ? { ...result, snapshot: { ...result.snapshot, sha256: retainedSha, sizeBytes: bytes.length + 3 } } : result;+ });+ await expect(prepareLocalPluginShare(1, 'local-example', operation, { includeAttribution: false }))+ .resolves.toHaveProperty('title', manifest.name);+ expect(io.put).toHaveBeenCalledOnce();+ retainedSha = '2'.repeat(64);+ await expect(prepareLocalPluginShare(1, 'local-example', operation, { includeAttribution: true }))+ .rejects.toMatchObject({ code: 'SHARE_READ_FAILED' });+ expect(io.put).toHaveBeenCalledOnce();+ expect(io.snapshot).toHaveBeenCalledOnce();+ });+it('reuses the exact uploaded snapshot when sharing material fails or attribution changes', async () => {failMaterial = true;await expect(prepareLocalPluginShare(1, 'local-example', operation, { includeAttribution: false })).rejects.toThrow();@@ -268,8 +291,10 @@ describe('local plugin sharing coordinator', () => {// during consent, lookup failure and owner change while reading the content.it('uses a verified content hit without compressing, inspecting or writing an archive', async () => {const snapshotId = 'c'.repeat(32);+ const snapshot = { ...details(snapshotId), sha256: '1'.repeat(64) };io.api.mockResolvedValueOnce({ status: 'ready', contentSha256: digest,- snapshot: { ...details(snapshotId), sha256: '1'.repeat(64) } });+ snapshot }).mockResolvedValueOnce({ schemaVersion: 1, kind: 'local-plugin', snapshot, includeAttribution: false,+ shareId: snapshotId, url: `https://share.example.test/s/${snapshotId}`, imageSvg: '<svg xmlns="http://www.w3.org/2000/svg"></svg>' });const result = await prepareShare(1, 'local-example', operation, { includeAttribution: false }, binding, false);expect(result).toHaveProperty('url', `https://share.example.test/s/${snapshotId}`);expect(io.snapshot).not.toHaveBeenCalled();@@ -347,6 +372,32 @@ describe('local plugin sharing coordinator', () => {.resolves.toEqual({ confirmationRequired: true });});+ // The real coordinator must reject stale consent before any new content read+ // or upload. Existing changed-content tests retained the operation in memory;+ // a missing record or the production 30-minute expiry loses that binding.+ it.each(['missing', 'expired'])('requires reopening after a %s confirmation record', async state => {+ vi.useFakeTimers();+ try {+ if (state === 'expired') {+ await prepareShare(1, 'local-example', operation, { includeAttribution: false }, binding, false);+ await vi.advanceTimersByTimeAsync(30 * 60_000);+ }+ const reads = io.content.mock.calls.length;+ const requests = io.api.mock.calls.length;+ const changed = Buffer.from('later local content');+ io.content.mockResolvedValue({ status: 'prepared', ghost, contentSha256: '0'.repeat(64) });+ io.snapshot.mockResolvedValue({ status: 'prepared', bytes: changed, ghost, shareContentSha256: '0'.repeat(64) });+ io.inspect.mockResolvedValue({ packageSha256: createHash('sha256').update(changed).digest('hex'), canonicalManifest: manifest });+ await expect(prepareShare(1, 'local-example', operation, { includeAttribution: false }, binding, true))+ .rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ expect(io.content).toHaveBeenCalledTimes(reads);+ expect(io.api).toHaveBeenCalledTimes(requests);+ expect(io.put).not.toHaveBeenCalled();+ await expect(prepareShare(1, 'local-example', 'operation_00000002', { includeAttribution: false }, binding, false))+ .resolves.toEqual({ confirmationRequired: true });+ } finally { vi.useRealTimers(); }+ });+it('stops before lookup when the owner changes during content reading', async () => {io.content.mockImplementation(async () => { currentOwner++; return { status: 'prepared', ghost, contentSha256: digest }; });await expect(prepareShare(1, 'local-example', operation, { includeAttribution: false }, binding, false)).rejects.toThrow();diff --git a/apps/desktop/src/main/plugin-market/localSharing.ts b/apps/desktop/src/main/plugin-market/localSharing.tsindex f6818a9866..fa9894755d 100644--- a/apps/desktop/src/main/plugin-market/localSharing.ts+++ b/apps/desktop/src/main/plugin-market/localSharing.ts@@ -144,18 +144,15 @@ export async function releaseLocalPluginSharesForCaller(caller: number): Promiseawait Promise.all([...operations.values()].filter(value => value.caller === caller).map(value => releaseLocalPluginShare(caller, value.id)));}-function bindSnapshot(snapshot: LocalPluginShareSnapshot, bundle: Bundle, id?: string) {- if ((id && snapshot.snapshotId !== id) || snapshot.sha256 !== bundle.sha256 || snapshot.sizeBytes !== bundle.sizeBytes ||- snapshot.ghostId !== bundle.ghostId || snapshot.version !== bundle.version)- throwIpcError('PRECONDITION_FAILED', 'Local share does not match the prepared package');- return snapshot;-}-function bindOperationSnapshot(snapshot: LocalPluginShareSnapshot, operation: Operation, id?: string) {if (snapshot.contentSha256 !== operation.content?.sha256 || snapshot.ghostId !== operation.content?.ghostId ||snapshot.version !== operation.expected.version || (id && snapshot.snapshotId !== id))throwIpcError('PRECONDITION_FAILED', 'Local share does not match the checked content');- return operation.bundle ? bindSnapshot(snapshot, operation.bundle, id) : snapshot;+ // The server may retain another ZIP encoding of the same verified content.+ // Once selected, that exact ZIP remains fixed for this operation's material.+ if (operation.snapshot && (snapshot.sha256 !== operation.snapshot.sha256 || snapshot.sizeBytes !== operation.snapshot.sizeBytes))+ throwIpcError('PRECONDITION_FAILED', 'Local share does not match the selected package');+ return snapshot;}async function checkContent(operation: Operation): Promise<LocalPluginShareSnapshot | undefined> {@@ -224,6 +221,8 @@ export async function prepareLocalPluginShare(caller: number, instanceId: stringif (operation && (operation.access.owner !== access.owner || operation.instanceId !== instanceId))throwIpcError('OWNER_CHANGED', 'Local share belongs to another owner or instance');if (!operation) {+ if (uploadConfirmed)+ throwIpcError('PRECONDITION_FAILED', 'Local share confirmation expired; reopen sharing to check it again');if ([...operations.values()].filter(value => value.caller === caller).length >= 8)throwIpcError('PRECONDITION_FAILED', 'Too many local share operations');const timer = setTimeout(() => { void releaseLocalPluginShare(caller, id); }, TTL_MS);diff --git a/apps/desktop/src/renderer/features/plugin/LocalPluginShareView.tsx b/apps/desktop/src/renderer/features/plugin/LocalPluginShareView.tsxindex e5372940b3..31df5f0261 100644--- a/apps/desktop/src/renderer/features/plugin/LocalPluginShareView.tsx+++ b/apps/desktop/src/renderer/features/plugin/LocalPluginShareView.tsx@@ -190,7 +190,14 @@ function RemoteShareInstall({ snapshot, device, online, onBusy, onError, onInstaawait acceptReceipt(parsePluginManagementReceipt(await invoke('begin', {operationId: id, kind: 'install-share', expectedSnapshot: snapshot,}), id));- } catch { if (writable()) setStatus('unknown'); }+ } catch (cause) {+ if (!current() || id !== operation.current) return;+ const code = extractIpcError(cause)?.code;+ if (['INVALID_PARAMS', 'NOT_FOUND', 'PRECONDITION_FAILED', 'UNSUPPORTED_CAPABILITY', 'PERMISSION_DENIED'].includes(code ?? '')) {+ operation.current = null; setBusy(false); onBusy(false); setStatus(null);+ onError('settings.ghosts.remote.actionFailed');+ } else setStatus('unknown');+ }};return <div className="space-y-3"><Button variant="cta" loading={busy} disabled={busy || !online || supported !== true} onClick={() => void install()}>diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/LocalPluginShareView.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/LocalPluginShareView.test.tsxindex 28b00d64e8..faf9c2b155 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/LocalPluginShareView.test.tsx+++ b/apps/desktop/src/renderer/features/plugin/__tests__/LocalPluginShareView.test.tsx@@ -105,6 +105,43 @@ it.each([false, true])('keeps an offline or unsupported device selected withoutexpect(io.install).not.toHaveBeenCalled();});+// A known rejection happens before the target stores a receipt. The old test+// only covered a lost response after send; querying that nonexistent operation+// must not leave installation and device selection permanently busy (unit).+it.each(['INVALID_PARAMS', 'NOT_FOUND', 'PRECONDITION_FAILED', 'UNSUPPORTED_CAPABILITY', 'PERMISSION_DENIED'] as const)(+ 'allows a new explicit install after the target rejects begin with %s', async code => {+ remoteHost();+ const host = io.invoke.getMockImplementation()!;+ let refused = false;+ io.invoke.mockImplementation(async (...args) => {+ if (args[2][0].actionId === 'management:begin' && !refused) {+ refused = true;+ throw createIpcError(code, 'Request rejected before creating an operation');+ }+ return host(...args);+ });+ const installed = vi.fn(); render(view(installed, control()));+ const button = await screen.findByRole<HTMLButtonElement>('button', { name: 'sharing.localInstallButton' });+ await waitFor(() => expect(button.disabled).toBe(false));+ vi.useFakeTimers();+ try {+ await act(async () => { fireEvent.click(button); });+ expect(button.disabled).toBe(false);+ expect(screen.getByRole<HTMLButtonElement>('button', { name: 'settings.ghosts.remote.device' }).disabled).toBe(false);+ expect(screen.getByText('settings.ghosts.remote.actionFailed')).toBeTruthy();+ await act(async () => { await vi.advanceTimersByTimeAsync(650); });+ expect(io.invoke.mock.calls.some(([, , [request]]) => request.actionId === 'management:operation')).toBe(false);+ await act(async () => { fireEvent.click(button); });+ await act(async () => { await vi.advanceTimersByTimeAsync(650); });+ expect(installed).toHaveBeenCalledOnce();+ const begins = io.invoke.mock.calls.filter(([, , [request]]) => request.actionId === 'management:begin');+ expect(begins).toHaveLength(2);+ expect(begins[1][2][0].input.operationId).not.toBe(begins[0][2][0].input.operationId);+ expect(io.install).not.toHaveBeenCalled();+ } finally { vi.useRealTimers(); }+ },+);+it('reads the original receipt after an ambiguous begin without sending another install', async () => {remoteHost();const host = io.invoke.getMockImplementation()!;diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex b4baea9c80..f86c461d5c 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -3646,6 +3646,8 @@ Main 先用原一致性读取入口核对已批准的本地实例,绑定版本不压缩 ZIP、不写上传包。命中本人已验证内容时直接返回本次新快照,免确认和上传;未命中才确认后打包,打包内容必须仍与确认前摘要一致。服务端从实际归档重新计算`contentSha256`,精确 ZIP `sha256` 继续负责传输和安装校验,版本号不能替代内容判据。+并发上传的相同内容也可复用不同编码的 ZIP;客户端先绑定服务端已验证的内容,再固定所选+快照的实际 ZIP SHA 和大小,后续分享素材或署名重试不得换包。原投稿恢复保存的 `contentSha256` 编码不变,分享使用独立版本化摘要,不改其持久状态。两仓增量协议同步,旧 ZIP 上传请求可省略新增摘要字段;服务端先部署检查能力,新客户端访问不支持检查的服务端时报告失败,不自动上传或回退成先压缩的检查。