mobux 0.40.2

A touch-friendly tmux web UI for unhinged people who run terminal sessions from their phone while walking the dog
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
// Renderer conformance suite (issue #207, D10).
//
// One spec exercises the explicit renderer interface (R1–R11, R15–R16) and
// runs against BOTH adapters via the xterm/sterk Playwright projects
// (playwright.config.cjs) — a renderer is conformant when this suite is green
// on its project. Every probe goes through the engine's test surface
// (`window.__mobuxView.test.*`), never a renderer global, so the assertions
// are renderer-agnostic: the same code must pass on xterm and on sterk.
//
// Scope note: R1–R16 are asserted here, both adapters. R12–R14 (selection,
// links, bell) landed in stage 3 with sterk pinned to a published release, so
// the sterk-side gaps the earlier stages worked around (public alt-screen
// state, native selection, a link module, a bell event) are now real API and
// held to the same contract as xterm. See the PR description.

const { test, expect } = require("./fixtures.cjs");
const { execSync } = require("child_process");

const BASE = process.env.MOBUX_URL || "https://localhost:5151";
const USER = process.env.MOBUX_USER || "";
const PASS = process.env.MOBUX_PASS || "";
const AUTH =
  USER && PASS
    ? "Basic " + Buffer.from(`${USER}:${PASS}`).toString("base64")
    : null;
const SESSION = process.env.MOBUX_TEST_SESSION || "mobux-conformance";

const { createTmuxRunner } = require("./lib/tmux.cjs");
const SANDBOX_HOME = process.env.MOBUX_TEST_HOME || "/tmp/mobux-smoke/home";
const SHELL_ENV = `-e HISTFILE=/dev/null -e HOME=${SANDBOX_HOME}`;
const tmux = createTmuxRunner("mobux-test");

test.use({
  ...(AUTH ? { extraHTTPHeaders: { Authorization: AUTH } } : {}),
});

test.beforeAll(() => {
  try {
    tmux(`kill-session -t ${SESSION}`);
  } catch (_) {}
  tmux(`new-session -d -s ${SESSION} ${SHELL_ENV} "bash --norc --noprofile"`);
  tmux(`send-keys -t ${SESSION} "PS1='\\$ '" Enter`);
  tmux(`send-keys -t ${SESSION} "clear" Enter`);
  execSync("sleep 0.3");
});

test.afterAll(() => {
  try {
    tmux(`kill-session -t ${SESSION}`);
  } catch (_) {}
});

// Boot the terminal page and wait until the engine is live and its socket is
// open. Returns once `window.__mobuxView.test` is usable.
async function boot(page) {
  await page.goto(`${BASE}/app#/s/${SESSION}`);
  await page.waitForFunction(() => typeof window.__mobuxView !== "undefined", {
    timeout: 8000,
  });
  await page.waitForFunction(
    () => window.__mobuxView?.test?.wsReady?.() === true,
    { timeout: 15000 },
  );
}

// Scan every display row for a marker string. Renderer-agnostic — reads the
// R7 row text through the engine.
async function bufferHasText(page, marker) {
  return page.evaluate((m) => {
    const len = window.__mobuxView.test.bufferLength();
    for (let y = 0; y < len; y++) {
      const t = window.__mobuxView.test.lineText(y);
      if (t && t.includes(m)) return true;
    }
    return false;
  }, marker);
}

// R1 — create / dispose. Mount attaches the engine test surface; a same-
// document navigation away disposes it (the island unmount path), tearing the
// surface down.
test("R1: create mounts the engine, navigation disposes it", async ({
  page,
}) => {
  await boot(page);
  expect(await page.evaluate(() => !!window.__mobuxView)).toBe(true);

  await page.goto(`${BASE}/app#/`);
  await page.waitForFunction(() => window.__mobuxView === undefined, {
    timeout: 8000,
  });
  expect(await page.evaluate(() => window.__mobuxView === undefined)).toBe(
    true,
  );
});

