Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(device-link): sanitize source denials and restore offline drafts

elfcv74317aaa7233
diff --git a/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts b/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
index 8e5fc2e95c..dd4a3a4bae 100644
--- a/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
@@ -93,12 +93,17 @@ describe('peer attachment upload preflight', () => {
// #6530: an unreadable local file must not cool down a healthy peer or trigger OSS fallback.
it.each(['EPERM', 'EACCES'])('keeps the peer usable after source open fails with %s', async code => {
const source = path.resolve('unreadable-inventory.xlsx');
- const error = Object.assign(new Error('source access denied'), { code, syscall: 'open', path: source });
+ const error = Object.assign(new Error(`${code}: open '${source}'`), { code, syscall: 'open', path: source });
const open = vi.spyOn(fsPromises, 'open').mockRejectedValueOnce(error);
const invoke = vi.fn(async () => ({ ok: true, result: { version: 1 } }));
const peer = `source-access-${code}`;
try {
- await expect(tryUploadPeerAttachment(peer, source, undefined, invoke)).rejects.toBe(error);
+ // The generic helper also serves plugin picking and directory export, outside outboundMedia.
+ const failure = await tryUploadPeerAttachment(peer, source, undefined, invoke).catch(error => error);
+ expect(failure).toMatchObject({ code: 'DEVICE_LINK_MEDIA_ACCESS_DENIED' });
+ expect(String(failure)).not.toContain(source);
+ expect(failure).not.toHaveProperty('path');
+ expect(failure).not.toHaveProperty('cause');
expect(invoke).not.toHaveBeenCalled();
// A subsequent readable attachment still probes the peer (no permission-error cooldown).
await tryUploadPeerAttachment(peer, Buffer.from('readable copy'), undefined, invoke);
@@ -740,6 +745,9 @@ describe('authorized file peer source', () => {
await tryUploadPeerAttachment(peer, file, undefined, invoke);
} catch (error) { caught = error; }
expect(isSourceFileAccessError(caught, file)).toBe(true);
+ expect(caught).toMatchObject({ code: 'DEVICE_LINK_MEDIA_ACCESS_DENIED' });
+ expect(caught).not.toHaveProperty('path');
+ expect(caught).not.toHaveProperty('cause');
expect(close).toHaveBeenCalledOnce();
if (phase === 'transfer') expect(ops()).toEqual(['begin', 'cancel']);
else expect(ops()).toEqual([]);
diff --git a/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts b/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts
index 9effb126cb..5e304f6f6c 100644
--- a/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts
@@ -241,6 +241,51 @@ describe('uploadLocalFile — 小文件整体 PUT', () => {
});
describe('uploadLocalFile — bounded snapshots', () => {
+ // #6530 / r4322420399, unit: the OSS entry must classify pathless local fd denials,
+ // unlike fetch failures. Existing source-error tests cover EIO, not permission recovery.
+ it.each(['buffer', 'bounded-stream', 'large-stream'] as const)(
+ 'returns a safe access error for a pathless %s source denial', async mode => {
+ const size = mode === 'large-stream' ? __testing.STREAM_THRESHOLD + 1 : 100;
+ statMock.mockResolvedValue({ isFile: () => true, size });
+ const denial = Object.assign(new Error('read denied'), {
+ code: 'EACCES', syscall: mode === 'buffer' ? 'fstat' : 'read',
+ });
+ if (mode === 'buffer') readFileMock.mockRejectedValueOnce(denial);
+ createReadStreamMock.mockImplementation(() => new Readable({
+ read() { this.destroy(denial); },
+ }));
+ undiciFetchMock.mockImplementation(drainingPut);
+ const failure = await uploadLocalFile('/private/source.xlsx',
+ mode === 'bounded-stream' ? { maxBytes: size } : undefined).catch(error => error);
+ expect(failure).toMatchObject({ code: 'DEVICE_LINK_MEDIA_ACCESS_DENIED' });
+ expect(String(failure)).not.toContain('/private/');
+ expect(failure).not.toHaveProperty('path');
+ expect(failure).not.toHaveProperty('cause');
+ expect(netFetchMock).not.toHaveBeenCalled();
+ if (mode !== 'large-stream') expect(undiciFetchMock).not.toHaveBeenCalled();
+ expect(apiFetch).toHaveBeenCalledWith(
+ DEL_PATH, expect.objectContaining({ method: 'DELETE', body: { key: KEY } }),
+ );
+ },
+ );
+
+ it.each(['network', 'other-source'] as const)(
+ 'does not label %s permission errors as attachment access denial', async kind => {
+ statMock.mockResolvedValue({ isFile: () => true, size: 100 });
+ const denial = Object.assign(new Error('permission failure'), kind === 'network'
+ ? { code: 'EACCES', syscall: 'connect' }
+ : { code: 'EPERM', syscall: 'read', path: '/other/source' });
+ readFileMock.mockResolvedValue(Buffer.alloc(100));
+ if (kind === 'other-source') readFileMock.mockRejectedValueOnce(denial);
+ undiciFetchMock.mockRejectedValue(denial);
+ netFetchMock.mockRejectedValue(denial);
+ const failure = await uploadLocalFile('/private/source.xlsx').catch(error => error);
+ expect(failure).toBeInstanceOf(Error);
+ expect(failure.code).not.toBe('DEVICE_LINK_MEDIA_ACCESS_DENIED');
+ if (kind === 'other-source') expect(failure).toBe(denial);
+ },
+ );
+
it.each([NaN, Infinity, -1, 1.5, 99])(
'rejects invalid or exceeded budget %s before presign',
async (maxBytes) => {
diff --git a/apps/desktop/src/main/device-link/filePeer.ts b/apps/desktop/src/main/device-link/filePeer.ts
index b4c7ac62cd..54702d64c2 100644
--- a/apps/desktop/src/main/device-link/filePeer.ts
+++ b/apps/desktop/src/main/device-link/filePeer.ts
@@ -41,7 +41,7 @@ import { createLogger } from '../logger.js';
import { handlePeerAttachment } from './peerAttachmentStore';
import { fileVersion } from './fileVersion';
import { remoteFileVersionCache, type FileVersionMetadata } from './remoteFileVersionCache';
-import { isSourceFileAccessError, withSourceFileHandleContext } from './sourceFileError';
+import { createSourceFileAccessError, isSourceFileAccessError, withSourceFileHandleContext } from './sourceFileError';
// Local-only diagnostics (scope is not upload-allowlisted): stages, sizes and timings, never paths.
const log = createLogger('device-link:filePeer');
@@ -1106,7 +1106,7 @@ export async function tryUploadPeerAttachment(
if (signal?.aborted) throw new Error('FILE_PEER_CANCELLED');
// The source is unreadable on this computer; another transport cannot fix it.
// Leave the healthy peer connection and its cooldown untouched.
- if (isSourceFileAccessError(error, source)) throw error;
+ if (isSourceFileAccessError(error, source)) throw createSourceFileAccessError();
cooldown.fail(peer);
const failed = outgoing.get(peer);
if (failed) stopConnection(failed.id, 'upload-failed');
diff --git a/apps/desktop/src/main/device-link/mediaTransfer.ts b/apps/desktop/src/main/device-link/mediaTransfer.ts
index 5eb42a94d1..8e65512efe 100644
--- a/apps/desktop/src/main/device-link/mediaTransfer.ts
+++ b/apps/desktop/src/main/device-link/mediaTransfer.ts
@@ -38,6 +38,7 @@ import { deviceLinkApiBase } from './index.js';
import { sharedTaskMediaId } from './sharedTaskMediaContext.js';
import { describeErrorChain } from '../utils/errorChain.js';
import { createLogger } from '../logger.js';
+import { sourceFileReadError, withSourceFileHandleContext } from './sourceFileError';
const log = createLogger('device-link:mediaTransfer');
@@ -419,7 +420,7 @@ export async function uploadLocalFile(
signal?: AbortSignal;
} = {},
): Promise<UploadResult> {
- const st = await stat(localPath);
+ const st = await withSourceFileHandleContext(localPath, () => stat(localPath));
if (!st.isFile()) throw new Error(`不是文件: ${localPath}`);
const size = st.size;
if (opts.maxBytes !== undefined) {
@@ -456,14 +457,17 @@ export async function uploadLocalFile(
...(opts.signal ? { signal: opts.signal } : {}),
});
sourcesClosed.push(new Promise((resolve) => source.once('close', () => resolve())));
- for await (const chunk of source) {
- received += chunk.length;
- if (received > size) throw new Error('REMOTE_FILE_TOO_LARGE');
- chunks.push(chunk);
- }
+ await withSourceFileHandleContext(localPath, async () => {
+ for await (const chunk of source) {
+ received += chunk.length;
+ if (received > size) throw new Error('REMOTE_FILE_TOO_LARGE');
+ chunks.push(chunk);
+ }
+ });
buf = Buffer.concat(chunks);
} else {
- buf = await readFile(localPath, opts.signal ? { signal: opts.signal } : undefined);
+ buf = await withSourceFileHandleContext(localPath, () =>
+ readFile(localPath, opts.signal ? { signal: opts.signal } : undefined));
}
if (buf.byteLength !== size) {
throw new Error(`文件在上传前发生变化:预期 ${size} 字节,实际 ${buf.byteLength} 字节`);
@@ -531,8 +535,9 @@ export async function uploadLocalFile(
// 必须同时把错误推给下游:`pipe` 不转发 error,只记不推的话 counter
// 既不 end 也不 error,web body 就此挂住,PUT 会一直干等到超时。
source.on('error', (err) => {
- current.sourceError = err;
- counter.destroy(err);
+ const failure = sourceFileReadError(err, localPath);
+ current.sourceError = failure;
+ counter.destroy(failure);
});
attempts.push(current);
return Readable.toWeb(source.pipe(counter)) as unknown as ReadableStream;
diff --git a/apps/desktop/src/main/device-link/outboundMedia.ts b/apps/desktop/src/main/device-link/outboundMedia.ts
index fb16dfc119..34284a6fc8 100644
--- a/apps/desktop/src/main/device-link/outboundMedia.ts
+++ b/apps/desktop/src/main/device-link/outboundMedia.ts
@@ -35,8 +35,7 @@ import {
import { buildLegacyAttachmentOssRef, parseAttachmentOssRef } from '../../shared/attachmentOssRef';
import { readStartReviewRequest } from '../maker-ipc/reviewStartHandler.js';
import { withPreparedOutboundReview } from '../maker-ipc/reviewOutboundInput.js';
-import { throwIpcError } from '../utils/ipcValidate';
-import { isSourceFileAccessError } from './sourceFileError';
+import { createSourceFileAccessError, isSourceFileAccessError } from './sourceFileError';
const log = createLogger('device-link:outboundMedia');
@@ -123,8 +122,7 @@ async function uploadAttachment(src: AttachmentSource): Promise<string> {
} catch (error) {
if (isSourceFileAccessError(error, file)) {
// Do not send Node's private source path across IPC or persist it in chat history.
- throwIpcError('DEVICE_LINK_MEDIA_ACCESS_DENIED',
- 'Cannot read the source attachment. Save a copy to an accessible folder, remove the original attachment, and add the copy again.');
+ throw createSourceFileAccessError();
}
throw error;
}
diff --git a/apps/desktop/src/main/device-link/sourceFileError.ts b/apps/desktop/src/main/device-link/sourceFileError.ts
index d1f07242b0..fae0023640 100644
--- a/apps/desktop/src/main/device-link/sourceFileError.ts
+++ b/apps/desktop/src/main/device-link/sourceFileError.ts
@@ -1,7 +1,16 @@
+import { createIpcError, isIpcError } from '../../shared/ipc-errors';
+
+/** Safe at every caller boundary, including non-chat IPC and remote export status. */
+export function createSourceFileAccessError() {
+ return createIpcError('DEVICE_LINK_MEDIA_ACCESS_DENIED',
+ 'Cannot read the source attachment. Save a copy to an accessible folder, remove the original attachment, and add the copy again.');
+}
+
/** Only a local source read denial warrants file-access recovery guidance.
* Transport permissions and failures writing another file must keep their own semantics.
*/
export function isSourceFileAccessError(error: unknown, source: string | Buffer): boolean {
+ if (isIpcError(error) && error.code === 'DEVICE_LINK_MEDIA_ACCESS_DENIED') return true;
if (typeof source !== 'string' || !error || typeof error !== 'object') return false;
const { code, syscall, path } = error as NodeJS.ErrnoException;
return (code === 'EPERM' || code === 'EACCES')
@@ -9,7 +18,20 @@ export function isSourceFileAccessError(error: unknown, source: string | Buffer)
&& (syscall === 'open' || syscall === 'stat' || syscall === 'fstat' || syscall === 'read');
}
-/** Use only around stat/read on a handle opened from this source, never around transport work. */
+/** Only for a known source read operation/stream; never use on a network or output error. */
+export function sourceFileReadError(error: Error, source: string | Buffer): Error {
+ const { code, syscall, path } = error as NodeJS.ErrnoException;
+ if (isSourceFileAccessError(error, source)
+ || (typeof source === 'string' && path === undefined
+ && (code === 'EPERM' || code === 'EACCES')
+ && (syscall === 'fstat' || syscall === 'read'))) {
+ // Do not retain path or cause: callers can serialize either, not just message.
+ return createSourceFileAccessError();
+ }
+ return error;
+}
+
+/** Use only around this source's stat/read operations, never around transport work. */
export async function withSourceFileHandleContext<T>(
source: string | Buffer,
operation: () => Promise<T>,
@@ -17,17 +39,6 @@ export async function withSourceFileHandleContext<T>(
try {
return await operation();
} catch (error) {
- if (typeof source === 'string' && error && typeof error === 'object') {
- const { code, syscall, path } = error as NodeJS.ErrnoException;
- // Node's fd-based failures omit path. Do not overwrite a different explicit path or
- // reinterpret a write/network failure just because it carries the same errno.
- if (path === undefined && (code === 'EPERM' || code === 'EACCES')
- && (syscall === 'fstat' || syscall === 'read')) {
- throw Object.assign(new Error('Source attachment access denied', { cause: error }), {
- code, syscall, path: source,
- });
- }
- }
- throw error;
+ throw error instanceof Error ? sourceFileReadError(error, source) : error;
}
}
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
index 633fb15e00..efe1d42708 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
@@ -5605,8 +5605,13 @@ describe('makerChatStore text delta batching', () => {
});
// #6530: the specific source-access error must release the outbox into editable draft recovery.
- it.each(['permission denied', '[DEVICE_LINK_MEDIA_ACCESS_DENIED] Cannot read the source attachment.'])(
- 'calls the composer recovery callback after permanent failure: %s', async failure => {
+ it.each([
+ ['permission denied', false],
+ ['[DEVICE_LINK_MEDIA_ACCESS_DENIED] Cannot read the source attachment.', false],
+ // #6530 / r4322420405: the source failure proves no dispatch even if the target goes offline.
+ ['[DEVICE_LINK_MEDIA_ACCESS_DENIED] Cannot read the source attachment.', true],
+ ] as const)(
+ 'calls the composer recovery callback after permanent failure: %s (offline=%s)', async (failure, offline) => {
remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);
const recoveryUrl = 'cindy-media://blobs/recover-me.png';
let enqueueAttempts = 0;
@@ -5630,7 +5635,10 @@ describe('makerChatStore text delta batching', () => {
if (enqueueAttempts === 1) throw new Error('[NOT_CONNECTED] target offline');
throw new Error(failure);
}
- if (channel === 'maker:input:get-projection') return projection(SESSION_ID);
+ if (channel === 'maker:input:get-projection') {
+ if (offline && enqueueAttempts >= 2) throw new Error('[NOT_CONNECTED] target offline');
+ return projection(SESSION_ID);
+ }
throw new Error(`unexpected remote channel: ${channel}`);
});
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 982b999555..2a3b3ca3b3 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -1917,6 +1917,9 @@ function isRemoteAroundClientIdMiss(error: unknown): boolean {
* settling outbox record.
*/
function isTerminalRemoteInputError(error: unknown): boolean {
+ // Local attachment preparation failed before dispatch. A disconnected target cannot
+ // make that delivery ambiguous; restore the draft without a remote reconciliation probe.
+ if (extractIpcError(error)?.code === 'DEVICE_LINK_MEDIA_ACCESS_DENIED') return true;
const formatted = formatRemoteError(error);
return formatted.includes('NOT_FOUND') || formatted.includes('REMOTE_OPTIMISTIC_SESSION_PURGED');
}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index ddc90d3a40..59d1016e16 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -628,10 +628,14 @@ warn/warning 状态检查项、等待或处理中的检查项和 warning issue
控制端上传附件时,仅将源路径一致的文件系统 `open/stat/fstat/read` 的 `EPERM/EACCES`
标记为 `DEVICE_LINK_MEDIA_ACCESS_DENIED`。已知由该源文件打开的句柄,其 `stat/read` 操作
-产生的无路径 `fstat/read` 拒绝在操作边界补齐来源;不覆盖已有路径,不对网络或写入操作补齐。
+产生的无路径 `fstat/read` 拒绝在操作边界按已知来源分类;同样覆盖 OSS 的本地整文件读取
+与流读取,不覆盖已有其他路径,不对网络或写入操作补齐来源。
源文件拒绝不触发直连冷却、连接关闭或 OSS
回退;消息仍整条不派发。网络、远端和其他路径的错误保留原有传输失败语义。
-该错误经现有 IPC 错误封装返回,不携带原始私人路径;Desktop 与 Mobile 的错误展示
+直传助手及 OSS 源读取边界即生成现有 IPC 格式的稳定错误,不保留原始私人路径或 cause,
+非聊天调用方也不会收到原始读取错误。Desktop 的待发消息在该错误下直接恢复草稿,
+不因后续远端查询离线而延迟或重试;该错误发生于派发前,不属于投递结果不确定。
+Desktop 与 Mobile 的错误展示
提供五语“另存到可访问文件夹、移除旧附件、用附件按钮重选”指引。
不新增 channel、relay 字段或权限。生成该错误的是桌面控制端,不要求目标设备升级;
旧客户端遇到历史里的未知错误仍走原通用提示。SSH 的远端文件读取流程不变。