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(device-link): 预收列表聊天正文并在打开任务时复用

Dash8840972fa466
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 c204563154..6a6aa4cbe2 100644
--- a/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts
@@ -15,6 +15,7 @@ import {
DEVICE_LINK_CAPABILITY_COMPACT_MESSAGE_HISTORY_V1,
CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1,
CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,
+ CONTROLLER_CAPABILITY_SESSION_LIST_MESSAGES_V1,
SESSION_SYNC_CHANNEL,
DL_SUBSCRIBE_CHANNEL,
DL_UNSUBSCRIBE_CHANNEL,
@@ -136,6 +137,27 @@ afterEach(() => {
});
describe('[1] 能力协商', () => {
+ it('prefetches full prose for new list subscribers only, without duplicate delivery or tools', async () => {
+ const h = mkClient();
+ __testing.setActiveClient(h.client as never);
+ const caps = [CONTROLLER_CAPABILITY_SESSION_LIST_MESSAGES_V1, CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1];
+ subscriptions.subscribe('phone', ['sessions'], 'phone', caps);
+ subscriptions.subscribe('desktop', ['sessions', 'session:s1'], 'desktop', caps);
+ subscriptions.subscribe('old', ['sessions'], 'old');
+ const content = '完整长回复'.repeat(2000);
+ __testing.forwardPush('maker:event', { sessionId: 's1', persistId: 'm1', event: { type: 'text', data: { text: content, isFinal: false } } });
+ __testing.forwardPush('local-db:messages:created', { sessionId: 's1', message: { id: 'm1', clientId: 'm1', role: 'assistant', content } });
+ __testing.forwardPush('local-db:messages:created', { sessionId: 's1', message: { id: 'tool', role: 'tool_result', content } });
+ await vi.advanceTimersByTimeAsync(WINDOW_MS);
+ const phone = h.sent.filter(push => push.dst === 'phone');
+ expect(phone.map(push => push.channel)).toEqual([MAKER_EVENT_BATCH_CHANNEL, 'local-db:messages:created']);
+ expect(phone[1].payload).toMatchObject({ listMessage: true, message: { content, remoteBodyVersion: expect.stringMatching(/^[a-f0-9]{64}$/) } });
+ expect((phone[0].payload as MakerEventBatchPayload).events[0]).toMatchObject({ listMessage: true });
+ expect(h.sent.filter(push => push.dst === 'old')).toEqual([]);
+ expect(h.sent.filter(push => push.dst === 'desktop' && push.channel === MAKER_EVENT_BATCH_CHANNEL)).toHaveLength(1);
+ expect(subscriptions.controllerHasTopic('phone', 'session:s1')).toBe(false);
+ });
+
it('coalesces task patches even for legacy list subscribers and cancels offline peers', async () => {
const h = mkClient();
__testing.setActiveClient(h.client as never);
@@ -704,6 +726,26 @@ describe('running session recovery on slow links', () => {
type: 'text', data: { text: 'whole prefix', isFinal: false, isFullText: true },
} };
+ it('repairs the prefix when leaving chat and continues list text until the list is unsubscribed', async () => {
+ const h = mkClient();
+ __testing.setActiveClient(h.client as never);
+ setSessionTextSnapshotReader(() => snapshot);
+ subscriptions.subscribe('phone', ['sessions', 'session:s1'], 'phone',
+ [...capabilities, CONTROLLER_CAPABILITY_SESSION_LIST_MESSAGES_V1]);
+ __testing.forwardPush('maker:event', delta('pending detail suffix'));
+ __testing.handleSubscriptionFrame('phone', { channel: DL_UNSUBSCRIBE_CHANNEL, args: [{ topics: ['session:s1'] }] });
+ await vi.advanceTimersByTimeAsync(250);
+ expect(h.sent).toHaveLength(1);
+ expect(h.sent[0]).toMatchObject({ channel: SESSION_SYNC_CHANNEL, payload: { ...snapshot, listMessage: true } });
+ __testing.forwardPush('maker:event', delta('list suffix'));
+ await vi.advanceTimersByTimeAsync(WINDOW_MS);
+ expect(batchesIn(h.sent)[0].events).toEqual([{ ...delta('list suffix'), listMessage: true }]);
+ __testing.forwardPush('maker:event', delta('cancelled suffix'));
+ __testing.handleSubscriptionFrame('phone', { channel: DL_UNSUBSCRIBE_CHANNEL, args: [{ topics: ['sessions'] }] });
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(h.sent).toHaveLength(2);
+ });
+
it.each([
['batch', 'queue'], ['batch', 'peer'], ['legacy', 'queue'], ['legacy', 'peer'],
] as const)('restores %s streaming within 250ms after %s recovery without polling the snapshot while blocked', (mode, blocker) => {
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 a6347ebaf1..d733caa4ae 100644
--- a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
@@ -18,7 +18,9 @@ import {
MAX_FRAME_BYTES,
PROTOCOL_VERSION,
type InvokeResultPayload,
+ SessionMessageReuse,
} from '@cindy/device-link';
+import { versionMessageBody } from '../sessionMessageReuse';
vi.mock('electron', () => ({
app: {
@@ -299,6 +301,26 @@ describe('history detail interest', () => {
});
describe('[14] sendInvokeResultSafe — 结果超限兜底', () => {
+ it.each(['local-db:messages:list', 'local-db:messages:view'])('keeps cached prose exact when %s needs oversized tool fallback', (channel) => {
+ const cache = new SessionMessageReuse();
+ const prose = { id: 'prose', clientId: 'prose', role: 'assistant', content: '完整正文'.repeat(2000) };
+ cache.receive('host', 'local-db:messages:created', { sessionId: 's1', message: versionMessageBody(prose) });
+ const request = cache.prepare('host', { channel, args: ['s1'] });
+ const rows = [prose, { id: 'tool', role: 'tool_result', content: 'x'.repeat(MAX_FRAME_BYTES) }];
+ const value = channel.endsWith(':list') ? rows : { items: [{ type: 'messages', key: 'rows', messages: rows }], hasMore: false };
+ const sendInvokeResult = vi.fn().mockImplementationOnce(() => { throw tooLarge(); });
+ __testing.sendInvokeResultSafe(mkClient({ sendInvokeResult }) as never, 'host', 'reuse-large',
+ { ok: true, result: value }, channel, request.payload.args);
+ const sent = sendInvokeResult.mock.calls.at(-1)![2] as InvokeResultPayload;
+ expect(sent.ok).toBe(true);
+ if (!sent.ok) throw new Error('Expected compact success');
+ const decoded = request.decode(sent.result) as typeof rows | { items: { messages: typeof rows }[] };
+ const restored = Array.isArray(decoded) ? decoded : decoded.items[0].messages;
+ expect(restored[0].content).toBe(prose.content);
+ expect(restored[1].content.length).toBeLessThan(MAX_FRAME_BYTES);
+ expect(JSON.stringify(sent)).not.toContain(prose.content);
+ });
+
it('消息页首发抛 PAYLOAD_TOO_LARGE → 先压缩超大消息内容并重发 ok:true,不冒泡', () => {
const sendInvokeResult = vi.fn().mockImplementationOnce(() => {
throw tooLarge();
diff --git a/apps/desktop/src/main/device-link/__tests__/sessionMessageReuse.test.ts b/apps/desktop/src/main/device-link/__tests__/sessionMessageReuse.test.ts
new file mode 100644
index 0000000000..9001181f20
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/sessionMessageReuse.test.ts
@@ -0,0 +1,133 @@
+import { describe, expect, it } from 'vitest';
+import { SessionMessageReuse, isListMessagePush, MAX_LIST_MESSAGE_CHARS } from '@cindy/device-link';
+import { encodeMessageBodies, versionMessageBody } from '../sessionMessageReuse';
+
+const text = '列表上已收到的完整回复。'.repeat(2000);
+const message = (content = text) => ({
+ id: 'm1',
+ clientId: 'c1',
+ sessionId: 's1',
+ role: 'assistant',
+ content,
+ createdAt: '2026-10-10T00:00:00.000Z',
+});
+const request = { channel: 'local-db:messages:view', args: ['s1', { lazyDetails: true }] };
+const page = (row = message()) => ({
+ version: 1,
+ items: [{ type: 'messages', key: 'm1', messages: [row] }],
+ nextCursor: null,
+ hasMore: false,
+});
+
+describe('list text reused by the actual history wire projection', () => {
+ it('sends long text once, restores it from the request snapshot and keeps new metadata', () => {
+ const cache = new SessionMessageReuse();
+ cache.receive('host', 'local-db:messages:created', {
+ sessionId: 's1',
+ message: versionMessageBody(message()),
+ });
+ const read = cache.prepare('host', request);
+ const updated = { ...message(), agentMeta: { model: 'new' } };
+ const packed = encodeMessageBodies(request.channel, read.payload.args, page(updated));
+ expect(JSON.stringify(packed)).not.toContain(text);
+ expect(JSON.stringify(packed).length).toBeLessThan(600);
+ // An intervening newer push cannot replace the body associated with this response.
+ cache.receive('host', 'local-db:messages:created', {
+ sessionId: 's1',
+ message: versionMessageBody(message('newer')),
+ });
+ expect(read.decode(packed)).toEqual(page({ ...updated, ...versionMessageBody(updated) }));
+ });
+
+ it('transfers changed bodies, handles nested work groups and supports legacy hosts/controllers', () => {
+ const cache = new SessionMessageReuse();
+ const initial = cache.prepare('host', request);
+ const nested = { ...page(), items: [{ type: 'work', key: 'work', children: page().items }] };
+ const first = encodeMessageBodies(request.channel, initial.payload.args, nested);
+ expect(initial.decode(first)).toMatchObject(nested);
+ const second = cache.prepare('host', request);
+ const changed = encodeMessageBodies(
+ request.channel,
+ second.payload.args,
+ page(message('corrected')),
+ );
+ expect(JSON.stringify(changed)).toContain('corrected');
+ expect(second.decode(changed)).toMatchObject(page(message('corrected')));
+ expect(second.decode(page())).toEqual(page()); // old Host
+ expect(encodeMessageBodies(request.channel, request.args, page())).toEqual(page()); // old controller
+ });
+
+ it('isolates computers, tasks and logout; keeps a request usable after eviction', () => {
+ const cache = new SessionMessageReuse();
+ cache.receive('host', 'local-db:messages:created', {
+ sessionId: 's1',
+ message: versionMessageBody(message()),
+ });
+ const read = cache.prepare('host', request);
+ const other = cache.prepare('other', request);
+ expect(
+ JSON.stringify(encodeMessageBodies(request.channel, other.payload.args, page())),
+ ).toContain(text);
+ cache.clear();
+ const packed = encodeMessageBodies(request.channel, read.payload.args, page());
+ expect(read.decode(packed)).toMatchObject(page());
+ expect(
+ JSON.stringify(
+ encodeMessageBodies(request.channel, cache.prepare('host', request).payload.args, page()),
+ ),
+ ).toContain(text);
+ });
+
+ it('invalidates deleted bodies and never guesses a missing reference', () => {
+ const cache = new SessionMessageReuse();
+ cache.receive('host', 'local-db:messages:created', {
+ sessionId: 's1',
+ message: versionMessageBody(message()),
+ });
+ cache.receive('host', 'local-db:messages:deleted', { sessionId: 's1', clientId: 'c1' });
+ const read = cache.prepare('host', request);
+ const { content: _, ...ref } = versionMessageBody(message());
+ expect(() => read.decode({ format: 'message-bodies-v1', value: [ref] })).toThrow(
+ 'Missing remote message body',
+ );
+ expect(
+ JSON.stringify(encodeMessageBodies(request.channel, read.payload.args, page())),
+ ).toContain(text);
+ });
+
+ it('excludes tool bodies and oversized text from list prefetch', () => {
+ expect(isListMessagePush('local-db:messages:created', { message: message() })).toBe(true);
+ expect(
+ isListMessagePush('local-db:messages:created', {
+ message: { ...message(), role: 'tool_result' },
+ }),
+ ).toBe(false);
+ expect(
+ isListMessagePush('local-db:messages:created', {
+ message: message('a'.repeat(MAX_LIST_MESSAGE_CHARS + 1)),
+ }),
+ ).toBe(false);
+ expect(isListMessagePush('maker:event', { event: { type: 'thinking', data: { text } } })).toBe(
+ false,
+ );
+ });
+
+ it('reuses structured user text but leaves attachments on demand', () => {
+ const row = { ...message(), role: 'user', content: { text } };
+ const cache = new SessionMessageReuse();
+ expect(isListMessagePush('local-db:messages:created', { message: row })).toBe(true);
+ expect(
+ isListMessagePush('local-db:messages:created', {
+ message: { ...row, content: { text, images: [{ url: 'image' }] } },
+ }),
+ ).toBe(false);
+ cache.receive('host', 'local-db:messages:created', {
+ sessionId: 's1',
+ message: versionMessageBody(row),
+ });
+ const read = cache.prepare('host', { channel: 'local-db:messages:list', args: ['s1'] });
+ const packed = encodeMessageBodies('local-db:messages:list', read.payload.args, [row]);
+ expect(JSON.stringify(packed)).not.toContain(text);
+ expect(read.decode(packed)).toMatchObject([row]);
+ });
+});
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index d09203735b..b21f58af67 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -1,4 +1,5 @@
import { executeTaskTags, TASK_TAG_CHANNEL } from '../localDb/ipc/taskTags.js';
+import { encodeMessageBodies, versionMessageBody } from './sessionMessageReuse.js';
import type { TaskTagRequest } from '@cindy/maker-shared';
import {
FILE_PEER_CHANNEL,
@@ -7,6 +8,11 @@ import {
encodeSessionTagCatalog,
decodeSessionTagCatalog,
scrubSharedProvider,
+ CONTROLLER_CAPABILITY_SESSION_LIST_MESSAGES_V1,
+ isListMessagePush,
+ mapMessageBodies,
+ messageRecord,
+ MESSAGE_BODY_FORMAT,
} from '@cindy/device-link';
import { requestFilePeer, stopFilePeers } from './filePeer';
import { requestTaskMigration } from '../task-migration/service';
@@ -1277,7 +1283,7 @@ function stageSessionSync(dst: string, sessionId: string, historyRequired = true
return;
}
for (const sid of stage.sessions.keys()) {
- if (!subscriptions.controllerHasTopic(dst, `session:${sid}`)) {
+ if (!receivesSessionText(dst, sid)) {
stage.sessions.delete(sid);
continue;
}
@@ -1300,8 +1306,8 @@ function stageSessionSync(dst: string, sessionId: string, historyRequired = true
let admissionFailed = false;
sendBotCheckedPush(dst, SESSION_SYNC_CHANNEL, payload,
(projected) => {
- if (activeClient && subscriptions.controllerHasTopic(dst, `session:${sid}`)) {
- activeClient.sendPush(dst, SESSION_SYNC_CHANNEL, projected, ownerStamp);
+ if (activeClient && receivesSessionText(dst, sid)) {
+ activeClient.sendPush(dst, SESSION_SYNC_CHANNEL, listMessagePayload(dst, sid, projected), ownerStamp);
// Admission is not delivery/ACK. Log once per admitted repair,
// never per retry or token, and never include the snapshot body.
log.debug(`session sync repair admitted to=${shortId(dst)}`
@@ -1601,6 +1607,7 @@ function flushMakerEventBatchSession(
while (segment.events.length > 0) {
const slice = takeMakerEventBatchSlice(segment);
if (slice.length === 0) break;
+ if (!receivesSessionText(dst, sessionId)) continue;
// relay 已确认离线:只把缓冲取空(维持强不变量),不再制造成功率恒为 0 的帧。
if (outcome.offline) {
outcome.droppedEvents += slice.length;
@@ -1887,6 +1894,11 @@ export function pushSessionActivityToController(
if (!activeClient) return;
if (!subscriptions.getControllersForTopic('sessions').includes(controllerDeviceId)) return;
stageSessionActivityPush(controllerDeviceId, payload, broadcastTap.getSafeDataOwnerPushStamp?.());
+ const sessionId = readPushSessionId(payload);
+ if (sessionId && receivesListMessages(controllerDeviceId)
+ && (payload as { phase?: unknown }).phase === 'running') {
+ stageSessionSync(controllerDeviceId, sessionId, false);
+ }
}
/**
@@ -1913,6 +1925,21 @@ function clearHistoryNotices(dst: string): void {
historyNoticeStages.delete(dst);
}
+function receivesListMessages(dst: string): boolean {
+ return !isSharedTaskPeer(dst) && !isProviderSharePeer(dst)
+ && subscriptions.controllerSupports(dst, CONTROLLER_CAPABILITY_SESSION_LIST_MESSAGES_V1)
+ && subscriptions.controllerHasTopic(dst, 'sessions');
+}
+
+function receivesSessionText(dst: string, sessionId: string): boolean {
+ return subscriptions.controllerHasTopic(dst, `session:${sessionId}`) || receivesListMessages(dst);
+}
+
+function listMessagePayload(dst: string, sessionId: string, payload: unknown): unknown {
+ return receivesListMessages(dst) && !subscriptions.controllerHasTopic(dst, `session:${sessionId}`)
+ ? { ...(payload as object), listMessage: true } : payload;
+}
+
function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerStamp): void {
if (!activeClient) return;
const topic = topicForPush(channel, payload);
@@ -1948,9 +1975,11 @@ function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerSt
remotePayload = projectInteractionDismissedForRemote(remotePayload);
}
const sharedTaskTopic = sharedTaskMetadataTopic(channel, remotePayload);
+ const listMessage = isListMessagePush(channel, remotePayload);
const targetsFor = (known: boolean): string[] => {
const lookup = known ? subscriptions.getKnownControllersForTopic : subscriptions.getControllersForTopic;
- const ordinary = lookup(topic);
+ const ordinary = [...new Set([...lookup(topic), ...(listMessage
+ ? lookup('sessions').filter(receivesListMessages) : [])])];
if (!sharedTaskTopic) return ordinary;
const shared = lookup(sharedTaskTopic).filter((dst) => isSharedTaskPeer(dst)
&& captureSharedTaskPush(dst, channel, remotePayload)?.() === true);
@@ -1994,7 +2023,14 @@ function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerSt
};
// 共享任务访客只能看见本任务:新消息推送里的来源身份与 invoke 读取同口径脱敏。
const payloadFor = (dst: string): unknown => {
- const projected = projectedPayloadFor(dst);
+ let projected = projectedPayloadFor(dst);
+ if (listMessage && receivesListMessages(dst)) {
+ if (channel === 'local-db:messages:created') {
+ const push = projected as { message: Record<string, unknown> };
+ projected = { ...push, message: versionMessageBody(push.message) };
+ }
+ projected = listMessagePayload(dst, readPushSessionId(remotePayload)!, projected);
+ }
return isSharedTaskPeer(dst) ? redactSharedGuestPush(channel, projected) : projected;
};
const historySessionId = readPushSessionId(remotePayload);
@@ -3270,7 +3306,11 @@ function sendInvokeResultSafe(
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);
+ const encoded = proactive.ok && !isSharedTaskPeer(src)
+ ? encodeMessageBodies(channel, args, proactive.result) : undefined;
+ const reused = proactive.ok && encoded !== undefined && encoded !== proactive.result
+ ? { ...proactive, result: encoded } : proactive;
+ const attempt = trySendInvokeResult(client, src, requestId, reused, channel, args);
// 以真正能上 wire 的结果作为去重真相:超限原结果若被 compact/改成结构化错误,
// 不能把缓存留在原始大对象上,否则缓存可能自淘汰且重复 requestId 会再次执行。
// 远程 Agent 的每个 op 自带幂等(poll 按游标、其余按各自 id 去重),高频的事件流结果不进
@@ -3547,6 +3587,14 @@ function compactInvokeResultForDeviceLink(
frame: { dst: string; requestId: string },
args?: unknown[],
): InvokeResultPayload | null {
+ if (result.ok && messageRecord(result.result) && result.result.format === MESSAGE_BODY_FORMAT) {
+ const compact = compactInvokeResultForDeviceLink(channel, { ok: true, result: result.result.value }, frame, args);
+ if (!compact?.ok) return null;
+ // Compaction may change a body; never advertise its pre-compaction digest.
+ const wrapped: InvokeResultPayload = { ok: true, result: { format: MESSAGE_BODY_FORMAT,
+ value: mapMessageBodies(compact.result, versionMessageBody) } };
+ return fitsInvokeResultFrame(frame, wrapped) ? wrapped : null;
+ }
if (result.ok && (channel === 'local-db:messages:view' || channel === 'local-db:messages:work-details')
&& result.result && typeof result.result === 'object') {
const page = result.result as Record<string, unknown>;
@@ -3640,6 +3688,7 @@ function fitsInvokeResultFrame(frame: { dst: string; requestId: string }, payloa
function forceCompactRemoteMessageContent(message: unknown): unknown {
if (!message || typeof message !== 'object' || Array.isArray(message)) return message;
const record = message as Record<string, unknown>;
+ if (typeof record.remoteBodyVersion === 'string' && !Object.prototype.hasOwnProperty.call(record, 'content')) return record;
return {
...record,
agentMeta: markRemoteContentTruncated(record.agentMeta),
@@ -3885,6 +3934,7 @@ function handleSubscriptionFrame(src: string, payload: InvokePayload): InvokeRes
const sessionId = topic.startsWith('session:') ? topic.slice('session:'.length) : null;
if (sessionId) dropMakerEventBatch(src, sessionId);
if (sessionId) sessionSyncStages.get(src)?.sessions.delete(sessionId);
+ if (sessionId && receivesListMessages(src)) stageSessionSync(src, sessionId, false);
}
}
syncForwarding();
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index e5591cf7d7..8af6acd5f3 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -28,6 +28,7 @@ import {
SHARED_TASK_CAPABILITY,
CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1,
CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,
+ CONTROLLER_CAPABILITY_SESSION_LIST_MESSAGES_V1,
CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,
CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1,
MAKER_EVENT_BATCH_CHANNEL,
@@ -526,6 +527,7 @@ const RESPONSIVENESS_PROBE_TICK_MS = 5_000;
* 必须用同一份 —— 只在一处声明会让另一条路径静默降级(mobile 侧 review 实测过这个坑)。
*/
const CONTROLLER_CAPABILITIES = [
+ CONTROLLER_CAPABILITY_SESSION_LIST_MESSAGES_V1,
SHARED_TASK_CAPABILITY,
CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,
CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,
diff --git a/apps/desktop/src/main/device-link/sessionMessageReuse.ts b/apps/desktop/src/main/device-link/sessionMessageReuse.ts
new file mode 100644
index 0000000000..e36996c4ec
--- /dev/null
+++ b/apps/desktop/src/main/device-link/sessionMessageReuse.ts
@@ -0,0 +1,53 @@
+import { createHash } from 'node:crypto';
+import {
+ isReusableMessage,
+ mapMessageBodies,
+ messageRecord,
+ MESSAGE_BODY_FORMAT,
+} from '@cindy/device-link';
+
+/** The digest covers the exact sanitized wire body, not its sidebar preview. */
+export function versionMessageBody(row: Record<string, unknown>): Record<string, unknown> {
+ return isReusableMessage(row)
+ ? {
+ ...row,
+ remoteBodyVersion: createHash('sha256').update(JSON.stringify(row.content)).digest('hex'),
+ }
+ : row;
+}
+
+/** Opt-in compression after authorization and sanitization; metadata always stays fresh. */
+export function encodeMessageBodies(
+ channel: string | undefined,
+ args: unknown[] | undefined,
+ value: unknown,
+): unknown {
+ if (channel !== 'local-db:messages:view' && channel !== 'local-db:messages:list') return value;
+ if (messageRecord(value) && value.format === MESSAGE_BODY_FORMAT) return value;
+ const options = args?.[1];
+ const request = messageRecord(options) ? options.messageBodies : undefined;
+ if (!messageRecord(request) || request.version !== 1 || !Array.isArray(request.known))
+ return value;
+ const known = new Map<string, string>();
+ for (const entry of request.known.slice(0, 256)) {
+ if (
+ Array.isArray(entry) &&
+ entry.length === 2 &&
+ typeof entry[0] === 'string' &&
+ entry[0].length <= 256 &&
+ typeof entry[1] === 'string' &&
+ /^[a-f0-9]{64}$/.test(entry[1])
+ )
+ known.set(entry[0], entry[1]);
+ }
+ return {
+ format: MESSAGE_BODY_FORMAT,
+ value: mapMessageBodies(value, (row) => {
+ const versioned = versionMessageBody(row);
+ if (!isReusableMessage(versioned) || known.get(versioned.id) !== versioned.remoteBodyVersion)
+ return versioned;
+ const { content: _content, ...reference } = versioned;
+ return reference;
+ }),
+ };
+}
diff --git a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts
index 5137509c46..d1f668303c 100644
--- a/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteMirrorCache.test.ts
@@ -46,6 +46,7 @@ import {
readCachedMessages,
readCachedSessionList,
scheduleSessionListPersist,
+ persistListMessage,
} from '@/features/device-link/mirrorCacheClient';
import {
__testing as dataOwnerGenTesting,
@@ -269,6 +270,35 @@ afterEach(() => {
});
describe('冷缓存 hydrate', () => {
+ it('shows a list-pushed reply immediately when opening a task while its history request is still pending', async () => {
+ const s = sid();
+ setDataOwnerGeneration('owner-a', 1);
+ registerRemote(s);
+ let push!: Parameters<typeof window.electronAPI.deviceLink.onRemotePush>[0];
+ window.electronAPI.deviceLink.onRemotePush = vi.fn(callback => { push = callback; return () => {}; });
+ makerChatStore.initGlobalListeners();
+ const row = dbMessage(s, 'prefetched', '完整长正文'.repeat(2000), '2026-10-10T00:00:00.000Z');
+ push({ deviceId: DEVICE_ID, channel: 'local-db:messages:created', payload: { sessionId: s, listMessage: true, message: row } });
+ await flush(30);
+ expect(makerChatStore.getSnapshot(s).messages.map(message => message.content)).toEqual([row.content]);
+ expect(invoke.mock.calls.filter(([, channel]) => channel.startsWith('local-db:messages:'))).toEqual([]);
+ expectPut(DEVICE_ID, s, [row]);
+ remoteListPromise = new Promise<Message[]>(() => {});
+ makerChatStore.ensureInitialMessages(s);
+ await flush(30);
+ expect(makerChatStore.getSnapshot(s).messages.map(message => message.content)).toEqual([row.content]);
+ });
+
+ it('merges prefetched list text into the protected disk window', async () => {
+ const s = sid();
+ const earlier = dbMessage(s, 'old', 'earlier', '2026-10-10T00:00:00.000Z');
+ const latest = dbMessage(s, 'new', '完整正文'.repeat(2000), '2026-10-10T00:01:00.000Z');
+ cachedMessages.set(`${DEVICE_ID}::${s}`, [earlier as unknown as Record<string, unknown>]);
+ persistListMessage(DEVICE_ID, s, latest);
+ await vi.waitFor(() => expectPut(DEVICE_ID, s, [earlier, latest]));
+ expect(putMessages.mock.calls[0].slice(3, 6)).toEqual([7, cachedOwnerToken, 0]);
+ });
+
it('restores the structured view through the actual offline session entry', async () => {
const s = sid();
const rows = [{ id: 'cached', clientId: 'cached', role: 'user', content: 'offline history', createdAt: '2026-09-17T00:00:00Z' }];
diff --git a/apps/desktop/src/renderer/features/device-link/mirrorCacheClient.ts b/apps/desktop/src/renderer/features/device-link/mirrorCacheClient.ts
index 631e8cada8..cda7e96a8f 100644
--- a/apps/desktop/src/renderer/features/device-link/mirrorCacheClient.ts
+++ b/apps/desktop/src/renderer/features/device-link/mirrorCacheClient.ts
@@ -145,6 +145,26 @@ export async function readCachedMessages(deviceId: string, sessionId: string, on
return read;
}
+const listMessageWrites = new Map<string, Promise<void>>();
+
+/** List pushes merge into the same protected disk window used when opening a task. */
+export function persistListMessage(deviceId: string, sessionId: string, message: Message): void {
+ const owner = getDataOwnerGeneration();
+ const token = sessionCacheInvalidationToken(sessionId);
+ const key = JSON.stringify([deviceId, sessionId]);
+ const current = () => isDataOwnerGenerationCurrent(owner) && token === sessionCacheInvalidationToken(sessionId);
+ const pending = (listMessageWrites.get(key) ?? Promise.resolve()).then(async () => {
+ if (!current()) return;
+ const rows = await readCachedMessages(deviceId, sessionId);
+ if (!current()) return;
+ await persistCachedMessages(deviceId, sessionId,
+ [...rows.filter(row => row.id !== message.id && (!message.clientId || row.clientId !== message.clientId)), message],
+ invalidationAtRequestStart(deviceId, sessionId), ownerTokenAtRequestStart(sessionId), accountCounterAtRequestStart(sessionId));
+ }).catch(error => log.debug('persist list message failed', error));
+ listMessageWrites.set(key, pending);
+ void pending.finally(() => { if (listMessageWrites.get(key) === pending) listMessageWrites.delete(key); });
+}
+
/** 写某 (设备, 会话) 的最近一页 server rows(空数组 = 清掉该条缓存)。失败静默。 */
/**
* main 侧会话级作废计数的**本地已知值**。get / put 的响应都会带回它;写入时把它当成
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 6d763de954..060e06b265 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -151,7 +151,7 @@ import {
requestRemoteReseed,
} from '@/features/device-link/remoteProjectsStore';
import { getStickySessionDeviceId } from '@/features/device-link/stickySessionOrigin';
-import { clearCachedMessages, readCachedMessages } from '@/features/device-link/mirrorCacheClient';
+import { clearCachedMessages, readCachedMessages, persistListMessage } from '@/features/device-link/mirrorCacheClient';
import {
noteRemoteSessionSyncCompleted,
noteRemoteSessionSyncStarted,
@@ -8940,7 +8940,8 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
inboundEvent?.type === 'text' &&
inboundEvent.data?.isFinal === false &&
inboundEvent.data?.isFullText !== true;
- if (push.deviceId && inboundSid && isDurableMessagePush && !isOrdinaryStreamingTextDelta) {
+ const listMessage = (push.payload as { listMessage?: unknown } | null)?.listMessage === true;
+ if (push.deviceId && inboundSid && isDurableMessagePush && !isOrdinaryStreamingTextDelta && !listMessage) {
scheduleRemoteMessageRepair(inboundSid);
}
if (inboundSid && isRemoteHeavyInboundChannel(push.channel)) _markInboundEvent(inboundSid);
@@ -8962,6 +8963,11 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
invalidateHistory: (sessionId) => {
const state = sessions.get(sessionId);
if (!state) return;
+ if (listMessage) {
+ bumpMessagesEpoch(sessionId);
+ setState(sessionId, current => ({ ...current, historyLoaded: false }));
+ return;
+ }
if (getRemoteHistoryView(sessionId)) {
// resyncRequired also repairs unrelated durable rows; a full
// text snapshot only protects its own live block.
@@ -9003,6 +9009,10 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {
case 'local-db:messages:created':
// 远程会话的持久化消息(接管路径)→ 注入 in-memory state(同本机)。
handleMessageCreatedRaw(push.payload, remoteIngress);
+ if (listMessage && push.deviceId && inboundSid) {
+ const row = (push.payload as { message?: Message }).message;
+ if (row && !isBeforeOrAtRendererClearBoundary(inboundSid, row.createdAt)) persistListMessage(push.deviceId, inboundSid, row);
+ }
break;
case 'local-db:messages:deleted':
handleMessageDeletedRaw(push.payload, remoteIngress);
diff --git a/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts b/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts
index 201f31bf88..9f55e076e2 100644
--- a/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts
+++ b/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts
@@ -179,6 +179,19 @@ describe('mobileSessionMessageCache', () => {
expect(cached[1].content).toBe('second');
});
+ it('merges list messages without losing earlier history and serializes rapid updates', async () => {
+ const { cacheSessionMessages, cacheSessionListMessage, getCachedSessionMessages } = await import('@/session/mobileSessionMessageCache');
+ await cacheSessionMessages('host-a', 'session-1', [makeMessage({ id: 'old', clientId: 'old', createdAt: isoAt(1) })]);
+ const content = '未截断的聊天正文。'.repeat(2000);
+ await Promise.all([
+ cacheSessionListMessage('host-a', 'session-1', makeMessage({ id: 'new', clientId: 'new', createdAt: isoAt(2), content: 'first' })),
+ cacheSessionListMessage('host-a', 'session-1', makeMessage({ id: 'new', clientId: 'new', createdAt: isoAt(2), content })),
+ ]);
+ const rows = await getCachedSessionMessages('host-a', 'session-1');
+ expect(rows.map(row => row.id)).toEqual(['old', 'new']);
+ expect(rows[1].content).toBe(content);
+ });
+
it('returns [] for missing cache or blank ids', async () => {
const { getCachedSessionMessages, cacheSessionMessages } = await import('@/session/mobileSessionMessageCache');
diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
index 6562834dad..1bcb634e66 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -6668,3 +6668,26 @@ describe('task tag source isolation', () => {
expect(remoteSessionStore.getSessions().find((row) => row.id === 'b')?.tags).toEqual([tag]);
});
});
+
+describe('list message reuse', () => {
+ beforeEach(() => remoteSessionStore.clear());
+ it('keeps explicitly prefetched prose after leaving a task, while stale detail pushes remain blocked', () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Host', [session('s1')]);
+ const authority = remoteSessionStore.enterSessionMessageDetail('s1');
+ remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', authority);
+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:created', { sessionId: 's1', message: message('stale', 's1') });
+ const content = '完整正文'.repeat(2000);
+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:messages:created', { sessionId: 's1', listMessage: true,
+ message: { ...message('prefetched', 's1'), content } });
+ expect(remoteSessionStore.getMessages('s1').map(row => row.id)).toEqual(['prefetched']);
+ expect(remoteSessionStore.getMessages('s1')[0].content).toBe(content);
+ remoteSessionStore.enterSessionMessageDetail('s1');
+ expect(remoteSessionStore.getMessages('s1')[0].content).toBe(content);
+ });
+
+ it('does not let another device seed the same task ID', () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Host', [session('s1')]);
+ remoteSessionStore.applyRemotePush('other', 'local-db:messages:created', { sessionId: 's1', listMessage: true, message: message('wrong', 's1') });
+ expect(remoteSessionStore.getMessages('s1')).toEqual([]);
+ });
+});
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index bb26797615..5fd71bd09b 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -19,6 +19,7 @@ import {
DeviceLinkError,
CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1,
CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,
+ CONTROLLER_CAPABILITY_SESSION_LIST_MESSAGES_V1,
CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,
DEVICE_LINK_CAPABILITY_COMPACT_MESSAGE_HISTORY_V1,
DL_SUBSCRIBE_CHANNEL,
@@ -221,6 +222,7 @@ const recoveryDiagnostics = new WeakMap<DeviceLinkClient, ReturnType<typeof crea
* 被控端按能力缺失降级)。被控端只在看到对应能力后才发送新 wire 形状。
*/
const CONTROLLER_CAPABILITIES = [
+ CONTROLLER_CAPABILITY_SESSION_LIST_MESSAGES_V1,
SHARED_TASK_CAPABILITY,
CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,
CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,
diff --git a/apps/mobile/src/session/mobileSessionMessageCache.ts b/apps/mobile/src/session/mobileSessionMessageCache.ts
index 3629cfb200..ab2d449fbd 100644
--- a/apps/mobile/src/session/mobileSessionMessageCache.ts
+++ b/apps/mobile/src/session/mobileSessionMessageCache.ts
@@ -154,6 +154,22 @@ export async function cacheSessionMessages(
await cacheSessionMessagesIfCurrent(authority, messages);
}
+/** Merge a durable list push with the existing disk window, using its write/delete queue. */
+export async function cacheSessionListMessage(deviceId: string, sessionId: string, message: RemoteMessage): Promise<void> {
+ const authority = captureSessionMessageCacheWriteAuthority(deviceId, sessionId);
+ if (!authority) return;
+ await enqueueCacheOperation(authority.key, async () => {
+ if (!isSessionMessageCacheWriteAuthorityCurrent(authority)) return;
+ const raw = await messageCacheStorage.getItem(authority.key);
+ const parsed: unknown = raw ? JSON.parse(raw) : null;
+ const previous = normalizeCachedMessages(isRecord(parsed) && Array.isArray(parsed.messages) ? parsed.messages : []);
+ const messages = normalizeCachedMessages([...previous.filter(row =>
+ row.id !== message.id && (!message.clientId || row.clientId !== message.clientId)), message]);
+ if (!isSessionMessageCacheWriteAuthorityCurrent(authority)) return;
+ await messageCacheStorage.setItem(authority.key, JSON.stringify({ version: 1, updatedAt: Date.now(), messages }));
+ });
+}
+
// 登出清空:遍历所有本前缀的 key 一次性删除(AsyncStorage 支持枚举,无需手动维护 host 索引)。
export function clearCachedSessionMessages(): Promise<void> {
if (activeGlobalClear) return activeGlobalClear;
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index c01fb00543..bc63ddae55 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -48,6 +48,7 @@ import {
} from '@/session/swipeRowRegistry';
import {
cacheSessionMessagesIfCurrent,
+ cacheSessionListMessage,
captureSessionMessageCacheWriteAuthority,
getCachedSessionMessages,
isSessionMessageCacheWriteAuthorityCurrent,
@@ -186,6 +187,7 @@ export interface SetLatestMessageWindowOptions {
}
export interface SessionMessageWriteOptions {
+ listMessage?: boolean;
authority?: SessionMessageAuthority;
/** 本行是否携带主机时间域的 createdAt;本地临时卡必须显式关闭。 */
hostTimeAuthoritative?: boolean;
@@ -1011,6 +1013,12 @@ function messageWriteAllowed(
return !sessionMessageLifecycle.hasEntered(sessionId);
}
+function listMessageWriteAllowed(sessionId: string, deviceId?: string): boolean {
+ const session = mergedSessionById.get(sessionId);
+ return !!session && session.deviceLinkDeviceId === deviceId && session.status === 'active'
+ && retentionForSession(sessionId) === 'regular';
+}
+
function normalizeWindowForRetention(
sessionId: string,
list: readonly RemoteMessage[],
@@ -3805,7 +3813,7 @@ export const remoteSessionStore = {
message: RemoteMessage,
options: SessionMessageWriteOptions = {},
): void {
- if (!messageWriteAllowed(sessionId, options.authority)) return;
+ if (!options.listMessage && !messageWriteAllowed(sessionId, options.authority)) return;
let changed = flushPendingTextDelta(sessionId);
changed = settleInputProjectionFromMessages(sessionId, [message]) || changed;
const reanchorAfterMessage = options.hostTimeAuthoritative !== false && message.role === 'user';
@@ -4345,13 +4353,17 @@ export const remoteSessionStore = {
const sessionId = readString(payload, 'sessionId');
const event = isRecord(payload.event) ? payload.event : null;
const persistId = readString(payload, 'persistId') ?? undefined;
- if (sessionId && event) this.applyMakerEvent(sessionId, event, persistId, deviceId);
+ const fromList = payload.listMessage === true;
+ if (fromList && (!sessionId || !listMessageWriteAllowed(sessionId, deviceId))) return;
+ if (sessionId && event) this.applyMakerEvent(sessionId, event, persistId, deviceId, fromList);
},
applyRemotePush(deviceId: string, channel: string, payload: unknown): void {
if (channel === SESSION_SYNC_CHANNEL) {
consumeRemoteSessionSync(payload, {
- applyEvent: (event) => this.applyRemotePush(deviceId, 'maker:event', event),
+ applyEvent: (event) => this.applyRemotePush(deviceId, 'maker:event', {
+ ...event, ...(isRecord(payload) && payload.listMessage === true ? { listMessage: true } : {}),
+ }),
invalidateHistory: (sessionId) => {
sessionMessageSyncMarkers.delete(sessionId);
forgetWindowCoverage(sessionId);
@@ -4423,7 +4435,12 @@ export const remoteSessionStore = {
if (channel === 'local-db:messages:created' && isRecord(payload)) {
const sessionId = readString(payload, 'sessionId');
const message = isRecord(payload.message) ? (payload.message as unknown as RemoteMessage) : null;
- if (sessionId && message) this.appendMessage(sessionId, message);
+ const fromList = payload.listMessage === true;
+ if (fromList && (!sessionId || !listMessageWriteAllowed(sessionId, deviceId))) return;
+ if (sessionId && message) {
+ this.appendMessage(sessionId, message, { listMessage: fromList });
+ if (fromList) void cacheSessionListMessage(deviceId, sessionId, message);
+ }
return;
}
if (channel === 'local-db:messages:deleted' && isRecord(payload)) {
@@ -4700,13 +4717,14 @@ export const remoteSessionStore = {
event: Record<string, unknown>,
persistId?: string,
deviceId?: string,
+ fromList = false,
): void {
markSessionMakerActivity(sessionId);
const type = readString(event, 'type');
const reconnectCleared = type !== null && type !== 'error' && type !== 'done'
? clearSessionReconnectAttempt(sessionId)
: false;
- const fullMessageWriteAllowed = messageWriteAllowed(sessionId);
+ const fullMessageWriteAllowed = fromList || messageWriteAllowed(sessionId);
if (type === 'text') {
if (!fullMessageWriteAllowed) {
if (reconnectCleared) emit();
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index c46f87cc79..b9b2f29f38 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -11,6 +11,22 @@
> **增量适用原则**:wire protocol 兼容对所有跨端改动生效,不因是小改而豁免。
+## 任务列表提前同步聊天正文
+
+同账号控制端声明 `session-list-messages-v1` 后,`sessions` 订阅同时接收普通用户/助手
+正文、文本增量与收尾/删除事件,复用原有 channel、微批和背压恢复。仅列表接收的 payload
+带 `listMessage: true`,不建立活跃控制意图,也不因正文到达自动拉取整段历史。工具正文、
+思考、附件及超过 200,000 字符的异常长消息仍按需读取;列表显示行数不变。
+共享任务访客和供应商分享不扩展订阅范围。旧控制端未声明能力时保持原来的路由。
+
+`messages:list` / `messages:view` 的 options 可选携带 `messageBodies: { version: 1, known }`,
+known 是消息 ID 与主机提供的 SHA-256 正文指纹对。支持的主机在授权、净化之后返回
+`message-bodies-v1` 包装,只省略指纹吻合的正文,顺序、分页与消息元数据始终重新读取。
+共享 DeviceLinkClient 从本次请求固定的正文快照还原后再交给两端界面。缓存不命中或正文
+变更时仍发送全文;旧主机返回普通页面,新控制端兼容;旧控制端不请求此格式。
+传输去重仅保留有界内存,两端持久展示缓存继续使用原有账号隔离与删除屏障。
+不修改 relay、不新增权限、数据库 migration 或 Mobile 原生指纹。
+
## 支付宝已付下一期的升级拒绝
升级报价和确认可返回 HTTP 409 `PLAN_CHANGE_RENEWAL_PREPAID`。Desktop Main 仅放行该
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index bca5f75ea2..c83d5e4b81 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -1,5 +1,6 @@
import { isPeerResetRetryableInvoke, isBackgroundInvoke, bypassInvokeScheduling } from './invokePolicy.js';
import { InvokeScheduler } from './invokeScheduler.js';
+import { SessionMessageReuse } from './sessionMessageReuse.js';
import { decodeScopedEnvelope, encodeScopedEnvelope, type ScopeSupport } from './providerShareEnvelope.js';
import { isProviderSharePeer } from './providerSharePeer.js';
import { isSharedTaskPeer } from './sharedTaskPeer.js';
@@ -987,6 +988,7 @@ export class DeviceLinkClient {
}
stop(): void {
+ this.messageReuse.clear();
if (this.stopped) return;
this.stopped = true;
this.clearTimers();
@@ -1377,12 +1379,13 @@ export class DeviceLinkClient {
options?: { preSend?: () => void },
): Promise<InvokeResultPayload> {
if (this.status !== 'online') throw new DeviceLinkError('NOT_CONNECTED', 'not connected to relay');
+ const reuse = this.messageReuse.prepare(dst, payload);
const send = () => {
// Admission may wait: validate caller ownership/cancellation after dequeue,
// synchronously before creating the request or retaining a transport frame.
options?.preSend?.();
return this.request(
- { v: PROTOCOL_VERSION, kind: 'invoke', dst, payload: requestSessionTagCatalog(payload) },
+ { v: PROTOCOL_VERSION, kind: 'invoke', dst, payload: requestSessionTagCatalog(reuse.payload) },
'invoke-result',
timeoutMs,
);
@@ -1394,7 +1397,7 @@ export class DeviceLinkClient {
return result.ok
? {
...result,
- result: decodeSessionTagCatalog(payload.channel, result.result),
+ result: reuse.decode(decodeSessionTagCatalog(payload.channel, result.result)),
}
: result;
}
@@ -2856,7 +2859,13 @@ export class DeviceLinkClient {
return task;
}
+ private readonly messageReuse = new SessionMessageReuse();
+
private emitFrame(env: Envelope): boolean | Promise<boolean> {
+ if (env.kind === 'push' && env.src) {
+ const push = env.payload as { channel: string; payload: unknown };
+ this.messageReuse.receive(env.src, push.channel, push.payload);
+ }
let ok = true;
let chain: Promise<void> | null = null;
for (const cb of this.frameHandlers) {
diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.ts
index 297c2b21e7..c3fc0054c9 100644
--- a/packages/device-link/src/index.ts
+++ b/packages/device-link/src/index.ts
@@ -45,6 +45,7 @@ export * from "./providerShareCatalog.js";
export * from "./providerShareEnvelope.js";
export * from "./modelFavorites.js";
export * from "./sessionListTransport.js";
+export * from './sessionMessageReuse.js';
export * from "./clipboardSync.js";
export * from "./clipboardSyncFailure.js";
diff --git a/packages/device-link/src/sessionMessageReuse.ts b/packages/device-link/src/sessionMessageReuse.ts
new file mode 100644
index 0000000000..e9c556d880
--- /dev/null
+++ b/packages/device-link/src/sessionMessageReuse.ts
@@ -0,0 +1,209 @@
+import type { InvokePayload } from "./protocol.js";
+
+/** List subscribers opt into ordinary chat text, without active-control intent. */
+export const CONTROLLER_CAPABILITY_SESSION_LIST_MESSAGES_V1 =
+ "session-list-messages-v1";
+export const MESSAGE_BODY_FORMAT = "message-bodies-v1";
+const MAX_BODIES = 256;
+const MAX_BYTES = 8 * 1024 * 1024;
+export const MAX_LIST_MESSAGE_CHARS = 200_000;
+export const messageRecord = (
+ value: unknown,
+): value is Record<string, unknown> =>
+ !!value && typeof value === "object" && !Array.isArray(value);
+
+/** Attachments and structured cards keep their existing on-demand path. */
+export function isReusableMessage(
+ row: unknown,
+): row is Record<string, unknown> & { id: string } {
+ return (
+ messageRecord(row) &&
+ typeof row.id === "string" &&
+ row.id.length > 0 &&
+ (row.role === "assistant" || row.role === "user") &&
+ (typeof row.content === "string"
+ ? row.content.length <= MAX_LIST_MESSAGE_CHARS
+ : messageRecord(row.content) &&
+ typeof row.content.text === "string" &&
+ row.content.text.length <= MAX_LIST_MESSAGE_CHARS &&
+ Object.keys(row.content).every((key) => key === "text"))
+ );
+}
+
+export function isListMessagePush(channel: string, value: unknown): boolean {
+ if (!messageRecord(value)) return false;
+ if (channel === "local-db:messages:created")
+ return isReusableMessage(value.message);
+ if (
+ channel === "local-db:messages:deleted" ||
+ channel === "maker:status-changed"
+ )
+ return true;
+ if (channel !== "maker:event" || !messageRecord(value.event)) return false;
+ const event = value.event;
+ if (event.type === "done") return true;
+ return (
+ event.type === "text" &&
+ messageRecord(event.data) &&
+ typeof event.data.text === "string" &&
+ event.data.text.length <= MAX_LIST_MESSAGE_CHARS
+ );
+}
+
+/** Only traverse protocol message containers, never user content. */
+export function mapMessageBodies(
+ value: unknown,
+ map: (row: Record<string, unknown>) => unknown,
+): unknown {
+ if (Array.isArray(value))
+ return value.map((row) => (messageRecord(row) ? map(row) : row));
+ if (!messageRecord(value)) return value;
+ if (Array.isArray(value.items))
+ return {
+ ...value,
+ items: value.items.map(function item(value): unknown {
+ if (!messageRecord(value)) return value;
+ if (value.type === "messages" && Array.isArray(value.messages))
+ return { ...value, messages: mapMessageBodies(value.messages, map) };
+ if (value.type === "work" && Array.isArray(value.children))
+ return { ...value, children: value.children.map(item) };
+ return value;
+ }),
+ };
+ if (Array.isArray(value.messages))
+ return { ...value, messages: mapMessageBodies(value.messages, map) };
+ return value;
+}
+
+type Body = { id: string; version: string; contentJson: string };
+const readChannels = new Set([
+ "local-db:messages:list",
+ "local-db:messages:view",
+]);
+
+/** Bounded transport deduplication; app stores remain responsible for display and disk. */
+export class SessionMessageReuse {
+ private bodies = new Map<
+ string,
+ { peer: string; session: string; body: Body }
+ >();
+ private bytes = 0;
+ private generation = 0;
+
+ clear(): void {
+ this.bodies.clear();
+ this.bytes = 0;
+ this.generation++;
+ }
+
+ private remember(
+ peer: string,
+ session: string,
+ row: Record<string, unknown>,
+ ): void {
+ if (
+ !isReusableMessage(row) ||
+ typeof row.remoteBodyVersion !== "string" ||
+ !/^[a-f0-9]{64}$/.test(row.remoteBodyVersion)
+ )
+ return;
+ const key = JSON.stringify([peer, session, row.id]);
+ const previous = this.bodies.get(key);
+ if (previous) this.bytes -= previous.body.contentJson.length * 2;
+ this.bodies.delete(key);
+ const contentJson = JSON.stringify(row.content);
+ this.bodies.set(key, {
+ peer,
+ session,
+ body: { id: row.id, version: row.remoteBodyVersion, contentJson },
+ });
+ this.bytes += contentJson.length * 2;
+ while (this.bodies.size > MAX_BODIES || this.bytes > MAX_BYTES) {
+ const first = this.bodies.entries().next().value!;
+ this.bytes -= first[1].body.contentJson.length * 2;
+ this.bodies.delete(first[0]);
+ }
+ }
+
+ receive(peer: string, channel: string, payload: unknown): void {
+ if (!messageRecord(payload) || typeof payload.sessionId !== "string")
+ return;
+ if (
+ channel === "local-db:messages:created" &&
+ messageRecord(payload.message)
+ ) {
+ this.remember(peer, payload.sessionId, payload.message);
+ }
+ // A clear/delete may reuse the same identity later; never advertise old bodies.
+ if (
+ channel === "local-db:messages:deleted" ||
+ channel === "local-db:session:error-persisted" ||
+ (channel === "local-db:sessions:patched" &&
+ messageRecord(payload.patch) &&
+ ("clearedAt" in payload.patch ||
+ payload.patch.status === "deleted" ||
+ payload.patch.status === "archived"))
+ ) {
+ for (const [key, entry] of this.bodies) {
+ if (entry.peer !== peer || entry.session !== payload.sessionId)
+ continue;
+ this.bytes -= entry.body.contentJson.length * 2;
+ this.bodies.delete(key);
+ }
+ }
+ }
+
+ prepare(
+ peer: string,
+ payload: InvokePayload,
+ ): { payload: InvokePayload; decode(value: unknown): unknown } {
+ const session = payload.args?.[0];
+ if (
+ !readChannels.has(payload.channel) ||
+ typeof session !== "string" ||
+ (payload.args[1] != null && !messageRecord(payload.args[1]))
+ )
+ return { payload, decode: (value) => value };
+ // This immutable request snapshot survives eviction, later pushes and concurrent reads.
+ const snapshot = new Map<string, Body>();
+ for (const entry of this.bodies.values()) {
+ if (entry.peer === peer && entry.session === session)
+ snapshot.set(entry.body.id, entry.body);
+ }
+ const generation = this.generation;
+ const args = [...payload.args];
+ args[1] = {
+ ...((args[1] as object) ?? {}),
+ messageBodies: {
+ version: 1,
+ known: [...snapshot.values()].map(({ id, version }) => [id, version]),
+ },
+ };
+ return {
+ payload: { ...payload, args },
+ decode: (value) => {
+ const packed =
+ messageRecord(value) && value.format === MESSAGE_BODY_FORMAT;
+ const decoded = mapMessageBodies(
+ packed ? value.value : value,
+ (row) => {
+ let restored = row;
+ if (
+ packed &&
+ !Object.prototype.hasOwnProperty.call(row, "content")
+ ) {
+ const body = snapshot.get(String(row.id));
+ if (!body || row.remoteBodyVersion !== body.version)
+ throw new Error("Missing remote message body");
+ restored = { ...row, content: JSON.parse(body.contentJson) };
+ }
+ if (generation === this.generation)
+ this.remember(peer, session, restored);
+ return restored;
+ },
+ );
+ return decoded;
+ },
+ };
+ }
+}
diff --git a/scripts/device-link/reconnect.test.ts b/scripts/device-link/reconnect.test.ts
index d489f70c94..792fa69aa4 100644
--- a/scripts/device-link/reconnect.test.ts
+++ b/scripts/device-link/reconnect.test.ts
@@ -17,6 +17,8 @@ import {
PROTOCOL_VERSION,
} from "../../packages/device-link/src/protocol";
import { createSubscriptionReplayScheduler } from "../../apps/desktop/src/main/device-link/subscriptionReplayScheduler";
+import { encodeMessageBodies, versionMessageBody } from '../../apps/desktop/src/main/device-link/sessionMessageReuse';
+import { CONTROLLER_CAPABILITY_SESSION_LIST_MESSAGES_V1, type InvokePayload } from '../../packages/device-link/src/index';
const until = (check: () => void) =>
vi.waitFor(check, { timeout: 8_000, interval: 10 });
@@ -57,6 +59,58 @@ async function setup() {
}
describe("Device Link over real loopback WebSockets (contract fixture)", () => {
+ it('reuses a full long list message over real sockets on both desktop and mobile', async () => {
+ const relay = await createRelayFixture();
+ cleanups.push(() => relay.close());
+ const host = createClient(relay.url, 'host', true);
+ const phone = createClient(relay.url, 'phone');
+ const desktop = createClient(relay.url, 'desktop', false, { desktop: true });
+ cleanups.push(() => host.close(), () => phone.close(), () => desktop.close());
+ const text = '提前传输的完整聊天内容,打开时直接复用。'.repeat(2000);
+ const row = { id: 'm1', clientId: 'm1', sessionId: SESSION_ID, role: 'assistant', content: text,
+ createdAt: '2026-10-10T00:00:00.000Z' };
+ const page = { version: 1, items: [{ type: 'messages', key: 'm1', messages: [row] }], hasMore: false, nextCursor: null };
+ const wireResults: unknown[] = [];
+ const received = new Set<string>();
+ const subscribed = new Map<string, string[]>();
+ host.client.onFrame(env => {
+ if (!env.src || !env.id) return;
+ if (env.kind === 'link-open') {
+ host.client.sendLinkAccept(env.src, env.id, { appVersion: 'test', allowlistHash: 'fixture' });
+ } else if (env.kind === 'invoke') {
+ const request = env.payload as InvokePayload;
+ if (request.channel === 'device-link:subscribe') {
+ subscribed.set(env.src, (request.args[0] as { topics: string[] }).topics);
+ host.client.sendInvokeResult(env.src, env.id, { ok: true, result: {} });
+ } else {
+ const result = encodeMessageBodies(request.channel, request.args, page);
+ wireResults.push(result);
+ host.client.sendInvokeResult(env.src, env.id, { ok: true, result });
+ }
+ }
+ });
+ host.client.start(); phone.client.start(); desktop.client.start();
+ await until(() => [host, phone, desktop].forEach(peer => expect(peer.client.getStatus()).toBe('online')));
+ for (const [id, controller] of [['phone', phone], ['desktop', desktop]] as const) {
+ controller.client.onFrame(env => { if (env.kind === 'push') received.add(id); });
+ await controller.client.openLink('host', { controllerName: id, protocolVersion: PROTOCOL_VERSION,
+ appVersion: 'test', capabilities: [CONTROLLER_CAPABILITY_SESSION_LIST_MESSAGES_V1] });
+ await invoke(controller.client, 'host', 'device-link:subscribe', [{ topics: ['sessions'] }]);
+ host.client.sendPush(id, 'local-db:messages:created', { sessionId: SESSION_ID, listMessage: true, message: versionMessageBody(row) });
+ }
+ await until(() => expect(received.size).toBe(2));
+ for (const controller of [phone, desktop]) {
+ const result = await invoke(controller.client, 'host', 'local-db:messages:view', [SESSION_ID, { lazyDetails: true }]);
+ expect(result).toMatchObject(page);
+ }
+ expect([...subscribed.values()]).toEqual([['sessions'], ['sessions']]);
+ for (const result of wireResults) {
+ expect(JSON.stringify(result)).not.toContain(text);
+ expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThan(600);
+ }
+ process.stdout.write(`Message reuse wire evidence: full=${Buffer.byteLength(JSON.stringify(page))} bytes, phone=${Buffer.byteLength(JSON.stringify(wireResults[0]))} bytes, desktop=${Buffer.byteLength(JSON.stringify(wireResults[1]))} bytes; decoded text exact\n`);
+ });
+
it("runs the explicit external-relay entry against a provisioned fixture without silently falling back", async () => {
const relay = await createRelayFixture();
cleanups.push(() => relay.close());