// R2 — write(data) resolves after the buffer reflects the data. (The stronger
// slow-CI flush guarantee for sterk is the upstream fix, stage 3; here both
// renderers must have the written text readable once the promise resolves.)
test("R2: write resolves after the buffer reflects the data", async ({
  page,
}) => {
  await boot(page);
  await page.evaluate(() =>
    window.__mobuxView.test.inject("CONFORMANCE_R2_MARKER\n"),
  );
  expect(await bufferHasText(page, "CONFORMANCE_R2_MARKER")).toBe(true);
});

// R3 — measure() is the renderer's authoritative fit; R4 — cols/rows report
// the current grid. Both must be positive and self-consistent.
test("R3/R4: measure and current grid are positive", async ({ page }) => {
  await boot(page);
  const dims = await page.evaluate(() => ({
    m: window.__mobuxView.test.measure(),
    cell: window.__mobuxView.test.cellMetrics(),
    cols: window.__mobuxView.test.cols(),
    rows: window.__mobuxView.test.rows(),
  }));
  expect(dims.m.cols).toBeGreaterThan(0);
  expect(dims.m.rows).toBeGreaterThan(0);
  expect(dims.m.cellWidth).toBeGreaterThan(0);
  expect(dims.m.cellHeight).toBeGreaterThan(0);
  expect(dims.cell.width).toBeGreaterThan(0);
  expect(dims.cell.height).toBeGreaterThan(0);
  expect(dims.cols).toBeGreaterThan(0);
  expect(dims.rows).toBeGreaterThan(0);
});

// R5 — onInput carries keystrokes to the PTY. Type into the renderer's native
// input surface and confirm the shell echoes it back into the buffer.
test("R5: keystrokes typed into the renderer reach the PTY", async ({
  page,
}) => {
  await boot(page);
  await page.evaluate(() => {
    window.__mobuxView.test.setNativeInputEnabled(true);
    window.__mobuxView.test.focus();
  });
  await page.keyboard.type("echo R5_CONFORMANCE_OK\r");
  await page.waitForFunction(
    () => {
      const len = window.__mobuxView.test.bufferLength();
      for (let y = 0; y < len; y++) {
        const t = window.__mobuxView.test.lineText(y);
        // The typed command line contains the literal marker; the echoed
        // output line contains it too. Either proves onInput reached the PTY.
        if (t && t.includes("R5_CONFORMANCE_OK")) return true;
      }
      return false;
    },
    { timeout: 15000 },
  );
});

// R6 — scroll: scrollLines moves the viewport off the bottom, scrollToBottom
// pins it back. Viewport position is read through the buffer.
test("R6: scrollLines and scrollToBottom move the viewport", async ({
  page,
}) => {
  await boot(page);
  await page.evaluate(() => window.__mobuxView.test.injectLines(300, "r6seed"));
  await page.waitForFunction(
    () => window.__mobuxView.test.bufferLength() > 200,
    { timeout: 10000 },
  );
  await page.evaluate(() => window.__mobuxView.test.scrollToBottom());
  const bottom = await page.evaluate(() => window.__mobuxView.test.viewportY());
  await page.evaluate(() => window.__mobuxView.test.scrollLines(-10));
  const scrolled = await page.evaluate(() =>
    window.__mobuxView.test.viewportY(),
  );
  expect(scrolled).toBeLessThan(bottom);
  await page.evaluate(() => window.__mobuxView.test.scrollToBottom());
  const back = await page.evaluate(() => window.__mobuxView.test.viewportY());
  expect(back).toBe(bottom);
});

// R7 — the display reports its scroll position and each row's text.
test("R7: viewport and row text read the display", async ({ page }) => {
  await boot(page);
  await page.evaluate(() =>
    window.__mobuxView.test.inject("R7_ROW_TEXT_XYZ\n"),
  );
  const probe = await page.evaluate(() => ({
    length: window.__mobuxView.test.bufferLength(),
    top: window.__mobuxView.test.viewportY(),
    rows: window.__mobuxView.test.rows(),
  }));
  expect(probe.length).toBeGreaterThanOrEqual(probe.rows);
  expect(probe.top).toBeGreaterThanOrEqual(0);
  expect(await bufferHasText(page, "R7_ROW_TEXT_XYZ")).toBe(true);
});

