@mobius-os/mobius 0.3.53 → 0.3.55

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.
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Reconnect regression — "TUI 输入经常显示两次" (input often renders twice).
3
+ *
4
+ * Root cause: the optimistic `pendingUser` placeholder is cleared on the live
5
+ * `entries` path but NOT when the same message is delivered via a reconnect's
6
+ * history reconciliation. Behind a reverse proxy (nginx idle timeout) the SSE
7
+ * stream drops mid-turn and auto-reconnects; the reconnect's stateless 对账
8
+ * (① groups → ② refetch of version-changed groups) picks up the just-sent user
9
+ * message, so it lands in `entries` while `pendingUser` is still set, and the
10
+ * user's input is shown twice. If the whole turn finished while disconnected, no
11
+ * live entry ever arrives to clear the placeholder, so the duplication persists
12
+ * until the next send.
13
+ *
14
+ * This test drops the SSE stream right after the user sends "good" and has the
15
+ * reconnect's reconciliation deliver that user entry, then asserts "good" is
16
+ * rendered exactly once. Without the retire-on-reconcile fix it renders twice.
17
+ *
18
+ * Run: npm run test:reconnect
19
+ */
20
+ import os from 'node:os'
21
+ import path from 'node:path'
22
+ import fs from 'node:fs'
23
+
24
+ const TMP_HOME = fs.mkdtempSync(path.join(os.tmpdir(), 'mobius-tui-reconnect-'))
25
+ process.env.MOBIUS_TUI_HOME = TMP_HOME
26
+
27
+ import React from 'react'
28
+ import { render } from 'ink-testing-library'
29
+ import { App } from '../src/App.js'
30
+
31
+ const delay = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))
32
+ const RS: any = (globalThis as any).ReadableStream
33
+ const enc = new TextEncoder()
34
+ let sseController: any = null
35
+
36
+ function json(body: unknown, status = 200) {
37
+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
38
+ }
39
+
40
+ let pass = 0, fail = 0
41
+ function ok(c: boolean, m: string) { c ? (pass++, console.log(` ✓ ${m}`)) : (fail++, console.error(` ✗ ${m}`)) }
42
+
43
+ const PID = 'proj-1', IID = 'issue-1', SID = 'sess-1'
44
+ let connectCount = 0
45
+ // agent-history mock 状态: 一个组, 发消息后 version 抬升并带上该条 user 条目.
46
+ // 重连的 stateless 对账 (① groups → version 变了 → ② 整组重拉) 会把它补进
47
+ // transcript — 这是旧 "history 回放" 的协议等价物.
48
+ let groupVersion = 0
49
+ let groupEntries: any[] = []
50
+
51
+ function mockFetch(url: string, init?: RequestInit): Response {
52
+ // ── SSE: a fresh stream per connect. Live entries stay silent; the only
53
+ // delivery path for the sent turn is the reconnect's ①② reconciliation. ──
54
+ if (url.includes('/events')) {
55
+ ++connectCount
56
+ return new Response(new RS({
57
+ start(c: any) {
58
+ sseController = c
59
+ c.enqueue(enc.encode('event: subscribed\ndata: {"event":"subscribed"}\n\n'))
60
+ },
61
+ }), { status: 200, headers: { 'content-type': 'text/event-stream' } })
62
+ }
63
+ const method = init?.method ?? 'GET'
64
+ if (url.endsWith(`/api/sessions/${SID}/groups`)) {
65
+ return json({
66
+ session_version: groupVersion,
67
+ groups: groupEntries.length
68
+ ? [{ id: 'g1', seq: 1, opener_ts: null, user_summary: 'good', version: groupVersion, entry_count: groupEntries.length }]
69
+ : [],
70
+ })
71
+ }
72
+ if (url.includes(`/api/sessions/${SID}/groups/`)) {
73
+ return json({ group_id: 'g1', version: groupVersion, entries: groupEntries })
74
+ }
75
+ if (url.endsWith('/api/auth/config')) return json({ password_required: false })
76
+ if (url.endsWith('/api/auth/me')) return json({ id: 'tester', display_name: 'Test User', role: 'admin', work_dir: '/tmp' })
77
+ if (url.endsWith('/api/auth/login')) return json({ token: 'mock-jwt-token', user: { id: 'tester', display_name: 'Test User', role: 'admin' } })
78
+ // aimux bridge probe — satisfy it so ensureSession doesn't loop for 8s.
79
+ if (url.includes('/aimux_bridge/api/remotes/') && url.includes('/connection')) {
80
+ const m = url.match(/remotes\/([^/]+)\/connection/)
81
+ return json({ identifier: m ? decodeURIComponent(m[1]) : 'x', event_stream_connected: true })
82
+ }
83
+ if (url.includes('/sessions') && url.includes('/issues') && method === 'POST') return json({ session_id: SID })
84
+ if (url.includes('/sessions') && url.includes('/issues') && method === 'GET') return json([])
85
+ // Sending a message: persist it into the history store (version bump), then DROP
86
+ // the live stream so the only delivery path is the reconnect's reconciliation
87
+ // (the exact scenario that used to double-render).
88
+ if (url.endsWith('/messages') && method === 'POST') {
89
+ groupEntries = [{ type: 'user', uuid: 'user-good-1', message: { role: 'user', content: 'good' } }]
90
+ groupVersion = 1
91
+ setTimeout(() => { try { sseController?.close() } catch { /* ignore */ } }, 150)
92
+ return json({ ok: true, session_id: SID, turn_number: 1 })
93
+ }
94
+ if (url.endsWith(`/api/sessions/${SID}/status`)) return json({ session_id: SID, alive: true, working: false })
95
+ if (url.includes('/api/projects/') && url.includes('/issues') && method === 'POST') return json({ id: IID, project_id: PID, title: '命令行任务' })
96
+ if (url.includes('/api/projects/') && url.includes('/issues') && method === 'GET') return json([])
97
+ if (url.includes('/api/projects') && method === 'GET') return json([{ id: PID, name: '已有项目甲' }])
98
+ if (url.endsWith('/api/projects') && method === 'POST') return json({ id: PID, name: '测试项目PTY' })
99
+ if (url.includes('/sessions/model-options')) return json([{ key: 'codex', label: 'GPT-5.5', title: 'GPT-5.5', sub: 'Codex', backend: 'tmux-codex' }])
100
+ if (url.includes('/sessions/default-model')) return json({ model: 'codex' })
101
+ if (url.includes('/skills')) return json([])
102
+ if (url.includes('/memories')) return json([])
103
+ return json({ error: `unmocked ${method} ${url}` }, 404)
104
+ }
105
+
106
+ async function waitFor(lastFrame: () => string | undefined, needle: string, timeoutMs = 6000) {
107
+ for (let i = 0; i < timeoutMs / 50; i++) {
108
+ if ((lastFrame() ?? '').includes(needle)) return true
109
+ await delay(50)
110
+ }
111
+ return false
112
+ }
113
+
114
+ /** Count non-overlapping occurrences of needle in s (after stripping ANSI codes). */
115
+ function countOccur(s: string, needle: string): number {
116
+ const clean = s.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '')
117
+ let n = 0, i = 0
118
+ while ((i = clean.indexOf(needle, i)) !== -1) { n++; i += needle.length }
119
+ return n
120
+ }
121
+
122
+ async function main() {
123
+ fs.writeFileSync(path.join(TMP_HOME, 'login.json'), JSON.stringify({
124
+ server: 'http://mock.local', username: 'tester', token: 'mock-jwt-token',
125
+ user: { id: 'tester', display_name: 'Test User', role: 'admin' },
126
+ }))
127
+ const realFetch = globalThis.fetch
128
+ globalThis.fetch = ((u: any, init?: any) => mockFetch(String(u), init)) as unknown as typeof fetch
129
+
130
+ console.log('\n[RECONNECT] input-not-duplicated regression (mocked backend)\n')
131
+ const { stdin, lastFrame, unmount } = render(React.createElement(App))
132
+
133
+ try {
134
+ // ── boot through the prep wizard into chat (same drive as flow.test) ─────────
135
+ ok(await waitFor(lastFrame, '选择当前路径的绑定项目'), 'booted into project picker')
136
+ stdin.write('\r'); await delay(120)
137
+ ok(await waitFor(lastFrame, '项目名称'), 'project create wizard opened')
138
+ stdin.write('测试项目PTY'); await delay(120)
139
+ stdin.write('\r'); await delay(300)
140
+ ok(await waitFor(lastFrame, '创建新任务'), 'issue picker shown')
141
+ stdin.write('\r'); await delay(120)
142
+ ok(await waitFor(lastFrame, '输入任务名称'), 'issue name wizard opened')
143
+ stdin.write('命令行任务'); await delay(120)
144
+ stdin.write('\r'); await delay(300)
145
+ ok(await waitFor(lastFrame, '选择模型'), 'model picker shown')
146
+ stdin.write('\r'); await delay(250)
147
+ ok(await waitFor(lastFrame, '选择回复语言'), 'language picker shown')
148
+ stdin.write('\r'); await delay(400)
149
+ ok(await waitFor(lastFrame, '输入问题'), 'entered chat')
150
+
151
+ // ── the bug: send "good", SSE drops, reconnect replays it via history ───────
152
+ connectCount = 0 // reset so the post-send reconnect is "connect 2"
153
+ stdin.write('good'); await delay(120)
154
+ stdin.write('\r')
155
+ // The user's message shows instantly via the optimistic placeholder, so do NOT
156
+ // gate on "good" appearing — gate on the reconnect actually firing (connect 2),
157
+ // which is what replays history and (without the fix) double-renders the input.
158
+ let reconnected = false
159
+ for (let i = 0; i < 8000 / 50; i++) {
160
+ if (connectCount >= 2) { reconnected = true; break }
161
+ await delay(50)
162
+ }
163
+ ok(reconnected, 'SSE dropped and reconnected after the send')
164
+ await delay(500) // let the reconnect's history replay render
165
+
166
+ const frame = lastFrame() ?? ''
167
+ const occurrences = countOccur(frame, 'good')
168
+ console.log(` i occurrences of "good" in frame: ${occurrences}`)
169
+ ok(occurrences === 1, `user input rendered exactly once (got ${occurrences}; would be 2 without the fix)`)
170
+ if (occurrences !== 1) {
171
+ console.log('── frame ──\n' + frame.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '').replace(/\n{3,}/g, '\n\n').trim())
172
+ }
173
+ } finally {
174
+ unmount()
175
+ globalThis.fetch = realFetch
176
+ }
177
+
178
+ try { fs.rmSync(TMP_HOME, { recursive: true, force: true }) } catch { /* ignore */ }
179
+ console.log(`\n==== RECONNECT RESULT: ${pass} passed, ${fail} failed ====\n`)
180
+ process.exit(fail === 0 ? 0 : 1)
181
+ }
182
+
183
+ main().catch((e) => { console.error('FATAL', e); process.exit(2) })
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Regression test: when ~/.mobius already has a bound project + an issue whose
3
+ * preferences are all configured, the app must boot STRAIGHT into chat (not get
4
+ * stuck on a bare prep header, and not need to re-run the wizard).
5
+ *
6
+ * Run: npm run test:resume
7
+ */
8
+ import os from 'node:os'
9
+ import path from 'node:path'
10
+ import fs from 'node:fs'
11
+
12
+ const TMP_HOME = fs.mkdtempSync(path.join(os.tmpdir(), 'mobius-tui-resume-'))
13
+ process.env.MOBIUS_TUI_HOME = TMP_HOME
14
+
15
+ import React from 'react'
16
+ import { render } from 'ink-testing-library'
17
+ import { App } from '../src/App.js'
18
+
19
+ const delay = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))
20
+ const CWD = process.cwd()
21
+ const PID = 'proj-r', IID = 'issue-r'
22
+ let pass = 0, fail = 0
23
+ function ok(c: boolean, m: string) { c ? (pass++, console.log(` ✓ ${m}`)) : (fail++, console.error(` ✗ ${m}`)) }
24
+
25
+ function json(body: unknown, status = 200) {
26
+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
27
+ }
28
+ function mockFetch(url: string, init?: RequestInit): Response {
29
+ const method = init?.method ?? 'GET'
30
+ if (url.endsWith('/api/auth/me')) return json({ id: 'tester', display_name: 'x', role: 'admin' })
31
+ if (url.includes('/api/projects') && method === 'GET' && !url.includes('issues')) return json([{ id: PID, name: '绑定项目' }])
32
+ if (url.includes('/issues') && method === 'GET') return json([{ id: IID, project_id: PID, title: '已配置任务' }])
33
+ if (url.includes('/sessions/model-options')) return json([{ key: 'codex', label: 'GPT', title: 'GPT', sub: '', backend: 'x' }])
34
+ return json({ error: `unmocked ${method} ${url}` }, 404)
35
+ }
36
+
37
+ async function main() {
38
+ // Pre-seed: token + cwd→project binding + issue with all prefs done.
39
+ fs.writeFileSync(path.join(TMP_HOME, 'login.json'), JSON.stringify({
40
+ server: 'http://mock.local', username: 'tester', token: 'tok', user: { id: 'tester', display_name: 'x', role: 'admin' },
41
+ }))
42
+ fs.writeFileSync(path.join(TMP_HOME, 'dir2project.json'), JSON.stringify({ [CWD]: PID }))
43
+ fs.writeFileSync(path.join(TMP_HOME, 'dir2project_preference.json'), JSON.stringify({
44
+ [CWD]: { issueId: IID, issueTitle: '已配置任务', prefs: { [IID]: {
45
+ model: 'codex', language: 'zh', excluded_skill_ids: [], excluded_memory_ids: [],
46
+ done: ['model', 'language', 'skills', 'memories'],
47
+ } } },
48
+ }))
49
+
50
+ const realFetch = globalThis.fetch
51
+ globalThis.fetch = ((u: any, init?: any) => mockFetch(String(u), init)) as unknown as typeof fetch
52
+
53
+ console.log('\n[RESUME] boot with saved prefs → straight to chat\n')
54
+ let reachedChat = false
55
+ const { lastFrame, unmount } = render(React.createElement(App))
56
+ for (let i = 0; i < 80; i++) { // up to ~4s
57
+ if ((lastFrame() ?? '').includes('输入问题')) { reachedChat = true; break }
58
+ await delay(50)
59
+ }
60
+ const frame = lastFrame() ?? ''
61
+ unmount()
62
+ globalThis.fetch = realFetch
63
+
64
+ ok(reachedChat, 'booted straight into chat (skipped wizard)')
65
+ ok(frame.includes('绑定项目') && frame.includes('已配置任务'), 'chat header shows the saved project + issue')
66
+ ok(!frame.includes('选择当前路径的绑定项目') && !frame.includes('选择模型'), 'did NOT show project/model picker')
67
+
68
+ try { fs.rmSync(TMP_HOME, { recursive: true, force: true }) } catch { /* ignore */ }
69
+ console.log(`\n==== RESUME RESULT: ${pass} passed, ${fail} failed ====\n`)
70
+ process.exit(fail === 0 ? 0 : 1)
71
+ }
72
+
73
+ main().catch((e) => { console.error('FATAL', e); process.exit(2) })
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Screen / picker residue regression — "选择项目/Issue/会话时屏幕不残留其他东西".
3
+ *
4
+ * Root cause: Ink renders inline and, per frame, erases only as many lines as the
5
+ * previous frame occupied. A frame taller than the terminal window scrolls, so
6
+ * Ink can no longer reach the real top of that frame to erase it — stale lines
7
+ * from the previous screen stay behind as residue (worst when a tall list picker
8
+ * gives way to a shorter screen).
9
+ *
10
+ * The fix has two halves, both asserted here:
11
+ * 1. <Screen> pins every route to exactly the terminal height (overflow:hidden)
12
+ * so no frame ever scrolls → no residue on any transition.
13
+ * 2. Select reserves enough chrome rows that a long list window never exceeds
14
+ * the terminal, so nothing is clipped/garbled at the bottom.
15
+ *
16
+ * Run: npm run test:screen
17
+ */
18
+ import React from 'react'
19
+ import { Box, Text } from 'ink'
20
+ import { render } from 'ink-testing-library'
21
+ import { Screen } from '../src/components/Screen.js'
22
+ import { Select } from '../src/components/primitives.js'
23
+ import { entryScreenRows } from '../src/lib/screen-text.js'
24
+ import { viewsForEntry } from '../src/lib/entry-view.js'
25
+ import { createRowAccess, sliceViewport, tailAnchor } from '../src/lib/transcript-viewport.js'
26
+
27
+ const delay = (ms: number) => new Promise<void>(r => setTimeout(r, ms))
28
+ const strip = (s: string) => s.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '')
29
+ const lineCount = (s: string) => s.split('\n').length
30
+
31
+ let pass = 0, fail = 0
32
+ function ok(c: boolean, m: string) { c ? (pass++, console.log(` ✓ ${m}`)) : (fail++, console.error(` ✗ ${m}`)) }
33
+
34
+ // ink-testing-library's stdout reports no `rows`, so Screen falls back to 24.
35
+ const ROWS = 24
36
+
37
+ async function main() {
38
+ console.log('\n[SCREEN] no-residue picker transitions\n')
39
+
40
+ // A partial message is now represented by the same styled ScreenRow as a
41
+ // complete message. Virtual slicing must preserve its ANSI foreground bytes.
42
+ const styledEntries = [
43
+ { type: 'assistant', uuid: 'styled-old', message: { role: 'assistant', content: [{ type: 'text', text: '[彩色链接](https://example.com)' }] } },
44
+ { type: 'assistant', uuid: 'styled-new', message: { role: 'assistant', content: [{ type: 'text', text: '最新消息' }] } },
45
+ ]
46
+ const rowAccess = createRowAccess(styledEntries, entry => entry.uuid, entry => entryScreenRows(viewsForEntry(entry), 80))
47
+ const viewport = sliceViewport(rowAccess, tailAnchor(rowAccess, 3), 3)
48
+ const partial = viewport.rows.find(item => item.entryId === 'styled-old')?.row
49
+ ok(partial !== undefined, 'small viewport exposes a row from the partial older message')
50
+ ok(!!partial?.styled.includes('\x1b[') && partial.styled.includes('彩色链接'), 'partial older row keeps its ANSI foreground styling')
51
+
52
+ // ── 1. Without Screen, a tall frame overflows the terminal (the bug). ───────
53
+ const tall = render(
54
+ <Box flexDirection="column">
55
+ {Array.from({ length: 40 }, (_, i) => <Text key={i}>item {i}</Text>)}
56
+ </Box>,
57
+ )
58
+ await delay(30)
59
+ const tallLines = lineCount(tall.lastFrame() ?? '')
60
+ ok(tallLines > ROWS, `uncapped tall frame overflows terminal (rendered ${tallLines} > ${ROWS})`)
61
+
62
+ // ── 2. Screen caps the same tall content to exactly the terminal height. ───
63
+ const capped = render(
64
+ <Screen>
65
+ <Box flexDirection="column">
66
+ {Array.from({ length: 40 }, (_, i) => <Text key={i}>item {i}</Text>)}
67
+ </Box>
68
+ </Screen>,
69
+ )
70
+ await delay(30)
71
+ const capFrame = capped.lastFrame() ?? ''
72
+ ok(lineCount(capFrame) === ROWS, `Screen caps frame to terminal height (${lineCount(capFrame)} === ${ROWS})`)
73
+
74
+ // ── 3. Realistic picker: AIMUX line + header + a 40-item Select + footer,
75
+ // wrapped in Screen, must fit within the terminal with the footer
76
+ // visible and the list windowed (overflow items hidden, not spilled). ─
77
+ const items = Array.from({ length: 40 }, (_, i) => ({ label: `项目 ${i}`, value: `p${i}`, desc: `desc ${i}` }))
78
+ const picker = render(
79
+ <Screen>
80
+ <Box flexDirection="column" paddingX={2} paddingY={1}>
81
+ <Text dimColor>AIMUX · 已连接</Text>
82
+ <Text bold color="cyan">选择当前路径的绑定项目</Text>
83
+ <Text color="gray">/some/path</Text>
84
+ <Box marginTop={1}>
85
+ <Select items={items} />
86
+ </Box>
87
+ <Text color="gray">↑↓ 选择 · 回车确认 · Esc 退出</Text>
88
+ </Box>
89
+ </Screen>,
90
+ )
91
+ await delay(30)
92
+ const pf = strip(picker.lastFrame() ?? '')
93
+ ok(lineCount(picker.lastFrame() ?? '') === ROWS, `picker frame pinned to terminal height (${lineCount(picker.lastFrame() ?? '')} === ${ROWS})`)
94
+ ok(pf.includes('Esc 退出'), 'picker footer visible (list did not push it off / clip it)')
95
+ ok(!pf.includes('项目 39'), 'list is windowed — tail item not spilled onto screen')
96
+ ok(/还有 \d+ 项/.test(pf), 'windowed overflow shows a "还有 N 项" hint')
97
+
98
+ // ── 4. Transition tall-picker → short screen leaves no residue: the new frame
99
+ // is still exactly terminal height (constant → Ink erase realigns) and
100
+ // contains none of the old picker's lines. ─────────────────────────────
101
+ picker.rerender(
102
+ <Screen>
103
+ <Box paddingX={2} paddingY={1}>
104
+ <Text color="green">准备就绪,进入对话…</Text>
105
+ </Box>
106
+ </Screen>,
107
+ )
108
+ await delay(30)
109
+ const after = strip(picker.lastFrame() ?? '')
110
+ ok(lineCount(picker.lastFrame() ?? '') === ROWS, `post-transition frame still terminal height (${lineCount(picker.lastFrame() ?? '')} === ${ROWS})`)
111
+ ok(!after.includes('选择当前路径'), 'previous picker heading gone after transition (no residue)')
112
+ ok(after.includes('准备就绪'), 'new screen content rendered')
113
+
114
+ console.log(`\n==== SCREEN RESULT: ${pass} passed, ${fail} failed ====\n`)
115
+ process.exit(fail === 0 ? 0 : 1)
116
+ }
117
+
118
+ main().catch(e => { console.error('FATAL', e); process.exit(2) })
@@ -0,0 +1,259 @@
1
+ /**
2
+ * Chat viewport regression: history paging and live terminal resizing.
3
+ *
4
+ * The chat caps the transcript to the terminal height and (because Ink redraws
5
+ * only the live frame) the terminal's own scrollback holds no past turns, so
6
+ * older messages used to be unreachable. The fix is an in-app pager: PageUp
7
+ * scrolls back through history, PageDown forward, with a "stick to latest"
8
+ * rule so the conversation auto-follows again once you page back to the bottom.
9
+ *
10
+ * It also emits real stdout resize events after a long transcript is present.
11
+ * The dynamic tree must refit the visible records without duplicating or
12
+ * corrupting the fixed header, composer, and status rows.
13
+ *
14
+ * Run: npm run test:scroll
15
+ */
16
+ import os from 'node:os'
17
+ import path from 'node:path'
18
+ import fs from 'node:fs'
19
+
20
+ const TMP_HOME = fs.mkdtempSync(path.join(os.tmpdir(), 'mobius-tui-scroll-'))
21
+ process.env.MOBIUS_TUI_HOME = TMP_HOME
22
+
23
+ import React from 'react'
24
+ import { render } from 'ink-testing-library'
25
+ import { App } from '../src/App.js'
26
+
27
+ const delay = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))
28
+ const RS: any = (globalThis as any).ReadableStream
29
+ const enc = new TextEncoder()
30
+ let sseController: any = null
31
+
32
+ function json(body: unknown, status = 200) {
33
+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
34
+ }
35
+ // SSE live batch counter — group_id_version must strictly increase (watermark).
36
+ let liveVersion = 0
37
+ function emitEntry(n: number) {
38
+ // distinct uuid per entry so useChat's de-dup keeps every one
39
+ liveVersion += 1
40
+ const payload = { event: 'entries', session_id: SID, group_id: 'g1', group_id_version: liveVersion, entries: [{ type: 'assistant', uuid: `a-${n}`, message: { role: 'assistant', content: [{ type: 'text', text: `回答 ${n}` }] } }] }
41
+ sseController?.enqueue(enc.encode(`event: entries\ndata: ${JSON.stringify(payload)}\n\n`))
42
+ }
43
+
44
+ let pass = 0, fail = 0
45
+ function ok(c: boolean, m: string) { c ? (pass++, console.log(` ✓ ${m}`)) : (fail++, console.error(` ✗ ${m}`)) }
46
+ const strip = (s: string) => s.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '')
47
+ const answerCount = (s: string) => (strip(s).match(/回答 \d+/g) ?? []).length
48
+
49
+ function resize(stdout: NodeJS.WriteStream, columns: number, rows: number) {
50
+ Object.defineProperty(stdout, 'columns', { configurable: true, value: columns })
51
+ Object.defineProperty(stdout, 'rows', { configurable: true, value: rows })
52
+ Object.defineProperty(stdout, 'isTTY', { configurable: true, value: true })
53
+ stdout.emit('resize')
54
+ }
55
+
56
+ const PID = 'proj-1', IID = 'issue-1', SID = 'sess-1'
57
+
58
+ function mockFetch(url: string, init?: RequestInit): Response {
59
+ if (url.includes('/events')) {
60
+ return new Response(new RS({
61
+ start(c: any) {
62
+ sseController = c
63
+ c.enqueue(enc.encode('event: subscribed\ndata: {"event":"subscribed"}\n\n'))
64
+ },
65
+ }), { status: 200, headers: { 'content-type': 'text/event-stream' } })
66
+ }
67
+ const method = init?.method ?? 'GET'
68
+ // agent-history 协议 ①②: 组元数据空表 (无 bootstrap 历史), live 事件由 emitEntry 注入.
69
+ if (url.endsWith(`/api/sessions/${SID}/groups`)) return json({ session_version: 0, groups: [] })
70
+ if (url.includes(`/api/sessions/${SID}/groups/`)) return json({ group_id: 'g1', version: 0, entries: [] })
71
+ if (url.endsWith('/api/auth/config')) return json({ password_required: false })
72
+ if (url.endsWith('/api/auth/me')) return json({ id: 'tester', display_name: 'Test User', role: 'admin', work_dir: '/tmp' })
73
+ if (url.endsWith('/api/auth/login')) return json({ token: 'mock-jwt-token', user: { id: 'tester', display_name: 'Test User', role: 'admin' } })
74
+ if (url.includes('/aimux_bridge/api/remotes/') && url.includes('/connection')) {
75
+ const m = url.match(/remotes\/([^/]+)\/connection/)
76
+ return json({ identifier: m ? decodeURIComponent(m[1]) : 'x', event_stream_connected: true })
77
+ }
78
+ if (url.includes('/sessions') && url.includes('/issues') && method === 'POST') return json({ session_id: SID })
79
+ if (url.includes('/sessions') && url.includes('/issues') && method === 'GET') return json([])
80
+ if (url.endsWith('/messages') && method === 'POST') return json({ ok: true, session_id: SID, turn_number: 1 }) // keep SSE alive
81
+ if (url.endsWith(`/api/sessions/${SID}/status`)) return json({ session_id: SID, alive: true, working: false })
82
+ if (url.includes('/api/projects/') && url.includes('/issues') && method === 'POST') return json({ id: IID, project_id: PID, title: '命令行任务' })
83
+ if (url.includes('/api/projects/') && url.includes('/issues') && method === 'GET') return json([])
84
+ if (url.includes('/api/projects') && method === 'GET') return json([{ id: PID, name: '已有项目甲' }])
85
+ if (url.endsWith('/api/projects') && method === 'POST') return json({ id: PID, name: '测试项目PTY' })
86
+ if (url.includes('/sessions/model-options')) return json([{ key: 'codex', label: 'GPT-5.5', title: 'GPT-5.5', sub: 'Codex', backend: 'tmux-codex' }])
87
+ if (url.includes('/sessions/default-model')) return json({ model: 'codex' })
88
+ if (url.includes('/skills')) return json([])
89
+ if (url.includes('/memories')) return json([])
90
+ return json({ error: `unmocked ${method} ${url}` }, 404)
91
+ }
92
+
93
+ async function waitFor(lastFrame: () => string | undefined, needle: string, timeoutMs = 6000) {
94
+ for (let i = 0; i < timeoutMs / 50; i++) {
95
+ if ((strip(lastFrame() ?? '')).includes(needle)) return true
96
+ await delay(50)
97
+ }
98
+ return false
99
+ }
100
+
101
+ // Walk the prep wizard (project → issue → model → language) into the chat.
102
+ async function bootToChat(stdin: any, lastFrame: () => string | undefined) {
103
+ ok(await waitFor(lastFrame, '选择当前路径的绑定项目'), 'booted into project picker')
104
+ stdin.write('\r'); await delay(120)
105
+ ok(await waitFor(lastFrame, '项目名称'), 'project create wizard opened')
106
+ stdin.write('测试项目PTY'); await delay(120)
107
+ stdin.write('\r'); await delay(300)
108
+ ok(await waitFor(lastFrame, '创建新任务'), 'issue picker shown')
109
+ stdin.write('\r'); await delay(120)
110
+ ok(await waitFor(lastFrame, '输入任务名称'), 'issue name wizard opened')
111
+ stdin.write('命令行任务'); await delay(120)
112
+ stdin.write('\r'); await delay(300)
113
+ ok(await waitFor(lastFrame, '选择模型'), 'model picker shown')
114
+ stdin.write('\r'); await delay(250)
115
+ ok(await waitFor(lastFrame, '选择回复语言'), 'language picker shown')
116
+ stdin.write('\r'); await delay(400)
117
+ ok(await waitFor(lastFrame, '输入问题'), 'entered chat')
118
+ }
119
+
120
+ async function populateTranscript(stdin: any, emit: (n: number) => void, count = 25) {
121
+ stdin.write('hi'); await delay(120)
122
+ stdin.write('\r'); await delay(400) // creates session → SSE connects
123
+ for (let i = 0; i < count; i++) { emit(i); await delay(15) }
124
+ await delay(500)
125
+ }
126
+
127
+ async function main() {
128
+ fs.writeFileSync(path.join(TMP_HOME, 'login.json'), JSON.stringify({
129
+ server: 'http://mock.local', username: 'tester', token: 'mock-jwt-token',
130
+ user: { id: 'tester', display_name: 'Test User', role: 'admin' },
131
+ }))
132
+ const realFetch = globalThis.fetch
133
+ globalThis.fetch = ((u: any, init?: any) => mockFetch(String(u), init)) as unknown as typeof fetch
134
+
135
+ console.log('\n[SCROLL] in-app history pager (mocked backend)\n')
136
+ const { stdin, stdout, lastFrame, unmount } = render(React.createElement(App))
137
+
138
+ try {
139
+ // ── boot through the prep wizard into chat ────────────────────────────────
140
+ await bootToChat(stdin, lastFrame)
141
+
142
+ // ── populate a long transcript ────────────────────────────────────────────
143
+ await populateTranscript(stdin, emitEntry)
144
+ const tailFrame = strip(lastFrame() ?? '')
145
+
146
+ ok(tailFrame.includes('回答 24'), 'latest entry visible at tail (not hidden)')
147
+ ok(tailFrame.includes('↑ 还有较早内容') && tailFrame.includes('滚轮 3 行'), 'navigation reports older content and the exact wheel step')
148
+
149
+ // ── live resize: refit one dynamic frame, never retain old-width output ──
150
+ resize(stdout as unknown as NodeJS.WriteStream, 52, 18)
151
+ await delay(300)
152
+ const narrowFrame = strip(lastFrame() ?? '')
153
+ const narrowAnswers = answerCount(narrowFrame)
154
+ ok(narrowFrame.includes('回答 24'), 'narrow resize keeps the latest reply visible')
155
+ ok(narrowFrame.includes('Mobius') && narrowFrame.includes('输入问题或 / 命令') && narrowFrame.includes('web ·'), 'narrow resize preserves header, composer, and status')
156
+ ok((narrowFrame.match(/>_ Mobius/g) ?? []).length === 1, 'narrow resize leaves exactly one dynamic header')
157
+
158
+ resize(stdout as unknown as NodeJS.WriteStream, 100, 36)
159
+ await delay(300)
160
+ const tallFrame = strip(lastFrame() ?? '')
161
+ const tallAnswers = answerCount(tallFrame)
162
+ ok(tallFrame.includes('回答 24'), 'larger resize keeps the latest reply visible')
163
+ ok(tallAnswers > narrowAnswers, 'larger resize reveals more history in the same viewport')
164
+ ok((tallFrame.match(/>_ Mobius/g) ?? []).length === 1, 'larger resize still has one dynamic header')
165
+
166
+ // Navigation is a fixed one-row part of the conversation chrome. It must be
167
+ // the FIRST line below the header and state the exact PageUp/PageDown step.
168
+ const tallLines = tallFrame.split('\n')
169
+ const hintIdx = tallLines.findIndex(l => l.includes('滚轮 3 行'))
170
+ ok(hintIdx === 1, `navigation is the first line under the header (line ${hintIdx}, expected 1)`)
171
+ ok(/PageUp\/PageDown \d+ 行/.test(tallLines[hintIdx] ?? ''), 'navigation exposes the deterministic page size')
172
+ const messageRows = tallLines.slice(hintIdx + 1).filter(line => line.trim())
173
+ ok(messageRows.length > 0 && messageRows[0].includes('回答'), 'a real virtualized message row follows navigation without a synthetic peek row')
174
+
175
+ // ── PageUp: viewport scrolls back over history ────────────────────────────
176
+ stdin.write('\x1b[5~') // PageUp
177
+ await delay(300)
178
+ const upFrame = strip(lastFrame() ?? '')
179
+ ok(upFrame.includes('↓ 有新内容'), 'after PageUp: navigation reports newer content below')
180
+ ok(!upFrame.includes('回答 24'), 'after PageUp: latest entry paged out of view')
181
+ ok(/回答 \d+/.test(upFrame), 'after PageUp: an older entry is visible')
182
+
183
+ // ── PageDown: snaps back to the latest ────────────────────────────────────
184
+ stdin.write('\x1b[6~') // PageDown
185
+ await delay(300)
186
+ const downFrame = strip(lastFrame() ?? '')
187
+ ok(downFrame.includes('回答 24'), 'after PageDown: latest entry back in view')
188
+
189
+ // ── Mouse wheel: SGR wheel events drive the same pager ────────────────────
190
+ stdin.write('\x1b[<64;5;5M') // wheel up = scroll back
191
+ await delay(300)
192
+ const wheelUp = strip(lastFrame() ?? '')
193
+ ok(wheelUp.includes('↓ 有新内容'), 'wheel up: navigation reports newer content below')
194
+ ok(!wheelUp.includes('回答 24'), 'wheel up: latest entry paged out of view')
195
+ ok(/回答 \d+/.test(wheelUp), 'wheel up: an older entry is visible')
196
+
197
+ stdin.write('\x1b[<65;5;5M') // wheel down = scroll forward
198
+ await delay(300)
199
+ const wheelDown = strip(lastFrame() ?? '')
200
+ ok(wheelDown.includes('回答 24'), 'wheel down: latest entry back in view')
201
+
202
+ // ── Mouse wheel (legacy X10 encoding, terminals without SGR 1006) ────────
203
+ // wheel up: ESC [ M Cb Cx Cy, Cb = button + 32 → 0x60 (96); coords at 18,18
204
+ stdin.write('\x1b[M' + String.fromCharCode(96, 50, 50))
205
+ await delay(300)
206
+ const legacyUp = strip(lastFrame() ?? '')
207
+ ok(legacyUp.includes('↓ 有新内容'), 'legacy wheel up: navigation reports newer content below')
208
+ ok(!legacyUp.includes('回答 24'), 'legacy wheel up: latest entry paged out of view')
209
+
210
+ stdin.write('\x1b[M' + String.fromCharCode(97, 50, 50)) // wheel down Cb = 0x61
211
+ await delay(300)
212
+ const legacyDown = strip(lastFrame() ?? '')
213
+ ok(legacyDown.includes('回答 24'), 'legacy wheel down: latest entry back in view')
214
+ } finally {
215
+ unmount()
216
+ globalThis.fetch = realFetch
217
+ }
218
+
219
+ // ── Phase 2: MOBIUS_TUI_DISABLE_MOUSE=1 opts out of wheel mode ─────────────
220
+ // Mouse reporting hands the terminal mouse to the app, which disables native
221
+ // drag-select. The env flag is the escape hatch: wheel stops, selection is
222
+ // free again. Here we assert wheel events no longer scroll the pager. A fresh
223
+ // MOBIUS_TUI_HOME is used because phase 1 persisted a dir→project binding.
224
+ const TMP_HOME2 = fs.mkdtempSync(path.join(os.tmpdir(), 'mobius-tui-scroll2-'))
225
+ process.env.MOBIUS_TUI_DISABLE_MOUSE = '1'
226
+ process.env.MOBIUS_TUI_HOME = TMP_HOME2
227
+ fs.writeFileSync(path.join(TMP_HOME2, 'login.json'), JSON.stringify({
228
+ server: 'http://mock.local', username: 'tester', token: 'mock-jwt-token',
229
+ user: { id: 'tester', display_name: 'Test User', role: 'admin' },
230
+ }))
231
+ globalThis.fetch = ((u: any, init?: any) => mockFetch(String(u), init)) as unknown as typeof fetch
232
+ const second = render(React.createElement(App))
233
+ try {
234
+ await bootToChat(second.stdin, second.lastFrame)
235
+ await populateTranscript(second.stdin, emitEntry)
236
+ const before = strip(second.lastFrame() ?? '')
237
+ const beforeAnswers = before.match(/回答 \d+/g) ?? []
238
+ ok(before.includes('回答 24'), 'disable-mouse: latest entry visible before wheel')
239
+
240
+ second.stdin.write('\x1b[<64;5;5M') // wheel up — must be ignored
241
+ await delay(300)
242
+ const after = strip(second.lastFrame() ?? '')
243
+ const afterAnswers = after.match(/回答 \d+/g) ?? []
244
+ ok(after.includes('回答 24'), 'disable-mouse: wheel up leaves latest entry in view')
245
+ ok(JSON.stringify(afterAnswers) === JSON.stringify(beforeAnswers), 'disable-mouse: wheel up leaves the visible row window unchanged')
246
+ } finally {
247
+ second.unmount()
248
+ delete process.env.MOBIUS_TUI_DISABLE_MOUSE
249
+ delete process.env.MOBIUS_TUI_HOME
250
+ globalThis.fetch = realFetch
251
+ try { fs.rmSync(TMP_HOME2, { recursive: true, force: true }) } catch { /* ignore */ }
252
+ }
253
+
254
+ try { fs.rmSync(TMP_HOME, { recursive: true, force: true }) } catch { /* ignore */ }
255
+ console.log(`\n==== SCROLL RESULT: ${pass} passed, ${fail} failed ====\n`)
256
+ process.exit(fail === 0 ? 0 : 1)
257
+ }
258
+
259
+ main().catch((e) => { console.error('FATAL', e); process.exit(2) })