Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(device-link): cancel stale attachment recovery uploads
elfcvcfa6686d01f5
diff --git a/apps/desktop/src/main/__tests__/appSessionBoundary.test.ts b/apps/desktop/src/main/__tests__/appSessionBoundary.test.tsindex 969e616921..862cc85f29 100644--- a/apps/desktop/src/main/__tests__/appSessionBoundary.test.ts+++ b/apps/desktop/src/main/__tests__/appSessionBoundary.test.ts@@ -28,6 +28,7 @@ vi.mock('../authBoundaryQuarantine.js', () => ({import {beginAppSessionBoundary,+ onAppSessionInvalidated,commitActiveAppSession,commitVolatileAppSession,getActiveAppSession,@@ -62,6 +63,20 @@ const createCloudCommit = new Function() => (ownerId: string, authRealmChanged: boolean) => void;describe('application session boundary isolation', () => {+ it('cancels request scopes before boundaries and generation changes, and unsubscribes on completion', () => {+ const observed: number[] = [];+ const unsubscribe = onAppSessionInvalidated(() => observed.push(getActiveAppSession().generation));+ const initial = getActiveAppSession();+ const release = beginAppSessionBoundary();+ release();+ commitActiveAppSession(initial.mode, initial.dataOwnerId, true);+ commitVolatileAppSession(initial.mode, initial.dataOwnerId, true);+ unsubscribe();+ const nextRelease = beginAppSessionBoundary();+ nextRelease();+ expect(observed).toEqual([initial.generation, initial.generation, initial.generation + 1]);+ });+it('does not treat a different durable Ghost projection owner as an App transition', () => {ghostBoundary.stable = false;expect(isAppSessionBoundaryPending()).toBe(false);diff --git a/apps/desktop/src/main/appSessionState.ts b/apps/desktop/src/main/appSessionState.tsindex 6e70c5557b..4b48caafc1 100644--- a/apps/desktop/src/main/appSessionState.ts+++ b/apps/desktop/src/main/appSessionState.ts@@ -81,6 +81,17 @@ const store = createOverrideSettingsFile<PersistedAppSessionSettings>({let active: ActiveAppSession | null = null;let boundaryDepth = 0;let appSessionCommitBoundaryHook: (() => void) | null = null;+const sessionInvalidationListeners = new Set<() => void>();++/** Cancel owner-bound requests before teardown or a new generation becomes visible. */+export function onAppSessionInvalidated(listener: () => void): () => void {+ sessionInvalidationListeners.add(listener);+ return () => { sessionInvalidationListeners.delete(listener); };+}++function invalidateSessionRequests(): void {+ for (const listener of sessionInvalidationListeners) listener();+}/*** Register synchronous owner-scoped runtime invalidation at the exact commit edge.@@ -143,6 +154,7 @@ export function activeOwnerScopeKey(): string {*/export function beginAppSessionBoundary(): () => void {boundaryDepth += 1;+ invalidateSessionRequests();let released = false;return () => {if (released) return;@@ -185,6 +197,7 @@ export function commitActiveAppSession(}store.writePatch({ activeMode: mode });+ invalidateSessionRequests();if (ownerChanged) appSessionCommitBoundaryHook?.();active = {mode,@@ -218,6 +231,7 @@ export function commitVolatileAppSession(if (!ownerChanged && !forceBumpGeneration) {return { ...previous };}+ invalidateSessionRequests();if (ownerChanged) appSessionCommitBoundaryHook?.();active = {mode,diff --git a/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts b/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.tsindex 5e304f6f6c..b1eecb26f1 100644--- a/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts@@ -167,6 +167,19 @@ describe('uploadLocalFile — 小文件整体 PUT', () => {expect(netFetchMock).not.toHaveBeenCalled();});+ it.each(['stat', 'presign', 'read', 'put'])('stops a stale attachment after %s and cleans any staged object', async stage => {+ let current = true;+ const assertCurrent = () => { if (!current) throw new Error('stale attachment'); };+ if (stage === 'stat') statMock.mockImplementationOnce(async () => { current = false; return { isFile: () => true, size: 100 }; });+ if (stage === 'presign') apiFetch.mockImplementationOnce(async () => { current = false; return { putUrl: 'https://oss.example/put', key: KEY }; });+ if (stage === 'read') readFileMock.mockImplementationOnce(async () => { current = false; return Buffer.alloc(100); });+ if (stage === 'put') undiciFetchMock.mockImplementationOnce(async () => { current = false; return { ok: true, status: 200 }; });+ await expect(uploadLocalFile('/tmp/a.png', { assertCurrent })).rejects.toThrow('stale attachment');+ expect(apiFetch.mock.calls.map(([path]) => path)).toEqual(stage === 'stat' ? [] : [PUT_PATH, DEL_PATH]);+ expect(undiciFetchMock).toHaveBeenCalledTimes(stage === 'put' ? 1 : 0);+ expect(netFetchMock).not.toHaveBeenCalled();+ });+it('取消上传 → 立刻中止 PUT,不换传输栈重试,并删除已签发的对象', async () => {const abort = new AbortController();undiciFetchMock.mockImplementation(@@ -719,6 +732,15 @@ describe('putBytesToOss — 传输栈回退', () => {});describe('uploadBuffer — 内存字节(base64 附件)', () => {+ it.each(['presign', 'put'])('discards a stale in-memory attachment after %s', async stage => {+ let current = true;+ if (stage === 'presign') apiFetch.mockImplementationOnce(async () => { current = false; return { putUrl: 'https://oss.example/put', key: KEY }; });+ else undiciFetchMock.mockImplementationOnce(async () => { current = false; return { ok: true, status: 200 }; });+ await expect(uploadBuffer(Buffer.from([1]), { ext: 'png', assertCurrent: () => { if (!current) throw new Error('stale'); } })).rejects.toThrow('stale');+ expect(apiFetch.mock.calls.map(([path]) => path)).toEqual([PUT_PATH, DEL_PATH]);+ expect(undiciFetchMock).toHaveBeenCalledTimes(stage === 'put' ? 1 : 0);+ });+it('presign-put 带 size/ext/contentType,整体 PUT,返回 key', async () => {okPut();const r = await uploadBuffer(Buffer.from([1, 2, 3, 4, 5]), {diff --git a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.tsindex 9222641f9a..435a8c3d95 100644--- a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts@@ -10,11 +10,13 @@* 之后,拦住就再也清不掉上一个账号的缓存。*/import { beforeEach, describe, expect, it, vi } from 'vitest';+import { EventEmitter } from 'node:events';const h = vi.hoisted(() => ({handlers: new Map<string, (...args: unknown[]) => unknown>(),trusted: true,ownerGeneration: 1,+ invalidations: new Set<() => void>(),senderDestroyed: false,selectFile: vi.fn(),canUseDeviceLink: true,@@ -58,6 +60,7 @@ vi.mock('../../lifecycle', () => ({}));// 读路径要比对 owner 作用域路径(账号边界复核),这里给个稳定值即可。vi.mock('../../appSessionState', () => ({+ onAppSessionInvalidated: (cancel: () => void) => { h.invalidations.add(cancel); return () => h.invalidations.delete(cancel); },getActiveAppSession: () => ({ dataOwnerId: 'owner-x', generation: h.ownerGeneration, mode: 'cloud' }),isAppSessionBoundaryPending: () => false,activeOwnerScopeKey: (): string => 'cloud:owner-x:1',@@ -166,7 +169,7 @@ vi.mock('../subscriptionRefcount', () => ({import { DEVICE_LINK_INVOKE } from '../../../shared/deviceLinkIpc';import { registerDeviceLinkIpc } from '../ipc';-import { readWithSourceFileAccessRecovery } from '../sourceFileAccessRecovery';+import { readWithSourceFileAccessRecovery, sourceFileAccessTransferOptions, onSourceFileAccessDiscard } from '../sourceFileAccessRecovery';import { rewriteOutboundMedia } from '../outboundMedia';import { DeviceLinkError, REMOTE_INVOKE_ALLOWLIST } from '@cindy/device-link';import { DESKTOP_LOCAL } from '../../../shared/remoteDesktop';@@ -179,9 +182,10 @@ import {} from '../index';import { setDeviceControlEnabled } from '../settings-store';+const senderEvents = new EventEmitter();const FRAME = { detached: false };const EVENT = {- sender: { id: 42, isDestroyed: () => h.senderDestroyed, mainFrame: FRAME },+ sender: Object.assign(senderEvents, { id: 42, isDestroyed: () => h.senderDestroyed, mainFrame: FRAME }),senderFrame: FRAME,} as unknown as Electron.IpcMainInvokeEvent;@@ -209,6 +213,11 @@ async function call(channel: string, payload: unknown): Promise<unknown> {beforeEach(() => {vi.clearAllMocks();+ vi.mocked(remoteInvoke).mockReset();+ vi.mocked(rewriteOutboundMedia).mockReset().mockImplementation(async (_channel, args) => args);+ h.selectFile.mockReset();+ senderEvents.removeAllListeners();+ h.invalidations.clear();h.handlers.clear();h.quitHandlers.clear();h.trusted = true;@@ -245,6 +254,63 @@ describe('attachment access confirmation IPC', () => {expect(vi.mocked(remoteInvoke).mock.calls[0][2]).toEqual(['session', { content: [{ type: 'file', path: 'uploaded-ref' }] }]);});+ it('keeps uploaded bytes when a dispatched message has an uncertain result', async () => {+ const discard = vi.fn();+ vi.mocked(rewriteOutboundMedia).mockImplementationOnce(async (_channel, args) => {+ onSourceFileAccessDiscard(discard);+ return args;+ });+ vi.mocked(remoteInvoke).mockRejectedValueOnce(new DeviceLinkError('INVOKE_TIMEOUT', 'uncertain'));+ await expect(call(DEVICE_LINK_INVOKE.INVOKE, payload)).rejects.toThrow();+ expect(remoteInvoke).toHaveBeenCalledOnce();+ expect(discard).not.toHaveBeenCalled();+ });++ it.each([false, true])('queue content edits recover only in the foreground (background=%s)', async background => {+ const read = installReadFailure();+ h.selectFile.mockResolvedValueOnce({ canceled: false, filePaths: [source] });+ vi.mocked(remoteInvoke).mockResolvedValueOnce({ ok: true, result: { sessionId: 'session', pendingQueue: [{ clientId: 'queued', files: [] }] } });+ vi.mocked(remoteInvoke).mockResolvedValueOnce({ ok: true, result: 'updated' });+ const edited = { ...payload, channel: 'maker:input:update-content', args: ['session', 'queued', { files: [{ path: source }] }], scheduling: { background } };+ if (background) {+ await expect(call(DEVICE_LINK_INVOKE.INVOKE, edited)).rejects.toThrow();+ expect(h.selectFile).not.toHaveBeenCalled();+ expect(read).toHaveBeenCalledOnce();+ expect(remoteInvoke).toHaveBeenCalledOnce();+ } else {+ await expect(call(DEVICE_LINK_INVOKE.INVOKE, edited)).resolves.toBe('updated');+ expect(h.selectFile).toHaveBeenCalledOnce();+ expect(read).toHaveBeenCalledTimes(2);+ expect(remoteInvoke).toHaveBeenCalledTimes(2);+ expect(vi.mocked(remoteInvoke).mock.calls[1][1]).toBe('maker:input:update-content');+ }+ });++ it.each(['owner', 'window', 'navigation'])('cancels the confirmed upload immediately on %s invalidation', async invalidation => {+ let attempts = 0;+ const read = vi.fn(async () => {+ if (++attempts === 1) throw denied();+ const { signal } = sourceFileAccessTransferOptions();+ expect(signal).toBeDefined();+ const cancelled = new Promise<never>((_resolve, reject) => signal!.addEventListener('abort', () => reject(new Error('UPLOAD_CANCELLED')), { once: true }));+ if (invalidation === 'owner') {+ h.ownerGeneration++;+ for (const cancel of h.invalidations) cancel();+ } else if (invalidation === 'window') senderEvents.emit('destroyed');+ else senderEvents.emit('did-start-navigation', {}, 'https://other.test', false, true);+ expect(signal!.aborted).toBe(true);+ return cancelled;+ });+ vi.mocked(rewriteOutboundMedia).mockImplementationOnce(async () => { await readWithSourceFileAccessRecovery(source, read); return []; });+ h.selectFile.mockResolvedValueOnce({ canceled: false, filePaths: [source] });+ await expect(call(DEVICE_LINK_INVOKE.INVOKE, payload)).rejects.toThrow('PERMISSION_DENIED');+ expect(read).toHaveBeenCalledTimes(2);+ expect(remoteInvoke).not.toHaveBeenCalled();+ expect(h.invalidations.size).toBe(0);+ expect(senderEvents.listenerCount('destroyed')).toBe(0);+ expect(senderEvents.listenerCount('did-start-navigation')).toBe(0);+ });+it.each(['cancel', 'wrong-file', 'owner-change', 'window-closed', 'page-changed'])('does not dispatch after %s', async outcome => {const read = installReadFailure();h.selectFile.mockImplementationOnce(async () => {diff --git a/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts b/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.tsindex 6c80522e9b..5c444ead7d 100644--- a/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts@@ -8,7 +8,8 @@ import path from 'node:path';const uploadLocalFile = vi.hoisted(() => vi.fn());const uploadBuffer = vi.hoisted(() => vi.fn());-vi.mock('../mediaTransfer', () => ({ uploadLocalFile, uploadBuffer, mimeOf: () => 'text/plain' }));+const removeRemote = vi.hoisted(() => vi.fn(async () => {}));+vi.mock('../mediaTransfer', () => ({ uploadLocalFile, uploadBuffer, removeRemote, mimeOf: () => 'text/plain' }));const resolveSafe = vi.hoisted(() => vi.fn());vi.mock('../../imageCacheStore', () => ({ resolveSafe }));@@ -60,10 +61,32 @@ describe('rewriteOutboundMedia — channel gating', () => {const selectFile = vi.fn(async () => file);const result = await withSourceFileAccessRecovery({ selectFile, assertCurrent: () => {} },() => rewriteOutboundMedia('maker:send', args));- expect(isAttachmentOssRef((result[1] as any).content[0].path)).toBe(true);+ expect(isAttachmentOssRef((result[1] as { content: Array<{ path: string }> }).content[0].path)).toBe(true);expect(selectFile).toHaveBeenCalledWith(file);expect(uploadLocalFile).toHaveBeenCalledTimes(2);- expect((args[1] as any).content[0].path).toBe(file);+ expect((args[1] as { content: Array<{ path: string }> }).content[0].path).toBe(file);+ });++ it('discards an uploaded object if its owner becomes stale while retaining the sent image', async () => {+ let current = true;+ const file = '/private/wechat/test.pdf';+ const signal = new AbortController().signal;+ await expect(withSourceFileAccessRecovery({ signal, selectFile: async () => file, assertCurrent: () => { if (!current) throw new Error('stale'); } },+ () => withPeerAttachmentUpload(async () => null,+ () => rewriteOutboundMedia('maker:send', ['session', { type: 'user', content: [{ type: 'file', path: file }] }]),+ async () => { current = false; }))).rejects.toThrow('stale');+ expect(uploadLocalFile).toHaveBeenCalledWith(file, expect.objectContaining({ signal, assertCurrent: expect.any(Function) }));+ expect(removeRemote).toHaveBeenCalledWith('cindy/device-link/u/x.png');+ });++ it('discards earlier objects in the same unsent batch when a later file loses its owner', async () => {+ const controller = new AbortController();+ let current = true;+ uploadLocalFile.mockResolvedValueOnce({ key: 'first-object', size: 1, contentType: 'application/octet-stream', sha256: SHA256 });+ uploadLocalFile.mockImplementationOnce(async () => { current = false; controller.abort(); throw new Error('cancelled'); });+ await expect(withSourceFileAccessRecovery({ signal: controller.signal, selectFile: async () => null, assertCurrent: () => { if (!current) throw new Error('stale'); } },+ () => rewriteOutboundMedia('maker:send', ['session', { type: 'user', content: [{ type: 'file', path: '/first' }, { type: 'file', path: '/second' }] }]))).rejects.toThrow('stale');+ expect(removeRemote).toHaveBeenCalledExactlyOnceWith('first-object');});it.each([null, '/private/another.pdf'])('keeps the original unsent when confirmation returns %s', async selected => {@@ -119,7 +142,7 @@ describe('rewriteOutboundMedia — channel gating', () => {const [cancelled, completed] = await Promise.allSettled([send(first, null), send(second, second)]);expect(cancelled.status).toBe('rejected');expect(completed.status).toBe('fulfilled');- if (completed.status === 'fulfilled') expect(isAttachmentOssRef((completed.value[1] as any).content[0].path)).toBe(true);+ if (completed.status === 'fulfilled') expect(isAttachmentOssRef((completed.value[1] as { content: Array<{ path: string }> }).content[0].path)).toBe(true);expect(uploadLocalFile.mock.calls.map(([file]) => file)).toEqual([first, second, second]);});it.each([@@ -201,11 +224,26 @@ describe('rewriteOutboundMedia — channel gating', () => {}});+ it('propagates foreground cancellation to peer upload and never falls back to OSS', async () => {+ const controller = new AbortController();+ const direct = vi.fn(async (_source: string | Buffer, _mime?: string, signal?: AbortSignal) => {+ expect(signal).toBe(controller.signal);+ controller.abort();+ throw new Error('FILE_PEER_CANCELLED');+ });+ await expect(withSourceFileAccessRecovery({ signal: controller.signal, selectFile: async () => null, assertCurrent: () => { controller.signal.throwIfAborted(); } },+ () => withPeerAttachmentUpload(direct, () => rewriteOutboundMedia('maker:send', ['session', {+ type: 'user', content: [{ type: 'file', path: '/controller/a.txt' }],+ }])))).rejects.toThrow();+ expect(direct).toHaveBeenCalledOnce();+ expect(uploadLocalFile).not.toHaveBeenCalled();+ });+it('uses peer staging for exact file bytes, preserves the name and retains OSS fallback', async () => {const direct = vi.fn(async () => buildPeerAttachmentRef({ ticket: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', size: 10, sha256: SHA256, mimeType: 'text/plain' }));const args = ['session', { type: 'user', content: [{ type: 'file', path: '/controller/a.txt', originalName: 'a.txt' }] }];const result = await withPeerAttachmentUpload(direct, () => rewriteOutboundMedia('maker:send', args));- const ref = (result[1] as any).content[0].path;+ const ref = (result[1] as { content: Array<{ path: string }> }).content[0].path;expect(parsePeerAttachmentRef(ref)?.originalName).toBe('a.txt');expect(uploadLocalFile).not.toHaveBeenCalled();await withPeerAttachmentUpload(async () => null, () => rewriteOutboundMedia('maker:send', args));diff --git a/apps/desktop/src/main/device-link/__tests__/sourceFileAccessRecovery.test.ts b/apps/desktop/src/main/device-link/__tests__/sourceFileAccessRecovery.test.tsnew file mode 100644index 0000000000..cce52e69a5--- /dev/null+++ b/apps/desktop/src/main/device-link/__tests__/sourceFileAccessRecovery.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it, vi } from 'vitest';+const stat = vi.hoisted(() => vi.fn());+vi.mock('node:fs/promises', () => ({ stat }));+import { readWithSourceFileAccessRecovery, withSourceFileAccessRecovery } from '../sourceFileAccessRecovery';++// #6530 / review r4356768707: readWithSourceFileAccessRecovery must resume a+// denied original selected with different Windows casing, while rejecting another file.+// Existing outboundMedia tests cover exact POSIX spelling only. This separate unit+// fixture mocks filesystem identity and isolates process.platform without loading IPC.+// Minimal input: one EPERM followed by a same-case-folded selection (same/different inode).+// Windows can return a different casing for the same selection. File identity,+// rather than case folding alone, must still reject distinct case-sensitive files.+describe('native attachment source selection on Windows', () => {+ it.each(['same', 'different', 'unavailable', 'unsupported'] as const)('checks filesystem identity when casing differs: %s', async identity => {+ const platform = Object.getOwnPropertyDescriptor(process, 'platform')!;+ Object.defineProperty(process, 'platform', { value: 'win32' });+ stat.mockReset();+ const source = 'C:\\WeChat\\Test.pdf';+ const selected = 'c:\\wechat\\test.pdf';+ if (identity === 'unavailable') stat.mockRejectedValue(new Error('denied'));+ else stat.mockResolvedValueOnce({ isFile: () => true, dev: 1n, ino: identity === 'unsupported' ? 0n : 42n })+ .mockResolvedValueOnce({ isFile: () => true, dev: 1n, ino: identity === 'same' ? 42n : 43n });+ const denied = Object.assign(new Error('denied'), { code: 'EPERM', syscall: 'open', path: source });+ const read = vi.fn().mockRejectedValueOnce(denied).mockResolvedValue('uploaded');+ try {+ const result = withSourceFileAccessRecovery({ selectFile: async () => selected, assertCurrent: () => {} },+ () => readWithSourceFileAccessRecovery(source, read));+ if (identity === 'same') await expect(result).resolves.toBe('uploaded');+ else await expect(result).rejects.toMatchObject({ code: 'DEVICE_LINK_MEDIA_ACCESS_DENIED' });+ expect(read).toHaveBeenCalledTimes(identity === 'same' ? 2 : 1);+ } finally {+ Object.defineProperty(process, 'platform', platform);+ }+ });+});diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.tsindex 95d0b6c398..e593496acc 100644--- a/apps/desktop/src/main/device-link/ipc.ts+++ b/apps/desktop/src/main/device-link/ipc.ts@@ -30,7 +30,7 @@ import { PLUGIN_OAUTH_CHANNEL, PLUGIN_OAUTH_LOCAL_CHANNEL, PLUGIN_SECRET_LOCAL_Cimport { handleAssistPluginOauth, handleSubmitPluginSecret, handleSubmitPluginConnection, handleSubmitInputHandoff, handleOpenInputHandoffPicture, handleAnswerInputHandoffPicture, type LocalOauthDeps } from '../plugin-oauth/localIpc.js';import { LocalDeviceCodeSessions } from '../plugin-oauth/deviceCodeSessions.js';import { PLUGIN_OAUTH_DEVICE_CODE_CHANNEL } from '../../shared/pluginOauthDeviceCode.js';-import { getActiveAppSession, isAppSessionBoundaryPending } from '../appSessionState.js';+import { getActiveAppSession, isAppSessionBoundaryPending, onAppSessionInvalidated } from '../appSessionState.js';import {DL_SESSION_REFERENCE_CAPABILITY_CHANNEL,DeviceLinkError,@@ -83,7 +83,7 @@ import { createSentImageRetainer } from './remoteMediaPersistentCache';import { withOutboundReviewConfirmation } from '../maker-ipc/reviewOutboundInput.js';import { confirmReviewArtifacts } from '../reviewer/confirmReviewArtifacts.js';import { tryUploadPeerAttachment } from './filePeer';-import { withSourceFileAccessRecovery } from './sourceFileAccessRecovery';+import { withSourceFileAccessRecovery, releaseSourceFileAccessUploads } from './sourceFileAccessRecovery';import { parseSharedTaskPeer, scrubSharedProviderCatalog } from '@cindy/device-link';import { withSharedTaskMedia } from './sharedTaskMediaContext.js';import {@@ -722,7 +722,7 @@ export async function handleInvoke(if (projectionUnavailable) {throwIpcError('DEVICE_LINK_CHANNEL_NOT_ALLOWED', 'Queued content editing is not supported by the target device');}- callArgs = await withPeerAttachmentUpload((source, mime) => peer ? Promise.resolve(null) : tryUploadPeerAttachment(normalizedDeviceId, source, mime, deps.invoke), () =>+ callArgs = await withPeerAttachmentUpload((source, mime, signal) => peer ? Promise.resolve(null) : tryUploadPeerAttachment(normalizedDeviceId, source, mime, deps.invoke, undefined, signal), () =>withSharedTaskMedia(peer?.role === 'host' ? peer.sharedTaskId : undefined,() => existing ? deps.rewriteOutboundMedia!(channel, callArgs, existing) : deps.rewriteOutboundMedia!(channel, callArgs)),createSentImageRetainer(normalizedDeviceId));@@ -1691,16 +1691,18 @@ export function registerDeviceLinkIpc(deps: DeviceLinkIpcDeps = defaultDeps()):() => handleInvoke(diagnostics.forWindow(deps, e.sender.id), p.deviceId, p.channel, p.args),);}- const interactiveAttachmentSend = ['maker:send', 'maker:steer', 'maker:input:enqueue', 'maker:input:steer'].includes(String(p.channel))+ const interactiveAttachmentSend = ['maker:send', 'maker:steer', 'maker:input:enqueue', 'maker:input:steer', 'maker:input:update-content'].includes(String(p.channel))&& !(p.scheduling && typeof p.scheduling === 'object' && 'background' in p.scheduling && p.scheduling.background === true);if (interactiveAttachmentSend) {assertTrustedAppRendererEvent(e);const owner = getActiveAppSession();+ const transfer = new AbortController();+ const cancel = () => transfer.abort();const frame = e.senderFrame;const targetWindow = BrowserWindow.fromWebContents(e.sender);const assertCurrent = () => {const current = getActiveAppSession();- if (isAppSessionBoundaryPending() || !owner.dataOwnerId+ if (transfer.signal.aborted || isAppSessionBoundaryPending() || !owner.dataOwnerId|| current.dataOwnerId !== owner.dataOwnerId || current.generation !== owner.generation|| e.sender.isDestroyed() || !frame || frame.detached || e.sender.mainFrame !== frame|| !targetWindow || targetWindow.isDestroyed()) {@@ -1712,10 +1714,21 @@ export function registerDeviceLinkIpc(deps: DeviceLinkIpcDeps = defaultDeps()):// This guard also runs immediately before final message dispatch, after all file awaits.const guardedDeps: DeviceLinkIpcDeps = {...scopedDeps,- invoke: (...args) => { assertCurrent(); return scopedDeps.invoke(...args); },+ invoke: (...args) => {+ assertCurrent();+ if (args[1] === p.channel) releaseSourceFileAccessUploads();+ return scopedDeps.invoke(...args);+ },+ };+ const unsubscribe = onAppSessionInvalidated(cancel);+ e.sender.on('destroyed', cancel);+ const onNavigation = (_event: unknown, _url: string, _inPlace: boolean, isMainFrame: boolean) => {+ if (isMainFrame) cancel();};+ e.sender.on('did-start-navigation', onNavigation);return withSourceFileAccessRecovery({assertCurrent,+ signal: transfer.signal,selectFile: async (source) => {assertCurrent();const selected = await dialog.showOpenDialog(targetWindow!, {@@ -1728,7 +1741,11 @@ export function registerDeviceLinkIpc(deps: DeviceLinkIpcDeps = defaultDeps()):assertCurrent();return selected.canceled || selected.filePaths.length !== 1 ? null : selected.filePaths[0];},- }, () => handleInvoke(guardedDeps, p.deviceId, p.channel, p.args, p.scheduling));+ }, () => handleInvoke(guardedDeps, p.deviceId, p.channel, p.args, p.scheduling)).finally(() => {+ unsubscribe();+ e.sender.removeListener('destroyed', cancel);+ e.sender.removeListener('did-start-navigation', onNavigation);+ });}return handleInvoke(diagnostics.forWindow(deps, e.sender.id), p.deviceId, p.channel, p.args, p.scheduling);});diff --git a/apps/desktop/src/main/device-link/mediaTransfer.ts b/apps/desktop/src/main/device-link/mediaTransfer.tsindex 8e65512efe..a0a58ff2e4 100644--- a/apps/desktop/src/main/device-link/mediaTransfer.ts+++ b/apps/desktop/src/main/device-link/mediaTransfer.ts@@ -291,6 +291,7 @@ async function putBytesToOss(bodySource: OssPutBodySource,contentType: string,signal?: AbortSignal,+ assertCurrent?: () => void,): Promise<void> {const host = hostOf(putUrl);const headers: Record<string, string> = {@@ -338,6 +339,7 @@ async function putBytesToOss(const failures: string[] = [];const hints: string[] = [];for (const transport of order) {+ assertCurrent?.();try {signal?.throwIfAborted();await attempt(transport.impl);@@ -418,9 +420,13 @@ export async function uploadLocalFile(onProgress?: (uploadedBytes: number) => void;/** Aborting stops the PUT at once (no transport retry) and deletes the staged object. */signal?: AbortSignal;+ /** Initiating request owner/window guard; never prepare or publish under a new scope. */+ assertCurrent?: () => void;} = {},): Promise<UploadResult> {+ opts.assertCurrent?.();const st = await withSourceFileHandleContext(localPath, () => stat(localPath));+ opts.assertCurrent?.();if (!st.isFile()) throw new Error(`不是文件: ${localPath}`);const size = st.size;if (opts.maxBytes !== undefined) {@@ -443,6 +449,8 @@ export async function uploadLocalFile(const sourcesClosed: Promise<void>[] = [];try {+ opts.assertCurrent?.();+ opts.signal?.throwIfAborted();if (size <= STREAM_THRESHOLD) {// 小媒体:读进 Buffer 整体 PUT(成熟稳定路径)。整体 PUT 无中间粒度,// 完成时一次性回调。@@ -469,6 +477,7 @@ export async function uploadLocalFile(buf = await withSourceFileHandleContext(localPath, () =>readFile(localPath, opts.signal ? { signal: opts.signal } : undefined));}+ opts.assertCurrent?.();if (buf.byteLength !== size) {throw new Error(`文件在上传前发生变化:预期 ${size} 字节,实际 ${buf.byteLength} 字节`);}@@ -480,6 +489,7 @@ export async function uploadLocalFile({ create: () => exactArrayBuffer(buf) },contentType,opts.signal,+ opts.assertCurrent,);opts.onProgress?.(size);} else {@@ -547,7 +557,7 @@ export async function uploadLocalFile(// 已缓冲的数据,每次换栈上传都漏一个。dispose: () => attempts.at(-1)?.dispose(),};- await putBytesToOss(putUrl, bodySource, contentType, opts.signal);+ await putBytesToOss(putUrl, bodySource, contentType, opts.signal, opts.assertCurrent);const uploadedAttempt = attempts.at(-1);if (!uploadedAttempt || uploadedAttempt.sent !== size) {// Cleanup is centralized below so transport and source-stream errors use the same path.@@ -558,6 +568,8 @@ export async function uploadLocalFile(if (!uploadedAttempt.sha256) throw new Error('上传流未读完,无法确认字节摘要');sha256 = uploadedAttempt.sha256;}+ opts.assertCurrent?.();+ opts.signal?.throwIfAborted();} catch (error) {// Cleanup is best-effort after every post-presign transfer failure; a cancelled upload// does not wait for it.@@ -577,8 +589,10 @@ export async function uploadLocalFile(*/export async function uploadBuffer(bytes: Buffer,- opts: { ext: string; contentType?: string },+ opts: { ext: string; contentType?: string; signal?: AbortSignal; assertCurrent?: () => void },): Promise<UploadResult> {+ opts.assertCurrent?.();+ opts.signal?.throwIfAborted();const size = bytes.byteLength;if (size <= 0) throw new Error('uploadBuffer: 空字节');if (size > MAX_MEDIA_BYTES) {@@ -586,13 +600,22 @@ export async function uploadBuffer(}const ext = extOf(`x.${opts.ext}`);const contentType = opts.contentType ?? mimeOf(ext);- const { putUrl, key } = await presignPut(size, ext, contentType);+ const { putUrl, key } = await abortable(presignPut(size, ext, contentType), opts.signal);const ab = bytes.buffer.slice(bytes.byteOffset,bytes.byteOffset + bytes.byteLength,) as ArrayBuffer;const sha256 = createHash('sha256').update(bytes).digest('hex');- await putBytesToOss(putUrl, { create: () => ab }, contentType);+ try {+ opts.assertCurrent?.();+ await putBytesToOss(putUrl, { create: () => ab }, contentType, opts.signal, opts.assertCurrent);+ opts.assertCurrent?.();+ opts.signal?.throwIfAborted();+ } catch (error) {+ const removing = removeRemote(key);+ if (!opts.signal?.aborted) await removing;+ throw error;+ }log.debug(`uploaded(buffer) key=${key} size=${size} ct=${contentType} integrity=sha256`);return { key, size, contentType, sha256 };}diff --git a/apps/desktop/src/main/device-link/outboundMedia.ts b/apps/desktop/src/main/device-link/outboundMedia.tsindex c6ea1175f9..ba81748be8 100644--- a/apps/desktop/src/main/device-link/outboundMedia.ts+++ b/apps/desktop/src/main/device-link/outboundMedia.ts@@ -15,7 +15,7 @@ import { promises as fsp } from 'node:fs';import path from 'node:path';import { AsyncLocalStorage } from 'node:async_hooks';import { buildPeerAttachmentRef, parsePeerAttachmentRef } from '@cindy/device-link';-type PeerUpload = (source: string | Buffer, mimeType?: string) => Promise<string | null>;+type PeerUpload = (source: string | Buffer, mimeType?: string, signal?: AbortSignal) => Promise<string | null>;type RetainSentImage = (source: string | Buffer, ref: string) => Promise<void>;const peerUploadContext = new AsyncLocalStorage<{ upload: PeerUpload; retain?: RetainSentImage }>();export function withPeerAttachmentUpload<T>(upload: PeerUpload, operation: () => Promise<T>, retain?: RetainSentImage) {@@ -25,7 +25,7 @@ export function withPeerAttachmentUpload<T>(upload: PeerUpload, operation: () =>import { createLogger } from '../logger';import * as imageCacheStore from '../imageCacheStore';import * as cindyMediaBlobStore from '../cindy-media/blobStore';-import { uploadLocalFile, uploadBuffer, mimeOf, type UploadResult } from './mediaTransfer';+import { uploadLocalFile, uploadBuffer, removeRemote, mimeOf, type UploadResult } from './mediaTransfer';import { sharedTaskMediaId } from './sharedTaskMediaContext.js';import {OUTBOUND_IMAGE_INPUT_MAX_BYTES,@@ -36,7 +36,7 @@ import { buildLegacyAttachmentOssRef, parseAttachmentOssRef } from '../../sharedimport { readStartReviewRequest } from '../maker-ipc/reviewStartHandler.js';import { withPreparedOutboundReview } from '../maker-ipc/reviewOutboundInput.js';import { createSourceFileAccessError, isSourceFileAccessError } from './sourceFileError';-import { readWithSourceFileAccessRecovery } from './sourceFileAccessRecovery';+import { readWithSourceFileAccessRecovery, sourceFileAccessTransferOptions, onSourceFileAccessDiscard } from './sourceFileAccessRecovery';const log = createLogger('device-link:outboundMedia');@@ -104,7 +104,10 @@ async function uploadAttachment(src: AttachmentSource): Promise<string> {const context = peerUploadContext.getStore();if (!context || sharedTaskMediaId()) return null;const effectiveMime = contentType ?? mimeOf(typeof source === 'string' ? path.extname(source).slice(1).toLowerCase() : 'bin');- const result = await context.upload(source, effectiveMime);+ const transfer = sourceFileAccessTransferOptions();+ transfer.assertCurrent?.();+ const result = await context.upload(source, effectiveMime, transfer.signal);+ transfer.assertCurrent?.();const parsed = result && parsePeerAttachmentRef(result);return parsed ? buildPeerAttachmentRef({ ...parsed, originalName }) : null;};@@ -114,12 +117,25 @@ async function uploadAttachment(src: AttachmentSource): Promise<string> {await peerUploadContext.getStore()?.retain?.(source, ref).catch(() => undefined);return ref;};- const bufferRef = async (bytes: Buffer, options: Parameters<typeof uploadBuffer>[1]) => retain(bytes,- await direct(bytes, options?.contentType) ?? buildUploadedAttachmentRef(await uploadBuffer(bytes, options), originalName));+ const retainUpload = async (source: string | Buffer, uploaded: UploadResult) => {+ onSourceFileAccessDiscard(() => { void removeRemote(uploaded.key); });+ sourceFileAccessTransferOptions().assertCurrent?.();+ const ref = await retain(source, buildUploadedAttachmentRef(uploaded, originalName));+ sourceFileAccessTransferOptions().assertCurrent?.();+ return ref;+ };+ const bufferRef = async (bytes: Buffer, options: Parameters<typeof uploadBuffer>[1]) => {+ const peerRef = await direct(bytes, options?.contentType);+ return peerRef ? retain(bytes, peerRef) : retainUpload(bytes,+ await uploadBuffer(bytes, { ...options, ...sourceFileAccessTransferOptions() }));+ };const fileRef = async (file: string, options: Parameters<typeof uploadLocalFile>[1]) => {try {- return await readWithSourceFileAccessRecovery(file, async () => retain(file,- await direct(file, options?.contentType) ?? buildUploadedAttachmentRef(await uploadLocalFile(file, options), originalName)));+ return await readWithSourceFileAccessRecovery(file, async () => {+ const peerRef = await direct(file, options?.contentType);+ if (peerRef) return retain(file, peerRef);+ return retainUpload(file, await uploadLocalFile(file, { ...options, ...sourceFileAccessTransferOptions() }));+ });} catch (error) {if (isSourceFileAccessError(error, file)) {// Do not send Node's private source path across IPC or persist it in chat history.diff --git a/apps/desktop/src/main/device-link/sourceFileAccessRecovery.ts b/apps/desktop/src/main/device-link/sourceFileAccessRecovery.tsindex 22c4165396..572426deab 100644--- a/apps/desktop/src/main/device-link/sourceFileAccessRecovery.ts+++ b/apps/desktop/src/main/device-link/sourceFileAccessRecovery.ts@@ -1,17 +1,70 @@import { AsyncLocalStorage } from 'node:async_hooks';import path from 'node:path';+import { stat } from 'node:fs/promises';import { createSourceFileAccessError, isSourceFileAccessError } from './sourceFileError';interface SourceFileAccessRecovery {/** A native single-file picker; the selected path stays inside Main. */selectFile(source: string): Promise<string | null>;assertCurrent(): void;+ signal?: AbortSignal;}-const recoveryContext = new AsyncLocalStorage<SourceFileAccessRecovery & { attempted: Set<string> }>();+const recoveryContext = new AsyncLocalStorage<SourceFileAccessRecovery & { attempted: Set<string>; discard: Set<() => void> }>();/** Only the trusted foreground chat adapter installs this scope. Exports/background jobs do not prompt. */export function withSourceFileAccessRecovery<T>(recovery: SourceFileAccessRecovery, operation: () => Promise<T>): Promise<T> {- return recoveryContext.run({ ...recovery, attempted: new Set() }, operation);+ const discard = new Set<() => void>();+ const discardUploads = () => {+ for (const cleanup of discard) cleanup();+ discard.clear();+ };+ recovery.signal?.addEventListener('abort', discardUploads, { once: true });+ return recoveryContext.run({ ...recovery, attempted: new Set(), discard }, async () => {+ try {+ return await operation();+ } catch (error) {+ discardUploads();+ recovery.assertCurrent();+ throw error;+ } finally {+ recovery.signal?.removeEventListener('abort', discardUploads);+ discard.clear();+ }+ });+}++/** Captured by each transfer, so its asynchronous checkpoints retain the initiating scope. */+export function sourceFileAccessTransferOptions(): { assertCurrent?: () => void; signal?: AbortSignal } {+ const scope = recoveryContext.getStore();+ return scope ? { assertCurrent: scope.assertCurrent, signal: scope.signal } : {};+}++/** A multi-attachment send owns every new object until its final dispatch starts. */+export function onSourceFileAccessDiscard(cleanup: () => void): void {+ const scope = recoveryContext.getStore();+ if (!scope) return;+ if (scope.signal?.aborted) cleanup();+ else scope.discard.add(cleanup);+}++/** Once dispatch starts its outcome may be uncertain; accepted messages still need these bytes. */+export function releaseSourceFileAccessUploads(): void {+ recoveryContext.getStore()?.discard.clear();+}++async function isSelectedSource(source: string, selected: string): Promise<boolean> {+ if (selected === source) return true;+ if (process.platform !== 'win32'+ || path.win32.normalize(selected).toLowerCase() !== path.win32.normalize(source).toLowerCase()) return false;+ // Folding alone would accept a different file in a case-sensitive Windows directory.+ // Compare filesystem identity instead; a missing/unsupported identity fails closed.+ try {+ const [original, confirmed] = await Promise.all([stat(source, { bigint: true }), stat(selected, { bigint: true })]);+ return original.isFile() && confirmed.isFile() && original.ino !== 0n+ && original.dev === confirmed.dev && original.ino === confirmed.ino;+ } catch {+ return false;+ }}export async function readWithSourceFileAccessRecovery<T>(source: string, read: () => Promise<T>): Promise<T> {@@ -23,13 +76,14 @@ export async function readWithSourceFileAccessRecovery<T>(source: string, read:return result;} catch (error) {if (!scope || !isSourceFileAccessError(error, source)- || !path.isAbsolute(source) || scope.attempted.has(source)) throw error;+ || !(process.platform === 'win32' ? path.win32 : path).isAbsolute(source) || scope.attempted.has(source)) throw error;scope.assertCurrent();scope.attempted.add(source);const selected = await scope.selectFile(source);scope.assertCurrent();// Confirm only this original. A different file must never silently replace a draft attachment.- if (!selected || selected !== source) throw createSourceFileAccessError();+ if (!selected || !await isSelectedSource(source, selected)) throw createSourceFileAccessError();+ scope.assertCurrent();// No recursive retry: a second denial returns the normal error and restores the draft.const result = await read();scope.assertCurrent();diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 2fb5680a09..7ad0f74720 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -763,6 +763,12 @@ Desktop 与 Mobile 的错误展示技术详情保持折叠。不新增 channel、relay 字段或权限。生成该错误的是桌面控制端,不要求目标设备升级;旧客户端遇到历史里的未知错误仍走原通用提示。SSH 的远端文件读取流程不变。+受信前台发送与队列编辑(`maker:input:update-content`)在单个源文件拒读后,允许一次原生+单文件确认并重试同一份草稿;后台任务不弹确认。Windows 大小写不同的选择必须由文件系统+文件身份(device/inode)证明为同一来源,不能仅忽略大小写接受。账号切换、代次变化、+窗口销毁或主页面导航会取消直传与 OSS 上传;各异步读取、预签名与 PUT 边界重新核对发起作用域,失效不再派发。+派发前失败对本次新上传对象做 best-effort 删除(OSS 生命周期兜底);开始派发后,结果可能+不确定,保留对象供已接收消息读取。清理不改变服务端 ownership 校验。这不授予 macOS 文件权限,也不证明微信拖入的系统授权生命周期已修复。## 电脑互联的消息文件与历史变更