// The reader's document is read from the engine buffer: a written line
// reaches it with its styled runs.
test("document: a written line reaches the document with its attrs", async ({
  page,
}) => {
  await boot(page);
  await page.evaluate(() =>
    window.__mobuxView.test.inject("plain \x1b[1mDOC_BOLD_XYZ\x1b[0m\n"),
  );
  const line = await page.evaluate(() =>
    window.__mobuxView.test
      .documentSnapshot()
      .lines.find((l) => l.text.includes("DOC_BOLD_XYZ")),
  );
  expect(line).toBeDefined();
  expect(line.text).toBe("plain DOC_BOLD_XYZ");
  const bold = line.runs.find((r) => r.text === "DOC_BOLD_XYZ");
  expect(bold.attrs.bold).toBe(true);
  expect(line.runs[0].attrs.bold).toBe(false);
});

// onBufferChanged fires after the buffer parses a write. Subscribe, then
// write in the same pass so the subscription is guaranteed live before it.
test("buffer: onBufferChanged fires after a write", async ({ page }) => {
  await boot(page);
  const observed = await page.evaluate(
    () =>
      new Promise((resolve) => {
        let done = false;
        const settle = (v) => {
          if (!done) {
            done = true;
            resolve(v);
          }
        };
        window.__mobuxView.test.awaitBufferChange().then(() => settle(true));
        setTimeout(() => settle(false), 5000);
        window.__mobuxView.test.writeData("R8_CHANGE\r\n");
      }),
  );
  expect(observed).toBe(true);
});

// R9 — alt-screen state follows the stream: after the injected alt-screen
// exit prefix the engine reports the normal screen.
test("R9: reports the normal screen after an alternate-screen exit", async ({
  page,
}) => {
  await boot(page);
  await page.evaluate(() =>
    window.__mobuxView.test.inject("R9_NORMAL_SCREEN\n"),
  );
  expect(await page.evaluate(() => window.__mobuxView.test.isAlternate())).toBe(
    false,
  );
});

// R16 — the alternate screen lives in the engine's buffer. A CSI `?…h` that
// packs it with another mode switches it and applies the other mode; what is
// drawn on it never reaches the display's scrollback, and leaving it restores
// the normal screen.
test("R16: the alternate screen switches in the buffer and leaves no scrollback", async ({
  page,
}) => {
  await boot(page);
  // Close the WS so tmux can't re-assert modes or clobber the injected content.
  await page.evaluate(() => window.__mobuxView.test.inject(""));

  await page.evaluate(() =>
    window.__mobuxView.test.writeData("\x1b[?1049;25h"),
  );
  expect(await page.evaluate(() => window.__mobuxView.test.isAlternate())).toBe(
    true,
  );

  // Mouse tracking (1002) packed with save-cursor (1048): 1048 must take
  // effect. Save the cursor after a marker, move away, restore, then print —
  // the trailing char lands back at the saved column iff 1048 applied.
  await page.evaluate(() =>
    window.__mobuxView.test.writeData(
      "\x1b[2J\x1b[HR16SAVE\x1b[?1002;1048h\r\nR16OTHR\x1b[?1048lZ",
    ),
  );
  expect(await bufferHasText(page, "R16SAVEZ")).toBe(true);

  let alt = "";
  for (let i = 0; i < 200; i++) alt += `R16_ALT_ONLY ${i}\r\n`;
  await page.evaluate((s) => window.__mobuxView.test.writeData(s), alt);
  await page.evaluate(() => window.__mobuxView.test.writeData("\x1b[?1049l"));
  expect(await page.evaluate(() => window.__mobuxView.test.isAlternate())).toBe(
    false,
  );
  expect(await bufferHasText(page, "R16_ALT_ONLY")).toBe(false);
  expect(await bufferHasText(page, "R16SAVE")).toBe(false);
});

