@linxin666/dsh-remote-web-ui 0.1.14 → 0.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,6 +9,7 @@
9
9
  */
10
10
  import type { IncomingMessage, ServerResponse } from 'node:http';
11
11
  import type { WebRoute } from '@deepseek-ai/dsh-host-webserver';
12
+ import { z } from 'zod';
12
13
  import { type PairingService, type PairingSnapshot } from './pairing.ts';
13
14
  /**
14
15
  * Browser-trust fence for the /api/pair routes, mirroring the connection
@@ -43,6 +44,22 @@ export declare const PAIR_PATHS: {
43
44
  readonly status: "/api/pair/status";
44
45
  readonly events: "/api/pair/events";
45
46
  };
47
+ /**
48
+ * /api/pair request payload contracts. Each POST endpoint validates its body
49
+ * against one of these instead of reaching into a hand-parsed object: the
50
+ * control-plane endpoints that carry no meaningful payload use the permissive
51
+ * pairActionPayloadSchema so their smoke calls keep working unchanged, while
52
+ * issue/accept enforce their optional/required fields. Unknown (extra) keys
53
+ * are tolerated exactly as the previous manual reads ignored them.
54
+ */
55
+ export declare const issuePayloadSchema: z.ZodObject<{
56
+ workspaceId: z.ZodOptional<z.ZodString>;
57
+ address: z.ZodOptional<z.ZodString>;
58
+ }, z.core.$strip>;
59
+ export declare const acceptPayloadSchema: z.ZodObject<{
60
+ token: z.ZodDefault<z.ZodString>;
61
+ }, z.core.$strip>;
62
+ export declare const pairActionPayloadSchema: z.ZodObject<{}, z.core.$loose>;
46
63
  /** The SSE fan-out for desktop panel status. */
