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(chat): revalidate live authority during reply file delivery

ylliuuu660595a7c0dc08
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
index 02c10f1cdd..493b2fa798 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
@@ -586,6 +586,53 @@ describe('Chat Server result delivery and refresh', () => {
});
// #6761: ordinary reply files must reach the completion payload, not remain local links.
+ it.each(['revision', 'revoked', 'requester-left', 'lease', 'temporary'])('refuses reply files when %s changes after the last tool call', async change => {
+ let revoked = false;
+ fixture.handle.mockImplementation((route, _method, body) => {
+ if (route === '/executions/claim') {
+ const next = claimed ? null : { ...execution, requester_id: selfId, access_mode: 'tools' };
+ claimed = true; return { body: { execution: next } };
+ }
+ if (revoked && change === 'temporary' && route.endsWith('/members')) return { status: 503, body: { code: 'UNAVAILABLE' } };
+ if (route.endsWith('/members')) return { body: [
+ { id: botId, kind: 'bot', ownerActorId: selfId, state: 'joined',
+ accessRevision: revoked && change === 'revision' ? 2 : 1, guestAccess: revoked && change === 'revoked' ? 'chat' : 'tools' },
+ { id: selfId, kind: 'human', ownerActorId: selfId, state: revoked && change === 'requester-left' ? 'left' : 'joined' },
+ ] };
+ if (revoked && change === 'lease' && body?.action === 'heartbeat') return { status: 409, body: { code: 'STALE_EXECUTION' } };
+ return response(route);
+ });
+ replyFiles.prepare.mockResolvedValue({ text: 'Report', attachments: [{ id: 'pdf', name: 'report.pdf' }] });
+ await start();
+ await authorizeGroupTool('lane', 'local-bot', 'read-self');
+ revoked = true;
+ const uploads = fixture.upload.mock.calls.length;
+ await service.settleLaneTurn({ ...terminal, resultText: '[Report](./report.pdf)' });
+ expect(fixture.upload.mock.calls.length).toBe(uploads);
+ expect(deliveries()).toHaveLength(0);
+ if (change === 'temporary') revoked = false;
+ await vi.advanceTimersByTimeAsync(16000);
+ expect(fixture.upload.mock.calls.length).toBe(uploads + (change === 'temporary' ? 1 : 0));
+ expect(deliveries()).toHaveLength(change === 'temporary' ? 1 : 0);
+ expect(deps.dispatch).toHaveBeenCalledOnce();
+ });
+
+ async function startFileReply() {
+ const original = fixture.handle.getMockImplementation()!;
+ fixture.handle.mockImplementation((route, method, body) => {
+ const result = original(route, method, body);
+ if (route === '/executions/claim' && result?.body?.execution) {
+ result.body.execution = { ...result.body.execution, access_mode: 'owner', requester_id: selfId };
+ }
+ if (route.endsWith('/members')) return { body: [
+ { id: botId, kind: 'bot', ownerActorId: selfId, state: 'joined', accessRevision: 1, guestAccess: 'tools' },
+ { id: selfId, kind: 'human', ownerActorId: selfId, state: 'joined' },
+ ] };
+ return result;
+ });
+ await start();
+ }
+
it('delivers a PDF reply and retries a lost completion ACK without another upload', async () => {
const file = { id: 'pdf', name: 'report.pdf', category: 'file', mimeType: 'application/pdf', size: 0, path: null, url: null };
replyFiles.prepare.mockResolvedValue({ text: 'Report', attachments: [file] });
@@ -595,7 +642,7 @@ describe('Chat Server result delivery and refresh', () => {
if (body?.action === 'complete' && ++attempts === 1) throw new Error('ECONNRESET');
return response(route);
});
- await start();
+ await startFileReply();
const uploads = fixture.upload.mock.calls.length;
await service.settleLaneTurn({ ...terminal, resultText: '[Report](./report.pdf)' });
expect(deliveries()[0][2].content).toEqual([{ type: 'text', text: 'Report' }, { type: 'media', mediaId: 'pdf', caption: 'report.pdf' }]);
@@ -613,7 +660,7 @@ describe('Chat Server result delivery and refresh', () => {
replyImages.mockResolvedValue({ text: 'Delivered', attachments: images });
const blocks = [...images, pdf].map(file => ({ type: 'media', mediaId: file.id }));
fixture.upload.mockRejectedValueOnce(Object.assign(new Error('MEDIA_UPLOAD_FAILED'), { status: 503 })).mockResolvedValue(blocks);
- await start();
+ await startFileReply();
await service.settleLaneTurn({ ...terminal, resultText: '![image](cindy-media://image) [Report](./report.pdf)' });
expect(deliveries()).toHaveLength(0);
await vi.advanceTimersByTimeAsync(16000);
@@ -627,7 +674,7 @@ describe('Chat Server result delivery and refresh', () => {
it('refuses mixed attachments exceeding the shared twenty-file limit before upload', async () => {
replyFiles.prepare.mockResolvedValue({ text: 'Report', attachments: [{ id: 'pdf' }] });
replyImages.mockResolvedValue({ text: 'Images', attachments: Array.from({ length: 20 }, (_, i) => ({ ...replyImage, id: `image-${i}` })) });
- await start();
+ await startFileReply();
const uploads = fixture.upload.mock.calls.length;
await service.settleLaneTurn({ ...terminal, resultText: 'Images and PDF' });
expect(fixture.upload.mock.calls.length).toBe(uploads);
@@ -637,7 +684,7 @@ describe('Chat Server result delivery and refresh', () => {
it('fails a refused reply file instead of publishing a successful local path', async () => {
replyFiles.prepare.mockRejectedValue(new Error('ATTACHMENT_UNAVAILABLE'));
- await start();
+ await startFileReply();
await service.settleLaneTurn({ ...terminal, resultText: '[Report](./report.pdf)' });
expect(deliveries()).toHaveLength(0);
expect(fixture.handle.mock.calls.filter(([, , body]) => body?.action === 'fail')).toHaveLength(1);
@@ -646,7 +693,7 @@ describe('Chat Server result delivery and refresh', () => {
it.each([400, 413, 415, 422])('reports a file rejected by the media service (%s)', async status => {
replyFiles.prepare.mockResolvedValue({ text: 'Report', attachments: [{ id: 'pdf', name: 'report.pdf' }] });
fixture.upload.mockRejectedValueOnce(new ChatResponseError('FILE_REFUSED', status));
- await start();
+ await startFileReply();
await service.settleLaneTurn({ ...terminal, resultText: '[Report](./report.pdf)' });
expect(deliveries()).toHaveLength(0);
expect(fixture.handle.mock.calls.filter(([, , body]) => body?.action === 'fail')).toHaveLength(1);
@@ -656,7 +703,7 @@ describe('Chat Server result delivery and refresh', () => {
replyFiles.prepare.mockResolvedValue({ text: 'Report', attachments: [{ id: 'pdf', name: 'report.pdf' }] });
fixture.upload.mockRejectedValueOnce(Object.assign(new Error('MEDIA_UPLOAD_FAILED'), { status: 503 }))
.mockResolvedValueOnce([{ type: 'media', mediaId: 'pdf', caption: 'report.pdf' }]);
- await start();
+ await startFileReply();
await service.settleLaneTurn({ ...terminal, resultText: '[Report](./report.pdf)' });
expect(deliveries()).toHaveLength(0);
await vi.advanceTimersByTimeAsync(16000);
@@ -1663,7 +1710,7 @@ describe('Chat Server result delivery and refresh', () => {
});
replyFiles.prepare.mockResolvedValue({ text: 'Report', attachments: [{ id: 'pdf', name: 'report.pdf' }] });
fixture.upload.mockImplementationOnce(async () => kind === 'talk' ? [{ type: 'media', mediaId: 'pdf', caption: 'report.pdf' }] : []);
- await start();
+ if (kind === 'talk') await startFileReply(); else await start();
await service.settleLaneTurn({ ...terminal, resultText: '[Report](./report.pdf)' });
expect(deliveries()[0][2]).not.toHaveProperty('continueDiscussion');
if (kind === 'talk') {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts
index ed238d1c30..1ab9ddf786 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts
@@ -12,6 +12,21 @@ import type { BotGroupAttachment } from '../../../shared/botGroupChat.js';
const attachment: BotGroupAttachment = { id: 'file', name: 'picture.png', category: 'image', mimeType: 'image/png', size: 3, url: 'cindy-media://test', path: null };
describe('chat private media', () => {
+ it.each(['read', 'put', 'seal'])('awaits live authorization before %s', async deniedStage => {
+ let stage = 'read';
+ const readBytes = vi.fn(async () => Buffer.from('private report'));
+ f.fetch.mockReset().mockImplementation(async () => { stage = 'seal'; return new Response('', { status: 200 }); });
+ const api = vi.fn(async route => {
+ if (route.endsWith('/media')) { stage = 'put'; return { id: 'media', uploadUrl: 'https://upload.example.test/signed' }; }
+ return {};
+ }) as unknown as ChatApi;
+ const validate = async () => { await Promise.resolve(); if (stage === deniedStage) throw new Error('REVOKED'); };
+ await expect(createChatMedia(api, () => true).upload('room', 'operation', [{ ...attachment, readBytes }], 'actor', validate)).rejects.toThrow('REVOKED');
+ if (deniedStage === 'read') expect(readBytes).not.toHaveBeenCalled();
+ if (deniedStage !== 'seal') expect(f.fetch).not.toHaveBeenCalled();
+ expect(vi.mocked(api).mock.calls.some(([route]) => route.endsWith('/complete'))).toBe(false);
+ });
+
it.each([undefined, '120'])('preserves PUT 429 Retry-After %s for settlement backoff', async retryAfter => {
f.read.mockResolvedValue({ buffer: Buffer.from('png') });
f.fetch.mockResolvedValue(new Response('', { status: 429, headers: retryAfter ? { 'Retry-After': retryAfter } : {} }));
diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.ts
index 9d8e45de70..68310fb83a 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -1407,6 +1407,31 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
executorId, epoch: run.execution.epoch, action, ...extra,
}, run.execution.bot_id);
}
+ async function validateExecutionAuthority(run: Running): Promise<void> {
+ const execution = run.execution;
+ const assertCurrent = () => {
+ if (!current() || running.get(execution.id) !== run) throw new GroupToolAuthorizationError();
+ };
+ assertCurrent();
+ // Recheck metadata and the execution lease at the tool or file-delivery boundary.
+ // Group administrators cannot grant access to someone else's companion.
+ try {
+ const members = await api<Member[]>(`/conversations/${execution.conversation_id}/members`);
+ assertCurrent();
+ const companion = members.find(m => m.id === execution.bot_id && m.kind === 'bot' && m.state === 'joined');
+ const requester = members.find(m => m.id === execution.requester_id && m.state === 'joined');
+ if (execution.access_mode === 'chat' || !companion || companion.ownerActorId !== selfId || !requester
+ || companion.accessRevision !== execution.access_revision
+ || (execution.access_mode === 'owner' ? requester.ownerActorId !== selfId : companion.guestAccess !== 'tools'))
+ throw new GroupToolAuthorizationError();
+ await updateExecution(run, 'heartbeat');
+ } catch (error) {
+ if (error instanceof ChatResponseError && [401, 403, 404, 409, 410].includes(error.status))
+ throw new GroupToolAuthorizationError();
+ throw error;
+ }
+ assertCurrent();
+ }
// Compatibility cache for servers which do not yet return failure_code.
// The server execution status still owns whether a notice is displayed.
const failureCodes = new Map<string, BotGroupRuntimeFailureCode>();
@@ -1488,8 +1513,22 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
produced.push(...pending.reply.attachments, ...pending.fileReply.attachments);
if (produced.length > BOT_GROUP_ATTACHMENTS_MAX) throw new Error('ATTACHMENT_UNAVAILABLE');
}
+ const validateUpload = async () => {
+ assertCurrent();
+ if (pending.fileReply?.attachments.length) {
+ try { await validateExecutionAuthority(run); }
+ catch (error) {
+ // Definitive revocation ends delivery; transport failures retain
+ // the same result for retry without running the Agent again.
+ if (error instanceof GroupToolAuthorizationError) throw new ChatResponseError('PERMISSION_DENIED', 403);
+ throw error;
+ }
+ }
+ assertCurrent();
+ };
+ if (ordinaryReply) await validateUpload();
files = await media.upload(run.execution.conversation_id, `step:${run.execution.id}:${run.execution.epoch}`,
- produced, run.execution.bot_id, ordinaryReply ? assertCurrent : undefined);
+ produced, run.execution.bot_id, ordinaryReply ? validateUpload : undefined);
assertCurrent();
}
} catch (error) {
@@ -1664,24 +1703,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
botId: bot.id, mode: execution.access_mode,
sourceGroup: { groupId: s.room.id, name: s.room.name },
isCurrent: () => current() && running.get(execution.id) === run && !run.settlement,
- validate: async () => {
- // Recheck metadata and the execution lease at the actual tool boundary.
- // Group administrators cannot grant access to someone else's companion.
- try {
- const members = await api<Member[]>(`/conversations/${s.room.id}/members`);
- const companion = members.find(m => m.id === execution.bot_id && m.kind === 'bot' && m.state === 'joined');
- const requester = members.find(m => m.id === execution.requester_id && m.state === 'joined');
- if (!companion || companion.ownerActorId !== selfId || !requester
- || companion.accessRevision !== execution.access_revision
- || (execution.access_mode === 'owner' ? requester.ownerActorId !== selfId : companion.guestAccess !== 'tools'))
- throw new GroupToolAuthorizationError();
- await updateExecution(run, 'heartbeat');
- } catch (error) {
- if (error instanceof ChatResponseError && [401, 403, 404, 409, 410].includes(error.status))
- throw new GroupToolAuthorizationError();
- throw error;
- }
- },
+ validate: () => validateExecutionAuthority(run),
});
if (run.plan && run.workspace?.ownerSessionId) {
const settings = workspaces().read(s.room.id)!;
diff --git a/apps/desktop/src/main/maker-ipc/chatServerMedia.ts b/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
index 0dbaa2e1e4..000e53aee3 100644
--- a/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
@@ -36,8 +36,8 @@ export function createChatMedia(api: ChatApi, current: () => boolean, log?: { wa
* blocks in the files' order. Every file settles before a failure is reported, so no
* upload keeps running after the send has given up; the first failure in order wins.
*/
- async upload(roomId: string, source: string, attachments: ChatUploadAttachment[], actorId: string, assertCurrent?: () => void): Promise<ChatContentBlock[]> {
- const checkUpload = () => { check(); assertCurrent?.(); };
+ async upload(roomId: string, source: string, attachments: ChatUploadAttachment[], actorId: string, assertCurrent?: () => void | Promise<void>): Promise<ChatContentBlock[]> {
+ const checkUpload = async () => { check(); await assertCurrent?.(); check(); };
const results: Array<PromiseSettledResult<ChatContentBlock>> = new Array(attachments.length);
let next = 0;
const worker = async () => {
@@ -55,17 +55,17 @@ export function createChatMedia(api: ChatApi, current: () => boolean, log?: { wa
async function uploadOne(attachment: ChatUploadAttachment): Promise<ChatContentBlock> {
let stage = 'read';
const started = Date.now();
- const checkFile = () => { checkUpload(); attachment.assertCurrent?.(); };
+ const checkFile = async () => { await checkUpload(); attachment.assertCurrent?.(); };
try {
- checkFile();
+ await checkFile();
if (attachment.size > MAX_SIZE) throw new Error('ATTACHMENT_TOO_LARGE');
if (attachment.path && !attachment.readBytes) {
- const stat = await fs.stat(attachment.path); checkFile();
+ const stat = await fs.stat(attachment.path); await checkFile();
if (!stat.isFile() || stat.size > MAX_SIZE) throw new Error('ATTACHMENT_TOO_LARGE');
}
const bytes = attachment.readBytes ? await attachment.readBytes() : attachment.url?.startsWith('cindy-media://') ? (await readMedia(attachment.url)).buffer
: attachment.path ? await fs.readFile(attachment.path) : null;
- checkFile();
+ await checkFile();
if (!bytes || !bytes.length || bytes.length > MAX_SIZE) throw new Error('ATTACHMENT_UNAVAILABLE');
const key = createHash('sha256').update(source).update(attachment.id).update(bytes).digest('hex');
// Expired abandoned uploads must get a new prepare receipt, but a successful
@@ -82,13 +82,13 @@ export function createChatMedia(api: ChatApi, current: () => boolean, log?: { wa
operationId: `media:${key}:${randomUUID()}`, name: attachment.name, type: attachment.mimeType, size: bytes.length,
}, actorId);
}
- checkFile();
+ await checkFile();
stage = 'upload';
const response = await net.fetch(signedUrl(upload.uploadUrl), { method: 'PUT', redirect: 'error',
headers: { 'Content-Type': attachment.mimeType }, body: new Uint8Array(bytes), signal: AbortSignal.timeout(60000) });
if (!response.ok) throw Object.assign(new Error('MEDIA_UPLOAD_FAILED'), { status: response.status,
...(response.status === 429 ? { retryAt: retryAfterDeadline(response) } : {}) });
- checkFile();
+ await checkFile();
stage = 'complete';
await api(`/conversations/${roomId}/media/${upload.id}/complete`, 'POST', { operationId: `seal:${upload.id}` }, actorId);
return { type: 'media', mediaId: upload.id, caption: attachment.name };
diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.md
index af7f7b506d..3a014544b9 100644
--- a/docs/product-rules/bot-group-chat.md
+++ b/docs/product-rules/bot-group-chat.md
@@ -460,6 +460,7 @@ Chat Server 声明 `capabilities.groupSingleSpeaker: 1` 时,服务器群按下
普通回复中明确展示的当前任务生成图片作为群附件交付,其他有权限的成员可以查看和下载;图片交付失败不降级为丢图的纯文字成功回复。
有文件访问授权的伙伴普通回复(含讨论队列)中,明确链接的当前任务工作目录内 PDF 等文件作为群附件交付;交付失败明确报错,不把本机路径当作成功交付,也不自动收集目录内其他文件。
+文件交付在读取、上传和封存前复验群成员、伙伴归属、授权版本及执行租约;工具调用结束时的授权不能替代交付时的授权。明确撤权则停止交付,临时校验失败保留同一执行结果重试,不重新运行 Agent。
Chris 已明确扩展到多人各带伙伴,并选择「主人按群预先授权」。正式群聊统一使用 Chat Server;已有本地群及消息自动迁移,不保留并行本地群入口。Agent 工作目录与私人资料仍留在执行端,外部成员的访问继续受下述授权边界约束。服务端群历史与 Agent 本机/云端执行分离,人和伙伴共用成员、群角色和消息合同,国内与国际账号可以互邀。