Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(device-link): 共用两端流式补齐与历史恢复规则
Dash1346249b9524
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex f6a02080a6..544178237a 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -18,6 +18,7 @@ import WebSocket from 'ws';import {DeviceLinkClient,CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1,+ CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1,MAKER_EVENT_BATCH_CHANNEL,@@ -496,6 +497,7 @@ const RESPONSIVENESS_PROBE_TICK_MS = 5_000;* 必须用同一份 —— 只在一处声明会让另一条路径静默降级(mobile 侧 review 实测过这个坑)。*/const CONTROLLER_CAPABILITIES = [+ CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1,// 桌面控制桌面时同样收微批:批的收益是**relay 帧数**,只要有一个控制端不支持,diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.tsindex cc4fb78550..ffb2d6c4b2 100644--- a/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts+++ b/apps/desktop/src/renderer/__tests__/deviceLinkControllerScenarios.test.ts@@ -116,6 +116,9 @@ function makeFakeHost(deviceId: string, deviceName: string) {deviceId,deviceName,invoke,+ push(channel: string, payload: unknown): void {+ pushCb?.({ deviceId, channel, payload });+ },/** 注册控制端 onRemotePush 回调(被控端经此向控制端转发广播)。 */registerPush(cb: (p: RemotePush) => void): () => void {pushCb = (push) => cb({ ...push, ownerStamp: push.ownerStamp ?? TEST_OWNER_STAMP });@@ -203,6 +206,73 @@ afterEach(() => {});describe('device-link controller mirror — end-to-end scenarios', () => {+ it('does not lose repair signals received while the first historical page is in flight', async () => {+ const s = sid();+ const old = dbMessage(s, 'h1', 'old page', '2026-09-08T00:00:00Z');+ host.seedSession(s, {}, [old]);+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);+ let resolveFirst!: (rows: Message[]) => void;+ const first = new Promise<Message[]>((resolve) => { resolveFirst = resolve; });+ const original = host.invoke.getMockImplementation()!;+ let hold = true;+ host.invoke.mockImplementation((...args) => {+ if (args[1] === 'local-db:messages:list' && hold) { hold = false; return first; }+ return original(...args);+ });+ makerChatStore.ensureInitialMessages(s);+ await flush();+ host.hostMessage(s, dbMessage(s, 'missed', 'new history', '2026-09-08T00:00:01Z'), { lossy: true });+ // Invalid text must not throw or prevent the independent history repair.+ host.push('maker:session-sync', { sessionId: s, event: { type: 'text' }, resyncRequired: true });+ host.push('maker:session-sync', { sessionId: s, resyncRequired: true });+ resolveFirst([old]);+ await flush();+ await flush();+ expect(makerChatStore.getSnapshot(s).messages.map((message) => message.content)).toEqual(['old page', 'new history']);+ expect(host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:list')).toHaveLength(2);+ });++ it.each([true, false])('repairs missing history during a live stream without replacing its newer text (overlap=%s)', async (overlap) => {+ const s = sid();+ host.seedSession(s, {}, [dbMessage(s, 'h1', 'history', '2026-09-08T00:00:00Z')]);+ remoteProjectsStore.setDeviceSessions(DEVICE_ID, 'Mac A', [{ id: s } as Session]);+ makerChatStore.ensureInitialMessages(s);+ await flush();+ await flush();+ host.push('maker:event', { sessionId: s, event: { type: 'status', data: { status: 'Running', isRunning: true } } });+ host.push('maker:session-sync', { sessionId: s, persistId: 'live', event: {+ type: 'text', data: { text: 'live prefix', isFinal: false, isFullText: true, createdAt: '2026-09-08T00:00:02Z' },+ } });+ expect(makerChatStore.getSnapshot(s).messages.at(-1)?.content).toBe('live prefix');+ expect(makerChatStore.getSnapshot(s).isStreaming).toBe(true);+ if (!overlap) host.seedSession(s, {}, []);+ host.hostMessage(s, dbMessage(s, 'missed', 'missed history', '2026-09-08T00:00:01Z'), { lossy: true });+ const before = host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:list').length;+ host.push('maker:session-sync', { sessionId: s, resyncRequired: true });+ await flush();+ await flush();+ expect(host.invoke.mock.calls.filter(([, channel]) => channel === 'local-db:messages:list').length).toBeGreaterThan(before);+ expect(makerChatStore.getSnapshot(s).messages.map((message) => message.content)).toEqual([+ ...(overlap ? ['history'] : []), 'missed history', 'live prefix',+ ]);+ host.push('maker:event', { sessionId: s, persistId: 'live', event: {+ type: 'text', data: { text: ' tail', isFinal: false },+ } });+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(makerChatStore.getSnapshot(s).messages.at(-1)?.content).toBe('live prefix tail');+ const durable = { ...dbMessage(s, 'live-db', 'persisted', '2026-09-08T00:00:02Z'), clientId: 'live' };+ host.hostMessage(s, durable);+ expect(makerChatStore.getSnapshot(s).streamingClientId).toBe('live');+ expect(makerChatStore.getSnapshot(s).messages.at(-1)?.isStreaming).toBe(false);+ // The assembly pointer outlives persistence. It must not prevent repair of+ // a later durable correction whose push was lost.+ host.seedSession(s, {}, [{ ...durable, content: 'corrected durable' }]);+ host.push('maker:session-sync', { sessionId: s, resyncRequired: true });+ await flush();+ await flush();+ expect(makerChatStore.getSnapshot(s).messages.at(-1)?.content).toBe('corrected durable');+ });+it('完整镜像回路:开会话见历史 → live push 追加 → 丢帧 reconcile heal → 设置变更镜像', async () => {const s = sid();// 被控端已有 1 条历史 + 注册到远程项目(getSessionDeviceId 命中 → 传输层走隧道)。diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.tsindex 2321f7ebff..d8c62567ed 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts@@ -510,6 +510,34 @@ const flushPromises = async () => {};describe('makerChatStore text delta batching', () => {+ it('repairs remote text before new deltas and ignores a repair after durable takeover', () => {+ remoteProjectsStore.pinSessionOrigin('device-1', SESSION_ID);+ const send = (channel: string, payload: unknown, deviceId = 'device-1') => onRemotePush?.({ deviceId, channel, payload });+ const text = (value: string) => ({ sessionId: SESSION_ID, persistId: 'assistant-1',+ event: { type: 'text', data: { text: value, isFinal: false } } });+ const repair = { ...text('prefix suffix'), event: { type: 'text', data: {+ text: 'prefix suffix', isFinal: false, isFullText: true, createdAt: '2026-09-08T00:00:01Z',+ } } };+ send('maker:event', text(' suffix'));+ send('maker:session-sync', repair);+ send('maker:session-sync', repair);+ send('maker:event', text(' tail'));+ vi.advanceTimersByTime(32);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([+ expect.objectContaining({ clientId: 'assistant-1', content: 'prefix suffix tail',+ createdAt: '2026-09-08T00:00:01.000Z', isStreaming: true }),+ ]);+ send('maker:session-sync', { ...repair, event: { type: 'text', data: { text: 'wrong owner', isFullText: true, isFinal: false } } }, 'device-2');+ expect(makerChatStore.getSnapshot(SESSION_ID).messages[0].content).toBe('prefix suffix tail');+ send('local-db:messages:created', { sessionId: SESSION_ID, message: {+ id: 'db-id', clientId: 'assistant-1', role: 'assistant', content: 'durable answer', createdAt: '2026-09-08T00:00:01Z',+ } });+ send('maker:session-sync', repair);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual([+ expect.objectContaining({ clientId: 'assistant-1', content: 'durable answer', isStreaming: false }),+ ]);+ });+const MULTI_SESSION_IDS = Array.from({ length: 10 }, (_, i) => `${SESSION_ID}-multi-${i}`);const LRU_SESSION_IDS = Array.from({ length: 21 }, (_, i) => `${SESSION_ID}-lru-${i}`);diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex 63970d81d3..9b8475959d 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -22,6 +22,8 @@*/import type { CindyRegion } from '@cindy/maker-shared/brand-identity';+import { SESSION_SYNC_CHANNEL } from '@cindy/device-link';+import { isRemoteTextDelta, readRemoteTextSnapshot, reconcileRemoteText, consumeRemoteSessionSync } from '@cindy/maker-shared/message-window';import {getDataOwnerGeneration,isDataOwnerGenerationCurrent,@@ -215,6 +217,7 @@ const AGENT_RUNTIME_CHAT_ERROR_CODES: ReadonlySet<string> = new Set(['AUTO_REVIEW_CONFIRM_UNDELIVERED',] as const);const REMOTE_HEAVY_INBOUND_CHANNELS: ReadonlySet<string> = new Set([+ SESSION_SYNC_CHANNEL,'maker:event','maker:status-changed','maker:input:projection',@@ -5028,6 +5031,12 @@ export function handleStreamEvent(isFinal: boolean;isFullText?: boolean;};+ const snapshot = readRemoteTextSnapshot(event);+ if (snapshot?.truncated) return state;+ // Persistence can finish the row before the turn clears streamingClientId.+ // The row, rather than that assembly pointer, owns durable precedence.+ if (snapshot && event.persistId && state.messages.some((message) =>+ message.clientId === event.persistId && message.role === 'assistant' && !message.isStreaming)) return state;// A DB/history snapshot can beat the first batched delta, or an old item's// final event can arrive after a newer item starts. Identity, not tail@@ -5161,14 +5170,18 @@ export function handleStreamEvent(role: 'assistant',content: text,isStreaming: true,- createdAt: new Date().toISOString(),+ createdAt: snapshot?.createdAt ?? new Date().toISOString(),...assistantMetaFields,},],};}- const nextText = textState.streamingText + text;+ const nextText = reconcileRemoteText(textState.streamingText, text, {+ snapshot: snapshot !== undefined, durable: false,+ truncated: (event as unknown as Record<string, unknown>).__deviceLinkTruncated === true+ || (event.data as Record<string, unknown>).__deviceLinkTruncated === true,+ });const id = textState.streamingClientId;return {...textState,@@ -5176,7 +5189,7 @@ export function handleStreamEvent(messages: replaceMessage(textState.messages,(m) => m.clientId === id,- (m) => ({ ...m, content: nextText }),+ (m) => ({ ...m, content: nextText, ...(snapshot?.createdAt ? { createdAt: snapshot.createdAt } : {}) }),),};}@@ -6806,9 +6819,7 @@ function bindIpc(}function isTextDeltaEvent(event: NonNullable<MakerEventPayload>['event']): boolean {- if (event?.type !== 'text') return false;- const data = event.data as { text?: unknown; isFinal?: unknown } | null;- return data?.isFinal === false && typeof data.text === 'string';+ return isRemoteTextDelta(event);}function isHighFrequencyStreamEvent(event: NonNullable<MakerEventPayload>['event']): boolean {@@ -8189,8 +8200,27 @@ function initGlobalListeners(options: GlobalListenerOptions = {}): void {}// stall 看门狗信号:只用重会话流刷新 lastInboundEventAt。列表级轻量 activity/patch// 可能仍在持续抵达,但 maker:event 重 topic 已经断流;若这里也刷新会掩盖卡死。+ if (push.channel === SESSION_SYNC_CHANNEL+ && (!inboundSid || remoteProjectsStore.getSessionDeviceId(inboundSid) !== push.deviceId)) return;if (inboundSid && isRemoteHeavyInboundChannel(push.channel)) _markInboundEvent(inboundSid);switch (push.channel) {+ case SESSION_SYNC_CHANNEL:+ consumeRemoteSessionSync(push.payload, {+ applyEvent: (event) => handleMakerEventRaw(event, remoteIngress),+ invalidateHistory: (sessionId) => {+ const state = sessions.get(sessionId);+ if (!state) return;+ if (!state.historyLoaded) {+ // A first page captured before the repair must not clear its+ // meaning. Existing invalidated-load settlement starts one new read.+ bumpMessagesEpoch(sessionId);+ ensureInitialMessages(sessionId);+ return;+ }+ void reconcileRemoteMessages(sessionId, { repair: true });+ },+ });+ break;case 'maker:event':handleMakerEventRaw(push.payload, remoteIngress);break;@@ -11100,6 +11130,7 @@ function reconcileOpenSessionOrigins(): void {* - isStreaming=true → 跳过(不打断在串的 turn;turn 结束会再触发一次)。* 例外:`opts.force`(仅 stall 看门狗在**被控端权威报 not-running 之后**才传)放行 ——* 此时 isStreaming 是「卡死残留」而非真在串,必须能补回丢失的终态/消息。+ * repair 为已授权的补流信号:允许在途对账,但保留当前 live 行,不以旧 DB 页覆盖它。* - 无新 clientId → no-op(不产生新数组引用,避免无谓重渲染)。*//**@@ -11120,23 +11151,25 @@ function reconcileOpenSessionOrigins(): void {*/const _remoteReconcileInFlight = new Map<string,- { run: Promise<boolean>; rerun: boolean; rerunForce: boolean }+ { run: Promise<boolean>; rerun: boolean; rerunForce: boolean; rerunRepair: boolean }>();-function reconcileRemoteMessages(sessionId: string, opts?: { force?: boolean }): Promise<boolean> {+function reconcileRemoteMessages(sessionId: string, opts?: { force?: boolean; repair?: boolean }): Promise<boolean> {// 返回完成 promise 供调用方需要时等待;既有调用方均按 fire-and-forget 使用。if (!sessionId || !isRemoteSession(sessionId)) return Promise.resolve(false);const inFlight = _remoteReconcileInFlight.get(sessionId);if (inFlight) {inFlight.rerun = true;if (opts?.force) inFlight.rerunForce = true;+ if (opts?.repair) inFlight.rerunRepair = true;void reconcilePendingInteractions(sessionId).catch(() => undefined);return inFlight.run;}- const entry: { run: Promise<boolean>; rerun: boolean; rerunForce: boolean } = {+ const entry: { run: Promise<boolean>; rerun: boolean; rerunForce: boolean; rerunRepair: boolean } = {run: Promise.resolve(false),rerun: false,rerunForce: false,+ rerunRepair: false,};_remoteReconcileInFlight.set(sessionId, entry);entry.run = (async () => {@@ -11149,7 +11182,7 @@ function reconcileRemoteMessages(sessionId: string, opts?: { force?: boolean }):// 先摘掉在飞标记,再补跑 —— 补跑会自己建新的 entry,期间来的触发继续被那一份合并。_remoteReconcileInFlight.delete(sessionId);if (rerun && sessions.has(sessionId)) {- applied = await reconcileRemoteMessages(sessionId, rerunForce ? { force: true } : undefined);+ applied = await reconcileRemoteMessages(sessionId, { force: rerunForce, repair: entry.rerunRepair });}}return applied;@@ -11162,7 +11195,7 @@ function reconcileRemoteMessages(sessionId: string, opts?: { force?: boolean }):return entry.run;}-function runRemoteReconcile(sessionId: string, opts?: { force?: boolean }): Promise<boolean> {+function runRemoteReconcile(sessionId: string, opts?: { force?: boolean; repair?: boolean }): Promise<boolean> {// 挂起交互面板重建**无条件先行**,不受下方 isStreaming 守卫约束:turn 内弹出的// permission / ask / plan 正是 isStreaming=true 的常见态(pendingPermission 与// isRunning 共存),断连重连 / 聚焦时若被守卫吞掉,交互面板不重建、用户无法回应,@@ -11170,7 +11203,7 @@ function runRemoteReconcile(sessionId: string, opts?: { force?: boolean }): Prom// 未读的 passive 远程回执必须等提示真实重建后才放行。const interactionsSync = reconcilePendingInteractions(sessionId);const state = sessions.get(sessionId);- if (!state || !state.historyLoaded || (state.isStreaming && !opts?.force)) {+ if (!state || !state.historyLoaded || (state.isStreaming && !opts?.force && !opts?.repair)) {// 消息对账被守卫挡下,但交互重建照跑。为它单独开一代:turn 进行中的// needs-interaction 未读,其「内容」就是权限 / ask / plan 提示本身——提示真实// 重建(count>0)才算一代完成,挂起的 passive 回执随之放行,不必等 turn 结束。@@ -11283,7 +11316,7 @@ function runRemoteReconcile(sessionId: string, opts?: { force?: boolean }): Prom// force 时(stall 看门狗已确认被控端 not-running)放行:此处 isStreaming 是卡死残留。// 丢弃合并 = 拉回的窗口没进 UI:置 windowApplied=false,本次不得上报同步完成// (否则挂起的远程已读回执会在缺帧内容尚未展示时被放行),等 turn 结束的下一轮。- if (s.isStreaming && !opts?.force) {+ if (s.isStreaming && !opts?.force && !opts?.repair) {windowApplied = false;return s;}@@ -11291,12 +11324,14 @@ function runRemoteReconcile(sessionId: string, opts?: { force?: boolean }): Prom// 并发跳转刚 merge 进来的孤岛)。const lateArrivals = isContiguous? []- : s.messages.filter((message) => !existingIds.has(message.clientId));+ : s.messages.filter((message) => !existingIds.has(message.clientId)+ || (opts?.repair && message.isStreaming === true));// 只给"启动到现在没被动过"的行开 hydrate 口子:其余只补不改。单飞之后,期间唯一可能动过// 这些行的就是 live push(messages:created),它比本次快照更新,不该被旧快照盖回去。const untouchedSinceStart = new Set<string>();for (const message of s.messages) {- if (rowsAtStart.get(message.clientId) === message) {+ if (rowsAtStart.get(message.clientId) === message+ && !(opts?.repair && message.isStreaming === true)) {untouchedSinceStart.add(message.clientId);}}diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex e6d9239766..90f7685b42 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -22,6 +22,7 @@ import {type AgentTaskUpdate,} from '@cindy/maker-shared/agent-task';import type { MobileGoalStatusPayload } from '@cindy/maker-shared/device-link-contract';+import { isRemoteTextDelta, readRemoteTextSnapshot, reconcileRemoteText, consumeRemoteSessionSync } from '@cindy/maker-shared/message-window';import { applyCodexPlanSnapshotOnDone, markCodexPlanTurnFailed } from '@cindy/maker-shared/message-render';import {buildSessionMessagePreviewIndex,@@ -2443,11 +2444,10 @@ function applyRemoteTextEvent(const isFinal = data?.isFinal === true;// Legacy hosts already send isFullText on final events. Keep their existing// reconciliation semantics; only the new in-flight snapshot replaces text.- const isFullText = data?.isFullText === true && !isFinal;- const snapshotCreatedAt = isFullText && !isFinal && typeof data?.createdAt === 'string'- && Number.isFinite(Date.parse(data.createdAt))- ? new Date(data.createdAt).toISOString()- : undefined;+ const snapshot = readRemoteTextSnapshot(event);+ if (snapshot?.truncated) return false;+ const isFullText = snapshot !== undefined;+ const snapshotCreatedAt = snapshot?.createdAt;if (!text) return false;const authoritativeDeviceId = authoritativeSessionDeviceId(sessionId);@@ -2593,9 +2593,7 @@ function applyRemoteTextEvent(}const currentText = existing ? contentToPreview(existing.content) : '';- const nextText = isFullText && !hasDeviceLinkTruncationMarker(event) && !hasDeviceLinkTruncationMarker(data)- ? text- : isFinal+ const nextText = isFinal? (finalTextWasTruncated && existing? currentText: existing && currentText@@ -2605,7 +2603,8 @@ function applyRemoteTextEvent(? currentText: `${currentText}${text}`): text)- : currentText + text;+ : reconcileRemoteText(currentText, text, { snapshot: isFullText, durable: matchedExistingIsPersisted,+ truncated: hasDeviceLinkTruncationMarker(event) || hasDeviceLinkTruncationMarker(data) });const nextMeta = isFinal? (isRecord(event.agentMeta)? { ...(existing?.agentMeta ?? {}), ...event.agentMeta }@@ -2689,10 +2688,7 @@ function applyRemoteTextEvent(}function isRemoteTextDeltaEvent(event: Record<string, unknown>): boolean {- if (readString(event, 'type') !== 'text') return false;- const data = isRecord(event.data) ? event.data : null;- return typeof data?.text === 'string' && data.text.length > 0 && data.isFinal === false- && data.isFullText !== true;+ return isRemoteTextDelta(event);}function enqueueRemoteTextDelta(@@ -4115,17 +4111,17 @@ export const remoteSessionStore = {},applyRemotePush(deviceId: string, channel: string, payload: unknown): void {- if (channel === SESSION_SYNC_CHANNEL && isRecord(payload)) {- const sessionId = readString(payload, 'sessionId');- if (!sessionId) return;- if (isRecord(payload.event)) this.applyRemotePush(deviceId, 'maker:event', payload);- if (payload.resyncRequired === true) {- sessionMessageSyncMarkers.delete(sessionId);- forgetWindowCoverage(sessionId);- pendingRefreshSessions.add(sessionId);- bumpMessageVersion(sessionId);- emit();- }+ if (channel === SESSION_SYNC_CHANNEL) {+ consumeRemoteSessionSync(payload, {+ applyEvent: (event) => this.applyRemotePush(deviceId, 'maker:event', event),+ invalidateHistory: (sessionId) => {+ sessionMessageSyncMarkers.delete(sessionId);+ forgetWindowCoverage(sessionId);+ pendingRefreshSessions.add(sessionId);+ bumpMessageVersion(sessionId);+ emit();+ },+ });return;}if (channel === SESSION_ACTIVITY_CHANNEL) {diff --git a/packages/maker-shared/src/__tests__/remoteTextStream.test.ts b/packages/maker-shared/src/__tests__/remoteTextStream.test.tsnew file mode 100644index 0000000000..0d3bd6aaed--- /dev/null+++ b/packages/maker-shared/src/__tests__/remoteTextStream.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest';+import { consumeRemoteSessionSync, isRemoteTextDelta, readRemoteTextSnapshot, reconcileRemoteText } from '../remoteTextStream.js';++describe('remote text recovery contract', () => {+ it('replaces a missing prefix idempotently before appending newer deltas', () => {+ let text = '';+ for (const [incoming, snapshot] of [[' suffix', false], ['prefix suffix', true], ['prefix suffix', true], [' tail', false]] as const) {+ text = reconcileRemoteText(text, incoming, { snapshot, durable: false });+ }+ expect(text).toBe('prefix suffix tail');+ expect(reconcileRemoteText('persisted', 'old', { snapshot: true, durable: true })).toBe('persisted');+ expect(reconcileRemoteText(text, 'cut', { snapshot: true, durable: false, truncated: true })).toBe(text);+ });+ it('does not batch a repair or treat legacy final text as an in-flight repair', () => {+ const event = { type: 'text', data: { text: 'whole', isFinal: false, isFullText: true, createdAt: '2026-09-08T00:00:00Z' } };+ expect(isRemoteTextDelta(event)).toBe(false);+ expect(readRemoteTextSnapshot(event)?.createdAt).toBe('2026-09-08T00:00:00.000Z');+ expect(isRemoteTextDelta({ ...event, data: { text: 'delta', isFinal: false } })).toBe(true);+ expect(readRemoteTextSnapshot({ ...event, data: { ...event.data, isFinal: true } })).toBeUndefined();+ expect(readRemoteTextSnapshot({ ...event, __deviceLinkTruncated: true })?.truncated).toBe(true);+ });+ it('applies the event before optional history invalidation, ignoring malformed envelopes', () => {+ const order: string[] = [];+ const adapter = { applyEvent: () => { order.push('text'); }, invalidateHistory: (id: string) => { order.push(id); } };+ const payload = { sessionId: 's', persistId: 'p', event: { type: 'text', data: { text: 'whole', isFinal: false, isFullText: true } } };+ consumeRemoteSessionSync({ ...payload, resyncRequired: true }, adapter);+ expect(order).toEqual(['text', 's']);+ consumeRemoteSessionSync({ ...payload, resyncRequired: false }, adapter);+ consumeRemoteSessionSync({ event: {}, resyncRequired: true }, adapter);+ expect(order).toEqual(['text', 's', 'text']);+ consumeRemoteSessionSync({ sessionId: 's', event: { type: 'text' }, resyncRequired: true }, adapter);+ expect(order).toEqual(['text', 's', 'text', 's']);+ });+});diff --git a/packages/maker-shared/src/messageWindow.ts b/packages/maker-shared/src/messageWindow.tsindex 1868de76a3..722e1e366c 100644--- a/packages/maker-shared/src/messageWindow.ts+++ b/packages/maker-shared/src/messageWindow.ts@@ -1,3 +1,5 @@+export { isRemoteTextDelta, readRemoteTextSnapshot, reconcileRemoteText, consumeRemoteSessionSync } from './remoteTextStream.js';+export interface MessageScrollMetrics {contentHeight: number;offsetY: number;diff --git a/packages/maker-shared/src/remoteTextStream.ts b/packages/maker-shared/src/remoteTextStream.tsnew file mode 100644index 0000000000..50ab24b05c--- /dev/null+++ b/packages/maker-shared/src/remoteTextStream.ts@@ -0,0 +1,44 @@+/** Shared remote-stream rules. Stores, notifications and clocks belong to adapters. */+type RecordValue = Record<string, unknown>;+const record = (value: unknown): RecordValue | undefined =>+ value !== null && typeof value === 'object' && !Array.isArray(value) ? value as RecordValue : undefined;++export function isRemoteTextDelta(event: unknown): boolean {+ const value = record(event);+ const data = record(value?.data);+ return value?.type === 'text' && data?.isFinal === false && data.isFullText !== true+ && typeof data.text === 'string' && data.text.length > 0;+}++export function readRemoteTextSnapshot(event: unknown): { text: string; createdAt?: string; truncated: boolean } | undefined {+ const value = record(event);+ const data = record(value?.data);+ if (value?.type !== 'text' || data?.isFinal !== false || data.isFullText !== true+ || typeof data.text !== 'string' || !data.text) return undefined;+ const createdAt = typeof data.createdAt === 'string' && Number.isFinite(Date.parse(data.createdAt))+ ? new Date(data.createdAt).toISOString() : undefined;+ return { text: data.text, createdAt,+ truncated: value.__deviceLinkTruncated === true || data.__deviceLinkTruncated === true };+}++/** A repair replaces the prefix; it cannot overwrite a durable row or use a truncated prefix. */+export function reconcileRemoteText(current: string, incoming: string, options: {+ snapshot: boolean; durable: boolean; truncated?: boolean;+}): string {+ if (!options.snapshot) return current + incoming;+ return options.durable || options.truncated ? current : incoming;+}++export function consumeRemoteSessionSync(payload: unknown, adapter: {+ applyEvent(payload: RecordValue): void;+ invalidateHistory(sessionId: string): void;+}): void {+ const value = record(payload);+ if (!value || typeof value.sessionId !== 'string' || !value.sessionId) return;+ // Keep this order: older local batches flush before the snapshot, then history reconciles.+ const snapshot = readRemoteTextSnapshot(value.event);+ if (snapshot && !snapshot.truncated && typeof value.persistId === 'string' && value.persistId.trim()) {+ adapter.applyEvent(value);+ }+ if (value.resyncRequired === true) adapter.invalidateHistory(value.sessionId);+}