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(agent-island): 按可见文本限制流式摘要长度

Dash85a0301eb977
diff --git a/apps/desktop/src/main/agent-island/__tests__/activityTextStream.test.ts b/apps/desktop/src/main/agent-island/__tests__/activityTextStream.test.ts
index 474c9484fc..598eb503d0 100644
--- a/apps/desktop/src/main/agent-island/__tests__/activityTextStream.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/activityTextStream.test.ts
@@ -96,6 +96,27 @@ describe('Agent Island activity text stream', () => {
expect(normalizeActivityText('`foo_bar **literal**`')).toBe('foo_bar **literal**');
});
+ // #7566: source-only limits froze a link destination before its closing
+ // delimiter and discarded the visible result. Unit, including tiny deltas.
+ it.each(['[文档](', '![图示](', '[文档](<'])('budgets visible text after a long streamed destination (%s)', opening => {
+ const parse = vi.spyOn(previewText, 'streamingMarkdownPreviewText');
+ const stream = createActivityTextStreamState();
+ const label = opening.startsWith('!') ? '图示' : '文档';
+ try {
+ expect(appendActivityTextStream(stream, opening)).toBe(label);
+ const calls = parse.mock.calls.length;
+ for (const delta of ['https://example.com/', ...'x'.repeat(1_000)]) {
+ expect(appendActivityTextStream(stream, delta)).toBe(label);
+ }
+ expect(parse.mock.calls.length).toBe(calls);
+ expect(appendActivityTextStream(stream, '(nested)')).toBe(label);
+ expect(appendActivityTextStream(stream, (opening.endsWith('<') ? '>)' : ')') + ' 测试已通过'))
+ .toBe(label + ' 测试已通过');
+ } finally {
+ parse.mockRestore();
+ }
+ });
+
it('hides irrecoverable rich protocol from old remote summaries', () => {
const collapsed = richAnswer.replace(/\s+/g, ' ');
expect(normalizeRemoteActivityText(collapsed)).toBe('');
@@ -117,6 +138,11 @@ describe('Agent Island activity text stream', () => {
expect(normalizeActivityText(example)).toBe(richAnswer.replace(/\s+/g, ' '));
const code = '```json\n{"status":"ok"}\n```';
expect(normalizeActivityText(code)).toBe('{"status":"ok"}');
+ // A destination-shaped string inside code is literal, even when it has no `)`.
+ for (const quoted of ['`[文档](https://example.com/unfinished`', '```text\n[文档](https://example.com/unfinished\n```']) {
+ const stream = createActivityTextStreamState();
+ expect(appendActivityTextStream(stream, quoted)).toBe('[文档](https://example.com/unfinished');
+ }
});
// #7566 review: transport recovery must not strip a valid local code example.
@@ -130,7 +156,7 @@ describe('Agent Island activity text stream', () => {
// Deterministic work assertion plus visible result; no wall-clock timing.
it.each(['', '{"content":"'])('does not parse an unchanged formatted streaming prefix again (%s)', prefix => {
- const parse = vi.spyOn(previewText, 'markdownPreviewText');
+ const parse = vi.spyOn(previewText, 'streamingMarkdownPreviewText');
try {
const stream = createActivityTextStreamState();
const visible = appendActivityTextStream(stream, prefix + '**完成** ' + 'x'.repeat(280));
@@ -169,13 +195,15 @@ describe('Agent Island activity text stream', () => {
expect(appendActivityTextStream(stream, inline)).toBe(normalizeActivityText(inline));
});
- it('hides a truncated rich operation until the full final text is available', () => {
+ it('hides an incomplete rich operation and projects it once the rest arrives', () => {
const source = '```cindy-ui\n'
+ JSON.stringify({ version: 1, seq: 1, op: 'create', id: 'answer', kind: 'text',
props: { style: { padding: 12 }, text: '检查完成。'.repeat(100) } }) + '\n```';
const stream = createActivityTextStreamState();
- expect(appendActivityTextStream(stream, source)).toBe('');
- expect(normalizeActivityText(source)).toBe('检查完成。'.repeat(100).slice(0, AGENT_ISLAND_ACTIVITY_TEXT_MAX_LENGTH));
+ expect(appendActivityTextStream(stream, source.slice(0, 400))).toBe('');
+ const expected = '检查完成。'.repeat(100).slice(0, AGENT_ISLAND_ACTIVITY_TEXT_MAX_LENGTH);
+ expect(appendActivityTextStream(stream, source.slice(400))).toBe(expected);
+ expect(normalizeActivityText(source)).toBe(expected);
});
it('preserves plain text across whitespace, emoji, and the 280-code-unit boundary', () => {
diff --git a/apps/desktop/src/main/agent-island/__tests__/state.test.ts b/apps/desktop/src/main/agent-island/__tests__/state.test.ts
index 3f521712e9..28bbe896fe 100644
--- a/apps/desktop/src/main/agent-island/__tests__/state.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/state.test.ts
@@ -1034,6 +1034,23 @@ describe('Agent Island display state', () => {
expect(user?.compactDetail).toBe('foo_bar **literal**');
});
+ // #7566 review, unit: a long destination must not consume the visible budget;
+ // cover both terminal entrances without relying on an independent final text.
+ it.each(['done', 'status'] as const)('completes a delta-only long-link reply through %s', terminal => {
+ const state = createAgentIslandState();
+ const meta = { sessionId: 'delta-link' };
+ applyAgentIslandEvent(state, meta, statusEvent(true, 'Generating...'), 1_000);
+ for (const delta of ['[文档](', 'https://example.com/' + 'x'.repeat(500), ') 测试已通过']) {
+ applyAgentIslandEvent(state, meta, textDeltaEvent(delta), 1_100);
+ }
+ expect(buildAgentIslandDisplayState(state, 1_200).sessions[0]?.messagePreview?.text)
+ .toBe('文档 测试已通过');
+ applyAgentIslandEvent(state, meta, terminal === 'done' ? doneEvent() : statusEvent(false, 'Done'), 1_300);
+ const completed = buildAgentIslandDisplayState(state, 1_400).sessions[0];
+ expect(completed).toMatchObject({ phase: 'completed', compactDetail: '文档 测试已通过' });
+ expect(completed?.activityLines.at(-1)?.text).toBe('文档 测试已通过');
+ });
+
// Review regression: a removed/emptied rich node must retract this message's
// streamed line from both the activity log and active/queued preview (unit tier).
it.each([
diff --git a/apps/desktop/src/main/agent-island/activityTextStream.ts b/apps/desktop/src/main/agent-island/activityTextStream.ts
index 9ae8c4eaef..0d6b210cdf 100644
--- a/apps/desktop/src/main/agent-island/activityTextStream.ts
+++ b/apps/desktop/src/main/agent-island/activityTextStream.ts
@@ -1,7 +1,9 @@
import { richAnswerText, splitRichAnswer } from '@cindy/maker-shared/rich-answer';
-import { markdownPreviewText } from '../../shared/markdownPreviewText.js';
+import { markdownPreviewText, streamingMarkdownPreviewText } from '../../shared/markdownPreviewText.js';
export const AGENT_ISLAND_ACTIVITY_TEXT_MAX_LENGTH = 280;
+// Match the rich-answer parser's source ceiling, separately from visible text.
+const ACTIVITY_SOURCE_MAX_LENGTH = 2_000_000;
type ActivityTextStreamMode = 'pending' | 'plain' | 'structured' | 'structured-extracted';
@@ -11,6 +13,8 @@ export interface ActivityTextStreamState {
rawPreview: string;
rawPreviewHasPendingWhitespace: boolean;
rawPreviewHasPendingNewline: boolean;
+ rawPreviewPendingLink: boolean;
+ rawPreviewPendingRich: boolean;
jsonClosingStack: Array<'}' | ']'>;
jsonInString: boolean;
jsonEscapePending: boolean;
@@ -32,6 +36,8 @@ export function createActivityTextStreamState(): ActivityTextStreamState {
rawPreview: '',
rawPreviewHasPendingWhitespace: false,
rawPreviewHasPendingNewline: false,
+ rawPreviewPendingLink: false,
+ rawPreviewPendingRich: false,
jsonClosingStack: [],
jsonInString: false,
jsonEscapePending: false,
@@ -56,7 +62,9 @@ export function appendActivityTextStream(
): string {
const previousPreview = state.rawPreview;
appendRawPreview(state, chunk, metrics);
- const previewChanged = state.rawPreview !== previousPreview;
+ const destinationOnly = state.rawPreviewPendingLink && !/[\s\\()[\]<>`"']/.test(chunk);
+ const uncommittedRich = state.rawPreviewPendingRich && !/[\r\n]/.test(chunk);
+ const previewChanged = state.rawPreview !== previousPreview && !destinationOnly && !uncommittedRich;
if (state.mode === 'plain') {
return rawPreviewText(state, previewChanged);
@@ -161,7 +169,8 @@ function appendRawPreview(
chunk: string,
metrics?: ActivityTextStreamMetrics,
): void {
- if (state.rawPreview.length >= AGENT_ISLAND_ACTIVITY_TEXT_MAX_LENGTH) return;
+ if (state.displayText.length >= AGENT_ISLAND_ACTIVITY_TEXT_MAX_LENGTH && !state.rawPreviewPendingLink) return;
+ if (state.rawPreview.length >= ACTIVITY_SOURCE_MAX_LENGTH) return;
for (let index = 0; index < chunk.length; index += 1) {
if (metrics) metrics.normalizationCodeUnits += 1;
@@ -176,15 +185,15 @@ function appendRawPreview(
if (state.rawPreviewHasPendingWhitespace) {
// Keep fence/operation boundaries until rich content has been projected to text.
- // The retained prefix remains bounded; final events normalize the full answer.
+ // Visible text and protocol source have separate budgets.
state.rawPreview += state.rawPreviewHasPendingNewline ? '\n' : ' ';
state.rawPreviewHasPendingWhitespace = false;
state.rawPreviewHasPendingNewline = false;
- if (state.rawPreview.length >= AGENT_ISLAND_ACTIVITY_TEXT_MAX_LENGTH) return;
+ if (state.rawPreview.length >= ACTIVITY_SOURCE_MAX_LENGTH) return;
}
state.rawPreview += codeUnit;
- if (state.rawPreview.length >= AGENT_ISLAND_ACTIVITY_TEXT_MAX_LENGTH) return;
+ if (state.rawPreview.length >= ACTIVITY_SOURCE_MAX_LENGTH) return;
}
}
@@ -279,7 +288,14 @@ function rawPreviewText(state: ActivityTextStreamState, changed = true): string
source = source.slice(0, start);
}
}
- state.displayText = normalizePlainActivityText(richAnswerText(source));
+ const lastPart = splitRichAnswer(source).at(-1);
+ state.rawPreviewPendingRich = lastPart?.kind === 'rich' && !lastPart.complete;
+ const readable = richAnswerText(source);
+ const projection = /[*_`~<>!#|&\n\r]|\](?:\(|\[)|^\s*(?:[-+] |\d+[.)] )/.test(readable)
+ ? streamingMarkdownPreviewText(readable)
+ : { text: readable, pendingLink: false };
+ state.rawPreviewPendingLink = projection.pendingLink;
+ state.displayText = boundActivityText(projection.text);
return state.displayText;
}
diff --git a/apps/desktop/src/shared/markdownPreviewText.ts b/apps/desktop/src/shared/markdownPreviewText.ts
index 9cc9455190..719c645104 100644
--- a/apps/desktop/src/shared/markdownPreviewText.ts
+++ b/apps/desktop/src/shared/markdownPreviewText.ts
@@ -13,9 +13,49 @@ export function markdownPreviewText(
markdown: string,
options: { includeImageAlt?: boolean; imageFallback?: string } = {},
): string {
+ return projectMarkdownPreview(markdown, options).text;
+}
+
+/** Streaming only: let the Markdown parser recognize an unfinished destination.
+ * Synthetic closers never enter the source or final projection, and code nodes
+ * remain code. The flag lets a stream skip parsing ordinary URL characters. */
+export function streamingMarkdownPreviewText(markdown: string): { text: string; pendingLink: boolean } {
+ return projectMarkdownPreview(markdown, {}, true);
+}
+
+function projectMarkdownPreview(
+ markdown: string,
+ options: { includeImageAlt?: boolean; imageFallback?: string },
+ streaming = false,
+): { text: string; pendingLink: boolean } {
// Marked's link regex can backtrack for minutes on short bracketed code spans.
// These previews run on Main after DB replies, so use the existing remark parser.
- const stack: Array<Nodes | string> = [previewParser.parse(richAnswerText(markdown))];
+ const source = richAnswerText(markdown);
+ let root = previewParser.parse(source);
+ let pendingLink = false;
+ if (streaming && source.includes('](')) {
+ // Parenthesized/angle destinations and optional quoted titles use the same
+ // parser, rather than a second Markdown grammar in the stream accumulator.
+ for (const closing of [')'.repeat(32), '>)', '")', "')"]) {
+ const continued = previewParser.parse(source + closing);
+ const candidates: Nodes[] = [continued];
+ while (candidates.length > 0) {
+ const node = candidates.pop()!;
+ if ((node.type === 'link' || node.type === 'image')
+ && (node.position?.start.offset ?? source.length) < source.length
+ && (node.position?.end.offset ?? 0) > source.length) {
+ root = continued;
+ pendingLink = true;
+ break;
+ }
+ if ('children' in node) {
+ for (const child of node.children) candidates.push(child);
+ }
+ }
+ if (pendingLink) break;
+ }
+ }
+ const stack: Array<Nodes | string> = [root];
const parts: string[] = [];
const includeImageAlt = options.includeImageAlt !== false;
while (stack.length > 0) {
@@ -24,6 +64,8 @@ export function markdownPreviewText(
parts.push(node);
continue;
}
+ // Ignore the unused synthetic closing characters after the recovered link.
+ if (pendingLink && (node.position?.start.offset ?? 0) >= source.length) continue;
switch (node.type) {
case 'text':
case 'inlineCode':
@@ -62,5 +104,5 @@ export function markdownPreviewText(
}
}
}
- return parts.join('').replace(/\s+/gu, ' ').trim();
+ return { text: parts.join('').replace(/\s+/gu, ' ').trim(), pendingLink };
}