controller.spec.ts 37 KB

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