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): project forwarded text in search and reply quotes

Chris6b4394ef2184
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 236192c6f9..a75ec741e8 100644
--- a/apps/desktop/scripts/fixtures/forwarded-request/forwarded-request-fixture.tsx
+++ b/apps/desktop/scripts/fixtures/forwarded-request/forwarded-request-fixture.tsx
@@ -1,4 +1,4 @@
-import { useSyncExternalStore } from 'react';
+import { useState, 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';
@@ -6,6 +6,12 @@ import { BotDirectMessageView } from '../../../src/renderer/features/bots/BotDir
import { BotDirectMessageCard } from '../../../src/renderer/features/bots/BotDirectMessageCard';
import { UserMessage } from '../../../src/renderer/components/chat/UserMessage';
import { formatForwardedRequest } from '../../../src/shared/forwardedRequest';
+import { BotChatQuoteProvider } from '../../../src/renderer/features/bots/botChatQuoteContext';
+import { BotChatQuoteComposerPreview, BotChatQuoteInBubble } from '../../../src/renderer/features/bots/BotChatQuoteViews';
+import { SearchResultsBody } from '../../../src/renderer/features/cc-agent/sidebar/ConversationSearchBox';
+import { mergeConversationSearchResults, normalizeConversationContentPreview } from '../../../src/main/localDb/conversationSearch.pure';
+import type { ChatMessage } from '../../../src/renderer/lib/makerChatStore';
+import type { ChatReplyQuote } from '../../../src/shared/chatReplyQuote';
import type { SupportedLocale } from '../../../src/shared/locale';
const original = '请检查消息中的换行,保留代码和路径。';
@@ -16,6 +22,39 @@ function DraftProbe({ sessionId, content }: { sessionId: string; content: string
return <><pre hidden data-ui-draft>{JSON.stringify(draft?.text)}</pre><pre hidden data-ui-original>{content}</pre></>;
}
+function QuoteScenario({ content }: { content: string }) {
+ const [quote, setQuote] = useState<ChatReplyQuote | null>(null);
+ const [loaded, setLoaded] = useState(true);
+ const message = { clientId: 'quoted-user', role: 'user', content,
+ automationOrigin: { kind: 'session', senderSessionId: 'sender' } } as ChatMessage;
+ const context = { sessionId: 'quote-task', names: { owner: 'Chris', companion: 'Cindy' },
+ getMessage: () => loaded ? message : undefined, isFirstReplyFor: () => false,
+ showReplyTargets: false, quote: setQuote, locate: () => {} };
+ return <div className="p-4 space-y-4" data-ui-page-subject><BotChatQuoteProvider value={context}>
+ <UserMessage workingDir="" sessionId="quote-task" messageClientId={message.clientId}
+ content={content} automationOrigin={message.automationOrigin} simplifiedBotConversation />
+ {quote && <div data-ui-quote-preview>
+ <BotChatQuoteComposerPreview sessionId="quote-task" quote={quote} getMessage={context.getMessage} names={context.names} />
+ <BotChatQuoteInBubble quote={quote} context={context} />
+ <pre hidden data-ui-quote-snapshot>{quote.excerpt}</pre>
+ </div>}
+ <button data-ui-unload onClick={() => setLoaded(false)}>Unload original (fixture)</button>
+ </BotChatQuoteProvider></div>;
+}
+
+function SearchScenario({ content }: { content: string }) {
+ const query = '最后一段';
+ const preview = normalizeConversationContentPreview('user', content, query, 180, JSON.stringify({ origin: { kind: 'session' } }));
+ const date = new Date(1792629000000).toISOString();
+ const results = mergeConversationSearchResults({ titleMatches: [], limit: 10, contentHits: [{
+ session: { id: 'search-task', title: '消息格式检查', workingDir: null, workspaceKind: 'dialogue',
+ agentKind: 'cc', status: 'active', createdAt: date, updatedAt: date, userSendAt: date, _count: { messages: 3 } },
+ hit: { messageId: 'search-message', messageClientId: 'search-user', role: 'user', createdAt: date,
+ preview: preview.preview, snippet: preview.snippet, score: 1, ftsRank: 1, vectorRank: null },
+ }] });
+ return <div className="p-4" data-ui-page-subject><SearchResultsBody trimmed={query} status="done" results={results} onSelect={() => {}} /></div>;
+}
+
void mountPage({
route: '/bots/bot-a/direct/thread',
host: (ctx) => {
@@ -36,6 +75,8 @@ void mountPage({
},
render: (ctx) => {
const content = formatForwardedRequest({ userText: original }, supplement, ctx.locale as SupportedLocale);
+ if (ctx.case === 'quote') return <QuoteScenario content={content} />;
+ if (ctx.case === 'search') return <SearchScenario content={content} />;
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' }} />
diff --git a/apps/desktop/scripts/fixtures/forwarded-request/ui-page.mjs b/apps/desktop/scripts/fixtures/forwarded-request/ui-page.mjs
index df128a12e7..bcefb03f58 100644
--- a/apps/desktop/scripts/fixtures/forwarded-request/ui-page.mjs
+++ b/apps/desktop/scripts/fixtures/forwarded-request/ui-page.mjs
@@ -1,7 +1,7 @@
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',
+ real: 'BotDirectMessageView/Card, UserMessage, BotChatQuote previews, SearchResultsBody and production display/search projections',
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: () => {} };" },
@@ -14,10 +14,19 @@ export default {
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' },
+ quote: { about: 'Reply snapshots and live quote previews use readable text' },
+ search: { about: 'Real search results render projected previews and hit snippets' },
card: { about: 'Expand a historical private-thread card' },
},
async check(page, ui) {
- if (['task', 'fork', 'rewind'].includes(ui.case)) {
+ if (ui.case === 'search') {
+ await page.getByText('最后一段', { exact: true }).first().waitFor();
+ const text = await page.locator('body').innerText();
+ assert.ok(text.includes('只检查,不发布。'));
+ assert.ok(!text.includes('\\n\\n'));
+ return;
+ }
+ if (['task', 'fork', 'rewind', 'quote'].includes(ui.case)) {
const expand = page.getByRole('button', { name: await ui.t('chat.userMessage.expandLongMessage'), exact: true });
if (await expand.count()) await expand.click();
}
@@ -27,6 +36,16 @@ export default {
assert.ok(text.includes('第一段:消息现在正常换行。'));
assert.ok(text.includes('const newline = "\\n";'));
assert.ok(!text.includes('第一段:消息现在正常换行。\\n\\n'));
+ if (ui.case === 'quote') {
+ await page.getByRole('button', { name: await ui.t('chat.messageActionBar.reply'), exact: true }).click();
+ const snapshot = await page.locator('[data-ui-quote-snapshot]').textContent();
+ assert.ok(snapshot.includes('第一段:消息现在正常换行。'));
+ assert.ok(!snapshot.includes('\\n\\n'));
+ const preview = await page.locator('[data-ui-quote-preview]').innerText();
+ assert.ok(preview.includes(snapshot));
+ await page.locator('[data-ui-unload]').click();
+ assert.equal(await page.locator('[data-ui-quote-preview]').innerText(), preview);
+ }
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';
diff --git a/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts b/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts
index b71dbf8b3a..55fd5e1dd2 100644
--- a/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts
@@ -293,3 +293,40 @@ describe('conversationSearch personal companion chats', () => {
}
});
});
+
+// Unit: search result rendering leaked JSON escapes after opening the same hit showed paragraphs.
+// Exercise the production search entry + SQLite metadata lookup; retrieval/FTS content stays raw.
+it('projects forwarded search hits only with their persisted session origin', async () => {
+ const db = createSearchDb();
+ const client = makeSearchDbClient(db);
+ setCurrentDbClient(client, 'test-user');
+ const content = '[来源] 用户原话由宿主从已接收的输入原样保留。\n用户原话:"只检查"\nagent补充:"第一段\\n\\n第二段 needle,保留 `\\\\n`"';
+ const ids = ['forwarded', 'human', 'malformed-meta'];
+ try {
+ for (const id of ids) {
+ insertSearchSession(db, id, 10, null);
+ db.prepare('INSERT INTO messages (id, client_id, session_id, role, content, agent_meta, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)')
+ .run(id, id, id, 'user', content, id === 'forwarded' ? JSON.stringify({ origin: { kind: 'session' } }) : id === 'human' ? null : '{invalid', 10);
+ }
+ mocks.searchChatHistoryHybrid.mockResolvedValue({
+ hits: ids.map(id => ({ messageId: id, sessionId: id, role: 'user', createdAt: 10,
+ score: 1, ftsRank: 1, vectorRank: null, context: [{ isHit: true, content }] })),
+ sessions: {}, vectorUsed: false, vectorSkipReason: null, nextOffset: null,
+ hasMore: false, poolSize: 3, poolCapped: false,
+ });
+ const result = await searchConversations({ query: 'needle', semanticMode: 'keyword' });
+ const forwarded = result.results.find(item => item.session.id === 'forwarded')!.contentHit!;
+ expect(forwarded.preview).toContain('第一段 第二段 needle,保留 `\\n`');
+ expect(forwarded.snippet).toBe(forwarded.preview);
+ expect(forwarded.ftsRank).toBe(1);
+ for (const id of ['human', 'malformed-meta']) {
+ expect(result.results.find(item => item.session.id === id)!.contentHit!.preview)
+ .toBe(content.replace(/\s+/g, ' '));
+ }
+ expect(db.prepare('SELECT content FROM messages WHERE id = ?').get('forwarded')).toEqual({ content });
+ expect(mocks.searchChatHistoryHybrid.mock.calls[0][0].query).toBe('needle');
+ } finally {
+ clearCurrentDbClient(client);
+ db.close();
+ }
+});
diff --git a/apps/desktop/src/main/localDb/conversationSearch.pure.ts b/apps/desktop/src/main/localDb/conversationSearch.pure.ts
index 6aa9441e55..909ec80283 100644
--- a/apps/desktop/src/main/localDb/conversationSearch.pure.ts
+++ b/apps/desktop/src/main/localDb/conversationSearch.pure.ts
@@ -1,3 +1,4 @@
+import { forwardedRequestDisplayText } from '@cindy/maker-shared/message-source';
import type {
ConversationSearchContentHit,
ConversationSearchResultItem,
@@ -243,8 +244,9 @@ export function normalizeConversationContentPreview(
content: unknown,
query: string,
max = 180,
+ agentMeta?: string | null,
): NormalizedConversationContentPreview {
- const visibleText = visibleMessageTextForConversationSearch(role, content);
+ const visibleText = visibleMessageTextForConversationSearch(role, content, agentMeta);
const ranges = keywordRanges(visibleText, query);
const snippet = ranges.length > 0 ? visibleSnippet(visibleText, ranges[0], max) : null;
return {
@@ -254,8 +256,12 @@ export function normalizeConversationContentPreview(
};
}
-export function visibleMessageTextForConversationSearch(role: string, content: unknown): string {
- return visibleMessageText(role, content).replace(/\s+/g, ' ').trim();
+export function visibleMessageTextForConversationSearch(role: string, content: unknown, agentMeta?: string | null): string {
+ const text = visibleMessageText(role, content);
+ const meta = tryParseJsonLike(agentMeta ?? '') as { origin?: { kind?: unknown } } | null;
+ const displayText = role === 'user' && meta?.origin?.kind === 'session'
+ ? forwardedRequestDisplayText(text) : text;
+ return displayText.replace(/\s+/g, ' ').trim();
}
/** Full visible content for result rendering; only search previews flatten Markdown. */
diff --git a/apps/desktop/src/main/localDb/conversationSearch.ts b/apps/desktop/src/main/localDb/conversationSearch.ts
index 9b232d1a92..3b675b6875 100644
--- a/apps/desktop/src/main/localDb/conversationSearch.ts
+++ b/apps/desktop/src/main/localDb/conversationSearch.ts
@@ -141,7 +141,7 @@ export async function searchConversations(
});
const contentMessageIds = content.hits.map((hit) => hit.messageId);
- const clientIdByMessageId = await fetchClientIds(contentMessageIds);
+ const messageById = await fetchHitMessages(contentMessageIds);
const contentHits: Array<{
session: ConversationSearchSessionSummary;
hit: ConversationSearchContentHit;
@@ -150,10 +150,11 @@ export async function searchConversations(
for (const hit of content.hits) {
const session = sessionSummaries.get(hit.sessionId);
if (!session) continue;
- const messageClientId = clientIdByMessageId.get(hit.messageId);
+ const message = messageById.get(hit.messageId);
+ const messageClientId = message?.clientId;
if (!messageClientId) continue;
const hitContext = hit.context.find((item) => item.isHit) ?? hit.context[0] ?? null;
- const preview = normalizeConversationContentPreview(hit.role, hitContext?.content ?? '', query);
+ const preview = normalizeConversationContentPreview(hit.role, hitContext?.content ?? '', query, 180, message?.agentMeta);
// 可见文本对 query 字面不匹配时,仍可能是 FTS 命中(「边,界」按字相邻)。
// 不要只靠 keywordRanges 清掉 ftsRank,否则这类命中会被整条丢弃。
// 但附件文件名、内部 citation 等隐藏字段命中不能当可见结果:
@@ -161,6 +162,7 @@ export async function searchConversations(
const visibleText = visibleMessageTextForConversationSearch(
hit.role,
hitContext?.content ?? '',
+ message?.agentMeta,
);
const ftsRank =
preview.keywordMatchedVisibleText || visibleTextMatchesMessagesFtsQuery(visibleText, query)
@@ -417,13 +419,13 @@ async function fetchMessageCounts(sessionIds: string[]): Promise<Map<string, num
return new Map(rows.map((row) => [row.sessionId, Number(row.cnt)]));
}
-async function fetchClientIds(messageIds: string[]): Promise<Map<string, string>> {
+async function fetchHitMessages(messageIds: string[]): Promise<Map<string, { clientId: string; agentMeta: string | null }>> {
if (messageIds.length === 0) return new Map();
const rows = await getDbClient().drizzle
- .select({ id: messages.id, clientId: messages.clientId })
+ .select({ id: messages.id, clientId: messages.clientId, agentMeta: messages.agentMeta })
.from(messages)
.where(inArray(messages.id, messageIds));
- return new Map(rows.map((row) => [row.id, row.clientId]));
+ return new Map(rows.map((row) => [row.id, row]));
}
function sessionSummaryFromRow(
diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
index 25ae3c21c9..4f94a96885 100644
--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
@@ -1091,13 +1091,13 @@ export function UserMessage({
const botQuote = useBotChatQuote(simplifiedBotConversation ? sessionId : undefined);
const handleAddToChat = useCallback(() => {
if (botQuote && messageClientId) {
- const quote = botReplyQuoteFor({ clientId: messageClientId, role: 'user', content, images, files });
+ const quote = botReplyQuoteFor({ clientId: messageClientId, role: 'user', content, images, files, automationOrigin, hookSource });
if (quote) botQuote.quote(quote);
return;
}
if (!sessionId || !messageDeepLink) return;
insertSessionLinkIntoComposer({ targetSessionId: sessionId, href: messageDeepLink });
- }, [botQuote, content, files, images, messageClientId, messageDeepLink, sessionId]);
+ }, [botQuote, content, files, images, automationOrigin, hookSource, messageClientId, messageDeepLink, sessionId]);
// 分享为图片:进入选择模式并预选本条(入口那条天然该已勾选,省一次点击)。
const handleShareAsImage = useMemo(
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botDmQuote.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botDmQuote.test.ts
new file mode 100644
index 0000000000..5c00ddaa6d
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botDmQuote.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest';
+import { botReplyQuoteDisplay, botReplyQuoteFor } from '../botDmQuote';
+import { formatForwardedRequest } from '../../../../shared/forwardedRequest';
+
+// Unit: reply previews/live originals re-exposed serialized paragraph escapes.
+// These production quote entry points had no forwarded-message coverage.
+describe('forwarded companion reply quotes', () => {
+ const content = formatForwardedRequest({ userText: '只检查' }, '第一段\n\n第二段,保留 `\\n`', 'zh-CN');
+ const message = { clientId: 'forwarded', role: 'user' as const, content,
+ automationOrigin: { kind: 'session' as const, senderSessionId: 'sender' } };
+ const names = { owner: 'Chris', companion: 'Cindy' };
+
+ it('uses readable text for the pending snapshot, live original and unloaded fallback', () => {
+ const quote = botReplyQuoteFor(message)!;
+ expect(quote.excerpt).toContain('第一段 第二段,保留 `\\n`');
+ expect(quote.excerpt).not.toContain('第一段\\n\\n');
+ expect(botReplyQuoteDisplay({ ...quote, excerpt: 'old escaped snapshot' }, message, names)).toMatchObject({ state: 'live', excerpt: quote.excerpt });
+ expect(botReplyQuoteDisplay(quote, undefined, names)).toMatchObject({ state: 'snapshot', excerpt: quote.excerpt });
+ expect(message.content).toBe(content);
+ });
+
+ it('preserves the same intentional JSON example from a human', () => {
+ const human = { ...message, automationOrigin: undefined };
+ const quote = botReplyQuoteFor(human)!;
+ expect(quote.excerpt).toBe(content.replace(/\s+/g, ' '));
+ expect(botReplyQuoteDisplay(quote, human, names)).toMatchObject({ state: 'live', excerpt: quote.excerpt });
+ });
+});
diff --git a/apps/desktop/src/renderer/features/bots/botDmQuote.ts b/apps/desktop/src/renderer/features/bots/botDmQuote.ts
index e19dd6733b..c9fb4bc544 100644
--- a/apps/desktop/src/renderer/features/bots/botDmQuote.ts
+++ b/apps/desktop/src/renderer/features/bots/botDmQuote.ts
@@ -4,6 +4,7 @@
*/
import { useSyncExternalStore } from 'react';
import { richAnswerText } from '@cindy/maker-shared/rich-answer';
+import { forwardedRequestDisplayText } from '@cindy/maker-shared/message-source';
import type { ChatMessage } from '@/lib/makerChatStore';
import type { BotGroupQuoteDisplay } from '../../../shared/botGroupChat';
@@ -37,11 +38,13 @@ export function usePendingBotReplyQuote(sessionId: string | null | undefined): C
return useSyncExternalStore(subscribe, () => getPendingBotReplyQuote(sessionId), () => null);
}
-type QuotableMessage = Pick<ChatMessage, 'clientId' | 'role' | 'content' | 'images' | 'files'>;
+type QuotableMessage = Pick<ChatMessage, 'clientId' | 'role' | 'content' | 'images' | 'files' | 'automationOrigin' | 'hookSource'>;
/** The text the user reads: a companion reply's components as their visible text, not their source. */
function readableText(message: QuotableMessage): string {
- return message.role === 'assistant' ? richAnswerText(message.content) : message.content;
+ if (message.role === 'assistant') return richAnswerText(message.content);
+ return message.automationOrigin?.kind === 'session' && !message.hookSource
+ ? forwardedRequestDisplayText(message.content) : message.content;
}
function attachmentSummary(message: QuotableMessage | undefined): { count: number; name: string | null } {
diff --git a/docs/product-rules/message-source.md b/docs/product-rules/message-source.md
index fa311fd944..633521fd2d 100644
--- a/docs/product-rules/message-source.md
+++ b/docs/product-rules/message-source.md
@@ -67,6 +67,8 @@ Agent 用 `send_to_session` 把消息发给另一台电脑上的既有任务时
- 桌面与手机在显示时仅对完整的宿主转发包装解码一层 JSON 字符串,恢复段落并去掉序列化引号,
保留来源说明及原话/补充标签。五语和旧中文历史格式均适用;普通用户文本、代码示例、
残缺包装及有意书写的转义不做全局替换。存储、重放和来源校验继续使用原始正文。
+ 会话搜索摘要及伙伴回复引用摘要沿用该显示投影,并从原消息来源判断是否适用;FTS 索引仍用
+ 原文。已截断、没有可加载原消息的旧引用快照不猜测解码。
- 编辑已有委派队列只改补充,原话保持不变;启动与重试沿用该轮来源快照。普通队列编辑仍为
正常正文。历史消息不批量改写。
- `agentMeta.autoReviewUserText` 的 `agent-request` 回执只记录来源,不恢复旧授权、不授予新权限;