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): 轻量化已完成工具输入驻留 (#3855)

DavidShenXD78a98708c46b
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 9683683c15..287a56282f 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -461,6 +461,11 @@ import {
shouldRefreshLatestMessageWindowOnReopen,
shouldKeepOlderMessagesAffordance,
} from '@/session/messagePaging';
+import {
+ fetchMobileToolInputDetail,
+ type MobileToolInputDetail,
+ type MobileToolInputProjection,
+} from '@/session/messageToolPayloadProjection';
import {
HISTORY_BACKFILL_MAX_GAPS_PER_VISIT,
HISTORY_GAP_MAX_CONSIDERED_PER_VISIT,
@@ -5003,6 +5008,16 @@ export default function SessionScreen() {
}
}, [abandonInFlightBackfill, deviceId, hasOlderMessages, isScheduleDetail, loadingEarlier, maker, oldestLoadedMessageCursor, sessionId]);
+ const loadToolInput = useCallback(async (
+ ref: MobileToolInputProjection,
+ ): Promise<MobileToolInputDetail> => {
+ if (!deviceId) throw new Error('tool input device is unavailable');
+ return fetchMobileToolInputDetail(
+ ref,
+ (messageId, options) => maker.aroundMessages(sessionId, messageId, options),
+ );
+ }, [deviceId, maker, sessionId]);
+
/**
* 历史窗口空洞的自动补齐(见 `historyWindowGap.ts` 的文件头)。
*
@@ -9544,6 +9559,7 @@ export default function SessionScreen() {
onDeleteMessage={collaborationReadOnlyReason ? undefined : deleteMessage}
onForkMessage={collaborationReadOnlyReason ? undefined : forkAtMessage}
onLoadEarlier={loadEarlierMessages}
+ onLoadToolInput={loadToolInput}
onOpenForkOrigin={forkOrigin ? openForkOrigin : undefined}
onBlockingOverlayChange={handleMessageBlockingOverlayChange}
onOpenSessionLink={openSessionLink}
diff --git a/apps/mobile/src/__tests__/messageNormalize.test.ts b/apps/mobile/src/__tests__/messageNormalize.test.ts
index 74b13f65ed..1e9099ff0c 100644
--- a/apps/mobile/src/__tests__/messageNormalize.test.ts
+++ b/apps/mobile/src/__tests__/messageNormalize.test.ts
@@ -7,6 +7,10 @@ import {
import { composerDocumentFromSerializedMessage } from '@/session/composerDocument';
import { buildMobileMessageCopyText } from '@/session/messageActions';
import { normalizeRemoteMessages } from '@/session/messageNormalize';
+import {
+ MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES,
+ projectLargeSettledToolInputs,
+} from '@/session/messageToolPayloadProjection';
import type { RemoteMessage } from '@/session/types';
function message(patch: Partial<RemoteMessage> & Pick<RemoteMessage, 'id' | 'role' | 'content'>): RemoteMessage {
@@ -25,6 +29,41 @@ describe('normalizeRemoteMessages', () => {
await i18n.changeLanguage('zh-CN');
});
+ it('renders a projected large tool input from its bounded summary and keeps its result', () => {
+ const projected = projectLargeSettledToolInputs([
+ message({
+ id: 'large-tool',
+ role: 'tool_use',
+ toolUseId: 'toolu-large',
+ content: {
+ input: { payload: 'x'.repeat(MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES + 1) },
+ toolName: 'WebFetch',
+ toolUseId: 'toolu-large',
+ },
+ }),
+ message({
+ id: 'large-result',
+ role: 'tool_result',
+ toolUseId: 'toolu-large',
+ content: 'finished',
+ createdAt: '2026-01-01T00:00:01.000Z',
+ }),
+ ]);
+
+ const [item] = normalizeRemoteMessages(projected);
+ expect(item).toMatchObject({
+ kind: 'tool',
+ label: 'WebFetch',
+ secondaryBody: 'finished',
+ toolSettled: true,
+ toolInputProjection: {
+ projected: true,
+ toolUseMessageId: 'large-tool',
+ },
+ });
+ expect(item.body.length).toBeLessThanOrEqual(480);
+ });
+
it('projects a persisted agent task terminal state from tool_use metadata', () => {
const [item] = normalizeRemoteMessages([
message({
diff --git a/apps/mobile/src/__tests__/messageToolPayloadProjection.test.ts b/apps/mobile/src/__tests__/messageToolPayloadProjection.test.ts
new file mode 100644
index 0000000000..b62ce88968
--- /dev/null
+++ b/apps/mobile/src/__tests__/messageToolPayloadProjection.test.ts
@@ -0,0 +1,222 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ buildMobileToolInputDetail,
+ fetchMobileToolInputDetail,
+ MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES,
+ projectLargeSettledToolInputs,
+} from '@/session/messageToolPayloadProjection';
+import type { RemoteMessage } from '@/session/types';
+
+function message(
+ id: string,
+ role: RemoteMessage['role'],
+ content: unknown,
+ toolUseId: string | null,
+ patch: Partial<RemoteMessage> = {},
+): RemoteMessage {
+ return {
+ id,
+ clientId: id,
+ sessionId: 'session-1',
+ role,
+ content,
+ toolUseId,
+ agentMeta: null,
+ createdAt: `2026-01-01T00:00:0${id.endsWith('result') ? '2' : '1'}.000Z`,
+ ...patch,
+ };
+}
+
+function toolPair(
+ toolName: string,
+ input: unknown,
+ patch: Partial<RemoteMessage> = {},
+): RemoteMessage[] {
+ return [
+ message('tool-use', 'tool_use', { input, toolName, toolUseId: 'toolu-1' }, 'toolu-1', patch),
+ message('tool-result', 'tool_result', 'ok', 'toolu-1'),
+ ];
+}
+
+describe('projectLargeSettledToolInputs', () => {
+ it('projects a persisted ordinary tool only after its exact result arrives', () => {
+ const input = { payload: 'x'.repeat(MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES + 1) };
+ const projected = projectLargeSettledToolInputs(toolPair('WebFetch', input));
+
+ expect(projected[0]).toMatchObject({
+ content: {
+ input: null,
+ mobilePayloadProjected: true,
+ toolName: 'WebFetch',
+ toolUseId: 'toolu-1',
+ },
+ mobileToolInputProjection: {
+ projected: true,
+ toolName: 'WebFetch',
+ toolUseId: 'toolu-1',
+ toolUseMessageId: 'tool-use',
+ version: 1,
+ },
+ });
+ expect(projected[0].mobileToolInputProjection).not.toHaveProperty('originalBytes');
+ expect(projected[1].content).toBe('ok');
+ });
+
+ it('keeps small, unsettled, unpersisted, or remotely truncated inputs intact', () => {
+ const largeInput = { payload: 'x'.repeat(MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES + 1) };
+ const small = toolPair('WebFetch', { payload: 'small' });
+ const unsettled = toolPair('WebFetch', largeInput).slice(0, 1);
+ const unpersisted = toolPair('WebFetch', largeInput, { id: '' });
+ const truncated = toolPair('WebFetch', largeInput, {
+ agentMeta: { remoteContentTruncated: true },
+ });
+
+ for (const rows of [small, unsettled, unpersisted, truncated]) {
+ expect(projectLargeSettledToolInputs(rows)[0].mobileToolInputProjection).toBeUndefined();
+ }
+ });
+
+ it('requires exact toolUseId pairing instead of adjacent result guessing', () => {
+ const rows = toolPair('WebFetch', {
+ payload: 'x'.repeat(MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES + 1),
+ });
+ rows[1] = { ...rows[1], toolUseId: 'another-tool' };
+
+ expect(projectLargeSettledToolInputs(rows)[0].mobileToolInputProjection).toBeUndefined();
+ });
+
+ it.each([
+ ['Agent', { prompt: 'x' }],
+ ['update_plan', { plan: [{ status: 'in_progress', step: 'x' }] }],
+ ['send_to_worker', { message: 'x', target_session_id: 'worker-1' }],
+ ['Edit', { file_path: '/repo/a.ts', old_string: 'a', new_string: 'b' }],
+ ])('preserves structural %s tool inputs', (toolName, seedInput) => {
+ const input = { ...seedInput, padding: 'x'.repeat(MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES + 1) };
+ expect(projectLargeSettledToolInputs(toolPair(toolName, input))[0].mobileToolInputProjection)
+ .toBeUndefined();
+ });
+
+ it('counts UTF-8 bytes instead of UTF-16 code units', () => {
+ const input = '界'.repeat(Math.ceil(MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES / 3) + 1);
+ const projected = projectLargeSettledToolInputs(toolPair('WebFetch', input));
+
+ expect(input.length).toBeLessThan(MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES);
+ expect(projected[0].mobileToolInputProjection).toBeDefined();
+ });
+
+ it('includes JSON syntax and escaping while applying the byte threshold', () => {
+ const syntaxBytes = '{"payload":""}'.length;
+ const exact = { payload: 'x'.repeat(MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES - syntaxBytes) };
+ const over = { payload: 'x'.repeat(MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES - syntaxBytes + 1) };
+
+ expect(projectLargeSettledToolInputs(toolPair('WebFetch', exact))[0]
+ .mobileToolInputProjection).toBeUndefined();
+ expect(projectLargeSettledToolInputs(toolPair('WebFetch', over))[0]
+ .mobileToolInputProjection).toBeDefined();
+ });
+
+ it('stops inspecting a large input as soon as the threshold is crossed', () => {
+ let latePropertyRead = false;
+ const input = {
+ payload: 'x'.repeat(MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES + 1),
+ get unreadTail() {
+ latePropertyRead = true;
+ return 'not reached';
+ },
+ };
+ const stringify = vi.spyOn(JSON, 'stringify');
+
+ try {
+ expect(projectLargeSettledToolInputs(toolPair('WebFetch', input))[0]
+ .mobileToolInputProjection).toBeDefined();
+ expect(latePropertyRead).toBe(false);
+ expect(stringify).not.toHaveBeenCalled();
+ } finally {
+ stringify.mockRestore();
+ }
+ });
+
+ it('is idempotent for an already projected row', () => {
+ const first = projectLargeSettledToolInputs(toolPair('WebFetch', {
+ payload: 'x'.repeat(MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES + 1),
+ }));
+ const second = projectLargeSettledToolInputs(first);
+
+ expect(second[0]).toBe(first[0]);
+ });
+
+ it('does not inspect the same settled small input again on later normalizations', () => {
+ let inspectionCount = 0;
+ const rows = toolPair('WebFetch', {
+ get payload() {
+ inspectionCount += 1;
+ return 'small';
+ },
+ });
+
+ expect(projectLargeSettledToolInputs(rows)[0].mobileToolInputProjection).toBeUndefined();
+ expect(projectLargeSettledToolInputs(rows)[0].mobileToolInputProjection).toBeUndefined();
+ expect(inspectionCount).toBe(1);
+ });
+});
+
+describe('buildMobileToolInputDetail', () => {
+ it('restores the full input from the exact authoritative tool row', () => {
+ const fullInput = {
+ nested: { value: 'x'.repeat(MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES + 1) },
+ };
+ const rows = toolPair('WebFetch', fullInput);
+ const projected = projectLargeSettledToolInputs(rows);
+ const ref = projected[0].mobileToolInputProjection!;
+
+ const detail = buildMobileToolInputDetail(rows, ref);
+ expect(detail?.toolName).toBe('WebFetch');
+ expect(detail?.body).toBe(JSON.stringify(fullInput, null, 2));
+ expect(detail?.body.length).toBeGreaterThan(MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES);
+ });
+
+ it('rejects missing, mismatched, truncated, or still-projected rows', () => {
+ const original = toolPair('WebFetch', {
+ payload: 'x'.repeat(MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES + 1),
+ });
+ const projected = projectLargeSettledToolInputs(original);
+ const ref = projected[0].mobileToolInputProjection!;
+
+ expect(buildMobileToolInputDetail([], ref)).toBeNull();
+ expect(buildMobileToolInputDetail([
+ { ...original[0], content: { input: {}, toolName: 'Other', toolUseId: 'toolu-1' } },
+ ], ref)).toBeNull();
+ expect(buildMobileToolInputDetail([
+ { ...original[0], agentMeta: { remoteContentTruncated: true } },
+ ], ref)).toBeNull();
+ expect(buildMobileToolInputDetail(projected, ref)).toBeNull();
+ });
+});
+
+describe('fetchMobileToolInputDetail', () => {
+ it('requests only the authoritative tool row and returns its full input', async () => {
+ const rows = toolPair('WebFetch', {
+ payload: 'x'.repeat(MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES + 1),
+ });
+ const ref = projectLargeSettledToolInputs(rows)[0].mobileToolInputProjection!;
+ const calls: Array<{ messageId: string; radius: number }> = [];
+
+ const detail = await fetchMobileToolInputDetail(ref, async (messageId, options) => {
+ calls.push({ messageId, radius: options.radius });
+ return rows;
+ });
+
+ expect(calls).toEqual([{ messageId: 'tool-use', radius: 0 }]);
+ expect(detail.body.length).toBeGreaterThan(MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES);
+ });
+
+ it('rejects when the authoritative row cannot restore the projected input', async () => {
+ const rows = toolPair('WebFetch', {
+ payload: 'x'.repeat(MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES + 1),
+ });
+ const ref = projectLargeSettledToolInputs(rows)[0].mobileToolInputProjection!;
+
+ await expect(fetchMobileToolInputDetail(ref, async () => [])).rejects
+ .toThrow('tool input is unavailable');
+ });
+});
diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
index ff7e42f4aa..6ccb27028c 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { MAKER_EVENT_BATCH_CHANNEL } from '@cindy/device-link';
import { clampLiveRowCreatedAt } from '@/session/messagePaging';
+import { MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES } from '@/session/messageToolPayloadProjection';
import { remoteSessionStore, sessionPendingWrites } from '@/session/remoteSessionStore';
import type { InputProjection, PendingInteraction, RemoteMessage, RemoteSession } from '@/session/types';
@@ -134,6 +135,36 @@ function pending(kind: string, requestId?: string, persistId?: string): PendingI
describe('remoteSessionStore', () => {
beforeEach(() => remoteSessionStore.clear());
+ it('releases a large persisted tool input when the matching result is appended', () => {
+ remoteSessionStore.setMessages('s1', [{
+ ...message('tool-use', 's1'),
+ role: 'tool_use',
+ toolUseId: 'toolu-1',
+ content: {
+ input: { payload: 'x'.repeat(MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES + 1) },
+ toolName: 'WebFetch',
+ toolUseId: 'toolu-1',
+ },
+ }]);
+ expect(remoteSessionStore.getMessages('s1')[0].mobileToolInputProjection).toBeUndefined();
+
+ remoteSessionStore.appendMessage('s1', {
+ ...message('tool-result', 's1'),
+ role: 'tool_result',
+ toolUseId: 'toolu-1',
+ content: 'finished',
+ createdAt: '2026-01-01T00:00:01.000Z',
+ });
+
+ expect(remoteSessionStore.getMessages('s1')[0]).toMatchObject({
+ content: { input: null, mobilePayloadProjected: true },
+ mobileToolInputProjection: {
+ projected: true,
+ toolUseMessageId: 'tool-use',
+ },
+ });
+ });
+
it('normalizes same-timestamp messages by host rowid', () => {
const createdAt = '2026-01-01T00:00:00.000Z';
remoteSessionStore.setMessages('s1', [
diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.json
index f1de4c0451..286c894bb5 100644
--- a/apps/mobile/src/i18n/locales/en/message.json
+++ b/apps/mobile/src/i18n/locales/en/message.json
@@ -116,6 +116,10 @@
"controlFork": "Fork session",
"markdownDocAriaLabel": "Message body",
"toolOutputTitle": "{{label}} output",
+ "toolInputTitle": "{{label}} input",
+ "viewToolInput": "View full input",
+ "loadingToolInput": "Loading full input",
+ "retryToolInput": "Couldn't load input. Retry",
"toolResultCompacted": "Full tool output was released (original size {{size}})",
"mermaidEmpty": "Empty Mermaid diagram.",
"diffEditCount": "{{n}} edits"
diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.json
index 2409d98495..6dcb9a3dfd 100644
--- a/apps/mobile/src/i18n/locales/ja/message.json
+++ b/apps/mobile/src/i18n/locales/ja/message.json
@@ -116,6 +116,10 @@
"controlFork": "セッションを分岐",
"markdownDocAriaLabel": "メッセージ本文",
"toolOutputTitle": "{{label}} の出力",
+ "toolInputTitle": "{{label}} の入力",
+ "viewToolInput": "完全な入力を表示",
+ "loadingToolInput": "完全な入力を読み込み中",
+ "retryToolInput": "入力を読み込めませんでした。再試行",
"toolResultCompacted": "Full tool output was released (original size {{size}})",
"mermaidEmpty": "空の Mermaid 図。",
"diffEditCount": "{{n}} 件の編集"
diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.json
index be863a205c..8412489233 100644
--- a/apps/mobile/src/i18n/locales/ko/message.json
+++ b/apps/mobile/src/i18n/locales/ko/message.json
@@ -116,6 +116,10 @@
"controlFork": "세션 분기",
"markdownDocAriaLabel": "메시지 본문",
"toolOutputTitle": "{{label}} 출력",
+ "toolInputTitle": "{{label}} 입력",
+ "viewToolInput": "전체 입력 보기",
+ "loadingToolInput": "전체 입력 불러오는 중",
+ "retryToolInput": "입력을 불러오지 못했습니다. 다시 시도",
"toolResultCompacted": "Full tool output was released (original size {{size}})",
"mermaidEmpty": "빈 Mermaid 다이어그램.",
"diffEditCount": "{{n}}개 편집"
diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.json
index 31e2b4f016..e76d09dbb5 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/message.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json
@@ -116,6 +116,10 @@
"controlFork": "分叉任务",
"markdownDocAriaLabel": "消息正文",
"toolOutputTitle": "{{label}} 输出",
+ "toolInputTitle": "{{label}} 输入",
+ "viewToolInput": "查看完整输入",
+ "loadingToolInput": "正在读取完整输入",
+ "retryToolInput": "读取失败,重试",
"toolResultCompacted": "Full tool output was released (original size {{size}})",
"mermaidEmpty": "空 Mermaid 图表。",
"diffEditCount": "{{n}} 处编辑"
diff --git a/apps/mobile/src/i18n/locales/zh-TW/message.json b/apps/mobile/src/i18n/locales/zh-TW/message.json
index 10dedc99e8..ff3b6b1f4b 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/message.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/message.json
@@ -116,6 +116,10 @@
"controlFork": "分叉任務",
"markdownDocAriaLabel": "訊息正文",
"toolOutputTitle": "{{label}} 輸出",
+ "toolInputTitle": "{{label}} 輸入",
+ "viewToolInput": "查看完整輸入",
+ "loadingToolInput": "正在讀取完整輸入",
+ "retryToolInput": "讀取失敗,重試",
"toolResultCompacted": "Full tool output was released (original size {{size}})",
"mermaidEmpty": "空 Mermaid 圖表。",
"diffEditCount": "{{n}} 處編輯"
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index 06a10d874f..3123ecdc0a 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -118,12 +118,17 @@ import type {
NormalizedToolDiff,
NormalizedToolMedia,
} from '@/session/messageNormalize';
+import type {
+ MobileToolInputDetail,
+ MobileToolInputProjection,
+} from '@/session/messageToolPayloadProjection';
import {
buildAttachmentPayload,
buildDiffPayload,
buildFilePayload,
buildMediaPayload,
buildMermaidPayload,
+ buildTextPayload,
buildToolResultPayload,
formatDiffPayloadView,
payloadMediaKindLabel,
@@ -589,6 +594,7 @@ interface MessageActions {
onLoadEarlier?: () => void | Promise<void>;
onOpenForkOrigin?: () => void;
onOpenPayload?: (payload: MessagePayload) => void;
+ onLoadToolInput?: (ref: MobileToolInputProjection) => Promise<MobileToolInputDetail>;
onBlockingOverlayChange?: (blocked: boolean) => void;
onMessageActionSheetOpenChange?: (clientId: string, open: boolean) => void;
/** 正文里会话深链 chip(xdt-maker://session/…)点击回调,app 内跳转。 */
@@ -631,6 +637,7 @@ export function MessageRenderer({
onForkMessage,
onDeleteMessage,
onLoadEarlier,
+ onLoadToolInput,
onOpenForkOrigin,
onBlockingOverlayChange,
onOpenSessionLink,
@@ -1481,6 +1488,7 @@ export function MessageRenderer({
onEnterShareSelection,
onShareableMessageViewChange: handleShareableMessageViewChange,
onOpenPayload: setPayload,
+ onLoadToolInput,
onMessageActionSheetOpenChange: handleMessageActionSheetOpenChange,
onResolveRemoteMedia,
// 待发送气泡(pending_send 项)的展开态与队列操作:漏了这一项 actions.pendingSend 就是
@@ -1511,6 +1519,7 @@ export function MessageRenderer({
onDeleteMessage,
onForkMessage,
onOpenForkOrigin,
+ onLoadToolInput,
onOpenSessionLink,
onPreviewRewind,
onEnterShareSelection,
@@ -3718,6 +3727,13 @@ function ToolActionRow({
{row.detail || tool.body ? (
<Text style={styles.toolRowDetailText}>{row.detail ?? tool.body}</Text>
) : null}
+ {tool.toolInputProjection ? (
+ <ProjectedToolInputButton
+ key={tool.toolInputProjection.toolUseMessageId}
+ actions={actions}
+ projection={tool.toolInputProjection}
+ />
+ ) : null}
{tool.diff ? <DiffPreview diff={tool.diff} layout={contentLayout} onOpen={actions.onOpenPayload} /> : null}
{tool.secondaryBody ? <ToolResultPreview layout={contentLayout} tool={tool} onOpen={actions.onOpenPayload} /> : null}
</View>
@@ -3726,6 +3742,63 @@ function ToolActionRow({
);
}
+function ProjectedToolInputButton({
+ actions,
+ projection,
+}: {
+ actions: MessageActions;
+ projection: MobileToolInputProjection;
+}) {
+ const { colors } = useTheme();
+ const { t } = useTranslation();
+ const styles = useThemedStyles(makeStyles);
+ const [status, setStatus] = useState<'error' | 'idle' | 'loading'>('idle');
+ const requestSeqRef = useRef(0);
+
+ useEffect(() => () => {
+ requestSeqRef.current += 1;
+ }, []);
+
+ const openFullInput = useCallback(() => {
+ if (!actions.onLoadToolInput || !actions.onOpenPayload || status === 'loading') return;
+ const requestSeq = requestSeqRef.current + 1;
+ requestSeqRef.current = requestSeq;
+ setStatus('loading');
+ void actions.onLoadToolInput(projection).then((detail) => {
+ if (requestSeqRef.current !== requestSeq) return;
+ setStatus('idle');
+ actions.onOpenPayload?.(buildTextPayload(
+ t('message.renderer.toolInputTitle', { label: detail.toolName }),
+ detail.body,
+ ));
+ }).catch(() => {
+ if (requestSeqRef.current === requestSeq) setStatus('error');
+ });
+ }, [actions, projection, status, t]);
+
+ const label = status === 'loading'
+ ? t('message.renderer.loadingToolInput')
+ : status === 'error'
+ ? t('message.renderer.retryToolInput')
+ : t('message.renderer.viewToolInput');
+ return (
+ <MessageContentOpenButton
+ accessibilityLabel={label}
+ disabled={status === 'loading'}
+ onPress={openFullInput}
+ style={styles.toolInputPreview}
+ testID="message.toolInputPayloadButton"
+ >
+ <View style={styles.toolInputActionRow}>
+ {status === 'loading' ? (
+ <CompactActivityIndicator color={colors.textTertiary} size={iconSize.sm} />
+ ) : null}
+ <Text style={styles.toolInputActionText}>{label}</Text>
+ </View>
+ </MessageContentOpenButton>
+ );
+}
+
function TodoCard({
animated,
item,
@@ -8347,6 +8420,25 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
fontSize: typeScale.footnote,
lineHeight: lineHeight.caption,
},
+ toolInputPreview: {
+ backgroundColor: colors.chatCodeSurface,
+ borderColor: colors.chatCodeBorder,
+ borderRadius: radius.container,
+ borderWidth: StyleSheet.hairlineWidth,
+ },
+ toolInputActionRow: {
+ alignItems: 'center',
+ flexDirection: 'row',
+ gap: spacing.sm,
+ minHeight: MESSAGE_CONTROL_TOUCH_SIZE,
+ paddingHorizontal: spacing.sm,
+ },
+ toolInputActionText: {
+ color: colors.textTertiary,
+ fontSize: typeScale.caption,
+ fontWeight: fontWeight.medium,
+ lineHeight: lineHeight.caption,
+ },
toolName: {
color: colors.textSecondary,
fontSize: typeScale.listBody,
diff --git a/apps/mobile/src/session/messageNormalize.ts b/apps/mobile/src/session/messageNormalize.ts
index 2e6e85338f..65ab5e9b0b 100644
--- a/apps/mobile/src/session/messageNormalize.ts
+++ b/apps/mobile/src/session/messageNormalize.ts
@@ -51,6 +51,7 @@ import {
localizeToolLoopError,
parseMobileToolLoopErrorDetails,
} from '@/session/toolLoopErrorI18n';
+import type { MobileToolInputProjection } from '@/session/messageToolPayloadProjection';
export type NormalizedRemoteMessageKind =
| 'user'
@@ -108,6 +109,8 @@ export interface NormalizedRemoteMessage {
orcaCard?: OrcaCollabCard;
/** tool 消息专用:tool_result 是否已到达(含被隐藏的 orca 空结果),驱动工具行 running/done 状态。 */
toolSettled?: boolean;
+ /** Large settled tool input is fetched only when the user asks to view it. */
+ toolInputProjection?: MobileToolInputProjection;
/** Durable Agent/Task terminal lifecycle restored from tool_use metadata. */
agentTaskStatus?: AgentTaskTerminalStatus;
/** assistant 专用:是否本轮收尾正文(操作行只挂在收尾正文上,对齐桌面 #456);由 messageRenderModel 标注。 */
@@ -195,6 +198,7 @@ export function normalizeRemoteMessages(messages: readonly RemoteMessage[]): Nor
if (message.role === 'tool_use') {
const tool = parseToolUse(message);
+ const toolInputProjection = message.mobileToolInputProjection;
const agentTaskStatus = normalizeAgentTaskTerminalStatus(
message.agentMeta?.agentTaskStatus,
);
@@ -232,6 +236,7 @@ export function normalizeRemoteMessages(messages: readonly RemoteMessage[]): Nor
// 结束时刻(配对 tool_result 落库时间)驱动渲染层的历史空洞判定,详见共享类型上的说明。
settledAt: toolResultPairing.resultCreatedAtFor(message, tool),
toolSettled: toolResultPairing.hasResultFor(message, tool),
+ ...(toolInputProjection ? { toolInputProjection } : {}),
...(agentTaskStatus ? { agentTaskStatus } : {}),
});
continue;
@@ -500,6 +505,16 @@ function parseToolUse(message: RemoteMessage): ToolUsePayload {
const cached = toolUsePayloadByMessage.get(message);
if (cached) return cached;
const sharedTool = parseMessageToolUse(message);
+ const projection = message.mobileToolInputProjection;
+ if (projection) {
+ const payload = {
+ ...sharedTool,
+ toolName: projection.toolName,
+ summary: projection.summary,
+ };
+ toolUsePayloadByMessage.set(message, payload);
+ return payload;
+ }
const { toolName, input } = sharedTool;
const summary = toolName ? formatToolUseSummary(toolName, input) : contentToPreview(message.content);
const diff = buildToolDiff(toolName, input);
diff --git a/apps/mobile/src/session/messageRenderReconcile.ts b/apps/mobile/src/session/messageRenderReconcile.ts
index cdd383a21f..f92ef6121c 100644
--- a/apps/mobile/src/session/messageRenderReconcile.ts
+++ b/apps/mobile/src/session/messageRenderReconcile.ts
@@ -227,5 +227,6 @@ function remoteMessageEqual(previous: RemoteMessage, next: RemoteMessage): boole
&& previous.systemCardType === next.systemCardType
&& deepValueEqual(previous.content, next.content)
&& deepValueEqual(previous.agentMeta, next.agentMeta)
+ && deepValueEqual(previous.mobileToolInputProjection, next.mobileToolInputProjection)
&& deepValueEqual(previous.systemCardData, next.systemCardData);
}
diff --git a/apps/mobile/src/session/messageToolPayloadProjection.ts b/apps/mobile/src/session/messageToolPayloadProjection.ts
new file mode 100644
index 0000000000..2cf56d1757
--- /dev/null
+++ b/apps/mobile/src/session/messageToolPayloadProjection.ts
@@ -0,0 +1,258 @@
+import { isAgentTaskToolName } from '@cindy/maker-shared/agent-task';
+import {
+ isAgentPlanToolName,
+} from '@cindy/maker-shared/message-render';
+import { parseMessageToolUse } from '@cindy/maker-shared/message-normalize';
+import {
+ buildPayloadToolDiff,
+ formatPayloadToolUseSummary,
+} from '@/session/messagePayload';
+import { classifyOrcaDispatchTool } from '@/session/orcaCollab';
+import type { RemoteMessage } from '@/session/types';
+
+export const MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES = 32 * 1024;
+
+const TOOL_SUMMARY_MAX_CHARS = 480;
+
+// Normalization can revisit the same immutable rows during pagination and refreshes.
+// Remember only that a settled row was evaluated; WeakSet neither retains the row nor
+// keeps any payload bytes alive.
+const evaluatedSettledToolInputs = new WeakSet<RemoteMessage>();
+
+export interface MobileToolInputProjection {
+ projected: true;
+ summary: string;
+ toolName: string;
+ toolUseId: string;
+ toolUseMessageId: string;
+ version: 1;
+}
+
+export interface MobileToolInputDetail {
+ body: string;
+ toolName: string;
+}
+
+export type MobileToolInputAroundLoader = (
+ messageId: string,
+ options: { radius: 0 },
+) => Promise<readonly RemoteMessage[]>;
+
+/**
+ * Release only large, persisted tool inputs after their exact result has arrived.
+ * Tool results are already bounded by the remote transport, while structural tools
+ * need their original input to build Agent, plan, Todo, Orca, and diff render models.
+ */
+export function projectLargeSettledToolInputs(
+ messages: readonly RemoteMessage[],
+): RemoteMessage[] {
+ const settledToolUseIds = new Set<string>();
+ for (const message of messages) {
+ if (message.role !== 'tool_result') continue;
+ const toolUseId = readToolUseId(message);
+ if (toolUseId) settledToolUseIds.add(toolUseId);
+ }
+ if (settledToolUseIds.size === 0) return [...messages];
+
+ return messages.map((message) => {
+ if (
+ message.role !== 'tool_use'
+ || message.mobileToolInputProjection
+ || !message.id
+ || message.agentMeta?.remoteContentTruncated === true
+ ) return message;
+
+ const tool = parseMessageToolUse(message);
+ if (
+ !tool.toolUseId
+ || !settledToolUseIds.has(tool.toolUseId)
+ ) return message;
+ if (evaluatedSettledToolInputs.has(message)) return message;
+ evaluatedSettledToolInputs.add(message);
+ if (!toolInputCanBeProjected(tool.toolName, tool.input)) return message;
+
+ if (!toolInputExceedsProjectionThreshold(tool.input)) return message;
+
+ const summary = limitText(
+ formatPayloadToolUseSummary(tool.toolName, tool.input),
+ TOOL_SUMMARY_MAX_CHARS,
+ );
+ const projection: MobileToolInputProjection = {
+ projected: true,
+ summary,
+ toolName: tool.toolName,
+ toolUseId: tool.toolUseId,
+ toolUseMessageId: message.id,
+ version: 1,
+ };
+ return {
+ ...message,
+ content: {
+ input: null,
+ mobilePayloadProjected: true,
+ toolName: tool.toolName,
+ toolUseId: tool.toolUseId,
+ },
+ mobileToolInputProjection: projection,
+ };
+ });
+}
+
+/** Build the one expanded detail directly from a radius-0 authoritative read. */
+export function buildMobileToolInputDetail(
+ messages: readonly RemoteMessage[],
+ ref: MobileToolInputProjection,
+): MobileToolInputDetail | null {
+ const message = messages.find((candidate) => (
+ candidate.role === 'tool_use' && candidate.id === ref.toolUseMessageId
+ ));
+ if (
+ !message
+ || message.agentMeta?.remoteContentTruncated === true
+ || message.mobileToolInputProjection
+ ) return null;
+
+ const tool = parseMessageToolUse(message);
+ if (tool.toolUseId !== ref.toolUseId || tool.toolName !== ref.toolName) return null;
+ const body = formatFullToolInput(tool.input);
+ return body ? { body, toolName: tool.toolName } : null;
+}
+
+export async function fetchMobileToolInputDetail(
+ ref: MobileToolInputProjection,
+ loadAround: MobileToolInputAroundLoader,
+): Promise<MobileToolInputDetail> {
+ const rows = await loadAround(ref.toolUseMessageId, { radius: 0 });
+ const detail = buildMobileToolInputDetail(rows, ref);
+ if (!detail) throw new Error('tool input is unavailable');
+ return detail;
+}
+
+function toolInputCanBeProjected(toolName: string, input: unknown): boolean {
+ if (!toolName) return false;
+ if (toolName === 'AskUserQuestion' || toolName === 'ExitPlanMode') return false;
+ if (isAgentTaskToolName(toolName) || isAgentPlanToolName(toolName)) return false;
+ if (classifyOrcaDispatchTool(toolName) !== null) return false;
+ return buildPayloadToolDiff(toolName, input) === undefined;
+}
+
+function readToolUseId(message: RemoteMessage): string | null {
+ if (message.toolUseId) return message.toolUseId;
+ if (!message.content || typeof message.content !== 'object' || Array.isArray(message.content)) {
+ return null;
+ }
+ const toolUseId = (message.content as Record<string, unknown>).toolUseId;
+ return typeof toolUseId === 'string' && toolUseId.length > 0 ? toolUseId : null;
+}
+
+interface JsonByteBudget {
+ ancestors: Set<object>;
+ remaining: number;
+}
+
+/** Count decoded JSON until 32 KiB is crossed, without building its full string. */
+function toolInputExceedsProjectionThreshold(input: unknown): boolean {
+ const budget: JsonByteBudget = {
+ ancestors: new Set(),
+ remaining: MOBILE_TOOL_INPUT_PROJECTION_THRESHOLD_BYTES,
+ };
+ return typeof input === 'string'
+ ? consumeUtf8(budget, input, false)
+ : measureJsonValue(budget, input) === true;
+}
+
+/** `true` means over budget; `null` means this is not a decoded JSON value. */
+function measureJsonValue(budget: JsonByteBudget, value: unknown): boolean | null {
+ if (value === null) return consumeAscii(budget, 4);
+ if (typeof value === 'string') return consumeUtf8(budget, value, true);
+ if (typeof value === 'boolean') return consumeAscii(budget, value ? 4 : 5);
+ if (typeof value === 'number') {
+ return consumeAscii(budget, Number.isFinite(value) ? String(value).length : 4);
+ }
+ if (typeof value !== 'object' || budget.ancestors.has(value)) return null;
+
+ if (!Array.isArray(value)) {
+ try {
+ const prototype = Object.getPrototypeOf(value);
+ if (prototype !== Object.prototype && prototype !== null) return null;
+ } catch {
+ return null;
+ }
+ }
+
+ budget.ancestors.add(value);
+ try {
+ if (Array.isArray(value)) {
+ if (consumeAscii(budget, 1)) return true;
+ for (let index = 0; index < value.length; index += 1) {
+ if (index > 0 && consumeAscii(budget, 1)) return true;
+ const measured = measureJsonValue(budget, value[index]);
+ if (measured === true) return true;
+ if (measured === null && consumeAscii(budget, 4)) return true;
+ }
+ return consumeAscii(budget, 1);
+ }
+
+ let written = 0;
+ if (consumeAscii(budget, 1)) return true;
+ for (const key of Object.keys(value)) {
+ const property = (value as Record<string, unknown>)[key];
+ if (property === undefined || typeof property === 'function' || typeof property === 'symbol') {
+ continue;
+ }
+ if (written > 0 && consumeAscii(budget, 1)) return true;
+ if (consumeUtf8(budget, key, true) || consumeAscii(budget, 1)) return true;
+ const measured = measureJsonValue(budget, property);
+ if (measured === null) return null;
+ if (measured) return true;
+ written += 1;
+ }
+ return consumeAscii(budget, 1);
+ } catch {
+ return null;
+ } finally {
+ budget.ancestors.delete(value);
+ }
+}
+
+function consumeAscii(budget: JsonByteBudget, bytes: number): boolean {
+ budget.remaining -= bytes;
+ return budget.remaining < 0;
+}
+
+function consumeUtf8(budget: JsonByteBudget, value: string, jsonQuoted: boolean): boolean {
+ if (jsonQuoted && consumeAscii(budget, 1)) return true;
+ for (let index = 0; index < value.length; index += 1) {
+ const code = value.charCodeAt(index);
+ let bytes: number;
+ if (jsonQuoted && (code === 0x22 || code === 0x5c || code === 0x08 || code === 0x09
+ || code === 0x0a || code === 0x0c || code === 0x0d)) bytes = 2;
+ else if (jsonQuoted && code <= 0x1f) bytes = 6;
+ else if (code <= 0x7f) bytes = 1;
+ else if (code <= 0x7ff) bytes = 2;
+ else if (code >= 0xd800 && code <= 0xdbff) {
+ const next = value.charCodeAt(index + 1);
+ if (next >= 0xdc00 && next <= 0xdfff) {
+ bytes = 4;
+ index += 1;
+ } else bytes = jsonQuoted ? 6 : 3;
+ } else if (jsonQuoted && code >= 0xdc00 && code <= 0xdfff) bytes = 6;
+ else bytes = 3;
+ if (consumeAscii(budget, bytes)) return true;
+ }
+ return jsonQuoted ? consumeAscii(budget, 1) : false;
+}
+
+function formatFullToolInput(input: unknown): string {
+ if (typeof input === 'string') return input;
+ try {
+ return JSON.stringify(input, null, 2) ?? '';
+ } catch {
+ return String(input ?? '');
+ }
+}
+
+function limitText(value: string, maxChars: number): string {
+ if (value.length <= maxChars) return value;
+ return `${value.slice(0, Math.max(0, maxChars - 1))}…`;
+}
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index 9dbedb8ef0..63fbf10850 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -63,6 +63,7 @@ import type { MobileSystemCardType } from '@/session/systemCard';
import type { InputProjection, PendingInteraction, RemoteMessage, RemoteSession } from '@/session/types';
import { clampLiveRowCreatedAt, compareMessageOrder, MESSAGE_PAGE_SIZE } from '@/session/messagePaging';
import { normalizeRemoteMoney } from '@/session/remoteMoney';
+import { projectLargeSettledToolInputs } from '@/session/messageToolPayloadProjection';
interface DeviceShard {
deviceId: string;
@@ -1572,7 +1573,7 @@ function preserveSessionRuntimeFields(
}
function normalizeMessages(list: readonly RemoteMessage[]): RemoteMessage[] {
- return [...list].sort(compareMessageOrder);
+ return projectLargeSettledToolInputs([...list].sort(compareMessageOrder));
}
function messageKey(message: RemoteMessage): string {
diff --git a/apps/mobile/src/session/types.ts b/apps/mobile/src/session/types.ts
index 8fff0c87aa..084bb6da1f 100644
--- a/apps/mobile/src/session/types.ts
+++ b/apps/mobile/src/session/types.ts
@@ -2,6 +2,7 @@ import type { MobileSessionAgentSwitchIntent } from '@cindy/maker-shared/device-
import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';
import type { RemoteMoney } from '@/session/remoteMoney';
import type { MobileToolLoopErrorDetails } from '@/session/toolLoopErrorI18n';
+import type { MobileToolInputProjection } from '@/session/messageToolPayloadProjection';
export type RemoteSessionStatus = 'active' | 'archived' | 'deleted';
export type RemoteMessageRole =
@@ -114,6 +115,8 @@ export interface RemoteMessage {
toolUseId: string | null;
agentMeta: Record<string, unknown> | null;
createdAt: string;
+ /** Large settled tool input released from the transcript mirror and recoverable by message id. */
+ mobileToolInputProjection?: MobileToolInputProjection;
systemCardData?: Record<string, unknown>;
systemCardType?: 'help' | 'context' | 'cost' | 'pwd' | 'status' | 'compact' | 'cmd' | 'goal-complete' | 'goal-resumed' | 'auto-resume' | 'learn' | 'agent-switch';
}