tui.snapshot.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. import { cp, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
  2. import { tmpdir } from 'node:os'
  3. import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path'
  4. import { fileURLToPath } from 'node:url'
  5. import { afterAll, describe, expect, it, vi } from 'vitest'
  6. import { Context } from 'cordis'
  7. import { scrubRequestHeaders, tokenizeSessionFixtureCwd } from '@deepseek-ai/dsh-acp-snapshot'
  8. import type { Agent } from '@deepseek-ai/dsh-agent'
  9. import * as AgentCore from '@deepseek-ai/dsh-agent-spine-demo'
  10. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  11. import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local'
  12. import WorkerCodeRuntime from '@deepseek-ai/dsh-code-runtime-worker'
  13. import CommandService from '@deepseek-ai/dsh-commands'
  14. import LocalFileSystem from '@deepseek-ai/dsh-fs-local'
  15. import * as FsPolicy from '@deepseek-ai/dsh-fs-policy'
  16. import * as ToolFs from '@deepseek-ai/dsh-tool-fs'
  17. import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek'
  18. import { installLlmReplay, parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
  19. import PlanModeService from '@deepseek-ai/dsh-plan-mode'
  20. import TokenMeterService from '@deepseek-ai/dsh-token-meter'
  21. import { packChunkRuns, SessionId, type Session, type SessionEvent } from '@deepseek-ai/dsh-session'
  22. import SubagentService from '@deepseek-ai/dsh-subagent'
  23. import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn'
  24. import * as ToolSubagent from '@deepseek-ai/dsh-tool-subagent'
  25. import * as ToolCordis from '@deepseek-ai/dsh-tool-cordis'
  26. import * as ToolTodo from '@deepseek-ai/dsh-tool-todo'
  27. import * as ToolRalph from '@deepseek-ai/dsh-tool-ralph'
  28. import * as ToolWorkflow from '@deepseek-ai/dsh-tool-workflow'
  29. import { createTuiChat, FILE_REFERENCE_PROMPT, TuiPromptService } from '@deepseek-ai/dsh-tui'
  30. import LocalSpillStore from '@deepseek-ai/dsh-spill-local'
  31. import * as SpillPolicy from '@deepseek-ai/dsh-spill-policy'
  32. import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
  33. import WorkerWorkflowEngine from '@deepseek-ai/dsh-workflow-workerthread'
  34. import { HeadlessTerminal } from '../../../packages/ui/tui/tests/headless-terminal.ts'
  35. const SNAPSHOTS_DIR = join(dirname(fileURLToPath(import.meta.url)), 'snapshots')
  36. // Keep pre-normalization layout widths identical across macOS and Linux.
  37. const SNAPSHOT_TMP_ROOT = process.platform === 'win32' ? tmpdir() : '/tmp'
  38. const PROVIDERS = [{ id: 'deepseek', models: [{ id: 'deepseek-v4-flash', contextWindow: 128_000 }] }]
  39. const UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi
  40. type SnapshotMode = 'replay' | 'record' | 'refresh'
  41. type Composition = 'native' | 'code' | 'advanced'
  42. interface Scenario {
  43. name: string
  44. composition: Composition
  45. expectedTools: string[]
  46. expectedEventCounts?: Record<string, number>
  47. childSessions?: number
  48. enterPlanMode?: boolean
  49. leavePlanModeAfterFirstTurn?: boolean
  50. recorded: boolean
  51. seedWorkspace?: boolean
  52. /**
  53. * Load the opt-in `todo_write` tool for this scenario. The shipped tui-agent
  54. * config omits it, so only the todo-plan scenario (the enabled-path proof)
  55. * mounts it; the rest cover the default, todo-free composition.
  56. */
  57. enableTodo?: boolean
  58. /**
  59. * Mount the spill stack (local backend + policy) with this inline cap, as the
  60. * shipped configs do. The dispatch-spill scenario proves the durable
  61. * `tool/code-dispatch` copy of an oversized sub-result is bounded to a
  62. * preview + locator while the program value stays whole.
  63. */
  64. spillMaxInlineBytes?: number
  65. }
  66. const SCENARIOS: Scenario[] = [
  67. {
  68. name: 'multi-turn-conversation',
  69. composition: 'native',
  70. expectedTools: [],
  71. expectedEventCounts: { 'plan/mode': 2 },
  72. enterPlanMode: true,
  73. leavePlanModeAfterFirstTurn: true,
  74. recorded: true,
  75. },
  76. {
  77. name: 'todo-plan',
  78. composition: 'native',
  79. expectedTools: ['todo_write'],
  80. expectedEventCounts: { 'todo/write': 1 },
  81. recorded: true,
  82. enableTodo: true,
  83. },
  84. {
  85. name: 'bash-terminal-card',
  86. composition: 'native',
  87. expectedTools: ['bash'],
  88. recorded: true,
  89. },
  90. {
  91. name: 'parallel-file-reads',
  92. composition: 'native',
  93. expectedTools: ['read', 'read'],
  94. recorded: true,
  95. seedWorkspace: true,
  96. },
  97. {
  98. name: 'code-mode',
  99. composition: 'code',
  100. expectedTools: ['run_code'],
  101. expectedEventCounts: { 'tool/code-dispatch': 2 },
  102. recorded: true,
  103. },
  104. {
  105. name: 'code-mode-dispatch-spill',
  106. composition: 'code',
  107. expectedTools: ['run_code'],
  108. expectedEventCounts: { 'tool/code-dispatch-start': 1, 'tool/code-dispatch': 1 },
  109. recorded: true,
  110. spillMaxInlineBytes: 600,
  111. },
  112. {
  113. name: 'dynamic-workflow',
  114. composition: 'native',
  115. expectedTools: ['workflow'],
  116. childSessions: 1,
  117. recorded: true,
  118. },
  119. {
  120. name: 'cordis-dynamic-toolchain',
  121. composition: 'advanced',
  122. expectedTools: ['cordis_mount', 'run_code', 'subagent', 'workflow', 'cordis_unmount'],
  123. expectedEventCounts: { 'tool/code-dispatch': 1 },
  124. childSessions: 2,
  125. recorded: false,
  126. },
  127. ]
  128. function snapshotModeFromEnv(value: string | undefined): SnapshotMode {
  129. if (value === undefined || value === '' || value === 'replay') return 'replay'
  130. if (value === 'record' || value === 'refresh') return value
  131. throw new Error(`DSH_SNAPSHOT must be replay, record, or refresh; got ${JSON.stringify(value)}`)
  132. }
  133. const MODE = snapshotModeFromEnv(process.env.DSH_SNAPSHOT)
  134. const observedScenarios = new Set<string>()
  135. function snapshotDisplayPath(displayPath: string, cwd: string, displayCwd: string): string {
  136. const rel = relative(cwd, displayPath)
  137. if (rel === '') return displayCwd
  138. if (isAbsolute(rel) || rel === '..' || rel.startsWith(`..${sep}`)) return displayPath
  139. return `${displayCwd}/${rel.split(sep).join('/')}`
  140. }
  141. function scenarioDir(scenario: Scenario): string {
  142. return join(SNAPSHOTS_DIR, scenario.name)
  143. }
  144. function childFixturePaths(scenario: Scenario): string[] {
  145. return Array.from(
  146. { length: scenario.childSessions ?? 0 },
  147. (_, index) => join(scenarioDir(scenario), `session.${index + 1}.jsonl`),
  148. )
  149. }
  150. function userPrompts(rawLog: string): string[] {
  151. return parseSessionLog(rawLog).flatMap((event) => {
  152. if (event.type !== 'user/message' || event.data.source.kind !== 'user') return []
  153. const text = event.data.content
  154. .filter(block => block.type === 'text')
  155. .map(block => block.text)
  156. .join('')
  157. return text.length > 0 ? [text] : []
  158. })
  159. }
  160. function rawSessionLog(session: Session): string {
  161. return [
  162. JSON.stringify({ type: 'session', ...session.header }),
  163. ...packChunkRuns(session.events).map(record => JSON.stringify(record)),
  164. '',
  165. ].join('\n')
  166. }
  167. function normalizeTerminalSnapshot(snapshot: string, cwd: string, displayCwd: string): string {
  168. return snapshot
  169. .split(`/private${cwd}`).join('/workspace/project')
  170. .split(displayCwd).join('/workspace/project')
  171. .split(cwd).join('/workspace/project')
  172. .replace(UUID_RE, '{{uuid}}')
  173. }
  174. async function settleTerminal(terminal: HeadlessTerminal): Promise<void> {
  175. let stable = 0
  176. for (let attempt = 0; attempt < 20 && stable < 3; attempt++) {
  177. const before = terminal.frames
  178. await new Promise(resolve => setTimeout(resolve, 10))
  179. await terminal.flush()
  180. stable = terminal.frames === before ? stable + 1 : 0
  181. }
  182. if (stable < 3) throw new Error('TUI frames did not quiesce within 200ms')
  183. }
  184. async function mountScenarioContext(
  185. scenario: Scenario,
  186. cwd: string,
  187. displayCwd: string,
  188. fixtureFile: string,
  189. childFiles: string[],
  190. ): Promise<Context> {
  191. class SnapshotLocalFileSystem extends LocalFileSystem {
  192. override async resolve(
  193. path: string,
  194. opts?: { cwd?: string; signal?: AbortSignal },
  195. ): Promise<Awaited<ReturnType<LocalFileSystem['resolve']>>> {
  196. const target = await super.resolve(path, opts)
  197. return { ...target, displayPath: snapshotDisplayPath(target.displayPath, cwd, displayCwd) }
  198. }
  199. }
  200. const ctx = new Context()
  201. await ctx.plugin(AgentCore, {
  202. agents: [],
  203. dshHome: join(cwd, '.dsh'),
  204. workspaceContext: false,
  205. tools: { mode: scenario.composition === 'code' ? 'code' : scenario.composition === 'advanced' ? 'both' : 'native' },
  206. skills: { local: { agentsHome: join(cwd, '.agents') } },
  207. })
  208. await ctx.plugin(TokenMeterService)
  209. await ctx.plugin(LocalSubprocessService)
  210. await ctx.plugin(LocalBashExecutor, { cwd, timeoutMs: 30_000 })
  211. await ctx.plugin(SnapshotLocalFileSystem, { cwd: '/' })
  212. await ctx.plugin(FsPolicy)
  213. await ctx.plugin(ToolFs)
  214. await ctx.plugin(UserInteractionService)
  215. await ctx.plugin(TuiPromptService)
  216. // todo_write is opt-in: only the todo-plan scenario mounts it, matching the shipped
  217. // config that omits it. The other scenarios prove the default todo-free composition.
  218. if (scenario.enableTodo === true) await ctx.plugin(ToolTodo)
  219. await ctx.plugin(SubagentService)
  220. await ctx.plugin(SubagentSpawn, { providerName: 'spawn' })
  221. await ctx.plugin(ToolSubagent, { provider: 'spawn', toolName: 'subagent', enableRunInBackground: false })
  222. await ctx.plugin(WorkerWorkflowEngine, { provider: 'spawn' })
  223. await ctx.plugin(ToolWorkflow)
  224. await ctx.plugin(ToolRalph)
  225. await ctx.plugin(CommandService)
  226. if (scenario.enterPlanMode === true) {
  227. await ctx.plugin(PlanModeService, { section: 'Snapshot plan mode instructions.' })
  228. }
  229. if (scenario.composition === 'code' || scenario.composition === 'advanced') {
  230. await ctx.plugin(WorkerCodeRuntime, {})
  231. }
  232. if (scenario.spillMaxInlineBytes !== undefined) {
  233. await ctx.plugin(LocalSpillStore, { root: join(cwd, '.spill') })
  234. await ctx.plugin(SpillPolicy, { maxInlineBytes: scenario.spillMaxInlineBytes })
  235. }
  236. if (scenario.composition === 'advanced') await ctx.plugin(ToolCordis, { vmTimeoutMs: 5_000 })
  237. if (MODE === 'record' && scenario.recorded) {
  238. await ctx.plugin(LlmDeepSeek)
  239. } else {
  240. installLlmReplay(ctx, { file: fixtureFile, childFiles, providers: PROVIDERS })
  241. }
  242. return ctx
  243. }
  244. interface ScenarioResult {
  245. terminal: string
  246. parent: Session
  247. children: Session[]
  248. workflowEvents: string[]
  249. }
  250. async function runScenario(scenario: Scenario): Promise<ScenarioResult> {
  251. const clock = vi.spyOn(Date, 'now').mockReturnValue(new Date(2026, 6, 21, 12, 0, 0).getTime())
  252. const dir = scenarioDir(scenario)
  253. const fixtureFile = join(dir, 'session.jsonl')
  254. const childFiles = childFixturePaths(scenario)
  255. const fixture = await readFile(fixtureFile, 'utf8')
  256. const prompts = userPrompts(fixture)
  257. expect(prompts.length, `${scenario.name} must carry at least one recorded user prompt`).toBeGreaterThan(0)
  258. const cwd = await mkdtemp(join(SNAPSHOT_TMP_ROOT, `dsh-tui-snapshot-${scenario.name}-`))
  259. const displayCwd = `/tmp/${basename(cwd)}`
  260. let ctx: Context | undefined
  261. let controller: ReturnType<typeof createTuiChat> | undefined
  262. const terminal = new HeadlessTerminal(100, 36)
  263. try {
  264. if (scenario.seedWorkspace === true) {
  265. const source = join(scenarioDir(scenario), 'workspace')
  266. await cp(source, cwd, { recursive: true })
  267. }
  268. ctx = await mountScenarioContext(scenario, cwd, displayCwd, fixtureFile, childFiles)
  269. const disposedSessions: Session[] = []
  270. ctx.on('session/disposed', (session) => { disposedSessions.push(session) })
  271. const workflowEvents: string[] = []
  272. for (const name of ['workflow/start', 'workflow/phase', 'workflow/agent-start', 'workflow/agent-end', 'workflow/end'] as const) {
  273. ctx.on(name, () => { workflowEvents.push(name) })
  274. }
  275. const handle = await ctx.agents.create({
  276. sessionId: SessionId('main-session'),
  277. meta: { cwd },
  278. agentOptions: { provider: 'deepseek', model: 'deepseek-v4-flash' },
  279. })
  280. const agent: Agent = handle.agent
  281. controller = createTuiChat(ctx, {
  282. sessionId: 'main-session',
  283. theme: { color: true },
  284. showReasoning: true,
  285. title: 'DSH TUI snapshot',
  286. welcome: `Recorded replay: ${scenario.name}`,
  287. maxToolOutputLines: 8,
  288. }, {
  289. terminal,
  290. exit: () => {},
  291. formatCwd: () => displayCwd,
  292. })
  293. await settleTerminal(terminal)
  294. let remainingPrompts = prompts
  295. if (scenario.enterPlanMode === true) {
  296. const firstPrompt = prompts[0]!
  297. terminal.send(`/plan ${firstPrompt}`)
  298. terminal.send('\r')
  299. await agent.whenIdle()
  300. await settleTerminal(terminal)
  301. remainingPrompts = prompts.slice(1)
  302. }
  303. if (scenario.leavePlanModeAfterFirstTurn === true) {
  304. terminal.send('/plan off')
  305. terminal.send('\r')
  306. await settleTerminal(terminal)
  307. }
  308. for (const prompt of remainingPrompts) {
  309. terminal.send(prompt)
  310. terminal.send('\r')
  311. await agent.whenIdle()
  312. await settleTerminal(terminal)
  313. }
  314. const events: SessionEvent[] = [...agent.session.events]
  315. const firstHeader = events.find(event => event.type === 'request/header')
  316. expect(firstHeader?.type === 'request/header' && firstHeader.data.header.system)
  317. .toContain(FILE_REFERENCE_PROMPT)
  318. expect(events.filter(event => event.type === 'tool/call').map(event => event.data.name)).toEqual(scenario.expectedTools)
  319. for (const [type, count] of Object.entries(scenario.expectedEventCounts ?? {})) {
  320. expect(events.filter(event => event.type === type), `${scenario.name} must emit ${type}`).toHaveLength(count)
  321. }
  322. if (scenario.enterPlanMode === true) {
  323. expect(ctx.planMode.get(agent)).toEqual({
  324. active: scenario.leavePlanModeAfterFirstTurn !== true,
  325. })
  326. const planMode = events.find(event => event.type === 'plan/mode')
  327. if (planMode === undefined || firstHeader === undefined) {
  328. throw new Error('plan-mode command snapshot needs plan/mode before its first request/header')
  329. }
  330. expect(planMode.seq).toBeLessThan(firstHeader.seq)
  331. expect(firstHeader.data.header.system).toContain('Snapshot plan mode instructions.')
  332. const firstMessage = events.find(event => event.type === 'user/message')
  333. expect(firstMessage?.data.content).toEqual([{ type: 'text', text: prompts[0] }])
  334. }
  335. if (scenario.leavePlanModeAfterFirstTurn === true) {
  336. const planModes = events.filter(event => event.type === 'plan/mode')
  337. expect(planModes.map(event => event.data.active)).toEqual([true, false])
  338. const headers = events.filter(event => event.type === 'request/header')
  339. const exit = planModes[1]
  340. const afterExit = headers[1]
  341. if (exit === undefined || afterExit === undefined) {
  342. throw new Error('active plan exit snapshot needs a committed exit and changed request header')
  343. }
  344. expect(exit.seq).toBeLessThan(afterExit.seq)
  345. expect(afterExit.data.header.system).not.toContain('Snapshot plan mode instructions.')
  346. expect(events.filter(event => event.type === 'user/message' && event.data.source.kind === 'plugin').map(event => (event.data as { content: unknown }).content))
  347. .toContainEqual([{ type: 'text', text: 'The user switched this session back to the default mode.' }])
  348. }
  349. if (scenario.spillMaxInlineBytes !== undefined) {
  350. // The REAL pipeline ran (tools execute on replay too): the durable
  351. // dispatch copy is bounded to a preview + locator under the run cwd,
  352. // while the outer result still carries the program's whole value.
  353. const dispatch = events.find(event => (event.type as string) === 'tool/code-dispatch')
  354. const content = (dispatch?.data as { content: { type: string; text?: string }[] }).content
  355. const text = content.filter(block => block.type === 'text').map(block => block.text ?? '').join('')
  356. expect(Buffer.byteLength(text, 'utf8')).toBeLessThanOrEqual(scenario.spillMaxInlineBytes)
  357. expect(text).toContain('Full formatted result stored at:')
  358. expect(text).toContain('.spill')
  359. }
  360. expect(events.filter(event => event.type === 'tool/result').every(event => !event.data.message.content[0].isError)).toBe(true)
  361. expect(events.filter(event => event.type === 'turn/end').every(event => event.data.reason.kind !== 'error')).toBe(true)
  362. if (scenario.name === 'dynamic-workflow' || scenario.name === 'cordis-dynamic-toolchain') {
  363. expect(workflowEvents).toEqual([
  364. 'workflow/start',
  365. 'workflow/phase',
  366. 'workflow/agent-start',
  367. 'workflow/agent-end',
  368. 'workflow/end',
  369. ])
  370. }
  371. expect(terminal.themeViolations(), `${scenario.name} must remain theme-agnostic`).toEqual([])
  372. const snapshot = normalizeTerminalSnapshot(
  373. await terminal.snapshot({ includeScrollback: true }),
  374. cwd,
  375. displayCwd,
  376. )
  377. await handle.dispose()
  378. const children = disposedSessions
  379. .filter(session => session !== agent.session)
  380. .sort((a, b) => a.header.createdAt - b.header.createdAt)
  381. expect(children).toHaveLength(scenario.childSessions ?? 0)
  382. return { terminal: snapshot, parent: agent.session, children, workflowEvents }
  383. } finally {
  384. await controller?.dispose()
  385. await ctx?.fiber.dispose()
  386. await terminal.dispose()
  387. await rm(cwd, { recursive: true, force: true })
  388. clock.mockRestore()
  389. }
  390. }
  391. async function writeRecording(scenario: Scenario, result: ScenarioResult): Promise<void> {
  392. const dir = scenarioDir(scenario)
  393. await mkdir(dir, { recursive: true })
  394. await writeFile(
  395. join(dir, 'session.jsonl'),
  396. scrubRequestHeaders(tokenizeSessionFixtureCwd(rawSessionLog(result.parent))),
  397. )
  398. expect(result.children).toHaveLength(scenario.childSessions ?? 0)
  399. for (const [index, child] of result.children.entries()) {
  400. await writeFile(
  401. join(dir, `session.${index + 1}.jsonl`),
  402. scrubRequestHeaders(tokenizeSessionFixtureCwd(rawSessionLog(child))),
  403. )
  404. }
  405. }
  406. describe('TUI recorded-session terminal snapshots', () => {
  407. for (const scenario of SCENARIOS) {
  408. it(scenario.name, async () => {
  409. observedScenarios.add(scenario.name)
  410. const result = await runScenario(scenario)
  411. const terminalFile = join(scenarioDir(scenario), 'terminal.expected.txt')
  412. if (MODE === 'record' || MODE === 'refresh') {
  413. await mkdir(scenarioDir(scenario), { recursive: true })
  414. await writeFile(terminalFile, result.terminal)
  415. }
  416. if (MODE === 'record' && scenario.recorded) await writeRecording(scenario, result)
  417. await expect(result.terminal).toMatchFileSnapshot(terminalFile)
  418. }, 120_000)
  419. }
  420. })
  421. afterAll(async () => {
  422. expect([...observedScenarios].sort()).toEqual(SCENARIOS.map(scenario => scenario.name).sort())
  423. const directories = (await readdir(SNAPSHOTS_DIR, { withFileTypes: true }))
  424. .filter(entry => entry.isDirectory())
  425. .map(entry => entry.name)
  426. .sort()
  427. expect(directories).toEqual(SCENARIOS.map(scenario => scenario.name).sort())
  428. for (const scenario of SCENARIOS) {
  429. const expected = [
  430. 'session.jsonl',
  431. 'terminal.expected.txt',
  432. ...scenario.seedWorkspace === true ? ['workspace'] : [],
  433. ...Array.from({ length: scenario.childSessions ?? 0 }, (_, index) => `session.${index + 1}.jsonl`),
  434. ].sort()
  435. expect((await readdir(scenarioDir(scenario))).sort()).toEqual(expected)
  436. for (const fixture of ['session.jsonl', ...childFixturePaths(scenario).map(path => basename(path))]) {
  437. const content = await readFile(join(scenarioDir(scenario), fixture), 'utf8')
  438. expect(scrubRequestHeaders(content), `${scenario.name}/${fixture} carries request-header bulk`).toBe(content)
  439. }
  440. }
  441. })