47
64
  export declare class PairingEventsStream {
48
65
  private readonly streams;
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AAChE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAA;AAC/D,OAAO,EAA0B,KAAK,cAAc,EAAE,KAAK,eAAe,EAAE,MAAM,cAAc,CAAA;AAGhG;;;;;;;;;;;;;GAaG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CA6BtG;AAKD;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAOxE;AAKD,8CAA8C;AAC9C,eAAO,MAAM,UAAU;;;;;;;CAOb,CAAA;AAiCV,gDAAgD;AAChD,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA0B;IAElD;;OAEG;gBACS,OAAO,EAAE,cAAc;IAInC,4DAA4D;IAC5D,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,cAAc,GAAG,IAAI;IAiBrD,kEAAkE;IAClE,IAAI,CAAC,QAAQ,EAAE,eAAe,GAAG,IAAI;IAYrC,wCAAwC;IACxC,IAAI,IAAI,IAAI,MAAM,CAEjB;CACF;AAED,6CAA6C;AAC7C,MAAM,WAAW,cAAc;IAC7B,2BAA2B;IAC3B,OAAO,EAAE,cAAc,CAAA;IACvB,0EAA0E;IAC1E,YAAY,EAAE,SAAS,MAAM,EAAE,CAAA;CAChC;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,cAAc,GAAG,QAAQ,EAAE,CAgK3D"}
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AAChE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAA;AAC/D,OAAO,EAAE,CAAC,EAAgB,MAAM,KAAK,CAAA;AACrC,OAAO,EAA0B,KAAK,cAAc,EAAE,KAAK,eAAe,EAAE,MAAM,cAAc,CAAA;AAGhG;;;;;;;;;;;;;GAaG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CA6BtG;AAKD;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAOxE;AAKD,8CAA8C;AAC9C,eAAO,MAAM,UAAU;;;;;;;CAOb,CAAA;AAEV;;;;;;;GAOG;AACH,eAAO,MAAM,kBAAkB;;;iBAG7B,CAAA;AACF,eAAO,MAAM,mBAAmB;;iBAE9B,CAAA;AACF,eAAO,MAAM,uBAAuB,gCAA6B,CAAA;AA4CjE,gDAAgD;AAChD,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA0B;IAElD;;OAEG;gBACS,OAAO,EAAE,cAAc;IAInC,4DAA4D;IAC5D,IAAI,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,cAAc,GAAG,IAAI;IAiBrD,kEAAkE;IAClE,IAAI,CAAC,QAAQ,EAAE,eAAe,GAAG,IAAI;IAYrC,wCAAwC;IACxC,IAAI,IAAI,IAAI,MAAM,CAEjB;CACF;AAED,6CAA6C;AAC7C,MAAM,WAAW,cAAc;IAC7B,2BAA2B;IAC3B,OAAO,EAAE,cAAc,CAAA;IACvB,0EAA0E;IAC1E,YAAY,EAAE,SAAS,MAAM,EAAE,CAAA;CAChC;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,cAAc,GAAG,QAAQ,EAAE,CA4K3D"}
@@ -7,6 +7,7 @@
7
7
  * cookie set on accept is the device identity the api/gate listener checks
8
8
  * on every other /api request.
9
9
  */
10
+ import { z } from 'zod';
10
11
  import { UnknownLanAddressError } from "./pairing.js";
11
12
  import { isLoopbackClient, readCookie } from "./gate.js";
12
13
  /**
@@ -90,6 +91,32 @@ export const PAIR_PATHS = {
90
91
  status: '/api/pair/status',
91
92
  events: '/api/pair/events',
92
93
  };
94
+ /**
95
+ * /api/pair request payload contracts. Each POST endpoint validates its body
96
+ * against one of these instead of reaching into a hand-parsed object: the
97
+ * control-plane endpoints that carry no meaningful payload use the permissive
98
+ * pairActionPayloadSchema so their smoke calls keep working unchanged, while
99
+ * issue/accept enforce their optional/required fields. Unknown (extra) keys
100
+ * are tolerated exactly as the previous manual reads ignored them.
101
+ */
102
+ export const issuePayloadSchema = z.object({
103
+ workspaceId: z.string().min(1).optional(),
104
+ address: z.string().min(1).optional(),
105
+ });
106
+ export const acceptPayloadSchema = z.object({
107
+ token: z.string().default(''),
108
+ });
109
+ export const pairActionPayloadSchema = z.object({}).passthrough();
110
+ /**
111
+ * Parse a pair request body through schema. A missing/empty or non-object
112
+ * body is treated as an empty object (the same way the previous manual reads
113
+ * yielded absent fields), and a value that fails the schema returns
114
+ * `undefined` so the caller can answer with the existing error shape.
115
+ */
116
+ function parsePairPayload(schema, body) {
117
+ const result = schema.safeParse(body ?? {});
118
+ return result.success ? result.data : undefined;
119
+ }
93
120
  /** One JSON response. */
94
121
  function writeJson(res, status, body) {
95
122
  const payload = JSON.stringify(body);
@@ -205,12 +232,12 @@ export function makeRoutes(deps) {
205
232
  return;
206
233
  }
207
234
  const body = await readJsonBody(req);
208
- const workspaceId = body === undefined || typeof body.workspaceId !== 'string' || body.workspaceId === ''
209
- ? undefined
210
- : body.workspaceId;
211
- const address = body === undefined || typeof body.address !== 'string' || body.address === ''
212
- ? undefined
213
- : body.address;
235
+ const payload = parsePairPayload(issuePayloadSchema, body);
236
+ if (payload === undefined) {
237
+ writeJson(res, 400, { ok: false, code: 'bad-payload' });
238
+ return;
239
+ }
240
+ const { workspaceId, address } = payload;
214
241
  try {
215
242
  const { token, expiresAt } = service.issue(workspaceId, address);
216
243
  // The default base is the public (tunneled) URL when configured — a
@@ -255,8 +282,12 @@ export function makeRoutes(deps) {
255
282
  return;
256
283
  }
257
284
  const body = await readJsonBody(req);
258
- const token = typeof body?.token === 'string' ? body.token : '';
259
- const result = service.accept(token);
285
+ const payload = parsePairPayload(acceptPayloadSchema, body);
286
+ if (payload === undefined) {
287
+ writeJson(res, 400, { ok: false, code: 'bad-payload' });
288
+ return;
289
+ }
290
+ const result = service.accept(payload.token);
260
291
  if (!result.ok) {
261
292
  writeJson(res, result.code === 'used' ? 409 : 404, { ok: false, code: result.code });
262
293
  return;
@@ -276,7 +307,11 @@ export function makeRoutes(deps) {
276
307
  writeJson(res, 403, { ok: false, code: 'forbidden' });
277
308
  return;
278
309
  }
279
- await readJsonBody(req);
310
+ const body = await readJsonBody(req);
311
+ if (parsePairPayload(pairActionPayloadSchema, body) === undefined) {
312
+ writeJson(res, 400, { ok: false, code: 'bad-payload' });
313
+ return;
314
+ }
280
315
  service.stop();
281
316
  writeJson(res, 200, { ok: true });
282
317
  };
@@ -287,7 +322,11 @@ export function makeRoutes(deps) {
287
322
  writeJson(res, 403, { ok: false, code: 'forbidden' });
288
323
  return;
289
324
  }
290
- await readJsonBody(req);
325
+ const body = await readJsonBody(req);
326
+ if (parsePairPayload(pairActionPayloadSchema, body) === undefined) {
327
+ writeJson(res, 400, { ok: false, code: 'bad-payload' });
328
+ return;
329
+ }
291
330
  const deviceId = readCookie(req.headers.cookie, service.config.cookieName);
292
331
  if (deviceId === undefined || !service.heartbeat(deviceId)) {
293
332
  writeJson(res, 401, { ok: false, code: 'unpaired' });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@linxin666/dsh-remote-web-ui",
3
3
  "description": "Mobile remote control for the dsh web GUI: scan-to-pair QR entry beside the settings button, one-time pairing tokens, live device status, and revocable mobile sessions",
4
- "version": "0.1.14",
4
+ "version": "0.1.15",
5
5
  "type": "module",
6
6
  "engines": {
7
7
  "node": "^22.19.0 || >=24.0.0"
@@ -1,25 +1,44 @@
1
+ // Generated by scripts/sync-shared.mjs from shared/client/settings/PluginSettingsCard.tsx. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
1
2
  /**
2
- * Shared chrome for the plugin settings card: a disclosure header naming the
3
- * plugin and what its settings govern, the controls inside, and the save that
4
- * writes them. Renders nothing while the namespace is unavailable — a
3
+ * Family-shared chrome for plugin settings cards: a disclosure header naming
4
+ * the plugin and what its settings govern, the controls inside, and the save
5
+ * that writes them. Renders nothing while the namespace is unavailable — a
5
6
  * deployment that does not compose the owning plugin should show no trace of
6
- * it. Mirrors the official ui-plugin-config PluginCard in a self-contained
7
- * slice (this package must not depend on a sibling UI package).
7
+ * it. Inlined into each consumer's client bundle; mirrors the official
8
+ * ui-plugin-config PluginCard in a self-contained slice.
8
9
  */
9
10
 
10
11
  import { useState, type ReactNode } from 'react'
11
12
  import type { CardShell } from './settings-form.ts'
12
- import type { SettingsCardKey } from './locales.ts'
13
13
  import css from './settings-card.module.css'
14
14
 
15
+ /** Copy keys the card chrome itself reads; every consumer locale carries this shared vocabulary. */
16
+ export const CARD_COPY_KEYS = [
17
+ 'settings.collapse',
18
+ 'settings.expand',
19
+ 'settings.notExposed',
20
+ 'settings.unsaved',
21
+ 'settings.readOnly',
22
+ 'settings.saveFailed',
23
+ 'settings.discard',
24
+ 'settings.save',
25
+ 'settings.saving',
26
+ ] as const
27
+
28
+ /** Copy key the card chrome itself reads. */
29
+ export type CardCopyKey = (typeof CARD_COPY_KEYS)[number]
30
+
31
+ /** Key domain for the plugin's own copy (inferred per consumer). */
32
+ export type SettingsCardKey<TKey extends string = string> = TKey | CardCopyKey
33
+
15
34
  /** Card chrome shared by every plugin settings card. */
16
- export interface PluginSettingsCardProps {
35
+ export interface PluginSettingsCardProps<TKey extends string = string> {
17
36
  /** Locale reader for this card's copy. */
18
- t: (key: SettingsCardKey) => string
37
+ t: (key: SettingsCardKey<TKey>, params?: Record<string, string | number>) => string
19
38
  /** Locale key of the plugin's name. */
20
- titleKey: SettingsCardKey
39
+ titleKey: TKey
21
40
  /** Locale key of the line describing what this plugin's settings govern. */
22
- descriptionKey: SettingsCardKey
41
+ descriptionKey: TKey
23
42
  /** The card's form state: availability, writability, and what a save would do. */
24
43
  state: CardShell
25
44
  /** Write every staged edit. */
@@ -35,11 +54,12 @@ export interface PluginSettingsCardProps {
35
54
  * @param props - the plugin's copy keys, its form state, and its controls.
36
55
  * @returns the card, or nothing while the namespace is still loading.
37
56
  */
38
- export function PluginSettingsCard(props: PluginSettingsCardProps) {
57
+ export function PluginSettingsCard<TKey extends string = string>(props: PluginSettingsCardProps<TKey>) {
39
58
  const [open, setOpen] = useState(false)
40
59
  const { state } = props
41
60
  if (!state.available) return null
42
61
  const title = props.t(props.titleKey)
62
+ const description = props.t(props.descriptionKey)
43
63
  const blocked = !state.dirty || state.invalid || state.saving
44
64
  const cardClass = open ? `${css.cardOpen} ${css.card}` : css.card
45
65
  // The namespace exists but the Host does not serve it to this client (the
@@ -57,8 +77,8 @@ export function PluginSettingsCard(props: PluginSettingsCardProps) {
57
77
  onClick={() => { setOpen(!open) }}
58
78
  >
59
79
  <span className={css.headText}>
60
- <span className={css.name}>{title}</span>
61
- <span className={css.description}>{props.t(props.descriptionKey)}</span>
80
+ <span className={css.name} title={title}>{title}</span>
81
+ <span className={css.description} title={description}>{description}</span>
62
82
  </span>
63
83
  <svg
64
84
  width="14"
@@ -94,10 +114,10 @@ export function PluginSettingsCard(props: PluginSettingsCardProps) {
94
114
  onClick={() => { setOpen(!open) }}
95
115
  >
96
116
  <span className={css.headText}>
97
- <span className={css.name}>{title}</span>
98
- <span className={css.description}>{props.t(props.descriptionKey)}</span>
117
+ <span className={css.name} title={title}>{title}</span>
118
+ <span className={css.description} title={description}>{description}</span>
99
119
  </span>
100
- {state.dirty ? <span className={css.pending}>{props.t('settings.unsaved')}</span> : null}
120
+ {state.dirty ? <span className={css.pending} title={props.t('settings.unsaved')}>{props.t('settings.unsaved')}</span> : null}
101
121
  <svg
102
122
  width="14"
103
123
  height="14"
@@ -259,4 +279,50 @@ export function BooleanField(props: FieldProps & {
259
279
  <p className={css.hint}>{props.hint}</p>
260
280
  </div>
261
281
  )
262
- }
282
+ }
283
+
284
+ /** A staged enumerated field rendered as a select. */
285
+ export function ChoiceField(props: FieldProps & {
286
+ /** Copy for the inherit option (draft text is the empty string). */
287
+ inheritLabel: string
288
+ /** Choices rendered in order; `value` is the draft/stored text. */
289
+ choices: ReadonlyArray<{ value: string; label: string }>
290
+ }) {
291
+ return (
292
+ <div className={css.field}>
293
+ <div className={css.head}>
294
+ <label className={css.label} htmlFor={props.id}>{props.label}</label>
295
+ {props.overridden
296
+ ? (
297
+ <span className={css.badges}>
298
+ <span className={css.badge}>{props.overriddenLabel}</span>
299
+ <button
300
+ type="button"
301
+ className={css.reset}
302
+ disabled={props.disabled}
303
+ onClick={props.onReset}
304
+ >
305
+ {props.resetLabel}
306
+ </button>
307
+ </span>
308
+ )
309
+ : null}
310
+ </div>
311
+ <select
312
+ id={props.id}
313
+ className={css.select}
314
+ value={props.text}
315
+ disabled={props.disabled}
316
+ onChange={(event) => { props.onEdit(event.target.value) }}
317
+ >
318
+ <option value="">{props.inheritLabel}</option>
319
+ {props.choices.map(choice => (
320
+ <option key={choice.value} value={choice.value}>{choice.label}</option>
321
+ ))}
322
+ </select>
323
+ <p className={props.invalid ? css.invalid : css.hint}>
324
+ {props.invalid ? props.invalidLabel : props.hint}
325
+ </p>
326
+ </div>
327
+ )
328
+ }
@@ -1,3 +1,4 @@
1
+ /* Generated by scripts/sync-shared.mjs from shared/client/settings/settings-card.module.css. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs". */
1
2
  /* Plugin settings card chrome + staged form fields.
2
3
  * Aligned with the official ui-settings-plugins PluginCard / fields CSS:
3
4
  * same semantic tokens, radius, typography and states so family cards read
@@ -229,6 +230,11 @@
229
230
  outline-offset: 2px;
230
231
  }
231
232
 
233
+ .reset:focus-visible {
234
+ outline: 2px solid var(--dsw-alias-brand-primary);
235
+ outline-offset: 2px;
236
+ }
237
+
232
238
  .input,
233
239
  .select {
234
240
  border: 1px solid var(--dsw-alias-border-l2);
@@ -1,10 +1,11 @@
1
+ // Generated by scripts/sync-shared.mjs from shared/client/settings/settings-form.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
1
2
  /**
2
3
  * Staged form model behind the plugin settings card. A card stages what the
3
4
  * user types and writes it only when they save — the settings write is a
4
5
  * durable, revision-fenced document mutation, so staging keeps what is on
5
- * screen exactly what a save would store. Mirrors the official
6
- * ui-plugin-config card-store pattern in a self-contained slice: this
7
- * package must not depend on a sibling UI package.
6
+ * screen exactly what a save would store. Family-shared slice inlined into
7
+ * each plugin's client bundle; mirrors the official ui-plugin-config
8
+ * card-store pattern.
8
9
  */
9
10
 
10
11
  import type { SettingsScope, SettingsScopeSnapshot, SnapshotStore } from '@deepseek-ai/dsh-client-runtime/client'
@@ -90,8 +91,17 @@ interface PlannedWrite {
90
91
  run: (() => Promise<boolean>) | undefined
91
92
  }
92
93
 
93
- /** A whole-number field. An empty draft clears the field; any other draft that is not a finite number blocks the save. */
94
- export function numberField(field: string): FieldSpec {
94
+ /** Constraints a numeric field's accepted drafts must satisfy, mirroring the host schema. */
95
+ export interface NumberConstraints {
96
+ /** The accepted value must be a whole number. */
97
+ integer?: boolean
98
+ /** The accepted value must be at least this. */
99
+ min?: number
100
+ }
101
+
102
+ /** A whole- or decimal-number field. An empty draft clears the field; any other draft that is not a finite number within the constraints blocks the save. */
103
+ export function numberField(field: string, constraints: NumberConstraints = {}): FieldSpec {
104
+ const { integer = false, min } = constraints
95
105
  return {
96
106
  field,
97
107
  format: value => typeof value === 'number' ? String(value) : '',
@@ -99,7 +109,10 @@ export function numberField(field: string): FieldSpec {
99
109
  const trimmed = text.trim()
100
110
  if (trimmed === '') return { kind: 'clear' }
101
111
  const parsed = Number(trimmed)
102
- return Number.isFinite(parsed) ? { kind: 'set', value: parsed } : undefined
112
+ if (!Number.isFinite(parsed)) return undefined
113
+ if (integer && !Number.isInteger(parsed)) return undefined
114
+ if (min !== undefined && parsed < min) return undefined
115
+ return { kind: 'set', value: parsed }
103
116
  },
104
117
  }
105
118
  }
@@ -122,13 +135,27 @@ export function booleanField(field: string): FieldSpec {
122
135
  field,
123
136
  format: value => typeof value === 'boolean' ? String(value) : '',
124
137
  parse: (text) => {
125
- if (text === 'true') return { kind: 'set', value: true }
126
- if (text === 'false') return { kind: 'set', value: false }
138
+ const trimmed = text.trim()
139
+ if (trimmed === '') return { kind: 'clear' }
140
+ if (trimmed === 'true') return { kind: 'set', value: true }
141
+ if (trimmed === 'false') return { kind: 'set', value: false }
127
142
  return undefined
128
143
  },
129
144
  }
130
145
  }
131
146
 
147
+ /** An enumerated string field; only the listed choices are accepted. An empty draft clears the field. */
148
+ export function choiceField(field: string, choices: readonly string[]): FieldSpec {
149
+ return {
150
+ field,
151
+ format: value => typeof value === 'string' && choices.includes(value) ? value : '',
152
+ parse: (text) => {
153
+ if (text === '') return { kind: 'clear' }
154
+ return choices.includes(text) ? { kind: 'set', value: text } : undefined
155
+ },
156
+ }
157
+ }
158
+
132
159
  /**
133
160
  * Stages one card's edits over one settings namespace and writes them on save.
134
161
  *
@@ -215,6 +242,9 @@ export class CardForm<T> {
215
242
  const plan = this.plan()
216
243
  const writes = plan.flatMap(item => item.run === undefined ? [] : [item.run])
217
244
  if (plan.length === 0 || this.saving || writes.length !== plan.length) return
245
+ // Snapshot the fields this save writes, so edits staged while it is in
246
+ // flight survive: only the staged keys this save actually wrote are cleared.
247
+ const fields = new Set(plan.map(item => item.field))
218
248
  this.saving = true
219
249
  this.failed = false
220
250
  this.publish()
@@ -222,7 +252,9 @@ export class CardForm<T> {
222
252
  for (const write of writes) {
223
253
  landed = await write() && landed
224
254
  }
225
- if (landed) this.staged.clear()
255
+ if (landed) {
256
+ for (const field of fields) this.staged.delete(field)
257
+ }
226
258
  this.saving = false
227
259
  this.failed = !landed
228
260
  this.publish()
@@ -80,8 +80,9 @@ describe('MuxClient polling fallback', () => {
80
80
  await vi.advanceTimersByTimeAsync(400)
81
81
  expect(pollLatest).not.toHaveBeenCalled()
82
82
 
83
- // Past the stall threshold the first poll runs and emits seq 0.
84
- await vi.advanceTimersByTimeAsync(700) // 1100ms total -> first stall-checker tick
83
+ // The single tick (400 ms) crosses the 800 ms stall threshold at 1200 ms:
84
+ // the same tick then runs the first poll and emits seq 0.
85
+ await vi.advanceTimersByTimeAsync(800) // 1200ms total -> first stall crossing tick
85
86
  expect(pollLatest).toHaveBeenCalledWith('s1')
86
87
  expect(frames).toHaveLength(1)
87
88
  expect(frames[0]).toMatchObject({ type: 'session/event', sessionId: 's1' })
@@ -104,7 +105,7 @@ describe('MuxClient polling fallback', () => {
104
105
  client.start()
105
106
  client.observe('s1')
106
107
 
107
- await vi.advanceTimersByTimeAsync(1100) // first poll -> 3 events
108
+ await vi.advanceTimersByTimeAsync(1200) // first poll -> 3 events
108
109
  expect(frames).toHaveLength(3)
109
110
 
110
111
  await vi.advanceTimersByTimeAsync(400) // second poll -> same page, nothing new
@@ -119,7 +120,7 @@ describe('MuxClient polling fallback', () => {
119
120
  client.start()
120
121
  client.observe('s1')
121
122
 
122
- await vi.advanceTimersByTimeAsync(1100)
123
+ await vi.advanceTimersByTimeAsync(1200)
123
124
  expect(pollLatest).toHaveBeenCalled()
124
125
 
125
126
  client.observe(undefined)
@@ -136,7 +137,7 @@ describe('MuxClient polling fallback', () => {
136
137
  client.start()
137
138
  client.observe('s1')
138
139
 
139
- await vi.advanceTimersByTimeAsync(1100)
140
+ await vi.advanceTimersByTimeAsync(1200)
140
141
  expect(pollLatest).toHaveBeenCalled()
141
142
 
142
143
  client.stop()
@@ -156,7 +157,7 @@ describe('MuxClient polling fallback', () => {
156
157
  client.observe('s1')
157
158
 
158
159
  // Stall into polling.
159
- await vi.advanceTimersByTimeAsync(1100)
160
+ await vi.advanceTimersByTimeAsync(1200)
160
161
  expect(pollLatest).toHaveBeenCalledTimes(1)
161
162
 
162
163
  // A live mux frame proves SSE delivers again -> fallback stops.
@@ -169,4 +170,81 @@ describe('MuxClient polling fallback', () => {
169
170
  expect(live[0]).toMatchObject({ type: 'session/subscribed', sessionId: 's1' })
170
171
  client.stop()
171
172
  })
173
+
174
+ it('drives the whole lifecycle on a single scheduler tick (one interval)', async () => {
175
+ const { factory } = makeSources()
176
+ const setIntervalSpy = vi.spyOn(globalThis, 'setInterval')
177
+ try {
178
+ const pages = [pageOf([0]), pageOf([0, 1])]
179
+ const pollLatest = vi.fn(async (_sessionId: string) => pages.shift() ?? pageOf([]))
180
+ const client = new MuxClient('/m/api/events.mux', {
181
+ sourceFactory: factory,
182
+ pollLatest,
183
+ stallThresholdMs: 1500,
184
+ pollIntervalMs: 2000,
185
+ })
186
+ client.start()
187
+ client.observe('s1')
188
+
189
+ // Exactly one interval is ever created: the single tick scheduler.
190
+ expect(setIntervalSpy).toHaveBeenCalledTimes(1)
191
+
192
+ // The tick fires below the stall threshold without polling.
193
+ await vi.advanceTimersByTimeAsync(1000)
194
+ expect(pollLatest).not.toHaveBeenCalled()
195
+
196
+ // The same interval arms the fallback once silence passes the threshold
197
+ // (tick at 2000 crosses 1500) and runs the first poll immediately.
198
+ await vi.advanceTimersByTimeAsync(1100) // 2100ms total
199
+ expect(pollLatest).toHaveBeenCalledTimes(1)
200
+ expect(setIntervalSpy).toHaveBeenCalledTimes(1) // still one timer
201
+
202
+ // Subsequent polls ride the same tick at the poll cadence (2000 ms).
203
+ await vi.advanceTimersByTimeAsync(2000)
204
+ expect(pollLatest).toHaveBeenCalledTimes(2)
205
+ client.stop()
206
+ } finally {
207
+ setIntervalSpy.mockRestore()
208
+ }
209
+ })
210
+
211
+ it('paces polls on the tick only after the stall phase ends', async () => {
212
+ const { factory } = makeSources()
213
+ const pages = [pageOf([0]), pageOf([0, 1]), pageOf([0, 1, 2]), pageOf([0, 1, 2, 3])]
214
+ const pollLatest = vi.fn(async (_sessionId: string) => pages.shift() ?? pageOf([]))
215
+ const client = new MuxClient('/m/api/events.mux', {
216
+ sourceFactory: factory,
217
+ pollLatest,
218
+ stallThresholdMs: 800,
219
+ pollIntervalMs: 400,
220
+ })
221
+ client.start()
222
+ client.observe('s1')
223
+
224
+ // At 1200 ms the stall threshold is crossed on this single 400 ms tick.
225
+ await vi.advanceTimersByTimeAsync(1200)
226
+ expect(pollLatest).toHaveBeenCalledTimes(1)
227
+
228
+ // Each subsequent 400 ms tick is a poll, matching the poll cadence.
229
+ await vi.advanceTimersByTimeAsync(400)
230
+ await vi.advanceTimersByTimeAsync(400)
231
+ await vi.advanceTimersByTimeAsync(400)
232
+ expect(pollLatest).toHaveBeenCalledTimes(4)
233
+ client.stop()
234
+ })
235
+
236
+ it('observe() already in the stall window starts the single-tick poller immediately', async () => {
237
+ const { factory } = makeSources()
238
+ const pollLatest = vi.fn(async (_sessionId: string) => pageOf([0]))
239
+ const client = new MuxClient('/m/api/events.mux', baseOptions(pollLatest, factory))
240
+ client.start()
241
+ // Advance well past the stall threshold while nothing is observed.
242
+ await vi.advanceTimersByTimeAsync(2000)
243
+ expect(pollLatest).not.toHaveBeenCalled()
244
+
245
+ // Observing a session now is already in the stall window: poll right away.
246
+ client.observe('s1')
247
+ expect(pollLatest).toHaveBeenCalledTimes(1)
248
+ client.stop()
249
+ })
172
250
  })
package/src/mobile/mux.ts CHANGED
@@ -66,6 +66,12 @@ type SessionEventFrame = Extract<MuxFrame, { type: 'session/event' }>
66
66
 
67
67
  const DEFAULT_POLL_INTERVAL_MS = 3000
68
68
  const DEFAULT_STALL_THRESHOLD_MS = 12000
69
+ /**
70
+ * Stall-check granularity: the single scheduler tick runs at least this
71
+ * often so fallback arms within a second of the stall threshold passing,
72
+ * while the poll cadence itself stays {@link MuxClientOptions.pollIntervalMs}.
73
+ */
74
+ const STALL_CHECK_MS = 1000
69
75
  /** Poll window: enough recent events to cover a few seconds of agent output. */
70
76
  const DEFAULT_POLL_PAGE_SIZE = 50
71
77
 
@@ -98,9 +104,11 @@ export class MuxClient {
98
104
  private sseAlive = false
99
105
  /** Per-session highest event seq already emitted, for poll dedup. */
100
106
  private readonly pollWatermark = new Map<string, number>()
101
- private stallTimer: ReturnType<typeof setInterval> | undefined
102
- private pollTimer: ReturnType<typeof setInterval> | undefined
107
+ /** Single scheduler tick: both the stall check and the poll cadence ride this one interval. */
108
+ private tickTimer: ReturnType<typeof setInterval> | undefined
103
109
  private polling = false
110
+ /** Epoch ms of the next due poll while polling (kept on the same tick timer). */
111
+ private nextPollAt = 0
104
112
 
105
113
  /**
106
114
  * @param url - the mobile events endpoint (browser-relative).
@@ -120,16 +128,17 @@ export class MuxClient {
120
128
  this.stopped = false
121
129
  this.lastDataAt = this.now()
122
130
  if (this.source === undefined) this.connect()
123
- this.startStallChecker()
131
+ this.startTick()
124
132
  }
125
133
 
126
134
  /** Close for good. */
127
135
  stop(): void {
128
136
  this.stopped = true
129
- this.stopStallChecker()
137
+ this.stopTick()
130
138
  this.stopPolling()
131
139
  this.closeSource()
132
140
  this.observeSessionId = undefined
141
+ this.nextPollAt = 0
133
142
  }
134
143
 
135
144
  /** Subscribe to validated frames; returns an unsubscribe function. */
@@ -176,40 +185,52 @@ export class MuxClient {
176
185
  }
177
186
  }
178
187
 
179
- private startStallChecker(): void {
180
- this.stopStallChecker()
181
- this.stallTimer = setInterval(() => {
182
- if (this.stopped) return
183
- if (this.observeSessionId === undefined) return
184
- if (this.polling) return
185
- // A live SSE channel only goes silent while the agent idles; never
186
- // poll against it. Fallback arms again only via onerror or a stream
187
- // that has never delivered.
188
- if (this.sseAlive) return
189
- if ((this.now() - this.lastDataAt) > this.stallThresholdMs) this.startPolling()
190
- }, 1000)
188
+ /**
189
+ * The single scheduler tick is the only interval this client owns. One
190
+ * timer (at the finer of the stall-check and poll cadences) both arms the
191
+ * polling fallback once the stall threshold passes and drives each poll at
192
+ * {@link MuxClientOptions.pollIntervalMs} — one timer instead of two.
193
+ */
194
+ private startTick(): void {
195
+ if (this.tickTimer !== undefined) return
196
+ const cadence = Math.min(this.pollIntervalMs, STALL_CHECK_MS)
197
+ this.tickTimer = setInterval(() => { this.tick() }, cadence)
198
+ }
199
+
200
+ private stopTick(): void {
201
+ if (this.tickTimer !== undefined) {
202
+ clearInterval(this.tickTimer)
203
+ this.tickTimer = undefined
204
+ }
191
205
  }
192
206
 
193
- private stopStallChecker(): void {
194
- if (this.stallTimer !== undefined) {
195
- clearInterval(this.stallTimer)
196
- this.stallTimer = undefined
207
+ private tick(): void {
208
+ if (this.stopped) return
209
+ if (this.observeSessionId === undefined) return
210
+ if (this.polling) {
211
+ // The stall phase has ended; the same tick now paces the polls.
212
+ if (this.now() >= this.nextPollAt) {
213
+ this.nextPollAt = this.now() + this.pollIntervalMs
214
+ void this.pollTick()
215
+ }
216
+ return
197
217
  }
218
+ // A live SSE channel only goes silent while the agent idles; never poll
219
+ // against it. Fallback arms again only via onerror or a stream that has
220
+ // never delivered.
221
+ if (this.sseAlive) return
222
+ if ((this.now() - this.lastDataAt) > this.stallThresholdMs) this.startPolling()
198
223
  }
199
224
 
200
225
  private startPolling(): void {
201
226
  if (this.polling || this.stopped) return
202
227
  this.polling = true
228
+ this.nextPollAt = this.now() + this.pollIntervalMs
203
229
  void this.pollTick()
204
- this.pollTimer = setInterval(() => { void this.pollTick() }, this.pollIntervalMs)
205
230
  }
206
231
 
207
232
  private stopPolling(): void {
208
233
  this.polling = false
209
- if (this.pollTimer !== undefined) {
210
- clearInterval(this.pollTimer)
211
- this.pollTimer = undefined
212
- }
213
234
  }
214
235
 
215
236
  /**