From c56605ca48a8e85b27e69363eec98173757cdf17 Mon Sep 17 00:00:00 2001 From: chenkai2 Date: Wed, 14 Oct 2026 20:53:52 +0800 Subject: [PATCH] =?UTF-8?q?fix(sidebar):=20agent-opens=20=E6=8E=A8?= =?UTF-8?q?=E9=80=81=E9=80=9A=E9=81=93=E5=8A=A0=E5=BF=83=E8=B7=B3=E5=B9=B6?= =?UTF-8?q?=E5=9C=A8=E6=96=AD=E7=BA=BF=E5=90=8E=E6=8C=81=E7=BB=AD=E9=87=8D?= =?UTF-8?q?=E8=BF=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 心跳:socket onopen 后每 20s 发送 {"kind":"ping"},避免空闲连接被 LB 空闲/发送超时(ALB 默认 60s、上限 300s)切断;服务端 attachAgentOpen 未注册 message 监听,该帧会被安全忽略。 - 重连:删除 FAILURE_LIMIT=3 的永久停止分支;连接成功 OPEN 并保持 ≥2s、或收到任意一帧即结束失败序列;重试改为有上限的指数退避(2s→4s→8s…max 30s),永不永久放弃。公式与既有 src/client/use-sidechat-push.ts(1s→15s)一致。 Fixes #953 Fixes #836 --- src/client/sidebar/use-host-feeds.ts | 70 +++++++-- tests/agent-opens-reconnect.spec.tsx | 205 +++++++++++++++++++++++++++ 2 files changed, 261 insertions(+), 14 deletions(-) create mode 100644 tests/agent-opens-reconnect.spec.tsx diff --git a/src/client/sidebar/use-host-feeds.ts b/src/client/sidebar/use-host-feeds.ts index 88ec0fef..517e22ee 100644 --- a/src/client/sidebar/use-host-feeds.ts +++ b/src/client/sidebar/use-host-feeds.ts @@ -16,9 +16,24 @@ import { clientJobs, useJobsSnapshot } from '../jobs-client.ts' import { mountedSessionId } from '../native/surface.ts' import { t } from '../locales.ts' -/** How many consecutive reconnect failures stop the agent-opens push loop - * (the loop restarts on session switch). */ -const FAILURE_LIMIT = 3 +/** + * Application-level heartbeat interval (ms) for the agent-opens socket. The + * browser WebSocket API cannot emit protocol-level pings and an idle socket + * carries no bytes at all, so a load balancer's idle/send timeout closes it + * (ALB: 60 s by default, 300 s ceiling). A data frame well below those + * thresholds keeps the connection alive; the host registers no `message` + * listener, so an unknown frame is ignored. + */ +const HEARTBEAT_INTERVAL_MS = 20_000 + +/** Heartbeat payload: `kind` is not file/folder/url, so the host ignores it. */ +const HEARTBEAT_FRAME = '{"kind":"ping"}' + +/** First reconnect delay (ms); doubles per consecutive failure. */ +const RECONNECT_BASE_MS = 2_000 + +/** Ceiling for the exponential reconnect backoff (ms). */ +const RECONNECT_MAX_MS = 30_000 /** * Subagent auto-open debounce (ms). The host delivers a new child's origin @@ -145,11 +160,15 @@ export function useHostFeeds(feeds: { * The host pushes one JSON request per open; the sidebar routes it to the * matching built-in tab: a file opens in the editor (per-path dedupe), a * folder opens a file window whose tree is rooted at the folder - * (`meta.dir`), and a URL opens in DSH's own browser tab type. A disconnected socket - * retries with a short backoff (mirror of the agent-terminals loop): the - * host queue keeps undelivered requests and replays them on the first - * attach, so a refresh or a session switch lands the opens the model - * queued while no view was connected. + * (`meta.dir`), and a URL opens in DSH's own browser tab type. The effect + * owns the connection for as long as the session is shown: an application + * heartbeat keeps an idle socket alive past a load balancer's idle/send + * timeout, and a dropped socket reconnects forever with a bounded + * exponential backoff. A connection that stays up (or delivers a frame) ends + * the consecutive-failure series, so unrelated drops never accumulate into a + * permanent stop. The host queue keeps undelivered requests and replays them + * on the first attach, so a refresh or a session switch lands the opens the + * model queued while no view was connected. * While the side-card setting is off, pushes are ignored as a defensive * gate — the host already unregisters the tool and drains the queue. */ @@ -157,14 +176,31 @@ export function useHostFeeds(feeds: { if (sessionId === undefined) return let socket: WebSocket | null = null let retry: number | undefined + let heartbeat: number | undefined + let openedAt: number | undefined let closed = false let failures = 0 + const stopHeartbeat = (): void => { + window.clearInterval(heartbeat) + heartbeat = undefined + } const connect = (): void => { if (closed) return const url = hostWebSocketUrl('sidebar/ws/agent-opens') url.search = new URLSearchParams({ sessionId }).toString() socket = new WebSocket(url.toString()) + socket.onopen = () => { + openedAt = Date.now() + stopHeartbeat() + heartbeat = window.setInterval(() => { + if (socket?.readyState === WebSocket.OPEN) socket.send(HEARTBEAT_FRAME) + }, HEARTBEAT_INTERVAL_MS) + } socket.onmessage = (event) => { + // A frame from the host proves the socket is live, so it ends the + // consecutive-failure series even if the socket drops right after. + failures = 0 + openedAt = undefined if (typeof event.data !== 'string') return try { const request = JSON.parse(event.data) as { kind?: unknown; target?: unknown; title?: unknown } @@ -200,18 +236,24 @@ export function useHostFeeds(feeds: { } socket.onclose = () => { if (closed) return - failures += 1 - if (failures >= FAILURE_LIMIT) { - console.error('[dsh-better-sidebar] agent-opens connection failed; stopping reconnect loop', sessionId) - return - } - retry = window.setTimeout(connect, 2000) + stopHeartbeat() + // A socket that stayed up past the base delay was a real connection: + // its drop restarts the series at the base delay instead of inheriting + // earlier failures, which is what accumulated into a permanent stop. + const stable = openedAt !== undefined && Date.now() - openedAt >= RECONNECT_BASE_MS + openedAt = undefined + failures = stable ? 1 : failures + 1 + // Never permanently stop: a bounded exponential backoff keeps retrying + // through a long outage instead of requiring a page reload. + const delay = Math.min(RECONNECT_BASE_MS * 2 ** (failures - 1), RECONNECT_MAX_MS) + retry = window.setTimeout(connect, delay) } socket.onerror = () => { socket?.close() } } connect() return () => { closed = true + stopHeartbeat() window.clearTimeout(retry) socket?.close() } diff --git a/tests/agent-opens-reconnect.spec.tsx b/tests/agent-opens-reconnect.spec.tsx new file mode 100644 index 00000000..e3d03c76 --- /dev/null +++ b/tests/agent-opens-reconnect.spec.tsx @@ -0,0 +1,205 @@ +/** + * The agent-opens push socket's LIVENESS contract (fixes #836 and the missing + * heartbeat). + * + * The socket is the only delivery path for `sidebar_open`; a socket that is + * never kept alive, or a reconnect loop that stops for good, silently drops + * the feature until the page is reloaded. Three behaviours are pinned: + * + * - HEARTBEAT: an idle socket still sends a small frame every + * HEARTBEAT_INTERVAL_MS, so a load balancer's idle/send timeout (60 s by + * default) never sees the connection idle. Nothing is sent before OPEN. + * - NO PERMANENT STOP: a connection that opened (or delivered a frame) ends + * the consecutive-failure series, so three scattered drops in a session no + * longer accumulate into the old `stopping reconnect loop` stop (#836). + * - BACKOFF: attempts that never reach OPEN double their delay (2 s → 4 s → + * 8 s … capped at RECONNECT_MAX_MS) and never stop retrying. + */ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createElement } from 'react' +import type { Context, SidebarSessionList } from '../src/context-types.ts' +import type { SidebarStore } from '../src/client/state.ts' +import { useHostFeeds } from '../src/client/sidebar/use-host-feeds.ts' +import { renderRoot, setupReactAct } from './test-utils.ts' + +setupReactAct() + +/** One controllable stand-in for the browser WebSocket. */ +class FakeSocket { + static readonly CONNECTING = 0 + static readonly OPEN = 1 + static readonly CLOSING = 2 + static readonly CLOSED = 3 + static instances: FakeSocket[] = [] + + readonly url: string + readonly sent: string[] = [] + readyState = FakeSocket.CONNECTING + onopen: ((event: Event) => void) | null = null + onmessage: ((event: MessageEvent) => void) | null = null + onclose: ((event: CloseEvent) => void) | null = null + onerror: ((event: Event) => void) | null = null + + constructor(url: string | URL) { + this.url = String(url) + FakeSocket.instances.push(this) + } + + send(data: string): void { + this.sent.push(data) + } + + close(): void { + if (this.readyState === FakeSocket.CLOSED) return + this.readyState = FakeSocket.CLOSED + this.onclose?.({} as CloseEvent) + } + + /** Drive the socket to OPEN (the host accepted the upgrade). */ + open(): void { + this.readyState = FakeSocket.OPEN + this.onopen?.({} as Event) + } + + /** Deliver one frame, then leave the socket open. */ + receive(data: string): void { + this.onmessage?.({ data } as MessageEvent) + } + + /** Drop the socket without a clean client-side close. */ + drop(): void { + this.readyState = FakeSocket.CLOSED + this.onclose?.({} as CloseEvent) + } +} + +/** The only hook input the agent-opens effect reads. */ +function mountFeeds(sessionId = 'session-1'): ReturnType { + const ctx = { get: () => undefined } as unknown as Context + const store = { + getPrefs: () => ({ agentOpenTools: true }), + markUnread: () => {}, + } as unknown as SidebarStore + const sessionList: SidebarSessionList = { byId: {} } + function Probe(): null { + useHostFeeds({ ctx, store, sessionList, sessionId }) + return null + } + return renderRoot(createElement(Probe)) +} + +/** The socket created by the attempt at `index`. */ +function socketAt(index: number): FakeSocket { + const socket = FakeSocket.instances[index] + if (socket === undefined) throw new Error(`no socket at index ${index}`) + return socket +} + +beforeEach(() => { + vi.useFakeTimers() + FakeSocket.instances = [] + vi.stubGlobal('WebSocket', FakeSocket) +}) + +afterEach(() => { + vi.unstubAllGlobals() + vi.useRealTimers() + vi.restoreAllMocks() +}) + +describe('agent-opens push socket', () => { + it('connects to the session-scoped endpoint', () => { + const mounted = mountFeeds() + expect(FakeSocket.instances).toHaveLength(1) + expect(socketAt(0).url).toContain('/sidebar/ws/agent-opens') + expect(socketAt(0).url).toContain('sessionId=session-1') + mounted.unmount() + }) + + it('sends a heartbeat every interval once open, and nothing before', () => { + const mounted = mountFeeds() + const socket = socketAt(0) + + vi.advanceTimersByTime(60_000) + expect(socket.sent).toEqual([]) + + socket.open() + vi.advanceTimersByTime(19_999) + expect(socket.sent).toEqual([]) + vi.advanceTimersByTime(1) + expect(socket.sent).toEqual(['{"kind":"ping"}']) + vi.advanceTimersByTime(20_000) + expect(socket.sent).toHaveLength(2) + + // Cleanup stops the heartbeat with the effect. + mounted.unmount() + vi.advanceTimersByTime(60_000) + expect(socket.sent).toHaveLength(2) + }) + + it('never stops reconnecting after repeated successful connections (#836)', () => { + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const mounted = mountFeeds() + + // Three connections that each OPEN, deliver a frame and then drop — the + // failure series must restart every time instead of accumulating into a stop. + for (let round = 0; round < 3; round++) { + const socket = socketAt(round) + socket.open() + socket.receive('{"kind":"file","target":"/tmp/a.ts","title":"a.ts"}') + vi.advanceTimersByTime(20_000) + socket.drop() + // A live connection's drop backs off from the BASE delay, not a grown one. + vi.advanceTimersByTime(2_000) + expect(FakeSocket.instances).toHaveLength(round + 2) + } + + expect(socketAt(3)).toBeDefined() + expect(errorSpy.mock.calls.flat().join(' ')).not.toContain('stopping reconnect loop') + mounted.unmount() + }) + + it('backs off exponentially for attempts that never open, and never gives up', () => { + const mounted = mountFeeds() + + socketAt(0).drop() + vi.advanceTimersByTime(1_999) + expect(FakeSocket.instances).toHaveLength(1) + vi.advanceTimersByTime(1) + expect(FakeSocket.instances).toHaveLength(2) + + socketAt(1).drop() + vi.advanceTimersByTime(3_999) + expect(FakeSocket.instances).toHaveLength(2) + vi.advanceTimersByTime(1) + expect(FakeSocket.instances).toHaveLength(3) + + socketAt(2).drop() + vi.advanceTimersByTime(7_999) + expect(FakeSocket.instances).toHaveLength(3) + vi.advanceTimersByTime(1) + expect(FakeSocket.instances).toHaveLength(4) + + // The ceiling holds, and the loop keeps scheduling attempts. + for (let attempts = 0; attempts < 6; attempts++) { + socketAt(FakeSocket.instances.length - 1).drop() + vi.advanceTimersByTime(30_000) + } + expect(FakeSocket.instances.length).toBeGreaterThan(4) + + mounted.unmount() + }) + + it('stops reconnecting after unmount', () => { + const mounted = mountFeeds() + socketAt(0).drop() + vi.advanceTimersByTime(2_000) + expect(FakeSocket.instances).toHaveLength(2) + + mounted.unmount() + socketAt(1).drop() + vi.advanceTimersByTime(120_000) + expect(FakeSocket.instances).toHaveLength(2) + }) +})