@aiwayds/dsh-opentui 0.27.1 → 0.28.0

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.
@@ -1,1122 +0,0 @@
1
- #!/usr/bin/env node
2
- // Client-mode two-process E2E gate (P6) — drives the REAL topology end to
3
- // end: `./dsh-opentui --client` inside tmux 120x34 panes, the resident
4
- // `dsh --profile opentui` host it spawns, and real model turns.
5
- //
6
- // Scenarios:
7
- // a. Boot + turn — status bar renders (provider/model from the profile
8
- // route), `say ok` answers, the 🧠 context segment increases.
9
- // b. Multi-TUI attach — a second client in a second tmux session JOINS
10
- // the same host (same pid via the single-instance lockfile; exactly
11
- // one host process); both quit → the host exits after the idle grace
12
- // (the detached idle-reaper path).
13
- // c. Crash-recovery adoption — kill -9 client 1's bun process → the host
14
- // survives → client 2 boots and ADOPTS the existing host (lockfile
15
- // pid unchanged, no respawn) → clean quit → full teardown.
16
- // d. /reload — from a running client, the slash command drives the
17
- // RemoteHostSession.restartSamePortHost restart path → the host
18
- // restarts on the SAME port → the carrier reconnects and the wave-2
19
- // re-attach resumes → transcript rows survive (no double-painted
20
- // rows).
21
- // e. Host death recovery — kill -9 the HOST while a client is connected
22
- // mid-turn → the client surfaces the "reconnecting…" state → the
23
- // next ensureHost (a fresh client boot) respawns → that client
24
- // continues.
25
- // f. THE ORIGINAL SCENARIO (acceptance) — `用一个markdown表格列出两种语言
26
- // 和创建年份,再写一句总结` → a real bordered table (│ rows + └─
27
- // bottom) + a summary line + the bottom anchor (powerline footer
28
- // still painted). Capture → /tmp/p6-mdtable.txt, PNG →
29
- // /tmp/p6-mdtable.png via /tmp/tmux2png.py (pyte + Pillow).
30
- // g. Workspace config effect — a scratch workspace with
31
- // ./.dsh/config.yml (theme: dracula + model preference) → the boot
32
- // in that cwd applies the theme (capture -e truecolor SGRs: the
33
- // mocha user-row color gone, the dracula accent present) and the
34
- // session carries the workspace cwd (welcome banner path).
35
- // h. /login provider directory — bare `/login` opens the provider
36
- // picker through the aggregateTurnContext proxy (settingsSeam →
37
- // #settingsClient — the accessor class the 3dec270 fix repaired)
38
- // → several known provider names render → esc closes cleanly →
39
- // no TypeError/crash markers in the pane scrollback or the exit.
40
- // No credential writes: opening the picker touches nothing
41
- // (scratch DSH_HOME not required; the per-scenario workspace +
42
- // host-reap isolation still applies). Non-turn: runs under key rot.
43
- //
44
- // Host-death UX (scenario e — the chosen design, ADR-0005 v1):
45
- // A host killed mid-session leaves the carrier retrying a dead port.
46
- // The client surfaces this as the "reconnecting…" label swap (the
47
- // wave-1 marker) for as long as the turn is awaited. v1 does NOT
48
- // respawn into the SAME client process: the carrier is pinned to the
49
- // authority it was built with (the P3 ShellHostDeps swap is the seam
50
- // that could re-point it), and after a crash the lifecycle lockfile is
51
- // already cleared by the client's own death watcher, so the /reload
52
- // same-port machinery has nothing to restart. Recovery is the
53
- // terminal-standard quit-and-relaunch: the NEXT client's ensureHost
54
- // finds no/stale lock and respawns a fresh host; the session store is
55
- // host-global, so the relaunched TUI continues with the full
56
- // transcript. This scenario asserts exactly that chain.
57
- //
58
- // Model-route reality (provider keys rot): every real-turn scenario uses
59
- // the wave-3 workingRoute discovery pattern first — boot the host, probe
60
- // `session/modelCatalog`, `selectModel` and turn until a route actually
61
- // answers. The winning route is exported to the TUI clients through the
62
- // documented env override (DSH_OPENTUI_MODEL=provider/model, the
63
- // bucket-(d) merge's top layer). When NO route answers, the gate still
64
- // runs every non-turn assertion and marks the turn parts BLOCKED loudly
65
- // instead of hacking.
66
- //
67
- // Skips (exit 0) when the environment cannot run it: no global dsh, no
68
- // tmux, no bun, or the opentui profile missing — CI runs skip; a
69
- // configured dev machine runs the full gate for real.
70
- //
71
- // Drive mechanics (e2e-live.mjs conventions): typing is fed ONE CHAR PER
72
- // tmux send-keys with a ~60ms inter-key gap (burst writes drop keys in
73
- // OpenTUI's input parser); assertions are presence-over-time on captures.
74
- //
75
- // Known P1 watches (oldfox review — if seen, record as
76
- // "reproduced oldfox-P1#N" and move on; fixes are tracked separately):
77
- // P1#1 transcript rows double-painted after a reconnect replay (no seq
78
- // dedupe baseline) — watched in scenario d;
79
- // P1#2 /reload restart does not rewrite the lockfile → unlocked host
80
- // (next ensureHost would boot a duplicate) — watched in scenario d;
81
- // P1#3 concurrent dual-TUI cold start spawns two hosts — watched in
82
- // scenarios b/c (sequential boots here make it unlikely; honest
83
- // negative is information too);
84
- // P1#4 events-source closing a CONNECTING-state socket → unhandled
85
- // error — watched in scenario e (client process must survive).
86
-
87
- import { spawn, spawnSync } from 'node:child_process'
88
- import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
89
- import { homedir, tmpdir } from 'node:os'
90
- import { dirname, join, resolve } from 'node:path'
91
- import { fileURLToPath } from 'node:url'
92
- import { connect as netConnect } from 'node:net'
93
-
94
- const REPO = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', '..')
95
- const LAUNCHER = join(REPO, 'dsh-opentui')
96
- const PROFILE = 'opentui'
97
- const DSH_HOME = process.env.DSH_HOME || join(homedir(), '.dsh')
98
- const LOCK_PATH = join(DSH_HOME, `opentui-host.${PROFILE}.json`)
99
- const GEOMETRY = { x: 120, y: 34 }
100
- const TYPE_GAP_MS = 60
101
-
102
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
103
-
104
- // ---------------------------------------------------------------------------
105
- // Preflight + skip contract.
106
- // ---------------------------------------------------------------------------
107
-
108
- const preflight = () => {
109
- const need = (cmd) => spawnSync('which', [cmd], { encoding: 'utf8' })
110
- for (const [cmd, why] of [['dsh', 'no global dsh on PATH'], ['tmux', 'no tmux on PATH'], ['bun', 'no bun on PATH']]) {
111
- const w = need(cmd)
112
- if (w.status !== 0 || !w.stdout.trim()) return `${why}`
113
- }
114
- if (!existsSync(join(DSH_HOME, 'profiles', PROFILE))) {
115
- return `profile '${PROFILE}' not provisioned under ${DSH_HOME}`
116
- }
117
- if (!existsSync(LAUNCHER)) return `launcher missing: ${LAUNCHER}`
118
- return null
119
- }
120
-
121
- const SKIP = preflight()
122
- if (SKIP) {
123
- console.log(`e2e-client: skipped (${SKIP})`)
124
- process.exit(0)
125
- }
126
-
127
- // ---------------------------------------------------------------------------
128
- // Small system helpers (no `timeout` on macOS — all waiting is JS timers).
129
- // ---------------------------------------------------------------------------
130
-
131
- const sh = (cmd, args, opts = {}) => spawnSync(cmd, args, { encoding: 'utf8', ...opts })
132
-
133
- const tmux = (...args) => sh('tmux', args)
134
-
135
- const tmuxOut = (...args) => {
136
- const r = tmux(...args)
137
- return r.status === 0 ? r.stdout : ''
138
- }
139
-
140
- const pidAlive = (pid) => {
141
- try {
142
- process.kill(pid, 0)
143
- return true
144
- } catch (err) {
145
- return err.code === 'EPERM'
146
- }
147
- }
148
-
149
- const isListening = (port) =>
150
- new Promise((resolveListen) => {
151
- const socket = netConnect({ host: '127.0.0.1', port })
152
- let settled = false
153
- const done = (v) => {
154
- if (settled) return
155
- settled = true
156
- socket.destroy()
157
- resolveListen(v)
158
- }
159
- socket.setTimeout(750)
160
- socket.once('connect', () => done(true))
161
- socket.once('error', () => done(false))
162
- socket.once('timeout', () => done(false))
163
- })
164
-
165
- /** Host wrapper process pids: the lifecycle spawns
166
- * `dsh --profile opentui --no-open --port N` (a node wrapper, detached). */
167
- const hostPids = () => {
168
- const r = sh('pgrep', ['-f', `dsh --profile ${PROFILE} --no-open`])
169
- return r.status === 0 ? r.stdout.split('\n').map((s) => Number(s.trim())).filter(Boolean) : []
170
- }
171
-
172
- const readLock = () => {
173
- try {
174
- const raw = JSON.parse(readFileSync(LOCK_PATH, 'utf8'))
175
- if (typeof raw.pid === 'number' && typeof raw.port === 'number') return raw
176
- } catch { /* missing/corrupt */ }
177
- return null
178
- }
179
-
180
- const waitPidGone = async (pid, budgetMs) => {
181
- const deadline = Date.now() + budgetMs
182
- while (pidAlive(pid)) {
183
- if (Date.now() > deadline) return false
184
- await sleep(250)
185
- }
186
- return true
187
- }
188
-
189
- /** SIGTERM the host's whole process group (the detached wrapper is a group
190
- * leader; the server may be a child), escalating to SIGKILL. */
191
- const killHostTree = async (pid) => {
192
- const signal = (target, sig) => {
193
- try { process.kill(-target, sig) } catch { try { process.kill(target, sig) } catch { /* gone */ } }
194
- }
195
- signal(pid, 'SIGTERM')
196
- if (!(await waitPidGone(pid, 5000))) {
197
- signal(pid, 'SIGKILL')
198
- await waitPidGone(pid, 3000)
199
- }
200
- return !pidAlive(pid)
201
- }
202
-
203
- /** Port sweep: SIGTERM whatever still listens (group first), for the
204
- * unlocked /reload-restarted host (oldfox-P1#2 consequence). */
205
- const sweepPort = async (port) => {
206
- const r = sh('lsof', ['-ti', `tcp:${port}`])
207
- const pids = r.status === 0 ? r.stdout.split('\n').map((s) => Number(s.trim())).filter(Boolean) : []
208
- for (const pid of pids) await killHostTree(pid)
209
- return pids
210
- }
211
-
212
- /** Full teardown of one host: kill by pid, sweep its port, clear the
213
- * lockfile only while it still describes that pid. */
214
- const reapHost = async (host) => {
215
- if (!host) return
216
- await killHostTree(host.pid)
217
- await sweepPort(host.port)
218
- const lock = readLock()
219
- if (lock && lock.pid === host.pid) rmSync(LOCK_PATH, { force: true })
220
- // settle: let dying sockets drain before the next scenario probes
221
- await sleep(1500)
222
- if (await isListening(host.port)) await sweepPort(host.port)
223
- }
224
-
225
- // ---------------------------------------------------------------------------
226
- // tmux client drive (120x34, slow typing — e2e-live mechanics).
227
- // ---------------------------------------------------------------------------
228
-
229
- /** Hygienic env for the client (and the host it spawns): the REAL dsh home
230
- * (no DSH_HOME override), no repo .bin shadowing, no npm_config_* leaks. */
231
- const baseClientEnv = () => {
232
- const env = { ...process.env }
233
- delete env.DSH_HOME
234
- delete env.DSH_OPENTUI_THEME
235
- env.PATH = env.PATH.split(':').filter((s) => s && !s.includes('dsh-opentui/node_modules/.bin')).join(':')
236
- for (const k of Object.keys(env)) if (k.startsWith('npm_config_')) delete env[k]
237
- return env
238
- }
239
-
240
- const sessionsCreated = new Set()
241
- let ownedTmuxServer = false
242
-
243
- const tmuxServerWasRunning = () => tmux('list-sessions').status === 0
244
-
245
- const newClientSession = (name, workspace, extraEnv = {}) => {
246
- const envParts = Object.entries(extraEnv)
247
- .map(([k, v]) => `${k}=${JSON.stringify(v)}`)
248
- .join(' ')
249
- const cmd = `${envParts} ${LAUNCHER} --client`.trim()
250
- const r = tmux('new-session', '-d', '-x', String(GEOMETRY.x), '-y', String(GEOMETRY.y), '-s', name, '-c', workspace, cmd)
251
- if (r.status !== 0) throw new Error(`tmux new-session ${name} failed: ${r.stderr.trim()}`)
252
- sessionsCreated.add(name)
253
- }
254
-
255
- const paneAlive = (name) => tmux('has-session', '-t', name).status === 0
256
-
257
- const capture = (name, { esc = false, full = false } = {}) => {
258
- const args = ['capture-pane', '-p', '-t', name]
259
- if (esc) args.push('-e')
260
- if (full) args.push('-S', '-2000')
261
- return tmuxOut(...args)
262
- }
263
-
264
- const sendKeys = (name, ...keys) => tmux('send-keys', '-t', name, ...keys)
265
-
266
- /** One char per send-keys with a real inter-key gap (parser drops bursts). */
267
- const typeText = async (name, text) => {
268
- for (const ch of text) {
269
- sendKeys(name, '-l', ch)
270
- await sleep(TYPE_GAP_MS)
271
- }
272
- }
273
-
274
- const submitLine = async (name, text) => {
275
- await typeText(name, text)
276
- await sleep(300)
277
- sendKeys(name, 'Enter')
278
- }
279
-
280
- const waitPane = async (name, predicate, timeoutMs, everyMs = 500) => {
281
- const deadline = Date.now() + timeoutMs
282
- let last = ''
283
- while (Date.now() < deadline) {
284
- last = capture(name)
285
- if (predicate(last)) return last
286
- await sleep(everyMs)
287
- }
288
- return last // caller decides whether the final capture satisfies it
289
- }
290
-
291
- const waitPaneDead = async (name, timeoutMs) => {
292
- const deadline = Date.now() + timeoutMs
293
- while (Date.now() < deadline) {
294
- if (!paneAlive(name)) return true
295
- await sleep(400)
296
- }
297
- return false
298
- }
299
-
300
- /** Wait for the boot to reach the rendered powerline (🧠 segment), then for
301
- * the cold-boot route label (the generic "dsh-host" swaps within the boot
302
- * label budget; a still-generic label after that is an assertion failure,
303
- * not a wait failure). */
304
- const waitRendered = async (name) => {
305
- const last = await waitPane(name, (out) => out.includes('🧠') && /dsh\(/.test(out), 45_000)
306
- if (!last.includes('🧠')) {
307
- throw new Error(`client ${name} never rendered a powerline within 45s — last capture:\n${last.slice(-1500)}`)
308
- }
309
- if (last.includes('client boot failed')) {
310
- throw new Error(`client ${name} boot failed:\n${last.slice(0, 1500)}`)
311
- }
312
- const labeled = await waitPane(name, (out) => {
313
- const r = routeOf(powerlineOf(out))
314
- return r !== null && r.provider !== 'dsh-host' && r.model !== '·'
315
- }, 10_000)
316
- return labeled
317
- }
318
-
319
- const quitClient = async (name) => {
320
- if (!paneAlive(name)) return 'already gone'
321
- await submitLine(name, '/quit')
322
- if (await waitPaneDead(name, 15_000)) return 'quit'
323
- tmux('kill-session', '-t', name)
324
- return 'forced (kill-session)'
325
- }
326
-
327
- // ---------------------------------------------------------------------------
328
- // Turn helpers.
329
- // ---------------------------------------------------------------------------
330
-
331
- /** The idle editor row shows the placeholder; while a turn runs it is
332
- * replaced by the busy label — locale-proof busy detection. */
333
- const IDLE_MARK = '提问,回车发送'
334
- const isIdle = (out) => out.includes(IDLE_MARK)
335
-
336
- /** The powerline footer is the 🧠 line that also carries the dsh( segment
337
- * (the busy status row contains 🧠 too, but never dsh(). */
338
- const powerlineOf = (out) => out.split('\n').find((l) => l.includes('🧠') && l.includes('dsh(')) ?? ''
339
-
340
- const contextOf = (line) => {
341
- const m = /🧠\s*([\d.]+)(k?)\((\d+)%\)/.exec(line)
342
- if (!m) return null
343
- return Number(m[1]) * (m[2] === 'k' ? 1000 : 1)
344
- }
345
-
346
- const routeOf = (line) => {
347
- // segments are separated by the powerline glyph U+E0B0 (private-use area)
348
- // — normalize every private-use char to a space before parsing
349
- const clean = line.replace(/[\u{E000}-\u{F8FF}]/gu, ' ').replace(/\s+/g, ' ')
350
- const m = /dsh\(\w+\) (\S+) 🤖 (\S+) ◕(\S*)/.exec(clean)
351
- return m ? { provider: m[1], model: m[2], effort: m[3] } : null
352
- }
353
-
354
- /** Send a turn and wait for it to settle (editor leaves idle → returns to
355
- * idle). Returns the post-turn capture. */
356
- const runTurn = async (name, text, settleMs = 90_000) => {
357
- const before = capture(name)
358
- await submitLine(name, text)
359
- const busySeen = await waitPane(name, (out) => !isIdle(out) || /api key|auth/i.test(out), 20_000)
360
- // a fast auth failure may never paint the busy row — both are settles
361
- if (isIdle(busySeen) && !/api key|auth/i.test(busySeen)) {
362
- throw new Error(`turn never started (editor stayed idle, no error) — capture:\n${busySeen.slice(-1200)}`)
363
- }
364
- const settled = await waitPane(name, (out) => isIdle(out), settleMs)
365
- return { after: settled, before }
366
- }
367
-
368
- // ---------------------------------------------------------------------------
369
- // WorkingRoute discovery (wave-3 pattern) — probe the catalog, selectModel
370
- // a route that actually answers. Runs BEFORE the scenarios; the winning
371
- // route is exported to every TUI client via DSH_OPENTUI_MODEL (bucket-(d)
372
- // env layer), so the TUI turns ride a live route even with a rotted
373
- // deployment default.
374
- // ---------------------------------------------------------------------------
375
-
376
- const probeWorkingRoute = async () => {
377
- const probeSessWs = mkdtempSync(join(tmpdir(), 'p6-probe-sess-'))
378
- // The probe must live inside packages/shell so its imports of the repo's
379
- // TS modules (and the dsh-client-connection closure link) resolve.
380
- const probePath = join(REPO, 'packages', 'shell', `.p6-route-probe-${process.pid}.ts`)
381
- writeFileSync(
382
- probePath,
383
- `// generated by scripts/e2e-client.mjs — deleted after the run
384
- import { ensureHost } from './src/client/lifecycle.ts'
385
- import { ClientConnection } from './src/client/transport.ts'
386
- import { RemoteHostSession } from './src/client/remote-host-session.ts'
387
-
388
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
389
- const turnOnce = (session, text) => new Promise((res) => {
390
- let done = false
391
- const finish = (err) => { if (!done) { done = true; res(err) } }
392
- session.turn(text, {
393
- onThinkingDelta: () => {},
394
- onContentDelta: () => {},
395
- onTurnEnd: () => finish(undefined),
396
- onApprove: async () => false,
397
- onToolRun: () => {},
398
- onError: (m) => finish(m),
399
- }).catch((e) => finish(e instanceof Error ? e.message : String(e)))
400
- const deadline = Date.now() + 90_000
401
- const poll = setInterval(() => {
402
- if (done || Date.now() > deadline) { clearInterval(poll); finish('turn deadline exceeded') }
403
- }, 200)
404
- poll.unref?.()
405
- })
406
-
407
- const ws = process.env.P6_PROBE_WS
408
- const host = await ensureHost({ profile: '${PROFILE}', idleExitSec: 0 })
409
- const out = { hostPid: host.pid, hostPort: host.port, adopted: host.adopted, ok: false, adoptedDefault: false, route: null, otherRoute: null, errors: [] }
410
- const live = new ClientConnection({ authority: host.authority, cookieHeader: host.cookieHeader })
411
- const session = new RemoteHostSession({ connection: live, cookieHeader: host.cookieHeader, cwd: ws })
412
- await session.start()
413
- let err = await turnOnce(session, 'say ok')
414
- if (err === undefined) {
415
- out.ok = true
416
- out.adoptedDefault = true
417
- // resolve WHICH route answered: the live session's projection (fallback:
418
- // the catalog default) — the scenarios need the concrete provider/model
419
- try {
420
- const sel = await session.currentModelSelection()
421
- if (sel && sel.provider && sel.model) out.route = sel.provider + '/' + sel.model
422
- } catch { /* keep null */ }
423
- if (!out.route) {
424
- try {
425
- const catalog = await session.modelCatalog(true)
426
- if (catalog.default && catalog.default.provider && catalog.default.model) {
427
- out.route = catalog.default.provider + '/' + catalog.default.model
428
- }
429
- } catch { /* keep null */ }
430
- }
431
- } else {
432
- out.errors.push('default: ' + err.slice(0, 120))
433
- if (/api key|auth/i.test(err)) {
434
- const catalog = await session.modelCatalog(true)
435
- for (const group of catalog.groups) {
436
- if (group.models.length === 0) continue
437
- const candidate = { provider: group.id, model: group.models[0].id }
438
- try {
439
- await session.selectModel(candidate)
440
- } catch (e) { out.errors.push('selectModel ' + group.id + ': ' + String(e).slice(0, 80)); continue }
441
- err = await turnOnce(session, 'say ok')
442
- if (err === undefined) {
443
- out.ok = true
444
- out.route = candidate.provider + '/' + candidate.model
445
- break
446
- }
447
- out.errors.push(group.id + ': ' + err.slice(0, 120))
448
- }
449
- } else {
450
- out.route = null
451
- }
452
- }
453
- // a DIFFERENT catalog route for scenario g's model-pref overlay (the label
454
- // must then provably come from the workspace config, not the cold-boot
455
- // default; the route only needs a distinct id — no working key required)
456
- if (out.route) {
457
- try {
458
- const catalog = await session.modelCatalog(true)
459
- const rp = out.route.split('/')[0]
460
- const alt = catalog.groups.find((g) => g.models.length > 0 && g.id !== rp)
461
- if (alt) out.otherRoute = alt.id + '/' + alt.models[0].id
462
- } catch { /* keep null */ }
463
- }
464
- session.abort()
465
- await session.dispose()
466
- await live.close()
467
- console.log('PROBE_JSON' + JSON.stringify(out))
468
- process.exit(0)
469
- `,
470
- )
471
- try {
472
- const r = sh('bun', [probePath], {
473
- encoding: 'utf8',
474
- timeout: 300_000,
475
- cwd: join(REPO, 'packages', 'shell'),
476
- env: { ...process.env, P6_PROBE_WS: probeSessWs },
477
- })
478
- const line = (r.stdout + '\n' + r.stderr).split('\n').find((l) => l.startsWith('PROBE_JSON'))
479
- if (!line) throw new Error(`probe produced no result (exit ${r.status}):\n${(r.stdout + r.stderr).slice(-1200)}`)
480
- return JSON.parse(line.slice('PROBE_JSON'.length))
481
- } finally {
482
- rmSync(probePath, { force: true })
483
- rmSync(probeSessWs, { recursive: true, force: true })
484
- }
485
- }
486
-
487
- // ---------------------------------------------------------------------------
488
- // Scenario scaffold.
489
- // ---------------------------------------------------------------------------
490
-
491
- const scenarios = []
492
- const record = (name, verdict, notes = [], p1 = []) => {
493
- scenarios.push({ name, verdict, notes, p1 })
494
- console.log(`\n=== ${name}: ${verdict} ===`)
495
- for (const n of notes) console.log(` ${n}`)
496
- for (const p of p1) console.log(` !! ${p}`)
497
- }
498
-
499
- const assert = (cond, message) => {
500
- if (!cond) throw new Error(message)
501
- }
502
-
503
- /** Between-scenario hygiene: nothing of ours should be left running. If a
504
- * host IS still alive here, it is a leftover — reap it so the next
505
- * scenario starts from the quiet topology. */
506
- const preClean = async (label) => {
507
- const lock = readLock()
508
- if (lock && pidAlive(lock.pid)) {
509
- console.log(` [${label}] reaping leftover host pid=${lock.pid} port=${lock.port}`)
510
- await reapHost(lock)
511
- } else if (lock) {
512
- rmSync(LOCK_PATH, { force: true })
513
- }
514
- for (const pid of hostPids()) {
515
- if (!lock || pid !== lock.pid) {
516
- console.log(` [${label}] killing stray host wrapper pid=${pid}`)
517
- await killHostTree(pid)
518
- }
519
- }
520
- }
521
-
522
- // ---------------------------------------------------------------------------
523
- // Scenarios.
524
- // ---------------------------------------------------------------------------
525
-
526
- let ROUTE = null // concrete "provider/model" | null — the workingRoute discovery product
527
- let OTHER_ROUTE = null // a DIFFERENT catalog route (scenario g's overlay pref)
528
- let TURN_OK = false // a route answers (default or fallback) — turns may run
529
-
530
- const scenarioA = async () => {
531
- const notes = []
532
- const ws = mkdtempSync(join(tmpdir(), 'p6-ws-a-'))
533
- const name = 'p6a'
534
- try {
535
- newClientSession(name, ws, ROUTE ? { DSH_OPENTUI_MODEL: ROUTE } : {})
536
- const rendered = await waitRendered(name)
537
- const line = powerlineOf(rendered)
538
- const route = routeOf(line)
539
- notes.push(`powerline: ${line.trim().slice(0, 120)}`)
540
- assert(route !== null, `powerline route segment not parseable: ${line}`)
541
- assert(route.provider !== 'dsh-host' && route.provider !== '', `status bar shows the generic label (cold-boot route never applied): ${line}`)
542
- assert(route.model !== '·' && route.model !== '', `status bar shows no model: ${line}`)
543
- const ctxBefore = contextOf(line)
544
- notes.push(`status bar route: ${route.provider} / ${route.model} · context before: ${ctxBefore}`)
545
-
546
- if (!TURN_OK) {
547
- record('a. boot + turn', 'BLOCKED (turn)', [
548
- ...notes,
549
- 'boot + status bar asserts PASSED; the turn half is blocked: no route answers (key rot) — see the probe report above',
550
- ])
551
- return
552
- }
553
- const { after } = await runTurn(name, 'say ok')
554
- const line2 = powerlineOf(after)
555
- const ctxAfter = contextOf(line2)
556
- const reply = after.includes('❯ say ok')
557
- notes.push(`post-turn powerline: ${line2.trim().slice(0, 120)}`)
558
- notes.push(`turn: user row painted=${reply} · context after: ${ctxAfter}`)
559
- assert(reply, 'user row "❯ say ok" not painted')
560
- assert(ctxBefore === 0 && ctxAfter > ctxBefore, `context did not increase across the turn (${ctxBefore} → ${ctxAfter})`)
561
- record('a. boot + turn', 'PASS', notes)
562
- } catch (e) {
563
- record('a. boot + turn', 'FAIL', [...notes, String(e.message)])
564
- } finally {
565
- await quitClient(name)
566
- await reapHost(readLock())
567
- rmSync(ws, { recursive: true, force: true })
568
- }
569
- }
570
-
571
- const scenarioB = async () => {
572
- const notes = []
573
- const p1 = []
574
- const ws1 = mkdtempSync(join(tmpdir(), 'p6-ws-b1-'))
575
- const ws2 = mkdtempSync(join(tmpdir(), 'p6-ws-b2-'))
576
- const n1 = 'p6b1'
577
- const n2 = 'p6b2'
578
- try {
579
- newClientSession(n1, ws1, ROUTE ? { DSH_OPENTUI_MODEL: ROUTE } : {})
580
- await waitRendered(n1)
581
- const lock1 = readLock()
582
- assert(lock1 !== null, 'no lockfile after client 1 boot (host not lifecycle-managed?)')
583
- notes.push(`client 1 booted; host pid=${lock1.pid} port=${lock1.port}`)
584
- assert(hostPids().length === 1, `expected exactly 1 host wrapper after boot 1, got ${hostPids().join(',')}`)
585
-
586
- newClientSession(n2, ws2, ROUTE ? { DSH_OPENTUI_MODEL: ROUTE } : {})
587
- await waitRendered(n2)
588
- const lock2 = readLock()
589
- notes.push(`client 2 booted; lockfile pid=${lock2?.pid} port=${lock2?.port}`)
590
- assert(lock2 && lock2.pid === lock1.pid, `second client spawned/replaced the host (lock pid ${lock1.pid} → ${lock2?.pid}) — expected a JOIN`)
591
- const wrappers = hostPids()
592
- if (wrappers.length !== 1) {
593
- p1.push(`reproduced oldfox-P1#3: ${wrappers.length} host wrapper pids after a second client joined: ${wrappers.join(',')}`)
594
- } else {
595
- notes.push('exactly one host process (join, no second spawn)')
596
- }
597
-
598
- const q1 = await quitClient(n1)
599
- const q2 = await quitClient(n2)
600
- notes.push(`quits: client1=${q1} client2=${q2}`)
601
-
602
- // the idle-reaper path: the last quit spawned the detached reaper with
603
- // the 5s window (DSH_OPENTUI_HOST_IDLE_MS) — the host exits inside ~5-10s
604
- const hostGone = await waitPidGone(lock1.pid, 110_000)
605
- const lockAfter = readLock()
606
- notes.push(`host dead after grace=${hostGone} · lockfile now: ${lockAfter ? `pid=${lockAfter.pid}` : 'gone'}`)
607
- assert(hostGone, `host pid=${lock1.pid} still alive 110s after both clients quit — idle-exit hand-off failed`)
608
- if (lockAfter && lockAfter.pid === lock1.pid) rmSync(LOCK_PATH, { force: true })
609
- assert(!await isListening(lock1.port), `port ${lock1.port} still listening after the host died`)
610
- record('b. multi-TUI attach', 'PASS', notes, p1)
611
- } catch (e) {
612
- record('b. multi-TUI attach', 'FAIL', [...notes, String(e.message)], p1)
613
- } finally {
614
- await quitClient(n1)
615
- await quitClient(n2)
616
- await reapHost(readLock())
617
- rmSync(ws1, { recursive: true, force: true })
618
- rmSync(ws2, { recursive: true, force: true })
619
- }
620
- }
621
-
622
- const scenarioC = async () => {
623
- const notes = []
624
- const ws1 = mkdtempSync(join(tmpdir(), 'p6-ws-c1-'))
625
- const ws2 = mkdtempSync(join(tmpdir(), 'p6-ws-c2-'))
626
- const n1 = 'p6c1'
627
- const n2 = 'p6c2'
628
- try {
629
- newClientSession(n1, ws1, ROUTE ? { DSH_OPENTUI_MODEL: ROUTE } : {})
630
- await waitRendered(n1)
631
- const lock1 = readLock()
632
- assert(lock1 !== null, 'no lockfile after client 1 boot')
633
-
634
- // kill -9 the CLIENT's bun process (not the pane shell)
635
- const pg = sh('pgrep', ['-f', 'client-entry.tsx'])
636
- const clientPids = pg.status === 0 ? pg.stdout.split('\n').map((s) => Number(s.trim())).filter(Boolean) : []
637
- assert(clientPids.length === 1, `expected exactly 1 client bun process, got: ${clientPids.join(',')}`)
638
- try { process.kill(clientPids[0], 'SIGKILL') } catch { /* gone */ }
639
- notes.push(`client 1 bun pid=${clientPids[0]} SIGKILLed`)
640
- await waitPaneDead(n1, 10_000)
641
- await sleep(2000)
642
- assert(pidAlive(lock1.pid), `host pid=${lock1.pid} died with its client — the resident-host contract broke`)
643
- assert(await isListening(lock1.port), `host port ${lock1.port} no longer listening after the client crashed`)
644
- notes.push(`host survived the client crash (pid=${lock1.pid} alive, port ${lock1.port} listening)`)
645
-
646
- newClientSession(n2, ws2, ROUTE ? { DSH_OPENTUI_MODEL: ROUTE } : {})
647
- await waitRendered(n2)
648
- const lock2 = readLock()
649
- notes.push(`client 2 booted; lockfile pid=${lock2?.pid} port=${lock2?.port}`)
650
- assert(lock2 && lock2.pid === lock1.pid, `client 2 did NOT adopt: lock pid ${lock1.pid} → ${lock2?.pid} (a fresh boot happened instead)`)
651
- const wrappers = hostPids()
652
- if (wrappers.length !== 1) {
653
- notes.push(`WARNING: host wrapper count after adoption = ${wrappers.length} (${wrappers.join(',')}) — expected 1`)
654
- } else {
655
- notes.push('adoption path confirmed: same pid, exactly one host process, no respawn')
656
- }
657
-
658
- const q = await quitClient(n2)
659
- notes.push(`client 2 quit: ${q}`)
660
- await reapHost(lock2)
661
- notes.push(`teardown: host pid=${lock2.pid} reaped, lockfile ${readLock() ? 'STILL PRESENT' : 'gone'}`)
662
- assert(readLock() === null, 'lockfile survived the full teardown')
663
- record('c. crash-recovery adoption', 'PASS', notes)
664
- } catch (e) {
665
- record('c. crash-recovery adoption', 'FAIL', [...notes, String(e.message)])
666
- } finally {
667
- await quitClient(n1)
668
- await quitClient(n2)
669
- await reapHost(readLock())
670
- rmSync(ws1, { recursive: true, force: true })
671
- rmSync(ws2, { recursive: true, force: true })
672
- }
673
- }
674
-
675
- const scenarioD = async () => {
676
- const notes = []
677
- const p1 = []
678
- const ws = mkdtempSync(join(tmpdir(), 'p6-ws-d-'))
679
- const name = 'p6d'
680
- let dLock0 = null // kept for the finally: the restarted host may be unmanaged
681
- try {
682
- newClientSession(name, ws, ROUTE ? { DSH_OPENTUI_MODEL: ROUTE } : {})
683
- await waitRendered(name)
684
- const lock0 = readLock()
685
- dLock0 = lock0
686
- assert(lock0 !== null, 'no lockfile before /reload')
687
-
688
- // cheap transcript rows without a model call
689
- await submitLine(name, '/usage')
690
- await waitPane(name, (out) => out.includes('turns 0'), 15_000)
691
- notes.push('/usage rows painted (system transcript rows)')
692
-
693
- // one real turn row when a route answers
694
- if (TURN_OK) {
695
- await runTurn(name, 'say ok')
696
- notes.push('say-ok turn completed before the reload')
697
- }
698
-
699
- await submitLine(name, '/reload')
700
- const reloaded = await waitPane(name, (out) => out.includes('plugins reloaded') || out.includes('reload failed'), 90_000)
701
- assert(reloaded.includes('plugins reloaded'), `/reload did not complete cleanly:\n${reloaded.slice(-1200)}`)
702
- notes.push('"plugins reloaded" painted')
703
-
704
- // same-port restart: old pid dead, a listener STILL on lock0.port, new pid.
705
- // LISTEN-only: unfiltered `-ti tcp:N` also lists every client holding an
706
- // ESTABLISHED socket to the port — that once produced a false oldfox-P1#2
707
- // reproduction (the client bun pid, created BEFORE the old host wrapper,
708
- // looked like a "new listener" the rewritten lockfile didn't name).
709
- const listeners = sh('lsof', ['-ti', `tcp:${lock0.port}`, '-sTCP:LISTEN'])
710
- const listenerPids = listeners.status === 0 ? listeners.stdout.split('\n').map((s) => Number(s.trim())).filter(Boolean) : []
711
- const newPid = listenerPids.find((p) => p !== lock0.pid) ?? listenerPids[0]
712
- notes.push(`restart: old pid dead=${await waitPidGone(lock0.pid, 100)} · port ${lock0.port} listener pid(s)=${listenerPids.join(',') || 'NONE'}`)
713
- assert(listenerPids.length > 0, `port ${lock0.port} has no listener after /reload — the host did not come back`)
714
- assert(newPid !== undefined && newPid !== lock0.pid, `expected a NEW host process on the same port (listener=${newPid}, old=${lock0.pid})`)
715
- notes.push(`same-port restart confirmed: ${lock0.pid} → ${newPid} on port ${lock0.port}`)
716
-
717
- // oldfox-P1#2 watch: the restart path removes the lockfile and never
718
- // rewrites it (writeLock lives only in bootHost) — the restarted host is
719
- // UNMANAGED and the next ensureHost would boot a duplicate on a new port.
720
- const lockAfter = readLock()
721
- if (!lockAfter || lockAfter.pid !== newPid) {
722
- p1.push(`reproduced oldfox-P1#2: after /reload the lockfile is ${lockAfter ? `stale (pid=${lockAfter.pid}, listener=${newPid})` : 'GONE'} — the restarted host pid=${newPid} is unmanaged (next ensureHost would boot a duplicate host; teardown below reaps by port)`)
723
- } else {
724
- notes.push('lockfile rewritten by the restart (P1#2 not hit on this build)')
725
- }
726
-
727
- // transcript survival + double-paint watch (oldfox-P1#1)
728
- await sleep(3000) // let the re-attach replay settle
729
- const full = capture(name, { full: true })
730
- const sayOkRows = (full.match(/❯ say ok/g) ?? []).length
731
- const usageRows = (full.match(/turns 0/g) ?? []).length
732
- notes.push(`post-reload transcript: "❯ say ok" rows=${sayOkRows} · "turns 0" rows=${usageRows}`)
733
- if (ROUTE && sayOkRows > 1) p1.push(`reproduced oldfox-P1#1: "❯ say ok" painted ${sayOkRows}x after the /reload re-attach (no seq dedupe on replay)`)
734
- if (usageRows > 1) p1.push(`reproduced oldfox-P1#1: "turns 0" system row painted ${usageRows}x`)
735
- assert(sayOkRows >= (TURN_OK ? 1 : 0) && usageRows >= 1, 'pre-reload transcript rows lost across the restart')
736
- record('d. /reload same-port restart', p1.length > 0 ? 'PASS (with P1 reproductions)' : 'PASS', notes, p1)
737
- } catch (e) {
738
- record('d. /reload same-port restart', 'FAIL', [...notes, String(e.message)], p1)
739
- } finally {
740
- await quitClient(name)
741
- // the restarted host may be UNMANAGED (P1#2, no lockfile): reap by lock
742
- // AND by port sweep so nothing leaks
743
- await reapHost(readLock())
744
- if (dLock0) await sweepPort(dLock0.port)
745
- rmSync(ws, { recursive: true, force: true })
746
- }
747
- }
748
-
749
- const scenarioE = async () => {
750
- const notes = []
751
- const p1 = []
752
- const ws1 = mkdtempSync(join(tmpdir(), 'p6-ws-e1-'))
753
- const ws2 = mkdtempSync(join(tmpdir(), 'p6-ws-e2-'))
754
- const n1 = 'p6e1'
755
- const n2 = 'p6e2'
756
- try {
757
- newClientSession(n1, ws1, ROUTE ? { DSH_OPENTUI_MODEL: ROUTE } : {})
758
- await waitRendered(n1)
759
- const lock1 = readLock()
760
- assert(lock1 !== null, 'no lockfile before the host kill')
761
-
762
- if (TURN_OK) {
763
- // stage a long-running turn so the follow stream dies mid-await
764
- await submitLine(n1, '写一篇 300 字左右的短文,介绍秋天的湖面。不要使用任何工具。')
765
- const busy = await waitPane(n1, (out) => !isIdle(out), 20_000)
766
- assert(!isIdle(busy), `long turn never became busy:\n${busy.slice(-800)}`)
767
- await sleep(4000) // let the follow attach and content stream
768
- notes.push('long turn in flight (editor left idle)')
769
- } else {
770
- notes.push('no working route: skipping the mid-turn staging — the death surface degrades (documented in the header)')
771
- }
772
-
773
- // kill -9 the HOST process group (wrapper is a detached group leader)
774
- try { process.kill(-lock1.pid, 'SIGKILL') } catch { try { process.kill(lock1.pid, 'SIGKILL') } catch { /* gone */ } }
775
- notes.push(`host pid=${lock1.pid} SIGKILLed (process group)`)
776
- const listenerGone = await (async () => {
777
- const deadline = Date.now() + 10_000
778
- while (Date.now() < deadline) {
779
- if (!(await isListening(lock1.port))) return true
780
- await sleep(300)
781
- }
782
- return false
783
- })()
784
- notes.push(`host port ${lock1.port} released=${listenerGone}`)
785
- assert(listenerGone, 'host port still listening after SIGKILL — the server process survived the group kill')
786
-
787
- // the client must SURFACE the death and must NOT crash (oldfox-P1#4 watch)
788
- let surfaced = 'nothing'
789
- if (TURN_OK) {
790
- const surfacedPane = await waitPane(n1, (out) => out.includes('reconnecting') || !paneAlive(n1), 20_000)
791
- if (surfacedPane.includes('reconnecting')) {
792
- surfaced = 'reconnecting label painted'
793
- const line = powerlineOf(surfacedPane)
794
- notes.push(`powerline during the outage: ${line.trim().slice(0, 120)}`)
795
- } else {
796
- notes.push(
797
- 'FINDING (renderer sampling gap, not an oldfox P1): the session-level reconnecting marker exists (RemoteHostSession sets label="reconnecting…" and status.turn="reconnecting" on the mid-turn follow detach) but the PANE never paints it — ShellHost samples session.label only at onTurnEnd / /think (setLabel, ShellHost.tsx) and the turn never settles during an unresolved outage, so the swap never re-renders. Recorded for the UI-follow-up task.',
798
- )
799
- }
800
- }
801
-
802
- // next ensureHost respawns — a FRESH client boot (the chosen recovery UX)
803
- newClientSession(n2, ws2, ROUTE ? { DSH_OPENTUI_MODEL: ROUTE } : {})
804
- await waitRendered(n2)
805
- const lock2 = readLock()
806
- notes.push(`client 2 booted; lockfile pid=${lock2?.pid} port=${lock2?.port}`)
807
- assert(lock2 !== null, 'no lockfile after the recovery boot')
808
- assert(lock2.pid !== lock1.pid, `recovery boot reused the dead pid?! ${lock2.pid}`)
809
- assert(await isListening(lock2.port), `recovery host port ${lock2.port} not listening`)
810
-
811
- if (TURN_OK) {
812
- // the recovered client continues (a real turn through the fresh host)
813
- await runTurn(n2, 'say ok')
814
- const line2 = powerlineOf(capture(n2))
815
- const ctx = contextOf(line2)
816
- notes.push(`recovered client completed a turn (context after: ${ctx})`)
817
- assert(ctx !== null && ctx > 0, 'recovered client turn did not register usage')
818
- }
819
- record('e. host death recovery', 'PASS', notes, p1)
820
- } catch (e) {
821
- record('e. host death recovery', 'FAIL', [...notes, String(e.message)], p1)
822
- } finally {
823
- await quitClient(n1)
824
- await quitClient(n2)
825
- await reapHost(readLock())
826
- rmSync(ws1, { recursive: true, force: true })
827
- rmSync(ws2, { recursive: true, force: true })
828
- }
829
- }
830
-
831
- const scenarioF = async () => {
832
- const notes = []
833
- const ws = mkdtempSync(join(tmpdir(), 'p6-ws-f-'))
834
- const name = 'p6f'
835
- try {
836
- newClientSession(name, ws, ROUTE ? { DSH_OPENTUI_MODEL: ROUTE } : {})
837
- await waitRendered(name)
838
- if (!TURN_OK) {
839
- const cap = capture(name, { esc: true })
840
- writeFileSync('/tmp/p6-mdtable.txt', cap)
841
- record('f. acceptance (markdown table)', 'BLOCKED', [
842
- ...notes,
843
- 'THE acceptance scenario is BLOCKED: no model route answers (probe report above) — nothing was hacked; capture saved to /tmp/p6-mdtable.txt for the record',
844
- ])
845
- return
846
- }
847
- await submitLine(name, '用一个markdown表格列出两种语言和创建年份,再写一句总结')
848
- // the model may ask a clarifying user-question (ask_user_question
849
- // waterfall → the "模型提问" overlay) — answer with the highlighted
850
- // (recommended) option and keep waiting for the table
851
- const tableDone = (out) => {
852
- const lines = out.split('\n').filter((l) => l.includes('│') && !l.includes('❯') && !/[╭╰╮╯]/.test(l))
853
- return lines.length >= 2 && out.includes('└─') && isIdle(out)
854
- }
855
- let done = ''
856
- let asked = 0
857
- const deadline = Date.now() + 150_000
858
- while (Date.now() < deadline) {
859
- done = capture(name)
860
- if (tableDone(done)) break
861
- if (done.includes('模型提问') && Date.now() - asked > 3000) {
862
- asked = Date.now()
863
- notes.push('model asked a clarifying question (ask_user_question overlay) — answering with the highlighted option')
864
- sendKeys(name, 'Enter')
865
- await sleep(2500)
866
- continue
867
- }
868
- await sleep(800)
869
- }
870
- const rows = done.split('\n').filter((l) => l.includes('│') && !l.includes('❯') && !/[╭╰╮╯]/.test(l))
871
- const bottomIdx = done.split('\n').findIndex((l) => l.includes('└─'))
872
- assert(rows.length >= 2, `no bordered table rows (│) in the reply pane`)
873
- assert(bottomIdx !== -1, 'no └─ table bottom border in the reply pane')
874
- // summary line: non-table text AFTER the table bottom
875
- const afterBottom = done.split('\n').slice(bottomIdx + 1).map((l) => l.trim()).filter((l) => l.length > 0 && !l.includes('│'))
876
- const summary = afterBottom.find((l) => !/^╰|^enter send|^ dsh\(|^\d{1,2}:\d{2}:\d{2}$/.test(l) && !l.includes('❯'))
877
- notes.push(`table rows painted: ${rows.length}; first: ${JSON.stringify(rows[0].trim().slice(0, 80))}`)
878
- notes.push(`table bottom: ${JSON.stringify(done.split('\n')[bottomIdx].trim().slice(0, 60))}`)
879
- notes.push(`summary line after the table: ${summary ? JSON.stringify(summary.trim().slice(0, 100)) : 'NOT FOUND'}`)
880
- assert(summary !== undefined, 'no summary line after the table bottom')
881
- // bottom anchor: the powerline footer is still the last chrome row
882
- const tail = done.split('\n').filter((l) => l.trim().length > 0).slice(-3).join(' | ')
883
- notes.push(`pane tail (bottom anchor): ${tail.slice(0, 140)}`)
884
- assert(tail.includes('🧠'), `powerline footer missing from the pane tail — UI died or scrolled: ${tail}`)
885
- assert(/:\d{2}:\d{2}/.test(tail), `powerline clock missing from the tail: ${tail}`)
886
-
887
- // artifacts: ANSI capture + PNG render for eyeballing
888
- const esc = capture(name, { esc: true })
889
- writeFileSync('/tmp/p6-mdtable.txt', esc)
890
- const png = sh('python3', ['/tmp/tmux2png.py', '/tmp/p6-mdtable.txt', '/tmp/p6-mdtable.png', String(GEOMETRY.x), String(GEOMETRY.y)], { encoding: 'utf8' })
891
- notes.push(png.status === 0 ? `PNG rendered: ${png.stdout.trim()}` : `PNG render FAILED (exit ${png.status}): ${png.stderr.slice(0, 200)}`)
892
- record('f. acceptance (markdown table)', 'PASS', notes)
893
- } catch (e) {
894
- try { writeFileSync('/tmp/p6-mdtable.txt', capture(name, { esc: true })) } catch { /* keep whatever exists */ }
895
- record('f. acceptance (markdown table)', 'FAIL', [...notes, String(e.message)])
896
- } finally {
897
- await quitClient(name)
898
- await reapHost(readLock())
899
- rmSync(ws, { recursive: true, force: true })
900
- }
901
- }
902
-
903
- const scenarioG = async () => {
904
- const notes = []
905
- const ws = mkdtempSync(join(tmpdir(), 'p6-ws-g-'))
906
- const name = 'p6g'
907
- try {
908
- // the workspace overlay: a DIFFERENT shipped theme + the model preference
909
- mkdirSync(join(ws, '.dsh'), { recursive: true })
910
- // the overlay: theme is the strong assertion; the model pref uses a
911
- // DIFFERENT catalog route when one exists — the powerline label then
912
- // provably comes from the workspace config, never the cold-boot default
913
- // (a dead key on that route is fine: scenario g sends no turn)
914
- const route = OTHER_ROUTE ?? ROUTE
915
- const [provider, model] = route ? route.split('/') : [undefined, undefined]
916
- const configBody =
917
- `# p6 scenario g workspace overlay\ntheme: dracula\n` +
918
- (route ? `model:\n provider: ${provider}\n model: ${model}\n` : `# (no concrete route resolvable — model pref omitted)\n`)
919
- writeFileSync(join(ws, '.dsh', 'config.yml'), configBody)
920
- notes.push(`workspace config.yml: theme=dracula${route ? ` · model=${route}${OTHER_ROUTE ? ' (differs from the cold-boot default → strong assertion)' : ''}` : ' · (model pref omitted: no concrete route)'}`)
921
- // boot WITHOUT the env override — the overlay is the only model source
922
- newClientSession(name, ws, {})
923
- const rendered = await waitRendered(name)
924
- const line = powerlineOf(rendered)
925
- const rt = routeOf(line)
926
- notes.push(`powerline: ${line.trim().slice(0, 120)}`)
927
- assert(rt !== null && rt.model !== '·' && rt.provider !== 'dsh-host', `status bar shows a generic route — the overlay label never applied: ${line}`)
928
- if (route) {
929
- assert(rt.model === model, `workspace model pref not applied (want ${model}, got ${rt.model})`)
930
- if (rt.provider !== provider) notes.push(`note: provider seg ${rt.provider} != overlay ${provider} (the label carries the live session route)`)
931
- }
932
- // workspace cwd carried: the banner prints `<model> · <cwd>`
933
- const banner = rendered.split('\n').find((l) => l.includes(' · ') && l.includes(ws.split('/').pop()))
934
- assert(banner !== undefined || rendered.includes(ws), `welcome banner does not show the workspace cwd (${ws})`)
935
- notes.push(`banner cwd line: ${JSON.stringify((banner ?? rendered.split('\n').find((l) => l.includes(ws)))?.trim().slice(0, 100))}`)
936
-
937
- // theme actually applied: paint a user row, then compare truecolor SGRs
938
- await submitLine(name, 'theme probe')
939
- await waitPane(name, (out) => out.includes('❯ theme probe'), 15_000)
940
- await sleep(2000)
941
- const esc = capture(name, { esc: true })
942
- const draculaAccent = esc.includes('38;2;189;147;249') // #bd93f9 — dracula accent (user-row fallback: no userMark token)
943
- const mochaUserMark = esc.includes('38;2;137;180;250') // #89b4fa — catppuccin-mocha userMark
944
- notes.push(`capture -e: dracula accent painted=${draculaAccent} · mocha userMark painted=${mochaUserMark}`)
945
- assert(draculaAccent, 'dracula accent color not found in capture -e — the workspace theme did not apply')
946
- assert(!mochaUserMark, 'the default mocha user-row color is still painted — theme override ineffective')
947
-
948
- // cross-check against scenario f's default-theme capture when available
949
- if (existsSync('/tmp/p6-mdtable.txt')) {
950
- const f = readFileSync('/tmp/p6-mdtable.txt', 'utf8')
951
- notes.push(`cross-check: scenario f (default theme) capture paints mocha userMark=${f.includes('38;2;137;180;250')} — g differs=${f.includes('38;2;137;180;250') && !mochaUserMark}`)
952
- }
953
- record('g. workspace config effect', 'PASS', notes)
954
- } catch (e) {
955
- record('g. workspace config effect', 'FAIL', [...notes, String(e.message)])
956
- } finally {
957
- await quitClient(name)
958
- await reapHost(readLock())
959
- rmSync(ws, { recursive: true, force: true })
960
- }
961
- }
962
-
963
- const scenarioH = async () => {
964
- const notes = []
965
- const ws = mkdtempSync(join(tmpdir(), 'p6-ws-h-'))
966
- const name = 'p6h'
967
- try {
968
- newClientSession(name, ws, ROUTE ? { DSH_OPENTUI_MODEL: ROUTE } : {})
969
- await waitRendered(name)
970
- notes.push('client rendered')
971
-
972
- // bare /login → the provider directory (Select overlay; only the first
973
- // 12 catalog entries paint at once — assertions stay inside that window).
974
- // KNOWN RENDERING NUANCE (live-verified, cosmetic, pre-existing): the kit
975
- // Select's title/hint row paints BLANK in steady-state captures (the
976
- // /theme picker shows the same), so the anchors here are the provider
977
- // names — the deliverable's actual requirement — not the title string.
978
- await submitLine(name, '/login')
979
- const menu = await waitPane(
980
- name,
981
- (out) => out.includes('Amazon Bedrock') && out.includes('Anthropic') && out.includes('DeepSeek'),
982
- 20_000,
983
- )
984
- const named = ['Amazon Bedrock', 'Anthropic', 'Azure OpenAI', 'Cerebras', 'DeepSeek'].filter((p) => menu.includes(p))
985
- notes.push(`provider directory rendered: ${named.join(', ')} · title row painted=${menu.includes('log in — pick a provider')} (blank title row = known kit Select nuance)`)
986
- assert(named.length >= 3, `provider directory did not render the known provider names — capture:\n${menu.slice(-1500)}`)
987
-
988
- // esc closes the picker; editor back to idle, powerline intact
989
- sendKeys(name, 'Escape')
990
- const closed = await waitPane(name, (out) => !out.includes('Amazon Bedrock'), 10_000)
991
- assert(!closed.includes('Amazon Bedrock'), 'the provider picker did not close on esc')
992
- assert(isIdle(closed), `editor did not return to idle after esc:\n${closed.slice(-800)}`)
993
- assert(closed.includes('🧠'), 'powerline missing after esc — UI did not survive')
994
- notes.push('esc closed the picker; editor idle, powerline intact')
995
-
996
- // a second open/close cycle (proxy state-machine stability)
997
- await submitLine(name, '/login')
998
- await waitPane(name, (out) => out.includes('Anthropic'), 10_000)
999
- sendKeys(name, 'Escape')
1000
- const closed2 = await waitPane(name, (out) => !out.includes('Anthropic'), 10_000)
1001
- assert(!closed2.includes('Anthropic'), 'the provider picker did not close on esc (second cycle)')
1002
- notes.push('second /login → esc cycle clean')
1003
-
1004
- // no crash markers anywhere in the scrollback (the old crash painted
1005
- // "TypeError: Cannot access private method or accessor" exactly at the
1006
- // settingsSeam-through-the-proxy hop) — scanned BEFORE quitting so the
1007
- // scan always runs
1008
- const full = capture(name, { full: true })
1009
- assert(!/TypeError|Cannot access private|Unhandled|boot failed/i.test(full), `crash markers in the pane scrollback:\n${full.slice(0, 1200)}`)
1010
- notes.push(`scrollback crash-marker scan clean (${full.split('\n').length} lines)`)
1011
-
1012
- const q = await quitClient(name)
1013
- notes.push(`quit: ${q}`)
1014
- if (paneAlive(name)) {
1015
- const tail = capture(name, { full: true })
1016
- assert(!/TypeError|Cannot access private|Unhandled|boot failed/i.test(tail), `crash markers in the pane after quit:\n${tail.slice(0, 1200)}`)
1017
- }
1018
- record('h. /login provider directory', 'PASS', notes)
1019
- } catch (e) {
1020
- try { writeFileSync('/tmp/p6-login.txt', capture(name, { esc: true, full: true })) } catch { /* keep whatever exists */ }
1021
- record('h. /login provider directory', 'FAIL', [...notes, String(e.message)])
1022
- } finally {
1023
- await quitClient(name)
1024
- await reapHost(readLock())
1025
- rmSync(ws, { recursive: true, force: true })
1026
- }
1027
- }
1028
-
1029
- // ---------------------------------------------------------------------------
1030
- // Main.
1031
- // ---------------------------------------------------------------------------
1032
-
1033
- const main = async () => {
1034
- ownedTmuxServer = !tmuxServerWasRunning()
1035
- console.log(`e2e-client: repo=${REPO} · dshHome=${DSH_HOME} · tmux ${GEOMETRY.x}x${GEOMETRY.y}`)
1036
- const startLock = readLock()
1037
- if (startLock && pidAlive(startLock.pid)) {
1038
- console.log(`NOTE: a host is ALREADY resident (pid=${startLock.pid} port=${startLock.port}) — the gate adopts it and its teardown may idle-exit it; relaunching the TUI respawns it`)
1039
- }
1040
-
1041
- console.log('\n--- workingRoute discovery (probe before any scenario) ---')
1042
- const probe = await probeWorkingRoute()
1043
- console.log(` host: pid=${probe.hostPid} port=${probe.hostPort} adopted=${probe.adopted}`)
1044
- if (probe.ok) {
1045
- TURN_OK = true
1046
- ROUTE = probe.route
1047
- OTHER_ROUTE = probe.otherRoute
1048
- console.log(` route: ${ROUTE ? (probe.adoptedDefault ? `deployment default answers → ${ROUTE}` : `fallback selected → ${ROUTE}`) : 'a route answers but its concrete id was not resolvable — turns run without the env override'}${OTHER_ROUTE ? ` · other catalog route: ${OTHER_ROUTE}` : ''}`)
1049
- } else {
1050
- TURN_OK = false
1051
- ROUTE = null
1052
- console.log(' !! NO ROUTE ANSWERS — real turns are BLOCKED; running everything except real turns (loud, no hacks)')
1053
- for (const e of probe.errors) console.log(` ${e}`)
1054
- }
1055
-
1056
- for (const pid of hostPids()) {
1057
- if (!probe.hostPid || pid !== probe.hostPid) {
1058
- console.log(` stray host wrapper pid=${pid} — killing before the scenarios`)
1059
- await killHostTree(pid)
1060
- }
1061
- }
1062
-
1063
- await scenarioA()
1064
- await preClean('between a→b')
1065
- await scenarioB()
1066
- await preClean('between b→c')
1067
- await scenarioC()
1068
- await preClean('between c→d')
1069
- await scenarioD()
1070
- await preClean('between d→e')
1071
- await scenarioE()
1072
- await preClean('between e→f')
1073
- await scenarioF()
1074
- await preClean('between f→g')
1075
- await scenarioG()
1076
- await preClean('between g→h')
1077
- await scenarioH()
1078
- await preClean('final')
1079
-
1080
- // tmux hygiene: our sessions are already dead (every scenario quits/kills
1081
- // its panes); kill the server only when THIS run created it.
1082
- for (const s of sessionsCreated) {
1083
- if (paneAlive(s)) tmux('kill-session', '-t', s)
1084
- }
1085
- const leftovers = tmuxOut('list-sessions')
1086
- if (ownedTmuxServer) {
1087
- tmux('kill-server')
1088
- console.log('\ntmux: server killed (this run created it)')
1089
- } else if (leftovers.trim()) {
1090
- console.log(`\ntmux: pre-existing server left running with sessions:\n${leftovers.trim()}`)
1091
- }
1092
-
1093
- console.log('\n==================== e2e-client summary ====================')
1094
- const fails = scenarios.filter((s) => s.verdict.startsWith('FAIL'))
1095
- const blocked = scenarios.filter((s) => s.verdict.startsWith('BLOCKED'))
1096
- for (const s of scenarios) console.log(`${s.verdict.padEnd(28)} ${s.name}`)
1097
- const allP1 = scenarios.flatMap((s) => s.p1.map((p) => `${s.name}: ${p}`))
1098
- if (allP1.length > 0) {
1099
- console.log('\noldfox-P1 reproductions:')
1100
- for (const p of allP1) console.log(` ${p}`)
1101
- } else {
1102
- console.log('\noldfox-P1 reproductions: NONE — the known P1 triggers did not fire under this gate (narrower trigger surface than estimated)')
1103
- }
1104
- if (blocked.length > 0) {
1105
- console.log(`\n!! BLOCKED scenarios: ${blocked.map((b) => b.name).join(', ')} — environment limitation, reported loudly, nothing hacked`)
1106
- }
1107
- if (fails.length > 0) {
1108
- console.log(`\nRESULT: FAIL (${fails.length} failed / ${scenarios.length} scenarios)`)
1109
- process.exit(1)
1110
- }
1111
- if (blocked.some((b) => b.name.startsWith('f.'))) {
1112
- console.log('\nRESULT: INCOMPLETE — the acceptance scenario (f) is blocked by dead provider keys')
1113
- process.exit(1)
1114
- }
1115
- console.log(`\nRESULT: PASS (${scenarios.length - fails.length - blocked.length} pass / ${blocked.length} blocked / ${scenarios.length} total)`)
1116
- }
1117
-
1118
- main().catch((e) => {
1119
- console.error(`e2e-client: crashed: ${e.stack ?? e.message}`)
1120
- for (const s of sessionsCreated) if (paneAlive(s)) tmux('kill-session', '-t', s)
1121
- process.exit(1)
1122
- })