Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix: 清理内部 Web 引用标记 (#1525)
Dash20ba989aba22
diff --git a/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts b/apps/desktop/src/main/__tests__/codexLocalSessions.test.tsindex a0fbff0279..9f7f261eb2 100644--- a/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts+++ b/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts@@ -1025,7 +1025,7 @@ describe('importExternalCodexMessagesForSession', () => {expect(rows.map((r) => JSON.parse(r.content))).toEqual(['first', 'third']);});- it('normalizes codex file citations in imported assistant messages (#785)', async () => {+ it('normalizes codex file and Web citations in imported assistant messages (#785)', async () => {const dbPath = createStateDb(externalHome);const rolloutPath = path.join(externalHome, 'sessions', `rollout-2026-05-13-${threadId}.jsonl`);fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });@@ -1036,7 +1036,7 @@ describe('importExternalCodexMessagesForSession', () => {rolloutLine('m2','assistant',- '已保存::codex-file-citation{path="/tmp/报告.docx" purpose="output"},请查收。',+ '已保存::codex-file-citation{path="/tmp/报告.docx" purpose="output"},请查收。\uE200cite\uE202turn17search1\uE201','2026-05-13T00:00:02.000Z',),'',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.tsindex 5fefca65b5..d2ca6629ed 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@@ -913,7 +913,13 @@ describe('进度快照(turn.progress 链路)', () => {// agent 的常态: 先说一句要去看看 -> 干活 -> 给结论。cb({ type: 'text', data: { text: '我先看看这个链接。', isFinal: true } });cb({ type: 'tool_use', data: { toolName: 'WebFetch', toolUseId: 'u1', input: {} } });- cb({ type: 'text', data: { text: '结论: 该库已停止维护。', isFinal: true } });+ cb({+ type: 'text',+ data: {+ text: '结论: 该库已停止维护。\uE200cite\uE202turn17search1\uE202turn17search2\uE201',+ isFinal: true,+ },+ });cb({ type: 'done', data: null });const outcome = await p;@@ -922,6 +928,7 @@ describe('进度快照(turn.progress 链路)', () => {// 发到公开时间线, 稀释最终结论 —— X 只发最后一条。expect(outcome.finalText).toBe('结论: 该库已停止维护。');expect(outcome.finalText).not.toContain('我先看看');+ expect(outcome.finalText).not.toContain('\uE200');} finally {vi.useRealTimers();}diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.tsindex 123fba69db..06f3b5eac2 100644--- a/apps/desktop/src/main/hook-control/session-runner.ts+++ b/apps/desktop/src/main/hook-control/session-runner.ts@@ -32,6 +32,7 @@ import fs from 'node:fs/promises';import path from 'node:path';import { app, BrowserWindow } from 'electron';+import { stripInternalWebCitations } from '@cindy/maker-shared/internal-citation';import type {AgentKind,@@ -367,7 +368,11 @@ async function collectOutboundForFinalText(allowedFileRoots: string[],log: { warn(msg: string): void },): Promise<{ finalText: string; attachments?: HookRunOutcome['attachments'] }> {- const { publicText, wholeTurn } = texts;+ // Defense in depth for X/Slack/Telegram: live Codex traffic is normalized in+ // maker-core, but older persisted/continuation text and future adapters must+ // never forward private Web citation delimiters to an external channel.+ const publicText = stripInternalWebCitations(texts.publicText);+ const wholeTurn = stripInternalWebCitations(texts.wholeTurn);if (!hasOutboundRefs(wholeTurn) && extraImageAbsPaths.length === 0) {return { finalText: publicText };}diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.tsindex 0796917c6c..5775176f07 100644--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts@@ -1279,7 +1279,13 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()const { turnPromise } = await startDefaultTurn();await turnPromise;- h.emit({ type: 'text', data: { text: 'complete text only', isFinal: true } });+ h.emit({+ type: 'text',+ data: {+ text: 'complete text only\uE200cite\uE202turn17search1\uE202turn17search2\uE201',+ isFinal: true,+ },+ });h.emit({ type: 'done', data: {} });await flushMicrotasks();diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.tsindex dc4f2dcebc..4c501a2d78 100644--- a/apps/desktop/src/main/im/shared/turnRunner.ts+++ b/apps/desktop/src/main/im/shared/turnRunner.ts@@ -34,6 +34,7 @@ import { createHash, randomUUID } from 'node:crypto';import path from 'node:path';import { eq } from 'drizzle-orm';+import { stripInternalWebCitations } from '@cindy/maker-shared/internal-citation';import { getMaker } from '../../maker-host';import { getDesktopProviderService } from '../../maker-host/createDesktopProviderService';import { isCredentialModeSwitchBusyError } from '../../maker-host/codex-credential-switch';@@ -1734,7 +1735,10 @@ export function createTurnRunner(* 纯文本快答没有 tool_use, renderActivity 返回空串, 视图与旧行为逐字一致。*/function composeStreamingView(turn: TurnState): string {- const body = turn.outputCardPrefix ? turn.outputCardPrefix + turn.buffer : turn.buffer;+ const rawBody = turn.outputCardPrefix ? turn.outputCardPrefix + turn.buffer : turn.buffer;+ // External-channel safeguard: maker-core normally strips these tokens,+ // while this boundary also protects old continuations and future adapters.+ const body = stripInternalWebCitations(rawBody);if (turn.done) return body;const act = renderActivity(turn.activity, Date.now());if (!act) return body;diff --git a/apps/desktop/src/main/localDb/__tests__/conversationSearch.pure.test.ts b/apps/desktop/src/main/localDb/__tests__/conversationSearch.pure.test.tsindex 6dcc9791a0..472f32bd0c 100644--- a/apps/desktop/src/main/localDb/__tests__/conversationSearch.pure.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/conversationSearch.pure.test.ts@@ -252,6 +252,13 @@ describe('conversationSearch.pure', () => {});});+ it('removes internal Web citation markers from assistant search previews', () => {+ const marker = '\uE200cite\uE202turn17search1\uE202turn17search2\uE201';+ expect(+ visibleMessageTextForConversationSearch('assistant', `结论。${marker}`),+ ).toBe('结论。');+ });+it('hides synthetic UI trigger rows from search previews and keyword matching', async () => {const { UI_ACTION_TRIGGER_PREFIX } = await import('../../../shared/interruptedTurn.js');// 隐藏续跑指令(合成 user 行)对用户不可见,搜索 preview/snippet 也不能露出,diff --git a/apps/desktop/src/main/localDb/__tests__/mapperCitation.test.ts b/apps/desktop/src/main/localDb/__tests__/mapperCitation.test.tsnew file mode 100644index 0000000000..3c639b1657--- /dev/null+++ b/apps/desktop/src/main/localDb/__tests__/mapperCitation.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from 'vitest';++import { extractMessagePreview, messageToCamel } from '../mapper.js';++const marker = '\uE200cite\uE202turn17search1\uE202turn17search2\uE201';++describe('message mapper internal citation compatibility', () => {+ it('hides persisted Web citation markers from message history', () => {+ const row = {+ id: 'message-1',+ clientId: 'client-1',+ sessionId: 'session-1',+ role: 'assistant',+ content: JSON.stringify(`结论。${marker}`),+ toolUseId: null,+ agentMeta: null,+ agentKind: 'codex',+ createdAt: 1,+ rewindAt: null,+ } as Parameters<typeof messageToCamel>[0];++ expect(messageToCamel(row).content).toBe('结论。');+ });++ it('hides persisted markers from sidebar previews without touching user text', () => {+ expect(extractMessagePreview(JSON.stringify(`结论。${marker}`), 'assistant')).toBe('结论。');+ expect(extractMessagePreview(JSON.stringify(`用户引用 ${marker}`), 'user')).toBe(+ `用户引用 ${marker}`,+ );+ });+});diff --git a/apps/desktop/src/main/localDb/conversationSearch.pure.ts b/apps/desktop/src/main/localDb/conversationSearch.pure.tsindex aa9d1b4d6a..987a6bb9ac 100644--- a/apps/desktop/src/main/localDb/conversationSearch.pure.ts+++ b/apps/desktop/src/main/localDb/conversationSearch.pure.ts@@ -4,6 +4,7 @@ import type {ConversationSearchSessionSummary,ConversationSearchSortBy,} from '../../shared/conversationSearch.js';+import { stripInternalWebCitations } from '@cindy/maker-shared/internal-citation';import { isSyntheticTriggerText } from '../../shared/interruptedTurn.js';const Bonus = {@@ -254,7 +255,8 @@ export function normalizeConversationContentPreview(export function visibleMessageTextForConversationSearch(role: string, content: unknown): string {const parsed = typeof content === 'string' ? tryParseJsonLike(content) : content;- const text = roleVisibleText(role, parsed);+ const rawText = roleVisibleText(role, parsed);+ const text = role === 'assistant' ? stripInternalWebCitations(rawText) : rawText;return text.replace(/\s+/g, ' ').trim();}diff --git a/apps/desktop/src/main/localDb/mapper.ts b/apps/desktop/src/main/localDb/mapper.tsindex 0c95274ed7..e63661d389 100644--- a/apps/desktop/src/main/localDb/mapper.ts+++ b/apps/desktop/src/main/localDb/mapper.ts@@ -8,6 +8,7 @@*/import { DEFAULT_DRAFT_SESSION_TITLE } from '@cindy/maker-shared/session-title';+import { stripInternalWebCitations } from '@cindy/maker-shared/internal-citation';import type {sessions,@@ -114,6 +115,7 @@ export function extractMessagePreview(// role='user' 的正常落库行,但对用户不可见 —— 预览显示隐藏英文指令会暴露// 实现细节。返回 null 与"无预览"同渲染语义。if (isSyntheticTriggerText(text)) return null;+ if (role === 'assistant') text = stripInternalWebCitations(text);const collapsed = text.replace(/\s+/g, ' ').trim();if (!collapsed) return null;return collapsed.length > PREVIEW_MAX_CHARS ? collapsed.slice(0, PREVIEW_MAX_CHARS) : collapsed;@@ -200,6 +202,9 @@ export function messageToCamel(row: MessageRow): Message {// 容错:极端情况下 content 可能不是合法 JSON(例如旧手工写入),保留原字符串content = row.content;}+ if (row.role === 'assistant' && typeof content === 'string') {+ content = stripInternalWebCitations(content);+ }// agent_meta 列存的是 JSON.stringify 后的字符串,老消息为 NULL。// 解析失败时返回 null 而非抛——容错保证历史消息能正常加载。let agentMeta: AgentMeta | null = null;diff --git a/packages/maker-core/src/agents/codex/translator.test.ts b/packages/maker-core/src/agents/codex/translator.test.tsindex 164fe608df..946de0e2b4 100644--- a/packages/maker-core/src/agents/codex/translator.test.ts+++ b/packages/maker-core/src/agents/codex/translator.test.ts@@ -1300,7 +1300,7 @@ describe('extractRolloutUpdatePlanFunctionCallEvent', () => {});});-describe('codex file citation 归一化 (#785)', () => {+describe('codex internal citation 归一化 (#785)', () => {it('normalizeCodexFileCitations 把标记换成行内代码路径,畸形标记整个剥掉', async () => {const { normalizeCodexFileCitations } = await import('./translator.js');expect(@@ -1407,6 +1407,50 @@ describe('codex file citation 归一化 (#785)', () => {expect(stableCitationBoundary(braceComplete)).toBe(braceComplete.length);});+ it('Web Search 引用标记被剥离,普通 cite 文本与相邻标点不变', async () => {+ const { finalizeCodexCitationText } = await import('./translator.js');+ const one = '\uE200cite\uE202turn17search1\uE201';+ const many = '\uE200cite\uE202turn17search1\uE202turn17search2\uE201';+ expect(finalizeCodexCitationText(`结论。${one}`)).toBe('结论。');+ expect(finalizeCodexCitationText(`A ${one};B ${many}。`)).toBe('A ;B 。');+ expect(finalizeCodexCitationText('Please cite the source.')).toBe('Please cite the source.');+ });++ it('Web Search 引用跨 update 到达时不进入 delta,completed 截断残尾也不泄漏', async () => {+ const { newCodexRuntimeState } = await import('./translator.js');+ const rt = newCodexRuntimeState();+ const q = createAsyncQueue<AgentEvent>();+ const push = (phase: 'started' | 'updated' | 'completed', text: string): void => {+ translateItemNotification(+ phase,+ {+ threadId: 'thread-web-citation',+ turnId: 'turn-web-citation',+ item: { type: 'agentMessage', id: 'msg-web-citation', text },+ },+ q,+ makeCtx(rt),+ );+ };++ push('started', '结论。');+ push('updated', '结论。 \uE200ci');+ push('updated', '结论。 \uE200cite\uE202turn17search1');+ push('updated', '结论。 \uE200cite\uE202turn17search1\uE201 后续');+ push('completed', '结论。 \uE200cite\uE202turn17search1\uE201 后续。\uE200cite\uE202turn18sea');++ const events = await collect(q);+ const deltas = events+ .filter((event) => event.type === 'text' && !(event.data as { isFinal: boolean }).isFinal)+ .map((event) => (event.data as { text: string }).text);+ expect(deltas.join('')).toBe('结论。 后续');+ expect(deltas.join('')).not.toContain('\uE200');+ const final = events.find(+ (event) => event.type === 'text' && (event.data as { isFinal: boolean }).isFinal,+ );+ expect((final?.data as { text: string }).text).toBe('结论。 后续。');+ });+it('路径本身含标记开头字面量:完整标记结构化消费,不被误认成新的未闭合开头', async () => {const { normalizeCodexFileCitations, stableCitationBoundary } = await import('./translator.js');// macOS/POSIX 文件名允许 `:` 与 `{`——路径里可以出现完整的 OPEN 字面量。diff --git a/packages/maker-core/src/agents/codex/translator.ts b/packages/maker-core/src/agents/codex/translator.tsindex 1aefd65ce5..2836109cef 100644--- a/packages/maker-core/src/agents/codex/translator.ts+++ b/packages/maker-core/src/agents/codex/translator.ts@@ -26,6 +26,10 @@ import {extractNonSecretErrorSignals,redactSensitiveText,} from '@cindy/maker-shared/error-redaction';+import {+ stableInternalWebCitationBoundary,+ stripInternalWebCitations,+} from '@cindy/maker-shared/internal-citation';import type { AgentEvent, AgentTaskStatus, AgentTaskUpdateEventData } from '../../types/events.js';import { normalizeAccountRateLimitSnapshot } from '../../types/account-rate-limits.js';@@ -744,20 +748,24 @@ function findUnfinishedCitationOpen(text: string): number {* 规范形(见 localDb worker 的 canonicalizeCodexCitations)。*/export function finalizeCodexCitationText(text: string): string {- const openAt = findUnfinishedCitationOpen(text);- return normalizeCodexFileCitations(openAt === -1 ? text : text.slice(0, openAt));+ const fileOpenAt = findUnfinishedCitationOpen(text);+ const fileStableEnd = fileOpenAt === -1 ? text.length : fileOpenAt;+ const stableEnd = Math.min(fileStableEnd, stableInternalWebCitationBoundary(text));+ return stripInternalWebCitations(normalizeCodexFileCitations(text.slice(0, stableEnd)));}export function stableCitationBoundary(text: string): number {const open = findUnfinishedCitationOpen(text);if (open !== -1) {- return open;+ return Math.min(open, stableInternalWebCitationBoundary(text));}const maxProbe = Math.min(text.length, CODEX_FILE_CITATION_OPEN.length - 1);for (let k = maxProbe; k > 0; k -= 1) {- if (text.endsWith(CODEX_FILE_CITATION_OPEN.slice(0, k))) return text.length - k;+ if (text.endsWith(CODEX_FILE_CITATION_OPEN.slice(0, k))) {+ return Math.min(text.length - k, stableInternalWebCitationBoundary(text));+ }}- return text.length;+ return stableInternalWebCitationBoundary(text);}function handleAgentMessage(@@ -789,7 +797,9 @@ function handleAgentMessage(return;}- const emitted = normalizeCodexFileCitations(rawText.slice(0, stableCitationBoundary(rawText)));+ const emitted = stripInternalWebCitations(+ normalizeCodexFileCitations(rawText.slice(0, stableCitationBoundary(rawText))),+ );const delta = emitted.slice(prevLen);ctx.rt.itemTextLen.set(item.id, emitted.length);if (delta.length === 0) return;diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.jsonindex e8b0dab385..48da9da6d3 100644--- a/packages/maker-shared/package.json+++ b/packages/maker-shared/package.json@@ -28,6 +28,7 @@"./fixtures": "./src/fixtures.ts","./history-gap": "./src/historyGap.ts","./interaction": "./src/interaction.ts",+ "./internal-citation": "./src/internalCitation.ts","./math-markdown": "./src/mathMarkdown.ts","./mention-ref": "./src/mentionRef.ts","./mermaid-autofix": "./src/mermaidAutofix.ts",diff --git a/packages/maker-shared/src/index.ts b/packages/maker-shared/src/index.tsindex d4e3e36065..24a6bd84a9 100644--- a/packages/maker-shared/src/index.ts+++ b/packages/maker-shared/src/index.ts@@ -15,6 +15,7 @@ export * from './deviceLinkContract.js';export * from './errorRedaction.js';export * from './expandedBlockMemory.js';export * from './interaction.js';+export * from './internalCitation.js';export * from './mathMarkdown.js';export * from './mermaidAutofix.js';export * from './messageRender.js';diff --git a/packages/maker-shared/src/internalCitation.test.ts b/packages/maker-shared/src/internalCitation.test.tsnew file mode 100644index 0000000000..368bf73b84--- /dev/null+++ b/packages/maker-shared/src/internalCitation.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import {+ stableInternalWebCitationBoundary,+ stripInternalWebCitations,+} from './internalCitation.js';++const source1 = '\uE200cite\uE202turn17search1\uE201';+const source2 = '\uE200cite\uE202turn17search1\uE202turn17search2\uE201';++describe('internal Web citation normalization', () => {+ it('strips single and multiple-source markers without changing punctuation', () => {+ expect(stripInternalWebCitations(`结论。${source1}`)).toBe('结论。');+ expect(stripInternalWebCitations(`A ${source1};B ${source2}。`)).toBe('A ;B 。');+ });++ it('leaves ordinary cite text and unrelated private-use text untouched', () => {+ expect(stripInternalWebCitations('Please cite the source.')).toBe('Please cite the source.');+ expect(stripInternalWebCitations('ordinary \uE200 text')).toBe('ordinary \uE200 text');+ });++ it('is idempotent and strips unfinished final tails', () => {+ expect(stripInternalWebCitations(`done ${source1}`)).toBe('done ');+ expect(stripInternalWebCitations(stripInternalWebCitations(`done ${source1}`))).toBe('done ');+ expect(stripInternalWebCitations('done \uE200cite\uE202turn17sea')).toBe('done ');+ expect(stripInternalWebCitations('done \uE200ci')).toBe('done ');+ });++ it('holds split streaming prefixes and incomplete markers until they are complete', () => {+ expect(stableInternalWebCitationBoundary('done')).toBe(4);+ expect(stableInternalWebCitationBoundary('done \uE200ci')).toBe(5);+ expect(stableInternalWebCitationBoundary('done \uE200cite\uE202turn17sea')).toBe(5);+ expect(stableInternalWebCitationBoundary(`done ${source2}`)).toBe(`done ${source2}`.length);+ });+});diff --git a/packages/maker-shared/src/internalCitation.ts b/packages/maker-shared/src/internalCitation.tsnew file mode 100644index 0000000000..c4ebbc37cf--- /dev/null+++ b/packages/maker-shared/src/internalCitation.ts@@ -0,0 +1,63 @@+/**+ * OpenAI Web Search may encode source references in assistant text with+ * private-use delimiters such as `\uE200cite\uE202...\uE201`. Those tokens are+ * transport metadata, not user-facing prose. Some Codex app-server versions+ * expose only the flattened text and omit the structured URL annotations, so+ * client boundaries must remove the opaque marker deterministically.+ */+const WEB_CITATION_OPEN = '\uE200cite\uE202';+const WEB_CITATION_CLOSE = '\uE201';++function unfinishedWebCitationOpen(text: string): number {+ let from = 0;+ for (;;) {+ const open = text.indexOf(WEB_CITATION_OPEN, from);+ if (open === -1) return -1;+ const close = text.indexOf(WEB_CITATION_CLOSE, open + WEB_CITATION_OPEN.length);+ if (close === -1) return open;+ from = close + WEB_CITATION_CLOSE.length;+ }+}++function partialWebCitationPrefixStart(text: string): number {+ const maxProbe = Math.min(text.length, WEB_CITATION_OPEN.length - 1);+ for (let length = maxProbe; length > 0; length -= 1) {+ if (text.endsWith(WEB_CITATION_OPEN.slice(0, length))) return text.length - length;+ }+ return text.length;+}++/**+ * Return the append-only prefix of a streaming assistant snapshot. A Web+ * citation tail is withheld until its closing delimiter arrives, because the+ * whole marker will disappear from the visible text once complete.+ */+export function stableInternalWebCitationBoundary(text: string): number {+ const unfinished = unfinishedWebCitationOpen(text);+ return unfinished === -1 ? partialWebCitationPrefixStart(text) : unfinished;+}++/**+ * Strip complete Web citation markers plus an unfinished final marker/prefix.+ * The payload is intentionally treated as opaque: private-use delimiters are+ * the exact compatibility boundary, while ordinary words such as "cite" are+ * left untouched. The transform is idempotent.+ */+export function stripInternalWebCitations(text: string): string {+ if (!text.includes('\uE200')) return text;++ const stableEnd = stableInternalWebCitationBoundary(text);+ const stable = stableEnd === text.length ? text : text.slice(0, stableEnd);+ if (!stable.includes(WEB_CITATION_OPEN)) return stable;++ let output = '';+ let from = 0;+ for (;;) {+ const open = stable.indexOf(WEB_CITATION_OPEN, from);+ if (open === -1) return output + stable.slice(from);+ const close = stable.indexOf(WEB_CITATION_CLOSE, open + WEB_CITATION_OPEN.length);+ if (close === -1) return output + stable.slice(from, open);+ output += stable.slice(from, open);+ from = close + WEB_CITATION_CLOSE.length;+ }+}