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): preserve forwarded envelopes in restored drafts

Chris60291c360f8d
diff --git a/apps/desktop/scripts/fixtures/forwarded-request/forwarded-request-fixture.tsx b/apps/desktop/scripts/fixtures/forwarded-request/forwarded-request-fixture.tsx
index 0623be0207..236192c6f9 100644
--- a/apps/desktop/scripts/fixtures/forwarded-request/forwarded-request-fixture.tsx
+++ b/apps/desktop/scripts/fixtures/forwarded-request/forwarded-request-fixture.tsx
@@ -1,3 +1,5 @@
+import { useSyncExternalStore } from 'react';
+import { getDraft, subscribeDraft } from '../../../src/renderer/lib/composerDraftStore';
import { Route, Routes } from 'react-router-dom';
import { AppFrame, mountPage, subscription } from '../../ui-page/harness';
import { BotDirectMessageView } from '../../../src/renderer/features/bots/BotDirectMessageView';
@@ -9,6 +11,11 @@ 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最后一段:只检查,不发布。';
+function DraftProbe({ sessionId, content }: { sessionId: string; content: string }) {
+ const draft = useSyncExternalStore(callback => subscribeDraft(sessionId, callback), () => getDraft(sessionId));
+ return <><pre hidden data-ui-draft>{JSON.stringify(draft?.text)}</pre><pre hidden data-ui-original>{content}</pre></>;
+}
+
void mountPage({
route: '/bots/bot-a/direct/thread',
host: (ctx) => {
@@ -21,13 +28,17 @@ void mountPage({
recipientBotId: 'bot-b', recipientBotName: 'Filo', content, createdAt: 1792629000000 }],
} }),
onBotDirectMessageChanged: subscription('directMessageChanged'),
- getCapabilities: async () => ({ availableModels: [], effortLevels: [], permissionModes: [], fork: { supported: false }, rewind: { supported: false } }),
+ getCapabilities: async () => ({ availableModels: [], effortLevels: [], permissionModes: [], fork: { supported: true }, rewind: { supported: true } }),
+ fork: async () => ({ id: 'forwarded-fork', updatedAt: new Date().toISOString() }),
+ rewindPreview: async () => ({ canRewind: true, filesChanged: [], conversationOnly: true }),
+ rewindCommit: async () => ({ id: 'forwarded-task', updatedAt: new Date().toISOString() }),
} };
},
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' }} />
+ if (['task', 'fork', 'rewind'].includes(ctx.case)) return <div className="p-4" data-ui-page-subject>
+ <DraftProbe sessionId={ctx.case === 'fork' ? 'forwarded-fork' : 'forwarded-task'} content={content} />
+ <UserMessage workingDir="" sessionId="forwarded-task" messageClientId="forwarded-user-2" agentKind="cc" 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) }} />
diff --git a/apps/desktop/scripts/fixtures/forwarded-request/ui-page.mjs b/apps/desktop/scripts/fixtures/forwarded-request/ui-page.mjs
index 7c987e8636..df128a12e7 100644
--- a/apps/desktop/scripts/fixtures/forwarded-request/ui-page.mjs
+++ b/apps/desktop/scripts/fixtures/forwarded-request/ui-page.mjs
@@ -2,8 +2,9 @@ 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',
+ notCovered: 'IPC transport, persistence, history reload and native mobile; historical API bodies are supplied by the fixture',
stubs: {
+ 'src/renderer/lib/makerChatStore': { partial: "import { makerChatStore as real } from './src/renderer/lib/makerChatStore'; export const makerChatStore = { ...real, reloadMessages: () => {} };" },
'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;',
@@ -11,10 +12,12 @@ export default {
cases: {
default: { about: 'Historical private-thread body: paragraphs, lists, code and attribution' },
task: { about: 'Attributed task input uses the same readable projection' },
+ fork: { about: 'Fork restores the original forwarded envelope in the new draft' },
+ rewind: { about: 'Rewind restores the original forwarded envelope in the current draft' },
card: { about: 'Expand a historical private-thread card' },
},
async check(page, ui) {
- if (ui.case === 'task') {
+ if (['task', 'fork', 'rewind'].includes(ui.case)) {
const expand = page.getByRole('button', { name: await ui.t('chat.userMessage.expandLongMessage'), exact: true });
if (await expand.count()) await expand.click();
}
@@ -24,5 +27,17 @@ export default {
assert.ok(text.includes('第一段:消息现在正常换行。'));
assert.ok(text.includes('const newline = "\\n";'));
assert.ok(!text.includes('第一段:消息现在正常换行。\\n\\n'));
+ if (ui.case === 'fork' || ui.case === 'rewind') {
+ const original = await page.locator('[data-ui-original]').textContent();
+ const actionKey = ui.case === 'fork' ? 'chat.messageActionBar.fork' : 'chat.messageActionBar.rewind';
+ if (ui.case === 'rewind') await page.getByRole('button', { name: await ui.t('chat.messageActionBar.moreActions'), exact: true }).click();
+ await page.getByRole(ui.case === 'rewind' ? 'menuitem' : 'button', { name: await ui.t(actionKey), exact: true }).click();
+ const confirmKey = ui.case === 'fork' ? 'chat.messageActionBar.forkConfirm' : 'chat.rewind.dialog.confirm';
+ await page.getByRole('button', { name: await ui.t(confirmKey), exact: true }).click();
+ await page.waitForFunction(() => document.querySelector('[data-ui-draft]')?.textContent);
+ const draft = JSON.parse(await page.locator('[data-ui-draft]').textContent());
+ assert.equal(draft.content[0].content[0].text, original);
+ await page.getByRole('alertdialog').waitFor({ state: 'hidden' });
+ }
},
};
diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
index 5ce7d4c79d..25ae3c21c9 100644
--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
@@ -915,6 +915,9 @@ export function UserMessage({
// 与提问导航条预览共用同一实现,规则见 userMessageDisplayText.ts;上面已
// 解析过的 Orca 结果传入复用,渲染热路径不重复 JSON.parse(Copilot review)。
const displayContent = resolveUserDisplayText({ content, hookSource, automationOrigin }, orcaCommunication);
+ // Only the bubble is decoded. Draft restoration must retain the canonical envelope.
+ const forwardedDraftBody = !hookSource && !orcaCommunication
+ && automationOrigin?.kind === 'session' && displayContent !== content ? content : undefined;
const groupContext = useMemo(
() => resolveHookGroupContext({ content, hookSource }),
[content, hookSource],
@@ -954,13 +957,16 @@ export function UserMessage({
);
// 意识指令等既有语义判断只看用户自己的正文,不把引用原文误识别成命令。
const bubbleBody = useMemo(() => joinChatQuoteTextSegments(quoteSegments), [quoteSegments]);
+ const draftBody = forwardedDraftBody ?? bubbleBody;
const inlineQuoteCount = quoteSegments.reduce(
(count, segment) => count + (segment.kind === 'quote' ? 1 : 0),
0,
);
const quoteDraftDocument = useMemo(
- () => (quotesEncoded ? quoteSegmentsToComposerDocument(quoteSegments) : undefined),
- [quoteSegments, quotesEncoded],
+ () => forwardedDraftBody !== undefined
+ ? textToTiptapDoc(forwardedDraftBody)
+ : quotesEncoded ? quoteSegmentsToComposerDocument(quoteSegments) : undefined,
+ [forwardedDraftBody, quoteSegments, quotesEncoded],
);
// $指令 开头且确认命中意识时,气泡正文渲剥掉指令 token 的余文($token 的
// 语义由气泡内的召唤标注行承载,正文不重复报幕);普通消息里的 $word 不受
@@ -1063,8 +1069,8 @@ export function UserMessage({
const copyBody = quotesEncoded ? stripChatQuoteMarkerLines(projectedSource) : projectedSource;
const visibleSource = quotesEncoded ? stripChatQuoteMarkerLines(ghostBody) : ghostBody;
// Display decoding must not change an unedited resend's wire bytes.
- const editSubmitText = automationOrigin?.kind === 'session' && displayContent !== content
- ? content
+ const editSubmitText = forwardedDraftBody !== undefined
+ ? forwardedDraftBody
: quotesEncoded
? ghostBody
: copyBody !== visibleSource
@@ -1111,7 +1117,7 @@ export function UserMessage({
sessionId,
messageClientId,
forkBlocked: shouldBlockUserFork(sessionRunning, delivery),
- draftText: quotesEncoded ? undefined : bubbleBody,
+ draftText: quotesEncoded ? undefined : draftBody,
draftDocument: quoteDraftDocument,
});
const handleDelete = useDeleteMessage({
@@ -1154,7 +1160,7 @@ export function UserMessage({
// Rewind soft-deletes this row server-side (rewind_at set), so on next
// reload it disappears from the list; the composer keeps the draft so
// the user can edit and re-send.
- const draftText = quoteDraftDocument ?? textToTiptapDoc(bubbleBody);
+ const draftText = quoteDraftDocument ?? textToTiptapDoc(draftBody);
const probe = rewindSourceProbeRef.current;
rewindSourceProbeRef.current = null;
const draftImages = probe && probe.images === images ? probe.imagesForDraft() : images;
@@ -1177,7 +1183,7 @@ export function UserMessage({
// Force chat store to re-fetch messages (server filters rewind_at).
makerChatStore.reloadMessages(sessionId);
},
- [sessionId, bubbleBody, quoteDraftDocument, images, files],
+ [sessionId, draftBody, quoteDraftDocument, images, files],
);
// 第一条 user 消息没有可作为锚点的 prior assistant uuid → 后端必抛
diff --git a/apps/mobile/src/__tests__/chatQuoteCrossDevice.test.ts b/apps/mobile/src/__tests__/chatQuoteCrossDevice.test.ts
index 9abe4debe6..6107106228 100644
--- a/apps/mobile/src/__tests__/chatQuoteCrossDevice.test.ts
+++ b/apps/mobile/src/__tests__/chatQuoteCrossDevice.test.ts
@@ -19,7 +19,8 @@ describe('mobile cross-device quote wiring', () => {
expect(bubbleSource).toContain("segment.kind === 'quote' ? [segment.quote] : []");
expect(bubbleSource).toContain('joinChatQuoteTextSegments(quoteSegments)');
expect(bubbleSource).toContain('actions.onPreviewRewind?.(clientId, {');
- expect(bubbleSource).toContain('{ orderedBody: item.message.body }');
+ expect(bubbleSource).toContain('const draftBody = item.message.draftBody ?? item.message.body;');
+ expect(bubbleSource).toContain('{ orderedBody: draftBody }');
});
it('propagates quote metadata through direct and attachment-outbox sends', () => {
diff --git a/apps/mobile/src/__tests__/messageNormalize.test.ts b/apps/mobile/src/__tests__/messageNormalize.test.ts
index 184ae31432..8ecac25eb5 100644
--- a/apps/mobile/src/__tests__/messageNormalize.test.ts
+++ b/apps/mobile/src/__tests__/messageNormalize.test.ts
@@ -1703,5 +1703,8 @@ it('projects forwarded machine history without rewriting human text or persisted
]);
expect(rows[0].body).toContain('第一段\n\n保留 `\\n`');
expect(rows[0].source.content).toBe(content);
+ expect(rows[0].draftBody).toBe(content);
+ expect(composerDocumentFromSerializedMessage(rows[0].draftBody!).nodes).toEqual([{ type: 'text', text: content }]);
expect(rows[1].body).toBe(content);
+ expect(rows[1].draftBody).toBeUndefined();
});
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index 44b4518bab..40e49dd6b1 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -3449,9 +3449,11 @@ function MessageBubble({
const displayBubbleBody = hasSentInlineAtoms
? sentInlineTokensDisplayText(sentInlineTokens)
: bubbleBody;
+ const draftBody = item.message.draftBody ?? item.message.body;
+ const draftText = item.message.draftBody ?? bubbleBody;
const composerDraftDocument = useMemo(
() => (item.message.kind === 'user'
- ? composerDocumentFromSerializedMessage(item.message.body, {
+ ? composerDocumentFromSerializedMessage(draftBody, {
quotesEncoded: item.message.quotesEncoded,
agentReferences: item.message.agentReferences,
pastedTextRanges: item.message.pastedTextRanges,
@@ -3459,7 +3461,7 @@ function MessageBubble({
})
: null),
[
- item.message.body,
+ draftBody,
item.message.agentReferences,
item.message.kind,
item.message.pastedTextRanges,
@@ -3643,10 +3645,10 @@ function MessageBubble({
}
if (id === 'rewind' && clientId) {
actions.onPreviewRewind?.(clientId, {
- document: composerDraftDocument ?? composerDocumentFromSerializedMessage(item.message.body),
- text: bubbleBody,
+ document: composerDraftDocument ?? composerDocumentFromSerializedMessage(draftBody),
+ text: draftText,
quotes: messageQuotes,
- ...(item.message.quotesEncoded === true ? { orderedBody: item.message.body } : {}),
+ ...(item.message.quotesEncoded === true ? { orderedBody: draftBody } : {}),
});
return;
}
@@ -3655,10 +3657,10 @@ function MessageBubble({
clientId,
item.message.kind === 'user'
? {
- document: composerDraftDocument ?? composerDocumentFromSerializedMessage(item.message.body),
- text: bubbleBody,
+ document: composerDraftDocument ?? composerDocumentFromSerializedMessage(draftBody),
+ text: draftText,
quotes: messageQuotes,
- ...(item.message.quotesEncoded === true ? { orderedBody: item.message.body } : {}),
+ ...(item.message.quotesEncoded === true ? { orderedBody: draftBody } : {}),
}
: undefined,
);
@@ -3669,11 +3671,11 @@ function MessageBubble({
}
}, [
actions,
- bubbleBody,
+ draftText,
clientId,
composerDraftDocument,
copyMessage,
- item.message.body,
+ draftBody,
item.message.kind,
item.message.quotesEncoded,
messageQuotes,
diff --git a/apps/mobile/src/session/messageNormalize.ts b/apps/mobile/src/session/messageNormalize.ts
index 3ece933643..1820d25eef 100644
--- a/apps/mobile/src/session/messageNormalize.ts
+++ b/apps/mobile/src/session/messageNormalize.ts
@@ -91,6 +91,8 @@ export interface NormalizedRemoteMessage {
role: RemoteMessageRole;
label: string;
body: string;
+ /** Original forwarded envelope for fork / rewind; display-only decoding must not change drafts. */
+ draftBody?: string;
rawError?: string;
errorSummaryKey?: string;
/** user 消息正文包含产品引用编码;驱动跨端 marker/legacy 解析。 */
@@ -596,6 +598,7 @@ export function normalizeRemoteMessages(
role: message.role,
label: message.role,
body,
+ ...(message.role === 'user' && !hookSource && body !== rawBody ? { draftBody: rawBody } : {}),
attachments: userContent?.attachments,
...(userContent?.quotesEncoded === true ? { quotesEncoded: true } : {}),
sessionReferences: userContent?.sessionReferences,