// R10 — the engine registers an OSC 133 handler through the renderer; an OSC
// 133 marker in the stream is detected and recorded.
test("R10: OSC 133 markers are detected via registerOscHandler", async ({
  page,
}) => {
  await boot(page);
  expect(await page.evaluate(() => window.__mobuxView.test.oscDetected())).toBe(
    false,
  );
  await page.evaluate(() =>
    window.__mobuxView.test.writeData("\x1b]133;A\x07prompt$ \r\n"),
  );
  await page.waitForFunction(
    () => window.__mobuxView.test.oscDetected() === true,
    { timeout: 5000 },
  );
  expect(
    await page.evaluate(() => window.__mobuxView.test.oscMarkerCount()),
  ).toBeGreaterThan(0);
});

// R11 — font size round-trips through the interface. (setTheme's renderer-
// specific palette application is covered by the theme-picker tests.)
test("R11: setFontSize / getFontSize round-trip", async ({ page }) => {
  await boot(page);
  const result = await page.evaluate(() => {
    const before = window.__mobuxView.test.getFontSize();
    window.__mobuxView.test.setFontSize(before + 3);
    const after = window.__mobuxView.test.getFontSize();
    window.__mobuxView.test.setFontSize(before);
    return { before, after, restored: window.__mobuxView.test.getFontSize() };
  });
  expect(result.after).toBe(result.before + 3);
  expect(result.restored).toBe(result.before);
});

// R15 — the renderer owns its input surface: focus() and
// setNativeInputEnabled(bool) are callable and idempotent without throwing.
test("R15: focus and setNativeInputEnabled are callable", async ({ page }) => {
  await boot(page);
  const ok = await page.evaluate(() => {
    window.__mobuxView.test.setNativeInputEnabled(false);
    window.__mobuxView.test.setNativeInputEnabled(true);
    window.__mobuxView.test.setNativeInputEnabled(false);
    window.__mobuxView.test.focus();
    return true;
  });
  expect(ok).toBe(true);
});

// R12 — selection: selectAll produces a readable, non-empty selection that
// fires onSelectionChange; clearSelection empties it. Sterk implements it with
// native DOM selection, xterm with its selection API — same contract.
test("R12: selectAll, getSelection, onSelectionChange, clearSelection", async ({
  page,
}) => {
  await boot(page);
  await page.evaluate(() =>
    window.__mobuxView.test.inject("R12_SELECTION_MARKER\n"),
  );
  await page.waitForFunction(() => window.__mobuxView.test.bufferLength() > 0, {
    timeout: 8000,
  });

  // Subscribe BEFORE selecting so the change event can't be missed.
  const changePromise = page.evaluate(
    () =>
      new Promise((resolve) => {
        let done = false;
        const settle = (v) => {
          if (!done) {
            done = true;
            resolve(v);
          }
        };
        window.__mobuxView.test.awaitSelectionChange().then(() => settle(true));
        setTimeout(() => settle(false), 5000);
      }),
  );
  await page.waitForTimeout(50);
  await page.evaluate(() => window.__mobuxView.test.selectAll());
  expect(await changePromise).toBe(true);

  expect(
    await page.evaluate(() => window.__mobuxView.test.hasSelection()),
  ).toBe(true);
  const selected = await page.evaluate(() =>
    window.__mobuxView.test.getSelection(),
  );
  expect(selected).toContain("R12_SELECTION_MARKER");

  await page.evaluate(() => window.__mobuxView.test.clearSelection());
  expect(
    await page.evaluate(() => window.__mobuxView.test.hasSelection()),
  ).toBe(false);
});

