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。

feat(device-link): improve continuity after reconnect (#1143)

hushaowu-rhc240bc72059b
diff --git a/.github/workflows/pr-code-review.yml b/.github/workflows/pr-code-review.yml
index 436ad6247c..ef7084df7a 100644
--- a/.github/workflows/pr-code-review.yml
+++ b/.github/workflows/pr-code-review.yml
@@ -69,7 +69,7 @@ jobs:
#
# 已知残余风险(有意接受,不是疏漏):钉这一行锁住的是「跑哪份 workflow 文件、
# 什么 prompt、什么权限声明、什么工具白名单」,锁不住「该文件在运行期拉取
- # 并执行哪个版本的 action」。截至 8744cd0,被调用文件内部是两个浮动 tag——
+ # 并执行哪个版本的 action」。截至 0838103,被调用文件内部是两个浮动 tag——
# actions/checkout@v6 与 anthropics/claude-code-action@v1——它们运行在持有
# ANTHROPIC_API_KEY 与 pull-requests:write 的 job 里。
# 接受的理由:这两个分别是 GitHub 与 Anthropic 的第一方 action,tag 被恶意
@@ -78,7 +78,7 @@ jobs:
# 真正的修法在上游:让 krosdai/.github 把内部 action 钉到 SHA,本仓再 re-pin
# 到新的上游 SHA。届时删掉本段注释。
# 背景见 PR #985 与安全门 issue #999。
- uses: krosdai/.github/.github/workflows/code-review.yml@8744cd0f82b5bb4bd26bdf998fe8ce8f4f2249f7 # v1
+ uses: krosdai/.github/.github/workflows/code-review.yml@0838103fffe7d4c38247050098defc8ae47b8355 # v1
with:
pr_number: ${{ github.event.pull_request.number }}
is_draft: ${{ github.event.pull_request.draft }}
diff --git a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
index 536dcbd04f..1ac820e252 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts
@@ -394,8 +394,9 @@ import { DEVICE_LINK_RECONCILIATION_PROBE_MARKER } from '@cindy/maker-shared/dev
import { MAKER_PUSH } from '../maker-ipc/channels';
/** 最小 fake client:捕获 onFrame handler,记录出站调用 */
-function makeFakeClient() {
+function makeFakeClient(initialStatus: 'stopped' | 'connecting' | 'online' = 'online') {
let frameHandler: ((env: Envelope) => unknown | Promise<unknown>) | null = null;
+ let status = initialStatus;
const calls = {
linkAccept: [] as Array<{ dst: string; requestId: string }>,
closed: [] as Array<{ dst: string; reason: string }>,
@@ -403,6 +404,7 @@ function makeFakeClient() {
invokeResult: [] as Array<{ dst: string; requestId: string; payload: unknown }>,
};
const client = {
+ getStatus: () => status,
onFrame: (cb: (env: Envelope) => unknown | Promise<unknown>) => {
frameHandler = cb;
return () => {};
@@ -417,6 +419,9 @@ function makeFakeClient() {
return {
client: client as never,
calls,
+ setStatus: (nextStatus: 'stopped' | 'connecting' | 'online') => {
+ status = nextStatus;
+ },
feed: (env: Envelope) => frameHandler?.(env),
};
}
@@ -513,6 +518,24 @@ describe('被控端控制链路生命周期', () => {
expect(hasBroadcastTapListener()).toBe(false);
});
+ it('显式 dropAll 清理断线期间已排队的 push', () => {
+ remoteControlEnabled = true;
+ const { client, feed } = makeFakeClient();
+ wireInboundDispatch(client);
+ feed(subFrame('ctrl-drop-queue', SUB, ['session:s1']));
+ handleControllerOffline('ctrl-drop-queue');
+ tapWindowBroadcast('local-db:messages:created', {
+ sessionId: 's1',
+ id: 'm-stale',
+ });
+ expect(dispatchTesting.queuedPushesFor('ctrl-drop-queue')).toHaveLength(1);
+
+ dropAllControllers(client, 'toggle-off');
+
+ expect(dispatchTesting.queuedPushesFor('ctrl-drop-queue')).toEqual([]);
+ expect(hasBroadcastTapListener()).toBe(false);
+ });
+
it('link-open capability controls whether provider projection includes new logo kinds', async () => {
const { client, feed } = makeFakeClient();
wireInboundDispatch(client);
@@ -607,14 +630,26 @@ describe('被控端控制链路生命周期', () => {
)).toBe(false);
});
- it('link-close → 移除控制端,最后一个关闭后停 broadcast-tap', () => {
+ it('link-close clears remembered routing and queued pushes', () => {
remoteControlEnabled = true;
const { client, feed } = makeFakeClient();
wireInboundDispatch(client);
- feed({ v: 1, kind: 'link-open', id: 'r3', src: 'ctrl-c', payload: { controllerName: 'C', protocolVersion: 1, appVersion: '1' } });
- expect(getActiveControllers()).toHaveLength(1);
+ feed(subFrame('ctrl-c', SUB, ['session:s1'], 'C'));
+ handleControllerOffline('ctrl-c');
+ tapWindowBroadcast('local-db:messages:created', {
+ sessionId: 's1',
+ id: 'm-before-close',
+ });
+ expect(dispatchTesting.queuedPushesFor('ctrl-c')).toHaveLength(1);
+
feed({ v: 1, kind: 'link-close', src: 'ctrl-c', payload: { reason: 'user' } });
+ tapWindowBroadcast('local-db:messages:created', {
+ sessionId: 's1',
+ id: 'm-after-close',
+ });
+
expect(getActiveControllers()).toHaveLength(0);
+ expect(dispatchTesting.queuedPushesFor('ctrl-c')).toEqual([]);
expect(hasBroadcastTapListener()).toBe(false);
});
@@ -1725,11 +1760,78 @@ describe('被控端订阅 registry + topic 转发', () => {
appVersion: '1.0.0',
},
});
+ expect(getUpdateRelaunchControllers()).toEqual([]);
+ feed(subFrame('ctrl-modern', SUB, ['session:s1'], 'Modern reconnect'));
expect(getUpdateRelaunchControllers()).toEqual([
{ deviceId: 'ctrl-modern', name: 'Modern reconnect' },
]);
});
+ it('modern reconnect after releasing every topic waits for a fresh subscribe', () => {
+ remoteControlEnabled = true;
+ const { client, calls, feed } = makeFakeClient();
+ wireInboundDispatch(client);
+
+ feed({
+ v: 1,
+ kind: 'link-open',
+ id: 'open-modern',
+ src: 'ctrl-modern',
+ payload: {
+ controllerName: 'Modern',
+ protocolVersion: 1,
+ appVersion: '1.0.0',
+ },
+ });
+ feed(subFrame('ctrl-modern', SUB, ['sessions'], 'Modern'));
+ feed(subFrame('ctrl-modern', UNSUB, ['sessions']));
+ handleControllerOffline('ctrl-modern');
+
+ feed({
+ v: 1,
+ kind: 'link-open',
+ id: 'open-modern-again',
+ src: 'ctrl-modern',
+ payload: {
+ controllerName: 'Modern reconnect',
+ protocolVersion: 1,
+ appVersion: '1.0.0',
+ },
+ });
+
+ tapWindowBroadcast('local-db:sessions:created', { sessionId: 's1' });
+ tapWindowBroadcast('maker:event', { sessionId: 's1', event: {} });
+
+ expect(calls.push).toEqual([]);
+ expect(getUpdateRelaunchControllers()).toEqual([]);
+ });
+
+ it('dropAll closes an accepted modern reconnect before explicit subscribe', () => {
+ remoteControlEnabled = true;
+ const { client, calls, feed } = makeFakeClient();
+ wireInboundDispatch(client);
+ feed(subFrame('ctrl-modern', SUB, ['sessions'], 'Modern'));
+ handleControllerOffline('ctrl-modern');
+
+ feed({
+ v: 1,
+ kind: 'link-open',
+ id: 'open-modern-again',
+ src: 'ctrl-modern',
+ payload: {
+ controllerName: 'Modern reconnect',
+ protocolVersion: 1,
+ appVersion: '1.0.0',
+ },
+ });
+ dropAllControllers(client, 'shutdown');
+
+ expect(calls.closed).toContainEqual({
+ dst: 'ctrl-modern',
+ reason: 'shutdown',
+ });
+ });
+
it('无人值守更新忽略纯 sessions viewer,但保护文件浏览和实际会话控制', () => {
remoteControlEnabled = true;
const changes: Array<{
@@ -1893,7 +1995,7 @@ describe('被控端订阅 registry + topic 转发', () => {
expect(calls.push).toEqual([]);
});
- it('unsubscribe 移除 topic;registry 空后停 tap', () => {
+ it('explicit unsubscribe removes the final remembered topic and stops the tap', () => {
remoteControlEnabled = true;
const { client, feed } = makeFakeClient();
wireInboundDispatch(client);
@@ -1903,15 +2005,49 @@ describe('被控端订阅 registry + topic 转发', () => {
expect(hasBroadcastTapListener()).toBe(false);
});
- it('presence-offline 清掉该控制端订阅(僵尸兜底)', () => {
+ it('relay-offline queues broadcasts for active topic subscribers', () => {
+ remoteControlEnabled = true;
+ const { client, calls, feed, setStatus } = makeFakeClient();
+ wireInboundDispatch(client);
+ feed(subFrame('ctrl-a', SUB, ['session:s1']));
+ setStatus('connecting');
+
+ tapWindowBroadcast('local-db:messages:created', {
+ sessionId: 's1',
+ id: 'm1',
+ });
+
+ expect(calls.push).toEqual([]);
+ expect(dispatchTesting.queuedPushesFor('ctrl-a')).toEqual([
+ {
+ channel: 'local-db:messages:created',
+ payload: { sessionId: 's1', id: 'm1' },
+ topic: 'session:s1',
+ },
+ ]);
+ });
+
+ it('presence-offline keeps the tap alive and queues broadcasts for remembered topics', () => {
remoteControlEnabled = true;
const { client, calls, feed } = makeFakeClient();
wireInboundDispatch(client);
- feed(subFrame('ctrl-a', SUB, ['sessions']));
+ feed(subFrame('ctrl-a', SUB, ['session:s1']));
handleControllerOffline('ctrl-a');
- expect(hasBroadcastTapListener()).toBe(false);
- tapWindowBroadcast('local-db:sessions:created', { sessionId: 's1' });
+
+ expect(hasBroadcastTapListener()).toBe(true);
+ tapWindowBroadcast('local-db:messages:created', {
+ sessionId: 's1',
+ id: 'm1',
+ });
+
expect(calls.push).toEqual([]);
+ expect(dispatchTesting.queuedPushesFor('ctrl-a')).toEqual([
+ {
+ channel: 'local-db:messages:created',
+ payload: { sessionId: 's1', id: 'm1' },
+ topic: 'session:s1',
+ },
+ ]);
});
it('开关关闭 → subscribe 帧回 REMOTE_DISABLED,不记录', () => {
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 5fb32c43be..a00344f0d6 100644
--- a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts
@@ -11,6 +11,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import {
DeviceLinkError,
+ DL_SUBSCRIBE_CHANNEL,
MAX_FRAME_BYTES,
PROTOCOL_VERSION,
type InvokeResultPayload,
@@ -28,8 +29,15 @@ vi.mock('electron', () => ({
// (经 scheduler-host 传递性 import 被拉进来),补桩避免 collect 阶段报 mock 未定义
nativeImage: { createFromPath: () => ({ isEmpty: () => true }) },
}));
-vi.mock('../../logger', () => ({
- createLogger: () => ({ info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() }),
+const deviceLinkSettings = vi.hoisted(() => ({
+ value: {
+ remoteControlEnabled: true,
+ revokedControllers: [] as string[],
+ },
+}));
+
+vi.mock('../settings-store', () => ({
+ readDeviceLinkSettings: () => deviceLinkSettings.value,
}));
import { __testing } from '../dispatch';
@@ -38,12 +46,17 @@ import * as subscriptions from '../subscriptions';
/** 最小 mock client:只实现被测路径用到的两个发送方法。 */
function mkClient(
over: Partial<{
+ getStatus: ReturnType<typeof vi.fn>;
sendInvokeResult: ReturnType<typeof vi.fn>;
sendPush: ReturnType<typeof vi.fn>;
}> = {},
) {
return {
+ getStatus: over.getStatus ?? vi.fn(() => 'online'),
sendInvokeResult: over.sendInvokeResult ?? vi.fn(),
+ sendLinkAccept: vi.fn(),
+ closeLink: vi.fn(),
+ onFrame: vi.fn(),
sendPush: over.sendPush ?? vi.fn(),
};
}
@@ -56,6 +69,10 @@ const invokeResultFrameBytes = (dst: string, requestId: string, payload: InvokeR
);
beforeEach(() => {
+ deviceLinkSettings.value = {
+ remoteControlEnabled: true,
+ revokedControllers: [],
+ };
__testing.reset();
});
@@ -469,20 +486,93 @@ describe('[13] forwardPush — 转发失败 best-effort,不冒泡', () => {
expect(compact.__deviceLinkTruncated).toBe(true);
});
- it('多控制端:一个抛错不影响其它控制端收到转发', () => {
- const sendPush = vi
- .fn()
- .mockImplementationOnce(() => {
- throw tooLarge();
- })
- .mockImplementation(() => {});
+ it('离线队列只记住原 topic 订阅者并按目标 topic 入队', () => {
+ const sendPush = vi.fn();
const client = mkClient({ sendPush });
__testing.setActiveClient(client as never);
- subscriptions.subscribe('ctrl-1', ['session:s1']);
- subscriptions.subscribe('ctrl-2', ['session:s1']);
+ subscriptions.subscribe('ctrl-sessions', ['sessions']);
+ subscriptions.subscribe('ctrl-s1', ['session:s1']);
+ subscriptions.clearController('ctrl-sessions');
+ subscriptions.clearController('ctrl-s1');
+ subscriptions.subscribe('live-s1', ['session:s1']);
+ __testing.setActiveClient(null);
+ subscriptions.clearController('live-s1');
+ __testing.setActiveClient(client as never);
- expect(() => __testing.forwardPush('maker:event', { sessionId: 's1' })).not.toThrow();
- // 两个控制端都尝试过(第一个抛错被接住,第二个正常)。
- expect(sendPush).toHaveBeenCalledTimes(2);
+ __testing.forwardPush('local-db:messages:created', { sessionId: 's1', id: 'm1' });
+ expect(sendPush).not.toHaveBeenCalled();
+ expect(__testing.queuedPushesFor('ctrl-sessions')).toEqual([]);
+ expect(__testing.queuedPushesFor('ctrl-s1')).toEqual([
+ {
+ channel: 'local-db:messages:created',
+ topic: 'session:s1',
+ payload: { sessionId: 's1', id: 'm1' },
+ },
+ ]);
+ });
+
+
+ it('revoked link-open purges remembered routing and closes without accepting', () => {
+ const client = mkClient();
+ __testing.setActiveClient(client as never);
+ subscriptions.subscribe('ctrl-revoked', ['session:s1']);
+ subscriptions.clearController('ctrl-revoked');
+ __testing.forwardPush('local-db:messages:created', { sessionId: 's1', id: 'm1' });
+ deviceLinkSettings.value.revokedControllers = ['ctrl-revoked'];
+
+ __testing.handleLinkOpen(client as never, 'ctrl-revoked', 'open-1', undefined);
+
+ expect(client.closeLink).toHaveBeenCalledWith('ctrl-revoked', 'revoked');
+ expect(client.sendLinkAccept).not.toHaveBeenCalled();
+ expect(__testing.queuedPushesFor('ctrl-revoked')).toEqual([]);
+ expect(subscriptions.getKnownControllersForTopic('session:s1')).toEqual([]);
+ });
+
+ it('legacy link-open restores wildcard behavior and replays wildcard backlog', () => {
+ const client = mkClient();
+ __testing.setActiveClient(client as never);
+ subscriptions.subscribe('ctrl-legacy', ['*']);
+ subscriptions.clearController('ctrl-legacy');
+ __testing.forwardPush('local-db:messages:created', { sessionId: 's1', id: 'm1' });
+
+ __testing.handleLinkOpen(client as never, 'ctrl-legacy', 'open-1', undefined);
+
+ expect(client.sendLinkAccept).toHaveBeenCalledTimes(1);
+ expect(client.sendPush).toHaveBeenCalledWith(
+ 'ctrl-legacy',
+ 'local-db:messages:created',
+ { sessionId: 's1', id: 'm1' },
+ );
+ expect(subscriptions.__testing.topicsOf('ctrl-legacy')).toEqual(['*']);
+ });
+
+ it('remembered modern link-open waits for an explicit subscribe frame', () => {
+ const client = mkClient();
+ __testing.setActiveClient(client as never);
+ subscriptions.subscribe('ctrl-modern', ['session:s1']);
+ subscriptions.clearController('ctrl-modern');
+ __testing.forwardPush('local-db:messages:created', { sessionId: 's1', id: 'm1' });
+
+ __testing.handleLinkOpen(client as never, 'ctrl-modern', 'open-1', {
+ controllerName: 'Mobile',
+ protocolVersion: 1,
+ appVersion: '1.0.0',
+ capabilities: [],
+ });
+
+ expect(client.sendLinkAccept).toHaveBeenCalledTimes(1);
+ expect(client.sendPush).not.toHaveBeenCalled();
+ expect(subscriptions.__testing.topicsOf('ctrl-modern')).toEqual([]);
+
+ const result = __testing.handleSubscriptionFrame('ctrl-modern', {
+ channel: DL_SUBSCRIBE_CHANNEL,
+ args: [{ topics: ['session:s1'] }],
+ });
+ expect(result).toEqual({ ok: true, result: { ok: true } });
+ expect(client.sendPush).toHaveBeenCalledWith(
+ 'ctrl-modern',
+ 'local-db:messages:created',
+ { sessionId: 's1', id: 'm1' },
+ );
});
});
diff --git a/apps/desktop/src/main/device-link/__tests__/offlinePushQueue.test.ts b/apps/desktop/src/main/device-link/__tests__/offlinePushQueue.test.ts
new file mode 100644
index 0000000000..181a38a0b5
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/offlinePushQueue.test.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it } from 'vitest';
+import { createOfflinePushQueue } from '../offlinePushQueue';
+
+describe('offline push queue', () => {
+ it('coalesces only state channels and preserves event order', () => {
+ let now = 1_000;
+ const queue = createOfflinePushQueue({ now: () => now });
+
+ queue.enqueue('dev-1', {
+ channel: 'maker:status-changed',
+ topic: 'session:s1',
+ payload: { sessionId: 's1', phase: 'running' },
+ });
+ now += 1;
+ queue.enqueue('dev-1', {
+ channel: 'local-db:messages:created',
+ topic: 'session:s1',
+ payload: { sessionId: 's1', id: 'm1' },
+ });
+ now += 1;
+ queue.enqueue('dev-1', {
+ channel: 'local-db:messages:created',
+ topic: 'session:s1',
+ payload: { sessionId: 's1', id: 'm2' },
+ });
+ now += 1;
+ queue.enqueue('dev-1', {
+ channel: 'usage:message-turn-cost',
+ topic: 'session:s1',
+ payload: { sessionId: 's1', messageId: 'm1', costUsd: 1 },
+ });
+ now += 1;
+ queue.enqueue('dev-1', {
+ channel: 'usage:message-turn-cost',
+ topic: 'session:s1',
+ payload: { sessionId: 's1', messageId: 'm2', costUsd: 2 },
+ });
+ now += 1;
+ queue.enqueue('dev-1', {
+ channel: 'maker:status-changed',
+ topic: 'session:s1',
+ payload: { sessionId: 's1', phase: 'completed' },
+ });
+
+ expect(queue.drain('dev-1')).toEqual([
+ {
+ channel: 'local-db:messages:created',
+ topic: 'session:s1',
+ payload: { sessionId: 's1', id: 'm1' },
+ },
+ {
+ channel: 'local-db:messages:created',
+ topic: 'session:s1',
+ payload: { sessionId: 's1', id: 'm2' },
+ },
+ {
+ channel: 'usage:message-turn-cost',
+ topic: 'session:s1',
+ payload: { sessionId: 's1', messageId: 'm1', costUsd: 1 },
+ },
+ {
+ channel: 'usage:message-turn-cost',
+ topic: 'session:s1',
+ payload: { sessionId: 's1', messageId: 'm2', costUsd: 2 },
+ },
+ {
+ channel: 'maker:status-changed',
+ topic: 'session:s1',
+ payload: { sessionId: 's1', phase: 'completed' },
+ },
+ ]);
+ });
+
+ it('drains only the requested topics and retains the rest', () => {
+ const queue = createOfflinePushQueue();
+ queue.enqueue('dev-1', { channel: 'a', topic: 'sessions', payload: { value: 1 } });
+ queue.enqueue('dev-1', { channel: 'b', topic: 'session:s1', payload: { value: 2 } });
+
+ expect(queue.drain('dev-1', ['sessions'])).toEqual([
+ { channel: 'a', topic: 'sessions', payload: { value: 1 } },
+ ]);
+ expect(queue.drain('dev-1')).toEqual([
+ { channel: 'b', topic: 'session:s1', payload: { value: 2 } },
+ ]);
+ });
+
+ it('bounds queue length and bytes by evicting the oldest items', () => {
+ const queue = createOfflinePushQueue({
+ maxItems: 2,
+ maxBytes: 20,
+ estimateBytes: (item) => String((item.payload as { text: string }).text).length,
+ });
+
+ queue.enqueue('dev-1', { channel: 'a', topic: 'sessions', payload: { text: '11111111' } });
+ queue.enqueue('dev-1', { channel: 'b', topic: 'sessions', payload: { text: '22222222' } });
+ queue.enqueue('dev-1', { channel: 'c', topic: 'sessions', payload: { text: '33333333' } });
+
+ expect(queue.drain('dev-1').map((item) => item.channel)).toEqual(['b', 'c']);
+ });
+
+ it('expires items and isolates devices', () => {
+ let now = 1_000;
+ const queue = createOfflinePushQueue({ now: () => now, ttlMs: 100 });
+ queue.enqueue('dev-1', { channel: 'a', topic: 'sessions', payload: { value: 1 } });
+ queue.enqueue('dev-2', { channel: 'b', topic: 'sessions', payload: { value: 2 } });
+
+ now += 101;
+ expect(queue.drain('dev-1')).toEqual([]);
+ expect(queue.drain('dev-2')).toEqual([]);
+ });
+
+ it('drops single entries that exceed the byte budget', () => {
+ const queue = createOfflinePushQueue({ maxBytes: 4, estimateBytes: () => 5 });
+ queue.enqueue('dev-1', { channel: 'big', topic: 'sessions', payload: { value: 1 } });
+ expect(queue.size('dev-1')).toBe(0);
+ });
+});
diff --git a/apps/desktop/src/main/device-link/__tests__/subscriptionsTopicLifecycle.test.ts b/apps/desktop/src/main/device-link/__tests__/subscriptionsTopicLifecycle.test.ts
index a4df7d61d4..d6bbdf48a1 100644
--- a/apps/desktop/src/main/device-link/__tests__/subscriptionsTopicLifecycle.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/subscriptionsTopicLifecycle.test.ts
@@ -69,6 +69,52 @@ describe('subscriptions topic lifecycle listeners', () => {
expect(new Set(releasedTopics)).toEqual(new Set(['fs-watch:/w1', 'fs-watch:/w2', 'sessions']));
});
+ it('retains topic routing across ordinary disconnect and forgets it on revocation', () => {
+ subscriptions.subscribe('c1', ['sessions', 'session:s1']);
+ subscriptions.subscribe('c2', ['session:s2']);
+ subscriptions.clearController('c1');
+
+ expect(subscriptions.getKnownControllersForTopic('sessions')).toEqual(['c1']);
+ expect(subscriptions.getKnownControllersForTopic('session:s1')).toEqual(['c1']);
+ expect(subscriptions.getKnownControllersForTopic('session:s2')).toEqual(['c2']);
+
+ subscriptions.forgetKnownController('c1');
+ expect(subscriptions.getKnownControllerIds()).toEqual(['c2']);
+ expect(subscriptions.getKnownControllersForTopic('sessions')).toEqual([]);
+ expect(subscriptions.getKnownControllersForTopic('session:s1')).toEqual([]);
+ });
+
+ it('revocation releases active topics before forgetting remembered routing', () => {
+ subscriptions.subscribe('c1', ['fs-watch:/w1']);
+
+ subscriptions.forgetKnownController('c1');
+
+ expect(released).toHaveBeenCalledWith(['fs-watch:/w1']);
+ expect(subscriptions.getControllerIds()).toEqual([]);
+ expect(subscriptions.getKnownControllerIds()).toEqual([]);
+ });
+
+ it('reports remembered topic state across ordinary disconnect and revocation', () => {
+ expect(subscriptions.hasRememberedTopics()).toBe(false);
+ subscriptions.subscribe('c1', ['session:s1']);
+ expect(subscriptions.hasRememberedTopics()).toBe(true);
+
+ subscriptions.clearController('c1');
+ expect(subscriptions.hasRememberedTopics()).toBe(true);
+
+ subscriptions.forgetKnownController('c1');
+ expect(subscriptions.hasRememberedTopics()).toBe(false);
+ });
+
+ it('explicit unsubscribe removes remembered topics from offline routing', () => {
+ subscriptions.subscribe('c1', ['sessions', 'session:s1']);
+ subscriptions.unsubscribe('c1', ['session:s1']);
+ subscriptions.clearController('c1');
+
+ expect(subscriptions.getKnownControllersForTopic('sessions')).toEqual(['c1']);
+ expect(subscriptions.getKnownControllersForTopic('session:s1')).toEqual([]);
+ });
+
it('listener exceptions never break subscription bookkeeping', () => {
subscriptions.setTopicsReleasedListener(() => {
throw new Error('boom');
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index f866866096..a25a8f03eb 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -63,6 +63,7 @@ import { transcribeRemoteVoiceInput } from './voiceTranscribe';
import { adviseAndRecordVoiceInputDictionaryLearning } from '../voice-input/index.js';
import { readDictionaryProjectionForMobile } from '../voice-input/dictionarySyncDriver.js';
import { setBroadcastTapListener } from './broadcast-tap';
+import { createOfflinePushQueue } from './offlinePushQueue';
import * as subscriptions from './subscriptions';
import { LEGACY_TOPIC, type ActiveController } from './subscriptions';
import { MAKER_PUSH } from '../maker-ipc/channels.js';
@@ -115,6 +116,22 @@ const UPDATE_RELAUNCH_NON_BLOCKING_INVOKE_CHANNELS: ReadonlySet<string> = new Se
'local-db:sessions:list',
]);
const textEncoder = new TextEncoder();
+const offlinePushQueue = createOfflinePushQueue();
+
+/** 只排队可由 session snapshot 对账、且不携带权限终态的会话域事件。 */
+const OFFLINE_QUEUEABLE_PUSH_CHANNELS: ReadonlySet<string> = new Set([
+ 'local-db:messages:created',
+ 'local-db:messages:deleted',
+ 'local-db:session:error-persisted',
+ 'maker:event',
+ 'maker:status-changed',
+ 'maker:interaction-request',
+ 'maker:interaction-dismissed',
+ 'maker:input:projection',
+ 'maker:goal:status-changed',
+ 'usage:message-turn-cost',
+ 'usage:message-model-mismatch',
+]);
/** wire 输入 fail-closed:未知形状视为空能力集,并限制数量/长度避免撑大常驻 registry。 */
function sanitizeControllerCapabilities(value: unknown): string[] {
@@ -405,8 +422,10 @@ let remoteInvokeResultOutboxBytes = 0;
let remoteInvokeResultOutboxTimer: ReturnType<typeof setTimeout> | null = null;
/** 显式 link-close/撤权世代;旧世代仍在执行的 IPC 完成后不得把结果送进新链路。 */
const remoteInvokeLinkEpoch = new Map<string, number>();
-/** Controllers that have successfully demonstrated topic-subscription support on this link. */
+/** Controllers that have demonstrated topic-subscription support in this process/account epoch. */
const topicSubscriptionControllers = new Set<string>();
+/** 已成功 accept、尚未显式 close 的控制端;可无 active topic(现代重连等待 subscribe)。 */
+const acceptedLinkControllers = new Set<string>();
/** `sessions` 订阅出现时通知 host replay 当前列表级轻量状态。 */
type SessionsSubscribedListener = (controllerDeviceId: string) => void;
@@ -507,7 +526,24 @@ function forwardPush(channel: string, payload: unknown): void {
remotePayload = { ...payload, request };
}
const dsts = subscriptions.getControllersForTopic(topic);
- for (const dst of dsts) {
+ // The active registry describes peer topic intent, not whether this host can
+ // currently write to the relay. During host-side reconnects sendPush is a
+ // silent no-op, so route queueable pushes through the offline backlog instead.
+ const relayOnline = activeClient.getStatus() === 'online';
+ const liveTargets = relayOnline ? dsts : [];
+ const offlineTargets = subscriptions
+ .getKnownControllersForTopic(topic)
+ .filter((dst) => !liveTargets.includes(dst));
+ for (const dst of offlineTargets) {
+ if (OFFLINE_QUEUEABLE_PUSH_CHANNELS.has(channel)) {
+ offlinePushQueue.enqueue(dst, {
+ channel,
+ payload: remotePayload,
+ topic,
+ });
+ }
+ }
+ for (const dst of liveTargets) {
// 转发是尽力而为的旁路:单个控制端的帧超限(PAYLOAD_TOO_LARGE,如大 tool 输出)/ 连接异常
// 绝不能冒泡——它会经 tapWindowBroadcast 回到 broadcastToAllWindows,让被控端**本机** renderer
// 漏收该事件(本地 UI 是第一优先);per-dst 接住也避免一个控制端坏帧拖垮其它控制端的转发。
@@ -628,12 +664,17 @@ function truncateRemoteString(value: string, state: TruncationState): string {
/**
* 同步「转发 tap 开关」与「被控横幅」到当前 registry 状态。任何 registry 变更后调用:
- * - registry 非空 → 注册 forwardPush tap(无监听时 broadcast-tap 是 O(1) no-op);空 → 注销。
+ * - active registry 或 remembered topic 非空 → 注册 forwardPush tap;两者均为空 → 注销。
+ * remembered topic 让普通断线期间的广播仍可进入离线队列。
* - UI 活跃控制端集 = 持 session:<id> / legacy '*' 的订阅者。
* - 更新重启阻塞集额外包含 fs-watch:<workdir>,但不扩大 UI 被控横幅语义。
*/
function syncForwarding(): void {
- setBroadcastTapListener(subscriptions.isEmpty() ? null : forwardPush);
+ setBroadcastTapListener(
+ subscriptions.isEmpty() && !subscriptions.hasRememberedTopics()
+ ? null
+ : forwardPush,
+ );
onControllersChanged?.(
subscriptions.getControlControllers(),
subscriptions.getUpdateRelaunchControllers(),
@@ -648,6 +689,7 @@ export function dropAllControllers(
const controllerIds = new Set([
...subscriptions.getControllerIds(),
...topicSubscriptionControllers,
+ ...acceptedLinkControllers,
]);
for (const dst of controllerIds) {
try {
@@ -660,6 +702,8 @@ export function dropAllControllers(
clearAllRemoteInvokeState();
subscriptions.clearAll();
topicSubscriptionControllers.clear();
+ acceptedLinkControllers.clear();
+ offlinePushQueue.clear();
syncForwarding();
}
@@ -670,7 +714,7 @@ export function dropAllControllers(
* 不清 invoke result/outbox:presence offline 可能只是弱网重连,控制端可靠请求仍在等回包。
*/
export function handleControllerOffline(deviceId: string): void {
- topicSubscriptionControllers.delete(deviceId);
+ acceptedLinkControllers.delete(deviceId);
if (subscriptions.clearController(deviceId)) {
syncForwarding();
}
@@ -681,6 +725,15 @@ export function forgetControllerInvokeState(deviceId: string): void {
clearRemoteInvokeStateFor(deviceId);
}
+/** 显式撤销时清理短时离线队列与 remembered topic,避免恢复后重放撤权期间数据。 */
+export function purgeRevokedController(deviceId: string): void {
+ offlinePushQueue.clear(deviceId);
+ subscriptions.forgetKnownController(deviceId);
+ topicSubscriptionControllers.delete(deviceId);
+ acceptedLinkControllers.delete(deviceId);
+ syncForwarding();
+}
+
/**
* 接线被控端隧道。在 device-link host init 时调用一次。
* 返回 unsubscribe(测试/重置用)。
@@ -707,10 +760,14 @@ async function handleFrame(client: DeviceLinkClient, env: Envelope): Promise<voi
case 'link-close':
if (!src) return;
clearRemoteInvokeStateFor(src);
- topicSubscriptionControllers.delete(src);
- if (subscriptions.clearController(src)) {
- syncForwarding();
- }
+ offlinePushQueue.clear(src);
+ acceptedLinkControllers.delete(src);
+ // Keep the protocol-capability marker, but discard all remembered routing.
+ // A modern controller must reconnect and explicitly subscribe; restoring the
+ // legacy wildcard here would silently re-enable broad delivery.
+ subscriptions.clearController(src);
+ subscriptions.forgetKnownController(src);
+ syncForwarding();
log.info(`control link closed by ${shortId(src)}`);
return;
case 'invoke':
@@ -744,6 +801,7 @@ function handleLinkOpen(
// (legacy openLink 仍会超时,但控制端据此 link-close 标记「已撤销」),不接受其 link-open。
if (isControllerRevoked(src)) {
log.warn(`link-open from ${shortId(src)} rejected: access revoked`);
+ purgeRevokedController(src);
client.closeLink(src, 'revoked');
return;
}
@@ -754,19 +812,29 @@ function handleLinkOpen(
// 老控制端无 subscribe 能力:link-open 视作订阅 legacy '*'(全量转发 + 横幅),向后兼容。
// 已在当前 link 上证明支持 topic 的客户端可能重复 open;不能重新装回兼容 wildcard。
const capabilities = sanitizeControllerCapabilities(payload?.capabilities);
+ const rememberedModernTopics = subscriptions.hasRememberedModernTopics(src);
+ const knownModernController =
+ topicSubscriptionControllers.has(src)
+ || rememberedModernTopics;
// 先确认 link-accept 已经进入 socket/可靠层,再提交本地订阅状态。弱网背压下
// accept 发送失败时不能留下“控制端未连上、被控端却显示已受控”的幽灵订阅。
client.sendLinkAccept(src, requestId, {
appVersion: app.getVersion(),
allowlistHash: computeAllowlistHash(),
});
- if (topicSubscriptionControllers.has(src)) {
+ acceptedLinkControllers.add(src);
+ if (knownModernController) {
subscriptions.updateControllerMetadata(src, name, capabilities);
} else {
subscriptions.subscribe(src, [LEGACY_TOPIC], name, capabilities);
}
syncForwarding();
flushRemoteInvokeResultOutbox(src);
+ if (!knownModernController) {
+ for (const queued of offlinePushQueue.drain(src, [LEGACY_TOPIC])) {
+ sendPushBestEffort(src, queued.channel, queued.payload);
+ }
+ }
log.info(`control link opened by ${shortId(src)} (${name})`);
}
@@ -1614,10 +1682,11 @@ function handleSubscriptionFrame(src: string, payload: InvokePayload): InvokeRes
// until disconnect. Empty/fully-filtered frames leave legacy compatibility intact.
// Add the modern topics first so replacing the last legacy topic does not discard the
// controller metadata (including negotiated capabilities) with the registry entry.
+ const hadLegacyTopic = subscriptions.controllerHasTopic(src, LEGACY_TOPIC);
subscriptions.subscribe(src, topics, name, optionalControllerCapabilities(o));
if (topics.length > 0) {
topicSubscriptionControllers.add(src);
- subscriptions.unsubscribe(src, [LEGACY_TOPIC]);
+ if (hadLegacyTopic) subscriptions.unsubscribe(src, [LEGACY_TOPIC]);
}
} else {
subscriptions.unsubscribe(src, topics);
@@ -1626,6 +1695,11 @@ function handleSubscriptionFrame(src: string, payload: InvokePayload): InvokeRes
if (isSub && topics.includes('sessions')) {
notifySessionsSubscribed(src);
}
+ if (isSub && topics.length > 0) {
+ for (const queued of offlinePushQueue.drain(src, topics)) {
+ sendPushBestEffort(src, queued.channel, queued.payload);
+ }
+ }
return { ok: true, result: { ok: true } };
}
@@ -1865,8 +1939,10 @@ export const __testing = {
clearRemoteInvokeResultOutboxTimer();
remoteInvokeLinkEpoch.clear();
topicSubscriptionControllers.clear();
+ acceptedLinkControllers.clear();
onSessionsSubscribed = null;
activeClient = null;
+ offlinePushQueue.clear();
setBroadcastTapListener(null);
},
getActiveControllers,
@@ -1884,6 +1960,12 @@ export const __testing = {
remoteInvokeResultOutboxSize: () => remoteInvokeResultOutbox.size,
flushRemoteInvokeResultOutbox,
forwardPush,
+ queuedPushesFor(deviceId: string) {
+ return offlinePushQueue.snapshot(deviceId);
+ },
+ handleLinkOpen,
+ handleSubscriptionFrame,
+ purgeRevokedController,
setActiveClient(c: DeviceLinkClient | null): void {
activeClient = c;
},
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index 1fc497ef7c..6674987baa 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -56,6 +56,7 @@ import {
dropAllControllers,
forgetControllerInvokeState,
handleControllerOffline,
+ purgeRevokedController,
} from './dispatch';
import { setBusyProbe, helloBusy, pollBusyChange, resetBusyDedupe } from './busyReporter';
import {
@@ -739,6 +740,7 @@ export async function revokeController(deviceId: string): Promise<void> {
forgetControllerInvokeState(deviceId);
// 踢掉它的订阅 registry + 重算转发/横幅(复用对等下线的单设备清理路径)。
handleControllerOffline(deviceId);
+ purgeRevokedController(deviceId);
// 末尾再 poll 一次(而非仅刷新基线):写锁释放到这里之间,别的实例可能已插入
// 新授权变更,仅刷新基线会把它静默记为已生效、永不 enforce;poll 是幂等的,
// 本地刚做过的动作重复 enforce 无害,同时能捕获这条竞态窗口里的外部变更。
@@ -833,6 +835,7 @@ function pollExternalSettingsChange(): void {
}
forgetControllerInvokeState(deviceId);
handleControllerOffline(deviceId);
+ purgeRevokedController(deviceId);
log.info(`access revoked for controller ${deviceId.slice(0, 8)} (external settings change)`);
}
diff --git a/apps/desktop/src/main/device-link/offlinePushQueue.ts b/apps/desktop/src/main/device-link/offlinePushQueue.ts
new file mode 100644
index 0000000000..058d81dd0c
--- /dev/null
+++ b/apps/desktop/src/main/device-link/offlinePushQueue.ts
@@ -0,0 +1,122 @@
+export interface OfflinePushQueueItem {
+ channel: string;
+ payload: unknown;
+ /** The topic that controls whether this item may be replayed. */
+ topic: string;
+}
+
+interface QueuedPush extends OfflinePushQueueItem {
+ queuedAt: number;
+ bytes: number;
+}
+
+export interface OfflinePushQueueOptions {
+ maxItems?: number;
+ maxBytes?: number;
+ ttlMs?: number;
+ now?: () => number;
+ estimateBytes?: (item: OfflinePushQueueItem) => number;
+}
+
+export interface OfflinePushQueue {
+ enqueue(deviceId: string, item: OfflinePushQueueItem): void;
+ drain(deviceId: string, topics?: readonly string[]): OfflinePushQueueItem[];
+ snapshot(deviceId: string): OfflinePushQueueItem[];
+ clear(deviceId?: string): void;
+ size(deviceId: string): number;
+}
+
+const DEFAULT_MAX_ITEMS = 128;
+const DEFAULT_MAX_BYTES = 512 * 1024;
+const DEFAULT_TTL_MS = 5 * 60 * 1000;
+const LEGACY_TOPIC = '*';
+const STATE_COALESCE_CHANNELS: ReadonlySet<string> = new Set([
+ 'maker:status-changed',
+ 'maker:input:projection',
+ 'maker:goal:status-changed',
+]);
+
+function defaultEstimateBytes(item: OfflinePushQueueItem): number {
+ try {
+ return Buffer.byteLength(JSON.stringify(item), 'utf8');
+ } catch {
+ return 0;
+ }
+}
+
+/**
+ * 被控端到单个控制端的短时断线 push 补发队列。只在进程内保存、按设备隔离并严格限量;
+ * 断线超过 TTL 或进程退出后仍需由权威 snapshot 补齐,不能把本队列当持久真相。
+ */
+export function createOfflinePushQueue(options: OfflinePushQueueOptions = {}): OfflinePushQueue {
+ const maxItems = options.maxItems ?? DEFAULT_MAX_ITEMS;
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
+ const now = options.now ?? Date.now;
+ const estimateBytes = options.estimateBytes ?? defaultEstimateBytes;
+ const byDevice = new Map<string, QueuedPush[]>();
+
+ const prune = (deviceId: string): QueuedPush[] => {
+ const cutoff = now() - ttlMs;
+ const current = (byDevice.get(deviceId) ?? []).filter((item) => item.queuedAt >= cutoff);
+ if (current.length === 0) byDevice.delete(deviceId);
+ else byDevice.set(deviceId, current);
+ return current;
+ };
+
+ return {
+ enqueue(deviceId, item): void {
+ const bytes = Math.max(0, estimateBytes(item));
+ if (!deviceId || !item.topic || bytes === 0 || bytes > maxBytes) return;
+ const queue = prune(deviceId);
+ // 只有明确列出的状态型 channel 才保留最新值;事件型 push 必须按顺序追加。
+ if (STATE_COALESCE_CHANNELS.has(item.channel)) {
+ const sessionId = typeof item.payload === 'object' && item.payload !== null
+ ? (item.payload as { sessionId?: unknown }).sessionId
+ : undefined;
+ if (typeof sessionId === 'string' && sessionId) {
+ const duplicateIndex = queue.findIndex((queued) => {
+ if (
+ queued.channel !== item.channel
+ || queued.topic !== item.topic
+ || typeof queued.payload !== 'object'
+ || queued.payload === null
+ ) return false;
+ return (queued.payload as { sessionId?: unknown }).sessionId === sessionId;
+ });
+ if (duplicateIndex >= 0) queue.splice(duplicateIndex, 1);
+ }
+ }
+ queue.push({ ...item, queuedAt: now(), bytes });
+ let totalBytes = queue.reduce((sum, queued) => sum + queued.bytes, 0);
+ while (queue.length > maxItems || totalBytes > maxBytes) {
+ totalBytes -= queue.shift()?.bytes ?? 0;
+ }
+ if (queue.length > 0) byDevice.set(deviceId, queue);
+ else byDevice.delete(deviceId);
+ },
+ drain(deviceId, topics): OfflinePushQueueItem[] {
+ const queue = prune(deviceId);
+ if (!topics || topics.includes(LEGACY_TOPIC)) {
+ byDevice.delete(deviceId);
+ return queue.map(({ channel, payload, topic }) => ({ channel, payload, topic }));
+ }
+ const allowed = new Set(topics);
+ const selected = queue.filter((item) => allowed.has(item.topic));
+ const remaining = queue.filter((item) => !allowed.has(item.topic));
+ if (remaining.length > 0) byDevice.set(deviceId, remaining);
+ else byDevice.delete(deviceId);
+ return selected.map(({ channel, payload, topic }) => ({ channel, payload, topic }));
+ },
+ snapshot(deviceId): OfflinePushQueueItem[] {
+ return prune(deviceId).map(({ channel, payload, topic }) => ({ channel, payload, topic }));
+ },
+ clear(deviceId): void {
+ if (deviceId) byDevice.delete(deviceId);
+ else byDevice.clear();
+ },
+ size(deviceId): number {
+ return prune(deviceId).length;
+ },
+ };
+}
diff --git a/apps/desktop/src/main/device-link/subscriptions.ts b/apps/desktop/src/main/device-link/subscriptions.ts
index 689e8c8736..7cb435a91d 100644
--- a/apps/desktop/src/main/device-link/subscriptions.ts
+++ b/apps/desktop/src/main/device-link/subscriptions.ts
@@ -35,6 +35,13 @@ export interface ActiveController {
}
const registry = new Map<string, ControllerEntry>();
+/** 当前进程曾成功建立过 link 的控制端;短时断线 push 队列据此按设备隔离补发。 */
+const knownControllerIds = new Set<string>();
+/**
+ * 普通断线会清掉 active registry,但保留最后明确持有的 topic,避免离线期间的
+ * session push 被错误地补发给只订阅 sessions 或其它 session 的控制端。
+ */
+const rememberedTopicsByController = new Map<string, Set<StoredTopic>>();
/**
* topic 生命周期监听(fs-watch 档消费:订阅驱动被控端文件 watch 启停)。
@@ -105,11 +112,16 @@ export function subscribe(
): void {
// Empty/fully-filtered subscribe frames must not create a phantom remote viewer.
if (topics.length === 0) return;
+ knownControllerIds.add(deviceId);
const e = getOrCreate(deviceId, name);
if (capabilities) {
e.capabilities = new Set(capabilities.filter((value) => typeof value === 'string'));
}
for (const t of topics) e.topics.add(t as StoredTopic);
+ // Remember the topic contract across ordinary disconnects, but not across explicit revocation.
+ const remembered = rememberedTopicsByController.get(deviceId) ?? new Set<StoredTopic>();
+ for (const t of topics) remembered.add(t as StoredTopic);
+ rememberedTopicsByController.set(deviceId, remembered);
// 幂等重放也通知(控制端断链重连后 replay subscribe → 消费方按幂等语义恢复 watch)。
notifySubscribed(topics);
}
@@ -128,12 +140,26 @@ export function updateControllerMetadata(
}
}
+export function controllerHasTopic(deviceId: string, topic: string): boolean {
+ return registry.get(deviceId)?.topics.has(topic as StoredTopic) === true;
+}
+
/** 取消订阅指定 topics;该控制端 topic 清空后整条移除。空 topics 为 no-op。 */
export function unsubscribe(deviceId: string, topics: readonly string[]): void {
const e = registry.get(deviceId);
- if (!e) return;
- for (const t of topics) e.topics.delete(t as StoredTopic);
- if (e.topics.size === 0) registry.delete(deviceId);
+ const remembered = rememberedTopicsByController.get(deviceId);
+ if (!e && !remembered) return;
+ if (e) {
+ for (const t of topics) e.topics.delete(t as StoredTopic);
+ }
+ if (remembered) {
+ for (const t of topics) remembered.delete(t as StoredTopic);
+ if (remembered.size === 0) {
+ rememberedTopicsByController.delete(deviceId);
+ knownControllerIds.delete(deviceId);
+ }
+ }
+ if (e?.topics.size === 0) registry.delete(deviceId);
notifyReleased(topics.filter((t) => !topicStillHeld(t as StoredTopic)));
}
@@ -147,11 +173,20 @@ export function clearController(deviceId: string): boolean {
return true;
}
+/** 显式撤销/账号边界使用:释放 active topics,并删除断线恢复状态。 */
+export function forgetKnownController(deviceId: string): void {
+ clearController(deviceId);
+ knownControllerIds.delete(deviceId);
+ rememberedTopicsByController.delete(deviceId);
+}
+
/** 清空所有订阅(登出 / 关被控 / 退出)。 */
export function clearAll(): void {
const held = new Set<StoredTopic>();
for (const e of registry.values()) for (const t of e.topics) held.add(t);
registry.clear();
+ knownControllerIds.clear();
+ rememberedTopicsByController.clear();
held.delete(LEGACY_TOPIC);
notifyReleased([...held]);
}
@@ -160,11 +195,36 @@ export function isEmpty(): boolean {
return registry.size === 0;
}
+/** 普通断线后是否仍有可用于离线队列精确路由的 remembered topic。 */
+export function hasRememberedTopics(): boolean {
+ return rememberedTopicsByController.size > 0;
+}
+
/** 当前所有订阅控制端 deviceId(dropAllControllers 逐个 closeLink 用)。 */
export function getControllerIds(): string[] {
return [...registry.keys()];
}
+/** 当前进程曾成功建立 link 的控制端;登出/停服务时由 clearAll 一起清空。 */
+export function getKnownControllerIds(): string[] {
+ return [...knownControllerIds];
+}
+
+/** 断线前曾持有该 topic(或 legacy `'*'`)的控制端。 */
+export function getKnownControllersForTopic(topic: Topic): string[] {
+ const out: string[] = [];
+ for (const [deviceId, topics] of rememberedTopicsByController) {
+ if (topics.has(LEGACY_TOPIC) || topics.has(topic)) out.push(deviceId);
+ }
+ return out;
+}
+
+/** 该控制端曾切换到现代 topic 订阅协议(而非 legacy wildcard)。 */
+export function hasRememberedModernTopics(deviceId: string): boolean {
+ const topics = rememberedTopicsByController.get(deviceId);
+ return topics !== undefined && [...topics].some((topic) => topic !== LEGACY_TOPIC);
+}
+
/** 持有该 topic(或 legacy `'*'`)的控制端 deviceId 列表 —— topic-scoped fan-out 依据。 */
export function getControllersForTopic(topic: Topic): string[] {
const out: string[] = [];
@@ -212,6 +272,8 @@ export function getUpdateRelaunchControllers(): ActiveController[] {
export const __testing = {
reset(): void {
registry.clear();
+ knownControllerIds.clear();
+ rememberedTopicsByController.clear();
},
/** 测试用:查某控制端当前订阅的 topic 集合。 */
topicsOf(deviceId: string): string[] {
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
index c303e96057..eb3f3daff5 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
@@ -154,6 +154,36 @@ describe('local-db:messages:list cursor', () => {
expect((rows as Array<{ id: string; rowid: number }>).map((row) => row.rowid)).toEqual([1, 4]);
});
+ it('lists only rows after a stable cursor, including same-timestamp inserts', async () => {
+ const sqlite = createDb();
+ sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');
+ insertMessage(sqlite, { id: 'row-z', createdAt: 1_000, content: 'cursor' });
+ insertMessage(sqlite, { id: 'row-a', createdAt: 1_000, content: 'same timestamp newer' });
+ insertMessage(sqlite, { id: 'row-new', createdAt: 1_001, content: 'newest' });
+
+ registerMessageIpc();
+ const listHandler = h.handlers.get('local-db:messages:list');
+ const rows = await listHandler?.({}, 's1', { limit: 10, after: 'row-z' });
+
+ expect((rows as Array<{ id: string }>).map((row) => row.id)).toEqual([
+ 'row-new',
+ 'row-a',
+ ]);
+ });
+
+ it('falls back to the latest page when an after cursor is unknown', async () => {
+ const sqlite = createDb();
+ sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');
+ insertMessage(sqlite, { id: 'row-old', createdAt: 999, content: 'old' });
+ insertMessage(sqlite, { id: 'row-new', createdAt: 1_000, content: 'new' });
+
+ registerMessageIpc();
+ const listHandler = h.handlers.get('local-db:messages:list');
+ const rows = await listHandler?.({}, 's1', { limit: 1, after: 'missing' });
+
+ expect((rows as Array<{ id: string }>).map((row) => row.id)).toEqual(['row-new']);
+ });
+
it('keeps around windows stable for same timestamp rows', async () => {
const sqlite = createDb();
sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');
diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.ts
index 574f7f34f1..e42107f567 100644
--- a/apps/desktop/src/main/localDb/ipc/messages.ts
+++ b/apps/desktop/src/main/localDb/ipc/messages.ts
@@ -87,6 +87,7 @@ export function registerMessageIpc(): void {
const limit = clampLimit((opts as { limit?: number } | undefined)?.limit);
const before = (opts as { before?: string } | undefined)?.before;
const beforeTs = (opts as { beforeTs?: number } | undefined)?.beforeTs;
+ const after = (opts as { after?: string } | undefined)?.after;
const db = getDbClient().drizzle;
// 外部历史导入(Codex rollout / Claude transcript):device-link 隧道调用
@@ -96,11 +97,12 @@ export function registerMessageIpc(): void {
sid,
{},
{
- deviceLinkFirstPage: !before && beforeTs == null,
+ deviceLinkFirstPage: !before && beforeTs == null && !after,
},
);
let beforeCursor: { createdAt: number; rowid: number } | null = null;
+ let afterCursor: { createdAt: number; rowid: number } | null = null;
let beforeMs: number | null = null;
if (typeof before === 'string' && before) {
const beforeRow = await db
@@ -114,6 +116,14 @@ export function registerMessageIpc(): void {
} else if (typeof beforeTs === 'number' && Number.isFinite(beforeTs)) {
beforeMs = beforeTs;
}
+ if (!beforeCursor && beforeMs === null && typeof after === 'string' && after) {
+ const afterRow = await db
+ .select({ createdAt: messages.createdAt, rowid: messageRowid })
+ .from(messages)
+ .where(and(eq(messages.id, after), eq(messages.sessionId, sid)))
+ .limit(1);
+ if (afterRow.length > 0) afterCursor = afterRow[0];
+ }
// /clear:过滤 createdAt > session.clearedAt,本地 DB 旧消息也遵守 clearedAt 边界
const sessionRow = await db
@@ -137,6 +147,13 @@ export function registerMessageIpc(): void {
);
} else if (beforeMs !== null) {
conds.push(lt(messages.createdAt, beforeMs));
+ } else if (afterCursor) {
+ conds.push(
+ or(
+ gt(messages.createdAt, afterCursor.createdAt),
+ and(eq(messages.createdAt, afterCursor.createdAt), gt(messageRowid, afterCursor.rowid)),
+ ),
+ );
}
if (clearedAtMs !== null) conds.push(gt(messages.createdAt, clearedAtMs));
const whereExpr = and(...conds);
@@ -148,9 +165,13 @@ export function registerMessageIpc(): void {
})
.from(messages)
.where(whereExpr)
- .orderBy(desc(messages.createdAt), desc(messageRowid))
+ .orderBy(
+ afterCursor ? asc(messages.createdAt) : desc(messages.createdAt),
+ afterCursor ? asc(messageRowid) : desc(messageRowid),
+ )
.limit(limit);
- return hydrateLegacyUserTurnCosts(rows.map(messageToCamelWithRowid));
+ const orderedRows = afterCursor ? rows.slice().reverse() : rows;
+ return hydrateLegacyUserTurnCosts(orderedRows.map(messageToCamelWithRowid));
});
ipcMain.handle(
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index a3b27a8911..80a72d784f 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -2973,7 +2973,7 @@ export default function SessionScreen() {
});
// 廉价对账:updatedAt 主信号(任何消息变化都会 bump),_count 仅在两侧都有时作辅助;
// 另外要求消息窗口已被详情页同步到当前 meta,避免首页先刷新 session preview 后,
- // 详情页把旧消息缓存误判成最新。任一变化 → 只拉最新小窗对账(store 旧消息保留 + 按 key 合并);
+ // 详情页把旧消息缓存误判成最新。任一变化 → 拉取权威最新窗口并对账;
// 都没变 → 跳过整窗重拉(内容已是最新,新消息由 live subscribe 推送)。
const freshCount = sessionMeta._count?.messages;
const metaChanged = shouldRefreshLatestMessageWindowOnReopen({
@@ -2982,7 +2982,6 @@ export default function SessionScreen() {
storedSession: storedSessionAtStart,
});
if (syncRun.isStale()) return;
- remoteSessionStore.upsertDeviceSession(deviceId, deviceName, sessionMeta);
remoteSessionStore.setActiveSessionSnapshots(
deviceId,
Array.isArray(activeSessionSnapshot.activeSessions)
@@ -3010,6 +3009,7 @@ export default function SessionScreen() {
// 真实消息数推断(getSession 没给总数时退化为窗口启发式)。
setHasOlderMessages(hasOlderMessagesAfterReopen(freshCount, remoteSessionStore.getMessages(sessionId)));
}
+ remoteSessionStore.upsertDeviceSession(deviceId, deviceName, sessionMeta);
remoteSessionStore.setPendingInteractions(sessionId, Array.isArray(pendingInteractions) ? pendingInteractions : []);
remoteSessionStore.setInputProjection(sessionId, projection);
}
diff --git a/apps/mobile/src/__tests__/deviceLinkRouteFrame.test.ts b/apps/mobile/src/__tests__/deviceLinkRouteFrame.test.ts
new file mode 100644
index 0000000000..82844598e5
--- /dev/null
+++ b/apps/mobile/src/__tests__/deviceLinkRouteFrame.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { Envelope } from '@cindy/device-link';
+import {
+ handlePeerLinkCloseFrame,
+ invalidatePeerLinkState,
+} from '@/device-link/linkClose';
+
+describe('handlePeerLinkCloseFrame', () => {
+ it.each(['user', 'toggle-off', 'shutdown', 'revoked'] as const)(
+ 'invalidates retained links on peer link-close (%s)',
+ (reason) => {
+ const onLinkClosed = vi.fn();
+ const handled = handlePeerLinkCloseFrame({
+ v: 1,
+ kind: 'link-close',
+ src: 'desktop-a',
+ payload: { reason },
+ } as Envelope, onLinkClosed);
+
+ expect(handled).toBe(true);
+ expect(onLinkClosed).toHaveBeenCalledWith('desktop-a');
+ },
+ );
+
+ it('ignores unrelated frames', () => {
+ const onLinkClosed = vi.fn();
+ expect(handlePeerLinkCloseFrame({
+ v: 1,
+ kind: 'push',
+ src: 'desktop-a',
+ } as Envelope, onLinkClosed)).toBe(false);
+ expect(onLinkClosed).not.toHaveBeenCalled();
+ });
+});
+
+describe('invalidatePeerLinkState', () => {
+ it('clears retained link state and reports invalidated session topic ACKs', () => {
+ const openLinks = new Map<string, unknown>([
+ ['desktop-a', Promise.resolve()],
+ ['desktop-b', Promise.resolve()],
+ ]);
+ const remoteTopicAcks = new Map<string, Set<string>>([
+ ['desktop-a', new Set(['sessions', 'session:s1', 'session:s2'])],
+ ['desktop-b', new Set(['sessions'])],
+ ]);
+ const onTopicsInterrupted = vi.fn();
+
+ invalidatePeerLinkState(
+ 'desktop-a',
+ openLinks,
+ remoteTopicAcks,
+ onTopicsInterrupted,
+ );
+
+ expect(openLinks.has('desktop-a')).toBe(false);
+ expect(remoteTopicAcks.has('desktop-a')).toBe(false);
+ expect(openLinks.has('desktop-b')).toBe(true);
+ expect(remoteTopicAcks.has('desktop-b')).toBe(true);
+ expect(onTopicsInterrupted).toHaveBeenCalledWith([
+ 'sessions',
+ 'session:s1',
+ 'session:s2',
+ ]);
+ });
+});
diff --git a/apps/mobile/src/__tests__/messagePaging.test.ts b/apps/mobile/src/__tests__/messagePaging.test.ts
index f43c71245a..a6a64ad648 100644
--- a/apps/mobile/src/__tests__/messagePaging.test.ts
+++ b/apps/mobile/src/__tests__/messagePaging.test.ts
@@ -2,7 +2,10 @@ import { describe, expect, it } from 'vitest';
import {
hasMoreOlderMessages,
hasOlderMessagesAfterReopen,
+ collectCompleteIncrementalMessages,
hasOlderMessagesByServerCount,
+ incrementalMessagePageNeedsFallback,
+ latestMessageCursor,
listMessagesWithPayloadRetry,
MESSAGE_PAGE_SIZE,
oldestMessageCursor,
@@ -41,6 +44,22 @@ describe('messagePaging', () => {
])).toBe('m1');
});
+ it('finds the latest host cursor and skips local system cards', () => {
+ expect(latestMessageCursor([
+ message('m1', '2026-01-01T00:00:01.000Z'),
+ message('mobile-system-context-1', '2026-01-01T00:00:03.000Z'),
+ message('m2', '2026-01-01T00:00:02.000Z'),
+ ])).toBe('m2');
+ });
+
+ it('uses the host rowid to choose a same-timestamp cursor', () => {
+ const createdAt = '2026-01-01T00:00:01.000Z';
+ expect(latestMessageCursor([
+ { ...message('z-older', createdAt), rowid: 4 },
+ { ...message('a-newer', createdAt), rowid: 5 },
+ ])).toBe('a-newer');
+ });
+
it('returns null when no stable message id exists', () => {
expect(oldestMessageCursor([
{ ...message('', '2026-01-01T00:00:01.000Z'), clientId: 'client-only' },
@@ -113,6 +132,244 @@ describe('messagePaging', () => {
})).toBe(false);
});
+ describe('incrementalMessagePageNeedsFallback', () => {
+ const page = {
+ messages: [message('m2', '2026-01-01T00:00:02.000Z')],
+ limit: 20,
+ reducedByPayloadTooLarge: false,
+ };
+
+ it('accepts a complete page when the fresh count delta matches it', () => {
+ expect(incrementalMessagePageNeedsFallback({
+ page,
+ totalCount: 2,
+ previousTotalCount: 1,
+ })).toBe(false);
+ });
+
+ it('falls back when the fresh count delta is larger than the returned page', () => {
+ expect(incrementalMessagePageNeedsFallback({
+ page,
+ totalCount: 3,
+ previousTotalCount: 1,
+ })).toBe(true);
+ });
+
+ it('falls back when the fresh count regresses', () => {
+ expect(incrementalMessagePageNeedsFallback({
+ page,
+ totalCount: 1,
+ previousTotalCount: 2,
+ })).toBe(true);
+ });
+
+ it('falls back when an older host ignores the after cursor', () => {
+ expect(incrementalMessagePageNeedsFallback({
+ page: {
+ ...page,
+ messages: [
+ message('m1', '2026-01-01T00:00:01.000Z'),
+ message('m2', '2026-01-01T00:00:02.000Z'),
+ ],
+ },
+ afterMessage: message('m1', '2026-01-01T00:00:01.000Z'),
+ })).toBe(true);
+ });
+
+ it('uses rowid when checking an incremental cursor with equal timestamps', () => {
+ const createdAt = '2026-01-01T00:00:01.000Z';
+ expect(incrementalMessagePageNeedsFallback({
+ page: {
+ ...page,
+ messages: [{ ...message('m2', createdAt), rowid: 5 }],
+ },
+ afterMessage: { ...message('m1', createdAt), rowid: 4 },
+ })).toBe(false);
+ expect(incrementalMessagePageNeedsFallback({
+ page: {
+ ...page,
+ messages: [{ ...message('m0', createdAt), rowid: 3 }],
+ },
+ afterMessage: { ...message('m1', createdAt), rowid: 4 },
+ })).toBe(true);
+ });
+
+ it('falls back for a full or payload-reduced page when the total is unknown', () => {
+ const fullPage = {
+ messages: Array.from({ length: 20 }, (_, index) =>
+ message(`m${index}`, `2026-01-01T00:00:${String(index).padStart(2, '0')}.000Z`)),
+ limit: 20,
+ reducedByPayloadTooLarge: false,
+ };
+ expect(incrementalMessagePageNeedsFallback({
+ page: fullPage,
+ })).toBe(true);
+ expect(incrementalMessagePageNeedsFallback({
+ page: { ...page, reducedByPayloadTooLarge: true },
+ })).toBe(true);
+ expect(incrementalMessagePageNeedsFallback({
+ page,
+ })).toBe(false);
+ });
+ });
+
+
+ describe('collectCompleteIncrementalMessages', () => {
+ it('walks multiple after pages to collect a large delta', async () => {
+ const anchor = message('m0', '2026-01-01T00:00:00.000Z');
+ const pages = new Map([
+ ['m2', { messages: [message('m3', '2026-01-01T00:00:03.000Z'), message('m4', '2026-01-01T00:00:04.000Z')], limit: 2, reducedByPayloadTooLarge: false }],
+ ]);
+ const result = await collectCompleteIncrementalMessages({
+ initialPage: { messages: [message('m1', '2026-01-01T00:00:01.000Z'), message('m2', '2026-01-01T00:00:02.000Z')], limit: 2, reducedByPayloadTooLarge: false },
+ afterMessage: anchor,
+ fetchAfter: async (cursor) => pages.get(cursor) ?? { messages: [], limit: 2, reducedByPayloadTooLarge: false },
+ fetchLatest: async () => { throw new Error('tail fallback should not run'); },
+ fetchBefore: async () => { throw new Error('before fallback should not run'); },
+ });
+ expect(result?.map((item) => item.id)).toEqual(['m1', 'm2', 'm3', 'm4']);
+ });
+
+ it('walks backward from the latest tail when after is ignored', async () => {
+ const anchor = message('m1', '2026-01-01T00:00:01.000Z');
+ const result = await collectCompleteIncrementalMessages({
+ initialPage: { messages: [message('m4', '2026-01-01T00:00:04.000Z'), message('m5', '2026-01-01T00:00:05.000Z')], limit: 2, reducedByPayloadTooLarge: false },
+ afterMessage: anchor,
+ fetchAfter: async () => ({ messages: [message('m4', '2026-01-01T00:00:04.000Z'), message('m5', '2026-01-01T00:00:05.000Z')], limit: 2, reducedByPayloadTooLarge: false }),
+ fetchLatest: async () => ({ messages: [message('m4', '2026-01-01T00:00:04.000Z'), message('m5', '2026-01-01T00:00:05.000Z')], limit: 2, reducedByPayloadTooLarge: false }),
+ fetchBefore: async (before) => before === 'm4'
+ ? { messages: [message('m2', '2026-01-01T00:00:02.000Z'), message('m3', '2026-01-01T00:00:03.000Z')], limit: 2, reducedByPayloadTooLarge: false }
+ : before === 'm2'
+ ? { messages: [message('m1', '2026-01-01T00:00:01.000Z')], limit: 2, reducedByPayloadTooLarge: false }
+ : { messages: [], limit: 2, reducedByPayloadTooLarge: false },
+ });
+ expect(result?.map((item) => item.id)).toEqual(['m2', 'm3', 'm4', 'm5']);
+ });
+ it('keeps paging until a short page even when a net delta would be smaller', async () => {
+ const anchor = message('m0', '2026-01-01T00:00:00.000Z');
+ const calls: string[] = [];
+ const result = await collectCompleteIncrementalMessages({
+ initialPage: { messages: [message('m1', '2026-01-01T00:00:01.000Z'), message('m2', '2026-01-01T00:00:02.000Z')], limit: 2, reducedByPayloadTooLarge: false },
+ afterMessage: anchor,
+ fetchAfter: async (cursor) => {
+ calls.push(cursor);
+ return cursor === 'm2'
+ ? { messages: [message('m3', '2026-01-01T00:00:03.000Z'), message('m4', '2026-01-01T00:00:04.000Z')], limit: 2, reducedByPayloadTooLarge: false }
+ : { messages: [message('m5', '2026-01-01T00:00:05.000Z')], limit: 2, reducedByPayloadTooLarge: false };
+ },
+ fetchLatest: async () => { throw new Error('tail fallback should not run'); },
+ fetchBefore: async () => { throw new Error('before fallback should not run'); },
+ });
+ expect(calls).toEqual(['m2', 'm4']);
+ expect(result?.map((item) => item.id)).toEqual(['m1', 'm2', 'm3', 'm4', 'm5']);
+ });
+
+ it('does not accept a forward prefix after reaching the page limit', async () => {
+ const anchor = message('m0', '2026-01-01T00:00:00.000Z');
+ const result = await collectCompleteIncrementalMessages({
+ initialPage: {
+ messages: [
+ message('m1', '2026-01-01T00:00:01.000Z'),
+ message('m2', '2026-01-01T00:00:02.000Z'),
+ ],
+ limit: 2,
+ reducedByPayloadTooLarge: false,
+ },
+ afterMessage: anchor,
+ fetchAfter: async () => ({
+ messages: [
+ message('m3', '2026-01-01T00:00:03.000Z'),
+ message('m4', '2026-01-01T00:00:04.000Z'),
+ ],
+ limit: 2,
+ reducedByPayloadTooLarge: false,
+ }),
+ fetchLatest: async () => {
+ throw new Error('tail fallback should not run');
+ },
+ fetchBefore: async () => {
+ throw new Error('before fallback should not run');
+ },
+ maxPages: 1,
+ });
+
+ expect(result).toBeNull();
+ });
+
+ it('does not accept an unknown after cursor from an empty continuation', async () => {
+ const anchor = message('deleted-anchor', '2026-01-01T00:00:01.000Z');
+ const result = await collectCompleteIncrementalMessages({
+ initialPage: {
+ messages: [
+ message('m4', '2026-01-01T00:00:04.000Z'),
+ message('m5', '2026-01-01T00:00:05.000Z'),
+ ],
+ limit: 2,
+ reducedByPayloadTooLarge: false,
+ },
+ afterMessage: anchor,
+ fetchAfter: async () => ({
+ messages: [],
+ limit: 2,
+ reducedByPayloadTooLarge: false,
+ }),
+ fetchLatest: async () => ({
+ messages: [
+ message('m4', '2026-01-01T00:00:04.000Z'),
+ message('m5', '2026-01-01T00:00:05.000Z'),
+ ],
+ limit: 2,
+ reducedByPayloadTooLarge: false,
+ }),
+ fetchBefore: async () => ({
+ messages: [message('m2', '2026-01-01T00:00:02.000Z')],
+ limit: 2,
+ reducedByPayloadTooLarge: false,
+ }),
+ });
+
+ expect(result).toBeNull();
+ });
+
+ it('rejects a short backward page that never reaches the original cursor', async () => {
+ const anchor = message('deleted-anchor', '2026-01-01T00:00:01.000Z');
+ const result = await collectCompleteIncrementalMessages({
+ initialPage: {
+ messages: [
+ message('m4', '2026-01-01T00:00:04.000Z'),
+ message('m5', '2026-01-01T00:00:05.000Z'),
+ ],
+ limit: 2,
+ reducedByPayloadTooLarge: false,
+ },
+ afterMessage: anchor,
+ fetchAfter: async () => ({
+ messages: [
+ message('m4', '2026-01-01T00:00:04.000Z'),
+ message('m5', '2026-01-01T00:00:05.000Z'),
+ ],
+ limit: 2,
+ reducedByPayloadTooLarge: false,
+ }),
+ fetchLatest: async () => ({
+ messages: [
+ message('m4', '2026-01-01T00:00:04.000Z'),
+ message('m5', '2026-01-01T00:00:05.000Z'),
+ ],
+ limit: 2,
+ reducedByPayloadTooLarge: false,
+ }),
+ fetchBefore: async () => ({
+ messages: [message('m2', '2026-01-01T00:00:02.000Z')],
+ limit: 2,
+ reducedByPayloadTooLarge: false,
+ }),
+ });
+
+ expect(result).toBeNull();
+ });
+ });
+
describe('shouldRefreshLatestMessageWindowOnReopen', () => {
it('refreshes when the cached message window was never synced to the current session meta', () => {
const freshSession = sessionVersion();
diff --git a/apps/mobile/src/__tests__/presenceRecovery.test.ts b/apps/mobile/src/__tests__/presenceRecovery.test.ts
index ce433273c9..dd1a7df391 100644
--- a/apps/mobile/src/__tests__/presenceRecovery.test.ts
+++ b/apps/mobile/src/__tests__/presenceRecovery.test.ts
@@ -207,6 +207,27 @@ describe('unavailable mirror wipe timer', () => {
vi.useRealTimers();
});
+ it('does not let a fulfilled retained link defer unavailable cleanup', async () => {
+ const { deps, timers, wipe } = timerHarness();
+ const tracked = new Map();
+ const request = getOrCreatePresenceTrackedRequest(
+ tracked,
+ createPresenceAvailabilityEpochs(),
+ createPresenceAvailabilityEpochs(),
+ 'dev-1',
+ async () => 'accepted',
+ { retainSuccessful: true },
+ );
+ await request.request;
+ deps.isConfirmationInFlight = () => tracked.get('dev-1')?.pending === true;
+
+ vi.advanceTimersByTime(5_000);
+
+ expect(timers.has('dev-1')).toBe(false);
+ expect(wipe).toHaveBeenCalledWith('dev-1');
+ vi.useRealTimers();
+ });
+
it('allows only an active confirmation to cross the maximum lifetime', () => {
const { deps, states, timers, wipe } = timerHarness();
let confirming = true;
@@ -365,6 +386,76 @@ describe('presence availability epochs', () => {
await request;
});
+ it('retains a successful tracked request for link reuse until the owner invalidates it', async () => {
+ const epochs = createPresenceAvailabilityEpochs();
+ const responseEvidenceEpochs = createPresenceAvailabilityEpochs();
+ const tracked = new Map();
+ const create = vi.fn(async () => 'accepted');
+
+ const first = getOrCreatePresenceTrackedRequest(
+ tracked,
+ epochs,
+ responseEvidenceEpochs,
+ 'dev-1',
+ create,
+ { retainSuccessful: true },
+ );
+ await expect(first.request).resolves.toBe('accepted');
+ const reused = getOrCreatePresenceTrackedRequest(
+ tracked,
+ epochs,
+ responseEvidenceEpochs,
+ 'dev-1',
+ create,
+ { retainSuccessful: true },
+ );
+
+ expect(reused).toBe(first);
+ expect(reused.pending).toBe(false);
+ expect(create).toHaveBeenCalledTimes(1);
+ tracked.delete('dev-1');
+ const reopened = getOrCreatePresenceTrackedRequest(
+ tracked,
+ epochs,
+ responseEvidenceEpochs,
+ 'dev-1',
+ create,
+ { retainSuccessful: true },
+ );
+ await reopened.request;
+ expect(create).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not retain failed requests when successful reuse is enabled', async () => {
+ const epochs = createPresenceAvailabilityEpochs();
+ const responseEvidenceEpochs = createPresenceAvailabilityEpochs();
+ const tracked = new Map();
+ const create = vi.fn()
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockResolvedValueOnce('accepted');
+
+ const failed = getOrCreatePresenceTrackedRequest(
+ tracked,
+ epochs,
+ responseEvidenceEpochs,
+ 'dev-1',
+ create,
+ { retainSuccessful: true },
+ );
+ await expect(failed.request).rejects.toThrow('offline');
+ await Promise.resolve();
+ const retried = getOrCreatePresenceTrackedRequest(
+ tracked,
+ epochs,
+ responseEvidenceEpochs,
+ 'dev-1',
+ create,
+ { retainSuccessful: true },
+ );
+ await expect(retried.request).resolves.toBe('accepted');
+ expect(create).toHaveBeenCalledTimes(2);
+ });
+
it('resets epochs on logout or account change', () => {
const epochs = createPresenceAvailabilityEpochs();
markPresenceAvailabilityEpoch(epochs, 'dev-1');
diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
index 6ae9befb31..9ddcdb826b 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -132,6 +132,32 @@ function pending(kind: string, requestId?: string, persistId?: string): PendingI
describe('remoteSessionStore', () => {
beforeEach(() => remoteSessionStore.clear());
+ it('normalizes same-timestamp messages by host rowid', () => {
+ const createdAt = '2026-01-01T00:00:00.000Z';
+ remoteSessionStore.setMessages('s1', [
+ { ...message('a-newer', 's1'), createdAt, rowid: 5 },
+ { ...message('z-older', 's1'), createdAt, rowid: 4 },
+ ]);
+
+ expect(remoteSessionStore.getMessages('s1').map((item) => item.id)).toEqual([
+ 'z-older',
+ 'a-newer',
+ ]);
+ });
+
+ it('preserves arrival order for same-timestamp messages without host rowid', () => {
+ const createdAt = '2026-01-01T00:00:00.000Z';
+ remoteSessionStore.setMessages('s1', [
+ { ...message('z-first', 's1'), createdAt },
+ { ...message('a-second', 's1'), createdAt },
+ ]);
+
+ expect(remoteSessionStore.getMessages('s1').map((item) => item.id)).toEqual([
+ 'z-first',
+ 'a-second',
+ ]);
+ });
+
it('stamps sessions with device-link origin and indexes session ids', () => {
remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);
@@ -1251,6 +1277,56 @@ describe('remoteSessionStore', () => {
]);
});
+ it('keeps a same-timestamp live tail with a larger host rowid', () => {
+ const createdAt = '2026-01-01T10:00:02.000Z';
+ remoteSessionStore.setMessages('s1', [
+ { ...messageAt('old-1', 's1', '2026-01-01T00:00:01.000Z'), rowid: 1 },
+ { ...messageAt('live-3', 's1', createdAt), rowid: 3 },
+ ]);
+
+ remoteSessionStore.setLatestMessageWindow('s1', [
+ { ...messageAt('latest-1', 's1', '2026-01-01T10:00:01.000Z'), rowid: 1 },
+ { ...messageAt('latest-2', 's1', createdAt), rowid: 2 },
+ ]);
+
+ expect(remoteSessionStore.getMessages('s1').map((item) => item.id)).toEqual([
+ 'latest-1',
+ 'latest-2',
+ 'live-3',
+ ]);
+ });
+
+ it('keeps a same-timestamp pending live assistant during latest-window reconciliation', () => {
+ vi.useFakeTimers();
+ try {
+ const createdAt = '2026-01-01T10:00:02.000Z';
+ pushMakerText('s1', 'live-3', 'still streaming', false);
+ vi.runOnlyPendingTimers();
+ remoteSessionStore.setMessages('s1', remoteSessionStore.getMessages('s1').map((item) => ({
+ ...item,
+ createdAt,
+ })));
+
+ remoteSessionStore.setLatestMessageWindow('s1', [
+ { ...messageAt('latest-1', 's1', '2026-01-01T10:00:01.000Z'), rowid: 1 },
+ { ...messageAt('latest-2', 's1', createdAt), rowid: 2 },
+ ]);
+
+ const rows = remoteSessionStore.getMessages('s1');
+ expect(rows.map((item) => item.id)).toEqual([
+ 'latest-1',
+ 'live-3',
+ 'latest-2',
+ ]);
+ expect(rows.find((item) => item.clientId === 'live-3')).toMatchObject({
+ content: 'still streaming',
+ agentMeta: { isStreaming: true },
+ });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('丢弃无法确认相接的更早缓存段:本页上沿之外服务端还有历史时(#1222)', () => {
// 「有交集」不等于「连续」:交集只说明两段有共同的行,不排除更早那一段与本页之间还隔着
// 服务端仍有、本地从未加载的行。断连期间漏收几十上百条 push 时就是这样,而漏收的量不大时
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 8bf0f167d4..89a0bfa02e 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -41,6 +41,10 @@ import { normalizeMobileAgentCapabilities } from '@/session/agentCapabilities';
import { evictComposerPaletteCacheForDevice, resetComposerPaletteCache } from '@/session/composerPaletteCache';
import { clearAllDeviceModelMeta, evictDeviceModelMeta } from '@/device-link/deviceModelMetaCache';
import { dispatchFileBrowserWatchEvent } from '@/device-link/fileBrowserWatch';
+import {
+ handlePeerLinkCloseFrame,
+ invalidatePeerLinkState,
+} from '@/device-link/linkClose';
import { resolveMobileInvokeTimeoutMs } from '@/device-link/invokeTimeouts';
import {
classifySnapshotBatchFailure,
@@ -249,7 +253,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
const presenceWipeTimerDeps = useMemo(() => ({
...basePresenceWipeTimerDeps,
isConfirmationInFlight: (deviceId: string) =>
- openLinkInFlightRef.current.has(deviceId),
+ openLinkInFlightRef.current.get(deviceId)?.pending === true,
}), []);
const presenceAvailableByDeviceRef = useRef(new Map<string, boolean>());
const presenceAvailabilityEpochsRef = useRef(createPresenceAvailabilityEpochs());
@@ -276,6 +280,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
remoteResponseEvidenceEpochs,
deviceId,
() => sendOpenLinkWithAccessHandling(client, deviceId),
+ { retainSuccessful: true },
);
}, []);
@@ -651,6 +656,9 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
});
const offPresence = client.onPresenceChanged((snap) => {
markPresenceAvailabilityEpoch(presenceAvailabilityEpochsRef.current, snap.deviceId);
+ // presence 变化代表目标链路代际变化(offline / remote-disabled / 恢复都一样):
+ // 上一代成功 link 不能跨代复用,下一次请求必须重新 link-open 确认。
+ openLinkInFlightRef.current.delete(snap.deviceId);
setLastPresenceSnapshot(snap);
setPresenceVersion((n) => n + 1);
const presence = updatePresenceAvailability(
@@ -711,6 +719,12 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
});
const offFrame = client.onFrame((env) => routeFrame(env, {
onAccessRevoked: (deviceId) => remoteSubscribedTopicsRef.current.delete(deviceId),
+ onLinkClosed: (deviceId) => invalidatePeerLinkState(
+ deviceId,
+ openLinkInFlightRef.current,
+ remoteSubscribedTopicsRef.current,
+ noteSessionLiveStreamsInterrupted,
+ ),
onProviderChanged: (deviceId) => {
// provider 目录与 capabilities.availableModels 是同一份 active catalog 的两种视图。
// 同时驱逐并后台重拉;页面保留旧画面,当前代完整快照提交后由订阅一次性更新。
@@ -951,14 +965,20 @@ function VisualMockDeviceLinkProvider({ children }: { children: ReactNode }) {
return <DeviceLinkContext.Provider value={value}>{children}</DeviceLinkContext.Provider>;
}
-function routeFrame(env: Envelope, handlers: {
+export function routeFrame(env: Envelope, handlers: {
onAccessRevoked?: (deviceId: string) => void;
+ onLinkClosed?: (deviceId: string) => void;
onProviderChanged?: (deviceId: string) => void;
} = {}): void {
+ const peerLinkClosed = handlePeerLinkCloseFrame(
+ env,
+ (deviceId) => handlers.onLinkClosed?.(deviceId),
+ );
if (applyAccessRevokedFrame(env)) {
if (env.src) handlers.onAccessRevoked?.(env.src);
return;
}
+ if (peerLinkClosed) return;
if (env.kind !== 'push' || !env.src) return;
const push = env.payload as PushPayload;
if (push.channel === 'maker:provider:changed') {
diff --git a/apps/mobile/src/device-link/linkClose.ts b/apps/mobile/src/device-link/linkClose.ts
new file mode 100644
index 0000000000..79bffe0c19
--- /dev/null
+++ b/apps/mobile/src/device-link/linkClose.ts
@@ -0,0 +1,25 @@
+import type { Envelope } from '@cindy/device-link';
+
+type DeviceScopedState = Pick<Map<string, unknown>, 'delete'>;
+type DeviceTopicAckState = Pick<Map<string, Set<string>>, 'delete' | 'get'>;
+
+export function invalidatePeerLinkState(
+ deviceId: string,
+ openLinks: DeviceScopedState,
+ remoteTopicAcks: DeviceTopicAckState,
+ onTopicsInterrupted: (topics: readonly string[]) => void,
+): void {
+ openLinks.delete(deviceId);
+ const topics = remoteTopicAcks.get(deviceId);
+ remoteTopicAcks.delete(deviceId);
+ if (topics && topics.size > 0) onTopicsInterrupted([...topics]);
+}
+
+export function handlePeerLinkCloseFrame(
+ env: Envelope,
+ onLinkClosed: (deviceId: string) => void,
+): boolean {
+ if (env.kind !== 'link-close' || !env.src) return false;
+ onLinkClosed(env.src);
+ return true;
+}
diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.ts
index 3d5830fc3e..5b746e6052 100644
--- a/apps/mobile/src/device-link/mobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts
@@ -151,6 +151,8 @@ export interface MessageListOptions {
limit?: number;
before?: string;
beforeTs?: number;
+ /** 只拉该 host 行之后的新消息;旧被控端会忽略未知可选字段并退化为最新页。 */
+ after?: string;
}
export interface MessageAroundOptions {
diff --git a/apps/mobile/src/device-link/presenceRecovery.ts b/apps/mobile/src/device-link/presenceRecovery.ts
index 92ec17b3cd..df21e2e4d6 100644
--- a/apps/mobile/src/device-link/presenceRecovery.ts
+++ b/apps/mobile/src/device-link/presenceRecovery.ts
@@ -50,6 +50,7 @@ export interface PresenceTrackedRequest<T> {
capturedPresenceEpoch: number;
capturedResponseEvidenceEpoch: number;
request: Promise<T>;
+ pending: boolean;
}
export function getOrCreatePresenceTrackedRequest<T>(
@@ -58,23 +59,38 @@ export function getOrCreatePresenceTrackedRequest<T>(
responseEvidenceEpochs: PresenceAvailabilityEpochs,
deviceId: string,
createRequest: () => Promise<T>,
+ options: {
+ /** 成功的 link 在当前 presence / 连接代保持可复用;失败仍立即清除。 */
+ retainSuccessful?: boolean;
+ } = {},
): PresenceTrackedRequest<T> {
const existing = inFlight.get(deviceId);
if (existing) return existing;
- const tracked = {
+ const tracked: PresenceTrackedRequest<T> = {
capturedPresenceEpoch: capturePresenceAvailabilityEpoch(epochs, deviceId),
capturedResponseEvidenceEpoch: capturePresenceAvailabilityEpoch(
responseEvidenceEpochs,
deviceId,
),
request: createRequest(),
+ pending: true,
};
inFlight.set(deviceId, tracked);
const cleanup = (): void => {
+ tracked.pending = false;
if (inFlight.get(deviceId) === tracked) inFlight.delete(deviceId);
};
- void tracked.request.then(cleanup, cleanup);
+ if (options.retainSuccessful) {
+ void tracked.request.then(
+ () => {
+ tracked.pending = false;
+ },
+ cleanup,
+ );
+ } else {
+ void tracked.request.then(cleanup, cleanup);
+ }
return tracked;
}
diff --git a/apps/mobile/src/session/messagePaging.ts b/apps/mobile/src/session/messagePaging.ts
index 1f7acae3d0..f118b56bbb 100644
--- a/apps/mobile/src/session/messagePaging.ts
+++ b/apps/mobile/src/session/messagePaging.ts
@@ -3,6 +3,15 @@ import type { RemoteMessage, RemoteSession } from '@/session/types';
export const MESSAGE_PAGE_SIZE = 80;
export const MESSAGE_PAGE_RETRY_LIMITS = [80, 40, 20, 10, 5, 1] as const;
+export function latestMessageCursor(messages: readonly RemoteMessage[]): string | null {
+ let latest: RemoteMessage | null = null;
+ for (const message of messages) {
+ if (!message.id || message.id.startsWith('mobile-system-')) continue;
+ if (!latest || compareMessageOrder(message, latest) > 0) latest = message;
+ }
+ return latest?.id ?? null;
+}
+
export function oldestMessageCursor(messages: readonly RemoteMessage[]): string | null {
let oldest: RemoteMessage | null = null;
for (const message of messages) {
@@ -125,8 +134,147 @@ export function isPayloadTooLargeError(error: unknown): boolean {
return code === 'PAYLOAD_TOO_LARGE' || message.includes('PAYLOAD_TOO_LARGE') || /frame exceeds \d+ bytes/i.test(message);
}
-function compareMessageOrder(a: RemoteMessage, b: RemoteMessage): number {
+export function incrementalMessagePageNeedsFallback(input: {
+ page: MessagePageRetryResult;
+ totalCount?: number;
+ previousTotalCount?: number;
+ afterMessage?: RemoteMessage | null;
+}): boolean {
+ const { page, totalCount, previousTotalCount, afterMessage } = input;
+ if (page.reducedByPayloadTooLarge) return true;
+ if (
+ afterMessage
+ && page.messages.some((message) => compareMessageOrder(message, afterMessage) <= 0)
+ ) {
+ // An old host may ignore `after` and return the latest page. A row at or before
+ // the client cursor proves this is not a contiguous incremental page.
+ return true;
+ }
+ if (page.messages.length >= page.limit) return true;
+ if (
+ typeof totalCount === 'number'
+ && Number.isFinite(totalCount)
+ && typeof previousTotalCount === 'number'
+ && Number.isFinite(previousTotalCount)
+ ) {
+ const expectedNewRows = totalCount - previousTotalCount;
+ return expectedNewRows < 0 || page.messages.length !== expectedNewRows;
+ }
+ return false;
+}
+
+export interface CompleteIncrementalMessageCollectionInput {
+ initialPage: MessagePageRetryResult;
+ afterMessage: RemoteMessage;
+ fetchAfter: (after: string) => Promise<MessagePageRetryResult>;
+ fetchLatest: () => Promise<MessagePageRetryResult>;
+ fetchBefore: (before: string) => Promise<MessagePageRetryResult>;
+ maxPages?: number;
+}
+
+/**
+ * Collect every row after a reopen cursor before marking the cached window synced.
+ * The first `after` page is intentionally capped, so a large offline delta needs
+ * cursor pagination; an old host that ignores `after` is handled by walking back
+ * from the latest window until the original cursor is reached.
+ */
+export async function collectCompleteIncrementalMessages(
+ input: CompleteIncrementalMessageCollectionInput,
+): Promise<RemoteMessage[] | null> {
+ const maxPages = input.maxPages ?? 256;
+ const anchor = input.afterMessage;
+ const collected = new Map<string, RemoteMessage>();
+ const addRowsAfterAnchor = (rows: readonly RemoteMessage[]): boolean => {
+ let valid = true;
+ for (const message of rows) {
+ if (compareMessageOrder(message, anchor) <= 0) {
+ valid = false;
+ continue;
+ }
+ const key = message.id || message.clientId;
+ if (key) collected.set(key, message);
+ }
+ return valid;
+ };
+ const anchorKey = anchor.id || anchor.clientId;
+ const containsAnchor = (rows: readonly RemoteMessage[]): boolean =>
+ Boolean(anchorKey) && rows.some((message) =>
+ (message.id || message.clientId) === anchorKey);
+ const ordered = (): RemoteMessage[] => [...collected.values()].sort(compareMessageOrder);
+ const hasTrimmedRows = (page: MessagePageRetryResult): boolean =>
+ page.messages.some((message) => message.agentMeta?.remoteRowsTrimmed === true);
+ // New hosts support cursor pagination. Every subsequent page must be strictly
+ // after the last cursor; otherwise the host is treated as legacy and we switch
+ // to the authoritative tail walk below.
+ let page = input.initialPage;
+ let forwardValid = addRowsAfterAnchor(page.messages);
+ let cursor = latestMessageCursor(page.messages);
+ let forwardComplete = false;
+ for (let pageIndex = 0; forwardValid && pageIndex < maxPages; pageIndex += 1) {
+ if (!cursor) break;
+ if (
+ page.messages.length < page.limit
+ && !page.reducedByPayloadTooLarge
+ && !hasTrimmedRows(page)
+ ) {
+ forwardComplete = true;
+ break;
+ }
+
+ const next = await input.fetchAfter(cursor);
+ if (next.messages.length === 0) {
+ // Empty continuation after more than one page proves a progressing forward
+ // walk reached the tail. After only the initial full/reduced page it can also
+ // mean the host ignored an unknown cursor and returned the latest window.
+ if (pageIndex > 0) forwardComplete = true;
+ else forwardValid = false;
+ break;
+ }
+ const nextCursor = latestMessageCursor(next.messages);
+ if (!nextCursor || nextCursor === cursor) {
+ forwardValid = false;
+ break;
+ }
+ forwardValid = addRowsAfterAnchor(next.messages);
+ page = next;
+ cursor = nextCursor;
+ }
+ if (forwardValid && forwardComplete) return ordered();
+ if (forwardValid) return null;
+
+ // A latest-window fallback must be paged backwards; using only its tail can
+ // silently omit the middle of a delta larger than the window size.
+ collected.clear();
+ page = await input.fetchLatest();
+ for (let pageIndex = 0; pageIndex < maxPages; pageIndex += 1) {
+ const reachedAnchor = containsAnchor(page.messages);
+ const crossedAnchor = !addRowsAfterAnchor(page.messages);
+ if (reachedAnchor) return ordered();
+ if (crossedAnchor) return null;
+ if (
+ page.messages.length < page.limit
+ && !page.reducedByPayloadTooLarge
+ && !hasTrimmedRows(page)
+ ) return null;
+ const before = oldestMessageCursor(page.messages);
+ if (!before) return null;
+ page = await input.fetchBefore(before);
+ if (page.messages.length === 0) return null;
+ }
+ return null;
+}
+
+export function compareMessageOrder(a: RemoteMessage, b: RemoteMessage): number {
const byTime = a.createdAt.localeCompare(b.createdAt);
if (byTime !== 0) return byTime;
- return (a.id || a.clientId).localeCompare(b.id || b.clientId);
+ if (
+ typeof a.rowid === 'number'
+ && Number.isFinite(a.rowid)
+ && typeof b.rowid === 'number'
+ && Number.isFinite(b.rowid)
+ && a.rowid !== b.rowid
+ ) return a.rowid - b.rowid;
+ // Older hosts and live push frames may not carry rowid. Their same-timestamp
+ // arrival order is meaningful; message ids are not insertion ordered.
+ return 0;
}
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index ee71c3143e..f6b7154400 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -22,6 +22,7 @@ import { cacheSessionMessages, getCachedSessionMessages } from '@/session/mobile
import { contentToPreview } from '@/utils/contentPreview';
import type { MobileSystemCardType } from '@/session/systemCard';
import type { InputProjection, PendingInteraction, RemoteMessage, RemoteSession } from '@/session/types';
+import { compareMessageOrder } from '@/session/messagePaging';
import { normalizeRemoteMoney } from '@/session/remoteMoney';
interface DeviceShard {
@@ -556,7 +557,7 @@ function preserveSessionRuntimeFields(fresh: RemoteSession, local: RemoteSession
}
function normalizeMessages(list: readonly RemoteMessage[]): RemoteMessage[] {
- return [...list].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
+ return [...list].sort(compareMessageOrder);
}
function messageKey(message: RemoteMessage): string {
@@ -1077,14 +1078,21 @@ function flushAndFinalizeRemoteStreamingMessages(
}
function hasLiveAssistantMessage(sessionId: string): boolean {
- const pendingLiveIds = pendingLiveAssistantClientIds.get(sessionId);
- if (!pendingLiveIds || pendingLiveIds.size === 0) return false;
return (messages.get(sessionId) ?? []).some((message) => (
- message.role === 'assistant'
- && (pendingLiveIds.has(message.clientId) || pendingLiveIds.has(message.id))
+ isPendingLiveAssistantMessage(sessionId, message)
));
}
+function isPendingLiveAssistantMessage(
+ sessionId: string,
+ message: RemoteMessage,
+): boolean {
+ const pendingLiveIds = pendingLiveAssistantClientIds.get(sessionId);
+ return message.role === 'assistant'
+ && pendingLiveIds !== undefined
+ && (pendingLiveIds.has(message.clientId) || pendingLiveIds.has(message.id));
+}
+
function flushPendingTextDeltas(): void {
let changed = false;
for (const sessionId of [...pendingTextDeltaBatches.keys()]) {
@@ -1466,7 +1474,13 @@ export const remoteSessionStore = {
// 本地系统卡(/learn、/context 等)没有服务端对应行:不管时序落在窗口哪里都
// 不会出现在 latestKeys 里,若不单独保留会被 window 刷新时静默丢弃。
const isLocalSystemCard = messageKey(item).startsWith('mobile-system-');
- if (isNewerThanLatestPage || isOlderLoadedPage || isLocalSystemCard) {
+ const isPendingLiveAssistant = isPendingLiveAssistantMessage(sessionId, item);
+ if (
+ isNewerThanLatestPage
+ || isOlderLoadedPage
+ || isLocalSystemCard
+ || isPendingLiveAssistant
+ ) {
byKey.set(messageKey(item), item);
}
}
diff --git a/apps/mobile/src/session/types.ts b/apps/mobile/src/session/types.ts
index fbc4011a1b..dc195c7ae7 100644
--- a/apps/mobile/src/session/types.ts
+++ b/apps/mobile/src/session/types.ts
@@ -87,6 +87,8 @@ export interface RemoteMessage {
id: string;
clientId: string;
sessionId: string;
+ /** SQLite insertion order from the host; absent on legacy/synthetic rows. */
+ rowid?: number;
role: RemoteMessageRole;
content: unknown;
toolUseId: string | null;