stdio-chat.spec.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  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
  163. // this fiber) fired its `agent/created` before the UI's listener existed, so
  164. // the live listener alone would miss it. Seeding from `ctx.agents.list()` at
  165. // install time is what keeps its turn header showing `[main turn N]` instead
  166. // of the raw session id.
  167. const ctx = new Context()
  168. await ctx.plugin(AgentRegistry)
  169. await ctx.plugin(UserInteractionService)
  170. const agent = makeAgent('main')
  171. ctx.agents.register(agent) // registered BEFORE the UI plugin below
  172. const { runtime, out } = makeRuntime()
  173. await ctx.plugin(Object.assign((inner: Context) => {
  174. createStdioChat(inner, CONFIG, runtime)
  175. }, { inject: ['agents', 'userInteraction'] }))
  176. ctx.emit('session/event', makeSession('main'), {
  177. type: 'turn/start', seq: 1, time: 0, data: { turn: 5, trigger: { kind: 'message' } },
  178. } as SessionEvent)
  179. expect(out.text()).toContain('[main turn 5] ')
  180. })
  181. it('resets dim styling at turn/end if a turn ends mid-reasoning', async () => {
  182. const { ctx, out } = await setup()
  183. const session = makeSession('main')
  184. ctx.emit('session/event', session, chunkEvent({ type: 'reasoning-delta', index: 0, text: 'mid' }))
  185. ctx.emit('session/event', session, {
  186. type: 'turn/end', seq: 1, time: 0, data: { turn: 1, reason: { kind: 'completed' } },
  187. } as SessionEvent)
  188. expect(out.text()).toContain('\x1B[2mmid\x1B[0m')
  189. })
  190. it('drops the label mapping on agent/disposed', async () => {
  191. const { ctx, out } = await setup()
  192. const agent = makeAgent('main')
  193. ctx.emit('agent/created', agent)
  194. ctx.emit('agent/disposed', agent)
  195. // After disposal the map no longer resolves the agent id — fall back to the
  196. // session header id.
  197. ctx.emit('session/event', makeSession('main'), {
  198. type: 'turn/start', seq: 1, time: 0, data: { turn: 1, trigger: { kind: 'message' } },
  199. } as SessionEvent)
  200. expect(out.text()).toContain('[main-session turn 1] ')
  201. })
  202. it('renders tool/call and tool/result session events', async () => {
  203. const { ctx, out } = await setup()
  204. const session = {} as Session
  205. const callEvent = {
  206. type: 'tool/call', seq: 1, time: 0,
  207. data: { turn: 1, step: 0, callId: 'c1', name: 'bash', arguments: '{"command":"ls"}' },
  208. } as SessionEvent
  209. ctx.emit('session/event', session, callEvent)
  210. expect(out.text()).toContain('[tool call] bash({"command":"ls"})')
  211. const resultEvent = {
  212. type: 'tool/result', seq: 2, time: 0,
  213. data: { turn: 1, step: 0, callId: 'c1', content: [{ type: 'text', text: 'file.txt' }], isError: false },
  214. } as SessionEvent
  215. ctx.emit('session/event', session, resultEvent)
  216. expect(out.text()).toContain('[tool result] file.txt')
  217. })
  218. it('renders a todo/write session event as a glyphed checklist', async () => {
  219. const { ctx, out } = await setup()
  220. const session = {} as Session
  221. ctx.emit('session/event', session, {
  222. type: 'todo/write', seq: 1, time: 0,
  223. data: { todos: [
  224. { content: 'read the code', status: 'completed' },
  225. { content: 'write the fix', status: 'in_progress' },
  226. { content: 'run the tests', status: 'pending' },
  227. ] },
  228. } as SessionEvent)
  229. const text = out.text()
  230. expect(text).toContain('[todos]')
  231. expect(text).toContain('[x] read the code')
  232. expect(text).toContain('[~] write the fix')
  233. expect(text).toContain('[ ] run the tests')
  234. })
  235. it('resets dim styling when a todo/write interrupts reasoning', async () => {
  236. const { ctx, out } = await setup()
  237. ctx.emit('session/event', {} as Session, chunkEvent({ type: 'reasoning-delta', index: 0, text: 'r' }))
  238. ctx.emit('session/event', {} as Session, {
  239. type: 'todo/write', seq: 1, time: 0,
  240. data: { todos: [{ content: 'a task', status: 'pending' }] },
  241. } as SessionEvent)
  242. expect(out.text()).toContain('\x1B[2mr\x1B[0m')
  243. })
  244. it('resets dim styling when a tool/call interrupts reasoning', async () => {
  245. const { ctx, out } = await setup()
  246. const session = {} as Session
  247. ctx.emit('session/event', session, chunkEvent({ type: 'reasoning-delta', index: 0, text: 'r' }))
  248. ctx.emit('session/event', session, {
  249. type: 'tool/call', seq: 1, time: 0,
  250. data: { turn: 1, step: 0, callId: 'c1', name: 'bash', arguments: '{}' },
  251. } as SessionEvent)
  252. expect(out.text()).toContain('\x1B[2mr\x1B[0m')
  253. })
  254. it('ignores session events it does not render', async () => {
  255. const { ctx, out } = await setup()
  256. const before = out.text()
  257. ctx.emit('session/event', {} as Session, {
  258. type: 'user/message', seq: 1, time: 0,
  259. data: { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } },
  260. } as SessionEvent)
  261. expect(out.text()).toBe(before)
  262. })
  263. })
  264. describe('createStdioChat input', () => {
  265. it('answers a pending user question instead of sending the line to the agent', async () => {
  266. const { ctx, input, out } = await setup()
  267. const agent = makeAgent('main', 'idle')
  268. ctx.agents.register(agent)
  269. const answer = ctx.userInteraction.ask({
  270. questions: [{
  271. id: 'confirm',
  272. header: 'Confirm',
  273. question: 'Proceed with the edit?',
  274. options: [{ label: 'Yes', description: 'Apply the edit now.' }],
  275. }],
  276. })
  277. await new Promise(r => setImmediate(r))
  278. input.feed('Use a smaller change')
  279. await expect(answer).resolves.toEqual({ answers: [{ id: 'confirm', selected: [], custom: 'Use a smaller change' }] })
  280. expect(agent.sent).toEqual([])
  281. expect(out.text()).toContain('[Confirm] Proceed with the edit?')
  282. expect(out.text()).toContain('1. Yes')
  283. expect(out.text()).toContain('Apply the edit now.')
  284. })
  285. it('answers a pending user question by numeric option selection', async () => {
  286. const { ctx, input } = await setup()
  287. const answer = ctx.userInteraction.ask({
  288. questions: [{
  289. id: 'mode',
  290. question: 'Which mode?',
  291. options: [
  292. { label: 'Safe' },
  293. { label: 'Fast' },
  294. ],
  295. }],
  296. })
  297. await new Promise(r => setImmediate(r))
  298. input.feed('2')
  299. await expect(answer).resolves.toEqual({
  300. answers: [{ id: 'mode', selected: ['Fast'] }],
  301. })
  302. })
  303. it('renders options in input order and selects by displayed number', async () => {
  304. const { ctx, input, out } = await setup()
  305. const answer = ctx.userInteraction.ask({
  306. questions: [{
  307. id: 'topic',
  308. question: 'Which topic?',
  309. options: [
  310. { label: 'Hobbies' },
  311. { label: 'Work', description: 'Questions about current projects.' },
  312. { label: 'Casual', description: 'Easy conversation.' },
  313. ],
  314. }],
  315. })
  316. await new Promise(r => setImmediate(r))
  317. expect(out.text()).toContain([
  318. 'Which topic?',
  319. ' 1. Hobbies',
  320. ' 2. Work',
  321. ' Questions about current projects.',
  322. ' 3. Casual',
  323. ' Easy conversation.',
  324. ].join('\n'))
  325. input.feed('3')
  326. await expect(answer).resolves.toEqual({
  327. answers: [{ id: 'topic', selected: ['Casual'] }],
  328. })
  329. })
  330. it('answers a multi-select question with multiple numeric selections', async () => {
  331. const { ctx, input } = await setup()
  332. const answer = ctx.userInteraction.ask({
  333. questions: [{
  334. id: 'targets',
  335. question: 'What should I update?',
  336. options: [{ label: 'Tests' }, { label: 'Docs' }, { label: 'Code' }],
  337. multiSelect: true,
  338. }],
  339. })
  340. await new Promise(r => setImmediate(r))
  341. input.feed('1 1, 3')
  342. await expect(answer).resolves.toEqual({
  343. answers: [{ id: 'targets', selected: ['Tests', 'Code'] }],
  344. })
  345. })
  346. it('accepts non-numeric multi-select input as a custom answer', async () => {
  347. const { ctx, input } = await setup()
  348. const answer = ctx.userInteraction.ask({
  349. questions: [{
  350. id: 'targets',
  351. question: 'What should I update?',
  352. options: [{ label: 'Tests' }, { label: 'Docs' }],
  353. multiSelect: true,
  354. }],
  355. })
  356. await new Promise(r => setImmediate(r))
  357. input.feed('the release notes')
  358. await expect(answer).resolves.toEqual({
  359. answers: [{ id: 'targets', selected: [], custom: 'the release notes' }],
  360. })
  361. })
  362. it('asks every question in a batch and returns answers by id', async () => {
  363. const { ctx, input, out } = await setup()
  364. const answer = ctx.userInteraction.ask({
  365. questions: [
  366. { id: 'language', question: 'Which language?', options: [{ label: 'Python' }, { label: 'TypeScript' }] },
  367. { id: 'note', question: 'Any note?' },
  368. ],
  369. })
  370. await new Promise(r => setImmediate(r))
  371. input.feed('2')
  372. await new Promise(r => setImmediate(r))
  373. expect(out.text()).toContain('\nAny note?\n')
  374. input.feed('ship today')
  375. await expect(answer).resolves.toEqual({
  376. answers: [
  377. { id: 'language', selected: ['TypeScript'] },
  378. { id: 'note', selected: [], custom: 'ship today' },
  379. ],
  380. })
  381. })
  382. it('re-prompts when option input is invalid', async () => {
  383. const { ctx, input, out } = await setup()
  384. const answer = ctx.userInteraction.ask({
  385. questions: [{
  386. id: 'mode',
  387. question: 'Which mode?',
  388. options: [{ label: 'Safe' }],
  389. multiSelect: true,
  390. }],
  391. })
  392. await new Promise(r => setImmediate(r))
  393. input.feed('2')
  394. await new Promise(r => setImmediate(r))
  395. expect(out.text()).toContain('Please enter one of the option numbers (comma or space separated) or a custom answer.')
  396. input.feed('1')
  397. await expect(answer).resolves.toEqual({
  398. answers: [{ id: 'mode', selected: ['Safe'] }],
  399. })
  400. })
  401. it('re-prompts when single-select option input is out of range', async () => {
  402. const { ctx, input, out } = await setup()
  403. const answer = ctx.userInteraction.ask({
  404. questions: [{
  405. id: 'mode',
  406. question: 'Which mode?',
  407. options: [{ label: 'Safe' }],
  408. }],
  409. })
  410. await new Promise(r => setImmediate(r))
  411. input.feed('2')
  412. await new Promise(r => setImmediate(r))
  413. expect(out.text()).toContain('Please enter one of the option numbers or a custom answer.')
  414. input.feed('1')
  415. await expect(answer).resolves.toEqual({
  416. answers: [{ id: 'mode', selected: ['Safe'] }],
  417. })
  418. })
  419. it('re-prompts when multi-select input contains no option numbers', async () => {
  420. const { ctx, input, out } = await setup()
  421. const answer = ctx.userInteraction.ask({
  422. questions: [{
  423. id: 'mode',
  424. question: 'Which mode?',
  425. options: [{ label: 'Safe' }],
  426. multiSelect: true,
  427. }],
  428. })
  429. await new Promise(r => setImmediate(r))
  430. input.feed(',')
  431. await new Promise(r => setImmediate(r))
  432. expect(out.text()).toContain('Please enter one of the option numbers (comma or space separated) or a custom answer.')
  433. input.feed('1')
  434. await expect(answer).resolves.toEqual({
  435. answers: [{ id: 'mode', selected: ['Safe'] }],
  436. })
  437. })
  438. it('re-prompts when an option question receives an empty answer', async () => {
  439. const { ctx, input, out } = await setup()
  440. const answer = ctx.userInteraction.ask({
  441. questions: [{
  442. id: 'mode',
  443. question: 'Which mode?',
  444. options: [{ label: 'Safe' }],
  445. }],
  446. })
  447. await new Promise(r => setImmediate(r))
  448. input.feed('')
  449. await new Promise(r => setImmediate(r))
  450. expect(out.text()).toContain('Please enter one of the option numbers or a custom answer.')
  451. input.feed('1')
  452. await expect(answer).resolves.toEqual({
  453. answers: [{ id: 'mode', selected: ['Safe'] }],
  454. })
  455. })
  456. it('re-prompts when a question receives an empty answer', async () => {
  457. const { ctx, input, out } = await setup()
  458. const answer = ctx.userInteraction.ask({ questions: [{ id: 'path', question: 'What should I use?' }] })
  459. await new Promise(r => setImmediate(r))
  460. input.feed('')
  461. await new Promise(r => setImmediate(r))
  462. expect(out.text()).toContain('Please enter an answer.')
  463. input.feed('Use defaults')
  464. await expect(answer).resolves.toEqual({ answers: [{ id: 'path', selected: [], custom: 'Use defaults' }] })
  465. })
  466. it('rejects an active question when its signal aborts', async () => {
  467. const { ctx } = await setup()
  468. const controller = new AbortController()
  469. const answer = ctx.userInteraction.ask({ questions: [{ id: 'continue', question: 'Continue?' }], signal: controller.signal })
  470. const rejected = expect(answer).rejects.toMatchObject({ code: 'ASK_ABORTED' })
  471. await new Promise(r => setImmediate(r))
  472. controller.abort()
  473. await rejected
  474. })
  475. it('continues to the next queued question when the active question aborts', async () => {
  476. const { ctx, input, out } = await setup()
  477. const controller = new AbortController()
  478. const first = ctx.userInteraction.ask({ questions: [{ id: 'first', question: 'First?' }], signal: controller.signal })
  479. const firstRejected = expect(first).rejects.toMatchObject({ code: 'ASK_ABORTED' })
  480. const second = ctx.userInteraction.ask({ questions: [{ id: 'second', question: 'Second?' }] })
  481. await new Promise(r => setImmediate(r))
  482. controller.abort()
  483. await firstRejected
  484. await new Promise(r => setImmediate(r))
  485. expect(out.text()).toContain('\nSecond?\n')
  486. input.feed('second answer')
  487. await expect(second).resolves.toEqual({ answers: [{ id: 'second', selected: [], custom: 'second answer' }] })
  488. })
  489. it('skips a queued question whose signal aborted before it became active', async () => {
  490. const { ctx, input, out } = await setup()
  491. const controller = new AbortController()
  492. const first = ctx.userInteraction.ask({ questions: [{ id: 'first', question: 'First?' }] })
  493. const second = ctx.userInteraction.ask({ questions: [{ id: 'second', question: 'Second?' }], signal: controller.signal })
  494. await new Promise(r => setImmediate(r))
  495. controller.abort()
  496. await expect(Promise.race([
  497. second.then(
  498. () => 'resolved',
  499. (error: unknown) => (error as { code?: string }).code,
  500. ),
  501. new Promise<string>((resolve) => { setImmediate(() => { resolve('pending') }) }),
  502. ])).resolves.toBe('ASK_ABORTED')
  503. expect(out.text()).not.toContain('\nSecond?\n')
  504. input.feed('first answer')
  505. await expect(first).resolves.toEqual({ answers: [{ id: 'first', selected: [], custom: 'first answer' }] })
  506. })
  507. it('removes an aborted queued question without promoting later queued work early', async () => {
  508. const { ctx, input, out } = await setup()
  509. const controller = new AbortController()
  510. const first = ctx.userInteraction.ask({ questions: [{ id: 'first', question: 'First?' }] })
  511. const second = ctx.userInteraction.ask({ questions: [{ id: 'second', question: 'Second?' }], signal: controller.signal })
  512. const third = ctx.userInteraction.ask({ questions: [{ id: 'third', question: 'Third?' }] })
  513. await new Promise(r => setImmediate(r))
  514. controller.abort()
  515. await expect(second).rejects.toMatchObject({ code: 'ASK_ABORTED' })
  516. expect(out.text()).toContain('\nFirst?\n')
  517. expect(out.text()).not.toContain('\nSecond?\n')
  518. expect(out.text()).not.toContain('\nThird?\n')
  519. input.feed('first answer')
  520. await new Promise(r => setImmediate(r))
  521. expect(out.text()).toContain('\nThird?\n')
  522. input.feed('third answer')
  523. await expect(first).resolves.toEqual({ answers: [{ id: 'first', selected: [], custom: 'first answer' }] })
  524. await expect(third).resolves.toEqual({ answers: [{ id: 'third', selected: [], custom: 'third answer' }] })
  525. })
  526. it('rejects active and queued questions when the UI is disposed', async () => {
  527. const { ctx, fiber } = await setup()
  528. const active = ctx.userInteraction.ask({ questions: [{ id: 'active', question: 'Active?' }] })
  529. const queued = ctx.userInteraction.ask({ questions: [{ id: 'queued', question: 'Queued?' }] })
  530. const activeRejected = expect(active).rejects.toMatchObject({ code: 'ASK_ABORTED' })
  531. const queuedRejected = expect(queued).rejects.toMatchObject({ code: 'ASK_ABORTED' })
  532. await new Promise(r => setImmediate(r))
  533. await fiber.dispose()
  534. await activeRejected
  535. await queuedRejected
  536. })
  537. it('rejects active and queued questions when stdin closes before the user answers', async () => {
  538. const { ctx, input, exit } = await setup()
  539. const active = ctx.userInteraction.ask({ questions: [{ id: 'active', question: 'Active?' }] })
  540. const queued = ctx.userInteraction.ask({ questions: [{ id: 'queued', question: 'Queued?' }] })
  541. const activeRejected = expect(active).rejects.toMatchObject({ code: 'ASK_ABORTED' })
  542. const queuedRejected = expect(queued).rejects.toMatchObject({ code: 'ASK_ABORTED' })
  543. await new Promise(r => setImmediate(r))
  544. input.finish()
  545. await new Promise(r => setImmediate(r))
  546. await activeRejected
  547. await queuedRejected
  548. expect(exit).not.toHaveBeenCalled()
  549. })
  550. it('rejects new questions immediately after stdin has closed', async () => {
  551. const { ctx, input, out } = await setup()
  552. input.finish()
  553. await new Promise(r => setImmediate(r))
  554. const before = out.text()
  555. const answer = ctx.userInteraction.ask({ questions: [{ id: 'late', question: 'Too late?' }] })
  556. await expect(answer).rejects.toMatchObject({ code: 'ASK_ABORTED' })
  557. expect(out.text()).toBe(before)
  558. })
  559. it('sends a typed line to an idle agent', async () => {
  560. const { ctx, input } = await setup()
  561. const agent = makeAgent('main', 'idle')
  562. ctx.agents.register(agent)
  563. input.feed('do a thing')
  564. await new Promise(r => setImmediate(r))
  565. expect(agent.sent).toEqual([[{ type: 'text', text: 'do a thing' }]])
  566. expect(agent.steered).toEqual([])
  567. })
  568. it('steers a typed line into a running agent', async () => {
  569. const { ctx, input } = await setup()
  570. const agent = makeAgent('main', 'running')
  571. ctx.agents.register(agent)
  572. input.feed('steer me')
  573. await new Promise(r => setImmediate(r))
  574. expect(agent.steered).toEqual([[{ type: 'text', text: 'steer me' }]])
  575. expect(agent.sent).toEqual([])
  576. })
  577. it('ignores blank lines', async () => {
  578. const { ctx, input } = await setup()
  579. const agent = makeAgent('main')
  580. ctx.agents.register(agent)
  581. input.feed(' ')
  582. await new Promise(r => setImmediate(r))
  583. expect(agent.sent).toEqual([])
  584. })
  585. it('logs and drops a line when the target agent is not running', async () => {
  586. const { ctx, input } = await setup()
  587. const spy = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {})
  588. input.feed('nobody home')
  589. await new Promise(r => setImmediate(r))
  590. expect(spy).toHaveBeenCalledWith('ui-stdio: agent "%s" is not running', 'main')
  591. })
  592. it('drives the agent named in config, not a hardcoded id', async () => {
  593. const { ctx, input } = await setup({ welcome: 'w', agent: 'worker' })
  594. const agent = makeAgent('worker')
  595. ctx.agents.register(agent)
  596. input.feed('hi')
  597. await new Promise(r => setImmediate(r))
  598. expect(agent.sent).toHaveLength(1)
  599. })
  600. })
  601. describe('createStdioChat EOF exit', () => {
  602. it('exits immediately on EOF when no work was submitted', async () => {
  603. const { input, exit } = await setup()
  604. input.finish()
  605. await flushExit()
  606. expect(exit).toHaveBeenCalledWith(0)
  607. })
  608. it('waits for the agent to settle idle after running before exiting', async () => {
  609. const { ctx, input, exit } = await setup()
  610. const agent = makeAgent('main', 'idle')
  611. ctx.agents.register(agent)
  612. input.feed('work')
  613. await new Promise(r => setImmediate(r))
  614. input.finish()
  615. await new Promise(r => setImmediate(r))
  616. // Work submitted but no 'running' observed yet — must NOT exit.
  617. expect(exit).not.toHaveBeenCalled()
  618. // The turn starts, then settles.
  619. ctx.emit('agent/status', agent, 'running')
  620. ;(agent as { status: AgentStatus }).status = 'idle'
  621. ctx.emit('agent/status', agent, 'idle')
  622. await flushExit()
  623. expect(exit).toHaveBeenCalledWith(0)
  624. })
  625. it('schedules the exit only once when idle fires repeatedly', async () => {
  626. const { ctx, input, exit } = await setup()
  627. const agent = makeAgent('main', 'running')
  628. ctx.agents.register(agent)
  629. input.feed('work')
  630. await new Promise(r => setImmediate(r))
  631. ctx.emit('agent/status', agent, 'running') // sawRunning = true
  632. input.finish()
  633. await new Promise(r => setImmediate(r)) // let readline 'close' set stdinClosed
  634. ;(agent as { status: AgentStatus }).status = 'idle'
  635. // Two idle signals while stdin is already closed: the first arms the timer,
  636. // the second must hit the already-scheduled guard, not arm a second.
  637. ctx.emit('agent/status', agent, 'idle')
  638. ctx.emit('agent/status', agent, 'idle')
  639. await flushExit()
  640. expect(exit).toHaveBeenCalledTimes(1)
  641. })
  642. it('does not exit on an idle transition for a different agent', async () => {
  643. const { ctx, input, exit } = await setup()
  644. const agent = makeAgent('main', 'idle')
  645. ctx.agents.register(agent)
  646. input.feed('work')
  647. await new Promise(r => setImmediate(r))
  648. input.finish()
  649. const other = makeAgent('other')
  650. ctx.emit('agent/status', other, 'running')
  651. ctx.emit('agent/status', other, 'idle')
  652. await flushExit()
  653. expect(exit).not.toHaveBeenCalled()
  654. })
  655. it('does not exit while a turn is still running at EOF', async () => {
  656. const { ctx, input, exit } = await setup()
  657. const agent = makeAgent('main', 'idle')
  658. ctx.agents.register(agent)
  659. input.feed('work')
  660. await new Promise(r => setImmediate(r))
  661. ctx.emit('agent/status', agent, 'running')
  662. ;(agent as { status: AgentStatus }).status = 'running'
  663. input.finish()
  664. // sawRunning is true, but the agent is still running — the idle gate holds.
  665. ctx.emit('agent/status', agent, 'idle') // a stale/duplicate signal while status stays 'running'
  666. await flushExit()
  667. expect(exit).not.toHaveBeenCalled()
  668. })
  669. })
  670. describe('createStdioChat disposal (HMR safety)', () => {
  671. it('never exits the process when EOF arrives after fiber dispose', async () => {
  672. const { fiber, input, exit } = await setup()
  673. await fiber.dispose()
  674. // A late EOF after disposal (reader.close() also fires 'close') must not exit.
  675. input.finish()
  676. await flushExit()
  677. expect(exit).not.toHaveBeenCalled()
  678. })
  679. it('cancels a scheduled exit if disposed within the flush window', async () => {
  680. const { fiber, input, exit } = await setup()
  681. // EOF with no work submitted schedules the 200ms flush-then-exit timer.
  682. input.finish()
  683. await new Promise(r => setImmediate(r))
  684. expect(exit).not.toHaveBeenCalled() // not yet — still inside the window
  685. // Dispose BEFORE the timer fires: the tracked handle must be cleared.
  686. await fiber.dispose()
  687. await flushExit()
  688. expect(exit).not.toHaveBeenCalled()
  689. })
  690. it('stops handling input after dispose', async () => {
  691. const { ctx, fiber, input } = await setup()
  692. const agent = makeAgent('main')
  693. ctx.agents.register(agent)
  694. await fiber.dispose()
  695. // The readline interface is closed on dispose; a late line reaches no handler.
  696. input.feed('too late')
  697. await new Promise(r => setImmediate(r))
  698. expect(agent.sent).toEqual([])
  699. })
  700. it('removes the agent/status listener on dispose', async () => {
  701. const { ctx, fiber, input, exit } = await setup()
  702. const agent = makeAgent('main', 'idle')
  703. ctx.agents.register(agent)
  704. input.feed('work')
  705. await new Promise(r => setImmediate(r))
  706. await fiber.dispose()
  707. // After dispose, status transitions must neither throw nor schedule an exit
  708. // (the listener and the EOF-exit path are both torn down).
  709. expect(() => {
  710. ctx.emit('agent/status', agent, 'running')
  711. ctx.emit('agent/status', agent, 'idle')
  712. }).not.toThrow()
  713. await flushExit()
  714. expect(exit).not.toHaveBeenCalled()
  715. })
  716. })