terminal.spec.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. /** Terminal screen continuity and process ownership under real output scheduling. */
  2. import { PassThrough } from 'node:stream'
  3. import { afterEach, describe, expect, it, vi } from 'vitest'
  4. import type { SubprocessOutcome, SubprocessTerminalHandle } from '@deepseek-ai/dsh-subprocess'
  5. import { BrowserTerminal } from '../src/terminal.ts'
  6. import { TerminalFollower } from '../src/stream.ts'
  7. import type { TerminalAttachmentId, TerminalFrame, WebTerminalId, WebTerminalInfo } from '../src/types.ts'
  8. const info: WebTerminalInfo = { id: 'terminal-test' as WebTerminalId, title: 'bash', shell: { path: '/bin/bash', name: 'bash', args: ['-i'] }, cwd: '/workspace', cols: 80, rows: 24, state: 'running', exitCode: null }
  9. const attachment = (id: string): TerminalAttachmentId => id as TerminalAttachmentId
  10. const cleanups: (() => Promise<void>)[] = []
  11. afterEach(async () => { await Promise.all(cleanups.splice(0).map(close => close())) })
  12. function fixture() {
  13. const output = new PassThrough()
  14. const outcome = Promise.withResolvers<SubprocessOutcome>()
  15. const handle = {
  16. pid: 123, output, done: outcome.promise, write: vi.fn(async () => {}), resize: vi.fn(async () => {}),
  17. inspectActivity: async () => ({ state: 'unknown' as const, revision: 0 }),
  18. inspectForeground: async () => undefined, signalForeground: async () => 123,
  19. terminate: vi.fn(async () => { output.end(); outcome.resolve({ exitCode: 0, signal: null }) }),
  20. }
  21. const checked: SubprocessTerminalHandle = handle
  22. const terminal = new BrowserTerminal(checked, info, 100, 100_000)
  23. cleanups.push(() => terminal.close())
  24. return { terminal, output, outcome, handle }
  25. }
  26. async function attach(terminal: BrowserTerminal, id = 'first') {
  27. const controller = new AbortController()
  28. const iterator = terminal.follow(attachment(id), controller.signal)[Symbol.asyncIterator]()
  29. const baseline = await readFrame(iterator)
  30. cleanups.push(async () => { controller.abort(); await iterator.return?.() })
  31. return { controller, iterator, baseline }
  32. }
  33. describe('BrowserTerminal', () => {
  34. it('restores the screen after detach without re-executing the shell or replaying duplicate output', async () => {
  35. const { terminal, output, handle } = fixture()
  36. const first = await attach(terminal)
  37. expect(first.baseline).toMatchObject({ type: 'snapshot', sequence: 0 })
  38. output.write(Buffer.from('hello\r\n'))
  39. expect(await readFrame(first.iterator)).toMatchObject({ type: 'output', sequence: 1, data: 'hello\r\n' })
  40. first.controller.abort()
  41. await first.iterator.return?.()
  42. expect(handle.terminate).not.toHaveBeenCalled()
  43. output.write(Buffer.from('world'))
  44. await expect.poll(() => terminal.info.state).toBe('running')
  45. const second = await attach(terminal, 'second')
  46. // The baseline and its output queue share the same ordered screen write queue.
  47. const frames = [second.baseline]
  48. if (second.baseline.type === 'snapshot' && !second.baseline.screen.includes('world')) frames.push(await readFrame(second.iterator))
  49. expect(JSON.stringify(frames)).toContain('world')
  50. expect(JSON.stringify(frames)).toContain('hello')
  51. expect(handle.terminate).not.toHaveBeenCalled()
  52. })
  53. it('preserves split UTF-8, gives the newest attachment input, and resizes both PTY and recovery screen', async () => {
  54. const { terminal, output, handle } = fixture()
  55. const first = await attach(terminal)
  56. const encoded = Buffer.from('终端')
  57. output.write(encoded.subarray(0, 2))
  58. await expect.poll(() => output.readableLength).toBe(0)
  59. output.write(encoded.subarray(2))
  60. expect(await readFrame(first.iterator)).toMatchObject({ type: 'output', data: '终端' })
  61. const second = await attach(terminal, 'second')
  62. await expect(terminal.write(attachment('first'), 'ignored')).rejects.toMatchObject({ code: 'terminal/control-unavailable', details: { reason: 'read-only' } })
  63. await terminal.write(attachment('second'), '\t')
  64. expect(handle.write).toHaveBeenCalledWith('\t')
  65. await terminal.resize(attachment('second'), 100, 30)
  66. expect(handle.resize).toHaveBeenCalledWith(100, 30)
  67. expect(terminal.info).toMatchObject({ cols: 100, rows: 30 })
  68. second.controller.abort()
  69. await second.iterator.return?.()
  70. expect(terminal.info.controllerId).toBeUndefined()
  71. })
  72. it('keeps exit facts and screen until explicit cleanup and never starts a replacement process', async () => {
  73. const { terminal, output, outcome, handle } = fixture()
  74. const first = await attach(terminal)
  75. output.end('done')
  76. outcome.resolve({ exitCode: 7, signal: null })
  77. expect(await readFrame(first.iterator)).toMatchObject({ type: 'output', data: 'done' })
  78. expect(await readFrame(first.iterator)).toMatchObject({ type: 'state', info: { state: 'exited', exitCode: 7 } })
  79. expect(handle.terminate).not.toHaveBeenCalled()
  80. const second = await attach(terminal, 'second')
  81. expect(second.baseline).toMatchObject({ type: 'snapshot', info: { state: 'exited', exitCode: 7 } })
  82. await terminal.close()
  83. expect(handle.terminate).toHaveBeenCalledOnce()
  84. })
  85. it('drains final output and exit state before closing followers', async () => {
  86. const { terminal, handle, output, outcome } = fixture()
  87. const first = await attach(terminal)
  88. vi.mocked(handle.terminate).mockImplementationOnce(async () => {
  89. output.end('FINAL OUTPUT\r\n')
  90. outcome.resolve({ exitCode: 0, signal: null })
  91. })
  92. await terminal.close()
  93. expect(await readFrame(first.iterator)).toMatchObject({ type: 'output', data: 'FINAL OUTPUT\r\n' })
  94. expect(await readFrame(first.iterator)).toMatchObject({ type: 'state', info: { state: 'exited' } })
  95. expect((await first.iterator.next()).done).toBe(true)
  96. })
  97. it('rejects input before attachment, during close and after process exit', async () => {
  98. const { terminal, handle, output, outcome } = fixture()
  99. await expect(terminal.write(attachment('first'), 'ignored')).rejects.toMatchObject({ code: 'terminal/control-unavailable', details: { reason: 'read-only' } })
  100. const first = await attach(terminal)
  101. output.end()
  102. outcome.resolve({ exitCode: 0, signal: null })
  103. expect(await readFrame(first.iterator)).toMatchObject({ type: 'state', info: { state: 'exited' } })
  104. await expect(terminal.write(attachment('first'), 'ignored')).rejects.toMatchObject({ code: 'terminal/control-unavailable', details: { reason: 'not-running' } })
  105. await expect(terminal.resize(attachment('first'), 100, 30)).rejects.toMatchObject({ code: 'terminal/control-unavailable', details: { reason: 'not-running' } })
  106. const closing = terminal.close()
  107. await expect(terminal.write(attachment('first'), 'ignored')).rejects.toMatchObject({ code: 'terminal/control-unavailable', details: { reason: 'not-running' } })
  108. await closing
  109. expect(handle.write).not.toHaveBeenCalled()
  110. expect(handle.resize).not.toHaveBeenCalled()
  111. })
  112. it('preserves the input controller when an older follower detaches', async () => {
  113. const { terminal, handle } = fixture()
  114. const first = await attach(terminal)
  115. const second = await attach(terminal, 'second')
  116. first.controller.abort()
  117. await first.iterator.return?.()
  118. expect(terminal.info.controllerId).toBe(attachment('second'))
  119. terminal.rename('build output')
  120. expect(await readFrame(second.iterator)).toMatchObject({ type: 'state', info: { title: 'build output', controllerId: 'second' } })
  121. await terminal.write(attachment('second'), 'pwd\r')
  122. expect(handle.write).toHaveBeenCalledWith('pwd\r')
  123. })
  124. it('does not grant input to attachments cancelled before their snapshot is ready', async () => {
  125. const { terminal, handle } = fixture()
  126. const aborted = new AbortController()
  127. aborted.abort(new Error('already detached'))
  128. await expect(terminal.follow(attachment('cancelled'), aborted.signal)[Symbol.asyncIterator]().next()).rejects.toThrow('already detached')
  129. await attach(terminal)
  130. const writing = Promise.withResolvers<undefined>()
  131. const written = Promise.withResolvers<undefined>()
  132. handle.write.mockImplementationOnce(async () => { writing.resolve(undefined); await written.promise })
  133. const pendingWrite = terminal.write(attachment('first'), 'pwd\r')
  134. try {
  135. await writing.promise
  136. const abort = new AbortController()
  137. const pendingAttachment = terminal.follow(attachment('late'), abort.signal)[Symbol.asyncIterator]().next()
  138. const rejected = expect(pendingAttachment).rejects.toThrow('detached while waiting')
  139. abort.abort(new Error('detached while waiting'))
  140. written.resolve(undefined)
  141. await pendingWrite
  142. await rejected
  143. expect(terminal.info.controllerId).toBe(attachment('first'))
  144. } finally { written.resolve(undefined) }
  145. })
  146. it('continues accepting operations after a provider write or resize fails', async () => {
  147. const { terminal, handle } = fixture()
  148. await attach(terminal)
  149. handle.write.mockRejectedValueOnce(new Error('input transport failed'))
  150. handle.resize.mockRejectedValueOnce(new Error('resize transport failed'))
  151. await expect(terminal.write(attachment('first'), 'failed')).rejects.toThrow('input transport failed')
  152. await expect(terminal.resize(attachment('first'), 100, 30)).rejects.toThrow('resize transport failed')
  153. expect(terminal.info).toMatchObject({ cols: 80, rows: 24 })
  154. await terminal.write(attachment('first'), 'accepted')
  155. await terminal.resize(attachment('first'), 90, 25)
  156. expect(handle.write).toHaveBeenLastCalledWith('accepted')
  157. expect(terminal.info).toMatchObject({ cols: 90, rows: 25 })
  158. })
  159. it.each([new Error('process wait failed'), 'remote process wait failed'])('publishes a failed process outcome and retains its recovery screen: %s', async (failure) => {
  160. const { terminal, output, outcome } = fixture()
  161. const first = await attach(terminal)
  162. output.end('last output')
  163. outcome.reject(failure)
  164. expect(await readFrame(first.iterator)).toMatchObject({ type: 'output', data: 'last output' })
  165. expect(await readFrame(first.iterator)).toMatchObject({ type: 'state', info: { state: 'failed', error: failure instanceof Error ? failure.message : failure } })
  166. const second = await attach(terminal, 'second')
  167. expect(second.baseline).toMatchObject({ type: 'snapshot', screen: 'last output', info: { state: 'failed' } })
  168. })
  169. it('publishes output-stream failure even when the process wait succeeds', async () => {
  170. const { terminal, output, outcome } = fixture()
  171. const first = await attach(terminal)
  172. output.destroy(new Error('output transport failed'))
  173. outcome.resolve({ exitCode: 0, signal: null })
  174. expect(await readFrame(first.iterator)).toMatchObject({ type: 'state', info: { state: 'failed', error: 'output transport failed' } })
  175. })
  176. it('flushes incomplete UTF-8 at EOF before publishing the process exit', async () => {
  177. const { terminal, output, outcome } = fixture()
  178. const first = await attach(terminal)
  179. output.end(Buffer.from([0xe7, 0xbb]))
  180. outcome.resolve({ exitCode: 0, signal: null })
  181. expect(await readFrame(first.iterator)).toMatchObject({ type: 'output', data: '�' })
  182. expect(await readFrame(first.iterator)).toMatchObject({ type: 'state', info: { state: 'exited' } })
  183. })
  184. it('preserves a leading UTF-8 BOM in the terminal output stream', async () => {
  185. const { terminal, output } = fixture()
  186. const first = await attach(terminal)
  187. output.write(Buffer.from('\uFEFF终端'))
  188. expect(await readFrame(first.iterator)).toMatchObject({ type: 'output', data: '\uFEFF终端' })
  189. })
  190. it('shares concurrent close attempts and permits retry after termination fails', async () => {
  191. const { terminal, handle } = fixture()
  192. await attach(terminal)
  193. handle.terminate.mockRejectedValueOnce(new Error('process range remains alive'))
  194. const first = terminal.close()
  195. expect(terminal.close()).toBe(first)
  196. await expect(first).rejects.toThrow('remains alive')
  197. await terminal.write(attachment('first'), 'retry cleanup next')
  198. await terminal.close()
  199. expect(handle.terminate).toHaveBeenCalledTimes(2)
  200. })
  201. it('reports overflow rather than silently discarding output', async () => {
  202. const follower = new TerminalFollower(64)
  203. follower.push({ type: 'output', sequence: 1, data: 'x'.repeat(128) })
  204. await expect(follower.read(new AbortController().signal)[Symbol.asyncIterator]().next()).rejects.toThrow('buffer')
  205. })
  206. })
  207. async function readFrame(iterator: AsyncIterator<TerminalFrame>): Promise<TerminalFrame> {
  208. const result = await iterator.next()
  209. if (result.done === true) throw new Error('Terminal stream ended before its expected frame')
  210. return result.value
  211. }
  212. it('refuses retention before allocation commit and disposes an uncommitted screen directly', async () => {
  213. const { terminal, handle } = fixture()
  214. expect(() => terminal.retain(new AbortController().signal)).toThrow('not been committed')
  215. await terminal.dispose()
  216. expect(handle.terminate).toHaveBeenCalledOnce()
  217. })