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(device-link): 精简手机工具消息并保留结果更新 (#4012)

DavidShenXD36638ff33ca8
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts
index a5e74b6ad4..9ec9e92cdf 100644
--- a/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts
@@ -12,6 +12,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import {
DeviceLinkError,
+ DEVICE_LINK_CAPABILITY_COMPACT_MESSAGE_HISTORY_V1,
CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1,
CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,
SESSION_SYNC_CHANNEL,
@@ -106,6 +107,22 @@ function batchesIn(sent: SentPush[]): MakerEventBatchPayload[] {
.map((s) => s.payload as MakerEventBatchPayload);
}
+it('projects large tool results before batch admission, preserving ordering with terminal pushes', () => {
+ const { client, sent } = mkClient();
+ __testing.setActiveClient(client as never);
+ subscriptions.subscribe('mobile', ['session:s1'], 'mobile', [
+ CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1, DEVICE_LINK_CAPABILITY_COMPACT_MESSAGE_HISTORY_V1,
+ ]);
+ const fullText = 'log'.repeat(100_000);
+ __testing.forwardPush('maker:event', { sessionId: 's1', persistId: 'p', resolvedContent: fullText,
+ event: { type: 'tool_result_full', data: { toolUseId: 'use', fullText } } });
+ expect(sent).toHaveLength(0);
+ __testing.forwardPush('maker:status-changed', { sessionId: 's1', status: 'idle' });
+ expect(sent.map((push) => push.channel)).toEqual([MAKER_EVENT_BATCH_CHANNEL, 'maker:status-changed']);
+ expect(JSON.stringify(sent[0].payload).length).toBeLessThan(10_000);
+ expect(JSON.stringify(sent[0].payload)).not.toContain('resolvedContent');
+});
+
beforeEach(() => {
vi.useFakeTimers();
deviceLinkSettings.value = { remoteControlEnabled: true, revokedControllers: [] };
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
index 38e9730c03..6c47825a05 100644
--- a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
@@ -11,6 +11,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import {
DeviceLinkError,
+ DEVICE_LINK_CAPABILITY_COMPACT_MESSAGE_HISTORY_V1,
CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1,
DL_SUBSCRIBE_CHANNEL,
MAX_FRAME_BYTES,
@@ -79,6 +80,46 @@ beforeEach(() => {
__testing.reset();
});
+describe('negotiated mobile tool projection', () => {
+ const input = { command: 'echo ' + 'x'.repeat(40_000) };
+ const row = { id: 'row', clientId: 'persist', sessionId: 's1', role: 'tool_use',
+ content: { toolUseId: 'use', toolName: 'Bash', input } };
+ function subscribe() {
+ subscriptions.subscribe('mobile', ['session:s1'], 'mobile', [DEVICE_LINK_CAPABILITY_COMPACT_MESSAGE_HISTORY_V1]);
+ subscriptions.subscribe('legacy', ['session:s1'], 'legacy', []);
+ }
+
+ it('projects new Mobile list reads but leaves old clients and radius-0 details intact', () => {
+ subscribe();
+ const client = mkClient();
+ for (const [dst, channel] of [['mobile', 'local-db:messages:list'], ['legacy', 'local-db:messages:list'],
+ ['mobile', 'local-db:messages:around']]) {
+ __testing.sendInvokeResultSafe(client as never, dst, channel, { ok: true, result: [row] }, channel);
+ }
+ expect(client.sendInvokeResult.mock.calls[0][2].result[0]).toHaveProperty('mobileToolInputProjection');
+ expect(client.sendInvokeResult.mock.calls[1][2].result[0]).toEqual(row);
+ expect(client.sendInvokeResult.mock.calls[2][2].result[0]).toEqual(row);
+ });
+
+ it('projects single live/created pushes per peer without changing the host broadcast', () => {
+ subscribe();
+ const client = mkClient();
+ __testing.setActiveClient(client as never);
+ const text = 'result'.repeat(30_000);
+ const payload = { sessionId: 's1', persistId: 'p', resolvedContent: text,
+ event: { type: 'tool_result_full', data: { toolUseId: 'use', fullText: text, isError: false } } };
+ __testing.forwardPush('maker:event', payload);
+ const calls = client.sendPush.mock.calls;
+ expect(calls.find((c) => c[0] === 'mobile')![2]).not.toHaveProperty('resolvedContent');
+ expect(calls.find((c) => c[0] === 'legacy')![2]).toEqual(payload);
+ __testing.forwardPush('local-db:messages:created', { sessionId: 's1', message: row });
+ expect(client.sendPush.mock.calls.find((c) => c[0] === 'mobile' && c[1] === 'local-db:messages:created')![2].message)
+ .toHaveProperty('mobileToolInputProjection');
+ expect(payload.resolvedContent).toBe(text);
+ expect(row.content.input).toBe(input);
+ });
+});
+
describe('[14] sendInvokeResultSafe — 结果超限兜底', () => {
it('消息页首发抛 PAYLOAD_TOO_LARGE → 先压缩超大消息内容并重发 ok:true,不冒泡', () => {
const sendInvokeResult = vi.fn().mockImplementationOnce(() => {
diff --git a/apps/desktop/src/main/device-link/__tests__/mobileToolProjection.test.ts b/apps/desktop/src/main/device-link/__tests__/mobileToolProjection.test.ts
new file mode 100644
index 0000000000..867156b01d
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/mobileToolProjection.test.ts
@@ -0,0 +1,138 @@
+import { describe, expect, it } from 'vitest';
+import { extractPayloadToolResultMedia } from '@cindy/maker-shared/payload-summary';
+import {
+ MOBILE_HISTORY_PAGE_BYTES, MOBILE_TOOL_RESULT_BYTES,
+ projectMobileMessagePage, projectMobileToolMessage, projectMobileToolPush, projectMobileToolResult,
+} from '../mobileToolProjection';
+
+const bytes = (value: unknown) => new TextEncoder().encode(JSON.stringify(value)).byteLength;
+const tool = (toolName = 'Bash', input: unknown = { command: 'echo hello ' + 'x'.repeat(40_000) }) => ({
+ id: 'row-1', clientId: 'persist-1', sessionId: 'session-1', rowid: 42,
+ role: 'tool_use', toolUseId: 'use-1', createdAt: '2026-09-06T00:00:00.000Z',
+ agentMeta: { parentUuid: 'parent', turnCompleted: false },
+ content: { toolName, toolUseId: 'use-1', input, turnCompleted: false },
+});
+
+describe('mobile tool projection', () => {
+ it('keeps stable identity and metadata, replacing a large input with a recoverable reference', () => {
+ const original = tool();
+ const projected = projectMobileToolMessage(original);
+ expect(projected).toMatchObject({
+ id: original.id, clientId: original.clientId, rowid: 42, agentMeta: original.agentMeta,
+ content: { input: null, toolName: 'Bash', turnCompleted: false },
+ mobileToolInputProjection: { projected: true, version: 1, toolUseId: 'use-1', toolUseMessageId: 'row-1', toolName: 'Bash' },
+ });
+ expect(bytes(projected)).toBeLessThan(1024);
+ expect(original.content.input).toHaveProperty('command');
+ expect(projectMobileToolMessage(projected)).toBe(projected);
+ });
+
+ it('budgets all fields and UTF-8, not each field separately', () => {
+ expect(projectMobileToolMessage(tool('Bash', { command: '中😀'.repeat(1500) }))).toHaveProperty('mobileToolInputProjection');
+ expect(projectMobileToolMessage(tool('WebFetch', Object.fromEntries(Array.from({ length: 100 }, (_, i) => [String(i), 'x'.repeat(100)])))))
+ .toHaveProperty('mobileToolInputProjection');
+ });
+
+ it('does not mislabel small or unavailable inputs', () => {
+ for (const row of [tool('Bash', { command: 'pwd' }), { ...tool(), id: '' },
+ { ...tool(), agentMeta: { remoteContentTruncated: true } }]) {
+ expect(projectMobileToolMessage(row)).toBe(row);
+ }
+ });
+
+ it.each(['AskUserQuestion', 'ExitPlanMode', 'TodoWrite', 'update_plan', 'Agent', 'Task',
+ 'create_workers', 'mcp__orca__send_to_worker', 'mcp:orca:create_worker', 'Write', 'Edit', 'MultiEdit', 'edit', 'write'])
+ ('keeps %s structural input intact', (name) => {
+ const row = tool(name, { plan: [{ step: 'x'.repeat(50_000) }], content: 'x'.repeat(50_000) });
+ expect(projectMobileToolMessage(row)).toBe(row);
+ const push = { sessionId: 's', event: { type: 'tool_use', data: row.content } };
+ expect(projectMobileToolPush('maker:event', push)).toBe(push);
+ });
+
+ it('bounds plain results on UTF-8 boundaries and marks shortened rows', () => {
+ const text = '中文😀'.repeat(10_000);
+ const result = projectMobileToolResult(text) as string;
+ expect(new TextEncoder().encode(result).byteLength).toBeLessThanOrEqual(MOBILE_TOOL_RESULT_BYTES);
+ expect(result).not.toContain('\uFFFD');
+ expect(result).toContain('[remote content truncated');
+ expect(projectMobileToolMessage({ ...tool(), role: 'tool_result', content: text })).toMatchObject({
+ toolUseId: 'use-1', agentMeta: { parentUuid: 'parent', mobileToolResultProjected: true }, content: result,
+ });
+ });
+
+ it('distinguishes current previews from transport fallback without clearing an existing fallback flag', () => {
+ const row = { ...tool(), role: 'tool_result', content: '中文'.repeat(2000) };
+ const preview = projectMobileToolMessage(row);
+ expect(preview).not.toHaveProperty('agentMeta.remoteContentTruncated');
+ expect(projectMobileToolMessage(preview)).toBe(preview);
+ expect(projectMobileToolMessage({ ...row, agentMeta: { remoteContentTruncated: true } }))
+ .toMatchObject({ agentMeta: { remoteContentTruncated: true, mobileToolResultProjected: true } });
+ expect(row.agentMeta).toEqual({ parentUuid: 'parent', turnCompleted: false });
+ });
+
+ it('preserves media JSON, actions, audio and references beyond the preview boundary', () => {
+ const content = JSON.stringify({
+ text: 'x'.repeat(50_000), xdt_image_url: 'cindy-media://blobs/a.png',
+ _xdt_actions: { jobId: 'job', buttons: [{ label: 'U1', customId: 'u1' }] },
+ xdt_audio_tracks: [{ xdt_audio_url: 'cindy-media://blobs/a.mp3', title: 'track' }],
+ });
+ expect(projectMobileToolResult(content)).toBe(content);
+ expect(extractPayloadToolResultMedia(projectMobileToolResult(content) as string)).toEqual(extractPayloadToolResultMedia(content));
+ for (const output of ['x'.repeat(9000) + '\nhttps://example.com/file.pdf',
+ '<tool_use_error>' + 'error'.repeat(9000) + '</tool_use_error>',
+ JSON.stringify({ _xdt_render_image: false, text: 'x'.repeat(9000) })]) {
+ const projected = projectMobileToolResult(output) as string;
+ expect(projected).not.toBe(output);
+ expect(new TextEncoder().encode(projected).byteLength).toBeLessThanOrEqual(MOBILE_TOOL_RESULT_BYTES);
+ }
+ });
+
+ it('removes duplicate result bodies while keeping correlation and failure flags', () => {
+ const fullText = 'output '.repeat(30_000);
+ const push = { sessionId: 's', persistId: 'p', resolvedContent: fullText,
+ event: { type: 'tool_result_full', source: 'codex', data: { toolUseId: 'u', fullText, isError: true } } };
+ const projected = projectMobileToolPush('maker:event', push);
+ expect(projected).not.toHaveProperty('resolvedContent');
+ expect(projected).toMatchObject({ persistId: 'p', event: { source: 'codex', data: { toolUseId: 'u', isError: true } } });
+ expect(bytes(projected)).toBeLessThan(10_000);
+ expect(push.resolvedContent).toBe(fullText);
+ expect(push.event.data.fullText).toBe(fullText);
+ });
+
+ it('does not project assistant text, thinking, approvals or terminal events', () => {
+ for (const type of ['text', 'thinking', 'done', 'error', 'agent_task_update']) {
+ const push = { sessionId: 's', event: { type, data: { text: 'x'.repeat(100_000) } } };
+ expect(projectMobileToolPush('maker:event', push)).toBe(push);
+ }
+ const request = { sessionId: 's', request: { input: 'x'.repeat(100_000) } };
+ expect(projectMobileToolPush('maker:interaction-request', request)).toBe(request);
+ });
+
+ it('projects created rows identically to history, including early running tools', () => {
+ const row = tool();
+ expect(projectMobileToolPush('local-db:messages:created', { sessionId: 's', message: row }))
+ .toEqual({ sessionId: 's', message: projectMobileMessagePage([row], {})[0] });
+ });
+});
+
+describe('mobile history byte budget', () => {
+ const rows = Array.from({ length: 8 }, (_, i) => ({ ...tool(), id: String(8 - i), role: 'assistant', content: 'x'.repeat(80_000) }));
+ it('returns newest rows and a continuation marker for backward reads', () => {
+ const page = projectMobileMessagePage(rows, { before: '9' }) as typeof rows;
+ expect(page.map((r) => r.id)).toEqual(['8', '7', '6']);
+ expect(bytes(page)).toBeLessThan(MOBILE_HISTORY_PAGE_BYTES);
+ expect(page[0].agentMeta).toMatchObject({ remoteRowsTrimmed: true, remoteOriginalRowCount: 8 });
+ expect(page[0].content).toBe(rows[0].content);
+ });
+ it('keeps the oldest delta for after reads so advancing the cursor skips no rows', () => {
+ const page = projectMobileMessagePage(rows, { after: '0' }) as typeof rows;
+ expect(page.map((r) => r.id)).toEqual(['3', '2', '1']);
+ });
+ it('always progresses with one intact large assistant row', () => {
+ const large = { ...rows[0], content: 'x'.repeat(MOBILE_HISTORY_PAGE_BYTES * 2) };
+ const page = projectMobileMessagePage([large, ...rows], {}) as typeof rows;
+ expect(page).toHaveLength(1);
+ expect(page[0].content).toBe(large.content);
+ expect(projectMobileMessagePage([], {})).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 97b39f87ed..3370cfb660 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -42,6 +42,7 @@ import {
MAKER_EVENT_BATCH_CHANNEL,
CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1,
CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,
+ DEVICE_LINK_CAPABILITY_COMPACT_MESSAGE_HISTORY_V1,
byteLength,
DeviceLinkError,
parseFsWatchTopic,
@@ -67,6 +68,7 @@ import {
import { app } from 'electron';
import type { DeviceLinkClient } from '@cindy/device-link';
import { createLogger } from '../logger';
+import { projectMobileMessagePage, projectMobileToolPush } from './mobileToolProjection';
import { normalizeSessionProviderId } from '../maker-host/session-provider-store.js';
import { readDeviceLinkSettings } from './settings-store';
import { dispatchLocalInvoke } from './invoke-registry';
@@ -1567,8 +1569,18 @@ function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerSt
const batchEligibleSessionId = batchTargets
? readPushSessionId(remotePayload)
: null;
- const batchEligible = batchEligibleSessionId !== null
- && estimateMakerEventBytes(remotePayload) < MAKER_EVENT_BATCH_MAX_BYTES;
+ // Project lazily once, before batching/offline queueing. Another Desktop or old Mobile
+ // on the same relay must still receive its unchanged payload.
+ let mobilePayload: unknown;
+ let mobilePayloadReady = false;
+ const payloadFor = (dst: string): unknown => {
+ if (!subscriptions.controllerSupports(dst, DEVICE_LINK_CAPABILITY_COMPACT_MESSAGE_HISTORY_V1)) return remotePayload;
+ if (!mobilePayloadReady) {
+ mobilePayload = projectMobileToolPush(channel, remotePayload);
+ mobilePayloadReady = true;
+ }
+ return mobilePayload;
+ };
const offlineTargets = subscriptions
.getKnownControllersForTopic(topic)
.filter((dst) => !liveTargets.includes(dst));
@@ -1576,14 +1588,16 @@ function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerSt
if (OFFLINE_QUEUEABLE_PUSH_CHANNELS.has(channel)) {
offlinePushQueue.enqueue(dst, {
channel,
- payload: remotePayload,
+ payload: payloadFor(dst),
topic,
...(ownerStamp ? { ownerStamp } : {}),
});
}
}
for (const dst of liveTargets) {
- const willBatch = batchEligible && batchTargets!.has(dst);
+ const targetPayload = payloadFor(dst);
+ const willBatch = batchEligibleSessionId !== null && batchTargets!.has(dst)
+ && estimateMakerEventBytes(targetPayload) < MAKER_EVENT_BATCH_MAX_BYTES;
// 跨 channel 保序(review 两轮):**不入批**的帧必须排在该会话已暂存的事件
// 之后——否则 interaction-request / status-changed / activity 终态会插到攒批
// 的文本 delta 前面,控制端先收「已完成/确认卡」(结束流式消息)、120ms 后
@@ -1593,15 +1607,15 @@ function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerSt
// - 必须只对 !willBatch 的帧做,否则每条 maker:event 都会先收口上一批,
// 批被拆回逐帧、优化完全失效。
if (!willBatch && makerEventBatchStages.size > 0) {
- flushMakerEventBatchesForSessionPush(dst, channel, remotePayload);
+ flushMakerEventBatchesForSessionPush(dst, channel, targetPayload);
}
if (willBatch) {
- stageMakerEventPush(dst, batchEligibleSessionId!, remotePayload, ownerStamp);
+ stageMakerEventPush(dst, batchEligibleSessionId!, targetPayload, ownerStamp);
continue;
}
// 会话活动是高频状态镜像:走 latest-wins 暂存整流,不直接冲可靠传输窗口。
if (channel === SESSION_ACTIVITY_CHANNEL) {
- stageSessionActivityPush(dst, remotePayload, ownerStamp);
+ stageSessionActivityPush(dst, targetPayload, ownerStamp);
continue;
}
// agent 事件流是本条链路的帧数大头:对声明了微批能力的控制端合并成
@@ -1611,7 +1625,7 @@ function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerSt
// 转发是尽力而为的旁路:单个控制端的帧超限(PAYLOAD_TOO_LARGE,如大 tool 输出)/ 连接异常
// 绝不能冒泡——它会经 tapWindowBroadcast 回到 broadcastToAllWindows,让被控端**本机** renderer
// 漏收该事件(本地 UI 是第一优先);per-dst 接住也避免一个控制端坏帧拖垮其它控制端的转发。
- sendPushBestEffort(dst, channel, remotePayload, ownerStamp);
+ sendPushBestEffort(dst, channel, targetPayload, ownerStamp);
}
}
@@ -2539,7 +2553,12 @@ function sendInvokeResultSafe(
): boolean {
const key = `${src}\u0000${requestId}`;
const normalized = sanitizeMessageInvokeResult(normalizeInvokeResultForWire(result), channel);
- const attempt = trySendInvokeResult(client, src, requestId, normalized, channel, args);
+ const proactive =
+ subscriptions.controllerSupports(src, DEVICE_LINK_CAPABILITY_COMPACT_MESSAGE_HISTORY_V1) &&
+ channel === 'local-db:messages:list' && normalized.ok && Array.isArray(normalized.result)
+ ? { ...normalized, result: projectMobileMessagePage(normalized.result, args?.[1]) }
+ : normalized;
+ const attempt = trySendInvokeResult(client, src, requestId, proactive, channel, args);
// 以真正能上 wire 的结果作为去重真相:超限原结果若被 compact/改成结构化错误,
// 不能把缓存留在原始大对象上,否则缓存可能自淘汰且重复 requestId 会再次执行。
if (fingerprint !== undefined) {
diff --git a/apps/desktop/src/main/device-link/mobileToolProjection.ts b/apps/desktop/src/main/device-link/mobileToolProjection.ts
new file mode 100644
index 0000000000..e195b751b4
--- /dev/null
+++ b/apps/desktop/src/main/device-link/mobileToolProjection.ts
@@ -0,0 +1,147 @@
+import { isAgentTaskToolName } from '@cindy/maker-shared/agent-task';
+import { isAgentPlanToolName } from '@cindy/maker-shared/message-render';
+import { isOrcaCommunicationTool } from '@cindy/maker-shared/message-normalize';
+import {
+ extractPayloadToolResultMedia,
+ formatPayloadToolUseSummary,
+} from '@cindy/maker-shared/payload-summary';
+
+export const MOBILE_TOOL_INPUT_BYTES = 4 * 1024;
+export const MOBILE_TOOL_RESULT_BYTES = 8 * 1024;
+export const MOBILE_HISTORY_PAGE_BYTES = 256 * 1024;
+const TRUNCATION_SUFFIX = '\n\n[remote content truncated: payload too large]';
+const encoder = new TextEncoder();
+
+function record(value: unknown): Record<string, unknown> | null {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ ? value as Record<string, unknown> : null;
+}
+
+/** UI models still derive plans, child agents, diffs and approvals from full input. */
+function canProjectInput(toolName: unknown): toolName is string {
+ return typeof toolName === 'string' && toolName.length > 0
+ && !['AskUserQuestion', 'ExitPlanMode', 'Edit', 'Write', 'MultiEdit', 'edit', 'write'].includes(toolName)
+ && !isAgentTaskToolName(toolName) && !isAgentPlanToolName(toolName)
+ && !/(?:^|:|__)(?:create_worker|create_workers|send_to_worker)$/.test(toolName)
+ && !isOrcaCommunicationTool(toolName);
+}
+
+function exceedsInputBudget(input: unknown): boolean {
+ try {
+ const serialized = JSON.stringify(input);
+ return serialized !== undefined && encoder.encode(serialized).byteLength > MOBILE_TOOL_INPUT_BYTES;
+ } catch {
+ // A malformed live payload must not break the host's local broadcast through its tap.
+ return false;
+ }
+}
+
+/** Preserve structured results and all media/file references until a typed detail projection
+ * exists. Cutting JSON or a reference-bearing string would silently remove artifacts. */
+export function projectMobileToolResult(content: unknown): unknown {
+ if (typeof content !== 'string' || encoder.encode(content).byteLength <= MOBILE_TOOL_RESULT_BYTES) return content;
+ // Keep structured media payloads intact because truncating them can drop an artifact
+ // reference. Plain URLs, action markers, errors, and arbitrary JSON remain bounded.
+ try {
+ const parsed: unknown = JSON.parse(content);
+ if (parsed !== null && typeof parsed === 'object' && extractPayloadToolResultMedia(content).length > 0) {
+ return content;
+ }
+ } catch { /* Plain tool output is the only format shortened in this phase. */ }
+ const bytes = encoder.encode(content);
+ let cut = MOBILE_TOOL_RESULT_BYTES - encoder.encode(TRUNCATION_SUFFIX).byteLength;
+ while (cut > 0 && (bytes[cut] & 0xc0) === 0x80) cut -= 1;
+ return new TextDecoder().decode(bytes.subarray(0, cut)) + TRUNCATION_SUFFIX;
+}
+
+/** Pure, per-controller wire projection. Never changes the host row or agent transcript.
+ * Reuse Mobile's existing radius-0 detail reference rather than marking input irretrievable. */
+export function projectMobileToolMessage(message: unknown): unknown {
+ const row = record(message);
+ if (!row) return message;
+ const meta = record(row.agentMeta);
+ if (row.role === 'tool_use') {
+ const content = record(row.content);
+ const toolName = content?.toolName;
+ const toolUseId = row.toolUseId || content?.toolUseId;
+ if (!content || !canProjectInput(toolName) || typeof row.id !== 'string' || !row.id
+ || typeof toolUseId !== 'string' || !toolUseId || row.mobileToolInputProjection
+ || meta?.remoteContentTruncated === true || !exceedsInputBudget(content.input)) return message;
+ return {
+ ...row,
+ content: { ...content, input: null, mobilePayloadProjected: true },
+ mobileToolInputProjection: {
+ projected: true,
+ version: 1,
+ summary: formatPayloadToolUseSummary(toolName, content.input).slice(0, 480),
+ toolName,
+ toolUseId,
+ toolUseMessageId: row.id,
+ },
+ };
+ }
+ if (row.role !== 'tool_result') return message;
+ const content = projectMobileToolResult(row.content);
+ // A current result preview must replace an earlier summary of the same row.
+ // remoteContentTruncated is reserved for transport fallback: Mobile deliberately
+ // refuses that content when it already has a usable row. Preserve a pre-existing
+ // fallback flag, but never set it merely because we generated a bounded preview.
+ return content === row.content ? message : {
+ ...row, content, agentMeta: { ...meta, mobileToolResultProjected: true },
+ };
+}
+
+/** Keep event ordering/identity and status signals. Mobile obtains ordinary tool rows from
+ * messages:created; resolvedContent is the Desktop renderer's duplicate result body. */
+export function projectMobileToolPush(channel: string, payload: unknown): unknown {
+ const push = record(payload);
+ if (!push) return payload;
+ if (channel === 'local-db:messages:created') {
+ const message = projectMobileToolMessage(push.message);
+ return message === push.message ? payload : { ...push, message };
+ }
+ if (channel !== 'maker:event') return payload;
+ const event = record(push.event);
+ const data = record(event?.data);
+ if (!event || !data || !['tool_use', 'tool_result', 'tool_result_full'].includes(String(event.type))) return payload;
+ let projectedData = data;
+ if (event.type === 'tool_use') {
+ if (canProjectInput(data.toolName) && exceedsInputBudget(data.input)) {
+ projectedData = { ...data, input: null };
+ }
+ } else {
+ for (const key of ['fullText', 'summary']) {
+ const preview = projectMobileToolResult(data[key]);
+ if (preview !== data[key]) projectedData = { ...projectedData, [key]: preview };
+ }
+ }
+ if (projectedData === data && !('resolvedContent' in push)) return payload;
+ const { resolvedContent: _, ...rest } = push;
+ return { ...rest, event: { ...event, data: projectedData } };
+}
+
+/** Soft byte budget: one intact row always progresses, even for a large assistant reply.
+ * `after` pages are returned descending by the IPC despite selecting the oldest delta first. */
+export function projectMobileMessagePage(messages: unknown[], options: unknown): unknown[] {
+ const rows = messages.map(projectMobileToolMessage);
+ const opts = record(options);
+ const forward = typeof opts?.after === 'string' && !!opts.after && !opts.before && opts.beforeTs == null;
+ const ordered = forward ? rows.slice().reverse() : rows;
+ let bytes = 1024; // Envelope and trimmed-window metadata allowance.
+ let keep = 0;
+ for (const row of ordered) {
+ const size = encoder.encode(JSON.stringify(row)).byteLength + 256;
+ if (keep > 0 && bytes + size > MOBILE_HISTORY_PAGE_BYTES) break;
+ bytes += size;
+ keep += 1;
+ }
+ if (keep === rows.length) return rows;
+ const selected = forward ? rows.slice(-keep) : rows.slice(0, keep);
+ return selected.map((row) => {
+ const value = record(row);
+ return value ? {
+ ...value,
+ agentMeta: { ...record(value.agentMeta), remoteRowsTrimmed: true, remoteOriginalRowCount: rows.length },
+ } : row;
+ });
+}
diff --git a/apps/mobile/src/__tests__/mobileWireToolProjection.test.ts b/apps/mobile/src/__tests__/mobileWireToolProjection.test.ts
new file mode 100644
index 0000000000..12179baef9
--- /dev/null
+++ b/apps/mobile/src/__tests__/mobileWireToolProjection.test.ts
@@ -0,0 +1,92 @@
+import { describe, expect, it, vi } from 'vitest';
+import { MOBILE_TOOL_RESULT_BYTES, projectMobileMessagePage, projectMobileToolMessage, projectMobileToolPush } from '../../../desktop/src/main/device-link/mobileToolProjection';
+import { normalizeRemoteMessages } from '@/session/messageNormalize';
+import { fetchMobileToolInputDetail } from '@/session/messageToolPayloadProjection';
+import { remoteSessionStore } from '@/session/remoteSessionStore';
+import type { RemoteMessage } from '@/session/types';
+
+describe('Desktop tool projection consumed by Mobile', () => {
+ const tool: RemoteMessage = {
+ id: 'wire-input', clientId: 'wire-client', sessionId: 'wire-projection-session',
+ role: 'tool_use', toolUseId: 'wire-use', agentMeta: null,
+ content: { toolName: 'Bash', toolUseId: 'wire-use', input: { command: 'echo ' + 'input'.repeat(10_000) } },
+ createdAt: '2026-09-06T00:00:00.000Z',
+ };
+
+ const resultUpdates = [
+ ['history merge', (row: RemoteMessage) => remoteSessionStore.mergeMessages(
+ row.sessionId, projectMobileMessagePage([row], {}) as RemoteMessage[],
+ )],
+ ['latest window', (row: RemoteMessage) => remoteSessionStore.setLatestMessageWindow(
+ row.sessionId, projectMobileMessagePage([row], {}) as RemoteMessage[],
+ )],
+ ['created push', (row: RemoteMessage) => remoteSessionStore.applyRemotePush(
+ 'wire-device', 'local-db:messages:created',
+ projectMobileToolPush('local-db:messages:created', { sessionId: row.sessionId, message: row }),
+ )],
+ ] as const;
+
+ it.each(resultUpdates)('replaces an earlier summary with the newer result preview via %s', (_name, update) => {
+ const summary: RemoteMessage = {
+ ...tool, id: 'wire-result', clientId: 'wire-result', role: 'tool_result', content: 'initial short summary',
+ };
+ // Below the Desktop 8192-character DB cap, but above the 8 KiB wire budget.
+ const full = { ...summary, content: '中文'.repeat(2000) };
+ const preview = projectMobileToolMessage(full) as RemoteMessage;
+ remoteSessionStore.setMessages(tool.sessionId, [summary]);
+
+ update(full);
+
+ const rows = remoteSessionStore.getMessages(tool.sessionId);
+ expect(rows).toHaveLength(1);
+ expect(rows[0].id).toBe(summary.id);
+ expect(rows[0].content).toBe(preview.content);
+ expect(rows[0].content).toContain('中文');
+ expect(rows[0].content).toContain('[remote content truncated');
+ expect(new TextEncoder().encode(rows[0].content as string).byteLength).toBeLessThanOrEqual(MOBILE_TOOL_RESULT_BYTES);
+
+ // A later authoritative full read must still replace the preview.
+ remoteSessionStore.mergeMessages(tool.sessionId, [full]);
+ expect(remoteSessionStore.getMessages(tool.sessionId)[0].content).toBe(full.content);
+ });
+
+ it.each(resultUpdates)('keeps a usable preview when a transport fallback arrives via %s', (_name, update) => {
+ const result: RemoteMessage = {
+ ...tool, id: 'wire-result', clientId: 'wire-result', role: 'tool_result', content: '中文'.repeat(2000),
+ };
+ const preview = projectMobileToolMessage(result) as RemoteMessage;
+ remoteSessionStore.setMessages(tool.sessionId, [preview]);
+
+ update({
+ ...result, content: '[remote content truncated: payload too large]',
+ agentMeta: { remoteContentTruncated: true },
+ });
+
+ expect(remoteSessionStore.getMessages(tool.sessionId)[0].content).toBe(preview.content);
+ });
+
+ it('shows the same summary and completion, and expands authoritative input via radius-0', async () => {
+ const projected = projectMobileToolMessage(tool) as RemoteMessage;
+ const result: RemoteMessage = { ...tool, id: 'wire-result', clientId: 'result', role: 'tool_result', content: 'done' };
+ const normalized = normalizeRemoteMessages([projected, result]);
+ expect(normalized[0].body).toBe(normalizeRemoteMessages([tool, result])[0].body);
+ expect(normalized[0].toolSettled).toBe(true);
+ expect(normalized[0].toolInputProjection).toBeDefined();
+ const load = vi.fn(async () => [tool]);
+ const detail = await fetchMobileToolInputDetail(projected.mobileToolInputProjection!, load);
+ expect(load).toHaveBeenCalledWith(tool.id, { radius: 0 });
+ expect(detail.body).toContain('input'.repeat(10_000));
+ });
+
+ it('keeps created-row detail references through the real store and result events', () => {
+ remoteSessionStore.setMessages(tool.sessionId, []);
+ const push = projectMobileToolPush('local-db:messages:created', { sessionId: tool.sessionId, message: tool });
+ remoteSessionStore.applyRemotePush('wire-device', 'local-db:messages:created', push);
+ remoteSessionStore.applyRemotePush('wire-device', 'maker:event', projectMobileToolPush('maker:event', {
+ sessionId: tool.sessionId, persistId: 'result', resolvedContent: 'x'.repeat(50_000),
+ event: { type: 'tool_result_full', data: { toolUseId: tool.toolUseId, fullText: 'x'.repeat(50_000), isError: false } },
+ }));
+ expect(remoteSessionStore.getMessages(tool.sessionId).find((m) => m.id === tool.id)?.mobileToolInputProjection)
+ .toEqual((projectMobileToolMessage(tool) as RemoteMessage).mobileToolInputProjection);
+ });
+});
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 400f0215d3..e7a8e576d1 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -8,6 +8,7 @@ import {
CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1,
CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,
CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,
+ DEVICE_LINK_CAPABILITY_COMPACT_MESSAGE_HISTORY_V1,
DL_SUBSCRIBE_CHANNEL,
DL_UNSUBSCRIBE_CHANNEL,
FILE_BROWSER_EVENT_CHANNEL,
@@ -188,6 +189,7 @@ const CONTROLLER_CAPABILITIES = [
// maker:event 微批:被控端把同一会话的连续事件合并成一帧,本端拆包后逐条消费
// (见 remoteSessionStore 的 MAKER_EVENT_BATCH_CHANNEL 分支)。
CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1,
+ DEVICE_LINK_CAPABILITY_COMPACT_MESSAGE_HISTORY_V1,
];
// 任意目标端真实应答的独立时序证据。它不等同于 presence verdict,也不参与 IPC/DB
diff --git a/packages/device-link/src/transport.ts b/packages/device-link/src/transport.ts
index cdeaeaaa14..ab09396d83 100644
--- a/packages/device-link/src/transport.ts
+++ b/packages/device-link/src/transport.ts
@@ -27,6 +27,10 @@ export const DEVICE_LINK_CAPABILITY_TRANSPORT_TIMEOUT_CLOSE = 'transport-timeout
*/
export const DEVICE_LINK_CAPABILITY_RELIABLE_LINK_CONFIRM = 'reliable-link-confirm-v1';
+/** Mobile understands tool-input detail references and bounded plain result previews in
+ * list/created/maker:event. Around reads retain full detail; old peers stay unchanged. */
+export const DEVICE_LINK_CAPABILITY_COMPACT_MESSAGE_HISTORY_V1 = 'compact-message-history-v1';
+
/** transport ACK 使用普通 push 承载,且 ACK 本身永不再包 transport。 */
export const DEVICE_LINK_TRANSPORT_ACK_CHANNEL = '__cindy/device-link/transport-ack';