Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(device-link): 修复后台重试与迟到补流回调并同步主干

Dash7592a1599ff7
diff --cc apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts
index db8e0d6035,84b7fb6a93..c204563154
--- a/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts
@@@ -704,85 -704,6 +704,112 @@@ describe('running session recovery on s
type: 'text', data: { text: 'whole prefix', isFinal: false, isFullText: true },
} };
+ it.each([
+ ['batch', 'queue'], ['batch', 'peer'], ['legacy', 'queue'], ['legacy', 'peer'],
+ ] as const)('restores %s streaming within 250ms after %s recovery without polling the snapshot while blocked', (mode, blocker) => {
+ const h = mkClient();
+ let blocked = true;
+ const canSendPush = vi.fn(() => blocker !== 'peer' || !blocked);
+ h.client.getReliableSendQueueDepth.mockImplementation(() => blocker === 'queue' && blocked ? 16 : 0);
+ __testing.setActiveClient({ ...h.client, canSendPush } as never);
+ subscriptions.subscribe('phone', ['session:s1'], 'phone', mode === 'batch'
+ ? capabilities : [CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1]);
+ let currentText = 'missing prefix';
+ const readSnapshot = vi.fn(() => ({ ...snapshot, event: {
+ ...snapshot.event, data: { ...snapshot.event.data, text: currentText },
+ } }));
+ setSessionTextSnapshotReader(readSnapshot);
+ __testing.forwardPush('maker:event', delta(currentText));
+ vi.advanceTimersByTime(WINDOW_MS);
+ currentText += ' plus latest text';
+ __testing.forwardPush('maker:event', delta(' plus latest text'));
+ vi.advanceTimersByTime(4_000);
+ expect(h.sent).toHaveLength(0);
+ expect(readSnapshot).not.toHaveBeenCalled();
+ expect(logSpy.debug.mock.calls.filter(([line]) => line.startsWith('session sync repair queued'))).toHaveLength(1);
+ expect(logSpy.debug.mock.calls.some(([line]) => line.startsWith('session sync repair admitted'))).toBe(false);
+
+ blocked = false;
+ // Recovery must not depend on another token arriving: a thinking/tool gap
+ // after the last delta must still reveal the latest accumulated text.
+ vi.advanceTimersByTime(250);
+ expect(h.sent.map(p => p.channel)).toEqual([SESSION_SYNC_CHANNEL]);
+ expect(h.sent[0].payload).toMatchObject({
+ resyncRequired: false, event: { data: { text: currentText, isFullText: true } },
+ });
+ expect(readSnapshot).toHaveBeenCalledTimes(1);
+ __testing.forwardPush('maker:event', delta(' live again'));
+ vi.advanceTimersByTime(WINDOW_MS);
+ expect(h.sent.map(p => p.channel)).toEqual([
+ SESSION_SYNC_CHANNEL, mode === 'batch' ? MAKER_EVENT_BATCH_CHANNEL : 'maker:event',
+ ]);
+ vi.advanceTimersByTime(2_000);
+ expect(readSnapshot).toHaveBeenCalledTimes(1);
+ const repairLogs = logSpy.debug.mock.calls.map(([line]) => line).filter(line => line.startsWith('session sync repair'));
+ expect(repairLogs).toHaveLength(2);
+ expect(repairLogs[1]).toContain('resyncRequired=false');
+ expect(repairLogs.join('\n')).not.toContain(currentText);
+ });
+
+ it.each(['sync', 'async'] as const)('keeps failed snapshot admission paced at two seconds through the %s authorization path', async (authorization) => {
+ const h = mkClient();
+ __testing.setActiveClient(h.client as never);
+ if (authorization === 'async') setRemoteBotSessionLookup(async () => 'visible');
+ subscriptions.subscribe('phone', ['session:s1'], 'phone', capabilities);
+ const readSnapshot = vi.fn(() => snapshot);
+ setSessionTextSnapshotReader(readSnapshot);
+ h.client.getReliableSendQueueDepth.mockReturnValue(16);
+ __testing.forwardPush('maker:event', delta('missed'));
+ await vi.advanceTimersByTimeAsync(WINDOW_MS);
+ h.client.getReliableSendQueueDepth.mockReturnValue(0);
+ h.sendPush.mockImplementationOnce(() => { throw new DeviceLinkError('BACKPRESSURE', 'socket bytes full'); });
+ h.sendPush.mockImplementationOnce(() => { throw new DeviceLinkError('BACKPRESSURE', 'socket bytes full'); });
+ await vi.advanceTimersByTimeAsync(200);
+ // The repair flushes this later batch, which can re-arm the same timer.
+ // A failed admission must still keep the slower pacing in that case.
+ __testing.forwardPush('maker:event', delta('later suffix'));
+ await vi.advanceTimersByTimeAsync(50);
+ expect(readSnapshot).toHaveBeenCalledTimes(1);
+ expect(h.sent).toHaveLength(0);
+ await vi.advanceTimersByTimeAsync(1_999);
+ expect(readSnapshot).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(readSnapshot).toHaveBeenCalledTimes(2);
+ expect(h.sent).toHaveLength(0);
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(readSnapshot).toHaveBeenCalledTimes(3);
+ expect(h.sent.map(p => p.channel)).toEqual([SESSION_SYNC_CHANNEL]);
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(readSnapshot).toHaveBeenCalledTimes(3);
+ });
+
++ it('does not let a late failed admission delay a newer repair stage', async () => {
++ const h = mkClient();
++ __testing.setActiveClient(h.client as never);
++ subscriptions.subscribe('phone', ['session:s1'], 'phone', capabilities);
++ let release!: () => void;
++ const pending = new Promise<void>((resolve) => { release = resolve; });
++ setRemoteBotSessionLookup(async () => { await pending; return 'visible'; });
++ const readSnapshot = vi.fn(() => snapshot);
++ setSessionTextSnapshotReader(readSnapshot);
++ h.client.getReliableSendQueueDepth.mockReturnValue(16);
++ __testing.forwardPush('maker:event', delta('first'));
++ await vi.advanceTimersByTimeAsync(WINDOW_MS);
++ h.client.getReliableSendQueueDepth.mockReturnValue(0);
++ await vi.advanceTimersByTimeAsync(250);
++ expect(readSnapshot).toHaveBeenCalledTimes(1);
++ h.client.getReliableSendQueueDepth.mockReturnValue(16);
++ __testing.forwardPush('maker:event', delta('new stage'));
++ await vi.advanceTimersByTimeAsync(WINDOW_MS);
++ h.client.getReliableSendQueueDepth.mockReturnValue(0);
++ h.sendPush.mockImplementationOnce(() => { throw new DeviceLinkError('BACKPRESSURE', 'full'); });
++ release();
++ await vi.advanceTimersByTimeAsync(0);
++ await vi.advanceTimersByTimeAsync(250);
++ expect(readSnapshot).toHaveBeenCalledTimes(2);
++ expect(h.sent.map(p => p.channel)).toEqual([SESSION_SYNC_CHANNEL]);
++ });
++
it('replays only the requested current block after old deltas and before new deltas', () => {
const h = mkClient();
__testing.setActiveClient(h.client as never);
diff --cc apps/desktop/src/main/device-link/dispatch.ts
index 42ec599a1a,c35f926aac..ffb6cbcc0c
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@@ -1018,7 -1011,7 +1032,11 @@@ function stageSessionSync(dst: string,
},
() => {
admissionFailed = true;
- stageSessionSync(dst, sid, payload.resyncRequired, SESSION_SYNC_FAILURE_RETRY_MS);
- stageSessionSync(dst, sid, payload.resyncRequired);
++ // A late authorization failure may belong to an already drained
++ // stage. Preserve a newer stage's fast timer while merging the work.
++ const currentStage = sessionSyncStages.get(dst);
++ stageSessionSync(dst, sid, payload.resyncRequired,
++ currentStage && currentStage !== stage ? SESSION_SYNC_RETRY_MS : SESSION_SYNC_FAILURE_RETRY_MS);
});
if (admissionFailed) break;
stage.sessions.delete(sid);
diff --cc apps/desktop/src/renderer/lib/makerChatStore.ts
index 9b8475959d,659a22d89e..89dca1667b
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@@ -22,8 -22,7 +22,9 @@@
*/
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 { parseMessageToolUse } from '@cindy/maker-shared/message-normalize';
import {
getDataOwnerGeneration,
isDataOwnerGenerationCurrent,
@@@ -212,12 -215,14 +217,15 @@@ const DEVICE_LINK_CHAT_ERROR_CODES: Rea
* 未登记的 code 仍然回退到英文兜底文案(绝不把 `[CODE]` 裸露给用户)。
*/
const AGENT_RUNTIME_CHAT_ERROR_CODES: ReadonlySet<string> = new Set([
- // Auto 档下审阅器没跑起来(与「模型判定动作危险」不同,后者刻意保持静默)。
+ // Distinguish review availability, blocked calls, and missing confirmations.
'AUTO_REVIEW_UNAVAILABLE',
'AUTO_REVIEW_CONFIRM_UNDELIVERED',
+ 'MCP_APPROVAL_AUTO_BLOCKED',
+ 'MCP_APPROVAL_CONFIRMATION_TIMEOUT',
+ 'MCP_APPROVAL_CONFIRMATION_UNAVAILABLE',
] as const);
const REMOTE_HEAVY_INBOUND_CHANNELS: ReadonlySet<string> = new Set([
+ SESSION_SYNC_CHANNEL,
'maker:event',
'maker:status-changed',
'maker:input:projection',
diff --cc apps/mobile/src/__tests__/scheduleIndex.test.ts
index df52dcf37d,0894467bbf..fca3d91307
--- a/apps/mobile/src/__tests__/scheduleIndex.test.ts
+++ b/apps/mobile/src/__tests__/scheduleIndex.test.ts
@@@ -7,8 -7,8 +7,9 @@@ import
invalidateRunningSessionScheduleEntries,
invalidateScheduleIndexForDevice,
invalidateTransientScheduleIndexFailureFor,
- invalidateTransientScheduleIndexFailures,
+ invalidateScheduleIndexesAfterLinkRecovery,
loadSessionScheduleIndex,
++ loadSharedSessionScheduleIndex,
loadSessionScheduleIndexThrottled,
replaceSessionScheduleIndexEntries,
resetScheduleIndexThrottleForTesting,
@@@ -32,6 -32,6 +33,29 @@@ function makerWithSchedules
}
describe('scheduleIndex', () => {
++ it('stops retries after blur without negative-caching cancellation for the next screen', async () => {
++ vi.useFakeTimers();
++ resetScheduleIndexThrottleForTesting();
++ try {
++ let active = true;
++ const list = vi.fn().mockRejectedValueOnce(new Error('[NOT_CONNECTED] offline')).mockResolvedValue([]);
++ const maker = { schedule: { list, listRuns: vi.fn() } } as unknown as Pick<MobileMakerTransport, 'schedule'>;
++ const first = loadSharedSessionScheduleIndex('blur-device', maker, () => active);
++ const rejected = expect(first).rejects.toThrow('consumer inactive');
++ await vi.advanceTimersByTimeAsync(0);
++ expect(list).toHaveBeenCalledTimes(1);
++ active = false;
++ await vi.runAllTimersAsync();
++ await rejected;
++ expect(list).toHaveBeenCalledTimes(1);
++ await expect(loadSharedSessionScheduleIndex('blur-device', maker)).resolves.toEqual(new Map());
++ expect(list).toHaveBeenCalledTimes(2);
++ } finally {
++ resetScheduleIndexThrottleForTesting();
++ vi.useRealTimers();
++ }
++ });
++
it('loads schedule unread and running metadata without failing the whole index on one bad schedule', async () => {
const listRuns = vi.fn(async (scheduleId: string) => {
if (scheduleId === 'broken') throw new Error('remote schedule runs unavailable');
diff --cc apps/mobile/src/session/scheduleIndex.ts
index 4891a5a2e7,11593280e5..e796c5e67a
--- a/apps/mobile/src/session/scheduleIndex.ts
+++ b/apps/mobile/src/session/scheduleIndex.ts
@@@ -264,25 -243,9 +264,33 @@@ export function resetScheduleIndexThrot
export function loadDeviceSessionScheduleIndex(
deviceId: string,
invoke: RemoteInvoke,
+ canStart?: () => boolean,
+): Promise<Map<string, RemoteSessionScheduleInfo>> {
+ return loadSharedSessionScheduleIndex(deviceId, createMobileMakerTransport({ deviceId, invoke }), canStart);
+}
+
+/** Every screen shares the strict load and its bounded retry, before negative caching. */
+export async function loadSharedSessionScheduleIndex(
+ deviceId: string,
+ maker: Pick<MobileMakerTransport, 'schedule'>,
+ canStart: () => boolean = () => true,
): Promise<Map<string, RemoteSessionScheduleInfo>> {
- return loadSessionScheduleIndex(createMobileMakerTransport({ deviceId, invoke }), {
- isDeviceUnresponsive: () => unresponsiveDevicesStore.has(deviceId),
+ return loadSessionScheduleIndexThrottled(deviceId, () => {
+ // Check again when an invalidated in-flight scan finishes. Throw before
+ // creating an entry so an abandoned waiter cannot poison active consumers.
+ if (!canStart()) throw new Error('Schedule index consumer inactive');
- return withTransientRemoteRetry(() => loadSessionScheduleIndex(maker, {
- throwOnTransientRunListError: true,
- isDeviceUnresponsive: () => unresponsiveDevicesStore.has(deviceId),
- }));
++ return withTransientRemoteRetry(() => {
++ if (!canStart()) {
++ // Cancellation is not a device failure: discard this pending entry on
++ // settle so the next visible consumer can start immediately.
++ invalidateScheduleIndexForDevice(deviceId);
++ throw new Error('Schedule index consumer inactive');
++ }
++ return loadSessionScheduleIndex(maker, {
++ throwOnTransientRunListError: true,
++ isDeviceUnresponsive: () => unresponsiveDevicesStore.has(deviceId),
++ });
++ });
});
}
diff --cc packages/device-link/src/__tests__/client.test.ts
index e7684fa798,3f38a39988..772a97b899
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@@ -1297,51 -1204,53 +1301,53 @@@ describe('DeviceLinkClient', () =>
&& env.dst === 'dev-b'
&& (env.payload as { reason?: string } | undefined)?.reason === 'transport-timeout'
))).toBe(true);
- });
- // relay 连接毫发无损:既没 terminate,也没新建 socket(其它 peer 零感知)
- expect(firstSocket.terminated).toBe(false);
- expect(firstSocket.closed).toBeNull();
- expect(h.sockets).toHaveLength(1);
- expect(warn).toHaveBeenCalledWith(expect.stringMatching(
- /ACK timeout; resetting peer link .*dst=dev-b seq=1 kind=push request=\S+ attempts=2 sent=true ageMs=\d+ pending=2\/\d+ ack=0 next=3 send=ready receive=true stream=.{8} remoteStream=inbound-/,
- ));
+ // relay 连接毫发无损:既没 terminate,也没新建 socket(其它 peer 零感知)
+ expect(firstSocket.terminated).toBe(false);
+ expect(firstSocket.closed).toBeNull();
+ expect(h.sockets).toHaveLength(1);
+ expect(warn).toHaveBeenCalledWith(expect.stringMatching(
- /ACK timeout; resetting peer link .*dst=dev-b seq=1 kind=push attempts=2 sent=true ageMs=\d+ pending=2\/\d+ ack=0 next=3 send=ready receive=true stream=.{8} remoteStream=inbound-/,
++ /ACK timeout; resetting peer link .*dst=dev-b seq=1 kind=push request=\S+ attempts=2 sent=true ageMs=\d+ pending=2\/\d+ ack=0 next=3 send=ready receive=true stream=.{8} remoteStream=inbound-/,
+ ));
- // 对端重开链路 → 陈旧 push 前缀被清扫,live invoke-result 按原 seq 重放
- const sentBefore = firstSocket.sent.length;
- await establishInboundReliableLink(h, 'inbound-timeout-stream');
- // 模拟真实接收端:重放帧已写入 socket FIFO 后立即回 ACK(见 client.ts
- // sendTransportAck 的交付即确认语义)。不 ACK 的话,重放后 retryTimer
- // 会在 Windows 低精度计时器(≈12ms>配置 5ms)下把同一帧再发一遍,慢 CI
- // runner 上断言窗口跨过该周期时会把「重试重发」误判成「重放两次」。
- const justReplayed = firstSocket.sent.slice(sentBefore).filter((env) => (
- env.kind === 'invoke-result' && parseTransportPayload(env.payload)
- ));
- if (justReplayed.length > 0) {
- const meta = parseTransportPayload(justReplayed[0].payload)!.meta;
- h.current().push({
- v: PROTOCOL_VERSION,
- kind: 'push',
- src: 'dev-b',
- payload: {
- channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,
- payload: { streamId: meta.streamId, ackSeq: meta.seq },
- },
+ // 对端重开链路 → 陈旧 push 前缀被清扫,live invoke-result 按原 seq 重放
+ const sentBefore = firstSocket.sent.length;
+ const reopened = establishInboundReliableLink(h, 'inbound-timeout-stream');
+ await vi.advanceTimersByTimeAsync(0);
+ await reopened;
+ // 受控时钟保持在重开时刻:真实计时器可能在 tick 等待期间已跨过 5ms
+ // 重试窗口,此时再 ACK 也来不及阻止第二帧。确认重放后再 ACK,不放宽数量断言。
+ const justReplayed = firstSocket.sent.slice(sentBefore).filter((env) => (
+ env.kind === 'invoke-result' && parseTransportPayload(env.payload)
+ ));
+ if (justReplayed.length > 0) {
+ const meta = parseTransportPayload(justReplayed[0].payload)!.meta;
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'push',
+ src: 'dev-b',
+ payload: {
+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,
+ payload: { streamId: meta.streamId, ackSeq: meta.seq },
+ },
+ });
+ }
+ const replayed = firstSocket.sent.slice(sentBefore);
+ const replays = replayed.filter((env) => (
+ env.kind === 'invoke-result' && parseTransportPayload(env.payload)
+ ));
+ expect(replays).toHaveLength(1);
+ expect(parseTransportPayload(replays[0].payload)?.meta).toMatchObject({
+ streamId: firstMeta.streamId,
+ seq: firstMeta.seq,
});
+ expect(replayed.filter((env) => (
+ env.kind === 'push'
+ && parseTransportPayload(env.payload)
+ ))).toHaveLength(0);
+ } finally {
+ h.client.stop();
+ vi.useRealTimers();
}
- const replayed = firstSocket.sent.slice(sentBefore);
- const replays = replayed.filter((env) => (
- env.kind === 'invoke-result' && parseTransportPayload(env.payload)
- ));
- expect(replays).toHaveLength(1);
- expect(parseTransportPayload(replays[0].payload)?.meta).toMatchObject({
- streamId: firstMeta.streamId,
- seq: firstMeta.seq,
- });
- expect(replayed.filter((env) => (
- env.kind === 'push'
- && parseTransportPayload(env.payload)
- ))).toHaveLength(0);
- h.client.stop();
});
it('互控:出站 link-accept 不覆盖入站标记,重试耗尽仍走 peer 级重置不拆共享 relay', async () => {