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。

perf(mobile): 复用长回复正文块并隔离工作组更新 (#3942)

Dash68de8a2331a9
diff --git a/apps/mobile/src/__tests__/chatActivityLocaleRefresh.test.ts b/apps/mobile/src/__tests__/chatActivityLocaleRefresh.test.ts
index 9f647f1ceb..2afd3da1cc 100644
--- a/apps/mobile/src/__tests__/chatActivityLocaleRefresh.test.ts
+++ b/apps/mobile/src/__tests__/chatActivityLocaleRefresh.test.ts
@@ -37,4 +37,19 @@ describe('会话流文案随 app 语言刷新', () => {
expect(source).toContain('i18n.language');
},
);
+
+ it('Markdown completed-block render callbacks invalidate translated fallback labels', () => {
+ const source = componentSource('MarkdownBody');
+ expect(source).toContain('const { t } = useTranslation()');
+ const inlineRenderer = source.slice(
+ source.indexOf('const renderInlines = useCallback('),
+ source.indexOf('const textRunGroupingOptions'),
+ );
+ expect(inlineRenderer).toMatch(/\[[^\]]*\bt\s*\],\s*\);\s*$/);
+ const runRenderer = source.slice(
+ source.indexOf('const renderTextRunBlock = useCallback('),
+ source.indexOf('const renderTextRun ='),
+ );
+ expect(runRenderer).toMatch(/\[[^\]]*\brenderInlines\b[^\]]*\]\);\s*$/);
+ });
});
diff --git a/apps/mobile/src/__tests__/markdownBlockContent.test.tsx b/apps/mobile/src/__tests__/markdownBlockContent.test.tsx
new file mode 100644
index 0000000000..3f91964988
--- /dev/null
+++ b/apps/mobile/src/__tests__/markdownBlockContent.test.tsx
@@ -0,0 +1,191 @@
+// @vitest-environment jsdom
+import React, { act, Fragment, useCallback, type ReactNode } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { MarkdownBlockContent } from '@/session/MarkdownBlockContent';
+import { useMarkdownSessionLinkTitles } from '@/session/useMarkdownSessionLinkTitles';
+import {
+ groupMobileMarkdownSelectableBlocks,
+ parseMobileMarkdownIncremental,
+ type MobileMarkdownBlock,
+ type MobileMarkdownParseResult,
+ type MobileMarkdownTextRunGroupingOptions,
+} from '@/session/messageMarkdown';
+
+type RenderBlock = (block: MobileMarkdownBlock, leadingGap: boolean) => ReactNode;
+
+// Host spans stand in for the native text spans. The production memo component
+// and immutable incremental parser are real; this measures React work, not RN
+// layout, native selection, or device frame rate.
+const renderText: RenderBlock = (block, leadingGap) => {
+ if (!('inlines' in block)) return <span>{block.type}</span>;
+ return <>
+ {leadingGap ? <span>{'\n\n'}</span> : null}
+ {block.inlines.map((inline, index) => (
+ <span key={index}>{'text' in inline ? inline.text : inline.alt}</span>
+ ))}
+ </>;
+};
+
+function Body({ parse, renderBlock, baseline = false, options }: {
+ parse: MobileMarkdownParseResult;
+ renderBlock: RenderBlock;
+ baseline?: boolean;
+ options?: MobileMarkdownTextRunGroupingOptions;
+}) {
+ return <>{groupMobileMarkdownSelectableBlocks(parse.blocks, options).map((group) => (
+ <div key={group.key} data-text-run={group.type === 'text_run' ? '' : undefined}>
+ {(group.type === 'text_run' ? group.blocks : [group.block]).map((block, index) => {
+ const leadingGap = index > 0 && !('textRunContinuation' in block && block.textRunContinuation);
+ return baseline
+ // The previous renderer eagerly built every block's inline tree.
+ ? <Fragment key={block.key}>{renderBlock(block, leadingGap)}</Fragment>
+ : <MarkdownBlockContent key={block.key} block={block} leadingGap={leadingGap} renderBlock={renderBlock} />;
+ })}
+ </div>
+ ))}</>;
+}
+
+let host: HTMLDivElement;
+let root: Root;
+beforeEach(() => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ host.remove();
+ Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
+});
+
+describe('streaming Markdown React block boundaries', () => {
+ it('re-renders only the changing tail while retaining the text view and completed spans', () => {
+ const prefix = Array.from({ length: 160 }, (_, n) => `Paragraph ${n} **bold** and \`code\` and *emphasis*.`).join('\n\n');
+ const versions: MobileMarkdownParseResult[] = [];
+ let parse = parseMobileMarkdownIncremental(`${prefix}\n\ntail`);
+ for (let update = 0; update <= 30; update += 1) {
+ parse = parseMobileMarkdownIncremental(`${prefix}\n\ntail ${'x'.repeat(update)}`, parse);
+ versions.push(parse);
+ }
+ const measure = (baseline: boolean) => {
+ const renderBlock = vi.fn(renderText);
+ act(() => root.render(<Body parse={versions[0]} renderBlock={renderBlock} baseline={baseline} />));
+ const run = host.firstElementChild;
+ const firstSpan = run?.firstElementChild;
+ renderBlock.mockClear();
+ const started = performance.now();
+ for (const version of versions.slice(1)) {
+ act(() => root.render(<Body parse={version} renderBlock={renderBlock} baseline={baseline} />));
+ }
+ const durationMs = performance.now() - started;
+ expect(host.firstElementChild).toBe(run);
+ expect(run?.firstElementChild).toBe(firstSpan);
+ expect(host.querySelectorAll('[data-text-run]')).toHaveLength(1);
+ // Memo boundaries add no host wrappers inside the selectable text run.
+ expect([...run!.children].every((child) => child.tagName === 'SPAN')).toBe(true);
+ return { blocks: renderBlock.mock.calls.length, durationMs, text: host.textContent };
+ };
+ const before = measure(true);
+ act(() => root.render(null));
+ const after = measure(false);
+ expect(before.blocks).toBe(161 * 30);
+ expect(after.blocks).toBe(30);
+ expect(after.text).toBe(before.text);
+ console.info('[markdown-block-perf]', JSON.stringify({
+ updates: 30, stableParagraphs: 160,
+ before: { blocks: before.blocks, reactDomMs: before.durationMs },
+ after: { blocks: after.blocks, reactDomMs: after.durationMs },
+ }));
+ }, 20_000);
+
+ it('refreshes completed blocks when rendering context changes or a prefix is edited', () => {
+ let parse = parseMobileMarkdownIncremental('first **bold**\n\nsecond');
+ const firstRenderer = vi.fn(renderText);
+ act(() => root.render(<Body parse={parse} renderBlock={firstRenderer} />));
+ const updatedRenderer = vi.fn<RenderBlock>((block, gap) => <span data-new-context>{renderText(block, gap)}</span>);
+ act(() => root.render(<Body parse={parse} renderBlock={updatedRenderer} />));
+ expect(updatedRenderer).toHaveBeenCalledTimes(2);
+ expect(host.querySelectorAll('[data-new-context]')).toHaveLength(2);
+
+ parse = parseMobileMarkdownIncremental('changed **bold**\n\nsecond', parse);
+ act(() => root.render(<Body parse={parse} renderBlock={updatedRenderer} />));
+ expect(host.textContent).toBe('changed bold\n\nsecond');
+ expect(host.textContent).not.toContain('first');
+ });
+
+ it('preserves Android run splitting, continuation gaps, and full text across appends', () => {
+ const options = { maxTextRunBlocks: 2, maxTextRunUtf16Length: 48, maxTextRunInlineFragments: 8 };
+ let parse = parseMobileMarkdownIncremental(`first\n\n${'long😀 text '.repeat(16)}\n\nlast`);
+ const renderBlock = vi.fn(renderText);
+ for (const suffix of ['', ' more', '\n\n```ts\nlet x = 1;\n```\n\nafter']) {
+ parse = parseMobileMarkdownIncremental(`${parse.source}${suffix}`, parse);
+ act(() => root.render(<Body parse={parse} renderBlock={renderBlock} options={options} baseline />));
+ const expected = host.innerHTML;
+ act(() => root.render(<Body parse={parse} renderBlock={renderBlock} options={options} />));
+ expect(host.innerHTML).toBe(expected);
+ }
+ });
+
+ it('reuses Android chunks of a completed oversized paragraph while appending to the tail', () => {
+ const options = { maxTextRunUtf16Length: 48, maxTextRunInlineFragments: 8 };
+ let parse = parseMobileMarkdownIncremental(`${'long😀 **bold** text '.repeat(80)}\n\ntail`);
+ const renderBlock = vi.fn(renderText);
+ act(() => root.render(<Body parse={parse} renderBlock={renderBlock} options={options} />));
+ expect(renderBlock.mock.calls.length).toBeGreaterThan(20);
+ const firstSpan = host.firstElementChild?.firstElementChild;
+ renderBlock.mockClear();
+ for (let n = 0; n < 10; n += 1) {
+ parse = parseMobileMarkdownIncremental(`${parse.source}x`, parse);
+ act(() => root.render(<Body parse={parse} renderBlock={renderBlock} options={options} />));
+ }
+ expect(renderBlock).toHaveBeenCalledTimes(10);
+ expect(host.firstElementChild?.firstElementChild).toBe(firstSpan);
+ });
+
+ it('invalidates equal-text spans when link targets, formatting, or selection gaps change', () => {
+ const renderBlock = vi.fn(renderText);
+ let block: MobileMarkdownBlock = { type: 'paragraph', key: 'p', inlines: [{ type: 'link', text: 'link', url: 'https://a.test' }] };
+ act(() => root.render(<MarkdownBlockContent block={block} renderBlock={renderBlock} />));
+ block = { ...block, inlines: [{ type: 'link', text: 'link', url: 'https://b.test' }] };
+ act(() => root.render(<MarkdownBlockContent block={block} renderBlock={renderBlock} />));
+ block = { ...block, inlines: [{ type: 'strong', text: 'link' }] };
+ act(() => root.render(<MarkdownBlockContent block={block} renderBlock={renderBlock} />));
+ act(() => root.render(<MarkdownBlockContent block={block} renderBlock={renderBlock} leadingGap />));
+ expect(renderBlock).toHaveBeenCalledTimes(4);
+ expect(host.textContent).toBe('\n\nlink');
+ });
+
+ it('keeps deep-link render context stable until a referenced title actually changes', () => {
+ const sessionId = '03e0c22d-19db-4ac5-814f-1ea04040b471';
+ const linkedText = `[task](cindy://session/${sessionId})\n\ntail`;
+ let parse = parseMobileMarkdownIncremental(linkedText);
+ const renders = vi.fn();
+ function LinkedBody({ document, sessions }: {
+ document: MobileMarkdownParseResult;
+ sessions: { id: string; title: string }[];
+ }) {
+ const titles = useMarkdownSessionLinkTitles(document.source, sessions);
+ const renderBlock = useCallback<RenderBlock>((block, gap) => {
+ renders();
+ return <span data-title={titles?.[sessionId]}>{renderText(block, gap)}</span>;
+ }, [titles]);
+ return <Body parse={document} renderBlock={renderBlock} />;
+ }
+ const sessions = [{ id: sessionId, title: 'First title' }];
+ act(() => root.render(<LinkedBody document={parse} sessions={sessions} />));
+ renders.mockClear();
+ for (let n = 0; n < 10; n += 1) {
+ parse = parseMobileMarkdownIncremental(`${parse.source}x`, parse);
+ act(() => root.render(<LinkedBody document={parse} sessions={[...sessions, { id: 'other', title: `Other ${n}` }]} />));
+ }
+ expect(renders).toHaveBeenCalledTimes(10);
+ renders.mockClear();
+ act(() => root.render(<LinkedBody document={parse} sessions={[{ id: sessionId, title: 'Renamed' }]} />));
+ expect(renders).toHaveBeenCalledTimes(2);
+ expect(host.querySelectorAll('[data-title="Renamed"]')).toHaveLength(2);
+ act(() => root.render(<LinkedBody document={parse} sessions={[]} />));
+ expect(host.querySelector('[data-title]')).toBeNull();
+ });
+});
diff --git a/apps/mobile/src/__tests__/workActivityProjection.test.ts b/apps/mobile/src/__tests__/workActivityProjection.test.ts
index 30a843141e..1875e459fd 100644
--- a/apps/mobile/src/__tests__/workActivityProjection.test.ts
+++ b/apps/mobile/src/__tests__/workActivityProjection.test.ts
@@ -5,6 +5,8 @@ import { summarizeToolRowPresentation } from '@/session/messagePresentation';
import {
projectMobileWorkActivities,
projectRecentMobileWorkActivities,
+ sameMobileWorkToolActivity,
+ type MobileProjectedToolActivity,
} from '@/session/workActivityProjection';
import type { RemoteMessage } from '@/session/types';
@@ -42,6 +44,41 @@ function activeWorkGroup(messages: RemoteMessage[]) {
}
describe('mobile work activity projection', () => {
+ it('keeps unchanged rows equivalent across large work-group projections and refreshes real changes', () => {
+ const commandActions = Array.from({ length: 200 }, (_, index) => ({
+ type: 'read', command: `cat src/file-${index}.ts`,
+ name: `file-${index}.ts`, path: `src/file-${index}.ts`,
+ }));
+ const group = activeWorkGroup([
+ message({ id: 'user', role: 'user', content: 'inspect' }),
+ toolUse('exec', 'exec', {
+ command: commandActions.map((action) => action.command).join(' && '),
+ commandActions, cwd: '/repo',
+ }, 2),
+ ]);
+ const tools = () => projectMobileWorkActivities(group.children, true).activities
+ .filter((activity): activity is MobileProjectedToolActivity => activity.kind === 'tool');
+ const before = tools();
+ const after = tools();
+ expect(before).toHaveLength(200);
+ expect(after.every((row, index) => row !== before[index])).toBe(true);
+ expect(after.every((row, index) => sameMobileWorkToolActivity(before[index], row))).toBe(true);
+
+ const row = before[0];
+ for (const changed of [
+ { ...row, key: 'another-key' },
+ { ...row, status: row.status === 'done' ? 'running' as const : 'done' as const },
+ { ...row, toolResult: 'new result' },
+ { ...row, message: { ...row.message, normalized: { ...row.message.normalized, secondaryBody: 'changed' } } },
+ { ...row, intentOverride: { ...row.intentOverride!, target: 'new target' } },
+ { ...row, intentOverride: { ...row.intentOverride!, path: '/new/path' } },
+ { ...row, intentOverride: { ...row.intentOverride!, action: 'search' as const } },
+ { ...row, intentOverride: undefined },
+ ]) {
+ expect(sameMobileWorkToolActivity(row, changed)).toBe(false);
+ }
+ });
+
it('expands structured Codex commands and keeps only the latest five live actions', () => {
const commandActions = Array.from({ length: 6 }, (_, index) => ({
type: 'read',
diff --git a/apps/mobile/src/session/MarkdownBlockContent.tsx b/apps/mobile/src/session/MarkdownBlockContent.tsx
new file mode 100644
index 0000000000..7b2d505a3e
--- /dev/null
+++ b/apps/mobile/src/session/MarkdownBlockContent.tsx
@@ -0,0 +1,44 @@
+import { memo, type ReactNode } from 'react';
+import type { MobileMarkdownBlock } from '@/session/messageMarkdown';
+
+function shallowEqual(left: object, right: object): boolean {
+ if (left === right) return true;
+ const entries = Object.entries(left);
+ return entries.length === Object.keys(right).length
+ && entries.every(([key, value]) => Object.hasOwn(right, key)
+ && Object.is(value, (right as Record<string, unknown>)[key]));
+}
+
+function sameBlock(left: MobileMarkdownBlock, right: MobileMarkdownBlock): boolean {
+ if (left === right) return true;
+ // Android's bounded text runs clone oversized blocks on each grouping pass.
+ // Compare their flat inline data so unchanged chunks also keep their spans.
+ // Non-text blocks stay on the parser identity fast path (no deep table walk).
+ if (!('inlines' in left) || !('inlines' in right)) return false;
+ const { inlines: leftInlines, ...leftFields } = left;
+ const { inlines: rightInlines, ...rightFields } = right;
+ return shallowEqual(leftFields, rightFields)
+ && leftInlines.length === rightInlines.length
+ && leftInlines.every((inline, index) => shallowEqual(inline, rightInlines[index]));
+}
+
+/**
+ * Keep immutable parser blocks as React update boundaries. This component adds
+ * no native view: text-run blocks remain children of the SAME selectable text
+ * view, so selection can still span paragraphs and list items.
+ */
+export const MarkdownBlockContent = memo(function MarkdownBlockContent({
+ block,
+ leadingGap = false,
+ renderBlock,
+}: {
+ block: MobileMarkdownBlock;
+ leadingGap?: boolean;
+ renderBlock: (block: MobileMarkdownBlock, leadingGap: boolean) => ReactNode;
+}) {
+ return renderBlock(block, leadingGap);
+}, (previous, next) => (
+ previous.renderBlock === next.renderBlock
+ && previous.leadingGap === next.leadingGap
+ && sameBlock(previous.block, next.block)
+));
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index 97f0588244..46bc3836de 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -186,12 +186,14 @@ import {
parseMobileMarkdownIncremental,
parseMobileMarkdownInlines,
type MobileMarkdownParseResult,
+ type MobileMarkdownBlock,
type MobileMarkdownBlockGroup,
type MobileMarkdownInline,
type MobileMarkdownTextRunGroupingOptions,
} from '@/session/messageMarkdown';
+import { MarkdownBlockContent } from '@/session/MarkdownBlockContent';
+import { useMarkdownSessionLinkTitles } from '@/session/useMarkdownSessionLinkTitles';
import {
- extractSessionLinkIds,
isCindyDeepLinkUrl,
parseProjectDeepLinkUrl,
parseSessionDeepLinkUrl,
@@ -310,6 +312,7 @@ import type { ContinuationInFlightProjectionCapability } from '@/session/types';
import {
projectMobileWorkActivities,
type MobileProjectedToolActivity,
+ sameMobileWorkToolActivity,
} from '@/session/workActivityProjection';
import { logUnhandledRenderItem } from '@/session/assertNever';
import type { OrcaCollabCard as OrcaCollabCardModel } from '@/session/orcaCollab';
@@ -3807,6 +3810,8 @@ function ToolGroupCard({
* 媒体条 / 结果预览,再点收起。展开态走共享进程内记忆(blockId 前缀 `toolrow-`,
* 与组级 `tools-` key 空间天然隔离)。无详情可展的行不显示 chevron、不可点击。
*/
+type ToolDetailActions = Pick<MessageActions, 'onLoadToolInput' | 'onOpenPayload'>;
+
function ToolActionRow({
actions,
contentLayout,
@@ -3814,7 +3819,7 @@ function ToolActionRow({
rowKey,
tool,
}: {
- actions: MessageActions & { firstUserMessageClientId?: string };
+ actions: ToolDetailActions;
contentLayout: MessageContentLayout;
row: ToolRowPresentation;
rowKey?: string;
@@ -3876,7 +3881,7 @@ function ProjectedToolInputButton({
actions,
projection,
}: {
- actions: MessageActions;
+ actions: ToolDetailActions;
projection: MobileToolInputProjection;
}) {
const { colors } = useTheme();
@@ -4253,10 +4258,16 @@ function WorkGroupCard({
: null),
[expanded, isStreaming, item.children],
);
+ // Tool detail rows do not consume message action/queue/share busy state.
+ // Keep their callbacks and streaming flag stable across those unrelated updates.
+ const toolActions = useMemo(() => ({
+ onLoadToolInput: actions.onLoadToolInput,
+ onOpenPayload: actions.onOpenPayload,
+ isSessionStreaming: actions.isSessionStreaming,
+ }), [actions.onLoadToolInput, actions.onOpenPayload, actions.isSessionStreaming]);
const startedAtIso = isStreaming && item.startedAtMs !== undefined
? new Date(item.startedAtMs).toISOString()
: undefined;
- const elapsedMs = useLiveElapsedMs(isStreaming, startedAtIso);
const explorationSummary = activityProjection?.isPureExploration
? [
activityProjection.explorationCounts.read > 0
@@ -4283,8 +4294,8 @@ function WorkGroupCard({
onControlledToggle={onToggle}
title={title}
subtitle={header.subtitle ?? undefined}
- trailingMeta={isStreaming && elapsedMs !== null
- ? <Text style={styles.workGroupElapsed}>{formatDuration(elapsedMs)}</Text>
+ trailingMeta={isStreaming
+ ? <WorkGroupElapsed sinceIso={startedAtIso} />
: undefined}
leadingIcon={isStreaming
? <CompactActivityIndicator color={colors.textTertiary} size={header.iconSize} />
@@ -4306,7 +4317,7 @@ function WorkGroupCard({
{(activityProjection?.toolActivitiesByChildKey.get(child.key) ?? []).map((activity) => (
<WorkToolActivityRow
key={activity.key}
- actions={actions}
+ actions={toolActions}
activity={activity}
contentLayout={contentLayout!}
/>
@@ -4323,12 +4334,21 @@ function WorkGroupCard({
);
}
-function WorkToolActivityRow({
+/** The clock must not re-render an expanded group's entire activity tree. */
+function WorkGroupElapsed({ sinceIso }: { sinceIso: string | undefined }) {
+ const styles = useThemedStyles(makeStyles);
+ const elapsedMs = useLiveElapsedMs(true, sinceIso);
+ return elapsedMs === null
+ ? null
+ : <Text style={styles.workGroupElapsed}>{formatDuration(elapsedMs)}</Text>;
+}
+
+const WorkToolActivityRow = memo(function WorkToolActivityRow({
actions,
activity,
contentLayout,
}: {
- actions: MessageActions & { firstUserMessageClientId?: string };
+ actions: ToolDetailActions & Pick<MessageActions, 'isSessionStreaming'>;
activity: MobileProjectedToolActivity;
contentLayout: MessageContentLayout;
}) {
@@ -4349,9 +4369,13 @@ function WorkToolActivityRow({
tool={tool}
/>
);
-}
+}, (previous, next) => (
+ previous.actions === next.actions
+ && previous.contentLayout === next.contentLayout
+ && sameMobileWorkToolActivity(previous.activity, next.activity)
+));
-function ExpandedWorkThinkingRow({
+const ExpandedWorkThinkingRow = memo(function ExpandedWorkThinkingRow({
item,
}: {
item: MobileThinkingItem;
@@ -4412,7 +4436,7 @@ function ExpandedWorkThinkingRow({
: null}
</Pressable>
);
-}
+});
// 真·子 agent 嵌套卡片(手机端净新能力):复用 FoldablePanel(与 ToolGroupCard/WorkGroupCard 同款折叠
// 路径,滚动安全已验证)、默认折叠;展开递归渲染内层 childItems(经 RenderItemView)+ 子 agent 终稿。
@@ -5021,9 +5045,9 @@ function MarkdownBody({
setContentWidth((current) => nextSettledContentWidth(current, nextWidth));
}, [pinContentWidth]);
const pinSettledWidth = pinContentWidth && contentWidth > 0;
- const settledTextStyle = pinSettledWidth
+ const settledTextStyle = useMemo(() => pinSettledWidth
? [styles.messageText, { width: contentWidth }]
- : styles.messageText;
+ : styles.messageText, [contentWidth, pinSettledWidth, styles.messageText]);
const markdownParseRef = useRef<MobileMarkdownParseResult | null>(null);
const markdownParse = useMemo(() => {
const startedAt = typeof performance !== 'undefined' && typeof performance.now === 'function'
@@ -5072,19 +5096,10 @@ function MarkdownBody({
markdownImageCacheKey,
onOpenPayload,
]);
- // 会话深链 chip 标题:渲染期同步从会话镜像查(WebView 静态 HTML 无法事后
- // patch)。不含深链的消息恒为 undefined,不影响 html memo 稳定性。
- const sessionLinkIds = useMemo(() => extractSessionLinkIds(text), [text]);
+ // Preserve the inline renderer while streaming or unrelated task metadata
+ // changes; referenced task title changes still refresh every affected chip.
const remoteSessions = useRemoteSessions();
- const sessionLinkTitles = useMemo(() => {
- if (sessionLinkIds.length === 0) return undefined;
- const map: Record<string, string> = {};
- for (const id of sessionLinkIds) {
- const title = remoteSessions.find((s) => s.id === id)?.title?.trim();
- if (title) map[id] = title;
- }
- return Object.keys(map).length > 0 ? map : undefined;
- }, [sessionLinkIds, remoteSessions]);
+ const sessionLinkTitles = useMarkdownSessionLinkTitles(text, remoteSessions);
const sessionReferenceDetails = useMemo(() => {
if (!sessionReferences?.length) return undefined;
const details: Record<string, string> = {};
@@ -5112,7 +5127,9 @@ function MarkdownBody({
streaming,
}))
),
- [onOpenSessionLink, openMarkdownImage, sessionLinkTitles, sessionReferenceDetails, streaming, styles],
+ // renderInline also reads translated fallback labels. Invalidate completed
+ // memoized text blocks when useTranslation refreshes its bound translator.
+ [onOpenSessionLink, openMarkdownImage, sessionLinkTitles, sessionReferenceDetails, streaming, styles, t],
);
const textRunGroupingOptions = Platform.OS === 'android'
? ANDROID_SELECTABLE_TEXT_RUN_GROUPING_OPTIONS
@@ -5136,9 +5153,34 @@ function MarkdownBody({
// 一个高度恰为 gap 的空行在视觉上与原块间距一致。由单块切出的 continuation 不插间距。
// 列表项在树内表达为「marker 前缀 span + 正文」
// (无悬挂缩进;任务项以 ☑/☐ 字符替代原边框小方块)。
- const renderTextRun = (group: Extract<MobileMarkdownBlockGroup, { type: 'text_run' }>): ReactNode => {
+ const renderTextRunBlock = useCallback((block: MobileMarkdownBlock, leadingGap: boolean): ReactNode => {
+ if (block.type !== 'paragraph' && block.type !== 'heading' && block.type !== 'list_item') return null;
const runSelectable = selectable === true;
const RunSpan = spanFor(runSelectable) ?? Text;
+ const spans: ReactNode[] = [];
+ if (leadingGap) {
+ spans.push(
+ <RunSpan key={`${block.key}:gap`} style={{ lineHeight: layout.markdownBodyGap }}>
+ {'\n\n'}
+ </RunSpan>,
+ );
+ }
+ const baseStyle: StyleProp<TextStyle> = block.type === 'heading'
+ ? [styles.markdownHeading, headingSizeStyle(styles, block.level)]
+ : styles.messageText;
+ if (block.type === 'list_item' && !('textRunContinuation' in block && block.textRunContinuation)) {
+ const task = typeof block.checked === 'boolean';
+ spans.push(
+ <RunSpan key={`${block.key}:marker`} style={[styles.messageText, styles.markdownListMarkerInline]}>
+ {task ? (block.checked ? '☑ ' : '☐ ') : block.ordered ? `${block.marker} ` : '• '}
+ </RunSpan>,
+ );
+ }
+ spans.push(...renderInlines(block.inlines, spanFor(runSelectable), baseStyle, block.key));
+ return spans;
+ }, [layout.markdownBodyGap, renderInlines, selectable, spanFor, styles]);
+ const renderTextRun = (group: Extract<MobileMarkdownBlockGroup, { type: 'text_run' }>): ReactNode => {
+ const runSelectable = selectable === true;
return (
<MarkdownSelectableText
allowIosUITextView={allowIosUITextView}
@@ -5147,35 +5189,196 @@ function MarkdownBody({
style={settledTextStyle}
testID="message.markdownTextRun"
>
- {group.blocks.flatMap((block, index) => {
- const spans: ReactNode[] = [];
- if (index > 0 && !block.textRunContinuation) {
- spans.push(
- <RunSpan key={`${block.key}:gap`} style={{ lineHeight: layout.markdownBodyGap }}>
- {'\n\n'}
- </RunSpan>,
- );
- }
- const baseStyle: StyleProp<TextStyle> = block.type === 'heading'
- ? [styles.markdownHeading, headingSizeStyle(styles, block.level)]
- : styles.messageText;
- if (block.type === 'list_item' && !block.textRunContinuation) {
- const task = typeof block.checked === 'boolean';
- spans.push(
- <RunSpan
- key={`${block.key}:marker`}
- style={[styles.messageText, styles.markdownListMarkerInline]}
- >
- {task ? (block.checked ? '☑ ' : '☐ ') : block.ordered ? `${block.marker} ` : '• '}
- </RunSpan>,
- );
- }
- spans.push(...renderInlines(block.inlines, spanFor(runSelectable), baseStyle, block.key));
- return spans;
- })}
+ {group.blocks.map((block, index) => (
+ <MarkdownBlockContent
+ key={block.key}
+ block={block}
+ leadingGap={index > 0 && !block.textRunContinuation}
+ renderBlock={renderTextRunBlock}
+ />
+ ))}
</MarkdownSelectableText>
);
};
+ const renderSingleBlock = useCallback((block: MobileMarkdownBlock): ReactNode => {
+ if (block.type === 'mermaid') {
+ // 内联图表按「图片」形态呈现:无卡片 chrome、无标签文字、无按钮,
+ // 就是一块圆角图表;点击任意位置打开沉浸式全屏详情(透明 Pressable
+ // 盖住整块——WebView 会吞掉触摸事件,不盖层拿不到点击)。
+ return (
+ <View key={block.key} testID="message.mermaidPreviewButton">
+ <ViewabilityGatedMermaidDiagram source={block.text} testID="message.mermaidDiagram" />
+ {onOpenPayload ? (
+ <Pressable
+ accessibilityLabel={t('message.renderer.openDiagramDetail')}
+ accessibilityRole="button"
+ onPress={() => onOpenPayload(buildMermaidPayload(block.text))}
+ style={StyleSheet.absoluteFill}
+ testID="message.mermaidPreviewTap"
+ />
+ ) : null}
+ </View>
+ );
+ }
+ if (block.type === 'math') {
+ // display 公式:WebView + KaTeX(形态对齐 mermaid 块,无 chip 卡壳——
+ // 公式在视觉上是正文的一部分,背景与气泡底色一致)。
+ return (
+ <ViewabilityGatedMathFormula
+ key={block.key}
+ source={block.text}
+ testID="message.mathFormula"
+ />
+ );
+ }
+ if (block.type === 'code') {
+ // 围栏代码在气泡内换行,不用横向 ScrollView:后者在展开长用户消息时
+ // 会按未折行内容报出超高,气泡巨幅空白并把每行裁在右侧圆角外。
+ return (
+ <View key={block.key} style={styles.markdownCodeFrame}>
+ <View
+ style={[
+ styles.markdownCodeContent,
+ {
+ paddingHorizontal: layout.codePaddingHorizontal,
+ paddingVertical: layout.codePaddingVertical,
+ },
+ ]}
+ >
+ <HighlightedCodeText
+ SpanComponent={spanFor(selectable === true) ?? Text}
+ allowIosUITextView={allowIosUITextView}
+ language={block.language}
+ selectable={selectable === true}
+ styles={styles}
+ text={block.text}
+ />
+ </View>
+ </View>
+ );
+ }
+ if (block.type === 'heading') {
+ const headingStyle = [
+ styles.markdownHeading,
+ headingSizeStyle(styles, block.level),
+ ];
+ const headingSelectable = inlinesSelectable(block.inlines);
+ return (
+ <MarkdownSelectableText
+ allowIosUITextView={allowIosUITextView}
+ key={block.key}
+ selectable={headingSelectable}
+ style={headingStyle}
+ testID="message.markdownHeading"
+ >
+ {renderInlines(block.inlines, spanFor(headingSelectable))}
+ </MarkdownSelectableText>
+ );
+ }
+ if (block.type === 'blockquote') {
+ return (
+ <View key={block.key} style={styles.markdownQuote} testID="message.markdownQuote">
+ <MarkdownSelectableText
+ allowIosUITextView={allowIosUITextView}
+ selectable={inlinesSelectable(block.inlines)}
+ style={[styles.messageText, styles.markdownQuoteText]}
+ >
+ {renderInlines(block.inlines, spanFor(inlinesSelectable(block.inlines)))}
+ </MarkdownSelectableText>
+ </View>
+ );
+ }
+ if (block.type === 'list_item') {
+ const task = typeof block.checked === 'boolean';
+ return (
+ <View
+ key={block.key}
+ style={[styles.markdownListRow, { gap: layout.markdownListGap }]}
+ testID={task ? 'message.markdownTaskItem' : undefined}
+ >
+ <Text style={[
+ styles.markdownListMarker,
+ { width: layout.markdownListMarkerWidth },
+ task && styles.markdownTaskMarker,
+ ]}>
+ {task ? (block.checked ? '✓' : '') : block.ordered ? block.marker : '•'}
+ </Text>
+ <MarkdownSelectableText
+ allowIosUITextView={allowIosUITextView}
+ selectable={inlinesSelectable(block.inlines)}
+ style={[styles.messageText, styles.markdownListText]}
+ >
+ {renderInlines(block.inlines, spanFor(inlinesSelectable(block.inlines)))}
+ </MarkdownSelectableText>
+ </View>
+ );
+ }
+ if (block.type === 'table') {
+ const columnWidths = buildMobileMarkdownTableColumnWidths({
+ header: block.header,
+ rows: block.rows,
+ availableWidth: layout.markdownTableAvailableWidth,
+ minWidth: layout.markdownTableCellMinWidth,
+ });
+ return (
+ <ScrollView
+ horizontal
+ key={block.key}
+ style={styles.markdownTableScroll}
+ testID="message.markdownTable"
+ >
+ <View style={styles.markdownTable}>
+ <View style={[styles.markdownTableRow, styles.markdownTableHeaderRow]}>
+ {columnWidths.map((columnWidth, index) => {
+ const cell = block.header[index] ?? [];
+ return (
+ <MarkdownSelectableText
+ allowIosUITextView={allowIosUITextView}
+ key={`${block.key}:th:${index}`}
+ selectable={inlinesSelectable(cell)}
+ style={[
+ styles.markdownTableCell,
+ { width: columnWidth },
+ styles.markdownTableHeaderCell,
+ ]}
+ >
+ {renderInlines(cell, spanFor(inlinesSelectable(cell)))}
+ </MarkdownSelectableText>
+ );
+ })}
+ </View>
+ {block.rows.map((row) => (
+ <View key={row.key} style={styles.markdownTableRow}>
+ {columnWidths.map((columnWidth, index) => {
+ const cell = row.cells[index] ?? [];
+ return (
+ <MarkdownSelectableText
+ allowIosUITextView={allowIosUITextView}
+ key={`${row.key}:td:${index}`}
+ selectable={inlinesSelectable(cell)}
+ style={[styles.markdownTableCell, { width: columnWidth }]}
+ >
+ {renderInlines(cell, spanFor(inlinesSelectable(cell)))}
+ </MarkdownSelectableText>
+ );
+ })}
+ </View>
+ ))}
+ </View>
+ </ScrollView>
+ );
+ }
+ return (
+ <MarkdownSelectableText
+ allowIosUITextView={allowIosUITextView}
+ key={`${block.key}:${pinSettledWidth ? contentWidth : 'hug'}`}
+ selectable={inlinesSelectable(block.inlines)}
+ style={settledTextStyle}
+ >
+ {renderInlines(block.inlines, spanFor(inlinesSelectable(block.inlines)))}
+ </MarkdownSelectableText>
+ );
+ }, [allowIosUITextView, contentWidth, inlinesSelectable, layout, onOpenPayload, pinSettledWidth, renderInlines, selectable, settledTextStyle, spanFor, styles, t]);
return (
<View
collapsable={false}
@@ -5192,189 +5395,9 @@ function MarkdownBody({
style={pinSettledWidth ? { width: contentWidth, maxWidth: '100%' } : null}
>
{groups.flatMap((group, groupIndex) => {
- const renderedGroup = (() => {
- if (group.type === 'text_run') {
- return renderTextRun(group);
- }
- const block = group.block;
- if (block.type === 'mermaid') {
- // 内联图表按「图片」形态呈现:无卡片 chrome、无标签文字、无按钮,
- // 就是一块圆角图表;点击任意位置打开沉浸式全屏详情(透明 Pressable
- // 盖住整块——WebView 会吞掉触摸事件,不盖层拿不到点击)。
- return (
- <View key={block.key} testID="message.mermaidPreviewButton">
- <ViewabilityGatedMermaidDiagram source={block.text} testID="message.mermaidDiagram" />
- {onOpenPayload ? (
- <Pressable
- accessibilityLabel={t('message.renderer.openDiagramDetail')}
- accessibilityRole="button"
- onPress={() => onOpenPayload(buildMermaidPayload(block.text))}
- style={StyleSheet.absoluteFill}
- testID="message.mermaidPreviewTap"
- />
- ) : null}
- </View>
- );
- }
- if (block.type === 'math') {
- // display 公式:WebView + KaTeX(形态对齐 mermaid 块,无 chip 卡壳——
- // 公式在视觉上是正文的一部分,背景与气泡底色一致)。
- return (
- <ViewabilityGatedMathFormula
- key={block.key}
- source={block.text}
- testID="message.mathFormula"
- />
- );
- }
- if (block.type === 'code') {
- // 围栏代码在气泡内换行,不用横向 ScrollView:后者在展开长用户消息时
- // 会按未折行内容报出超高,气泡巨幅空白并把每行裁在右侧圆角外。
- return (
- <View key={block.key} style={styles.markdownCodeFrame}>
- <View
- style={[
- styles.markdownCodeContent,
- {
- paddingHorizontal: layout.codePaddingHorizontal,
- paddingVertical: layout.codePaddingVertical,
- },
- ]}
- >
- <HighlightedCodeText
- SpanComponent={spanFor(selectable === true) ?? Text}
- allowIosUITextView={allowIosUITextView}
- language={block.language}
- selectable={selectable === true}
- styles={styles}
- text={block.text}
- />
- </View>
- </View>
- );
- }
- if (block.type === 'heading') {
- const headingStyle = [
- styles.markdownHeading,
- headingSizeStyle(styles, block.level),
- ];
- const headingSelectable = inlinesSelectable(block.inlines);
- return (
- <MarkdownSelectableText
- allowIosUITextView={allowIosUITextView}
- key={block.key}
- selectable={headingSelectable}
- style={headingStyle}
- testID="message.markdownHeading"
- >
- {renderInlines(block.inlines, spanFor(headingSelectable))}
- </MarkdownSelectableText>
- );
- }
- if (block.type === 'blockquote') {
- return (
- <View key={block.key} style={styles.markdownQuote} testID="message.markdownQuote">
- <MarkdownSelectableText
- allowIosUITextView={allowIosUITextView}
- selectable={inlinesSelectable(block.inlines)}
- style={[styles.messageText, styles.markdownQuoteText]}
- >
- {renderInlines(block.inlines, spanFor(inlinesSelectable(block.inlines)))}
- </MarkdownSelectableText>
- </View>
- );
- }
- if (block.type === 'list_item') {
- const task = typeof block.checked === 'boolean';
- return (
- <View
- key={block.key}
- style={[styles.markdownListRow, { gap: layout.markdownListGap }]}
- testID={task ? 'message.markdownTaskItem' : undefined}
- >
- <Text style={[
- styles.markdownListMarker,
- { width: layout.markdownListMarkerWidth },
- task && styles.markdownTaskMarker,
- ]}>
- {task ? (block.checked ? '✓' : '') : block.ordered ? block.marker : '•'}
- </Text>
- <MarkdownSelectableText
- allowIosUITextView={allowIosUITextView}
- selectable={inlinesSelectable(block.inlines)}
- style={[styles.messageText, styles.markdownListText]}
- >
- {renderInlines(block.inlines, spanFor(inlinesSelectable(block.inlines)))}
- </MarkdownSelectableText>
- </View>
- );
- }
- if (block.type === 'table') {
- const columnWidths = buildMobileMarkdownTableColumnWidths({
- header: block.header,
- rows: block.rows,
- availableWidth: layout.markdownTableAvailableWidth,
- minWidth: layout.markdownTableCellMinWidth,
- });
- return (
- <ScrollView
- horizontal
- key={block.key}
- style={styles.markdownTableScroll}
- testID="message.markdownTable"
- >
- <View style={styles.markdownTable}>
- <View style={[styles.markdownTableRow, styles.markdownTableHeaderRow]}>
- {columnWidths.map((columnWidth, index) => {
- const cell = block.header[index] ?? [];
- return (
- <MarkdownSelectableText
- allowIosUITextView={allowIosUITextView}
- key={`${block.key}:th:${index}`}
- selectable={inlinesSelectable(cell)}
- style={[
- styles.markdownTableCell,
- { width: columnWidth },
- styles.markdownTableHeaderCell,
- ]}
- >
- {renderInlines(cell, spanFor(inlinesSelectable(cell)))}
- </MarkdownSelectableText>
- );
- })}
- </View>
- {block.rows.map((row) => (
- <View key={row.key} style={styles.markdownTableRow}>
- {columnWidths.map((columnWidth, index) => {
- const cell = row.cells[index] ?? [];
- return (
- <MarkdownSelectableText
- allowIosUITextView={allowIosUITextView}
- key={`${row.key}:td:${index}`}
- selectable={inlinesSelectable(cell)}
- style={[styles.markdownTableCell, { width: columnWidth }]}
- >
- {renderInlines(cell, spanFor(inlinesSelectable(cell)))}
- </MarkdownSelectableText>
- );
- })}
- </View>
- ))}
- </View>
- </ScrollView>
- );
- }
- return (
- <MarkdownSelectableText
- allowIosUITextView={allowIosUITextView}
- key={`${block.key}:${pinSettledWidth ? contentWidth : 'hug'}`}
- selectable={inlinesSelectable(block.inlines)}
- style={settledTextStyle}
- >
- {renderInlines(block.inlines, spanFor(inlinesSelectable(block.inlines)))}
- </MarkdownSelectableText>
- );
- })();
+ const renderedGroup = group.type === 'text_run'
+ ? renderTextRun(group)
+ : <MarkdownBlockContent key={group.key} block={group.block} renderBlock={renderSingleBlock} />;
if (groupIndex === 0 || isTextRunContinuationGroup(group)) {
return [renderedGroup];
}
diff --git a/apps/mobile/src/session/useMarkdownSessionLinkTitles.ts b/apps/mobile/src/session/useMarkdownSessionLinkTitles.ts
new file mode 100644
index 0000000000..1a41d68a20
--- /dev/null
+++ b/apps/mobile/src/session/useMarkdownSessionLinkTitles.ts
@@ -0,0 +1,23 @@
+import { useMemo } from 'react';
+import { extractSessionLinkIds } from '@/session/sessionLinks';
+
+/** Stable render context: only a referenced title changing invalidates spans. */
+export function useMarkdownSessionLinkTitles(
+ text: string,
+ sessions: readonly { id: string; title?: string | null }[],
+): Record<string, string> | undefined {
+ const idsJson = useMemo(() => JSON.stringify(extractSessionLinkIds(text)), [text]);
+ const titlesJson = useMemo(() => {
+ const ids = JSON.parse(idsJson) as string[];
+ if (ids.length === 0) return undefined;
+ const titles: Record<string, string> = {};
+ for (const id of ids) {
+ const title = sessions.find((session) => session.id === id)?.title?.trim();
+ if (title) titles[id] = title;
+ }
+ return Object.keys(titles).length > 0 ? JSON.stringify(titles) : undefined;
+ }, [idsJson, sessions]);
+ return useMemo(() => titlesJson === undefined
+ ? undefined
+ : JSON.parse(titlesJson) as Record<string, string>, [titlesJson]);
+}
diff --git a/apps/mobile/src/session/workActivityProjection.ts b/apps/mobile/src/session/workActivityProjection.ts
index 5945e93f6a..16c813ae30 100644
--- a/apps/mobile/src/session/workActivityProjection.ts
+++ b/apps/mobile/src/session/workActivityProjection.ts
@@ -22,6 +22,22 @@ export type MobileProjectedThinkingActivity = ProjectedThinkingActivity;
export type MobileProjectedWorkActivity = ProjectedWorkActivity<MobileWorkActivityMessage>;
export type MobileWorkActivityProjection = WorkActivityProjection<MobileWorkActivityMessage>;
+/** Compare the data consumed by WorkToolActivityRow, not projection wrappers. */
+export function sameMobileWorkToolActivity(
+ previous: MobileProjectedToolActivity,
+ next: MobileProjectedToolActivity,
+): boolean {
+ return previous === next || (
+ previous.key === next.key
+ && previous.message.normalized === next.message.normalized
+ && previous.status === next.status
+ && previous.toolResult === next.toolResult
+ && previous.intentOverride?.action === next.intentOverride?.action
+ && previous.intentOverride?.target === next.intentOverride?.target
+ && previous.intentOverride?.path === next.intentOverride?.path
+ );
+}
+
function readRecord(value: unknown): Record<string, unknown> | null {
return value && typeof value === 'object' && !Array.isArray(value)
? value as Record<string, unknown>