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(messages): render forwarded requests without JSON escapes

Chris4f81b1107d29
diff --git a/apps/desktop/scripts/fixtures/forwarded-request/forwarded-request-fixture.tsx b/apps/desktop/scripts/fixtures/forwarded-request/forwarded-request-fixture.tsx
new file mode 100644
index 0000000000..0623be0207
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/forwarded-request/forwarded-request-fixture.tsx
@@ -0,0 +1,37 @@
+import { Route, Routes } from 'react-router-dom';
+import { AppFrame, mountPage, subscription } from '../../ui-page/harness';
+import { BotDirectMessageView } from '../../../src/renderer/features/bots/BotDirectMessageView';
+import { BotDirectMessageCard } from '../../../src/renderer/features/bots/BotDirectMessageCard';
+import { UserMessage } from '../../../src/renderer/components/chat/UserMessage';
+import { formatForwardedRequest } from '../../../src/shared/forwardedRequest';
+import type { SupportedLocale } from '../../../src/shared/locale';
+
+const original = '请检查消息中的换行,保留代码和路径。';
+const supplement = '第一段:消息现在正常换行。\n\n1. 保留段落与列表\n2. 保留有意书写的转义\n\n```js\nconst newline = "\\n";\nconst path = "C:\\\\new\\\\test";\n```\n\n最后一段:只检查,不发布。';
+
+void mountPage({
+ route: '/bots/bot-a/direct/thread',
+ host: (ctx) => {
+ const content = formatForwardedRequest({ userText: original }, supplement, ctx.locale as SupportedLocale);
+ return { maker: {
+ getBotDirectMessageThread: async () => ({ ok: true, thread: {
+ id: 'thread', botAId: 'bot-a', botAName: 'Cindy', botBId: 'bot-b', botBName: 'Filo',
+ status: 'active', closeReason: null, messageCount: 1, maxMessages: 12,
+ messages: [{ id: 'message', sequence: 1, senderBotId: 'bot-a', senderBotName: 'Cindy',
+ recipientBotId: 'bot-b', recipientBotName: 'Filo', content, createdAt: 1792629000000 }],
+ } }),
+ onBotDirectMessageChanged: subscription('directMessageChanged'),
+ getCapabilities: async () => ({ availableModels: [], effortLevels: [], permissionModes: [], fork: { supported: false }, rewind: { supported: false } }),
+ } };
+ },
+ render: (ctx) => {
+ const content = formatForwardedRequest({ userText: original }, supplement, ctx.locale as SupportedLocale);
+ if (ctx.case === 'task') return <div className="p-4" data-ui-page-subject>
+ <UserMessage workingDir="" content={content} automationOrigin={{ kind: 'session', senderSessionId: 'sender', senderBotName: 'Cindy', senderBotId: 'bot-a' }} />
+ </div>;
+ if (ctx.case === 'card') return <div className="p-4" data-ui-page-subject>
+ <BotDirectMessageCard data={{ v: 1, threadId: 'thread', viewerBotId: 'bot-a', peerBotId: 'bot-b', peerBotName: 'Filo', direction: 'sent', sequence: 1, preview: content.slice(0, 400) }} />
+ </div>;
+ return <AppFrame sidebarWidth={0}><Routes><Route path="/bots/:botId/direct/:threadId" element={<BotDirectMessageView />} /></Routes></AppFrame>;
+ },
+});
diff --git a/apps/desktop/scripts/fixtures/forwarded-request/ui-page.mjs b/apps/desktop/scripts/fixtures/forwarded-request/ui-page.mjs
new file mode 100644
index 0000000000..7c987e8636
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/forwarded-request/ui-page.mjs
@@ -0,0 +1,28 @@
+import assert from 'node:assert/strict';
+export default {
+ name: 'forwarded-request', entry: './forwarded-request-fixture.tsx', viewport: { width: 760, height: 860 },
+ real: 'BotDirectMessageView, BotDirectMessageCard, UserMessage and production forwarded-request formatter/display projection',
+ notCovered: 'IPC transport, persistence and native mobile; historical API bodies are supplied by the fixture',
+ stubs: {
+ 'src/renderer/voice-input/workletUrl': 'export const getVoiceInputWorkletUrl = () => "";',
+ 'src/renderer/features/bots/botStore': 'const profiles = []; export const useBotProfiles = () => profiles;',
+ 'src/renderer/components/chat/GhostToolCard': 'export const CARD_EXPAND_TOGGLE_EVENT = "xdt-card-expand-toggle"; export const GhostToolCard = () => null; export const MailCardEditor = () => null;',
+ },
+ cases: {
+ default: { about: 'Historical private-thread body: paragraphs, lists, code and attribution' },
+ task: { about: 'Attributed task input uses the same readable projection' },
+ card: { about: 'Expand a historical private-thread card' },
+ },
+ async check(page, ui) {
+ if (ui.case === 'task') {
+ const expand = page.getByRole('button', { name: await ui.t('chat.userMessage.expandLongMessage'), exact: true });
+ if (await expand.count()) await expand.click();
+ }
+ if (ui.case === 'card') await page.getByRole('button', { name: await ui.t('bots.directMessage.expandThread'), exact: true }).click();
+ await page.getByText('最后一段:只检查,不发布。', { exact: false }).last().waitFor();
+ const text = await page.locator('body').innerText();
+ assert.ok(text.includes('第一段:消息现在正常换行。'));
+ assert.ok(text.includes('const newline = "\\n";'));
+ assert.ok(!text.includes('第一段:消息现在正常换行。\\n\\n'));
+ },
+};
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/forwardedRequest.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/forwardedRequest.test.ts
index ed08afc7c3..14fb87b447 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/forwardedRequest.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/forwardedRequest.test.ts
@@ -1,3 +1,4 @@
+import { forwardedRequestDisplayText } from '@cindy/maker-shared/message-source';
import { setMainLocale } from '../../i18n.js';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { captureAgentRequest } from '../forwardedRequest.js';
@@ -79,3 +80,38 @@ describe('host-owned forwarded request', () => {
expect(result.autoReviewUserText.request).toEqual({ userText: null });
});
});
+
+
+// Regression: complete JSON-quoted delegation messages displayed literal \\n.
+// Unit: real formatter + display projection; existing tests only covered wire validation.
+describe('forwarded request display', () => {
+ const original = ' 只检查\n"不要发布" ';
+ const supplement = '第一段\n\n1. 保留代码 `\\n`\n2. 路径 C:\\new\\test\n用户原话:这是补充中的文本';
+ it.each(['en', 'zh-CN', 'zh-TW', 'ja', 'ko'] as const)('decodes %s once without changing receipts or authored escapes', locale => {
+ const source = { userText: original, sessionId: 'owner', clientId: 'input' };
+ const body = formatForwardedRequest(source, supplement, locale);
+ const display = forwardedRequestDisplayText(body);
+ expect(display).toContain(original);
+ expect(display).toContain(supplement);
+ expect(display).not.toContain(JSON.stringify(supplement));
+ expect(forwardedRequestDisplayText(display)).toBe(display);
+ expect(matchesForwardedRequest(source, body)).toBe(true);
+ expect(matchesForwardedRequest({ ...source, userText: '发布' }, body)).toBe(false);
+ expect(matchesForwardedRequest(source, display)).toBe(false);
+ });
+ it('reads legacy Chinese, absent-source and task-prefixed history', () => {
+ const body = '[来源] 用户原话由宿主从已接收的输入原样保留。\n用户原话:"只检查"\nagent补充:"第一段\\n\\n第二段"';
+ expect(forwardedRequestDisplayText(body)).toContain('agent补充:\n\n第一段\n\n第二段');
+ const absent = formatForwardedRequest({ userText: null }, supplement, 'zh-CN');
+ expect(forwardedRequestDisplayText(absent)).toContain(supplement);
+ const prefix = '[任务来源] 本任务由伙伴发起。\n\n任务 ID: task-1\n\n';
+ expect(forwardedRequestDisplayText(prefix + body)).toBe(prefix + forwardedRequestDisplayText(body));
+ });
+ it('leaves incomplete wrappers, code samples and ordinary escaped prose verbatim', () => {
+ const body = formatForwardedRequest({ userText: original }, supplement, 'zh-CN');
+ for (const text of [body.slice(0, -1), body + '\nextra', '```text\n' + body + '\n```',
+ 'literal \\n and C:\\new', body.replace('用户原话:', 'Other:'), body.replace(JSON.stringify(supplement), '42')]) {
+ expect(forwardedRequestDisplayText(text)).toBe(text);
+ }
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/messageNavRailModel.test.ts b/apps/desktop/src/renderer/__tests__/messageNavRailModel.test.ts
index 0647123a85..5e776689da 100644
--- a/apps/desktop/src/renderer/__tests__/messageNavRailModel.test.ts
+++ b/apps/desktop/src/renderer/__tests__/messageNavRailModel.test.ts
@@ -1,3 +1,4 @@
+import { resolveUserDisplayText } from '@/components/chat/userMessageDisplayText';
/**
* messageNavRailModel 纯逻辑单测:条目派生过滤 / 当前提问判定 / 空间与截断规划。
* 全部 node 环境,无 DOM(组件侧几何测量不在此覆盖,见 MessageNavRail.tsx 注释)。
@@ -627,3 +628,13 @@ describe('forwardNavRailWheel', () => {
expect(() => forwardNavRailWheel(null, { deltaX: 0, deltaY: 10 })).not.toThrow();
});
});
+
+
+// Unit regression: bubble and navigation share this projection, which formerly
+// returned JSON-quoted history verbatim. Human examples must remain literal.
+it('shows readable delegated history only on attributed task messages', () => {
+ const content = '[来源] 用户原话由宿主从已接收的输入原样保留。\n用户原话:"只检查"\nagent补充:"第一段\\n\\n保留 `\\\\n`"';
+ expect(resolveUserDisplayText({ content, automationOrigin: { kind: 'session' } }))
+ .toContain('第一段\n\n保留 `\\n`');
+ expect(resolveUserDisplayText({ content })).toBe(content);
+});
diff --git a/apps/desktop/src/renderer/__tests__/pendingQueueRowPresentation.test.ts b/apps/desktop/src/renderer/__tests__/pendingQueueRowPresentation.test.ts
index 0894a45382..e45a5a6b72 100644
--- a/apps/desktop/src/renderer/__tests__/pendingQueueRowPresentation.test.ts
+++ b/apps/desktop/src/renderer/__tests__/pendingQueueRowPresentation.test.ts
@@ -331,3 +331,14 @@ describe('resolveSoleSteerableQueuedMessage', () => {
).toBeNull();
});
});
+
+
+// Unit regression: pending task input must show the same paragraphs as delivered
+// history, while its send payload and an ordinary user's draft stay literal.
+it('decodes forwarded queue display without mutating the queued body', () => {
+ const content = '[来源] 用户原话由宿主从已接收的输入原样保留。\n用户原话:"只检查"\nagent补充:"第一段\\n第二段"';
+ const entry = queuedMessage({ text: content, persistedContent: content, origin: { kind: 'session', senderSessionId: 'sender', displayText: content } });
+ expect(getPendingQueueRowPresentation(entry).displayText).toContain('第一段\n第二段');
+ expect(entry.persistedContent).toBe(content);
+ expect(getPendingQueueRowPresentation(queuedMessage({ text: content })).displayText).toBe(content);
+});
diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
index 040c60b8a7..5ce7d4c79d 100644
--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
@@ -914,7 +914,7 @@ export function UserMessage({
// 显示文本推导(Orca JSON 解包 / hook 消息取 userText 或剥 <thread_context>)
// 与提问导航条预览共用同一实现,规则见 userMessageDisplayText.ts;上面已
// 解析过的 Orca 结果传入复用,渲染热路径不重复 JSON.parse(Copilot review)。
- const displayContent = resolveUserDisplayText({ content, hookSource }, orcaCommunication);
+ const displayContent = resolveUserDisplayText({ content, hookSource, automationOrigin }, orcaCommunication);
const groupContext = useMemo(
() => resolveHookGroupContext({ content, hookSource }),
[content, hookSource],
@@ -1062,7 +1062,10 @@ export function UserMessage({
const projectedSource = projectSlashCommandsInText(ghostBody, slashCommandRanges);
const copyBody = quotesEncoded ? stripChatQuoteMarkerLines(projectedSource) : projectedSource;
const visibleSource = quotesEncoded ? stripChatQuoteMarkerLines(ghostBody) : ghostBody;
- const editSubmitText = quotesEncoded
+ // Display decoding must not change an unedited resend's wire bytes.
+ const editSubmitText = automationOrigin?.kind === 'session' && displayContent !== content
+ ? content
+ : quotesEncoded
? ghostBody
: copyBody !== visibleSource
? visibleSource
diff --git a/apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts b/apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts
index e6b189497f..6db2706d3a 100644
--- a/apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts
+++ b/apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts
@@ -1,3 +1,4 @@
+import { forwardedRequestDisplayText } from '@cindy/maker-shared/message-source';
import { captureImContext, type ImMessageSource } from '../../../shared/imMessageSource';
/**
* userMessageDisplayText
@@ -77,6 +78,7 @@ export function resolveHookGroupContext(source: {
export interface UserDisplayTextSource {
content: string;
hookSource?: { userText?: string } | null;
+ automationOrigin?: { kind: string };
}
export function resolveUserDisplayText(
@@ -89,7 +91,8 @@ export function resolveUserDisplayText(
),
): string {
const rawDisplayContent = orcaCommunication?.content ?? source.content;
- if (!source.hookSource) return rawDisplayContent;
+ if (!source.hookSource) return source.automationOrigin?.kind === 'session'
+ ? forwardedRequestDisplayText(rawDisplayContent) : rawDisplayContent;
return (
source.hookSource.userText ?? rawDisplayContent.replace(THREAD_CONTEXT_PREFIX_RE, '').trim()
);
diff --git a/apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts b/apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts
index eb62f1cdf9..100d7e8bf3 100644
--- a/apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts
+++ b/apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts
@@ -1,4 +1,4 @@
-import { isHookSchedulerOrigin } from '@cindy/maker-shared/message-source';
+import { forwardedRequestDisplayText, isHookSchedulerOrigin } from '@cindy/maker-shared/message-source';
import { queueItemVisibleText } from '@cindy/maker-shared/queue';
import { UI_ACTION_TRIGGER_PREFIX, type QueuedMessage } from '@/lib/makerChatStore';
import { stripChatQuoteMarkerLines } from '@/lib/chatQuotes';
@@ -93,7 +93,7 @@ export function getPendingQueueRowPresentation(entry: QueuedMessage): PendingQue
displayText: isOrca
? (origin.displayText ?? entry.text)
: isScheduler || isSession || isPlugin
- ? queueItemVisibleText(entry)
+ ? (isSession ? forwardedRequestDisplayText(queueItemVisibleText(entry)) : queueItemVisibleText(entry))
: entry.chatMessage.quotesEncoded === true
? stripChatQuoteMarkerLines(entry.text)
: entry.text,
diff --git a/apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx b/apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx
index 091750edab..02685a2bab 100644
--- a/apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx
@@ -1,3 +1,4 @@
+import { forwardedRequestDisplayText } from '@cindy/maker-shared/message-source';
import { useEffect, useId, useRef, useState } from 'react';
import { ArrowLeftRight, ChevronDown, ChevronUp, SquareArrowOutUpRight } from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -113,7 +114,7 @@ function BotDirectMessageCardBody({ meta, sessionId }: { meta: BotDirectMessageM
</div>
{meta.preview.trim() ? (
<p className="mt-1.5 line-clamp-2 whitespace-pre-wrap break-words rounded-lg border-l-2 border-[var(--msg-blockquote-border)] bg-[var(--surface-chip)] px-2.5 py-1.5 text-13 leading-[1.6] text-[var(--text-primary)]">
- {meta.preview.trim()}
+ {forwardedRequestDisplayText(meta.preview).trim()}
</p>
) : null}
<div className="mt-2 flex min-w-0 flex-wrap items-center gap-1.5">
@@ -151,7 +152,7 @@ function BotDirectMessageCardBody({ meta, sessionId }: { meta: BotDirectMessageM
{sender.name} · {formatBotMessageGroupTime(message.createdAt, i18n.language)}
</div>
<div className="min-w-0 break-words text-13 text-[var(--text-primary)]">
- <MarkdownRenderer workingDir="" content={message.content} allowPrivilegedLinks={false} />
+ <MarkdownRenderer workingDir="" content={forwardedRequestDisplayText(message.content)} allowPrivilegedLinks={false} />
</div>
</div>
</article>
diff --git a/apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx b/apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx
index a5d7801534..12162405b0 100644
--- a/apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx
@@ -1,3 +1,4 @@
+import { forwardedRequestDisplayText } from '@cindy/maker-shared/message-source';
import { Button } from '@/components/ui/button';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { ArrowLeftRight, CircleAlert, LockKeyhole } from 'lucide-react';
@@ -179,7 +180,7 @@ export function BotDirectMessageView() {
}`}
>
{/* Teammate-authored text: rendered like chat, never with privileged links. */}
- <MarkdownRenderer workingDir="" content={message.content} allowPrivilegedLinks={false} />
+ <MarkdownRenderer workingDir="" content={forwardedRequestDisplayText(message.content)} allowPrivilegedLinks={false} />
</div>
</div>
{ownSide ? <BotAvatar bot={sender} size="sm" /> : null}
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotDirectMessageView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotDirectMessageView.test.tsx
index 5513467450..f36217d86e 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotDirectMessageView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotDirectMessageView.test.tsx
@@ -220,3 +220,18 @@ it('does not restore a header when a remote read finishes after navigation away'
expect(screen.queryByText('Can you check this?')).toBeNull();
expect(unsubscribe).toHaveBeenCalledTimes(4);
});
+
+
+// Unit regression for the reported private-thread screen: transport quotes are
+// removed at render time while the stored/API content and inert-link policy stay intact.
+it('renders historical forwarded paragraphs without JSON string quotes', async () => {
+ const result = await mocks.getThread();
+ const content = '[来源] 用户原话由宿主从已接收的输入原样保留。\n用户原话:"只检查"\nagent补充:"第一段\\n\\n保留 `\\\\n`"';
+ result.thread.messages[0].content = content;
+ mocks.getThread.mockResolvedValue(result);
+ render(<TestPage />);
+ const body = await screen.findByText((_text, element) => element?.getAttribute('data-markdown') === 'false'
+ && Boolean(element.textContent?.includes('第一段\n\n保留 `\\n`')));
+ expect(body.textContent).not.toContain('agent补充:"');
+ expect(result.thread.messages[0].content).toBe(content);
+});
diff --git a/apps/mobile/app/companions/direct/[threadId].tsx b/apps/mobile/app/companions/direct/[threadId].tsx
index 38f4c0e53d..21cd2cd6ba 100644
--- a/apps/mobile/app/companions/direct/[threadId].tsx
+++ b/apps/mobile/app/companions/direct/[threadId].tsx
@@ -1,3 +1,4 @@
+import { forwardedRequestDisplayText } from '@cindy/maker-shared/message-source';
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
import { useFocusEffect, useLocalSearchParams, useRouter } from 'expo-router';
import { ActivityIndicator, RefreshControl, ScrollView, StyleSheet, View } from 'react-native';
@@ -82,7 +83,7 @@ export default function CompanionDirectMessages() {
{!ownSide ? avatar : null}
<View style={[styles.column, ownSide ? styles.columnOwn : styles.columnPeer]}>
<Text style={styles.meta}>{`${sender.name} · ${formatBotMessageGroupTime(message.createdAt, i18n.language)}`}</Text>
- <Text selectable style={[styles.bubble, ownSide ? styles.bubbleOwn : styles.bubblePeer]}>{message.content}</Text>
+ <Text selectable style={[styles.bubble, ownSide ? styles.bubbleOwn : styles.bubblePeer]}>{forwardedRequestDisplayText(message.content)}</Text>
</View>
{ownSide ? avatar : null}
</View>;
diff --git a/apps/mobile/src/__tests__/messageNormalize.test.ts b/apps/mobile/src/__tests__/messageNormalize.test.ts
index 5c3d113447..184ae31432 100644
--- a/apps/mobile/src/__tests__/messageNormalize.test.ts
+++ b/apps/mobile/src/__tests__/messageNormalize.test.ts
@@ -1691,3 +1691,17 @@ it('keeps durable coordination hidden on phone history without hiding user-facin
expect(JSON.stringify(rendered)).toContain('Requested status');
expect(JSON.stringify(rendered)).toContain('Final result');
});
+
+
+// Unit regression: historical machine inputs used to expose JSON escapes in bubbles/copy.
+// Same bytes from a human must remain untouched; source content still drives replay.
+it('projects forwarded machine history without rewriting human text or persisted bytes', () => {
+ const content = '[来源] 用户原话由宿主从已接收的输入原样保留。\n用户原话:"只检查"\nagent补充:"第一段\\n\\n保留 `\\\\n`"';
+ const rows = normalizeRemoteMessages([
+ message({ id: 'forwarded', role: 'user', content, agentMeta: { origin: { kind: 'session', senderSessionId: 'sender' } } }),
+ message({ id: 'human', role: 'user', content }),
+ ]);
+ expect(rows[0].body).toContain('第一段\n\n保留 `\\n`');
+ expect(rows[0].source.content).toBe(content);
+ expect(rows[1].body).toBe(content);
+});
diff --git a/apps/mobile/src/__tests__/pendingSendItems.test.ts b/apps/mobile/src/__tests__/pendingSendItems.test.ts
index 678208b8b4..f09401edc5 100644
--- a/apps/mobile/src/__tests__/pendingSendItems.test.ts
+++ b/apps/mobile/src/__tests__/pendingSendItems.test.ts
@@ -20,6 +20,7 @@ import {
isPendingSendItemSelected,
mergePendingSendItems,
pendingSendItemKey,
+ pendingSendBubbleText,
pendingSendSpins,
type MobilePendingSendActions,
} from '@/session/pendingSendItems';
@@ -593,3 +594,14 @@ describe('pending bubble source labels', () => {
expect(bubble.source).toBeNull();
});
});
+
+
+// Unit regression: remote pending bubble used to expose transport escapes. The
+// original queue item is retained for sending; a human draft is not decoded.
+it('decodes only attributed forwarded pending bubbles', () => {
+ const content = '[来源] 用户原话由宿主从已接收的输入原样保留。\n用户原话:"只检查"\nagent补充:"第一段\\n第二段"';
+ const item = { ...queued('forwarded', content), origin: { kind: 'session' as const, senderSessionId: 'sender' } };
+ expect(pendingSendBubbleText(item)).toContain('第一段\n第二段');
+ expect(item.persistedContent).toBe(content);
+ expect(pendingSendBubbleText(queued('human', content))).toBe(content);
+});
diff --git a/apps/mobile/src/session/messageNormalize.ts b/apps/mobile/src/session/messageNormalize.ts
index f6279e8c04..3ece933643 100644
--- a/apps/mobile/src/session/messageNormalize.ts
+++ b/apps/mobile/src/session/messageNormalize.ts
@@ -1,3 +1,4 @@
+import { forwardedRequestDisplayText } from '@cindy/maker-shared/message-source';
import { formatDuration } from '@cindy/maker-shared/message-render';
import { parseMcpAppHistory } from '@cindy/maker-shared/mcp-apps';
import { collectPluginInvocations, type PluginInvocation } from './pluginInvocations';
@@ -585,7 +586,8 @@ export function normalizeRemoteMessages(
// 本机 IM 落库的就是用户原文:正文保持完整落库内容,分叉 / 回退据此恢复草稿。
const body = hookSource && !hookSource.userTextContent
? hookSource.userText
- : message.role === 'assistant' ? stripGoalVerdictBlock(rawBody) : rawBody;
+ : message.role === 'assistant' ? stripGoalVerdictBlock(rawBody)
+ : readRecord(message.agentMeta?.origin)?.kind === 'session' ? forwardedRequestDisplayText(rawBody) : rawBody;
const turnCost = readTurnCost(message);
result.push({
key: messageNormalizeKey(message),
diff --git a/apps/mobile/src/session/pendingSendItems.ts b/apps/mobile/src/session/pendingSendItems.ts
index 6a182bd1d6..6d14198fa8 100644
--- a/apps/mobile/src/session/pendingSendItems.ts
+++ b/apps/mobile/src/session/pendingSendItems.ts
@@ -1,3 +1,4 @@
+import { forwardedRequestDisplayText } from '@cindy/maker-shared/message-source';
/**
* 待发送消息 → 消息流渲染项。
* ---------------------------------------------------------------------------
@@ -206,7 +207,8 @@ function pendingSendAgentText(item: PendingSendTextSource): string {
const persisted = parseOrcaPersistedMessage(item.persistedContent);
if (persisted) return persisted.body;
}
- return queueItemVisibleText(item);
+ const visible = queueItemVisibleText(item);
+ return origin?.kind === 'session' ? forwardedRequestDisplayText(visible) : visible;
}
/**
diff --git a/docs/product-rules/message-source.md b/docs/product-rules/message-source.md
index 689f09c8b5..fa311fd944 100644
--- a/docs/product-rules/message-source.md
+++ b/docs/product-rules/message-source.md
@@ -64,6 +64,9 @@ Agent 用 `send_to_session` 把消息发给另一台电脑上的既有任务时
自动化输入不从更早的用户消息补造本轮原话。模型工具不提供填写或改写原话的参数。
- 有原话的伙伴委派仍使用「用户原话 / Agent补充」两栏和 JSON 字符串引用,保留换行、引号和
首尾空格;补充里的同名标签不成为原话。标签使用发送宿主的界面语言,原话与补充不翻译。
+- 桌面与手机在显示时仅对完整的宿主转发包装解码一层 JSON 字符串,恢复段落并去掉序列化引号,
+ 保留来源说明及原话/补充标签。五语和旧中文历史格式均适用;普通用户文本、代码示例、
+ 残缺包装及有意书写的转义不做全局替换。存储、重放和来源校验继续使用原始正文。
- 编辑已有委派队列只改补充,原话保持不变;启动与重试沿用该轮来源快照。普通队列编辑仍为
正常正文。历史消息不批量改写。
- `agentMeta.autoReviewUserText` 的 `agent-request` 回执只记录来源,不恢复旧授权、不授予新权限;
diff --git a/packages/maker-shared/src/forwardedRequestDisplay.ts b/packages/maker-shared/src/forwardedRequestDisplay.ts
new file mode 100644
index 0000000000..cfd2cd486e
--- /dev/null
+++ b/packages/maker-shared/src/forwardedRequestDisplay.ts
@@ -0,0 +1,36 @@
+// Persisted envelope dialects, not UI translations. Keep old spellings readable
+// regardless of the viewing device's locale. This parser never grants authorship
+// or permission; the host's receipt validator still consumes the original bytes.
+const DIALECTS = [
+ ['[Source] ', 'User’s original words:', 'Agent supplement:', '[Task source] ', 'Task ID:'],
+ ['[来源] ', '用户原话:', 'Agent补充:', '[任务来源] ', '任务 ID:'],
+ ['[来源] ', '用户原话:', 'agent补充:', '[任务来源] ', '任务 ID:'],
+ ['[來源] ', '使用者原話:', 'Agent補充:', '[任務來源] ', '任務 ID:'],
+ ['[出典] ', 'ユーザーの原文:', 'Agent の補足:', '[タスクの出典] ', 'タスク ID:'],
+ ['[출처] ', '사용자 원문:', 'Agent 보충:', '[작업 출처] ', '작업 ID:'],
+] as const;
+
+/** Display only, for attributed machine messages. Decode one complete envelope,
+ * never arbitrary backslashes, nested payloads, code fences or truncated previews.
+ * The wire body, history, replay and source receipts must remain untouched. */
+export function forwardedRequestDisplayText(body: string): string {
+ if (!body.startsWith('[')) return body;
+ const lines = body.split('\n');
+ for (const [sourcePrefix, userPrefix, agentPrefix, taskPrefix, taskIdPrefix] of DIALECTS) {
+ // Background tasks prepend two host lines separated by blank lines.
+ const offset = lines.length === 7 && lines[0].startsWith(taskPrefix)
+ && lines[1] === '' && lines[2].startsWith(`${taskIdPrefix} `) && lines[3] === '' ? 4 : 0;
+ if (lines.length !== offset + 3 || !lines[offset].startsWith(sourcePrefix)
+ || !lines[offset + 1].startsWith(userPrefix) || !lines[offset + 2].startsWith(agentPrefix)) continue;
+ const quotedUser = lines[offset + 1].slice(userPrefix.length);
+ const quotedAgent = lines[offset + 2].slice(agentPrefix.length);
+ try {
+ const user: unknown = JSON.parse(quotedUser);
+ const agent: unknown = JSON.parse(quotedAgent);
+ if (typeof user !== 'string' || typeof agent !== 'string'
+ || JSON.stringify(user) !== quotedUser || JSON.stringify(agent) !== quotedAgent) continue;
+ return [...lines.slice(0, offset), lines[offset], '', userPrefix, '', user, '', agentPrefix, '', agent].join('\n');
+ } catch { /* Malformed or incomplete history stays verbatim. */ }
+ }
+ return body;
+}
diff --git a/packages/maker-shared/src/messageSource.ts b/packages/maker-shared/src/messageSource.ts
index fb78a7ab46..3ad47e3e97 100644
--- a/packages/maker-shared/src/messageSource.ts
+++ b/packages/maker-shared/src/messageSource.ts
@@ -1,3 +1,4 @@
+export { forwardedRequestDisplayText } from './forwardedRequestDisplay.js';
/**
* 消息来源:界面标签与发给模型的来源说明共用的一份描述。
*