controller.spec.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. /** Session identity, allocation races, confinement and real PTY behavior. */
  2. import { mkdtemp, rm } from 'node:fs/promises'
  3. import { tmpdir } from 'node:os'
  4. import { join } from 'node:path'
  5. import { PassThrough } from 'node:stream'
  6. import { Context } from '@deepseek-ai/cordis'
  7. import type { Agent } from '@deepseek-ai/dsh-agent'
  8. import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session'
  9. import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox'
  10. import { SubprocessExecutableNotFoundError, type SubprocessRuntime, type SubprocessTerminalEnvironment, type SubprocessTerminalHandle } from '@deepseek-ai/dsh-subprocess'
  11. import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
  12. import { afterEach, describe, expect, it, vi } from 'vitest'
  13. import { TerminalController, type Config } from '../src/index.ts'
  14. import { resolveShell } from '../src/shells.ts'
  15. import type { TerminalAttachmentId, WebTerminalId } from '../src/types.ts'
  16. const roots: Context[] = []
  17. afterEach(async () => { await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) })
  18. const config: Config = { shellCandidates: ['zsh', 'bash', 'sh'], shell: { path: '/bin/bash', name: 'bash', args: ['--noprofile', '--norc', '-i'] }, maxTerminals: 2, maxCols: 200, maxRows: 100, scrollback: 100, maxBufferedBytes: 100_000, maxInputBytes: 1000, disposeGraceMs: 100 }
  19. const id = 'test-terminal' as WebTerminalId
  20. const request = { id, cols: 80, rows: 24 }
  21. const signal = (): AbortSignal => new AbortController().signal
  22. function owner(ctx: Context, id = 'session'): Agent {
  23. return { id: id as SessionId, ctx, session: { id: id as SessionId } } as unknown as Agent
  24. }
  25. function fixture(overrides: Partial<Config> = {}) {
  26. const ctx = new Context()
  27. roots.push(ctx)
  28. const effects = vi.spyOn(ctx.fiber, 'effect')
  29. const sandboxPolicy = { defaultMode: 'danger-full-access', resolve: vi.fn((): SandboxExecutionPolicy => ({ mode: 'danger-full-access', workspaceRoot: '/workspace' })) }
  30. const projections = { stateOf: vi.fn((): SandboxMode | null => null) }
  31. ctx.provide('sandboxPolicy', sandboxPolicy as never)
  32. ctx.provide('sessionProjections', projections as never)
  33. const output = new PassThrough()
  34. const done = Promise.withResolvers<{ exitCode: number; signal: null }>()
  35. const handle = {
  36. pid: 123, output, done: done.promise, write: vi.fn(async () => {}), resize: vi.fn(async () => {}),
  37. inspectForeground: async () => undefined, signalForeground: async () => 123,
  38. terminate: vi.fn(async () => { output.end(); done.resolve({ exitCode: 0, signal: null }) }) }
  39. const checked: SubprocessTerminalHandle = handle
  40. const subprocess = { terminalEnvironment: vi.fn(async (): Promise<SubprocessTerminalEnvironment> => ({ platform: 'posix', defaultShell: '/bin/bash' })), resolveExecutable: vi.fn(async (path: string) => path), spawnTerminal: vi.fn(async () => checked) }
  41. ctx.provide('subprocess', subprocess as never)
  42. const controller = new TerminalController(ctx, { ...config, ...overrides })
  43. const disposeEffect = (label: string): Promise<void> => {
  44. const index = effects.mock.calls.findIndex(call => call[1] === label)
  45. const result = effects.mock.results[index]
  46. if (result?.type !== 'return' || typeof result.value !== 'function') throw new Error(`Missing effect: ${label}`)
  47. return result.value()
  48. }
  49. return { ctx, agent: owner(ctx), controller, subprocess, handle, sandboxPolicy, projections, disposeEffect }
  50. }
  51. describe('TerminalController', () => {
  52. it('resolves execution services from an Agent plugin context without consumer injections', async () => {
  53. const { ctx, controller } = fixture()
  54. let agent: Agent | undefined
  55. await ctx.plugin((child) => { agent = owner(child) })
  56. if (agent === undefined) throw new Error('Agent plugin did not load')
  57. expect(controller.environment(agent, signal())).toMatchObject({ cwd: '/workspace' })
  58. await controller.create(agent, request, signal())
  59. await controller.close(agent, id)
  60. })
  61. it('creates the environment default shell and keeps an existing identity when that default changes', async () => {
  62. const { controller, agent, subprocess } = fixture({ shell: undefined })
  63. subprocess.terminalEnvironment.mockResolvedValue({ platform: 'posix', defaultShell: '/usr/local/bin/zsh' })
  64. expect(controller.environment(agent, signal())).toEqual({ cwd: '/workspace', maxCols: 200, maxRows: 100, maxInputBytes: 1000, scrollback: 100 })
  65. expect(subprocess.terminalEnvironment).not.toHaveBeenCalled()
  66. const created = await controller.create(agent, request, signal())
  67. expect(created.shell.path).toBe('/usr/local/bin/zsh')
  68. expect(subprocess.spawnTerminal).toHaveBeenCalledWith(expect.objectContaining({ argv: ['/usr/local/bin/zsh', '-i'] }))
  69. subprocess.terminalEnvironment.mockResolvedValue({ platform: 'posix', defaultShell: '/bin/sh' })
  70. expect(await controller.create(agent, request, signal())).toBe(created)
  71. expect(subprocess.terminalEnvironment).toHaveBeenCalledOnce()
  72. expect(subprocess.spawnTerminal).toHaveBeenCalledOnce()
  73. })
  74. it('restores a running terminal after its default executable becomes unavailable', async () => {
  75. const { controller, agent, subprocess } = fixture({ shell: undefined })
  76. await controller.create(agent, request, signal())
  77. subprocess.resolveExecutable.mockRejectedValue(new SubprocessExecutableNotFoundError('default shell was removed'))
  78. expect(controller.environment(agent, signal())).toMatchObject({ cwd: '/workspace', maxInputBytes: 1000 })
  79. expect(controller.list(agent.id)).toMatchObject([{ id, state: 'running' }])
  80. const stream = controller.follow(agent, id, 'restored' as TerminalAttachmentId, signal())[Symbol.asyncIterator]()
  81. try {
  82. expect(await stream.next()).toMatchObject({ done: false, value: { type: 'snapshot', info: { id, state: 'running' } } })
  83. expect(subprocess.resolveExecutable).toHaveBeenCalledOnce()
  84. await expect(controller.create(agent, { ...request, id: 'new-terminal' as WebTerminalId }, signal())).rejects.toThrow('default shell was removed')
  85. expect(subprocess.spawnTerminal).toHaveBeenCalledOnce()
  86. } finally { await stream.return?.() }
  87. })
  88. it('honors cancellation before reading environment limits', () => {
  89. const { controller, agent, subprocess, sandboxPolicy } = fixture()
  90. const abort = new AbortController()
  91. abort.abort(new Error('request cancelled'))
  92. expect(() => controller.environment(agent, abort.signal)).toThrow('request cancelled')
  93. expect(subprocess.terminalEnvironment).not.toHaveBeenCalled()
  94. expect(sandboxPolicy.resolve).not.toHaveBeenCalled()
  95. })
  96. it('deduplicates concurrent creates, scopes access by Session, and preserves terminals when a stream aborts', async () => {
  97. const { controller, agent, ctx, subprocess, handle } = fixture()
  98. const [first, second] = await Promise.all([controller.create(agent, request, signal()), controller.create(agent, request, signal())])
  99. expect(first.id).toBe(second.id)
  100. expect(subprocess.spawnTerminal).toHaveBeenCalledOnce()
  101. expect(subprocess.spawnTerminal).toHaveBeenCalledWith(expect.objectContaining({ terminalType: 'xterm-256color', cwd: '/workspace' }))
  102. expect(controller.list('other' as SessionId)).toEqual([])
  103. expect(() => controller.follow(owner(ctx, 'other'), id, 'writer' as TerminalAttachmentId, signal())).toThrow('no longer exists')
  104. const abort = new AbortController()
  105. const stream = controller.follow(agent, id, 'writer' as TerminalAttachmentId, abort.signal)[Symbol.asyncIterator]()
  106. const firstFrame = await stream.next()
  107. if (firstFrame.done === true) throw new Error('Terminal stream ended before its snapshot')
  108. expect(firstFrame.value.type).toBe('snapshot')
  109. abort.abort()
  110. await stream.return?.()
  111. expect(handle.terminate).not.toHaveBeenCalled()
  112. await controller.close(agent, id)
  113. expect(handle.terminate).toHaveBeenCalledOnce()
  114. expect(controller.list(agent.id)).toEqual([])
  115. await controller.close(agent, id)
  116. })
  117. it('waits for pending allocation when explicitly closing and rolls back cancellation before publication', async () => {
  118. const { controller, agent, subprocess, handle } = fixture()
  119. const allocation = Promise.withResolvers<SubprocessTerminalHandle>()
  120. subprocess.spawnTerminal.mockImplementationOnce(() => allocation.promise)
  121. const creating = controller.create(agent, request, signal())
  122. const rejected = expect(creating).rejects.toThrow('closed in this Session')
  123. const closing = controller.close(agent, id)
  124. allocation.resolve(handle)
  125. await rejected
  126. await closing
  127. expect(controller.list(agent.id)).toEqual([])
  128. expect(handle.terminate).toHaveBeenCalledOnce()
  129. })
  130. it('rejects a delayed create after close even when that identity has never been allocated', async () => {
  131. const { controller, agent, subprocess } = fixture()
  132. await controller.close(agent, id)
  133. await controller.close(agent, id)
  134. await expect(controller.create(agent, request, signal())).rejects.toThrow('closed in this Session')
  135. expect(subprocess.spawnTerminal).not.toHaveBeenCalled()
  136. const nextId = 'next-terminal' as WebTerminalId
  137. await expect(controller.create(agent, { ...request, id: nextId }, signal())).resolves.toMatchObject({ id: nextId })
  138. expect(subprocess.spawnTerminal).toHaveBeenCalledOnce()
  139. })
  140. it('rejects original, duplicate and later creates when close arrives during allocation', async () => {
  141. const { controller, agent, subprocess, handle } = fixture()
  142. const allocation = Promise.withResolvers<SubprocessTerminalHandle>()
  143. const spawning = Promise.withResolvers<undefined>()
  144. subprocess.spawnTerminal.mockImplementationOnce(() => { spawning.resolve(undefined); return allocation.promise })
  145. const creating = controller.create(agent, request, signal())
  146. const duplicate = controller.create(agent, request, signal())
  147. const rejected = expect(creating).rejects.toThrow('closed in this Session')
  148. const duplicateRejected = expect(duplicate).rejects.toThrow('closed in this Session')
  149. try {
  150. await spawning.promise
  151. const closing = controller.close(agent, id)
  152. await expect(controller.create(agent, request, signal())).rejects.toThrow('closed in this Session')
  153. allocation.resolve(handle)
  154. await Promise.all([rejected, duplicateRejected, closing])
  155. await expect(controller.create(agent, request, signal())).rejects.toThrow('closed in this Session')
  156. expect(handle.terminate).toHaveBeenCalledOnce()
  157. expect(subprocess.spawnTerminal).toHaveBeenCalledOnce()
  158. expect(controller.list(agent.id)).toEqual([])
  159. } finally { allocation.resolve(handle) }
  160. })
  161. it('retains failed allocation cleanup for a later explicit close', async () => {
  162. const { controller, agent, subprocess, handle } = fixture()
  163. const abort = new AbortController()
  164. subprocess.spawnTerminal.mockImplementationOnce(async () => { abort.abort(new Error('request disconnected')); return handle })
  165. vi.mocked(handle.terminate).mockRejectedValueOnce(new Error('cleanup failed'))
  166. await expect(controller.create(agent, request, abort.signal)).rejects.toThrow('cleanup failed')
  167. expect(controller.list(agent.id)).toMatchObject([{ id, state: 'failed' }])
  168. await controller.close(agent, id)
  169. expect(handle.terminate).toHaveBeenCalledTimes(2)
  170. expect(controller.list(agent.id)).toEqual([])
  171. })
  172. it('retains a terminal when process cleanup fails so closing can be retried', async () => {
  173. const { controller, agent, handle } = fixture()
  174. await controller.create(agent, request, signal())
  175. vi.mocked(handle.terminate).mockRejectedValueOnce(new Error('process still alive'))
  176. await expect(controller.close(agent, id)).rejects.toThrow('still alive')
  177. expect(controller.list(agent.id)).toHaveLength(1)
  178. await expect(controller.create(agent, request, signal())).rejects.toThrow('closed in this Session')
  179. await controller.close(agent, id)
  180. expect(controller.list(agent.id)).toHaveLength(0)
  181. })
  182. it('rejects invalid dimensions, unavailable shells and oversized input before executing them', async () => {
  183. const { controller, agent, subprocess } = fixture()
  184. await expect(controller.create(agent, { ...request, cols: 1 }, signal())).rejects.toThrow('dimensions')
  185. subprocess.resolveExecutable.mockRejectedValueOnce(new SubprocessExecutableNotFoundError('shell unavailable'))
  186. await expect(controller.create(agent, request, signal())).rejects.toThrow('unavailable')
  187. expect(subprocess.spawnTerminal).not.toHaveBeenCalled()
  188. await expect(controller.write(agent, id, 'writer' as TerminalAttachmentId, 'x'.repeat(1001))).rejects.toThrow('input')
  189. })
  190. it('keeps the committed identity on repeated creation and counts pending reservations toward the Session limit', async () => {
  191. const { controller, agent, subprocess, handle } = fixture({ maxTerminals: 1 })
  192. const allocation = Promise.withResolvers<SubprocessTerminalHandle>()
  193. const spawning = Promise.withResolvers<undefined>()
  194. subprocess.spawnTerminal.mockImplementationOnce(() => { spawning.resolve(undefined); return allocation.promise })
  195. const creating = controller.create(agent, request, signal())
  196. try {
  197. await spawning.promise
  198. await expect(controller.create(agent, { ...request, id: 'another' as WebTerminalId }, signal())).rejects.toMatchObject({ code: 'terminal/limit-reached', details: { limit: 1 } })
  199. } finally { allocation.resolve(handle) }
  200. const first = await creating
  201. expect(await controller.create(agent, request, signal())).toBe(first)
  202. expect(subprocess.spawnTerminal).toHaveBeenCalledOnce()
  203. })
  204. it('keeps failed allocations reserved until their cleanup succeeds', async () => {
  205. const { controller, agent, subprocess, handle } = fixture({ maxTerminals: 1 })
  206. const abort = new AbortController()
  207. subprocess.spawnTerminal.mockImplementationOnce(async () => { abort.abort('lost request'); return handle })
  208. handle.terminate.mockRejectedValueOnce(new Error('still alive'))
  209. await expect(controller.create(agent, request, abort.signal)).rejects.toThrow('cleanup failed')
  210. expect(controller.list(agent.id)).toMatchObject([{ id, state: 'failed', error: 'lost request' }])
  211. await expect(controller.create(agent, request, signal())).rejects.toThrow('Close the failed terminal allocation')
  212. await expect(controller.create(agent, { ...request, id: 'another' as WebTerminalId }, signal())).rejects.toMatchObject({ code: 'terminal/limit-reached', details: { limit: 1 } })
  213. await controller.close(agent, id)
  214. expect(controller.list(agent.id)).toEqual([])
  215. })
  216. it('lets close reclaim an allocation whose request failed while close was waiting', async () => {
  217. const { controller, agent, subprocess, handle } = fixture()
  218. const allocation = Promise.withResolvers<SubprocessTerminalHandle>()
  219. const abort = new AbortController()
  220. subprocess.spawnTerminal.mockImplementationOnce(() => allocation.promise)
  221. const creating = controller.create(agent, request, abort.signal)
  222. const rejected = expect(creating).rejects.toThrow('cancelled')
  223. const closing = controller.close(agent, id)
  224. abort.abort(new Error('cancelled'))
  225. allocation.resolve(handle)
  226. await rejected
  227. await closing
  228. expect(handle.terminate).toHaveBeenCalledOnce()
  229. expect(controller.list(agent.id)).toEqual([])
  230. })
  231. it('routes input, resize and trimmed names through the active attachment', async () => {
  232. const { controller, agent, handle } = fixture({ maxInputBytes: 6 })
  233. await controller.create(agent, request, signal())
  234. const attachmentId = 'writer' as TerminalAttachmentId
  235. const stream = controller.follow(agent, id, attachmentId, signal())[Symbol.asyncIterator]()
  236. await stream.next()
  237. try {
  238. await controller.write(agent, id, attachmentId, '终端')
  239. expect(handle.write).toHaveBeenCalledWith('终端')
  240. await expect(controller.write(agent, id, attachmentId, '终端!')).rejects.toThrow('input exceeds')
  241. await controller.resize(agent, id, attachmentId, 200, 100)
  242. expect(handle.resize).toHaveBeenCalledWith(200, 100)
  243. controller.rename(agent, id, ' server logs ')
  244. expect(controller.list(agent.id)).toMatchObject([{ title: 'server logs', cols: 200, rows: 100 }])
  245. } finally { await stream.return?.() }
  246. })
  247. it.each([{ cols: 1.5, rows: 24 }, { cols: 201, rows: 24 }, { cols: 80, rows: 1.5 }, { cols: 80, rows: 0 }, { cols: 80, rows: 101 }])('rejects dimensions $cols × $rows before allocation or resize', async (dimensions) => {
  248. const { controller, agent, subprocess, handle } = fixture()
  249. await expect(controller.create(agent, { ...request, ...dimensions }, signal())).rejects.toThrow('dimensions')
  250. await expect(controller.resize(agent, id, 'writer' as TerminalAttachmentId, dimensions.cols, dimensions.rows)).rejects.toThrow('dimensions')
  251. expect(subprocess.spawnTerminal).not.toHaveBeenCalled()
  252. expect(handle.resize).not.toHaveBeenCalled()
  253. })
  254. it('rejects invalid wire identities and names without changing retained terminals', async () => {
  255. const { controller, agent } = fixture()
  256. await expect(controller.create(agent, { ...request, id: '../terminal' as WebTerminalId }, signal())).rejects.toThrow('Invalid terminal identity')
  257. expect(() => controller.follow(agent, id, '' as TerminalAttachmentId, signal())).toThrow('attachment identity')
  258. expect(() => { controller.rename(agent, id, ' ') }).toThrow('1–120')
  259. expect(() => { controller.rename(agent, id, 'x'.repeat(121)) }).toThrow('1–120')
  260. await controller.close(agent, id)
  261. expect(controller.list(agent.id)).toEqual([])
  262. })
  263. it('uses the Session sandbox policy to confine its selected shell', async () => {
  264. const { controller, agent, ctx, sandboxPolicy, subprocess } = fixture()
  265. const policy: SandboxExecutionPolicy = { mode: 'workspace-write', workspaceRoot: '/workspace', sessionId: agent.id }
  266. sandboxPolicy.resolve.mockReturnValue(policy)
  267. const confine = vi.fn((argv: readonly string[]) => ({ argv: ['sandbox-runner', ...argv] }))
  268. ctx.provide('sandbox', { confine } as never)
  269. await controller.create(agent, request, signal())
  270. expect(confine).toHaveBeenCalledWith(['/bin/bash', '--noprofile', '--norc', '-i'], policy, expect.any(AbortSignal))
  271. expect(subprocess.spawnTerminal).toHaveBeenCalledWith(expect.objectContaining({ argv: ['sandbox-runner', '/bin/bash', '--noprofile', '--norc', '-i'], env: { DSH_SESSION_ID: agent.id }, graceMs: 100 }))
  272. })
  273. it('rejects a confined Session without a sandbox provider before spawning', async () => {
  274. const { controller, agent, sandboxPolicy, subprocess } = fixture()
  275. sandboxPolicy.resolve.mockReturnValue({ mode: 'read-only', workspaceRoot: '/workspace' })
  276. await expect(controller.create(agent, request, signal())).rejects.toThrow('requires an execution sandbox provider')
  277. expect(subprocess.spawnTerminal).not.toHaveBeenCalled()
  278. })
  279. it.each(['subprocess', 'sandboxPolicy'] as const)('fails clearly when the Session lacks %s', (missing) => {
  280. const { controller, subprocess, sandboxPolicy } = fixture()
  281. const isolated = new Context()
  282. roots.push(isolated)
  283. if (missing !== 'subprocess') isolated.provide('subprocess', subprocess as never)
  284. if (missing !== 'sandboxPolicy') isolated.provide('sandboxPolicy', sandboxPolicy as never)
  285. expect(() => controller.environment(owner(isolated), signal())).toThrow('requires subprocess and sandbox policy providers')
  286. })
  287. it('blocks sandbox-mode changes only while that Session retains a terminal', async () => {
  288. const { controller, agent, ctx, projections } = fixture()
  289. const mode = (mode: SandboxMode): void => { ctx.emit('session/event', agent.session, { type: 'sandbox/mode', data: { mode } } as SessionEvent) }
  290. ctx.emit('session/disposed', agent.session)
  291. ctx.emit('session/event', agent.session, { type: 'turn/start', data: { turn: 1 } } as SessionEvent)
  292. expect(() => { mode('workspace-write') }).not.toThrow()
  293. await controller.create(agent, request, signal())
  294. expect(() => { mode('danger-full-access') }).not.toThrow()
  295. expect(() => { mode('workspace-write') }).toThrow('Close browser terminals')
  296. projections.stateOf.mockReturnValue('read-only')
  297. expect(() => { mode('read-only') }).not.toThrow()
  298. expect(() => { mode('danger-full-access') }).toThrow('Close browser terminals')
  299. await controller.close(agent, id)
  300. expect(() => { mode('workspace-write') }).not.toThrow()
  301. })
  302. it('terminates committed processes when the Session effect ends', async () => {
  303. const { controller, agent, handle, disposeEffect } = fixture()
  304. await controller.create(agent, request, signal())
  305. await disposeEffect('terminal-controller.owner')
  306. expect(handle.terminate).toHaveBeenCalledOnce()
  307. expect(controller.list(agent.id)).toEqual([])
  308. })
  309. it('cleans up a Session when its real Agent plugin fiber is disposed', async () => {
  310. const { controller, ctx, handle } = fixture()
  311. let agent: Agent | undefined
  312. const fiber = await ctx.plugin((child) => { agent = owner(child) })
  313. if (agent === undefined) throw new Error('Agent plugin did not load')
  314. await controller.create(agent, request, signal())
  315. await fiber.dispose()
  316. expect(handle.terminate).toHaveBeenCalledOnce()
  317. expect(controller.list(agent.id)).toEqual([])
  318. })
  319. it('waits for pending creation during Host disposal and rolls back its process before resolving', async () => {
  320. const { controller, agent, subprocess, handle, disposeEffect } = fixture()
  321. const allocation = Promise.withResolvers<SubprocessTerminalHandle>()
  322. const spawning = Promise.withResolvers<undefined>()
  323. subprocess.spawnTerminal.mockImplementationOnce(() => { spawning.resolve(undefined); return allocation.promise })
  324. const creating = controller.create(agent, request, signal())
  325. const rejected = expect(creating).rejects.toThrow('disposed')
  326. await spawning.promise
  327. const disposing = disposeEffect('terminal-controller.processes')
  328. allocation.resolve(handle)
  329. await rejected
  330. await disposing
  331. expect(handle.terminate).toHaveBeenCalledOnce()
  332. expect(controller.list(agent.id)).toEqual([])
  333. await expect(controller.create(agent, request, signal())).rejects.toThrow('controller disposed')
  334. })
  335. it('shares cleanup between the Session and Host effects while awaiting process termination', async () => {
  336. const { controller, agent, handle, disposeEffect } = fixture()
  337. await controller.create(agent, request, signal())
  338. const stopping = Promise.withResolvers<undefined>()
  339. const stopped = Promise.withResolvers<undefined>()
  340. const terminate = handle.terminate.getMockImplementation()
  341. if (terminate === undefined) throw new Error('Missing process cleanup fixture')
  342. handle.terminate.mockImplementationOnce(async () => { stopping.resolve(undefined); await stopped.promise; await terminate() })
  343. const ownerDisposal = disposeEffect('terminal-controller.owner')
  344. try {
  345. await stopping.promise
  346. const hostDisposal = disposeEffect('terminal-controller.processes')
  347. stopped.resolve(undefined)
  348. await Promise.all([ownerDisposal, hostDisposal])
  349. expect(handle.terminate).toHaveBeenCalledOnce()
  350. expect(controller.list(agent.id)).toEqual([])
  351. } finally { stopped.resolve(undefined) }
  352. })
  353. it('retains cleanup failures from both Session and Host disposal for explicit retry', async () => {
  354. const { controller, agent, handle, disposeEffect } = fixture()
  355. await controller.create(agent, request, signal())
  356. handle.terminate.mockRejectedValueOnce(new Error('still alive'))
  357. await expect(disposeEffect('terminal-controller.owner')).rejects.toThrow('Session terminal cleanup failed')
  358. await expect(controller.create(agent, request, signal())).rejects.toThrow('Session owner disposed')
  359. handle.terminate.mockRejectedValueOnce(new Error('still alive again'))
  360. await expect(disposeEffect('terminal-controller.processes')).rejects.toThrow('Browser terminal cleanup failed')
  361. expect(controller.list(agent.id)).toHaveLength(1)
  362. await controller.close(agent, id)
  363. expect(controller.list(agent.id)).toEqual([])
  364. expect(handle.terminate).toHaveBeenCalledTimes(3)
  365. })
  366. it('reclaims retained failed allocations when the owning Session ends', async () => {
  367. const { controller, agent, subprocess, handle, disposeEffect } = fixture()
  368. const abort = new AbortController()
  369. subprocess.spawnTerminal.mockImplementationOnce(async () => { abort.abort(new Error('disconnected')); return handle })
  370. handle.terminate.mockRejectedValueOnce(new Error('first cleanup failed'))
  371. await expect(controller.create(agent, request, abort.signal)).rejects.toThrow('cleanup failed')
  372. await disposeEffect('terminal-controller.owner')
  373. expect(handle.terminate).toHaveBeenCalledTimes(2)
  374. expect(controller.list(agent.id)).toEqual([])
  375. })
  376. })
  377. describe('shell resolution', () => {
  378. it('accepts an omitted shell profile and defaults configured arguments to an empty list', () => {
  379. // Loader input is unvalidated; the schema's declared type describes its normalized output.
  380. const parse = (input: unknown): Config => TerminalController.Config(input as Config)
  381. expect(parse({}).shell).toBeUndefined()
  382. expect(parse({ shell: { path: 'custom', name: 'Project shell' } }).shell).toEqual({ path: 'custom', name: 'Project shell', args: [] })
  383. expect(() => parse({ shell: { name: 'Project shell' } })).toThrow()
  384. })
  385. it.each([
  386. { platform: 'posix' as const, path: '/bin/sh', name: 'sh', args: ['-i'] },
  387. { platform: 'windows' as const, path: 'cmd.exe', name: 'cmd.exe', args: [] },
  388. ])('uses the conservative $platform fallback only when the provider omits its default shell', async ({ platform, path, name, args }) => {
  389. const { subprocess } = fixture()
  390. subprocess.terminalEnvironment.mockResolvedValue({ platform })
  391. const runtime = subprocess as unknown as SubprocessRuntime
  392. const requestSignal = signal()
  393. expect(await resolveShell(runtime, undefined, requestSignal)).toEqual({ path, name, args })
  394. expect(subprocess.resolveExecutable).toHaveBeenCalledExactlyOnceWith(path, undefined, requestSignal)
  395. })
  396. it.each([
  397. { platform: 'posix' as const, defaultShell: '/usr/local/bin/fish', name: 'fish', args: ['-i'] },
  398. { platform: 'windows' as const, defaultShell: 'C:\\Windows\\CMD.EXE', name: 'CMD.EXE', args: [] },
  399. { platform: 'windows' as const, defaultShell: 'C:\\PowerShell\\powershell.exe', name: 'powershell.exe', args: ['-NoLogo'] },
  400. { platform: 'posix' as const, defaultShell: '/usr/local/bin/pwsh', name: 'pwsh', args: ['-NoLogo'] },
  401. ])('resolves only the declared default $defaultShell with its interactive arguments', async ({ platform, defaultShell, name, args }) => {
  402. const { subprocess } = fixture()
  403. subprocess.terminalEnvironment.mockResolvedValue({ platform, defaultShell })
  404. subprocess.resolveExecutable.mockResolvedValue('/resolved/shell')
  405. const runtime = subprocess as unknown as SubprocessRuntime
  406. const requestSignal = signal()
  407. expect(await resolveShell(runtime, undefined, requestSignal)).toEqual({ path: '/resolved/shell', name, args })
  408. expect(subprocess.terminalEnvironment).toHaveBeenCalledExactlyOnceWith(requestSignal)
  409. expect(subprocess.resolveExecutable).toHaveBeenCalledExactlyOnceWith(defaultShell, undefined, requestSignal)
  410. })
  411. it('uses an explicit profile without querying the environment and preserves its name and arguments', async () => {
  412. const { subprocess } = fixture()
  413. subprocess.resolveExecutable.mockResolvedValue('/resolved/custom')
  414. const runtime = subprocess as unknown as SubprocessRuntime
  415. const requestSignal = signal()
  416. const configured = { path: 'custom', name: 'Project shell', args: ['--project'] }
  417. expect(await resolveShell(runtime, configured, requestSignal)).toEqual({ ...configured, path: '/resolved/custom' })
  418. expect(subprocess.terminalEnvironment).not.toHaveBeenCalled()
  419. expect(subprocess.resolveExecutable).toHaveBeenCalledExactlyOnceWith('custom', undefined, requestSignal)
  420. })
  421. it.each([new SubprocessExecutableNotFoundError('missing default'), new Error('transport unavailable')])('reports default resolution failure without attempting fallback: %s', async (failure) => {
  422. const { subprocess } = fixture()
  423. subprocess.resolveExecutable.mockRejectedValue(failure)
  424. const runtime = subprocess as unknown as SubprocessRuntime
  425. await expect(resolveShell(runtime, undefined, signal())).rejects.toBe(failure)
  426. expect(subprocess.resolveExecutable).toHaveBeenCalledOnce()
  427. })
  428. it('reports an unavailable configured shell without consulting the provider default', async () => {
  429. const { subprocess } = fixture()
  430. const failure = new SubprocessExecutableNotFoundError('missing configured shell')
  431. subprocess.resolveExecutable.mockRejectedValue(failure)
  432. const runtime = subprocess as unknown as SubprocessRuntime
  433. await expect(resolveShell(runtime, { path: '/missing', name: 'missing', args: [] }, signal())).rejects.toBe(failure)
  434. expect(subprocess.resolveExecutable).toHaveBeenCalledOnce()
  435. expect(subprocess.terminalEnvironment).not.toHaveBeenCalled()
  436. })
  437. it('propagates environment cancellation before verifying an executable', async () => {
  438. const { subprocess } = fixture()
  439. const cancelled = new Error('request disconnected')
  440. subprocess.terminalEnvironment.mockRejectedValue(cancelled)
  441. const runtime = subprocess as unknown as SubprocessRuntime
  442. await expect(resolveShell(runtime, undefined, signal())).rejects.toBe(cancelled)
  443. expect(subprocess.resolveExecutable).not.toHaveBeenCalled()
  444. })
  445. })
  446. it.skipIf(process.platform === 'win32')('runs a real interactive shell with completion, TERM and live window dimensions', async () => {
  447. const cwd = await mkdtemp(join(tmpdir(), 'dsh-web-terminal-'))
  448. const ctx = new Context()
  449. const runtime = await ctx.plugin(LocalSubprocessRuntime)
  450. try {
  451. const handle = await ctx.subprocess.spawnTerminal({ argv: ['/bin/bash', '--noprofile', '--norc', '-i'], cwd, rows: 24, cols: 80, terminalType: 'xterm-256color', graceMs: 100, env: { PS1: 'READY> ', PS2: '' } })
  452. let output = ''
  453. handle.output.on('data', (data: Buffer) => { output += data.toString('utf8') })
  454. try {
  455. await expect.poll(() => output).toContain('READY>')
  456. await handle.resize(100, 30)
  457. await handle.write("printf 'TERM:%s\\n' \"$TERM\"; stty size\r")
  458. await expect.poll(() => output).toContain('TERM:xterm-256color')
  459. await expect.poll(() => output).toContain('30 100')
  460. // Bash's builtin completion expands this unambiguous command before Enter.
  461. await handle.write('histor\t')
  462. await expect.poll(() => output).toContain('history')
  463. } finally { await handle.terminate() }
  464. await expect(handle.done).resolves.toBeDefined()
  465. } finally {
  466. await runtime.dispose()
  467. await ctx.fiber.dispose()
  468. await rm(cwd, { recursive: true, force: true })
  469. }
  470. })
  471. it('discovers installed shells once per path, preserves default arguments, and refuses unlisted paths', async () => {
  472. const h = fixture({ shellCandidates: ['bash', 'zsh', 'missing'] })
  473. h.subprocess.resolveExecutable.mockImplementation(async (path) => {
  474. if (path === 'missing') throw new SubprocessExecutableNotFoundError('absent')
  475. return path.startsWith('/') ? path : `/bin/${path}`
  476. })
  477. const shells = await h.controller.shells(h.agent, signal())
  478. expect(shells).toEqual([config.shell, { path: '/bin/zsh', name: 'zsh', args: ['-i'] }])
  479. expect(h.subprocess.spawnTerminal).not.toHaveBeenCalled()
  480. await expect(h.controller.create(h.agent, { ...request, shellPath: '/bin/unlisted' }, signal())).rejects.toThrow('Selected shell is not available')
  481. expect(h.subprocess.spawnTerminal).not.toHaveBeenCalled()
  482. const created = await h.controller.create(h.agent, { ...request, shellPath: '/bin/zsh' }, signal())
  483. expect(created.shell.path).toBe('/bin/zsh')
  484. expect(h.subprocess.spawnTerminal).toHaveBeenCalledWith(expect.objectContaining({ argv: ['/bin/zsh', '-i'] }))
  485. h.subprocess.resolveExecutable.mockRejectedValue(new Error('SSH disconnected'))
  486. await expect(h.controller.shells(h.agent, signal())).rejects.toThrow('SSH disconnected')
  487. expect(await h.controller.create(h.agent, { ...request, shellPath: '/bin/bash' }, signal())).toBe(created)
  488. })
  489. it('propagates optional-shell discovery transport errors and cancellation', async () => {
  490. const h = fixture({ shellCandidates: ['fish'] })
  491. h.subprocess.resolveExecutable.mockImplementation(async (path) => {
  492. if (path === 'fish') throw new Error('lookup transport failed')
  493. return path
  494. })
  495. await expect(h.controller.shells(h.agent, signal())).rejects.toThrow('lookup transport failed')
  496. const cancelled = AbortSignal.abort(new Error('cancelled discovery'))
  497. expect(() => h.controller.shells(h.agent, cancelled)).toThrow('cancelled discovery')
  498. })
  499. it('deduplicates Windows executable paths regardless of letter case', async () => {
  500. const h = fixture({ shell: { path: 'C:\\Windows\\cmd.exe', name: 'Command Prompt', args: [] }, shellCandidates: ['c:\\windows\\cmd.exe'] })
  501. expect(await h.controller.shells(h.agent, signal())).toEqual([{ path: 'C:\\Windows\\cmd.exe', name: 'Command Prompt', args: [] }])
  502. })