@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,261 @@
1
+ /**
2
+ * Flow test — drive the WHOLE App as a user would, end to end, through the real
3
+ * Ink screens (login → prep wizard → chat → /clear → /resume), against a mocked
4
+ * backend. Captures rendered frames at each milestone as evidence.
5
+ *
6
+ * Run: npm run test:flow
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-flow-'))
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 RS: any = (globalThis as any).ReadableStream
21
+ const enc = new TextEncoder()
22
+ let sseController: any = null
23
+ function emit(ev: string, data: Record<string, unknown>) {
24
+ sseController?.enqueue(enc.encode(`event: ${ev}\ndata: ${JSON.stringify({ event: ev, ...data })}\n\n`))
25
+ }
26
+ // SSE live 批次计数 — group_id_version 必须严格递增 (水位线).
27
+ let liveVersion = 0
28
+ function emitEntries(entries: any[]) {
29
+ liveVersion += 1
30
+ emit('entries', { session_id: SID, group_id: 'g1', group_id_version: liveVersion, entries })
31
+ }
32
+ function json(body: unknown, status = 200) {
33
+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
34
+ }
35
+
36
+ const snapshots: { step: string; frame: string }[] = []
37
+ function snap(step: string, frame: string) { snapshots.push({ step, frame: frame.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '') }) }
38
+
39
+ let pass = 0, fail = 0
40
+ function ok(c: boolean, m: string) { c ? (pass++, console.log(` ✓ ${m}`)) : (fail++, console.error(` ✗ ${m}`)) }
41
+
42
+ // ── mocked backend (precise URL matchers — substring overlaps broke an earlier draft) ─
43
+ const PID = 'proj-1', IID = 'issue-1', SID = 'sess-1'
44
+ let lastMessageBody: any = null
45
+ function mockFetch(url: string, init?: RequestInit): Response {
46
+ // SSE
47
+ if (url.includes('/events')) {
48
+ return new Response(new RS({ start(c: any) { sseController = c; c.enqueue(enc.encode('event: subscribed\ndata: {"event":"subscribed"}\n\n')) } }),
49
+ { status: 200, headers: { 'content-type': 'text/event-stream' } })
50
+ }
51
+ const method = init?.method ?? 'GET'
52
+ // auth
53
+ if (url.endsWith('/api/auth/config')) return json({ password_required: false })
54
+ if (url.endsWith('/api/auth/me')) return json({ id: 'tester', display_name: 'Test User', role: 'admin', work_dir: '/tmp' })
55
+ if (url.endsWith('/api/auth/login')) return json({ token: 'mock-jwt-token', user: { id: 'tester', display_name: 'Test User', role: 'admin' } })
56
+ if (url.includes('/aimux_bridge/api/remotes/') && url.endsWith('/connection')) {
57
+ const match = url.match(/remotes\/([^/]+)\/connection/)
58
+ return json({ identifier: match ? decodeURIComponent(match[1]) : 'tui-test', event_stream_connected: true })
59
+ }
60
+ // sessions (must be checked before issues/projects — the session URL contains /issues too)
61
+ if (url.includes('/sessions') && url.includes('/issues') && method === 'POST') return json({ session_id: SID }) // create session
62
+ if (url.includes('/sessions') && url.includes('/issues') && method === 'GET') { // list sessions (resume)
63
+ return json([{ session_id: SID, name: '历史会话一', last_active: new Date(Date.now() - 3600_000).toISOString(), message_count: 5, model: 'codex', issue_title: '命令行任务' }])
64
+ }
65
+ if (url.endsWith('/messages') && method === 'POST') {
66
+ lastMessageBody = JSON.parse(String(init?.body || '{}'))
67
+ // /compact turns come back as claude-code local-command artifacts (command
68
+ // echo + completion stdout) instead of an assistant reply.
69
+ if (String(lastMessageBody?.content || '').trim() === '/compact') {
70
+ setTimeout(() => {
71
+ emit('typing', { active: true })
72
+ emitEntries([{ type: 'user', uuid: 'flow-cmd-echo', message: { role: 'user', content: '<command-name>/compact</command-name><command-message>compact</command-message><command-args></command-args><local-command-caveat>no need to respond</local-command-caveat>' } }, { type: 'user', uuid: 'flow-cmd-done', message: { role: 'user', content: [{ type: 'text', text: '<local-command-stdout>Compacted. Your new context length is 8,840 tokens</local-command-stdout>' }] } }])
73
+ emit('typing', { active: false })
74
+ }, 200)
75
+ return json({ ok: true, session_id: SID, turn_number: 2 })
76
+ }
77
+ setTimeout(() => {
78
+ emit('typing', { active: true })
79
+ emitEntries([{ type: 'assistant', message: { role: 'assistant', content: [{ type: 'text', text: '已收到,这是来自 TUI 的回复。' }] } }])
80
+ emit('typing', { active: false })
81
+ }, 200)
82
+ return json({ ok: true, session_id: SID, turn_number: 1 })
83
+ }
84
+ // agent-history 协议 ①②: 组元数据空表 (无 bootstrap 历史), live 批次由 emitEntries 注入.
85
+ if (url.endsWith(`/api/sessions/${SID}/groups`)) return json({ session_version: 0, groups: [] })
86
+ if (url.includes(`/api/sessions/${SID}/groups/`)) return json({ group_id: 'g1', version: 0, entries: [] })
87
+ if (url.endsWith(`/api/sessions/${SID}/status`)) {
88
+ return json({ session_id: SID, alive: true, working: false })
89
+ }
90
+ // issues
91
+ if (url.includes('/api/projects/') && url.includes('/issues') && method === 'POST') return json({ id: IID, project_id: PID, title: '命令行任务' }) // create issue
92
+ if (url.includes('/api/projects/') && url.includes('/issues') && method === 'GET') return json([{ id: IID, project_id: PID, title: '命令行任务', description: '任务说明' }]) // list issues
93
+ // projects
94
+ if (url.includes('/api/projects') && method === 'GET') return json([{ id: PID, name: '已有项目甲', description: '项目说明' }]) // list projects
95
+ if (url.endsWith('/api/projects') && method === 'POST') return json({ id: PID, name: '测试项目PTY' }) // create project (exact)
96
+ // preference lookups
97
+ if (url.includes('/sessions/model-options')) return json([{ key: 'codex', label: 'GPT-5.5', title: 'GPT-5.5', sub: 'Codex', backend: 'tmux-codex' }])
98
+ if (url.includes('/sessions/default-model')) return json({ model: 'codex' })
99
+ if (url.includes('/skills')) return json([])
100
+ if (url.includes('/memories')) return json([])
101
+ return json({ error: `unmocked ${method} ${url}` }, 404)
102
+ }
103
+
104
+ async function waitFor(lastFrame: () => string | undefined, needle: string, timeoutMs = 4000) {
105
+ for (let i = 0; i < timeoutMs / 50; i++) {
106
+ if ((lastFrame() ?? '').includes(needle)) return true
107
+ await delay(50)
108
+ }
109
+ return false
110
+ }
111
+
112
+ async function main() {
113
+ // Pre-seed login so App auto-logs in (login form itself is covered in ui.test).
114
+ fs.writeFileSync(path.join(TMP_HOME, 'login.json'), JSON.stringify({
115
+ server: 'http://mock.local', username: 'tester', token: 'mock-jwt-token',
116
+ user: { id: 'tester', display_name: 'Test User', role: 'admin' },
117
+ }))
118
+ const realFetch = globalThis.fetch
119
+ globalThis.fetch = ((u: any, init?: any) => mockFetch(String(u), init)) as unknown as typeof fetch
120
+ process.env.MOBIUS_TUI_DEBUG = '1'
121
+
122
+ console.log('\n[FLOW] full App drive (mocked backend)\n')
123
+ const { stdin, lastFrame, unmount } = render(React.createElement(App))
124
+
125
+ try {
126
+ // ── prep: project picker (auto-logged in) ────────────────────────────────
127
+ ok(await waitFor(lastFrame, '选择当前路径的绑定项目'), 'booted into project picker')
128
+ // pick "➕ 创建新项目" (active index 0) → name wizard
129
+ stdin.write('\r'); await delay(120)
130
+ ok(await waitFor(lastFrame, '项目名称'), 'project create wizard opened')
131
+ stdin.write('测试项目PTY'); await delay(120)
132
+ stdin.write('\r'); await delay(300) // submit project name
133
+ snap('1-prep-project-created', lastFrame() ?? '')
134
+
135
+ // ── prep: issue picker (no issues → create) ──────────────────────────────
136
+ ok(await waitFor(lastFrame, '创建新任务'), 'issue picker shown')
137
+ stdin.write('\r'); await delay(120) // → create-name
138
+ ok(await waitFor(lastFrame, '输入任务名称'), 'issue name wizard opened')
139
+ stdin.write('\x1b'); await delay(120) // Esc → issue list
140
+ ok(await waitFor(lastFrame, '选择任务(Issue)'), 'Esc returns from issue name wizard to issue list')
141
+ stdin.write('\r'); await delay(120) // → create-name again
142
+ ok(await waitFor(lastFrame, '输入任务名称'), 'issue name wizard can be reopened after Esc')
143
+ stdin.write('命令行任务'); await delay(120)
144
+ stdin.write('\r'); await delay(300) // create issue (worktree off) → model
145
+
146
+ // ── prep: preferences ────────────────────────────────────────────────────
147
+ ok(await waitFor(lastFrame, '选择模型'), 'model picker shown')
148
+ stdin.write('\r'); await delay(250) // pick codex
149
+ ok(await waitFor(lastFrame, '选择回复语言'), 'language picker shown')
150
+ stdin.write('\r'); await delay(400) // zh; skills+memories empty → auto-skip
151
+
152
+ // ── chat ─────────────────────────────────────────────────────────────────
153
+ ok(await waitFor(lastFrame, '输入问题'), 'entered chat (preferences complete)')
154
+ snap('2-chat-ready', lastFrame() ?? '')
155
+
156
+ // send a message — expect streamed assistant reply
157
+ stdin.write('你好,请回复一句话'); await delay(120)
158
+ stdin.write('\r')
159
+ ok(await waitFor(lastFrame, '已收到', 6000), 'assistant reply streamed into transcript')
160
+ await delay(300)
161
+ snap('3-chat-after-reply', lastFrame() ?? '')
162
+
163
+ // ── /clear ───────────────────────────────────────────────────────────────
164
+ stdin.write('/clear'); await delay(120)
165
+ stdin.write('\r')
166
+ ok(await waitFor(lastFrame, '输入问题'), '/clear reset to a fresh chat')
167
+ snap('4-after-clear', lastFrame() ?? '')
168
+
169
+ // ── /resume ──────────────────────────────────────────────────────────────
170
+ // /resume — wait for the post-/clear remount to settle, then type slowly.
171
+ await delay(500)
172
+ stdin.write('/resume'); await delay(300)
173
+ stdin.write('\r')
174
+ await delay(500)
175
+ snap('4b-resume-picker', lastFrame() ?? '')
176
+ ok(await waitFor(lastFrame, '恢复历史会话'), '/resume picker opened')
177
+ ok((lastFrame() ?? '').includes('历史会话一'), 'resume list shows the past session')
178
+ stdin.write('\r'); await delay(500) // pick session → reconnect SSE
179
+ ok(await waitFor(lastFrame, '输入问题'), 'resumed into chat')
180
+ snap('5-after-resume', lastFrame() ?? '')
181
+
182
+ // ── /config: full reconfigure (project → issue → model) ──────────────
183
+ // Unlike /model, /config walks through project, issue, AND model steps.
184
+ await delay(400)
185
+ stdin.write('/config'); await delay(300)
186
+ stdin.write('\r')
187
+ ok(await waitFor(lastFrame, '重新配置'), '/config opens the full reconfig flow')
188
+ ok(await waitFor(lastFrame, '选择项目'), '/config shows project picker first')
189
+ ok(await waitFor(lastFrame, '已有项目甲 - 项目说明'), '/config keeps the project explanation on its main row')
190
+ // Pick the first project (created above), then verify Esc walks back one
191
+ // level at a time instead of closing the entire config flow.
192
+ stdin.write('\r'); await delay(400)
193
+ ok(await waitFor(lastFrame, '选择任务'), '/config shows issue picker after project')
194
+ ok((lastFrame() ?? '').includes('命令行任务 - 任务说明'), '/config keeps the issue explanation on its main row')
195
+ stdin.write('\x1b'); await delay(180)
196
+ ok(await waitFor(lastFrame, '选择项目'), 'Esc from issue selection returns to project selection')
197
+ stdin.write('\r'); await delay(400)
198
+ ok(await waitFor(lastFrame, '选择任务'), 'project selection can be re-entered after Esc')
199
+
200
+ // Pick the issue and verify the model step also returns to the issue step.
201
+ stdin.write('\r'); await delay(400)
202
+ ok(await waitFor(lastFrame, '选择模型'), '/config shows model picker after issue')
203
+ ok(await waitFor(lastFrame, 'GPT-5.5'), '/config model list rendered')
204
+ ok((lastFrame() ?? '').includes('GPT-5.5 (默认) - Codex'), '/config keeps the model explanation on its main row')
205
+ stdin.write('\x1b'); await delay(180)
206
+ ok(await waitFor(lastFrame, '选择任务'), 'Esc from model selection returns to issue selection')
207
+ stdin.write('\r'); await delay(400)
208
+ ok(await waitFor(lastFrame, '选择模型'), 'issue selection can be re-entered after Esc')
209
+ stdin.write('\r'); await delay(700) // pick codex → create session
210
+ ok(await waitFor(lastFrame, '输入问题'), '/config creates a fresh session and returns to chat')
211
+ ok((lastFrame() ?? '').includes('?session=sess-1'), 'reconfigured chat is attached to the new session')
212
+ snap('6-after-config', lastFrame() ?? '')
213
+
214
+ // ── /model: swap model only, keep current task ─────────────────────────
215
+ // No issue/project step — the current task is kept; pick a model and App
216
+ // remounts Chat on the eagerly created session.
217
+ await delay(400)
218
+ stdin.write('/model'); await delay(300)
219
+ stdin.write('\r')
220
+ ok(await waitFor(lastFrame, '更换模型'), '/model opens the model picker directly')
221
+ ok(await waitFor(lastFrame, '选择模型'), 'model picker shown without an issue-selection step')
222
+ ok((lastFrame() ?? '').includes('当前任务: 命令行任务'), 'current task is kept (issue not changed)')
223
+ ok(await waitFor(lastFrame, 'GPT-5.5'), 'model list rendered (Select mounted)')
224
+ stdin.write('\r'); await delay(700) // pick codex → create session
225
+ ok(await waitFor(lastFrame, '输入问题'), '/model creates a fresh session and returns to chat')
226
+ ok((lastFrame() ?? '').includes('?session=sess-1'), '/model new session attached')
227
+ snap('7-after-model', lastFrame() ?? '')
228
+
229
+ // ── /compact: dispatch the literal command on the live session ────────
230
+ await delay(400)
231
+ stdin.write('/compact'); await delay(200)
232
+ stdin.write('\r')
233
+ ok(await waitFor(lastFrame, '上下文已压缩', 6000), '/compact renders the compact completion system line')
234
+ ok(lastMessageBody?.content === '/compact', '/compact posts the literal command to the session (web parity)')
235
+ snap('7b-after-compact', lastFrame() ?? '')
236
+
237
+ // ── /logout ─────────────────────────────────────────────────────────────
238
+ await delay(400)
239
+ stdin.write('/logout'); await delay(150)
240
+ stdin.write('\r')
241
+ ok(await waitFor(lastFrame, 'Mobius 登录'), '/logout returns to the login form')
242
+ ok(!fs.existsSync(path.join(TMP_HOME, 'login.json')), '/logout clears the persisted login token')
243
+ ok((lastFrame() ?? '').includes('http://mock.local') && (lastFrame() ?? '').includes('tester'), '/logout keeps server and username available for the next login')
244
+ snap('6-after-config', lastFrame() ?? '')
245
+ } finally {
246
+ unmount()
247
+ globalThis.fetch = realFetch
248
+ }
249
+
250
+ console.log('\n──────── captured frames ────────')
251
+ for (const s of snapshots) {
252
+ console.log(`\n── ${s.step} ──`)
253
+ console.log(s.frame.replace(/\n{3,}/g, '\n\n').trim())
254
+ }
255
+
256
+ try { fs.rmSync(TMP_HOME, { recursive: true, force: true }) } catch { /* ignore */ }
257
+ console.log(`\n==== FLOW RESULT: ${pass} passed, ${fail} failed ====\n`)
258
+ process.exit(fail === 0 ? 0 : 1)
259
+ }
260
+
261
+ main().catch((e) => { console.error('FATAL', e); process.exit(2) })
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Integration test — exercises the real Mobius backend end-to-end.
3
+ *
4
+ * login (passwordless) → getMe → listModels → createProject → createIssue →
5
+ * createSession → sendMessage → open SSE → assert assistant entries stream in.
6
+ *
7
+ * Run: npm run test:integration
8
+ * Target: a local Mobius backend by default; set MOBIUS_TUI_SERVER /
9
+ * MOBIUS_TUI_USER to point at a specific server. Set
10
+ * MOBIUS_TUI_PASSWORD when that server requires password login, or provide an
11
+ * existing bearer token through MOBIUS_TUI_TOKEN. MOBIUS_TUI_MODEL can select
12
+ * a specific available model for the live reply check.
13
+ */
14
+ import { login, getMe, MobiusClient, ApiError } from '../src/api.js'
15
+ import { SseConnection } from '../src/sse.js'
16
+ import { assistantEntryText, isHiddenNoise } from '../src/lib/entry-view.js'
17
+ import type { AnyEntry } from '../src/types.js'
18
+
19
+ const SERVER = process.env.MOBIUS_TUI_SERVER || 'http://127.0.0.1:45616'
20
+ const USERNAME = process.env.MOBIUS_TUI_USER || 'admin'
21
+ const PASSWORD = process.env.MOBIUS_TUI_PASSWORD || undefined
22
+ const TOKEN = process.env.MOBIUS_TUI_TOKEN || undefined
23
+ const MODEL = process.env.MOBIUS_TUI_MODEL || undefined
24
+ const WAIT_MS = Number(process.env.MOBIUS_TUI_WAIT_MS || 90000)
25
+
26
+ let pass = 0, fail = 0
27
+ function ok(cond: boolean, msg: string) {
28
+ if (cond) { pass++; console.log(` ✓ ${msg}`) }
29
+ else { fail++; console.error(` ✗ ${msg}`) }
30
+ }
31
+
32
+ async function main() {
33
+ console.log(`\n[1/7] authenticate → ${SERVER} as ${USERNAME}`)
34
+ const lr = TOKEN
35
+ ? { token: TOKEN, user: await getMe(SERVER, TOKEN) }
36
+ : await login(SERVER, USERNAME, PASSWORD)
37
+ ok(!!lr.token && lr.token.length > 20, `got token (len ${lr.token.length})`)
38
+ ok(!!lr.user.id && (TOKEN ? true : lr.user.id === USERNAME), `user.id = ${lr.user.id} (${lr.user.display_name})`)
39
+
40
+ console.log('\n[2/7] getMe validates token')
41
+ const me = await getMe(SERVER, lr.token)
42
+ ok(me.id === lr.user.id, `getMe ok, role=${me.role}, work_dir=${me.work_dir}`)
43
+
44
+ const client = new MobiusClient(SERVER, lr.token)
45
+
46
+ console.log('\n[3/7] model options')
47
+ const models = await client.modelOptions()
48
+ const keys = models.map(m => m.key)
49
+ ok(models.length > 0, `${models.length} models available`)
50
+ ok(keys.includes('codex') || models.some(m => /codex|claude|deepseek/i.test(m.key)),
51
+ `a usable model present (sample: ${keys.slice(0, 5).join(', ')})`)
52
+ if (MODEL && !keys.includes(MODEL)) throw new Error(`requested model is unavailable: ${MODEL}`)
53
+ const modelKey = MODEL || (keys.includes('codex') ? 'codex' : models[0].key)
54
+
55
+ console.log('\n[4/7] create test project + issue')
56
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
57
+ const proj = await client.createProject({ name: `tui-itest-${stamp}`, description: 'TUI integration test (auto)', bindPath: `tui-itest-${stamp}`, defaultUseWorktree: false })
58
+ ok(!!proj.id, `project created: ${proj.name} (${proj.id})`)
59
+ const issue = await client.createIssue(proj.id, { title: 'auto-test', description: 'integration', use_worktree: false })
60
+ ok(!!issue.id, `issue created: ${issue.title} (${issue.id})`)
61
+
62
+ console.log('\n[5/7] create session with preferences')
63
+ const session = await client.createSession(issue.id, {
64
+ name: `tui-itest-${stamp}`, model: modelKey, language: 'zh',
65
+ excluded_skill_ids: [], excluded_memory_ids: [],
66
+ })
67
+ ok(!!session.session_id, `session created (${session.session_id})`)
68
+
69
+ console.log('\n[6/7] send message + open SSE, wait for assistant reply')
70
+ await client.sendMessage(session.session_id, '请只回复两个字:成功。不要调用任何工具。')
71
+
72
+ const entries: AnyEntry[] = []
73
+ let gotAssistant = false
74
+ let firstEntryMs = 0
75
+ const t0 = Date.now()
76
+ await new Promise<void>((resolve) => {
77
+ const url = `${SERVER}/api/sessions/${encodeURIComponent(session.session_id)}/events?token=${encodeURIComponent(lr.token)}`
78
+ const conn = new SseConnection(url, {
79
+ onEntries: ({ entries: batch }) => {
80
+ for (const entry of batch) {
81
+ if (!firstEntryMs) firstEntryMs = Date.now() - t0
82
+ entries.push(entry)
83
+ if (!isHiddenNoise(entry) && assistantEntryText(entry)) gotAssistant = true
84
+ }
85
+ if (gotAssistant) { setTimeout(resolve, 1500) } // grab trailing entries
86
+ },
87
+ onError: (m) => console.error(' (sse error)', m),
88
+ })
89
+ conn.start()
90
+ const deadline = setTimeout(() => { conn.close(); resolve() }, WAIT_MS)
91
+ // also resolve promptly once we clearly have a finalized assistant msg
92
+ const poll = setInterval(() => {
93
+ if (gotAssistant && Date.now() - (entries[entries.length - 1]?.__ts ?? 0) > 3000) {
94
+ // no-op; rely on the 1.5s resolve above
95
+ }
96
+ if (Date.now() - t0 > WAIT_MS) { clearInterval(poll); clearTimeout(deadline) }
97
+ }, 1000)
98
+ })
99
+
100
+ ok(entries.length > 0, `received ${entries.length} SSE entries (group events)`)
101
+ ok(firstEntryMs > 0, `first entry after ${firstEntryMs}ms`)
102
+ ok(gotAssistant, 'received an assistant text entry')
103
+
104
+ // Show a sample of the transcript the TUI would render.
105
+ console.log('\n —— transcript sample ——')
106
+ for (const e of entries.slice(0, 8)) {
107
+ const t = assistantEntryText(e)
108
+ if (t) console.log(' • ' + t.slice(0, 120).replace(/\n/g, '\n '))
109
+ }
110
+
111
+ console.log('\n[7/7] cleanup')
112
+ try { await client.stopSession(session.session_id) } catch { /* ignore */ }
113
+ for (const p of [`/api/sessions/${session.session_id}`, `/api/issues/${issue.id}`, `/api/projects/${proj.id}`]) {
114
+ try { await fetch(`${SERVER}${p}`, { method: 'DELETE', headers: { Authorization: `Bearer ${lr.token}` } }) } catch { /* ignore */ }
115
+ }
116
+ console.log(' (best-effort cleanup done)')
117
+
118
+ console.log(`\n==== RESULT: ${pass} passed, ${fail} failed ====\n`)
119
+ process.exit(fail === 0 ? 0 : 1)
120
+ }
121
+
122
+ main().catch((e) => {
123
+ console.error('\nFATAL:', e instanceof ApiError ? `${e.message} (HTTP ${e.status})` : e)
124
+ process.exit(2)
125
+ })
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Typing-latency benchmark (scratch, not part of the suite).
3
+ *
4
+ * Mounts ChatScreen on a REAL Ink render (custom stdout PassThrough so the
5
+ * terminal isn't hijacked) and measures key→paint latency: from feeding a
6
+ * keystroke into the input stream to the first stdout write that follows.
7
+ *
8
+ * A/B: with MOBIUS_TUI_DISABLE_PAINT_FLUSH=1 the immediate-paint flush hook
9
+ * is disabled and Ink's stock 32ms throttle paces every keystroke paint.
10
+ *
11
+ * Run: npx tsx tests/perf-typing.tsx [history-count] [disable-flush]
12
+ */
13
+ import os from 'node:os'
14
+ import path from 'node:path'
15
+ import fs from 'node:fs'
16
+ import { PassThrough } from 'node:stream'
17
+
18
+ const TMP_HOME = fs.mkdtempSync(path.join(os.tmpdir(), 'mobius-tui-perf-'))
19
+ process.env.MOBIUS_TUI_HOME = TMP_HOME
20
+ process.env.MOBIUS_TUI_DISABLE_AIMUX = '1'
21
+
22
+ import React from 'react'
23
+ import { render } from 'ink'
24
+ import { ChatScreen } from '../src/components/Chat.js'
25
+ import { MobiusClient } from '../src/api.js'
26
+ import type { ReadyState } from '../src/components/PrepScreen.js'
27
+
28
+ const delay = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))
29
+ const RS: any = (globalThis as any).ReadableStream
30
+ const enc = new TextEncoder()
31
+
32
+ function json(body: unknown, status = 200) {
33
+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
34
+ }
35
+
36
+ function longEntry(i: number) {
37
+ const body = Array.from({ length: 8 }, (_, p) =>
38
+ `第 ${i} 段第 ${p} 句:这是一段比较长的助手回答,用来模拟真实会话里的 markdown 文本与代码块。`).join('\n\n')
39
+ return { type: 'assistant', uuid: `a-${i}`, message: { role: 'assistant', content: [{ type: 'text', text: body }] } }
40
+ }
41
+
42
+ async function bench(label: string, entryCount: number) {
43
+ const client = new MobiusClient('http://mock.local', 'tok')
44
+ const ready: ReadyState = {
45
+ project: { id: 'p1', name: 'p' },
46
+ issue: { id: 'i1', project_id: 'p1', title: 't' },
47
+ prefs: { model: 'm', language: 'zh', excluded_skill_ids: [], excluded_memory_ids: [] },
48
+ }
49
+ const history = Array.from({ length: entryCount }, (_, i) => longEntry(i))
50
+ ;(globalThis as any).fetch = ((url: any) => {
51
+ const u = String(url)
52
+ if (u.includes('/events')) {
53
+ return new Response(new RS({
54
+ start(c: any) {
55
+ c.enqueue(enc.encode('event: subscribed\ndata: {"event":"subscribed"}\n\n'))
56
+ },
57
+ }), { status: 200, headers: { 'content-type': 'text/event-stream' } })
58
+ }
59
+ // agent-history 协议 ①②: 订阅后 bootstrap 拉末尾组的全部条目 (旧 SSE 尾部回放的等价物).
60
+ if (u.endsWith('/api/sessions/s1/groups')) {
61
+ return json({ session_version: 1, groups: [{ id: 'g1', seq: 1, opener_ts: null, user_summary: '', version: 1, entry_count: history.length }] })
62
+ }
63
+ if (u.includes('/api/sessions/s1/groups/')) {
64
+ return json({ group_id: 'g1', version: 1, entries: history })
65
+ }
66
+ if (u.endsWith('/api/sessions/s1/status')) return json({ session_id: 's1', alive: true, working: false })
67
+ if (u.endsWith('/messages')) return json({ ok: true, session_id: 's1', turn_number: 1 })
68
+ return json({ error: 'no' }, 404)
69
+ }) as any
70
+
71
+ // Custom stdin/stdout PassThroughs; the instances WeakMap is keyed by THIS
72
+ // stdout, which is exactly what paint-flush looks up via useStdin().
73
+ const fakeStdin = new PassThrough() as any
74
+ // Ink enables raw mode only when stdin.isTTY; claim TTY with no-op raw-mode
75
+ // (+ref/unref, which raw-mode enablement calls) so useInput subscribes and
76
+ // keystrokes reach the Composer.
77
+ fakeStdin.isTTY = true
78
+ fakeStdin.setRawMode = () => {}
79
+ fakeStdin.ref = () => {}
80
+ fakeStdin.unref = () => {}
81
+ const fakeStdout = new PassThrough() as any
82
+ fakeStdout.columns = 100
83
+ fakeStdout.rows = 30
84
+ fakeStdout.isTTY = false
85
+ let keyAt = 0
86
+ let paints: number[] = []
87
+ const realWrite = fakeStdout.write.bind(fakeStdout)
88
+ fakeStdout.write = (...args: any[]) => {
89
+ if (keyAt) paints.push(performance.now() - keyAt)
90
+ return realWrite(...(args as [any, any?, (() => void)?]))
91
+ }
92
+ // Drain the output so the PassThrough never fills.
93
+ fakeStdout.on('data', () => {})
94
+
95
+ const instance = render(
96
+ React.createElement(ChatScreen, {
97
+ client, ready, webUserId: 'u', resumeSessionId: 's1',
98
+ onClear: () => {}, onResume: () => {}, onQuit: () => {}, onLogout: () => {},
99
+ onReconfigure: () => {}, onConfigCancel: () => {},
100
+ }),
101
+ { stdin: fakeStdin, stdout: fakeStdout, patchConsole: false },
102
+ )
103
+ await delay(500) // SSE connect + history replay
104
+
105
+ const lat: number[] = []
106
+ for (let i = 0; i < 12; i++) {
107
+ paints = []
108
+ keyAt = performance.now()
109
+ fakeStdin.write('字')
110
+ await delay(80)
111
+ keyAt = 0
112
+ lat.push(paints.length ? Math.min(...paints) : 999)
113
+ }
114
+ lat.sort((a, b) => a - b)
115
+ instance.unmount()
116
+ const median = lat[Math.floor(lat.length / 2)]
117
+ const p90 = lat[Math.floor(lat.length * 0.9)]
118
+ console.log(`${label} (${entryCount} 条历史): key→paint 中位 ${median.toFixed(1)}ms · p90 ${p90.toFixed(1)}ms · 样本 ${lat.map(t => t.toFixed(0)).join(',')}`)
119
+ }
120
+
121
+ async function main() {
122
+ const count = Number(process.argv[2] ?? 300) || 300
123
+ const disableFlush = process.argv[3] === 'noflush'
124
+ process.env.MOBIUS_TUI_DISABLE_PAINT_FLUSH = disableFlush ? '1' : ''
125
+ await bench(disableFlush ? '基线(无 flush)' : 'flush 生效 ', count)
126
+ fs.rmSync(TMP_HOME, { recursive: true, force: true })
127
+ }
128
+ main().catch(e => { console.error(e); process.exit(2) })
@@ -0,0 +1,104 @@
1
+ /**
2
+ * 一次性预览: 把典型 jsonl entry 喂进新的 mergeToolCalls → viewsForBlock,
3
+ * 按 Chat.tsx 的 ViewLine 格式打印, 直观验证"对齐 web"后的渲染效果.
4
+ * 跑: npx tsx tests/preview.tsx (看完可删)
5
+ */
6
+ import { mergeToolCalls, viewsForBlock, toolLabel } from '../src/lib/entry-view.js'
7
+
8
+ // ── 典型 entry 构造 (Claude SDK 形态) ──────────────────────────────────────
9
+ const entries: any[] = [
10
+ // 1. 用户提问
11
+ { type: 'user', uuid: 'u1', message: { content: '帮我把 getData 改成 async 实现' } },
12
+
13
+ // 2. assistant 文本回复 (full 完整展示)
14
+ { type: 'assistant', uuid: 'a1', message: { content: [{ type: 'text', text: '好的,改成 async/await 实现。\n\n主要改动:\n1. 加 async 关键字\n2. await 替换 .then()\n3. try/catch 错误处理' }] } },
15
+
16
+ // 3. Read 命令 + 结果 (compact, 合并成一块, ≤2 行)
17
+ { type: 'assistant', uuid: 'a2', message: { content: [{ type: 'tool_use', id: 't1', name: 'Read', input: { file_path: '/src/foo.ts' } }] } },
18
+ { type: 'user', uuid: 'u2', message: { content: [{ type: 'tool_result', tool_use_id: 't1', content: 'export function getData() {\n return fetch(url);\n}\n\n// ... 还有 200 行省略' }] } },
19
+
20
+ // 4. Edit 代码修改 (full: old−/new+ 完整展示)
21
+ { type: 'assistant', uuid: 'a3', message: { content: [{ type: 'tool_use', id: 't2', name: 'Edit', input: { file_path: '/src/foo.ts', old_string: 'export function getData() {\n return fetch(url);\n}', new_string: 'export async function getData() {\n const res = await fetch(url);\n return res.json();\n}' } }] } },
22
+ { type: 'user', uuid: 'u3', message: { content: [{ type: 'tool_result', tool_use_id: 't2', content: 'The file /src/foo.ts has been updated.' }] } },
23
+
24
+ // 5. Bash 命令 + 长结果 (compact, 合并, ≤2 行)
25
+ { type: 'assistant', uuid: 'a4', message: { content: [{ type: 'tool_use', id: 't3', name: 'Bash', input: { command: 'npm run typecheck' } }] } },
26
+ { type: 'user', uuid: 'u4', message: { content: [{ type: 'tool_result', tool_use_id: 't3', content: '> @mobius-os/mobius typecheck\n> tsc --noEmit\n\nAll good. 还有非常多非常多的编译输出行全部应该被压成一行省略号...' }] } },
27
+
28
+ // 6. reasoning 思考 (compact, ≤2 行)
29
+ { type: 'assistant', uuid: 'a5', message: { content: [{ type: 'thinking', thinking: '用户要改异步实现,先读代码理解同步逻辑,再用 async/await 重写。要注意错误处理和返回值结构。这段思考过程非常非常长,必须被 clampLines 硬截断到最多两行,超出部分末尾加省略号。' }] } },
30
+
31
+ // 7. 噪声 (应被隐藏, 不显示)
32
+ { type: 'event_msg', uuid: 'n1', payload: { type: 'token_count', input_tokens: 1234, output_tokens: 567 } },
33
+ { type: 'session_meta', uuid: 'n2', payload: { cwd: '/repo', model: 'gpt-5' } },
34
+ { type: 'turn_context', uuid: 'n4', payload: { turn_id: 't0' } },
35
+
36
+ // 8. context_compacted (对齐 web: 不再隐藏, 显示成 system 行)
37
+ { type: 'event_msg', uuid: 'n3', payload: { type: 'context_compacted' } },
38
+
39
+ // 9. error (full 完整展示)
40
+ { type: 'event_msg', uuid: 'e1', payload: { type: 'error', message: '模型连接超时,请检查网络后重试' } },
41
+ ]
42
+
43
+ // ── 模拟 Chat.tsx ViewLine 的格式 (带 ANSI 颜色) ─────────────────────────
44
+ const WIDTH = 76
45
+ const C = { red: '\x1b[31m', green: '\x1b[32m', cyan: '\x1b[36m', magenta: '\x1b[35m', yellow: '\x1b[33m', dim: '\x1b[2m', bold: '\x1b[1m', reset: '\x1b[0m' }
46
+
47
+ function clamp(text: string, width: number, max: number): string[] {
48
+ if (!text) return ['']
49
+ const paras = text.replace(/\r\n/g, '\n').split('\n')
50
+ const wrapped: string[] = []
51
+ for (const p of paras) {
52
+ if (p === '') { wrapped.push(''); continue }
53
+ for (let i = 0; i < p.length; i += width) wrapped.push(p.slice(i, i + width))
54
+ }
55
+ if (wrapped.length <= max) return wrapped
56
+ const t = wrapped.slice(0, max)
57
+ const last = t[max - 1]
58
+ t[max - 1] = last.length >= width ? last.slice(0, width - 1) + '…' : last + '…'
59
+ return t
60
+ }
61
+
62
+ console.log(`${C.dim}═══ 合并后渲染预览 (width=76, 对齐 web 过滤) ═══${C.reset}\n`)
63
+ const blocks = mergeToolCalls(entries)
64
+ console.log(`${C.dim}[原始 ${entries.length} 条 entry → 合并后 ${blocks.length} 个 block]${C.reset}\n`)
65
+
66
+ for (const block of blocks) {
67
+ for (const view of viewsForBlock(block)) {
68
+ switch (view.kind) {
69
+ case 'skip':
70
+ break
71
+ case 'user':
72
+ console.log(`\n${C.bold}› ${view.text}${C.reset}`)
73
+ break
74
+ case 'assistant':
75
+ console.log(`${C.bold}•${C.reset} ${view.text}`)
76
+ break
77
+ case 'tool_call': {
78
+ const head = clamp(`${toolLabel(view.toolName)} ${view.summary}`.trim(), WIDTH - 2, 1)[0]
79
+ console.log(`${C.cyan}• ${head}${C.reset}`)
80
+ if (view.result) console.log(`${C.dim} └ ${clamp(view.result.text, WIDTH - 4, 1)[0] || '(无输出)'}${C.reset}`)
81
+ break
82
+ }
83
+ case 'code_edit':
84
+ console.log(`${C.magenta}✎ 编辑 ${view.filePath || '(未指定文件)'}${C.reset}`)
85
+ for (const l of view.oldString.split('\n')) console.log(` ${C.red}−${C.reset} ${l}`)
86
+ for (const l of view.newString.split('\n')) console.log(` ${C.green}+${C.reset} ${l}`)
87
+ break
88
+ case 'write_file':
89
+ console.log(`${C.magenta}✎ 写入 ${view.filePath || '(未指定文件)'}${C.reset}`)
90
+ for (const l of view.content.split('\n')) console.log(` ${C.green}+${C.reset} ${l}`)
91
+ break
92
+ case 'reasoning':
93
+ clamp(view.text, WIDTH - 4, 2).forEach((l, i) => console.log(`${C.dim}${C.magenta} ◇ ${l}${C.reset}`))
94
+ break
95
+ case 'system':
96
+ console.log(`${C.dim}${C.yellow} ${clamp(view.text, WIDTH - 2, 2)[0]}${C.reset}`)
97
+ break
98
+ case 'error':
99
+ console.log(`${C.red}⚠ ${view.text}${C.reset}`)
100
+ break
101
+ }
102
+ }
103
+ }
104
+ console.log(`\n${C.dim}═══ 预览结束 ═══${C.reset}`)