// R13 — links: a URL in the buffer, when activated, is reported through
// onLink. Both adapters detect the URL themselves (xterm: WebLinks addon;
// sterk: its link module) and fan the activation out to the UI.
test("R13: URL activation is reported through onLink", async ({ page }) => {
  await boot(page);
  const URL = "https://example.com/r13-conformance";

  // The coarse-pointer touch overlay and the loading splash both sit above the
  // terminal and would eat the click; drop them so the renderer's own link
  // layer sees the mouse (the desktop path). inject() closes the WS, so the
  // splash's first-data dismissal never fires on its own. The mobile
  // tap-to-open affordance is separate.
  await page.evaluate(() => {
    const o = document.getElementById("touchOverlay");
    if (o) o.style.pointerEvents = "none";
    const q = document.getElementById("loadquote");
    if (q) q.remove();
  });

  // `\x1b[K` erases to end of line after the URL so a residual char left on the
  // row by earlier output can't extend the detected link (the URL regex is
  // greedy up to the next whitespace).
  await page.evaluate(
    (u) => window.__mobuxView.test.inject(`open ${u}\x1b[K\n`),
    URL,
  );
  await page.evaluate(() => window.__mobuxView.test.scrollToBottom());
  await page.waitForFunction(
    (u) => {
      const len = window.__mobuxView.test.bufferLength();
      for (let y = 0; y < len; y++) {
        const t = window.__mobuxView.test.lineText(y);
        if (t && t.includes(u)) return true;
      }
      return false;
    },
    URL,
    { timeout: 10000 },
  );

  // Centre of the URL text, in viewport pixels.
  const point = await page.evaluate((u) => {
    const len = window.__mobuxView.test.bufferLength();
    const vy = window.__mobuxView.test.viewportY();
    const rows = window.__mobuxView.test.rows();
    const cell = window.__mobuxView.test.cellMetrics();
    const rect = document.getElementById("terminal").getBoundingClientRect();
    for (let y = vy; y < Math.min(len, vy + rows); y++) {
      const t = window.__mobuxView.test.lineText(y);
      const idx = t ? t.indexOf(u) : -1;
      if (idx >= 0) {
        const col = idx + Math.floor(u.length / 2);
        return {
          x: rect.left + (col + 0.5) * cell.width,
          y: rect.top + (y - vy + 0.5) * cell.height,
        };
      }
    }
    return null;
  }, URL);
  expect(point).not.toBeNull();

  const linkPromise = page.evaluate(
    () =>
      new Promise((resolve) => {
        let done = false;
        const settle = (v) => {
          if (!done) {
            done = true;
            resolve(v);
          }
        };
        window.__mobuxView.test.awaitLink().then((uri) => settle(uri));
        setTimeout(() => settle(null), 6000);
      }),
  );
  await page.waitForTimeout(100);
  await page.mouse.move(point.x, point.y);
  await page.mouse.move(point.x, point.y);
  await page.mouse.click(point.x, point.y);
  expect(await linkPromise).toBe(URL);
});

// R13 (boundary) — the detected link excludes trailing punctuation, matching
// xterm's WebLinks addon (its regex forbids a URL ending in punctuation). A URL
// abutting a sentence-ending period links without the period on BOTH adapters.
test("R13: trailing punctuation is not part of the link", async ({ page }) => {
  await boot(page);
  const URL = "https://example.com/r13-boundary";

  await page.evaluate(() => {
    const o = document.getElementById("touchOverlay");
    if (o) o.style.pointerEvents = "none";
    const q = document.getElementById("loadquote");
    if (q) q.remove();
  });

  // The URL is followed immediately by a period. The detected link must stop
  // before it. `\x1b[K` erases any residual tail so it can't extend the match.
  await page.evaluate(
    (u) => window.__mobuxView.test.inject(`see ${u}.\x1b[K\n`),
    URL,
  );
  await page.evaluate(() => window.__mobuxView.test.scrollToBottom());
  await page.waitForFunction(
    (u) => {
      const len = window.__mobuxView.test.bufferLength();
      for (let y = 0; y < len; y++) {
        const t = window.__mobuxView.test.lineText(y);
        if (t && t.includes(`${u}.`)) return true;
      }
      return false;
    },
    URL,
    { timeout: 10000 },
  );

  // Click the centre of the URL body (excluding the trailing period).
  const point = await page.evaluate((u) => {
    const len = window.__mobuxView.test.bufferLength();
    const vy = window.__mobuxView.test.viewportY();
    const rows = window.__mobuxView.test.rows();
    const cell = window.__mobuxView.test.cellMetrics();
    const rect = document.getElementById("terminal").getBoundingClientRect();
    for (let y = vy; y < Math.min(len, vy + rows); y++) {
      const t = window.__mobuxView.test.lineText(y);
      const idx = t ? t.indexOf(u) : -1;
      if (idx >= 0) {
        const col = idx + Math.floor(u.length / 2);
        return {
          x: rect.left + (col + 0.5) * cell.width,
          y: rect.top + (y - vy + 0.5) * cell.height,
        };
      }
    }
    return null;
  }, URL);
  expect(point).not.toBeNull();

  const linkPromise = page.evaluate(
    () =>
      new Promise((resolve) => {
        let done = false;
        const settle = (v) => {
          if (!done) {
            done = true;
            resolve(v);
          }
        };
        window.__mobuxView.test.awaitLink().then((uri) => settle(uri));
        setTimeout(() => settle(null), 6000);
      }),
  );
  await page.waitForTimeout(100);
  await page.mouse.move(point.x, point.y);
  await page.mouse.move(point.x, point.y);
  await page.mouse.click(point.x, point.y);
  // No trailing period — the reported URI is the bare URL on both adapters.
  expect(await linkPromise).toBe(URL);
});

