Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions docs/design/2026-09-08-session-live-state-poll-interval.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 2 additions & 0 deletions docs/developers/qwen-serve-protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 12 additions & 0 deletions docs/users/qwen-serve.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions packages/cli/src/serve/routes/capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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[]`.
Expand Down
66 changes: 66 additions & 0 deletions packages/cli/src/serve/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
2 changes: 2 additions & 0 deletions packages/cli/src/serve/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[];
/**
Expand Down
5 changes: 5 additions & 0 deletions packages/sdk-typescript/src/daemon/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down
3 changes: 3 additions & 0 deletions packages/web-shell/client/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -11056,6 +11057,7 @@ describe('App conversation indicator keep-alive (#9487)', () => {
mockWorkspace.client,
{
enabled: true,
pollIntervalMs: 10_000,
workspaceCwds: ['/tmp/project', '/tmp/live'],
groupWorkspaceCwds: [],
},
Expand All @@ -11078,6 +11080,7 @@ describe('App conversation indicator keep-alive (#9487)', () => {
mockWorkspace.client,
{
enabled: false,
pollIntervalMs: undefined,
workspaceCwds: [],
groupWorkspaceCwds: [],
},
Expand Down
1 change: 1 addition & 0 deletions packages/web-shell/client/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ let otherWorkspaceSessions: Record<string, DaemonSessionSummary[]>;
let scopedSessionsOptions: { pollIntervalMs?: number };
let workspaceLiveStateOptions: {
enabled: boolean;
pollIntervalMs?: number;
workspaceCwds?: string[];
};
let statusReportOptions: { autoLoad?: boolean; detail?: string };
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -407,6 +407,7 @@ function SessionOverviewPanelInner({
const liveStateActive = manageLiveState && liveStateEnabled;
useWorkspaceSessionLiveState(workspace.client, {
enabled: liveStateActive,
pollIntervalMs: workspace.capabilities?.sessionLiveStatePollIntervalMs,
workspaceCwds: liveStateWorkspaceCwds,
groupWorkspaceCwds: [],
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1540,6 +1540,7 @@ export function WebShellSidebar({
workspace.client,
{
enabled: workspaceSessionLiveStateEnabled,
pollIntervalMs: workspace.capabilities?.sessionLiveStatePollIntervalMs,
workspaceCwds: liveStateWorkspaceCwds,
groupWorkspaceCwds: liveStateGroupWorkspaceCwds,
},
Expand Down
Original file line number Diff line number Diff line change
@@ -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();
});
}
Original file line number Diff line number Diff line change
@@ -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);
},
);
});
Original file line number Diff line number Diff line change
@@ -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;
}
Loading
Loading