@aiwayds/dsh-opentui 0.27.2 → 0.28.1

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,932 +0,0 @@
1
- #!/usr/bin/env node
2
- // Full command-surface sweep (client mode) — the repeatable gate for the
3
- // "sweep every slash command + keyboard surface" audit.
4
- //
5
- // node scripts/e2e-sweep.mjs
6
- //
7
- // What it drives (everything under DSH_OPENTUI client mode, tmux 120x34,
8
- // one char per send-keys with a ~60ms gap — burst writes drop keys in
9
- // OpenTUI's input parser):
10
- // · boot + real route label on the powerline
11
- // · every TUI slash command from ShellHost's COMMANDS array (read-only
12
- // forms), each with open → render → action → close-clean → crash-scan
13
- // · the overlay pickers (/preset /model /theme /settings /agents /history
14
- // /resume /search) with item-text anchors (kit Select title
15
- // rows paint BLANK — anchor on items, never the title)
16
- // · /config bare + set + invalid-key forms; /login|/logout headless REF
17
- // forms and the PANEL flow (directory → key entry → esc), including the
18
- // keystroke-leak regression (the confirm-stage y/n must NOT type into
19
- // the blurred editor — engine-focus ghost after the menu Select unmounts)
20
- // · keyboard surfaces: slash palette (filter ↑↓ tab enter), input history
21
- // recall (↑↑ across "/" entries — the palette must NOT own the arrows),
22
- // alt+enter newline, bracketed paste into the editor, PgUp/PgDn scroll,
23
- // ctrl+t / ctrl+o dock toggles, esc stop-confirm (arm → n resume →
24
- // y abort, both without buffer residue)
25
- // · real turns ONLY where the surface needs one (stop-confirm, queue
26
- // drain, btw, history fork, viewer) via the workingRoute pattern: probe
27
- // the catalog, selectModel until a route answers, export via
28
- // DSH_OPENTUI_MODEL. No route → those items report BLOCKED loudly and
29
- // everything else still runs.
30
- //
31
- // Isolation: the whole sweep runs under a SCRATCH DSH_HOME (temp dir, mode
32
- // 700) seeded from the real home — profiles/opentui, credentials, model
33
- // store, agents/skills/themes. Nothing in this script touches the real
34
- // profile; login/logout/config/preset writes land in the scratch home.
35
- //
36
- // Skips (exit 0) when the environment cannot run it: no global dsh, no
37
- // tmux, no bun, or the opentui profile missing — CI skips; a configured
38
- // dev machine runs the full gate.
39
-
40
- import { spawn, spawnSync } from 'node:child_process'
41
- import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
42
- import { homedir, tmpdir } from 'node:os'
43
- import { dirname, join, resolve } from 'node:path'
44
- import { fileURLToPath } from 'node:url'
45
- import { connect as netConnect } from 'node:net'
46
-
47
- const REPO = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', '..')
48
- const LAUNCHER = join(REPO, 'dsh-opentui')
49
- const PROFILE = 'opentui'
50
- const REAL_HOME = process.env.DSH_HOME || join(homedir(), '.dsh')
51
- const GEOMETRY = { x: 120, y: 34 }
52
- const TYPE_GAP_MS = 60
53
- const IDLE = '提问,回车发送'
54
- const CRASH_RE = /TypeError|Cannot access private|Unhandled|boot failed/i
55
- const SESS = 'sweep'
56
- // Render-paint lag under full-sweep pacing, not logic bugs: both items verified
57
- // correct in isolation (see batch-B repros), but the strict post-type assertion
58
- // races with frame paint when the whole 68-item sweep paces the renderer.
59
- const KNOWN_STALL = ['palette filter /lo', 'alt+enter newline']
60
-
61
- const sh = (cmd, args, opts = {}) => spawnSync(cmd, args, { encoding: 'utf8', ...opts })
62
- const tmux = (...a) => sh('tmux', a)
63
- const tmuxOut = (...a) => (tmux(...a).status === 0 ? tmux(...a).stdout : '')
64
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
65
-
66
- // ---------------------------------------------------------------------------
67
- // Preflight + skip contract.
68
- // ---------------------------------------------------------------------------
69
- const preflight = () => {
70
- for (const [cmd, why] of [['dsh', 'no global dsh on PATH'], ['tmux', 'no tmux on PATH'], ['bun', 'no bun on PATH']]) {
71
- const w = sh('which', [cmd])
72
- if (w.status !== 0 || !w.stdout.trim()) return why
73
- }
74
- if (!existsSync(join(REAL_HOME, 'profiles', PROFILE))) return `profile '${PROFILE}' not provisioned under ${REAL_HOME}`
75
- if (!existsSync(LAUNCHER)) return `launcher missing: ${LAUNCHER}`
76
- return null
77
- }
78
- const SKIP = preflight()
79
- if (SKIP) {
80
- console.log(`e2e-sweep: skipped (${SKIP})`)
81
- process.exit(0)
82
- }
83
-
84
- // ---------------------------------------------------------------------------
85
- // Scratch home: temp dir (mode 700) seeded from the real profile.
86
- // ---------------------------------------------------------------------------
87
- const SWEEP_HOME = mkdtempSync(join(tmpdir(), 'dsh-sweep-home-'))
88
- chmodSync(SWEEP_HOME, 0o700)
89
- const SWEEP_WS = mkdtempSync(join(tmpdir(), 'dsh-sweep-ws-'))
90
- const seedInto = (rel) => {
91
- const from = join(REAL_HOME, rel)
92
- if (existsSync(from)) cpSync(from, join(SWEEP_HOME, rel), { recursive: true })
93
- }
94
- mkdirSync(join(SWEEP_HOME, 'profiles'), { recursive: true })
95
- cpSync(join(REAL_HOME, 'profiles', PROFILE), join(SWEEP_HOME, 'profiles', PROFILE), { recursive: true })
96
- for (const rel of ['.credentials.yaml', 'models-store.json', 'model-profiles.json', 'workspace-presets.json', 'settings.yaml', 'agents', 'skills', 'themes']) seedInto(rel)
97
-
98
- const LOCK_PATH = join(SWEEP_HOME, `opentui-host.${PROFILE}.json`)
99
- const readLock = () => {
100
- try {
101
- const raw = JSON.parse(readFileSync(LOCK_PATH, 'utf8'))
102
- return typeof raw.pid === 'number' ? raw : null
103
- } catch { return null }
104
- }
105
-
106
- /** Derive the apiKeyEnv ref for a provider id (the /login rule). */
107
- const deriveKeyRef = (provider) => `${provider.toUpperCase().replace(/[^A-Z0-9]+/g, '_')}_API_KEY`
108
-
109
- /** Register llm-pi-ai routes for every models-store provider whose derived
110
- * credential ref exists in the scratch credentials — the same shape the
111
- * /login flow writes. Best-effort: a host without the settings service
112
- * leaves the catalog as-is (the probe then tries whatever exists). */
113
- const seedRoutes = async () => {
114
- const probe = join(REPO, 'packages', 'shell', `.sweep-seed-${process.pid}.ts`)
115
- writeFileSync(probe, `
116
- import { ensureHost } from './src/client/lifecycle.ts'
117
- import { ClientConnection } from './src/client/transport.ts'
118
- import { RemoteHostSession } from './src/client/remote-host-session.ts'
119
- import { readFileSync } from 'node:fs'
120
- const home = process.env.SWEEP_HOME!
121
- const ws = process.env.SWEEP_WS!
122
- const host = await ensureHost({ profile: '${PROFILE}', idleExitSec: 0, dshHome: home })
123
- const live = new ClientConnection({ authority: host.authority, cookieHeader: host.cookieHeader })
124
- const session = new RemoteHostSession({ connection: live, cookieHeader: host.cookieHeader, cwd: ws })
125
- await session.start()
126
- const out: string[] = []
127
- try {
128
- let creds = ''
129
- try { creds = readFileSync(home + '/.credentials.yaml', 'utf8') } catch {}
130
- const store = JSON.parse(readFileSync(home + '/models-store.json', 'utf8'))
131
- const seam = (session as any).settingsSeam
132
- if (seam) {
133
- const entries = await seam.describe()
134
- const desc = Array.isArray(entries) ? entries.find((e: any) => e?.ns === 'llm-pi-ai') : undefined
135
- const providers: Record<string, unknown> = {}
136
- for (const id of Object.keys(store)) {
137
- const ref = id.toUpperCase().replace(/[^A-Z0-9]+/g, '_') + '_API_KEY'
138
- if (creds.includes(ref)) providers[id] = { apiKeyEnv: ref }
139
- }
140
- if (Object.keys(providers).length > 0) {
141
- await seam.mutate('llm-pi-ai', [{ op: 'set', path: ['providers'], value: providers }], desc?.revision)
142
- out.push('seeded:' + Object.keys(providers).join(','))
143
- }
144
- }
145
- } catch (e) { out.push('seed-error:' + String(e).slice(0, 80)) }
146
- console.log('SEED ' + JSON.stringify({ out }))
147
- session.abort(); await session.dispose(); await live.close(); process.exit(0)
148
- `)
149
- try {
150
- const r = sh('bun', [probe], { cwd: join(REPO, 'packages', 'shell'), timeout: 180_000, env: { ...process.env, SWEEP_HOME, SWEEP_WS } })
151
- const line = (r.stdout + '\n' + r.stderr).split('\n').find((l) => l.startsWith('SEED '))
152
- return line ? JSON.parse(line.slice(5)) : { out: ['no-seed-output'] }
153
- } finally {
154
- rmSync(probe, { force: true })
155
- }
156
- }
157
-
158
- // ---------------------------------------------------------------------------
159
- // tmux client drive.
160
- // ---------------------------------------------------------------------------
161
- let ownedTmuxServer = false
162
- const bootClient = async ({ modelEnv } = {}) => {
163
- tmux('kill-server')
164
- await sleep(700)
165
- const env = [`DSH_HOME=${SWEEP_HOME}`, 'DSH_OPENTUI_DEBUG=1']
166
- if (modelEnv) env.push(`DSH_OPENTUI_MODEL=${modelEnv}`)
167
- const r = tmux('new-session', '-d', '-x', String(GEOMETRY.x), '-y', String(GEOMETRY.y), '-s', SESS, '-c', SWEEP_WS,
168
- `${env.join(' ')} ${LAUNCHER} --client 2>/dev/null`)
169
- if (r.status !== 0) throw new Error('tmux boot failed: ' + r.stderr)
170
- }
171
- const capture = ({ esc = false, full = false } = {}) => {
172
- const args = ['capture-pane', '-p', '-t', SESS]
173
- if (esc) args.push('-e')
174
- if (full) args.push('-S', '-3000')
175
- return tmuxOut(...args)
176
- }
177
- const captureEsc = () => sh('tmux', ['capture-pane', '-e', '-p', '-t', SESS]).stdout
178
- const sendKeys = (...keys) => tmux('send-keys', '-t', SESS, ...keys)
179
- const typeText = async (text) => { for (const ch of text) { sendKeys('-l', ch); await sleep(TYPE_GAP_MS) } }
180
- const submit = async (text) => {
181
- const typed = async () => {
182
- await typeText(text)
183
- await sleep(300)
184
- // first-key drop guard: the parser intermittently drops the FIRST
185
- // keystroke after an idle/nudge period — a lost "/" turned "/login"
186
- // into the plain prompt "login" (a real turn). RAW verify (flat()
187
- // strips the leading "/" and would pass the broken state), clean,
188
- // retype once.
189
- if (!inputRow(capture()).includes(text)) {
190
- for (let i = 0; i < text.length + 6; i++) { sendKeys('BSpace'); await sleep(60) }
191
- await sleep(200)
192
- await typeText(text)
193
- await sleep(300)
194
- }
195
- sendKeys('Enter')
196
- }
197
- await typed()
198
- }
199
- const waitPane = async (pred, timeoutMs, everyMs = 500) => {
200
- const deadline = Date.now() + timeoutMs
201
- let last = ''
202
- while (Date.now() < deadline) {
203
- const frame = capture()
204
- // mid-redraw frames can capture EMPTY (the pane buffer cleared between
205
- // flushes) — never let an empty frame erase a good prior capture
206
- if (frame.trim().length > 0) last = frame
207
- try { if (last && pred(last)) return { ok: true, out: last } } catch { /* keep waiting */ }
208
- await sleep(everyMs)
209
- }
210
- return { ok: false, out: last }
211
- }
212
- const idle = (out) => out.includes(IDLE)
213
- const bufferEmpty = (out) => out.split('\n').some((l) => l.includes('❯') && l.includes(IDLE))
214
- const inputRow = (out) => (out.split('\n').filter((l) => l.includes('❯')).pop() ?? '').trim()
215
- /** Paint-over tolerance: OpenTUI's diff-paint can interleave fragments of
216
- * neighboring rows mid-redraw (a capture can read `turnaborted` for
217
- * "turn aborted"). Markers match on the alphanumeric-only projection. */
218
- const flat = (s) => String(s).replace(/[^a-zA-Z0-9\u4e00-\u9fff]/g, '')
219
- const has = (out, marker) => flat(out).includes(flat(marker))
220
- const hasAny = (out, markers) => markers.some((m) => has(out, m))
221
- const crashScan = (out, label) => {
222
- const m = out.match(CRASH_RE)
223
- return m ? `crash marker [${m[0]}] during ${label}` : null
224
- }
225
- const cleanBuffer = async (n = 24) => {
226
- for (let i = 0; i < n; i++) { sendKeys('BSpace'); await sleep(70) }
227
- await sleep(200)
228
- // full-load render stalls drop BACKSPACES too (batch B evidence: grouped
229
- // capture failures from frozen-pane frames) — a half-cleared buffer leaks
230
- // into the next typed command ('/preset/model'-style stuck rows). Verify
231
- // the idle row is back; one bounded re-sweep if not.
232
- for (let i = 0; i < 2 && !bufferEmpty(capture()); i++) {
233
- for (let j = 0; j < n; j++) { sendKeys('BSpace'); await sleep(70) }
234
- await sleep(200)
235
- }
236
- }
237
- /** First-key drop guard for RAW typeText bursts (palette filter, newline
238
- * draft): the parser intermittently drops the FIRST keystroke after an
239
- * idle/nudge period — the same race submit() guards. Verify the row took
240
- * the text; clean + retype once. includes() not endsWith(): the editor row
241
- * carries box-border/padding around the text. */
242
- const typeVerified = async (text) => {
243
- const typed = async () => {
244
- await typeText(text)
245
- await sleep(300)
246
- return inputRow(capture())
247
- }
248
- let row = await typed()
249
- if (!row.includes(text)) {
250
- await cleanBuffer()
251
- row = await typed()
252
- }
253
- return row
254
- }
255
- /** Repaint nudge: a torn mid-redraw row can persist on screen until its
256
- * region redraws (engine-level diff-paint; flagged in the report, not
257
- * hacked around in the client). PgUp+PgDn re-renders the transcript
258
- * window, clearing the tear so content assertions read the settled frame. */
259
- const nudge = async () => {
260
- // SIGWINCH dance: a one-row resize forces the client's FULL re-render
261
- // (PgUp/PgDn only repaints when the scroll window actually moves, and a
262
- // short transcript makes that a no-op — the tear survived it in run 4)
263
- tmux('resize-pane', '-t', SESS, '-y', '33')
264
- await sleep(500)
265
- tmux('resize-pane', '-t', SESS, '-y', '34')
266
- await sleep(600)
267
- }
268
-
269
- /** Escape an overlay until its OPEN-marker (item text visible while the
270
- * picker is up) disappears. Anchoring on the OPEN marker is essential: a
271
- * close-confirmation row that only paints after Enter gives a trivial
272
- * "gone" on the first check, and a DROPPED Escape then leaves the picker
273
- * open — every later typed command navigates it (the /preset cascade). */
274
- const closeOverlay = async (openMarker) => {
275
- const markers = Array.isArray(openMarker) ? openMarker : [openMarker]
276
- for (let i = 0; i < 4; i++) {
277
- sendKeys('Escape')
278
- const gone = await waitPane((o) => !hasAny(o, markers), 4000, 250)
279
- if (gone.ok) return true
280
- await nudge() // a torn frame keeps the picker's rows visible after close
281
- }
282
- return false
283
- }
284
- /** Escape until every overlay is gone: the editor is idle/empty again.
285
- * Overlays nest (agents list → fields → pickers), so loop on idle. */
286
- const closeAllOverlays = async () => {
287
- for (let i = 0; i < 6; i++) {
288
- sendKeys('Escape')
289
- const quiet = await waitPane((o) => bufferEmpty(o), 3000, 250)
290
- if (quiet.ok) return true
291
- await sleep(300)
292
- }
293
- return bufferEmpty(capture())
294
- }
295
- /** Stable-paint settle: poll until two consecutive captures AGREE (digits
296
- * stripped — the powerline clock/percent counters tick every second, which
297
- * would otherwise keep every frame "changed"). Empty mid-redraw frames are
298
- * skipped, not trusted. Repo law: poll for a stable frame, never fixed
299
- * sleeps ("E2E 固定 sleep 与 provider/渲染速度耦合"). */
300
- const settlePane = async (timeoutMs = 8000, everyMs = 600) => {
301
- const norm = (s) => String(s).replace(/\d+/g, '')
302
- const deadline = Date.now() + timeoutMs
303
- let prev = ''
304
- while (Date.now() < deadline) {
305
- const cur = capture()
306
- if (cur.trim().length > 0) {
307
- if (prev && norm(cur) === norm(prev)) return { open: !bufferEmpty(cur), out: cur }
308
- prev = cur
309
- }
310
- await sleep(everyMs)
311
- }
312
- const last = capture()
313
- return { open: !bufferEmpty(last), out: last }
314
- }
315
- const waitRendered = async () => {
316
- const w = await waitPane((o) => o.includes('🧠') && /dsh\(/.test(o), 45_000)
317
- if (!w.out.includes('🧠')) throw new Error('client never rendered a powerline — last capture:\n' + w.out.slice(-1200))
318
- return w.out
319
- }
320
- const quitClient = async () => {
321
- if (tmux('has-session', '-t', SESS).status !== 0) return 'gone'
322
- await submit('/quit')
323
- const deadline = Date.now() + 15_000
324
- while (Date.now() < deadline) {
325
- if (tmux('has-session', '-t', SESS).status !== 0) return 'quit'
326
- await sleep(400)
327
- }
328
- tmux('kill-session', '-t', SESS)
329
- return 'forced'
330
- }
331
- const reapHost = () => {
332
- const lock = readLock()
333
- if (!lock) return
334
- const sig = (p, s) => { try { process.kill(-p, s) } catch { try { process.kill(p, s) } catch {} } }
335
- sig(lock.pid, 'SIGTERM')
336
- const deadline = Date.now() + 6000
337
- while (Date.now() < deadline) {
338
- try { process.kill(lock.pid, 0); sleep(250) } catch { break }
339
- break
340
- }
341
- sig(lock.pid, 'SIGKILL')
342
- rmSync(LOCK_PATH, { force: true })
343
- }
344
-
345
- // ---------------------------------------------------------------------------
346
- // Working-route discovery (the e2e-client pattern, scratch-home scoped).
347
- // ---------------------------------------------------------------------------
348
- const probeWorkingRoute = async () => {
349
- const probe = join(REPO, 'packages', 'shell', `.sweep-route-${process.pid}.ts`)
350
- writeFileSync(probe, `
351
- import { ensureHost } from './src/client/lifecycle.ts'
352
- import { ClientConnection } from './src/client/transport.ts'
353
- import { RemoteHostSession } from './src/client/remote-host-session.ts'
354
- const turnOnce = (session: any, text: string) => new Promise((res) => {
355
- let done = false
356
- const finish = (err: any) => { if (!done) { done = true; res(err) } }
357
- session.turn(text, {
358
- onThinkingDelta: () => {}, onContentDelta: () => {},
359
- onTurnEnd: () => finish(undefined), onApprove: async () => false,
360
- onToolRun: () => {}, onError: (m: string) => finish(m),
361
- }).catch((e: any) => finish(String(e)))
362
- const deadline = Date.now() + 60_000
363
- const poll = setInterval(() => { if (done || Date.now() > deadline) { clearInterval(poll); finish('deadline') } }, 200)
364
- })
365
- const host = await ensureHost({ profile: '${PROFILE}', idleExitSec: 0, dshHome: process.env.SWEEP_HOME! })
366
- const live = new ClientConnection({ authority: host.authority, cookieHeader: host.cookieHeader })
367
- const session = new RemoteHostSession({ connection: live, cookieHeader: host.cookieHeader, cwd: process.env.SWEEP_WS! })
368
- await session.start()
369
- const out: any = { ok: false, route: null, tried: [] }
370
- const catalog = await session.modelCatalog(true)
371
- const candidates = catalog.groups.filter((g: any) => g.models.length > 0)
372
- for (const group of candidates) {
373
- const candidate = { provider: group.id, model: group.models[0].id }
374
- try { await session.selectModel(candidate) } catch (e) { out.tried.push(group.id + ':sel'); continue }
375
- const err = await turnOnce(session, 'say ok')
376
- out.tried.push(group.id + ':' + (err === undefined ? 'OK' : String(err).slice(0, 60)))
377
- if (err === undefined) { out.ok = true; out.route = candidate.provider + '/' + candidate.model; break }
378
- }
379
- console.log('ROUTE ' + JSON.stringify(out))
380
- session.abort(); await session.dispose(); await live.close(); process.exit(0)
381
- `)
382
- try {
383
- const r = sh('bun', [probe], { cwd: join(REPO, 'packages', 'shell'), timeout: 300_000, env: { ...process.env, SWEEP_HOME, SWEEP_WS } })
384
- const line = (r.stdout + '\n' + r.stderr).split('\n').find((l) => l.startsWith('ROUTE '))
385
- if (!line) throw new Error('route probe produced no result: ' + (r.stdout + r.stderr).slice(-400))
386
- return JSON.parse(line.slice(6))
387
- } finally {
388
- rmSync(probe, { force: true })
389
- }
390
- }
391
-
392
- // ---------------------------------------------------------------------------
393
- // Item ledger + verdicts.
394
- // ---------------------------------------------------------------------------
395
- const results = []
396
- const record = (item, verdict, notes) => {
397
- const list = notes === undefined ? [] : Array.isArray(notes) ? notes : [String(notes)]
398
- results.push({ item, verdict, notes: list })
399
- console.log(`${verdict.padEnd(9)} ${item}${list.length ? ' · ' + list.join(' · ') : ''}`)
400
- }
401
-
402
-
403
- /** pressUntil — OpenTUI's input parser drops keys (documented e2e
404
- * convention: burst writes drop keys); a single overlay-advance Enter can
405
- * vanish. Press the key until the expected stage paints (bounded). */
406
- const pressUntil = async (pred, key, tries = 3, gapMs = 1600) => {
407
- for (let i = 0; i < tries; i++) {
408
- sendKeys(key)
409
- const hit = await waitPaneN(pred, gapMs)
410
- if (hit.ok) return hit
411
- // NOTE: no repaint nudge here — a SIGWINCH mid-advance disrupts the
412
- // overlay being driven (observed: the login menu stopped advancing)
413
- }
414
- return { ok: false, out: capture() }
415
- }
416
-
417
- /** Guard: every keystroke section assumes the editor is idle (no turn
418
- * running, no overlay up). A pending turn turns typed commands into
419
- * steering and plain prompts into sends. */
420
- const ensureIdle = async (label = '') => {
421
- // a pending ask_user_question overlay parks the turn — decline it (esc)
422
- // so the settle wait below can actually converge
423
- for (let i = 0; i < 4; i++) {
424
- const cap = capture()
425
- if (hasAny(cap, ['abort this turn?', 'esc resumes'])) {
426
- sendKeys('-l', 'n') // disarm a stop-confirm the decline-esc armed
427
- await sleep(800)
428
- continue
429
- }
430
- if (!idle(cap) && hasAny(cap, ['模型提问', 'ask.title', '登录', 'choose', '选项'])) {
431
- sendKeys('Escape') // esc declines the ask; the turn keeps running
432
- await sleep(1200)
433
- continue
434
- }
435
- break
436
- }
437
- const q = await waitPane((o) => idle(o) && bufferEmpty(o), 90_000)
438
- if (!q.ok) record('ensureIdle' + (label ? ` (${label})` : ''), 'FAIL', ['editor never returned to idle — typing sections would steer/send'])
439
- return q.ok
440
- }
441
-
442
- /** waitPane + one repaint nudge + re-check (tear-tolerant content waits). */
443
- const waitPaneN = async (pred, timeoutMs, everyMs = 500) => {
444
- const first = await waitPane(pred, timeoutMs, everyMs)
445
- if (first.ok) return first
446
- await nudge()
447
- return waitPane(pred, Math.min(6000, timeoutMs), everyMs)
448
- }
449
-
450
- /** Parameterized command probe: submit → expect → crash-scan → save. */
451
- const capsDir = mkdtempSync(join(tmpdir(), 'dsh-sweep-caps-'))
452
- const expectCommand = async (name, { line, marker, closeMarker, required = true }) => {
453
- await submit(line ?? name)
454
- // marker === null → an overlay picker is expected: anything that leaves
455
- // the idle editor (the picker covers the placeholder) is the open signal
456
- const pred = typeof marker === 'string'
457
- ? (o) => has(o, marker)
458
- : Array.isArray(marker)
459
- ? (o) => hasAny(o, marker)
460
- : marker
461
- ? (o) => marker.test(o)
462
- : (o) => !idle(o)
463
- let w = await waitPane(pred, 12_000)
464
- if (!w.ok) {
465
- // the marker may be missing because the row painted torn (diff-paint
466
- // tear — engine-level, flagged) OR because the submit itself was
467
- // dropped (post-boot input races drop keys). Repaint, then re-submit
468
- // once before judging.
469
- await nudge()
470
- w = await waitPane(pred, 4_000)
471
- if (!w.ok) {
472
- await submit(line ?? name)
473
- w = await waitPane(pred, 8_000)
474
- }
475
- }
476
- const crash = crashScan(w.out + capture({ full: true }), name)
477
- const ok = w.ok && !crash
478
- record(name, ok ? 'PASS' : required ? 'FAIL' : 'CHECK', crash ? [crash] : ok ? [] : ['tail: ' + inputRow(w.out).slice(0, 60)])
479
- writeFileSync(join(capsDir, name.replace(/[^a-z0-9]+/gi, '_') + '.txt'), w.out)
480
- if (closeMarker) {
481
- const closed = await closeOverlay(closeMarker)
482
- record(name + ' [closed]', closed ? 'PASS' : 'FAIL')
483
- }
484
- return ok
485
- }
486
-
487
- // ---------------------------------------------------------------------------
488
- // Main.
489
- // ---------------------------------------------------------------------------
490
- // Seed FIRST (registers scratch-home routes for credentials-bearing
491
- // providers), THEN probe which route actually answers a turn.
492
- const SEED = await seedRoutes()
493
- const ROUTE_PROBE = await probeWorkingRoute()
494
- const ROUTE = ROUTE_PROBE.ok ? ROUTE_PROBE.route : null
495
- // a real 1x1 png for /attach
496
- writeFileSync(join(SWEEP_WS, 'sweep-1px.png'), Buffer.from(
497
- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
498
- 'base64',
499
- ))
500
- console.log(`e2e-sweep: home=${SWEEP_HOME} ws=${SWEEP_WS}`)
501
- console.log(`e2e-sweep: route=${ROUTE ?? 'NONE (turn items BLOCKED)'} · route-probe: ${ROUTE_PROBE.tried.join(' | ') || 'empty catalog'} · seed: ${SEED.out.join(',')}`)
502
-
503
- try {
504
- ownedTmuxServer = tmux('list-sessions').status !== 0
505
- await bootClient({ modelEnv: ROUTE ?? undefined })
506
- const booted = await waitRendered()
507
- record('boot + powerline route', booted.includes('🧠') ? 'PASS' : 'FAIL')
508
- await waitPane((o) => idle(o), 10_000) // editor settled before the first keystroke
509
- await sleep(1000)
510
-
511
- // ---- read-only transcript commands ----
512
- for (const item of [
513
- { name: '/help', marker: '命令列表' },
514
- { name: '/usage', marker: 'turns 0' },
515
- { name: '/hotkeys', marker: /viewer/ },
516
- { name: '/plugins', marker: /plugins|no plugins installed/ },
517
- { name: '/skills', marker: /skills \(|no skills registered/ },
518
- { name: '/session', marker: /💬/ },
519
- { name: '/repair', marker: 'no broken logs found' },
520
- { name: '/unknown-zzz', line: '/unknown-zzz', marker: 'unknown command' },
521
- { name: '/config (bare)', line: '/config', marker: /config keys:/ },
522
- { name: '/config set', line: '/config retentionDays 14', marker: 'retentionDays = 14' },
523
- { name: '/config invalid key', line: '/config nosuchkey 1', marker: /unknown config key: nosuchkey/ },
524
- { name: '/config reset', line: '/config retentionDays 0', marker: 'retentionDays = 0' },
525
- // NOTE: 'search:' was a vacuous anchor under flat() — the colon is
526
- // stripped, so it matched the /hotkeys keybinding row 'search
527
- // ctrl+alt+f' already on screen and PASSed frames where the response
528
- // row never painted. Anchor on the response row only;
529
- // expectCommand's nudge+resubmit covers dropped submits and torn rows.
530
- { name: '/search (miss)', line: '/search zzz-nohit', marker: ['no sessions matching'] },
531
- { name: '/hints toggle', line: '/hints', marker: 'key hints' },
532
- { name: '/hints untoggle', line: '/hints', marker: 'key hints' },
533
- { name: '/language cycle', line: '/language', marker: 'language' },
534
- { name: '/language restore', line: '/language', marker: 'language' },
535
- { name: '/language restore2', line: '/language', marker: 'language' },
536
- { name: '/language restore3', line: '/language', marker: 'language' },
537
- ]) await expectCommand(item.name, item)
538
-
539
- // ---- overlay pickers (item-text anchors; titles paint blank) ----
540
- // /preset dispatch is ASYNC (host RPC listPresets resolves before the
541
- // picker opens) and the stale /config row 'dock icon style: default |
542
- // minimal' collided with a 'minimal' marker — the old wait returned on
543
- // that stale frame before the picker existed, then closeAllOverlays
544
- // Escaped at nothing and the late picker leaked into /model (runs 9-11).
545
- // 'minimal' is dropped from the names; names match case-insensitively
546
- // (picker labels are registry display names); the empty-registry notice
547
- // and the overlay open-signal (idle row gone) are accepted anchors too.
548
- await submit('/preset')
549
- const presetLanded = await waitPaneN((o) =>
550
- !idle(o) ||
551
- has(o, 'no presets in the agentPresets registry') ||
552
- /standard|codemode|ptc|cordis/i.test(flat(o)), 10_000)
553
- record('/preset', presetLanded.ok ? 'PASS' : 'FAIL', presetLanded.ok ? [] : ['picker never painted (listPresets RPC hang?)'])
554
- writeFileSync(join(capsDir, '_preset.txt'), presetLanded.out)
555
- // settle BEFORE closing: poll until the pane stops changing so a
556
- // late-opening picker is actually up when we Escape (a close fired at a
557
- // pre-open frame is a silent no-op and the picker leaks onward)
558
- const presetSettled = await settlePane(8000)
559
- const presetClosed = presetSettled.open ? await closeAllOverlays() : bufferEmpty(capture())
560
- record('/preset [closed]', presetClosed ? 'PASS' : 'FAIL')
561
- // model/theme: every catalog id also sits on the powerline, so the close
562
- // check is the editor returning to its idle/empty state after escape
563
- await submit('/model')
564
- await waitPane((o) => !idle(o), 8000)
565
- sendKeys('Escape'); await sleep(400)
566
- const modelClosed = await waitPane((o) => bufferEmpty(o), 5000)
567
- record('/model picker + esc', modelClosed.ok ? 'PASS' : 'FAIL')
568
- await submit('/theme')
569
- await waitPaneN((o) => o.includes('dracula') || o.includes('catppuccin'), 8000)
570
- sendKeys('Escape'); await sleep(400)
571
- const themeClosed = await waitPane((o) => bufferEmpty(o), 5000)
572
- record('/theme picker + esc', themeClosed.ok ? 'PASS' : 'FAIL')
573
-
574
- // /agents round-trip: list → fields → esc ×2 (list + fields both close —
575
- // closeAllOverlays guards the nesting; a leftover list layer would eat
576
- // every later typed command)
577
- await submit('/agents')
578
- const ag = await waitPane((o) => o.includes('no agents in') || !idle(o), 8000)
579
- const agOpen = ag.ok && !ag.out.includes('no agents in')
580
- record('/agents list', ag.ok ? 'PASS' : 'FAIL', ag.out.includes('no agents in') ? ['no agents seeded'] : [])
581
- writeFileSync(join(capsDir, 'agents.txt'), ag.out)
582
- if (agOpen) {
583
- const fields = await pressUntil((o) => o.includes('model:') || o.includes('thinking:'), 'Enter')
584
- record('/agents fields', fields.ok ? 'PASS' : 'FAIL')
585
- }
586
- record('/agents close (all layers)', (await closeAllOverlays()) ? 'PASS' : 'FAIL')
587
-
588
- // /settings: namespaces → keys → esc all
589
- await submit('/settings')
590
- const st = await waitPaneN((o) => o.includes('revision') || o.includes('no top-level'), 8000)
591
- record('/settings namespaces', st.ok ? 'PASS' : 'FAIL')
592
- if (st.ok) {
593
- // the keys view is a kit Select — its TITLE ('settings: <ns>') paints
594
- // BLANK (kit title law), so that anchor can never match on its own.
595
- // The stage announces itself through its item rows and, once an
596
- // advance Enter selects the first key, the read-only notice
597
- // '<ns>.<key> = … — edit via /settings-edit …' (present in every
598
- // recorded run's capture; a zero-key namespace → 'no top-level keys').
599
- const keys = await pressUntil((o) => has(o, 'edit via /settings-edit') || o.includes('no top-level keys') || o.includes('settings: '), 'Enter')
600
- const keysOpen = keys.ok || !idle(capture()) // kit Select title rows paint blank — overlay-up taken as open
601
- record('/settings keys', keysOpen ? 'PASS' : 'CHECK')
602
- writeFileSync(join(capsDir, 'settings_keys.txt'), keys.out)
603
- await closeAllOverlays()
604
- }
605
-
606
- // ---- login PANEL flow + keystroke-leak regression (scratch home) ----
607
- await ensureIdle('login')
608
- await submit('/login')
609
- const dirPainted = (o) => has(o, 'Amazon Bedrock') && has(o, 'Anthropic')
610
- let menu = await waitPaneN(dirPainted, 12_000)
611
- if (!menu.ok) {
612
- // dropped-slash dispatch: '/login' reached the model as a plain prompt
613
- // and a REAL turn started (run 10 capture: ask_user_question overlay +
614
- // 运行中 editor instead of the provider directory). Recover ONLY that
615
- // signature — decline the ask, wait the turn out, resubmit once. An
616
- // open-but-unmatched menu is NOT retried (resubmitting into a picker
617
- // would navigate it).
618
- const wrongTurn = capture()
619
- if (wrongTurn.includes('运行中') || hasAny(wrongTurn, ['abort this turn?', 'ask_user_question', '模型提问'])) {
620
- await ensureIdle('login-retry')
621
- await cleanBuffer()
622
- await submit('/login')
623
- menu = await waitPaneN(dirPainted, 12_000)
624
- }
625
- }
626
- writeFileSync(join(capsDir, 'login_menu.txt'), menu.out)
627
- record('/login provider directory', menu.ok ? 'PASS' : 'FAIL')
628
- if (menu.ok) {
629
- const entry = await pressUntil((o) => has(o, 'API key for'), 'Enter') // first catalog provider → key entry
630
- record('/login key entry stage', entry.ok ? 'PASS' : 'FAIL')
631
- await typeText('sweep-probe-key')
632
- await sleep(400)
633
- const typed = capture()
634
- const entryLeak = /❯\s*s/.test(inputRow(typed))
635
- record('LEAK-REG login entry — no editor residue', entryLeak ? 'FAIL (leak)' : 'PASS')
636
- writeFileSync(join(capsDir, 'login_entry.txt'), typed)
637
- sendKeys('Escape'); await sleep(400)
638
- sendKeys('Escape'); await sleep(400)
639
- const closed = await waitPane((o) => !o.includes('API key for'), 5000)
640
- record('/login panel esc close', closed.ok ? 'PASS' : 'FAIL')
641
- // FIX C: the editor must receive typing again after the panel closed
642
- await typeText('focusprobe')
643
- await sleep(300)
644
- const focusBack = /focusprobe/.test(inputRow(capture()))
645
- record('LEAK-REG editor refocused after login close', focusBack ? 'PASS' : 'FAIL')
646
- await cleanBuffer()
647
- await closeAllOverlays()
648
- }
649
-
650
- await submit('/logout')
651
- const lmenu = await waitPane((o) => has(o, 'no subscribed') || has(o, 'log out'), 12_000)
652
- const lmenuOpen = lmenu.ok && !lmenu.out.includes('no subscribed')
653
- record('/logout menu', lmenu.ok ? 'PASS' : 'FAIL', [lmenu.out.includes('no subscribed') ? 'nothing subscribed (menu path still verified)' : ''])
654
- if (lmenuOpen) {
655
- const confirm = await pressUntil((o) => has(o, 'y confirm'), 'Enter')
656
- record('/logout confirm stage', confirm.ok ? 'PASS' : 'FAIL')
657
- if (confirm.ok) {
658
- sendKeys('-l', 'n') // resume — do NOT commit (keeps the seeded route for the turn items)
659
- await sleep(500)
660
- const afterN = capture()
661
- const nLeak = /╰❯─n|│❯ n/.test(afterN)
662
- record('LEAK-REG logout confirm n — no residue', nLeak ? 'FAIL (leak)' : 'PASS')
663
- writeFileSync(join(capsDir, 'logout_confirm.txt'), afterN)
664
- }
665
- await closeAllOverlays()
666
- }
667
-
668
- // ---- keyboard surfaces ----
669
- await ensureIdle('keyboard')
670
- // slash palette: filter + arrows + tab
671
- // first-key-drop guard (typeVerified): a dropped '/' leaves plain 'lo'
672
- // typed as a draft and the palette never opens
673
- const loRow = await typeVerified('/lo')
674
- let cap = capture()
675
- record('palette filter /lo', loRow.includes('/lo') && hasAny(cap, ['set an api key', 'remove an api key']) ? 'PASS' : 'FAIL')
676
- sendKeys('Down'); await sleep(200)
677
- sendKeys('Down'); await sleep(200)
678
- sendKeys('Up'); await sleep(200)
679
- sendKeys('Tab'); await sleep(300)
680
- cap = capture()
681
- record('palette tab completes', hasAny(inputRow(cap), ['login', 'logout']) ? 'PASS' : 'FAIL')
682
- await cleanBuffer()
683
-
684
- // history recall across "/" entries
685
- await submit('/hotkeys')
686
- await waitPane((o) => o.includes('scrollUp'), 8000)
687
- await submit('/usage')
688
- await waitPaneN((o) => o.includes('turns 0'), 8000)
689
- cap = capture()
690
- record('history: buffer empty after submit', bufferEmpty(cap) ? 'PASS' : 'FAIL')
691
- sendKeys('Up'); await sleep(400)
692
- cap = capture()
693
- record('history ↑ #1 → /usage', /\/usage/.test(inputRow(cap)) ? 'PASS' : 'FAIL')
694
- sendKeys('Up'); await sleep(400)
695
- cap = capture()
696
- record('LEAK-REG history ↑ #2 → /hotkeys (palette not owning arrows)', /hotkeys/.test(inputRow(cap)) ? 'PASS' : 'FAIL')
697
- writeFileSync(join(capsDir, 'history_up2.txt'), cap)
698
- sendKeys('Down'); await sleep(350)
699
- const beforeDown2 = inputRow(capture())
700
- sendKeys('Down'); await sleep(350)
701
- // a dropped/stalled second ↓ leaves the recalled row in place — require
702
- // the input row to actually CHANGE (repaint proof) AND read empty before
703
- // judging; re-press bounded (Down at the empty draft is a no-op)
704
- let ddOk = false
705
- let ddOut = ''
706
- for (let i = 0; i < 5 && !ddOk; i++) {
707
- const cur = capture()
708
- if (inputRow(cur) !== beforeDown2 && bufferEmpty(cur)) { ddOk = true; ddOut = cur; break }
709
- sendKeys('Down'); await sleep(400)
710
- }
711
- record('history ↓↓ → draft empty', ddOk ? 'PASS' : 'FAIL')
712
-
713
- // alt+enter newline
714
- await typeVerified('sweep line one') // first-key-drop guard (batch B)
715
- sendKeys('M-Enter'); await sleep(250)
716
- await typeText('line two')
717
- await sleep(300)
718
- cap = capture()
719
- record('alt+enter newline', /sweep line one/.test(cap) && /line two/.test(cap) ? 'PASS' : 'FAIL')
720
- await cleanBuffer()
721
-
722
- // bracketed paste into the editor
723
- sh('tmux', ['set-buffer', '-b', 'sweepbuf', '--', 'sweep-paste-xyz'])
724
- sh('tmux', ['paste-buffer', '-b', 'sweepbuf', '-t', SESS])
725
- await sleep(600)
726
- cap = capture()
727
- record('paste into editor', /sweep-paste-xyz/.test(inputRow(cap)) ? 'PASS' : 'FAIL')
728
- await cleanBuffer()
729
-
730
- // ---- real-turn surfaces (need a working route) ----
731
- if (ROUTE) {
732
- await ensureIdle('turns')
733
- // /attach: the image rides the NEXT message — give it its own throwaway
734
- // turn so it cannot pollute later assertions
735
- await submit('/attach ' + join(SWEEP_WS, 'sweep-1px.png'))
736
- const att = await waitPaneN((o) => has(o, 'attached'), 8000)
737
- record('/attach (1px png)', att.ok ? 'PASS' : 'FAIL')
738
- await submit('reply with only the word: ack')
739
- const ack = await waitPane((o) => idle(o) && flat(o).includes('ack'), 90_000)
740
- record('/attach image turn', ack.ok ? 'PASS' : 'CHECK', ['ack row painted'])
741
-
742
- await submit('reply with the single word sweepok and nothing else')
743
- let t = await waitPane((o) => idle(o) && flat(o).includes('sweepok'), 90_000)
744
- if (!t.ok) {
745
- await submit('answer with exactly one word: sweepok')
746
- t = await waitPane((o) => idle(o) && flat(o).includes('sweepok'), 90_000)
747
- }
748
- // mangle-tolerant: any non-echo row mentioning the reply token after idle
749
- const replyRow = t.out.split('\n').find((l) => !l.includes('❯') && !l.includes('●') && flat(l).includes('sweepok'))
750
- record('turn: real reply', replyRow !== undefined || flat(t.out).includes('sweepok') ? 'PASS' : 'FAIL')
751
- writeFileSync(join(capsDir, 'turn_reply.txt'), t.out)
752
-
753
- // esc stop-confirm: arm → n → y, no residue either way
754
- await submit('count from 1 to 8, one number per line, nothing else, no tools')
755
- const busy = await waitPane((o) => !idle(o), 20_000)
756
- record('turn: slow turn busy', !idle(busy.out) ? 'PASS' : 'FAIL')
757
- sendKeys('Escape'); await sleep(500)
758
- cap = capture()
759
- record('stop-confirm arms on esc', hasAny(cap, ['abort this turn?', 'esc resumes']) ? 'PASS' : 'FAIL')
760
- writeFileSync(join(capsDir, 'stop_armed.txt'), cap)
761
- sendKeys('-l', 'n'); await sleep(500)
762
- cap = capture()
763
- const nLeak = /╰❯─n|│❯ n/.test(cap)
764
- record('LEAK-REG stop n resumes — no residue', !hasAny(cap, ['abort this turn?', 'esc resumes']) && !nLeak ? 'PASS' : 'FAIL (leak)')
765
- await waitPane((o) => idle(o), 120_000)
766
- await cleanBuffer()
767
- await submit('count from 1 to 8 again, one number per line, no tools')
768
- await waitPane((o) => !idle(o), 20_000)
769
- sendKeys('Escape'); await sleep(500)
770
- sendKeys('-l', 'y'); await sleep(700)
771
- cap = capture()
772
- const yLeak = /╰❯─y|│❯ y/.test(cap)
773
- record('stop y aborts — no residue', hasAny(cap, ['turn aborted', 'aborted']) && !yLeak ? 'PASS' : 'FAIL (leak or no abort)')
774
- writeFileSync(join(capsDir, 'stop_y.txt'), cap)
775
- await waitPane((o) => idle(o), 20_000)
776
- await cleanBuffer()
777
-
778
- // ctrl+G viewer during a running subagent turn (best-effort: the rail
779
- // clears 1s after every child settles, so the window is live-only)
780
- await submit('use the minimal-subagent subagent: ask it to reply with the word childok, then tell me its reply. no other tools.')
781
- let viewerTried = false
782
- for (let i = 0; i < 40 && !viewerTried; i++) {
783
- cap = capture()
784
- if (!idle(cap) && /minimal|subagent/i.test(cap)) {
785
- sendKeys('C-g'); await sleep(500)
786
- viewerTried = true
787
- }
788
- await sleep(1000)
789
- }
790
- cap = capture()
791
- if (cap.includes('pick to view transcript')) {
792
- record('ctrl+G mid-turn → child picker', 'PASS')
793
- sendKeys('Enter'); await sleep(700)
794
- cap = capture()
795
- record('ctrl+G viewer shows child transcript', cap.includes('esc back') ? 'PASS' : 'CHECK')
796
- writeFileSync(join(capsDir, 'viewer_body.txt'), cap)
797
- sendKeys('Escape'); await sleep(400)
798
- } else {
799
- record('ctrl+G mid-turn → child picker', 'CHECK', ['rail window missed (child settled before ctrl+G); empty-state verified: ' + cap.includes('no subagents yet')])
800
- }
801
- await waitPane((o) => idle(o), 180_000)
802
- await cleanBuffer()
803
-
804
- // /resume picker + resume replay
805
- await submit('/resume')
806
- const sess = await waitPane((o) => !idle(o), 10_000)
807
- cap = capture()
808
- record('/resume picker lists stored', /sweepok|count|reply with/.test(cap) ? 'PASS' : 'FAIL')
809
- if (sess.ok) {
810
- await pressUntil((o) => hasAny(o, ['resumed', '已恢复', '已挂载']), 'Enter', 2, 2500)
811
- cap = capture({ full: true })
812
- record('/resume resume replays rows', /resumed|已恢复|已挂载/.test(cap) ? 'PASS' : 'CHECK')
813
- await submit('/new'); await waitPane((o) => idle(o), 8000)
814
- }
815
-
816
- // /search hit overlay
817
- await submit('/search sweepok')
818
- await sleep(1500)
819
- cap = capture()
820
- const searchOpen = cap.includes('search:') || cap.includes('no sessions matching')
821
- record('/search hit', searchOpen ? 'PASS' : 'CHECK')
822
- if (searchOpen && !cap.includes('no sessions matching')) { sendKeys('Escape'); await sleep(400) }
823
-
824
- // /queue: enqueue mid-turn, drains after the turn settles
825
- await submit('reply with the single word: qdrain')
826
- await waitPane((o) => !idle(o), 20_000)
827
- await submit('/queue sweep-queued')
828
- const q1 = await waitPaneN((o) => has(o, 'queued'), 8000)
829
- cap = capture()
830
- record('/queue enqueue mid-turn', q1.ok ? 'PASS' : 'FAIL')
831
- const drained = await waitPane((o) => idle(o), 120_000)
832
- await waitPane((o) => idle(o) && /sweep-queued/.test(o), 90_000)
833
- cap = capture({ full: true })
834
- record('queue drains after the turn', /sweep-queued/.test(cap) ? 'PASS' : 'CHECK')
835
-
836
- // /btw side question (overlay only, never the transcript)
837
- await submit('/btw what is 2+2? answer with just the number')
838
- const btw = await waitPane((o) => o.includes('btw') && /A: ?.*4|4/.test(o), 60_000)
839
- record('/btw side answer', btw.ok ? 'PASS' : 'CHECK')
840
- await waitPane((o) => idle(o), 30_000)
841
-
842
- // /login|/logout headless REF forms (locale-proof anchors: zh-CN rows
843
- // are 凭据 … 已保存 / 已移除)
844
- await submit('/login sweep_probe_ref sk-sweep-probe')
845
- const logined = await waitPane((o) => o.includes('sweep_probe_ref') && /已保存|saved|subscribed|stored/.test(o), 10_000)
846
- record('/login REF KEY (headless)', logined.ok ? 'PASS' : 'FAIL')
847
- await submit('/logout sweep_probe_ref')
848
- const logouted = await waitPane((o) => o.includes('sweep_probe_ref') && /已移除|removed|unsubscribed/.test(o) && idle(o), 10_000)
849
- record('/logout REF (headless)', logouted.ok ? 'PASS' : 'FAIL')
850
-
851
- // /history fork (needs a completed turn): picker lists turns, enter forks
852
- await submit('/history')
853
- const hist = await waitPane((o) => !idle(o), 10_000)
854
- cap = capture()
855
- if (cap.includes('no completed turns yet')) {
856
- record('/history fork', 'CHECK', ['no completed turns yet (turn row missing)'])
857
- sendKeys('Escape'); await sleep(300)
858
- } else {
859
- const pickerRows = cap.split('\n').filter((l) => l.includes('fork before this turn') || l.includes('分叉点')).length
860
- record('/history picker lists turns', pickerRows > 0 ? 'PASS' : 'FAIL')
861
- writeFileSync(join(capsDir, 'history_picker.txt'), cap)
862
- sendKeys('Enter'); await sleep(2500)
863
- cap = capture({ full: true })
864
- record('/history fork applied (⑂ boundary marker)', /forked at turn boundary|⑂/.test(cap) ? 'PASS' : 'CHECK')
865
- writeFileSync(join(capsDir, 'history_forked.txt'), cap)
866
- await submit('/new'); await waitPane((o) => idle(o), 8000)
867
- }
868
-
869
- // /tail: watch the newest stored session live (read-only 2s poll)
870
- try {
871
- const sessDir = join(SWEEP_HOME, 'sessions')
872
- const newest = readdirSync(sessDir).filter((f) => !f.startsWith('.')).sort().pop()
873
- const sid = (newest ?? '').replace(/\.jsonl(\.zst)?$/, '')
874
- if (sid) {
875
- await submit('/tail ' + sid.slice(0, 8))
876
- const tail = await waitPaneN((o) => hasAny(o, ['watching', 'usage: /tail', 'tail:']), 12_000)
877
- record('/tail sessionId', tail.ok ? 'PASS' : 'FAIL', ['tail: ' + (tail.out.split('\n').find((l) => hasAny(l, ['watching', 'tail:'])) ?? '').trim().slice(0, 60)])
878
- writeFileSync(join(capsDir, 'tail.txt'), tail.out)
879
- if (hasAny(tail.out, ['watching'])) {
880
- await submit('/new') // /new stops the tail
881
- await waitPane((o) => idle(o), 8000)
882
- }
883
- } else {
884
- record('/tail sessionId', 'CHECK', ['no stored session files in the scratch home'])
885
- }
886
- } catch { record('/tail sessionId', 'CHECK', ['sessions dir unreadable']) }
887
- } else {
888
- for (const item of ['turn: real reply', 'stop-confirm arm/n/y', '/resume resume', '/search hit', '/queue drain', '/btw', '/history fork']) {
889
- record(item, 'BLOCKED', ['no route answers (probe: ' + (ROUTE_PROBE.tried.join(' | ') || 'empty') + ')'])
890
- }
891
- }
892
-
893
- // ---- /reload (works without a route) ----
894
- await ensureIdle('reload')
895
- const lockBefore = readLock()
896
- await submit('/reload')
897
- const reloaded = await waitPane((o) => o.includes('plugins reloaded') || o.includes('reload failed'), 90_000)
898
- record('/reload', reloaded.out.includes('plugins reloaded') ? 'PASS' : 'FAIL')
899
- await sleep(3000)
900
- const lockAfter = readLock()
901
- record('/reload same-port restart', lockBefore && lockAfter && lockAfter.port === lockBefore.port && lockAfter.pid !== lockBefore.pid ? 'PASS' : 'CHECK', `pid ${lockBefore?.pid}→${lockAfter?.pid}`)
902
- await submit('/usage')
903
- const back = await waitPane((o) => o.includes('turns'), 10_000)
904
- record('carrier reconnected after /reload', back.ok ? 'PASS' : 'FAIL')
905
-
906
- // ---- final crash scan ----
907
- const full = capture({ full: true })
908
- const crash = crashScan(full, 'final scrollback')
909
- record('final crash-scan (full scrollback)', crash ? 'FAIL' : 'PASS', crash ? [crash] : [`${full.split('\n').length} lines`])
910
- writeFileSync(join(capsDir, 'final_full.txt'), full)
911
- } catch (e) {
912
- record('sweep', 'FAIL', [String(e.message).slice(0, 300)])
913
- } finally {
914
- await quitClient().catch(() => {})
915
- reapHost()
916
- tmux('kill-server')
917
- const fails = results.filter((r) => r.verdict === 'FAIL')
918
- const blocked = results.filter((r) => r.verdict === 'BLOCKED')
919
- console.log('\n==================== e2e-sweep summary ====================')
920
- for (const r of results) {
921
- const label = r.verdict === 'FAIL' && KNOWN_STALL.includes(r.item) ? 'KNOWN-STALL' : r.verdict
922
- console.log(`${label.padEnd(11)} ${r.item}`)
923
- }
924
- console.log(`\ncaptures: ${capsDir}`)
925
- console.log(`scratch home (left for inspection): ${SWEEP_HOME}`)
926
- if (fails.length > 0) {
927
- console.log(`\nRESULT: FAIL (${fails.length} failed / ${results.length} items)`)
928
- process.exit(1)
929
- }
930
- console.log(`\nRESULT: PASS (${results.length - blocked.length} pass / ${blocked.length} blocked / ${results.length} items)`)
931
- if (blocked.length > 0) process.exit(2) // blocked ≠ green: dead provider keys are an environment fact, reported loudly
932
- }