// R14 — bell: a terminal BEL (0x07) is reported through onBell.
test("R14: terminal BEL is reported through onBell", async ({ page }) => {
  await boot(page);
  const observed = await page.evaluate(
    () =>
      new Promise((resolve) => {
        let done = false;
        const settle = (v) => {
          if (!done) {
            done = true;
            resolve(v);
          }
        };
        window.__mobuxView.test.awaitBell().then(() => settle(true));
        setTimeout(() => settle(false), 5000);
        window.__mobuxView.test.writeData("\x07");
      }),
  );
  expect(observed).toBe(true);
});

// Regression: a raw client-side BEL must never trigger the chime, regardless
// of notification prefs — only the server-gated push path may (src/main.rs
// only fires the push when prefs.bell is true; see chime.js's service-worker
// listener). The renderer still reports the BEL through onBell (R14, above)
// — the UI simply must not react to it by chiming.
test("bell: a raw client-side BEL never triggers the chime", async ({
  page,
}) => {
  await boot(page);
  await page.waitForFunction(() => typeof window.__mobuxChime === "function", {
    timeout: 8000,
  });
  const chimed = await page.evaluate(
    () =>
      new Promise((resolve) => {
        let called = false;
        const original = window.__mobuxChime;
        window.__mobuxChime = (...args) => {
          called = true;
          return original(...args);
        };
        window.__mobuxView.test.awaitBell().then(() => {
          setTimeout(() => resolve(called), 200);
        });
        window.__mobuxView.test.writeData("\x07");
      }),
  );
  expect(chimed).toBe(false);
});

// Device queries are answered once, by the engine buffer: the display only
// ever receives the redraw writer's output, so its own replies never reach
// tmux. tmux queries the client when it attaches; those replies settle first.
test("device queries: a DA query gets exactly one reply", async ({ page }) => {
  await page.addInitScript(() => {
    window.__sent = [];
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function (data) {
      window.__sent.push({ data, at: Date.now() });
      return send.call(this, data);
    };
  });
  const isDA = (d) => typeof d === "string" && /^\x1b\[[?>][\d;]*c$/.test(d);
  const daReplies = () =>
    page.evaluate(
      (src) =>
        window.__sent.filter(({ data }) =>
          new Function(`return (${src})`)()(data),
        ),
      isDA.toString(),
    );
  await boot(page);
  const booted = Date.now();
  await expect
    .poll(
      async () => {
        const last = (await daReplies()).at(-1);
        return Date.now() - (last ? last.at : booted);
      },
      { timeout: 10000, intervals: [250] },
    )
    .toBeGreaterThan(1000);
  await page.evaluate(async () => {
    window.__sent.length = 0;
    await window.__mobuxView.test.writeData("\x1b[c");
  });
  await page.waitForTimeout(500);
  const replies = (await daReplies()).map(({ data }) => data);
  expect(replies).toHaveLength(1);
  expect(replies[0]).toMatch(/^\x1b\[\?[\d;]*c$/);
});