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): 缩短拥堵后的流式文字恢复等待

Dash3886da833248
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts
index 84b7fb6a93..db8e0d6035 100644
--- a/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts
@@ -704,6 +704,85 @@ describe('running session recovery on slow links', () => {
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('replays only the requested current block after old deltas and before new deltas', () => {
const h = mkClient();
__testing.setActiveClient(h.client as never);
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 79df5ed396..42ec599a1a 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -931,6 +931,13 @@ const makerEventBatchStages = new Map<string, MakerEventBatchStage>();
// Bound live traffic before it enters the shared socket FIFO. Only opt-in
// controllers can repair skipped deltas from the authoritative in-flight block.
const MAKER_EVENT_WINDOW_SOFT_CAP = 16;
+// Recheck the existing repair stage promptly after the window drains. Waiting
+// two seconds here also suppresses healthy later deltas for those two seconds.
+// The peer/window gates still run before reading or sending any snapshot.
+const SESSION_SYNC_RETRY_MS = 250;
+// Keep the original pacing when reading/admitting a snapshot actually fails:
+// socket bytes or the authorization queue can be full even below the soft cap.
+const SESSION_SYNC_FAILURE_RETRY_MS = 2_000;
function isNonFinalTextPush(payload: unknown): boolean {
const event = (payload as { event?: { type?: unknown; data?: { isFinal?: unknown } } } | null)?.event;
return event?.type === 'text' && event.data?.isFinal === false;
@@ -940,6 +947,7 @@ const sessionSyncStages = new Map<string, {
sessions: Map<string, boolean>;
timer: ReturnType<typeof setTimeout> | null;
ownerStamp?: PushOwnerStamp;
+ startedAt: number;
}>();
function clearSessionSyncStage(dst: string): void {
@@ -948,18 +956,26 @@ function clearSessionSyncStage(dst: string): void {
sessionSyncStages.delete(dst);
}
-function stageSessionSync(dst: string, sessionId: string, historyRequired = true): void {
+function stageSessionSync(dst: string, sessionId: string, historyRequired = true, retryDelayMs = SESSION_SYNC_RETRY_MS): void {
if (!subscriptions.controllerSupports(dst, CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1)) return;
let stage = sessionSyncStages.get(dst);
if (!stage) {
- stage = { sessions: new Map(), timer: null, ownerStamp: broadcastTap.getSafeDataOwnerPushStamp?.() };
+ stage = { sessions: new Map(), timer: null, ownerStamp: broadcastTap.getSafeDataOwnerPushStamp?.(), startedAt: Date.now() };
sessionSyncStages.set(dst, stage);
+ log.debug(`session sync repair queued to=${shortId(dst)}`
+ + ` queueDepth=${activeClient?.getReliableSendQueueDepth?.(dst) ?? 0}`
+ + ` writable=${activeClient?.canSendPush?.(dst) !== false}`);
}
stage.sessions.set(sessionId, historyRequired || stage.sessions.get(sessionId) === true);
if (stage.sessions.size > SESSION_ACTIVITY_STAGE_MAX_KEYS) {
stage.sessions.delete(stage.sessions.keys().next().value!);
}
- if (stage.timer) return;
+ if (stage.timer) {
+ if (retryDelayMs !== SESSION_SYNC_FAILURE_RETRY_MS) return;
+ // Flushing an older batch may have re-armed the fast check. A subsequent
+ // admission failure must retain the original, slower retry interval.
+ clearTimeout(stage.timer);
+ }
stage.timer = setTimeout(() => {
stage.timer = null;
if (!activeClient || activeClient.getStatus() !== 'online'
@@ -991,24 +1007,30 @@ function stageSessionSync(dst: string, sessionId: string, historyRequired = true
let admissionFailed = false;
sendBotCheckedPush(dst, SESSION_SYNC_CHANNEL, payload,
(projected) => {
- if (subscriptions.controllerHasTopic(dst, `session:${sid}`)) {
- activeClient?.sendPush(dst, SESSION_SYNC_CHANNEL, projected, ownerStamp);
+ if (activeClient && subscriptions.controllerHasTopic(dst, `session:${sid}`)) {
+ activeClient.sendPush(dst, SESSION_SYNC_CHANNEL, projected, ownerStamp);
+ // Admission is not delivery/ACK. Log once per admitted repair,
+ // never per retry or token, and never include the snapshot body.
+ log.debug(`session sync repair admitted to=${shortId(dst)}`
+ + ` session=${shortId(sid)} stageAgeMs=${Date.now() - stage.startedAt}`
+ + ` resyncRequired=${payload.resyncRequired}`);
}
},
() => {
admissionFailed = true;
- stageSessionSync(dst, sid, payload.resyncRequired);
+ stageSessionSync(dst, sid, payload.resyncRequired, SESSION_SYNC_FAILURE_RETRY_MS);
});
if (admissionFailed) break;
stage.sessions.delete(sid);
} catch {
+ stageSessionSync(dst, sid, stage.sessions.get(sid), SESSION_SYNC_FAILURE_RETRY_MS);
break;
}
}
const next = stage.sessions.entries().next().value;
if (next) stageSessionSync(dst, next[0], next[1]);
else clearSessionSyncStage(dst);
- }, 2_000);
+ }, retryDelayMs);
(stage.timer as unknown as { unref?: () => void }).unref?.();
}