stdio-chat.spec.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. import { Readable, Writable } from 'node:stream'
  2. import { describe, expect, it, vi } from 'vitest'
  3. import { Context } from 'cordis'
  4. import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent'
  5. import AgentRegistry from '@deepseek-ai/dsh-agent'
  6. import type { ContentBlock, StreamChunk } from '@deepseek-ai/dsh-llm'
  7. import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
  8. import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
  9. import { createStdioChat, type Config, type StdioRuntime } from '../src/stdio-chat.ts'
  10. /**
  11. * Unit tests for the stdio UI plugin. They drive the REAL plugin body
  12. * (`createStdioChat`) with an injected {@link StdioRuntime} so every render,
  13. * input, EOF, and disposal branch runs without touching the real `process`
  14. * streams — the I/O seam is what makes the per-file gate reachable. The
  15. * `agents` service is real (`@deepseek-ai/dsh-agent`); a minimal fake `Agent`
  16. * stands in for the loop, since the loop is the genuinely expensive collaborator
  17. * and we only need its `status` + `send`/`steer` surface here.
  18. */
  19. /** A controllable stdin: a Readable we push lines into and can end on demand. */
  20. function makeInput(): Readable & { feed(line: string): void; finish(): void } {
  21. const stream = new Readable({ read() {} }) as Readable & { feed(line: string): void; finish(): void }
  22. stream.feed = (line: string) => stream.push(`${line}\n`)
  23. stream.finish = () => stream.push(null)
  24. return stream
  25. }
  26. /** A stdout sink that accumulates everything written, for assertions. */
  27. function makeOutput(): { write: (s: string) => boolean; text: () => string } {
  28. let buf = ''
  29. return { write: (s: string) => { buf += s; return true }, text: () => buf }
  30. }
  31. function makeRuntime(over: Partial<StdioRuntime> = {}): {
  32. runtime: StdioRuntime
  33. input: ReturnType<typeof makeInput>
  34. out: ReturnType<typeof makeOutput>
  35. exit: ReturnType<typeof vi.fn>
  36. } {
  37. const input = makeInput()
  38. const out = makeOutput()
  39. const exit = vi.fn()
  40. return { runtime: { input, output: { write: out.write } as never, exit, ...over }, input, out, exit }
  41. }
  42. /** A minimal Agent fake exposing the surface the UI touches. */
  43. function makeAgent(id: string, status: AgentStatus = 'idle'): Agent & {
  44. status: AgentStatus
  45. sent: ContentBlock[][]
  46. steered: ContentBlock[][]
  47. } {
  48. const sent: ContentBlock[][] = []
  49. const steered: ContentBlock[][] = []
  50. return {
  51. id: id as Agent['id'],
  52. status,
  53. sent,
  54. steered,
  55. // A minimal session stub: the UI reads only `session.header.id` (to map the
  56. // session back to its agent id for the turn-boundary label).
  57. session: { header: { id: `${id}-session` } },
  58. send: (content: ContentBlock[]) => void sent.push(content),
  59. steer: (content: ContentBlock[]) => void steered.push(content),
  60. } as never
  61. }
  62. /** A session stub whose `header.id` matches an agent's, for `session/event` emits. */
  63. function makeSession(agentId: string): Session {
  64. return { header: { id: `${agentId}-session` } } as Session
  65. }
  66. /** An `assistant/chunk` session event carrying one raw stream chunk. */
  67. function chunkEvent(chunk: StreamChunk): SessionEvent {
  68. return { type: 'assistant/chunk', seq: 0, time: 0, data: { turn: 1, step: 0, chunk } }
  69. }
  70. const CONFIG: Config = { welcome: 'hi there', agent: 'main' }
  71. async function setup(config: Config = CONFIG, runtimeOver: Partial<StdioRuntime> = {}) {
  72. const ctx = new Context()
  73. await ctx.plugin(AgentRegistry)
  74. await ctx.plugin(UserInteractionService)
  75. const { runtime, input, out, exit } = makeRuntime(runtimeOver)
  76. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  77. createStdioChat(inner, config, runtime)
  78. }, { inject: ['agents', 'userInteraction'] }))
  79. return { ctx, fiber, input, out, exit }
  80. }
  81. /** Drive a fake idle timer past the 200ms flush delay. */
  82. function flushExit(): Promise<void> {
  83. return new Promise(resolve => setTimeout(resolve, 250))
  84. }
  85. describe('createStdioChat rendering', () => {
  86. it('writes the welcome banner and prompt on start', async () => {
  87. const { out } = await setup()
  88. expect(out.text()).toBe('hi there\n> ')
  89. })
  90. it('falls back to default welcome/agent when called with empty config', async () => {
  91. // createStdioChat is exported and may be driven directly (bypassing the
  92. // Loader's schemastery validation), so it must default welcome/agent itself.
  93. const { out } = await setup({})
  94. expect(out.text()).toBe('ready.\n> ')
  95. // And it drives the default agent id 'main'.
  96. })
  97. it('detects readline terminal mode from both stream TTY flags', async () => {
  98. for (const [inputTTY, outputTTY] of [[true, false], [true, true]] as const) {
  99. const ctx = new Context()
  100. await ctx.plugin(AgentRegistry)
  101. await ctx.plugin(UserInteractionService)
  102. let text = ''
  103. const output = new Writable({
  104. write(chunk, _encoding, callback) {
  105. text += String(chunk)
  106. callback()
  107. },
  108. }) as Writable & { isTTY?: boolean }
  109. const { runtime } = makeRuntime({ output })
  110. ;(runtime.input as Readable & { isTTY?: boolean }).isTTY = inputTTY
  111. output.isTTY = outputTTY
  112. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  113. createStdioChat(inner, CONFIG, runtime)
  114. }, { inject: ['agents', 'userInteraction'] }))
  115. expect(text).toContain('hi there')
  116. await fiber.dispose()
  117. }
  118. })
  119. it('renders text-delta chunks verbatim', async () => {
  120. const { ctx, out } = await setup()
  121. ctx.emit('session/event', makeSession('main'), chunkEvent({ type: 'text-delta', index: 0, text: 'hello' }))
  122. expect(out.text()).toContain('hello')
  123. })
  124. it('wraps reasoning-delta in the dim SGR and resets on the following text-delta', async () => {
  125. const { ctx, out } = await setup()
  126. const session = makeSession('main')
  127. ctx.emit('session/event', session, chunkEvent({ type: 'reasoning-delta', index: 0, text: 'think' }))
  128. ctx.emit('session/event', session, chunkEvent({ type: 'reasoning-delta', index: 0, text: 'more' }))
  129. ctx.emit('session/event', session, chunkEvent({ type: 'text-delta', index: 0, text: 'answer' }))
  130. expect(out.text()).toContain('\x1B[2mthinkmore\x1B[0m\nanswer')
  131. })
  132. it('ignores stream-chunk types it does not render', async () => {
  133. const { ctx, out } = await setup()
  134. const before = out.text()
  135. ctx.emit('session/event', makeSession('main'), chunkEvent({ type: 'block-start', index: 0, blockType: 'text' }))
  136. expect(out.text()).toBe(before)
  137. })
  138. it('renders turn/start and turn/end markers from the session feed', async () => {
  139. const { ctx, out } = await setup()
  140. const agent = makeAgent('main')
  141. // agent/created populates the session-id → agent-id label map.
  142. ctx.emit('agent/created', agent)
  143. const session = makeSession('main')
  144. ctx.emit('session/event', session, {
  145. type: 'turn/start', seq: 1, time: 0, data: { turn: 3, trigger: { kind: 'message' } },
  146. } as SessionEvent)
  147. expect(out.text()).toContain('[main turn 3] ')
  148. ctx.emit('session/event', session, {
  149. type: 'turn/end', seq: 2, time: 0, data: { turn: 3, reason: { kind: 'completed' } },
  150. } as SessionEvent)
  151. expect(out.text()).toContain('\n> ')
  152. })
  153. it('falls back to the session id as the label when no agent is mapped', async () => {
  154. const { ctx, out } = await setup()
  155. // No agent/created emitted, so the label map is empty — the header id shows.
  156. ctx.emit('session/event', makeSession('orphan'), {
  157. type: 'turn/start', seq: 1, time: 0, data: { turn: 1, trigger: { kind: 'message' } },
  158. } as SessionEvent)
  159. expect(out.text()).toContain('[orphan-session turn 1] ')
  160. })
  161. it('seeds labels for agents already registered before the UI installs', async () => {
  162. // The pre-created `main` agent (and any agent surviving an HMR reload of just this fiber)
  163. // fired its `agent/created` before the UI's listener existed, so the live listener alone
  164. // would miss it. Seeding from `ctx.agents.list()` preserves the `[main turn N]` label instead
  165. // of falling back to the raw session id.
  166. const ctx = new Context()
  167. await ctx.plugin(AgentRegistry)
  168. await ctx.plugin(UserInteractionService)
  169. const agent = makeAgent('main')
  170. ctx.agents.register(agent) // registered BEFORE the UI plugin below
  171. const { runtime, out } = makeRuntime()
  172. await ctx.plugin(Object.assign((inner: Context) => {
  173. createStdioChat(inner, CONFIG, runtime)
  174. }, { inject: ['agents', 'userInteraction'] }))
  175. ctx.emit('session/event', makeSession('main'), {
  176. type: 'turn/start', seq: 1, time: 0, data: { turn: 5, trigger: { kind: 'message' } },
  177. } as SessionEvent)
  178. expect(out.text()).toContain('[main turn 5] ')
  179. })
  180. it('resets dim styling at turn/end if a turn ends mid-reasoning', async () => {
  181. const { ctx, out } = await setup()
  182. const session = makeSession('main')
  183. ctx.emit('session/event', session, chunkEvent({ type: 'reasoning-delta', index: 0, text: 'mid' }))
  184. ctx.emit('session/event', session, {
  185. type: 'turn/end', seq: 1, time: 0, data: { turn: 1, reason: { kind: 'completed' } },
  186. } as SessionEvent)
  187. expect(out.text()).toContain('\x1B[2mmid\x1B[0m')
  188. })
  189. it('drops the label mapping on agent/disposed', async () => {
  190. const { ctx, out } = await setup()
  191. const agent = makeAgent('main')
  192. ctx.emit('agent/created', agent)
  193. ctx.emit('agent/disposed', agent)
  194. // After disposal the map no longer resolves the agent id — fall back to the
  195. // session header id.
  196. ctx.emit('session/event', makeSession('main'), {
  197. type: 'turn/start', seq: 1, time: 0, data: { turn: 1, trigger: { kind: 'message' } },
  198. } as SessionEvent)
  199. expect(out.text()).toContain('[main-session turn 1] ')
  200. })
  201. it('renders tool/call and tool/result session events', async () => {
  202. const { ctx, out } = await setup()
  203. const session = {} as Session
  204. const callEvent = {
  205. type: 'tool/call', seq: 1, time: 0,
  206. data: { turn: 1, step: 0, callId: 'c1', name: 'bash', arguments: '{"command":"ls"}' },
  207. } as SessionEvent
  208. ctx.emit('session/event', session, callEvent)
  209. expect(out.text()).toContain('[tool call] bash({"command":"ls"})')
  210. const resultEvent = {
  211. type: 'tool/result', seq: 2, time: 0,
  212. data: { turn: 1, step: 0, callId: 'c1', content: [{ type: 'text', text: 'file.txt' }], isError: false },
  213. } as SessionEvent
  214. ctx.emit('session/event', session, resultEvent)
  215. expect(out.text()).toContain('[tool result] file.txt')
  216. })
  217. it('renders a todo/write session event as a glyphed checklist', async () => {
  218. const { ctx, out } = await setup()
  219. const session = {} as Session
  220. ctx.emit('session/event', session, {
  221. type: 'todo/write', seq: 1, time: 0,
  222. data: { todos: [
  223. { content: 'read the code', status: 'completed' },
  224. { content: 'write the fix', status: 'in_progress' },
  225. { content: 'run the tests', status: 'pending' },
  226. ] },
  227. } as SessionEvent)
  228. const text = out.text()
  229. expect(text).toContain('[todos]')
  230. expect(text).toContain('[x] read the code')
  231. expect(text).toContain('[~] write the fix')
  232. expect(text).toContain('[ ] run the tests')
  233. })
  234. it('resets dim styling when a todo/write interrupts reasoning', async () => {
  235. const { ctx, out } = await setup()
  236. ctx.emit('session/event', {} as Session, chunkEvent({ type: 'reasoning-delta', index: 0, text: 'r' }))
  237. ctx.emit('session/event', {} as Session, {
  238. type: 'todo/write', seq: 1, time: 0,
  239. data: { todos: [{ content: 'a task', status: 'pending' }] },
  240. } as SessionEvent)
  241. expect(out.text()).toContain('\x1B[2mr\x1B[0m')
  242. })
  243. it('resets dim styling when a tool/call interrupts reasoning', async () => {
  244. const { ctx, out } = await setup()
  245. const session = {} as Session
  246. ctx.emit('session/event', session, chunkEvent({ type: 'reasoning-delta', index: 0, text: 'r' }))
  247. ctx.emit('session/event', session, {
  248. type: 'tool/call', seq: 1, time: 0,
  249. data: { turn: 1, step: 0, callId: 'c1', name: 'bash', arguments: '{}' },
  250. } as SessionEvent)
  251. expect(out.text()).toContain('\x1B[2mr\x1B[0m')
  252. })
  253. it('ignores session events it does not render', async () => {
  254. const { ctx, out } = await setup()
  255. const before = out.text()
  256. ctx.emit('session/event', {} as Session, {
  257. type: 'user/message', seq: 1, time: 0,
  258. data: { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } },
  259. } as SessionEvent)
  260. expect(out.text()).toBe(before)
  261. })
  262. })
  263. describe('createStdioChat input', () => {
  264. it('answers a pending user question instead of sending the line to the agent', async () => {
  265. const { ctx, input, out } = await setup()
  266. const agent = makeAgent('main', 'idle')
  267. ctx.agents.register(agent)
  268. const answer = ctx.userInteraction.ask({
  269. questions: [{
  270. id: 'confirm',
  271. header: 'Confirm',
  272. question: 'Proceed with the edit?',
  273. options: [{ label: 'Yes', description: 'Apply the edit now.' }],
  274. }],
  275. })
  276. await new Promise(r => setImmediate(r))
  277. input.feed('Use a smaller change')
  278. await expect(answer).resolves.toEqual({ answers: [{ id: 'confirm', selected: [], custom: 'Use a smaller change' }] })
  279. expect(agent.sent).toEqual([])
  280. expect(out.text()).toContain('[Confirm] Proceed with the edit?')
  281. expect(out.text()).toContain('1. Yes')
  282. expect(out.text()).toContain('Apply the edit now.')
  283. })
  284. it('answers a pending user question by numeric option selection', async () => {
  285. const { ctx, input } = await setup()
  286. const answer = ctx.userInteraction.ask({
  287. questions: [{
  288. id: 'mode',
  289. question: 'Which mode?',
  290. options: [
  291. { label: 'Safe' },
  292. { label: 'Fast' },
  293. ],
  294. }],
  295. })
  296. await new Promise(r => setImmediate(r))
  297. input.feed('2')
  298. await expect(answer).resolves.toEqual({
  299. answers: [{ id: 'mode', selected: ['Fast'] }],
  300. })
  301. })
  302. it('renders options in input order and selects by displayed number', async () => {
  303. const { ctx, input, out } = await setup()
  304. const answer = ctx.userInteraction.ask({
  305. questions: [{
  306. id: 'topic',
  307. question: 'Which topic?',
  308. options: [
  309. { label: 'Hobbies' },
  310. { label: 'Work', description: 'Questions about current projects.' },
  311. { label: 'Casual', description: 'Easy conversation.' },
  312. ],
  313. }],
  314. })
  315. await new Promise(r => setImmediate(r))
  316. expect(out.text()).toContain([
  317. 'Which topic?',
  318. ' 1. Hobbies',
  319. ' 2. Work',
  320. ' Questions about current projects.',
  321. ' 3. Casual',
  322. ' Easy conversation.',
  323. ].join('\n'))
  324. input.feed('3')
  325. await expect(answer).resolves.toEqual({
  326. answers: [{ id: 'topic', selected: ['Casual'] }],
  327. })
  328. })
  329. it('answers a multi-select question with multiple numeric selections', async () => {
  330. const { ctx, input } = await setup()
  331. const answer = ctx.userInteraction.ask({
  332. questions: [{
  333. id: 'targets',
  334. question: 'What should I update?',
  335. options: [{ label: 'Tests' }, { label: 'Docs' }, { label: 'Code' }],
  336. multiSelect: true,
  337. }],
  338. })
  339. await new Promise(r => setImmediate(r))
  340. input.feed('1 1, 3')
  341. await expect(answer).resolves.toEqual({
  342. answers: [{ id: 'targets', selected: ['Tests', 'Code'] }],
  343. })
  344. })
  345. it('accepts non-numeric multi-select input as a custom answer', async () => {
  346. const { ctx, input } = await setup()
  347. const answer = ctx.userInteraction.ask({
  348. questions: [{
  349. id: 'targets',
  350. question: 'What should I update?',
  351. options: [{ label: 'Tests' }, { label: 'Docs' }],
  352. multiSelect: true,
  353. }],
  354. })
  355. await new Promise(r => setImmediate(r))
  356. input.feed('the release notes')
  357. await expect(answer).resolves.toEqual({
  358. answers: [{ id: 'targets', selected: [], custom: 'the release notes' }],
  359. })
  360. })
  361. it('asks every question in a batch and returns answers by id', async () => {
  362. const { ctx, input, out } = await setup()
  363. const answer = ctx.userInteraction.ask({
  364. questions: [
  365. { id: 'language', question: 'Which language?', options: [{ label: 'Python' }, { label: 'TypeScript' }] },
  366. { id: 'note', question: 'Any note?' },
  367. ],
  368. })
  369. await new Promise(r => setImmediate(r))
  370. input.feed('2')
  371. await new Promise(r => setImmediate(r))
  372. expect(out.text()).toContain('\nAny note?\n')
  373. input.feed('ship today')
  374. await expect(answer).resolves.toEqual({
  375. answers: [
  376. { id: 'language', selected: ['TypeScript'] },
  377. { id: 'note', selected: [], custom: 'ship today' },
  378. ],
  379. })
  380. })
  381. it('re-prompts when option input is invalid', async () => {
  382. const { ctx, input, out } = await setup()
  383. const answer = ctx.userInteraction.ask({
  384. questions: [{
  385. id: 'mode',
  386. question: 'Which mode?',
  387. options: [{ label: 'Safe' }],
  388. multiSelect: true,
  389. }],
  390. })
  391. await new Promise(r => setImmediate(r))
  392. input.feed('2')
  393. await new Promise(r => setImmediate(r))
  394. expect(out.text()).toContain('Please enter one of the option numbers (comma or space separated) or a custom answer.')
  395. input.feed('1')
  396. await expect(answer).resolves.toEqual({
  397. answers: [{ id: 'mode', selected: ['Safe'] }],
  398. })
  399. })
  400. it('re-prompts when single-select option input is out of range', async () => {
  401. const { ctx, input, out } = await setup()
  402. const answer = ctx.userInteraction.ask({
  403. questions: [{
  404. id: 'mode',
  405. question: 'Which mode?',
  406. options: [{ label: 'Safe' }],
  407. }],
  408. })
  409. await new Promise(r => setImmediate(r))
  410. input.feed('2')
  411. await new Promise(r => setImmediate(r))
  412. expect(out.text()).toContain('Please enter one of the option numbers or a custom answer.')
  413. input.feed('1')
  414. await expect(answer).resolves.toEqual({
  415. answers: [{ id: 'mode', selected: ['Safe'] }],
  416. })
  417. })
  418. it('re-prompts when multi-select input contains no option numbers', async () => {
  419. const { ctx, input, out } = await setup()
  420. const answer = ctx.userInteraction.ask({
  421. questions: [{
  422. id: 'mode',
  423. question: 'Which mode?',
  424. options: [{ label: 'Safe' }],
  425. multiSelect: true,
  426. }],
  427. })
  428. await new Promise(r => setImmediate(r))
  429. input.feed(',')
  430. await new Promise(r => setImmediate(r))
  431. expect(out.text()).toContain('Please enter one of the option numbers (comma or space separated) or a custom answer.')
  432. input.feed('1')
  433. await expect(answer).resolves.toEqual({
  434. answers: [{ id: 'mode', selected: ['Safe'] }],
  435. })
  436. })
  437. it('re-prompts when an option question receives an empty answer', async () => {
  438. const { ctx, input, out } = await setup()
  439. const answer = ctx.userInteraction.ask({
  440. questions: [{
  441. id: 'mode',
  442. question: 'Which mode?',
  443. options: [{ label: 'Safe' }],
  444. }],
  445. })
  446. await new Promise(r => setImmediate(r))
  447. input.feed('')
  448. await new Promise(r => setImmediate(r))
  449. expect(out.text()).toContain('Please enter one of the option numbers or a custom answer.')
  450. input.feed('1')
  451. await expect(answer).resolves.toEqual({
  452. answers: [{ id: 'mode', selected: ['Safe'] }],
  453. })
  454. })
  455. it('re-prompts when a question receives an empty answer', async () => {
  456. const { ctx, input, out } = await setup()
  457. const answer = ctx.userInteraction.ask({ questions: [{ id: 'path', question: 'What should I use?' }] })
  458. await new Promise(r => setImmediate(r))
  459. input.feed('')
  460. await new Promise(r => setImmediate(r))
  461. expect(out.text()).toContain('Please enter an answer.')
  462. input.feed('Use defaults')
  463. await expect(answer).resolves.toEqual({ answers: [{ id: 'path', selected: [], custom: 'Use defaults' }] })
  464. })
  465. it('rejects an active question when its signal aborts', async () => {
  466. const { ctx } = await setup()
  467. const controller = new AbortController()
  468. const answer = ctx.userInteraction.ask({ questions: [{ id: 'continue', question: 'Continue?' }], signal: controller.signal })
  469. const rejected = expect(answer).rejects.toMatchObject({ code: 'ASK_ABORTED' })
  470. await new Promise(r => setImmediate(r))
  471. controller.abort()
  472. await rejected
  473. })
  474. it('continues to the next queued question when the active question aborts', async () => {
  475. const { ctx, input, out } = await setup()
  476. const controller = new AbortController()
  477. const first = ctx.userInteraction.ask({ questions: [{ id: 'first', question: 'First?' }], signal: controller.signal })
  478. const firstRejected = expect(first).rejects.toMatchObject({ code: 'ASK_ABORTED' })
  479. const second = ctx.userInteraction.ask({ questions: [{ id: 'second', question: 'Second?' }] })
  480. await new Promise(r => setImmediate(r))
  481. controller.abort()
  482. await firstRejected
  483. await new Promise(r => setImmediate(r))
  484. expect(out.text()).toContain('\nSecond?\n')
  485. input.feed('second answer')
  486. await expect(second).resolves.toEqual({ answers: [{ id: 'second', selected: [], custom: 'second answer' }] })
  487. })
  488. it('skips a queued question whose signal aborted before it became active', async () => {
  489. const { ctx, input, out } = await setup()
  490. const controller = new AbortController()
  491. const first = ctx.userInteraction.ask({ questions: [{ id: 'first', question: 'First?' }] })
  492. const second = ctx.userInteraction.ask({ questions: [{ id: 'second', question: 'Second?' }], signal: controller.signal })
  493. await new Promise(r => setImmediate(r))
  494. controller.abort()
  495. await expect(Promise.race([
  496. second.then(
  497. () => 'resolved',
  498. (error: unknown) => (error as { code?: string }).code,
  499. ),
  500. new Promise<string>((resolve) => { setImmediate(() => { resolve('pending') }) }),
  501. ])).resolves.toBe('ASK_ABORTED')
  502. expect(out.text()).not.toContain('\nSecond?\n')
  503. input.feed('first answer')
  504. await expect(first).resolves.toEqual({ answers: [{ id: 'first', selected: [], custom: 'first answer' }] })
  505. })
  506. it('removes an aborted queued question without promoting later queued work early', async () => {
  507. const { ctx, input, out } = await setup()
  508. const controller = new AbortController()
  509. const first = ctx.userInteraction.ask({ questions: [{ id: 'first', question: 'First?' }] })
  510. const second = ctx.userInteraction.ask({ questions: [{ id: 'second', question: 'Second?' }], signal: controller.signal })
  511. const third = ctx.userInteraction.ask({ questions: [{ id: 'third', question: 'Third?' }] })
  512. await new Promise(r => setImmediate(r))
  513. controller.abort()
  514. await expect(second).rejects.toMatchObject({ code: 'ASK_ABORTED' })
  515. expect(out.text()).toContain('\nFirst?\n')
  516. expect(out.text()).not.toContain('\nSecond?\n')
  517. expect(out.text()).not.toContain('\nThird?\n')
  518. input.feed('first answer')
  519. await new Promise(r => setImmediate(r))
  520. expect(out.text()).toContain('\nThird?\n')
  521. input.feed('third answer')
  522. await expect(first).resolves.toEqual({ answers: [{ id: 'first', selected: [], custom: 'first answer' }] })
  523. await expect(third).resolves.toEqual({ answers: [{ id: 'third', selected: [], custom: 'third answer' }] })
  524. })
  525. it('rejects active and queued questions when the UI is disposed', async () => {
  526. const { ctx, fiber } = await setup()
  527. const active = ctx.userInteraction.ask({ questions: [{ id: 'active', question: 'Active?' }] })
  528. const queued = ctx.userInteraction.ask({ questions: [{ id: 'queued', question: 'Queued?' }] })
  529. const activeRejected = expect(active).rejects.toMatchObject({ code: 'ASK_ABORTED' })
  530. const queuedRejected = expect(queued).rejects.toMatchObject({ code: 'ASK_ABORTED' })
  531. await new Promise(r => setImmediate(r))
  532. await fiber.dispose()
  533. await activeRejected
  534. await queuedRejected
  535. })
  536. it('rejects active and queued questions when stdin closes before the user answers', async () => {
  537. const { ctx, input, exit } = await setup()
  538. const active = ctx.userInteraction.ask({ questions: [{ id: 'active', question: 'Active?' }] })
  539. const queued = ctx.userInteraction.ask({ questions: [{ id: 'queued', question: 'Queued?' }] })
  540. const activeRejected = expect(active).rejects.toMatchObject({ code: 'ASK_ABORTED' })
  541. const queuedRejected = expect(queued).rejects.toMatchObject({ code: 'ASK_ABORTED' })
  542. await new Promise(r => setImmediate(r))
  543. input.finish()
  544. await new Promise(r => setImmediate(r))
  545. await activeRejected
  546. await queuedRejected
  547. expect(exit).not.toHaveBeenCalled()
  548. })
  549. it('rejects new questions immediately after stdin has closed', async () => {
  550. const { ctx, input, out } = await setup()
  551. input.finish()
  552. await new Promise(r => setImmediate(r))
  553. const before = out.text()
  554. const answer = ctx.userInteraction.ask({ questions: [{ id: 'late', question: 'Too late?' }] })
  555. await expect(answer).rejects.toMatchObject({ code: 'ASK_ABORTED' })
  556. expect(out.text()).toBe(before)
  557. })
  558. it('sends a typed line to an idle agent', async () => {
  559. const { ctx, input } = await setup()
  560. const agent = makeAgent('main', 'idle')
  561. ctx.agents.register(agent)
  562. input.feed('do a thing')
  563. await new Promise(r => setImmediate(r))
  564. expect(agent.sent).toEqual([[{ type: 'text', text: 'do a thing' }]])
  565. expect(agent.steered).toEqual([])
  566. })
  567. it('steers a typed line into a running agent', async () => {
  568. const { ctx, input } = await setup()
  569. const agent = makeAgent('main', 'running')
  570. ctx.agents.register(agent)
  571. input.feed('steer me')
  572. await new Promise(r => setImmediate(r))
  573. expect(agent.steered).toEqual([[{ type: 'text', text: 'steer me' }]])
  574. expect(agent.sent).toEqual([])
  575. })
  576. it('ignores blank lines', async () => {
  577. const { ctx, input } = await setup()
  578. const agent = makeAgent('main')
  579. ctx.agents.register(agent)
  580. input.feed(' ')
  581. await new Promise(r => setImmediate(r))
  582. expect(agent.sent).toEqual([])
  583. })
  584. it('logs and drops a line when the target agent is not running', async () => {
  585. const { ctx, input } = await setup()
  586. const spy = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {})
  587. input.feed('nobody home')
  588. await new Promise(r => setImmediate(r))
  589. expect(spy).toHaveBeenCalledWith('ui-stdio: agent "%s" is not running', 'main')
  590. })
  591. it('drives the agent named in config, not a hardcoded id', async () => {
  592. const { ctx, input } = await setup({ welcome: 'w', agent: 'worker' })
  593. const agent = makeAgent('worker')
  594. ctx.agents.register(agent)
  595. input.feed('hi')
  596. await new Promise(r => setImmediate(r))
  597. expect(agent.sent).toHaveLength(1)
  598. })
  599. })
  600. describe('createStdioChat EOF exit', () => {
  601. it('exits immediately on EOF when no work was submitted', async () => {
  602. const { input, exit } = await setup()
  603. input.finish()
  604. await flushExit()
  605. expect(exit).toHaveBeenCalledWith(0)
  606. })
  607. it('waits for the agent to settle idle after running before exiting', async () => {
  608. const { ctx, input, exit } = await setup()
  609. const agent = makeAgent('main', 'idle')
  610. ctx.agents.register(agent)
  611. input.feed('work')
  612. await new Promise(r => setImmediate(r))
  613. input.finish()
  614. await new Promise(r => setImmediate(r))
  615. // Work submitted but no 'running' observed yet — must NOT exit.
  616. expect(exit).not.toHaveBeenCalled()
  617. // The turn starts, then settles.
  618. ctx.emit('agent/status', agent, 'running')
  619. ;(agent as { status: AgentStatus }).status = 'idle'
  620. ctx.emit('agent/status', agent, 'idle')
  621. await flushExit()
  622. expect(exit).toHaveBeenCalledWith(0)
  623. })
  624. it('schedules the exit only once when idle fires repeatedly', async () => {
  625. const { ctx, input, exit } = await setup()
  626. const agent = makeAgent('main', 'running')
  627. ctx.agents.register(agent)
  628. input.feed('work')
  629. await new Promise(r => setImmediate(r))
  630. ctx.emit('agent/status', agent, 'running') // sawRunning = true
  631. input.finish()
  632. await new Promise(r => setImmediate(r)) // let readline 'close' set stdinClosed
  633. ;(agent as { status: AgentStatus }).status = 'idle'
  634. // Two idle signals while stdin is already closed: the first arms the timer,
  635. // the second must hit the already-scheduled guard, not arm a second.
  636. ctx.emit('agent/status', agent, 'idle')
  637. ctx.emit('agent/status', agent, 'idle')
  638. await flushExit()
  639. expect(exit).toHaveBeenCalledTimes(1)
  640. })
  641. it('does not exit on an idle transition for a different agent', async () => {
  642. const { ctx, input, exit } = await setup()
  643. const agent = makeAgent('main', 'idle')
  644. ctx.agents.register(agent)
  645. input.feed('work')
  646. await new Promise(r => setImmediate(r))
  647. input.finish()
  648. const other = makeAgent('other')
  649. ctx.emit('agent/status', other, 'running')
  650. ctx.emit('agent/status', other, 'idle')
  651. await flushExit()
  652. expect(exit).not.toHaveBeenCalled()
  653. })
  654. it('does not exit while a turn is still running at EOF', async () => {
  655. const { ctx, input, exit } = await setup()
  656. const agent = makeAgent('main', 'idle')
  657. ctx.agents.register(agent)
  658. input.feed('work')
  659. await new Promise(r => setImmediate(r))
  660. ctx.emit('agent/status', agent, 'running')
  661. ;(agent as { status: AgentStatus }).status = 'running'
  662. input.finish()
  663. // sawRunning is true, but the agent is still running — the idle gate holds.
  664. ctx.emit('agent/status', agent, 'idle') // a stale/duplicate signal while status stays 'running'
  665. await flushExit()
  666. expect(exit).not.toHaveBeenCalled()
  667. })
  668. })
  669. describe('createStdioChat disposal (HMR safety)', () => {
  670. it('never exits the process when EOF arrives after fiber dispose', async () => {
  671. const { fiber, input, exit } = await setup()
  672. await fiber.dispose()
  673. // A late EOF after disposal (reader.close() also fires 'close') must not exit.
  674. input.finish()
  675. await flushExit()
  676. expect(exit).not.toHaveBeenCalled()
  677. })
  678. it('cancels a scheduled exit if disposed within the flush window', async () => {
  679. const { fiber, input, exit } = await setup()
  680. // EOF with no work submitted schedules the 200ms flush-then-exit timer.
  681. input.finish()
  682. await new Promise(r => setImmediate(r))
  683. expect(exit).not.toHaveBeenCalled() // not yet — still inside the window
  684. // Dispose BEFORE the timer fires: the tracked handle must be cleared.
  685. await fiber.dispose()
  686. await flushExit()
  687. expect(exit).not.toHaveBeenCalled()
  688. })
  689. it('stops handling input after dispose', async () => {
  690. const { ctx, fiber, input } = await setup()
  691. const agent = makeAgent('main')
  692. ctx.agents.register(agent)
  693. await fiber.dispose()
  694. // The readline interface is closed on dispose; a late line reaches no handler.
  695. input.feed('too late')
  696. await new Promise(r => setImmediate(r))
  697. expect(agent.sent).toEqual([])
  698. })
  699. it('removes the agent/status listener on dispose', async () => {
  700. const { ctx, fiber, input, exit } = await setup()
  701. const agent = makeAgent('main', 'idle')
  702. ctx.agents.register(agent)
  703. input.feed('work')
  704. await new Promise(r => setImmediate(r))
  705. await fiber.dispose()
  706. // After dispose, status transitions must neither throw nor schedule an exit
  707. // (the listener and the EOF-exit path are both torn down).
  708. expect(() => {
  709. ctx.emit('agent/status', agent, 'running')
  710. ctx.emit('agent/status', agent, 'idle')
  711. }).not.toThrow()
  712. await flushExit()
  713. expect(exit).not.toHaveBeenCalled()
  714. })
  715. })