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): 列表预收收敛为完整消息并容纳离线长正文

Dash2e0eeb2b6809
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 9f5e8461e0..714bce72ea 100644
--- a/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts
@@ -137,7 +137,7 @@ afterEach(() => {
});
describe('[1] 能力协商', () => {
- it('projects done to lifecycle fields for list subscribers while retaining full detail events', async () => {
+ it('keeps SDK done off the list subscription while retaining full detail events', async () => {
const h = mkClient();
__testing.setActiveClient(h.client as never);
const capabilities = [CONTROLLER_CAPABILITY_SESSION_LIST_MESSAGES_V1, CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1];
@@ -148,9 +148,7 @@ describe('[1] 能力协商', () => {
plan: ['tool-body'], cancelled: true, silentStop: true } } };
__testing.forwardPush('maker:event', payload);
await vi.advanceTimersByTimeAsync(WINDOW_MS);
- const list = h.sent.find(push => push.dst === 'list')!.payload as MakerEventBatchPayload;
- expect(list.events).toEqual([{ sessionId: 's1', listMessage: true, event: { type: 'done', source: 'codex',
- turnContinuationId: 2, turnScope: 'background', data: { cancelled: true, silentStop: true } } }]);
+ expect(h.sent.filter(push => push.dst === 'list')).toEqual([]);
expect((h.sent.find(push => push.dst === 'detail')!.payload as MakerEventBatchPayload).events).toEqual([payload]);
});
@@ -167,9 +165,8 @@ describe('[1] 能力协商', () => {
__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(phone.map(push => push.channel)).toEqual(['local-db:messages:created']);
+ expect(phone[0].payload).toMatchObject({ listMessage: true, message: { content, remoteBodyVersion: expect.stringMatching(/^[a-f0-9]{64}$/) } });
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);
@@ -599,13 +596,13 @@ describe('[10] 收敛检查点:主动发送闸门的全部入口与边界(review
});
describe('[11] 重连恢复的顺序(review 第三轮)', () => {
- it('replays a reply completed while the relay was offline to sessions-only subscribers', () => {
+ it.each(['completed offline', '中'.repeat(200_000), '\u0000'.repeat(200_000)])('replays an allowed offline body intact (%#)', (content) => {
const h = mkClient();
__testing.setActiveClient(h.client as never);
const capabilities = [CONTROLLER_CAPABILITY_SESSION_LIST_MESSAGES_V1];
subscriptions.subscribe('phone', ['sessions'], 'phone', capabilities);
h.client.getStatus.mockReturnValue('connecting');
- const message = { id: 'final', clientId: 'final', role: 'assistant', content: 'completed offline' };
+ const message = { id: 'final', clientId: 'final', role: 'assistant', content };
__testing.forwardPush('local-db:messages:created', { sessionId: 's1', message });
expect(h.sent).toEqual([]);
h.client.getStatus.mockReturnValue('online');
@@ -766,13 +763,12 @@ describe('running session recovery on slow links', () => {
subscriptions.subscribe('list', ['sessions', 'session:s1'], 'list', [...capabilities, CONTROLLER_CAPABILITY_SESSION_LIST_MESSAGES_V1]);
__testing.handleSubscriptionFrame('list', { channel: DL_UNSUBSCRIBE_CHANNEL, args: [{ topics: ['session:s1'] }] });
await vi.advanceTimersByTimeAsync(250);
- expect(h.sent[0]).toMatchObject({ channel: SESSION_SYNC_CHANNEL, payload: { sessionId: 's1', listMessage: true, resyncRequired: true } });
- expect(JSON.stringify(h.sent[0])).not.toContain('xxx');
+ expect(h.sent).toEqual([]);
__testing.handleSubscriptionFrame('detail', { channel: DL_SUBSCRIBE_CHANNEL, args: [{ topics: ['session:s1'], capabilities }] });
expect(h.sent.at(-1)).toMatchObject({ channel: SESSION_SYNC_CHANNEL, payload: oversized });
});
- it('repairs the prefix when leaving chat and continues list text until the list is unsubscribed', async () => {
+ it('drops pending detail text when leaving chat and only prefetches the completed body', async () => {
const h = mkClient();
__testing.setActiveClient(h.client as never);
setSessionTextSnapshotReader(() => snapshot);
@@ -781,15 +777,39 @@ describe('running session recovery on slow links', () => {
__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 } });
+ expect(h.sent).toEqual([]);
__testing.forwardPush('maker:event', delta('list suffix'));
await vi.advanceTimersByTimeAsync(WINDOW_MS);
- expect(batchesIn(h.sent)[0].events).toEqual([{ ...delta('list suffix'), listMessage: true }]);
+ expect(h.sent).toEqual([]);
+ const message = { id: 'p1', role: 'assistant', content: 'complete durable body' };
+ __testing.forwardPush('local-db:messages:created', { sessionId: 's1', message });
+ expect(h.sent).toHaveLength(1);
+ expect(h.sent[0]).toMatchObject({ payload: { listMessage: true, message } });
__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);
+ expect(h.sent).toHaveLength(1);
+ });
+
+ it('never finalizes a truncated list prefix after cumulative or full-snapshot overflow', async () => {
+ const h = mkClient();
+ __testing.setActiveClient(h.client as never);
+ subscriptions.subscribe('list', ['sessions'], 'list', [...capabilities, CONTROLLER_CAPABILITY_SESSION_LIST_MESSAGES_V1]);
+ // Each delta fits the old per-event check, but together they exceed the body limit.
+ for (let i = 0; i < 3; i++) __testing.forwardPush('maker:event', delta('中'.repeat(100_000)));
+ __testing.forwardPush('maker:event', snapshot);
+ __testing.forwardPush('maker:event', { ...snapshot, event: { ...snapshot.event,
+ data: { ...snapshot.event.data, text: '中'.repeat(200_001) } } });
+ __testing.forwardPush('maker:event', { sessionId: 's1', event: { type: 'done', data: {} } });
+ __testing.forwardPush('local-db:messages:created', { sessionId: 's1',
+ message: { id: 'p1', role: 'assistant', content: '中'.repeat(300_000) } });
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(h.sent).toEqual([]);
+ // The next bounded message is independent and remains eligible for prefetch.
+ const message = { id: 'p2', role: 'assistant', content: 'next complete reply' };
+ __testing.forwardPush('local-db:messages:created', { sessionId: 's1', message });
+ expect(h.sent).toHaveLength(1);
+ expect(h.sent[0]).toMatchObject({ payload: { listMessage: true, message } });
});
it.each([
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 9a89272ffc..a352bc3bd8 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -13,7 +13,6 @@ import {
mapMessageBodies,
messageRecord,
MESSAGE_BODY_FORMAT,
- MAX_LIST_MESSAGE_CHARS,
} from '@cindy/device-link';
import { requestFilePeer, stopFilePeers } from './filePeer';
import { requestTaskMigration } from '../task-migration/service';
@@ -199,7 +198,9 @@ const UPDATE_RELAUNCH_NON_BLOCKING_INVOKE_CHANNELS: ReadonlySet<string> = new Se
'local-db:sessions:get-many',
]);
const textEncoder = new TextEncoder();
-const offlinePushQueue = createOfflinePushQueue();
+// A 200,000-code-unit body can take 1.2 MB after JSON escaping. Keep the existing
+// per-peer queue bounded, with room for that body plus its message envelope.
+const offlinePushQueue = createOfflinePushQueue({ maxBytes: 2 * 1024 * 1024 });
// Serialize the async DB check at the final wire boundary, retaining per-peer
// order even when replies arrive out of order. Bounds match best-effort push:
@@ -1284,7 +1285,7 @@ function stageSessionSync(dst: string, sessionId: string, historyRequired = true
return;
}
for (const sid of stage.sessions.keys()) {
- if (!receivesSessionText(dst, sid)) {
+ if (!subscriptions.controllerHasTopic(dst, `session:${sid}`)) {
stage.sessions.delete(sid);
continue;
}
@@ -1307,8 +1308,8 @@ function stageSessionSync(dst: string, sessionId: string, historyRequired = true
let admissionFailed = false;
sendBotCheckedPush(dst, SESSION_SYNC_CHANNEL, payload,
(projected) => {
- if (activeClient && receivesSessionText(dst, sid)) {
- activeClient.sendPush(dst, SESSION_SYNC_CHANNEL, listMessagePayload(dst, sid, projected), ownerStamp);
+ if (activeClient && subscriptions.controllerHasTopic(dst, `session:${sid}`)) {
+ activeClient.sendPush(dst, SESSION_SYNC_CHANNEL, 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)}`
@@ -1608,7 +1609,7 @@ function flushMakerEventBatchSession(
while (segment.events.length > 0) {
const slice = takeMakerEventBatchSlice(segment);
if (slice.length === 0) break;
- if (!receivesSessionText(dst, sessionId)) continue;
+ if (!subscriptions.controllerHasTopic(dst, `session:${sessionId}`)) continue;
// relay 已确认离线:只把缓冲取空(维持强不变量),不再制造成功率恒为 0 的帧。
if (outcome.offline) {
outcome.droppedEvents += slice.length;
@@ -1895,11 +1896,6 @@ 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);
- }
}
/**
@@ -1932,28 +1928,9 @@ function receivesListMessages(dst: string): boolean {
&& 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 {
- if (!receivesListMessages(dst) || subscriptions.controllerHasTopic(dst, `session:${sessionId}`)) return payload;
- const value = payload as Record<string, unknown>;
- const event = messageRecord(value.event) ? value.event : undefined;
- const data = messageRecord(event?.data) ? event.data : undefined;
- // Snapshot repair must use the same bound as ordinary list text pushes.
- if (event?.type === 'text' && typeof data?.text === 'string' && data.text.length > MAX_LIST_MESSAGE_CHARS) {
- return { sessionId, listMessage: true, resyncRequired: true };
- }
- // SDK done payloads can contain the entire turn, including tools and thinking.
- // List subscribers need only the lifecycle boundary, including continuation claims.
- if (event?.type === 'done') return {
- sessionId, listMessage: true,
- event: { type: 'done', source: event.source, turnScope: event.turnScope,
- turnContinuationId: event.turnContinuationId,
- data: { silentStop: data?.silentStop === true, cancelled: data?.cancelled === true } },
- };
- return { ...value, listMessage: true };
+ return receivesListMessages(dst) && !subscriptions.controllerHasTopic(dst, `session:${sessionId}`)
+ ? { ...(payload as object), listMessage: true } : payload;
}
function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerStamp): void {
@@ -3951,7 +3928,6 @@ 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/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 1e87daf5cc..3af39e087f 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -14,12 +14,14 @@
## 任务列表提前同步聊天正文
同账号控制端声明 `session-list-messages-v1` 后,`sessions` 订阅同时接收普通用户/助手
-正文、文本增量与收尾/删除事件,复用原有 channel、微批和背压恢复。仅列表接收的 payload
+已保存的完整正文、状态与删除事件,复用原有 channel。仅列表接收的 payload
带 `listMessage: true`,不建立活跃控制意图,也不因正文到达自动拉取整段历史。工具正文、
思考、附件及超过 200,000 字符的异常长消息仍按需读取;列表显示行数不变。
共享任务访客和供应商分享不扩展订阅范围。旧控制端未声明能力时保持原来的路由。
-列表收尾只携带生命周期字段,不转发 SDK 整轮工具/思考结果;快照补偿同样受正文长度上限
-约束,超限时只标记历史待核对。列表离线补发按 `sessions` topic 回放。桌面预收正文在现有
+流式增量、SDK 收尾与在途正文补偿只走详情订阅;列表仍显示原活动简介,不缓存未完成前缀。
+列表离线补发按 `sessions` topic 回放,现有每设备队列上限为 2 MiB,容纳 200,000 字符
+正文最坏情况下的 JSON 转义体积;仍受 128 条/5 分钟限制,超预算或过期后由打开时的
+历史核对补齐,不承诺无期限离线预收。桌面预收正文在现有
缓存写锁内合并并保留结构化历史,从未打开的任务同样计入现有内存回收预算。
`messages:list` / `messages:view` 的 options 可选携带 `messageBodies: { version: 1, known }`,
diff --git a/packages/device-link/src/sessionMessageReuse.ts b/packages/device-link/src/sessionMessageReuse.ts
index e9c556d880..33da1f375b 100644
--- a/packages/device-link/src/sessionMessageReuse.ts
+++ b/packages/device-link/src/sessionMessageReuse.ts
@@ -39,15 +39,9 @@ export function isListMessagePush(channel: string, value: unknown): boolean {
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 complete persisted bodies enter prefetch. Streaming text and SDK done
+ // stay on the detail topic: prefixes cannot establish a whole-message bound.
+ return false;
}
/** Only traverse protocol message containers, never user content. */