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(im): 隔离远程后台结果的本机附件解析

Dash5dc9b662e205
diff --git a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
index 7a99ea320b..e5b841b861 100644
--- a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
+++ b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
@@ -3290,6 +3290,38 @@ describe('watchContinuation: 观察桌面端续跑并回流', () => {
for (let i = 0; i < times; i++) await Promise.resolve();
}
+ it.each([false, true])('continuation attachments stay in their runtime (remote=%s)', async (remote) => {
+ const workDir = process.cwd().replaceAll('\\', '/');
+ fakeMaker.getSession.mockReturnValueOnce({
+ ...makeManualSession('sess-live'),
+ workDir,
+ ...(remote ? { remoteHostId: 'ssh-host' } : {}),
+ });
+ const onEnd = vi.fn();
+ const runner = createMakerHookSessionRunner({ log });
+ const { req } = watchReq({ onEnd });
+ runner.watchContinuation!(req as never);
+ const cb = h.eventCbs.get('sess-live')!;
+ const media = `cindy-media://blobs/${'a'.repeat(64)}.png`;
+ const text = `结果 [文件](xdt-file://${workDir}/package.json) ![图](xdt-image://chart.png) ![媒体](${media})`;
+ cb({ type: 'tool_result_full', data: { fullText: `![工具图](xdt-image://tool.png) ![工具媒体](${media})` } });
+ cb({ type: 'text', data: { text, isFinal: true } });
+ cb({ type: 'done', data: null });
+ await vi.waitFor(() => expect(onEnd).toHaveBeenCalledTimes(1));
+ const outcome = onEnd.mock.calls[0]![0];
+ expect(outcome.status).toBe('ok');
+ if (remote) {
+ expect(resolveXdtImage).not.toHaveBeenCalled();
+ expect(cindyMock.resolveSafe).not.toHaveBeenCalled();
+ expect(outcome.attachments).toBeUndefined();
+ expect(outcome.finalText).toBe(text);
+ } else {
+ expect(resolveXdtImage).toHaveBeenCalled();
+ expect(cindyMock.resolveSafe).toHaveBeenCalled();
+ expect(outcome.attachments?.map((a: { name: string }) => a.name)).toContain('package.json');
+ }
+ });
+
it.each([false, true])('isolates child events before root completion (isFinal=%s)', async (isFinal) => {
const session = makeManualSession('sess-subagent-output');
const onProgress = vi.fn();
diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.ts
index 11a8c8f6e2..004606c077 100644
--- a/apps/desktop/src/main/hook-control/session-runner.ts
+++ b/apps/desktop/src/main/hook-control/session-runner.ts
@@ -457,6 +457,9 @@ async function collectOutboundForFinalText(
// never forward private Web citation delimiters to an external channel.
const publicText = stripInternalWebCitations(texts.publicText);
const wholeTurn = stripInternalWebCitations(texts.wholeTurn);
+ // Remote runtimes do not grant access to this host's files or media cache.
+ // The attachment collector's managed-image path is independent of file roots.
+ if (allowedFileRoots.length === 0) return { finalText: publicText };
if (!hasOutboundRefs(wholeTurn) && extraImageAbsPaths.length === 0) {
return { finalText: publicText };
}
@@ -967,6 +970,7 @@ export function createMakerHookSessionRunner(deps: {
// 就会让"续跑接回渠道"那条路径静默落后于本路径。
// tool_result 旁路收集的出站图片 absPath(收口时随 turn.end 附件外发)
const extraImageAbsPaths: string[] = [];
+ const allowedFileRoots = session.remoteHostId ? [] : [workingDir];
const useTelegramProgressParity = req.source?.im === 'telegram';
const observer = observeHookTurn(session, {
onTurnTerminal: req.onTurnTerminal,
@@ -976,7 +980,9 @@ export function createMakerHookSessionRunner(deps: {
...(useTelegramProgressParity
? { progressBodyMode: 'whole' as const, flushProgressOnDone: true }
: {}),
- onToolResult: (fullText) => collectOutboundImages(fullText, extraImageAbsPaths, log),
+ onToolResult: (fullText) => {
+ if (allowedFileRoots.length > 0) collectOutboundImages(fullText, extraImageAbsPaths, log);
+ },
onSilentStopSettled,
log,
});
@@ -1429,7 +1435,7 @@ export function createMakerHookSessionRunner(deps: {
const collected = await collectOutboundForFinalText(
turnTextsFor(observer),
extraImageAbsPaths,
- [workingDir],
+ allowedFileRoots,
log,
);
let finalText = collected.finalText;
@@ -1490,6 +1496,7 @@ function beginContinuationWatch(
}
const startedAt = Date.now();
const extraImageAbsPaths: string[] = [];
+ const allowedFileRoots = session.remoteHostId ? [] : [session.workDir];
let claimed = false;
let settled = false;
const useTelegramProgressParity = req.source?.im === 'telegram';
@@ -1503,7 +1510,9 @@ function beginContinuationWatch(
...(useTelegramProgressParity
? { progressBodyMode: 'whole' as const, flushProgressOnDone: true }
: {}),
- onToolResult: (fullText) => collectOutboundImages(fullText, extraImageAbsPaths, log),
+ onToolResult: (fullText) => {
+ if (allowedFileRoots.length > 0) collectOutboundImages(fullText, extraImageAbsPaths, log);
+ },
onSilentStopSettled,
log,
});
@@ -1545,7 +1554,7 @@ function beginContinuationWatch(
const collected = await collectOutboundForFinalText(
turnTextsFor(observer),
extraImageAbsPaths,
- [session.workDir],
+ allowedFileRoots,
log,
);
req.onEnd({
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts
index cbf5e81c3f..3a720bd1b4 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts
@@ -662,6 +662,36 @@ describe('turnRunner 渠道任务后台结果回传', () => {
expect(mocks.slackIm.startStreamingText).not.toHaveBeenCalled();
});
+ it.each(['rich-card', 'chunked-text'] as const)('%s 远端正文引用只回传标签,不交给渠道解析本机附件', async (kind) => {
+ const stub = streamingHandleStub();
+ mocks.slackIm.startStreamingText.mockResolvedValue(stub);
+ if (kind === 'chunked-text') {
+ runner = createTurnRunner({ ...fakeAdapter, output: {
+ kind, im: fakeAdapter.im, commitFinal: vi.fn(async () => undefined),
+ } }, fakeRepo, fakeCards);
+ }
+ const h = makeSessionHarness('remote-markdown');
+ Object.assign(h.session, { remoteHostId: 'ssh-host' });
+ runner.attachSessionOutput(h.session, 'U1');
+ h.emit({ type: 'text', data: {
+ text: '结果 ![图](xdt-image://remote.png) ![媒体](cindy-media://blobs/remote.png) [文件](xdt-file:///repo/report.txt)',
+ isFinal: true,
+ } });
+ h.emit({ type: 'done', data: {} });
+ if (kind === 'rich-card') {
+ await vi.waitFor(() => expect(stub.finalize).toHaveBeenCalledWith('结果 图 媒体 文件'));
+ for (const [text] of stub.replace.mock.calls) {
+ expect(text).not.toMatch(/(?:xdt-image|xdt-file|cindy-media):/);
+ }
+ } else {
+ await vi.waitFor(() => expect(mocks.slackIm.sendMarkdownText).toHaveBeenCalledWith(
+ 'U1', '结果 图 媒体 文件', { threadTs: undefined },
+ ));
+ }
+ expect(mocks.resolveXdtImageUrl).not.toHaveBeenCalled();
+ expect(mocks.slackIm.sendFile).not.toHaveBeenCalled();
+ });
+
it('重启后仅恢复输出监听,不新建会话;重复恢复不会重复回复', async () => {
const h = makeSessionHarness('cold-session');
const stub = streamingHandleStub();
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index 9012e372f4..11b98294e2 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -97,6 +97,7 @@ import type {
InteractiveCardSpec,
StreamingTextHandle,
} from '@cindy/im';
+import { transformXdtRefs } from '@cindy/im';
import type { AutoReviewUserReferences } from '@cindy/maker-shared/auto-review-intent';
import { persistUserMessage } from '../messagePersistence';
@@ -2641,15 +2642,20 @@ export function createTurnRunner(
// composeStreamingView,避免回归 #118。
/** 转播卡正文:运行中 = 头 + 步骤时间线 + 正文;收口 = 头 + 正文(去步骤)。 */
- function composeTranspondView(t: ScheduledTranspond, final: boolean): string {
+ function composeTranspondView(state: SessionState, t: ScheduledTranspond, final: boolean): string {
const header = t.header;
+ // Rich transports resolve managed refs themselves. A remote session's refs
+ // must stay text, never reach those host-local file/media resolvers.
+ const body = state.makerSession.remoteHostId
+ ? transformXdtRefs(t.buffer, { image: (ref) => ref.alt, file: (ref) => ref.alt })
+ : t.buffer;
if (final) {
- return [header, t.buffer].filter(Boolean).join('\n\n');
+ return [header, body].filter(Boolean).join('\n\n');
}
const act = renderActivity(t.activity, Date.now());
const parts: string[] = header ? [header] : [];
if (act) parts.push(act);
- if (t.buffer) parts.push(t.buffer);
+ if (body) parts.push(body);
// 自动任务沿用标题紧接步骤的排版,其它轮次只显示步骤和正文。
if (header && parts.length > 1) return `${header}\n${parts.slice(1).join('\n\n')}`;
return parts.join('\n\n');
@@ -2685,7 +2691,7 @@ export function createTurnRunner(
if (!t || !richIm) return;
void ensureTranspondHandle(state, t)
.then((h) => {
- if (state.scheduledTranspond === t) h.replace(composeTranspondView(t, false));
+ if (state.scheduledTranspond === t) h.replace(composeTranspondView(state, t, false));
})
.catch((err) => log.warn('transpond refresh failed (non-fatal)', err));
}
@@ -2752,7 +2758,7 @@ export function createTurnRunner(
// 低频 ticker 刷新耗时(只刷已存在的卡)。
if (richIm && !t.activityTicker) {
t.activityTicker = setInterval(() => {
- t.streamingHandle?.replace(composeTranspondView(t, false));
+ t.streamingHandle?.replace(composeTranspondView(state, t, false));
}, ACTIVITY_TICK_MS);
}
refreshTranspondCard(state);
@@ -2785,7 +2791,7 @@ export function createTurnRunner(
{
const notice = turnRetryNotice(event.data, { channel });
if (notice !== null && setActivityNotice(t.activity, notice)) {
- t.streamingHandle?.replace(composeTranspondView(t, false));
+ t.streamingHandle?.replace(composeTranspondView(state, t, false));
}
}
return;
@@ -2821,7 +2827,7 @@ export function createTurnRunner(
}
}
if (sessionStates.get(state.makerSession.id) !== state) return;
- const base = composeTranspondView(t, true);
+ const base = composeTranspondView(state, t, true);
const body = errMsg ? [base, ui.agent.runtimeError(errMsg)].filter(Boolean).join('\n\n') : base;
if (output.kind === 'chunked-text') {
// 微信等文本渠道由适配器解析当前账号下该聊天最近的有效回复上下文。
diff --git a/docs/product-rules/telegram-bot-parity.md b/docs/product-rules/telegram-bot-parity.md
index 62808dea4b..1030e810d1 100644
--- a/docs/product-rules/telegram-bot-parity.md
+++ b/docs/product-rules/telegram-bot-parity.md
@@ -251,7 +251,8 @@ hook 侧既有的逐轮 `[渠道说明]`,两者措辞不同但都向模型说
其它来源直接显示回复正文,目的地沿用该任务原聊天和话题。正常 IM 入站轮次仍只发送一次;
子代理和旧轮次的后台事件不转播。纯文本渠道通过适配器使用现有有效聊天上下文发送最终结果。
工具结果中的托管图片沿用正常 IM 轮次的解析与去重规则,即使最终正文没有重复引用也会回传;
-SSH 任务不把远端路径当作本地文件上传。
+SSH 任务不把远端路径或托管媒体引用当作本地文件上传;个人渠道的正文引用仅保留标签,
+官方渠道在收集工具图片和最终附件之前排除远程执行实例。
临时回复通知不建立普通任务的持续转播;`/ctr` 接管任务仍只转播 scheduler 输出。
每轮执行前从当前账号库恢复输出监听,核对 bot 身份和任务状态,因此重启后无需先从 IM 发一条消息。