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(mobile): filter embedded URLs throughout source literals

DavidShene466f8d51397
diff --git a/apps/desktop/src/main/device-link/__tests__/mobileToolProjection.test.ts b/apps/desktop/src/main/device-link/__tests__/mobileToolProjection.test.ts
index 9775ae725f..8093f8e08d 100644
--- a/apps/desktop/src/main/device-link/__tests__/mobileToolProjection.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/mobileToolProjection.test.ts
@@ -14,6 +14,19 @@ const tool = (toolName = 'Bash', input: unknown = { command: 'echo hello ' + 'x'
});
describe('mobile tool projection', () => {
+ it('keeps URLs inside long source literals as text even when the closing quote is truncated', () => {
+ const source = 'const message = "Open xdt-file:///tmp/fixture.pdf '
+ + 'source text '.repeat(1500) + '";';
+ const row = { ...tool('Read'), role: 'tool_result', content: source };
+ const live = projectMobileToolPush('local-db:messages:created', { message: row }) as { message: typeof row };
+ const history = projectMobileMessagePage([row], {}) as typeof row[];
+ expect(live.message).toEqual(history[0]);
+ expect(live.message.content).toContain('const message = "Open');
+ expect(live.message.content).toContain('[remote content truncated');
+ expect(live.message.content).not.toContain('_xdt_model_files');
+ expect(extractPayloadToolResultFiles(live.message.content)).toEqual([]);
+ expect(row.content).toBe(source);
+ });
it('keeps large source output as text instead of promoting fixtures to file declarations', () => {
const source = "const urls = ['xdt-file://open?path=%2Ftmp%2Ffixture.pdf', 'xdt-file:///tmp/example.html'];\n"
+ "const path = enabled ? 'xdt-file:///tmp/conditional.pdf' : undefined\n"
diff --git a/apps/mobile/src/__tests__/pluginResultRendering.test.ts b/apps/mobile/src/__tests__/pluginResultRendering.test.ts
index b3816fd8d5..805896ab24 100644
--- a/apps/mobile/src/__tests__/pluginResultRendering.test.ts
+++ b/apps/mobile/src/__tests__/pluginResultRendering.test.ts
@@ -11,6 +11,18 @@ function messages(content: unknown): RemoteMessage[] {
];
}
describe('plugin results are visible outside collapsed tool details', () => {
+ it.each([true, false])('keeps URLs later in source literals out of file cards (streaming=%s)', (isSessionStreaming) => {
+ for (const source of [
+ 'const message = "Open xdt-file:///tmp/fixture.pdf";',
+ 'const message = "Open xdt-file:///tmp/fixture.pdf\n[remote content truncated]',
+ ]) {
+ const rows = messages({ text: source });
+ const normalized = normalizeRemoteMessages(rows).find((row) => row.kind === 'tool');
+ expect(normalized?.files).toEqual([]);
+ expect(normalized?.secondaryBody).toBe(JSON.stringify({ text: source }));
+ expect(buildMobileMessageRenderItems(rows, { isSessionStreaming }).some((row) => row.type === 'tool_media')).toBe(false);
+ }
+ });
it.each([true, false])('does not render source fixtures as delivered files (streaming=%s)', (isSessionStreaming) => {
const source = "const urls = ['xdt-file://open?path=%2Ftmp%2Ffixture.pdf', 'xdt-file:///tmp/example.html'];\n"
+ "const path = enabled ? 'xdt-file:///tmp/conditional.pdf' : undefined\n"
diff --git a/packages/maker-shared/src/__tests__/pluginResults.test.ts b/packages/maker-shared/src/__tests__/pluginResults.test.ts
index 4f6ffd8133..5ff542d1b5 100644
--- a/packages/maker-shared/src/__tests__/pluginResults.test.ts
+++ b/packages/maker-shared/src/__tests__/pluginResults.test.ts
@@ -4,6 +4,44 @@ import { hasVisibleHistoryResult } from '../historyViewProjection.js';
const blob = (ext: string) => `cindy-media://blobs/${'a'.repeat(64)}.${ext}`;
describe('portable plugin results', () => {
+ it.each(["'", '"', String.fromCharCode(96)])('ignores URLs anywhere inside source literals quoted with %s', (quote) => {
+ const url = 'xdt-file:///tmp/fixture.pdf';
+ const body = 'Open ' + url + ' or [report](xdt-file://open?path=%2Ftmp%2Fother.pdf)';
+ const literal = quote + body + quote;
+ for (const source of [
+ 'const message = ' + literal,
+ 'return ' + literal,
+ 'notify(' + literal + ')',
+ 'const messages = [' + literal + ', /* next */ ' + literal + ']',
+ 'const message = { text: ' + literal + ' }',
+ 'const message = enabled ? ' + literal + ' : undefined',
+ 'const message = fallback || ' + literal,
+ 'const message = ' + quote + 'Open \\' + quote + 'report\\' + quote + ' at ' + url + quote,
+ ]) {
+ expect(files(source), source).toEqual([]);
+ expect(files(JSON.stringify({ content: [{ type: 'text', text: source }] })), source).toEqual([]);
+ expect(files(source + '\nSaved [report](' + url + ')'), source).toEqual([{ url, title: 'fixture.pdf' }]);
+ expect(files(JSON.stringify({ text: source, _xdt_model_files: [{ url, name: 'Report' }] }))).toEqual([{ url, title: 'Report' }]);
+ }
+ });
+ it('keeps URLs in quoted prose and does not inherit source context from a previous statement', () => {
+ const a = 'xdt-file:///tmp/first.pdf';
+ const b = 'xdt-file:///tmp/second.pdf';
+ const expected = [{ url: a, title: 'first.pdf' }, { url: b, title: 'second.pdf' }];
+ for (const quote of ["'", '"', String.fromCharCode(96)]) {
+ const prose = 'Saved ' + quote + 'first [file](' + a + ')' + quote + ', ' + quote + 'second [file](' + b + ')' + quote;
+ expect(files(prose)).toEqual(expected);
+ expect(files('const label = "example";\n' + prose)).toEqual(expected);
+ expect(files(JSON.stringify({ note: prose }))).toEqual(expected);
+ }
+ expect(files('Saved "Open ' + a + '", "Open ' + b + '"')).toEqual(expected);
+ });
+ it('filters multiple URLs in a multiline source template', () => {
+ const source = 'const message = ' + String.fromCharCode(96)
+ + 'Open\nxdt-file:///tmp/first.pdf\nand xdt-file:///tmp/second.pdf\n'
+ + String.fromCharCode(96);
+ expect(files(source)).toEqual([]);
+ });
it('preserves the legacy direct-path punctuation alphabet in real references', () => {
// #4692 accepted these filename characters. Source filtering must not
// redefine the URL alphabet and silently point to a different file.
diff --git a/packages/maker-shared/src/payloadSummary.ts b/packages/maker-shared/src/payloadSummary.ts
index 00988f8afc..5e920abd95 100644
--- a/packages/maker-shared/src/payloadSummary.ts
+++ b/packages/maker-shared/src/payloadSummary.ts
@@ -488,11 +488,13 @@ function absoluteToolFilePath(url: string): string | null {
}
}
+const SOURCE_CONTEXT_TOKEN_RE = /"(?:\\[\s\S]|[^"\\])*(?:"|$)|'(?:\\[\s\S]|[^'\\])*(?:'|$)|`(?:\\[\s\S]|[^`\\])*(?:`|$)|\/\*[\s\S]*?\*\/|(?<![:/])\/\/[^\r\n]*/g;
+
function withoutSourceComments(text: string): string {
- // Skip complete string literals before recognizing comments, so URL schemes
+ // Skip string literals before recognizing comments, so URL schemes
// and comment-like file names inside strings remain part of the context.
return text.replace(
- /"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|`(?:\\[\s\S]|[^`\\])*`|\/\*[\s\S]*?\*\/|(?<![:/])\/\/[^\r\n]*/g,
+ SOURCE_CONTEXT_TOKEN_RE,
(token) => token.startsWith('/') ? token.replace(/[^\r\n]/g, ' ') : token,
);
}
@@ -503,7 +505,7 @@ function looksLikeQuotedSourceLiteral(text: string, index: number, end: number):
if (before !== '`' && before !== '\'' && before !== '"') return false;
// Quotes alone also occur in prose and inline Markdown. Require source syntax
// around the literal (assignment, collection entry, argument or conditional).
- const prefix = withoutSourceComments(text.slice(0, index - 1)).trimEnd();
+ const prefix = text.slice(0, index - 1).trimEnd();
return /(?:[=\[(,?]|&&|\|\||\breturn)$/.test(prefix)
// A colon alone is also a prose label ("File:"). Require a preceding
// conditional, allowing indented continuation lines but not new prose.
@@ -512,6 +514,26 @@ function looksLikeQuotedSourceLiteral(text: string, index: number, end: number):
|| (after === before && /^\s*;/.test(text.slice(end + 1)));
}
+function* quotedSourceRanges(text: string): Generator<{ start: number; end: number }> {
+ // Classify the whole literal, not only URLs touching its opening quote.
+ // Comments and escaped quotes use the same token boundaries as source context.
+ let previous: { end: number; source: boolean } | undefined;
+ for (const match of text.matchAll(SOURCE_CONTEXT_TOKEN_RE)) {
+ if (match[0].startsWith('/')) continue;
+ const start = match.index;
+ // Tool output may end mid-literal after the Host applies its byte budget.
+ const closed = match[0].length > 1 && match[0].endsWith(match[0][0]);
+ const end = start + match[0].length - (closed ? 1 : 0);
+ const continuesList = previous
+ && withoutSourceComments(text.slice(previous.end + 1, start)).trim() === ',';
+ const source: boolean = previous && continuesList
+ ? previous.source
+ : looksLikeQuotedSourceLiteral(text, start + 1, end);
+ if (source) yield { start, end };
+ previous = { end, source };
+ }
+}
+
/** Existing 3D attachments and managed file references retain a usable file entry on Mobile. */
export function extractPayloadToolResultFiles(text: string): PayloadToolFile[] {
const parsed = parseToolResultPayload(text);
@@ -543,10 +565,18 @@ export function extractPayloadToolResultFiles(text: string): PayloadToolFile[] {
while (pending.length) {
const value = pending.pop();
if (typeof value === 'string') {
+ if (!value.includes('xdt-file://')) continue;
const urlPattern = new RegExp(TOOL_FILE_URL_RE);
+ // Strip comments once; repeatedly lexing the prefix of every literal is
+ // quadratic for large source-file output. Offsets stay in the original text.
+ const sourceContext = withoutSourceComments(value);
+ const sourceRanges = quotedSourceRanges(sourceContext);
+ let range = sourceRanges.next();
let previous: { end: number; source: boolean } | undefined;
for (let match; (match = urlPattern.exec(value));) {
const start = match.index;
+ while (!range.done && range.value.end < start) range = sourceRanges.next();
+ if (!range.done && range.value.start < start && start < range.value.end) continue;
// Quotes/backticks may be filename characters. Treat one as a delimiter
// only when it matches the opening wrapper around this reference.
const quote = value[start - 1];
@@ -560,7 +590,7 @@ export function extractPayloadToolResultFiles(text: string): PayloadToolFile[] {
&& withoutSourceComments(value.slice(previous.end + 1, start - 1)).trim() === ',';
const source = previous && continuesList
? previous.source
- : looksLikeQuotedSourceLiteral(value, start, start + url.length);
+ : looksLikeQuotedSourceLiteral(sourceContext, start, start + url.length);
if (!source) add(url);
previous = { end: start + url.length, source };
}