terminal.spec.ts 12 KB

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