diff --git a/docs/design/2026-09-08-session-live-state-poll-interval.md b/docs/design/2026-09-08-session-live-state-poll-interval.md new file mode 100644 index 00000000000..1a822f6a45c --- /dev/null +++ b/docs/design/2026-09-08-session-live-state-poll-interval.md @@ -0,0 +1,27 @@ +# Configurable session live-state polling interval + +## Problem + +Web Shell polls each selected workspace every two seconds. Five workspaces therefore produce about 150 recurring requests per minute. The default should be five seconds, with an operator configuration through the daemon environment rather than a Web Shell preference. + +## Design + +Read `QWEN_SESSION_LIVE_STATE_POLL_INTERVAL_MS` from the daemon startup environment. Accept integer milliseconds from 1000 through 2147483647; missing, blank, malformed, fractional, or out-of-range values use 5000. The lower bound prevents accidental subsecond polling and the upper bound avoids JavaScript timer overflow. Changing the environment takes effect after restarting the daemon and reloading any open Web Shell pages to refresh cached capabilities. + +The existing process-global `GET /capabilities` route advertises the resolved numeric `sessionLiveStatePollIntervalMs`. Resolve it once from the injected, frozen daemon environment, never from a selected workspace overlay or ambient environment during a request. Keep the field optional in daemon and SDK types for compatibility with older daemons. No new feature tag or route is required. + +The sidebar, session overview, and sidebarless App pass the already-loaded workspace capabilities value to the live-state hook. They use the same daemon-wide interval even when displaying several workspaces. The hook validates incoming values too, defaulting to five seconds for older or malformed capability responses. Direct SDK consumers can read the hint but continue to own their scheduling. + +Changing the interval replaces only the recurring timer. In-flight reads, retained snapshots, catalog reconciliation, immediate local/visibility refreshes, and error backoff retain existing ownership and behavior. No Web Shell settings control, localStorage preference, or settings.json entry is introduced. + +## Affected areas and validation + +- Daemon capabilities route, envelope type, SDK type, protocol and user documentation. +- Three Web Shell call sites and the live-state hook/interval validation. +- Focused route tests for defaults, bounds, configured values and startup environment snapshotting. +- Hook and caller tests for actual scheduling, capability wiring, compatibility and cleanup. +- Browser tests and isolated global/local daemon runs for the default five-second cadence, a ten-second environment override, and compatibility with older daemons. + +## Scope + +No SSE, adaptive polling, per-workspace configuration, additional capability requests, or changes to full-catalog polling. Browser and other SDK consumers still own their polling timers. diff --git a/docs/developers/qwen-serve-protocol.md b/docs/developers/qwen-serve-protocol.md index a741f08e107..2c3abdb30d6 100644 --- a/docs/developers/qwen-serve-protocol.md +++ b/docs/developers/qwen-serve-protocol.md @@ -295,6 +295,8 @@ Runtime status and ensure responses use this shape: `workspace_session_live_state` advertises `GET /workspaces/:workspace/sessions/live-state`, a trusted-only, memory-only snapshot of the selected workspace runtime's live sessions plus an in-memory catalog version that tells clients when a full persisted-catalog reload is warranted. It is independent of `workspace_qualified_rest_core`: released daemons can advertise the broader workspace REST capability without implementing this route, so clients must pre-flight this tag directly. The tag is unconditional because a trusted single-workspace primary can use the route by id or cwd; per-workspace trust checks still apply on every request, and the route does not extend the permissive untrusted-secondary persisted-catalog read policy to live bridge state. The tag means the endpoint exists; it does not promise that every live item carries the optional `updatedAt` activity watermark, which is lifecycle-dependent. +The optional top-level `/capabilities` field `sessionLiveStatePollIntervalMs` advertises the daemon-wide live-state polling interval in milliseconds. It is resolved once from the startup environment variable `QWEN_SESSION_LIVE_STATE_POLL_INTERVAL_MS`, independently of workspace environment overlays. Integer values from `1000` to `2147483647` are accepted; missing or invalid values use `5000`. Web Shell consumes this hint for all workspace live-state polling and also falls back to `5000` for an absent or invalid field from an older or incompatible daemon. This field does not change the route's snapshot semantics, immediate local/visibility refreshes, or full-catalog polling. SDK clients remain responsible for their own timers. + `slow_client_warning` covers SSE backpressure behavior: (a) the daemon emits a `slow_client_warning` synthetic event-stream frame when a subscriber's live frame backlog or live serialized-byte backlog crosses 75% full, once per overflow episode (rearmed after both measurements drain below 37.5%); (b) `GET /session/:id/events` accepts a `?maxQueued=N` query param (range `[16, 2048]`) to pre-size the per-subscriber frame backlog for cold reconnects against a large replay ring. The serialized-byte cap is daemon-owned (default **2 MiB** per subscriber), live-only, and intentionally has no query parameter. The daemon-wide ring size is controlled by `--event-ring-size` (default **8000**, per #3803 ยง02). Old daemons silently lack the warning/query behavior โ€” pre-flight this tag before opting in. `typed_event_schema` advertises daemon event payloads that match the SDK's `KnownDaemonEvent` schema. Older daemons may still stream compatible frames, but SDK clients should pre-flight this tag before assuming typed event coverage. diff --git a/docs/users/qwen-serve.md b/docs/users/qwen-serve.md index 209ce60e7e6..6b533df0b89 100644 --- a/docs/users/qwen-serve.md +++ b/docs/users/qwen-serve.md @@ -99,6 +99,18 @@ curl http://127.0.0.1:4170/daemon/status The `workspaceCwd` field surfaces the primary compatibility workspace so clients can intentionally omit `cwd` on `POST /session`. Current clients should select a trusted entry from `workspaces[]` and send that entry's `cwd` when targeting a runtime explicitly. The `limits.maxPendingPromptsPerSession` field advertises the active per-session prompt admission cap; `null` means the cap is disabled. `limits.maxTotalSessions` advertises the optional daemon-wide fresh-session cap; `null` means unlimited. +### Adjust session live-state polling + +Web Shell refreshes workspace session live-state every **5 seconds** by default. To use a different interval, set the daemon environment variable before starting it: + +```bash +QWEN_SESSION_LIVE_STATE_POLL_INTERVAL_MS=10000 qwen serve --web +``` + +The value is an integer in milliseconds, from `1000` to `2147483647`. Missing or invalid values fall back to `5000`. The interval applies to all workspaces served by that daemon; restart the daemon and reload any open Web Shell pages after changing it. Local session actions and returning to a visible tab can still refresh immediately. This only changes live-state polling, not full session-catalog polling. + +The daemon publishes the effective interval as `sessionLiveStatePollIntervalMs` in `/capabilities`. Web Shell uses that value and falls back to five seconds when connecting to an older daemon that omits it. SDK consumers can read the value when choosing their own polling schedule. + ### Run channels from the daemon ```bash diff --git a/packages/cli/src/serve/routes/capabilities.ts b/packages/cli/src/serve/routes/capabilities.ts index 5f37e3d179f..951e2f93419 100644 --- a/packages/cli/src/serve/routes/capabilities.ts +++ b/packages/cli/src/serve/routes/capabilities.ts @@ -58,6 +58,15 @@ export function registerCapabilitiesRoutes( app: Application, deps: RegisterCapabilitiesRoutesDeps, ): void { + const configuredPollIntervalMs = Number( + deps.daemonEnv['QWEN_SESSION_LIVE_STATE_POLL_INTERVAL_MS'], + ); + const sessionLiveStatePollIntervalMs = + Number.isSafeInteger(configuredPollIntervalMs) && + configuredPollIntervalMs >= 1_000 && + configuredPollIntervalMs <= 2_147_483_647 + ? configuredPollIntervalMs + : 5_000; app.get('/capabilities', (_req, res) => { const entries = deps.workspaceRegistry .listAllEntries() @@ -80,6 +89,7 @@ export function registerCapabilitiesRoutes( : {}), mode: deps.mode, features, + sessionLiveStatePollIntervalMs, modelServices: [], // Surface the primary workspace so clients can omit `cwd` on // `POST /session`; multi-workspace clients use `workspaces[]`. diff --git a/packages/cli/src/serve/server.test.ts b/packages/cli/src/serve/server.test.ts index 317e2c2d137..c3fac5a1016 100644 --- a/packages/cli/src/serve/server.test.ts +++ b/packages/cli/src/serve/server.test.ts @@ -4440,6 +4440,72 @@ describe('createServeApp', () => { }); describe('GET /capabilities', () => { + it.each([ + [undefined, 5_000], + ['', 5_000], + [' ', 5_000], + ['invalid', 5_000], + ['10000ms', 5_000], + ['NaN', 5_000], + ['Infinity', 5_000], + ['0', 5_000], + ['-1', 5_000], + ['999', 5_000], + ['1000.5', 5_000], + ['2147483648', 5_000], + ['1000', 1_000], + ['10000', 10_000], + [' 30000 ', 30_000], + ['2147483647', 2_147_483_647], + ])( + 'resolves live-state polling environment %s to %i ms', + async (value, expected) => { + const app = createServeApp(baseOpts, undefined, { + bridge: fakeBridge(), + daemonEnv: { QWEN_SESSION_LIVE_STATE_POLL_INTERVAL_MS: value }, + }); + const response = await request(app) + .get('/capabilities') + .set('Host', `127.0.0.1:${baseOpts.port}`); + expect(response.status).toBe(200); + expect(response.body.sessionLiveStatePollIntervalMs).toBe(expected); + }, + ); + + it('keeps the process-wide live-state interval from the startup environment', async () => { + const daemonEnv = { QWEN_SESSION_LIVE_STATE_POLL_INTERVAL_MS: '10000' }; + const primary = makeWorkspaceRuntimeForTest({ + workspaceId: 'primary-id', + workspaceCwd: WS_BOUND, + primary: true, + bridge: fakeBridge(), + }); + const secondary: WorkspaceRuntime = { + ...makeWorkspaceRuntimeForTest({ + workspaceId: 'secondary-id', + workspaceCwd: '/workspace/secondary', + primary: false, + bridge: fakeBridge(), + }), + env: { + mode: 'runtime-overlay', + overlayKeys: ['QWEN_SESSION_LIVE_STATE_POLL_INTERVAL_MS'], + effectiveEnv: { QWEN_SESSION_LIVE_STATE_POLL_INTERVAL_MS: '30000' }, + }, + }; + const app = createServeApp(baseOpts, undefined, { + bridge: primary.bridge, + workspaceRegistry: createWorkspaceRegistry([primary, secondary]), + daemonEnv, + }); + daemonEnv.QWEN_SESSION_LIVE_STATE_POLL_INTERVAL_MS = '20000'; + const response = await request(app) + .get('/capabilities') + .set('Host', `127.0.0.1:${baseOpts.port}`); + expect(response.status).toBe(200); + expect(response.body.sessionLiveStatePollIntervalMs).toBe(10_000); + }); + it('advertises workflow availability per workspace before a session exists', async () => { const primaryBridge = fakeBridge(); const primary = makeWorkspaceRuntimeForTest({ diff --git a/packages/cli/src/serve/types.ts b/packages/cli/src/serve/types.ts index 844d71d25b9..73c9792273a 100644 --- a/packages/cli/src/serve/types.ts +++ b/packages/cli/src/serve/types.ts @@ -414,6 +414,8 @@ export interface CapabilitiesEnvelope { * additive to v=1; older v=1 daemons omit it. */ qwenCodeVersion?: string; + /** Process-wide live-state polling interval in milliseconds; older daemons omit it. */ + sessionLiveStatePollIntervalMs?: number; mode: ServeMode; features: string[]; /** diff --git a/packages/sdk-typescript/src/daemon/types.ts b/packages/sdk-typescript/src/daemon/types.ts index 519f6befeb2..816d8f33ef9 100644 --- a/packages/sdk-typescript/src/daemon/types.ts +++ b/packages/sdk-typescript/src/daemon/types.ts @@ -474,6 +474,11 @@ export interface DaemonCapabilities { * additive to v=1; older v=1 daemons omit it. */ qwenCodeVersion?: string; + /** + * Process-wide live-state polling interval in milliseconds. Older daemons + * omit it; polling consumers should default to 5000 ms. + */ + sessionLiveStatePollIntervalMs?: number; mode: DaemonMode; /** * Feature tags the client should gate UI off (e.g. `permission_vote`, diff --git a/packages/web-shell/client/App.test.tsx b/packages/web-shell/client/App.test.tsx index 6da36418ec1..3fa0cc3ff0a 100644 --- a/packages/web-shell/client/App.test.tsx +++ b/packages/web-shell/client/App.test.tsx @@ -11032,6 +11032,7 @@ describe('App conversation indicator keep-alive (#9487)', () => { it('polls prompt authority only for trusted workspaces when the sidebar is disabled (#10989)', async () => { mockConnection.capabilities.features = ['workspace_session_live_state']; mockWorkspace.capabilities = { + sessionLiveStatePollIntervalMs: 10_000, workspaces: [ { id: 'primary', @@ -11056,6 +11057,7 @@ describe('App conversation indicator keep-alive (#9487)', () => { mockWorkspace.client, { enabled: true, + pollIntervalMs: 10_000, workspaceCwds: ['/tmp/project', '/tmp/live'], groupWorkspaceCwds: [], }, @@ -11078,6 +11080,7 @@ describe('App conversation indicator keep-alive (#9487)', () => { mockWorkspace.client, { enabled: false, + pollIntervalMs: undefined, workspaceCwds: [], groupWorkspaceCwds: [], }, diff --git a/packages/web-shell/client/App.tsx b/packages/web-shell/client/App.tsx index 4588a033da8..69199909016 100644 --- a/packages/web-shell/client/App.tsx +++ b/packages/web-shell/client/App.tsx @@ -3273,6 +3273,7 @@ export function App({ .map((entry) => entry.cwd); }, [sidebarOptions.enabled, workspaces]); useWorkspaceSessionLiveState(workspace.client, { + pollIntervalMs: workspace.capabilities?.sessionLiveStatePollIntervalMs, enabled: Boolean( sidebarlessLiveStateWorkspaceCwds.length > 0 && connection.capabilities?.features?.includes( diff --git a/packages/web-shell/client/components/SessionOverviewPanel.test.tsx b/packages/web-shell/client/components/SessionOverviewPanel.test.tsx index 7743d6f75cc..4b6f2ccd671 100644 --- a/packages/web-shell/client/components/SessionOverviewPanel.test.tsx +++ b/packages/web-shell/client/components/SessionOverviewPanel.test.tsx @@ -52,6 +52,7 @@ let otherWorkspaceSessions: Record; let scopedSessionsOptions: { pollIntervalMs?: number }; let workspaceLiveStateOptions: { enabled: boolean; + pollIntervalMs?: number; workspaceCwds?: string[]; }; let statusReportOptions: { autoLoad?: boolean; detail?: string }; @@ -120,7 +121,11 @@ vi.mock('../hooks/useScopedSessions', () => ({ vi.mock('../session-catalog/workspace-session-live-state', () => ({ useWorkspaceSessionLiveState: ( _client: unknown, - options: { enabled: boolean; workspaceCwds?: string[] }, + options: { + enabled: boolean; + workspaceCwds?: string[]; + pollIntervalMs?: number; + }, ) => { workspaceLiveStateOptions = options; return new Map(); @@ -2552,6 +2557,21 @@ describe('SessionOverviewPanel', () => { }); describe('SessionOverviewPanel polling', () => { + it('uses the polling interval advertised by the workspace daemon', () => { + connectionState.capabilities = { + features: ['workspace_session_live_state'], + workspaceCwd: '/w', + }; + workspaceCapabilities = { + features: ['workspace_session_live_state'], + workspaceCwd: '/w', + sessionLiveStatePollIntervalMs: 10_000, + }; + render(); + expect(workspaceLiveStateOptions.enabled).toBe(true); + expect(workspaceLiveStateOptions.pollIntervalMs).toBe(10_000); + }); + it('keeps the old status-report details fresh', async () => { sessionsState.sessions = [session('s')]; vi.useFakeTimers(); diff --git a/packages/web-shell/client/components/SessionOverviewPanel.tsx b/packages/web-shell/client/components/SessionOverviewPanel.tsx index 8d6541c30f6..5dd21aa73dd 100644 --- a/packages/web-shell/client/components/SessionOverviewPanel.tsx +++ b/packages/web-shell/client/components/SessionOverviewPanel.tsx @@ -371,7 +371,7 @@ function SessionOverviewPanelInner({ const currentWorkspaceCwd = connection.workspaceCwd || workspaceCwd || primaryCwd; - // Live-state (2s channel) is the sidebar's refresh path: it patches the + // Live-state is the sidebar's refresh path: it patches the // catalog store's sessions with hasActivePrompt / isWaitingForPermission / // isWaitingForUserQuestion and coordinates full-catalog reconciles only when // something actually changed. Adopt it only when trusted live-state routes @@ -407,6 +407,7 @@ function SessionOverviewPanelInner({ const liveStateActive = manageLiveState && liveStateEnabled; useWorkspaceSessionLiveState(workspace.client, { enabled: liveStateActive, + pollIntervalMs: workspace.capabilities?.sessionLiveStatePollIntervalMs, workspaceCwds: liveStateWorkspaceCwds, groupWorkspaceCwds: [], }); diff --git a/packages/web-shell/client/components/sidebar/WebShellSidebar.tsx b/packages/web-shell/client/components/sidebar/WebShellSidebar.tsx index d9c77d0724a..555e1fc995c 100644 --- a/packages/web-shell/client/components/sidebar/WebShellSidebar.tsx +++ b/packages/web-shell/client/components/sidebar/WebShellSidebar.tsx @@ -1540,6 +1540,7 @@ export function WebShellSidebar({ workspace.client, { enabled: workspaceSessionLiveStateEnabled, + pollIntervalMs: workspace.capabilities?.sessionLiveStatePollIntervalMs, workspaceCwds: liveStateWorkspaceCwds, groupWorkspaceCwds: liveStateGroupWorkspaceCwds, }, diff --git a/packages/web-shell/client/e2e/web-shell.live-state-poll-interval.spec.ts b/packages/web-shell/client/e2e/web-shell.live-state-poll-interval.spec.ts new file mode 100644 index 00000000000..5796b2715aa --- /dev/null +++ b/packages/web-shell/client/e2e/web-shell.live-state-poll-interval.spec.ts @@ -0,0 +1,66 @@ +import { expect, test } from '@playwright/test'; +import { + createWebShellDaemonScenario, + installMockDaemon, +} from './utils/mockDaemon'; + +for (const { name, advertisedInterval, expectedInterval } of [ + { + name: 'older daemon', + advertisedInterval: undefined, + expectedInterval: 5000, + }, + { + name: 'ten-second override', + advertisedInterval: 10000, + expectedInterval: 10000, + }, + { name: 'custom interval', advertisedInterval: 7500, expectedInterval: 7500 }, + { name: 'invalid capability', advertisedInterval: 0, expectedInterval: 5000 }, +]) { + test(`uses the daemon live-state cadence for ${name}`, async ({ + page, + }, testInfo) => { + const scenario = createWebShellDaemonScenario({ + capabilities: { + ...(advertisedInterval === undefined + ? {} + : { sessionLiveStatePollIntervalMs: advertisedInterval }), + features: [ + 'session_events', + 'session_source_metadata', + 'workspace_session_live_state', + ], + }, + }); + const daemon = await installMockDaemon(page, scenario, { + baseURL: String(testInfo.project.use.baseURL), + }); + const liveRequests = () => + daemon.requests.filter( + (request) => + request.method === 'GET' && + /^\/workspaces\/[^/]+\/sessions\/live-state\/?$/.test(request.path), + ).length; + const expectCadence = async () => { + const before = liveRequests(); + await page.clock.runFor(expectedInterval - 1); + expect(liveRequests()).toBe(before); + await page.clock.runFor(1); + await expect.poll(liveRequests).toBe(before + 1); + }; + + await page.clock.install({ time: new Date('2026-09-08T00:00:00Z') }); + await page.clock.pauseAt(new Date('2026-09-08T01:00:00Z')); + await page.goto(`/session/${encodeURIComponent(scenario.sessionId)}`); + await expect(page.locator('[data-web-shell-root]')).toBeVisible(); + await expect.poll(liveRequests).toBeGreaterThan(0); + await expectCadence(); + + const beforeReload = liveRequests(); + await page.reload(); + await expect(page.locator('[data-web-shell-root]')).toBeVisible(); + await expect.poll(liveRequests).toBeGreaterThan(beforeReload); + await expectCadence(); + }); +} diff --git a/packages/web-shell/client/session-catalog/session-live-state-poll-interval.test.ts b/packages/web-shell/client/session-catalog/session-live-state-poll-interval.test.ts new file mode 100644 index 00000000000..94d98210939 --- /dev/null +++ b/packages/web-shell/client/session-catalog/session-live-state-poll-interval.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest'; +import { resolveSessionLiveStatePollInterval } from './session-live-state-poll-interval'; + +describe('session live-state polling interval', () => { + it.each([ + undefined, + null, + '', + '10000', + 0, + -1, + 999, + 1000.5, + Number.NaN, + Number.POSITIVE_INFINITY, + 2_147_483_648, + ])( + 'defaults to five seconds for missing or invalid capabilities: %s', + (value) => { + expect(resolveSessionLiveStatePollInterval(value)).toBe(5_000); + }, + ); + + it.each([1_000, 5_000, 10_000, 30_000, 2_147_483_647])( + 'accepts %i milliseconds from the daemon', + (value) => { + expect(resolveSessionLiveStatePollInterval(value)).toBe(value); + }, + ); +}); diff --git a/packages/web-shell/client/session-catalog/session-live-state-poll-interval.ts b/packages/web-shell/client/session-catalog/session-live-state-poll-interval.ts new file mode 100644 index 00000000000..a9ea40f200c --- /dev/null +++ b/packages/web-shell/client/session-catalog/session-live-state-poll-interval.ts @@ -0,0 +1,10 @@ +export const SESSION_LIVE_STATE_POLL_MS = 5_000; + +export function resolveSessionLiveStatePollInterval(value: unknown): number { + return typeof value === 'number' && + Number.isSafeInteger(value) && + value >= 1_000 && + value <= 2_147_483_647 + ? value + : SESSION_LIVE_STATE_POLL_MS; +} diff --git a/packages/web-shell/client/session-catalog/workspace-session-live-state.test.tsx b/packages/web-shell/client/session-catalog/workspace-session-live-state.test.tsx index f6817975cf6..b9002d7c6c7 100644 --- a/packages/web-shell/client/session-catalog/workspace-session-live-state.test.tsx +++ b/packages/web-shell/client/session-catalog/workspace-session-live-state.test.tsx @@ -110,9 +110,11 @@ describe('useWorkspaceSessionLiveState', () => { function Probe({ organizationEnabled = false, sourceType, + pollIntervalMs, }: { organizationEnabled?: boolean; sourceType?: string; + pollIntervalMs?: number; }) { const activeQuery = useMemo( () => ({ @@ -125,6 +127,7 @@ describe('useWorkspaceSessionLiveState', () => { controller = useSessionCatalogController(client); const groupCatalogs = useWorkspaceSessionLiveState(client, { enabled: true, + pollIntervalMs, workspaceCwds: ['/work'], groupWorkspaceCwds: organizationEnabled ? ['/work'] : [], }); @@ -141,12 +144,14 @@ describe('useWorkspaceSessionLiveState', () => { async function renderProbe( organizationEnabled = false, sourceType?: string, + pollIntervalMs?: number, ): Promise { await act(async () => { root.render( , ); await Promise.resolve(); @@ -156,6 +161,57 @@ describe('useWorkspaceSessionLiveState', () => { }); } + it('defaults to five seconds between periodic live-state requests', async () => { + await renderProbe(); + expect(getLiveState).toHaveBeenCalledTimes(2); + await act(async () => vi.advanceTimersByTimeAsync(4_999)); + expect(getLiveState).toHaveBeenCalledTimes(2); + await act(async () => vi.advanceTimersByTimeAsync(1)); + expect(getLiveState).toHaveBeenCalledTimes(3); + }); + + it('changes the interval without releasing state, rescanning, or overlapping an in-flight request', async () => { + await renderProbe(); + const catalogRequests = listSessions.mock.calls.length; + const store = getSessionCatalogStore(client); + let resolveLive!: (value: DaemonWorkspaceSessionLiveState) => void; + getLiveState.mockReturnValueOnce( + new Promise((resolve) => { + resolveLive = resolve; + }), + ); + await act(async () => vi.advanceTimersByTimeAsync(5_000)); + expect(getLiveState).toHaveBeenCalledTimes(3); + + await renderProbe(false, undefined, 10_000); + expect(store.isWorkspaceLiveStateEnabled('/work')).toBe(true); + expect(getLiveState).toHaveBeenCalledTimes(3); + expect(listSessions).toHaveBeenCalledTimes(catalogRequests); + await act(async () => vi.advanceTimersByTimeAsync(10_000)); + expect(getLiveState).toHaveBeenCalledTimes(3); + await act(async () => resolveLive(liveState(1, true))); + expect(container.textContent).toBe('true:true:no-group'); + await act(async () => vi.advanceTimersByTimeAsync(9_999)); + expect(getLiveState).toHaveBeenCalledTimes(3); + await act(async () => vi.advanceTimersByTimeAsync(1)); + expect(getLiveState).toHaveBeenCalledTimes(4); + expect(listSessions).toHaveBeenCalledTimes(catalogRequests); + + act(() => root.render(null)); + await act(async () => vi.advanceTimersByTimeAsync(30_000)); + expect(getLiveState).toHaveBeenCalledTimes(4); + expect(store.isWorkspaceLiveStateEnabled('/work')).toBe(false); + }); + + it('refreshes immediately on a local wake even with a thirty-second interval', async () => { + await renderProbe(false, undefined, 30_000); + const initialRequests = getLiveState.mock.calls.length; + await act(async () => { + getSessionCatalogStore(client).requestWorkspaceLiveStateRefresh('/work'); + }); + expect(getLiveState.mock.calls.length).toBeGreaterThan(initialRequests); + }); + it('polls only live-state after the initial version-fenced catalog load', async () => { let active = false; getLiveState.mockImplementation(async () => liveState(1, active)); @@ -176,12 +232,13 @@ describe('useWorkspaceSessionLiveState', () => { }); it('does not rescan the catalog for prompt admission, and rate-limits unusable-watermark completions', async () => { - await renderProbe(); + const pollIntervalMs = 2_000; + await renderProbe(false, undefined, pollIntervalMs); const catalogRequests = listSessions.mock.calls.length; act(() => controller.promptAdmitted('/work', 'session-a')); await act(async () => { - await vi.advanceTimersByTimeAsync(SESSION_LIVE_STATE_POLL_MS); + await vi.advanceTimersByTimeAsync(pollIntervalMs); }); expect(listSessions).toHaveBeenCalledTimes(catalogRequests); @@ -193,13 +250,13 @@ describe('useWorkspaceSessionLiveState', () => { controller.turnCompleted('/work', 'session-a'); }); await act(async () => { - await vi.advanceTimersByTimeAsync(SESSION_LIVE_STATE_POLL_MS); + await vi.advanceTimersByTimeAsync(pollIntervalMs); }); expect(listSessions).toHaveBeenCalledTimes(catalogRequests + 1); act(() => controller.turnCompleted('/work', 'session-a')); await act(async () => { - await vi.advanceTimersByTimeAsync(SESSION_LIVE_STATE_POLL_MS); + await vi.advanceTimersByTimeAsync(pollIntervalMs); }); expect(listSessions).toHaveBeenCalledTimes(catalogRequests + 1); // Falling back must still resolve the pending completion โ€” a leaked @@ -884,13 +941,14 @@ describe('useWorkspaceSessionLiveState', () => { }); it('rate-limits sustained lifecycle invalidations to one reconcile per window', async () => { - await renderProbe(); + const pollIntervalMs = 2_000; + await renderProbe(false, undefined, pollIntervalMs); const initialCatalogRequests = listSessions.mock.calls.length; // A single local change still reconciles immediately. act(() => controller.sessionCreated('/work', 'session-b')); await act(async () => { - await vi.advanceTimersByTimeAsync(SESSION_LIVE_STATE_POLL_MS); + await vi.advanceTimersByTimeAsync(pollIntervalMs); }); expect(listSessions).toHaveBeenCalledTimes(initialCatalogRequests + 1); @@ -902,7 +960,7 @@ describe('useWorkspaceSessionLiveState', () => { controller.promptAdmissionUncertain('/work'); }); await act(async () => { - await vi.advanceTimersByTimeAsync(SESSION_LIVE_STATE_POLL_MS * 3); + await vi.advanceTimersByTimeAsync(pollIntervalMs * 3); }); expect(listSessions).toHaveBeenCalledTimes(initialCatalogRequests + 1); @@ -966,7 +1024,8 @@ describe('useWorkspaceSessionLiveState', () => { }); it('does not hot-loop when a staged commit is persistently refused', async () => { - await renderProbe(); + const pollIntervalMs = 2_000; + await renderProbe(false, undefined, pollIntervalMs); const initialCatalogRequests = listSessions.mock.calls.length; // Every staged fetch bumps the revision mid-flight, so every commit @@ -988,7 +1047,7 @@ describe('useWorkspaceSessionLiveState', () => { expect(callsAfterGiveUp).toBeGreaterThan(initialCatalogRequests); await act(async () => { - await vi.advanceTimersByTimeAsync(SESSION_LIVE_STATE_POLL_MS * 4); + await vi.advanceTimersByTimeAsync(pollIntervalMs * 4); }); // One invalidation-gated retry per cooldown window at most โ€” without // the fix every 2s tick re-runs two catalog fetches. diff --git a/packages/web-shell/client/session-catalog/workspace-session-live-state.ts b/packages/web-shell/client/session-catalog/workspace-session-live-state.ts index 92bde8e0dc8..5d14c6ba568 100644 --- a/packages/web-shell/client/session-catalog/workspace-session-live-state.ts +++ b/packages/web-shell/client/session-catalog/workspace-session-live-state.ts @@ -9,8 +9,9 @@ import { getSessionCatalogStore, type StagedWorkspaceSessionCatalog, } from './session-catalog-store'; +import { resolveSessionLiveStatePollInterval } from './session-live-state-poll-interval'; -export const SESSION_LIVE_STATE_POLL_MS = 2_000; +export { SESSION_LIVE_STATE_POLL_MS } from './session-live-state-poll-interval'; export const SESSION_LIVE_STATE_ERROR_RETRY_MS = 30_000; /** * Consecutive live-state request failures before the retained snapshot is @@ -39,6 +40,7 @@ interface WorkspacePollState { interface WorkspaceSessionLiveStateOptions { enabled: boolean; + pollIntervalMs?: number; workspaceCwds: readonly string[]; groupWorkspaceCwds: readonly string[]; } @@ -79,11 +81,16 @@ export function useWorkspaceSessionLiveState( client: DaemonClient, { enabled, + pollIntervalMs: configuredPollIntervalMs, workspaceCwds, groupWorkspaceCwds, }: WorkspaceSessionLiveStateOptions, ): ReadonlyMap { const catalogStore = useMemo(() => getSessionCatalogStore(client), [client]); + const pollIntervalMs = resolveSessionLiveStatePollInterval( + configuredPollIntervalMs, + ); + const pollAllRef = useRef<(() => void) | undefined>(undefined); const targetsKey = [...new Set(workspaceCwds)].sort().join('\n'); const targets = useMemo( () => targetsKey.split('\n').filter(Boolean), @@ -388,7 +395,7 @@ export function useWorkspaceSessionLiveState( // Interactive refresh requests (explicit refresh(), expiring // maxAgeMs subscriptions, group-membership growth) and recorded turn // completions wake the loop immediately instead of waiting for the - // next 2s tick. + // next periodic tick. const stopWake = catalogStore.onLiveStateWake( (workspaceCwd, bypassRetry) => { const state = states.find( @@ -406,20 +413,27 @@ export function useWorkspaceSessionLiveState( if (typeof document !== 'undefined') { document.addEventListener('visibilitychange', onVisibilityWake); } + pollAllRef.current = onVisibilityWake; for (const state of states) void poll(state); - const interval = window.setInterval(() => { - for (const state of states) void poll(state); - }, SESSION_LIVE_STATE_POLL_MS); return () => { disposed = true; + pollAllRef.current = undefined; stopWake(); if (typeof document !== 'undefined') { document.removeEventListener('visibilitychange', onVisibilityWake); } - window.clearInterval(interval); for (const release of releaseLiveState) release(); }; }, [catalogStore, client, enabled, targets]); + useEffect(() => { + if (!enabled || targets.length === 0) return; + const interval = window.setInterval( + () => pollAllRef.current?.(), + pollIntervalMs, + ); + return () => window.clearInterval(interval); + }, [client, enabled, pollIntervalMs, targets]); + return groupCatalogs; }