model.client.spec.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. /** Browser view ownership across slow RPCs, remounts and transport generations. */
  2. import { afterEach, expect, it, vi } from 'vitest'
  3. import { RemoteStream, RemoteStreamCarrierError, type ClientRemote, type RemoteStreamOptions } from '@deepseek-ai/dsh-api-gateway/client'
  4. import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
  5. import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
  6. import type {} from '@deepseek-ai/dsh-api-terminal-controller/remote'
  7. import type { SessionId } from '@deepseek-ai/dsh-session/types'
  8. import { TerminalView, type TerminalRemote } from '../src/client/model.ts'
  9. import type { TerminalEnvironment, TerminalFrame, WebTerminalId, WebTerminalInfo } from '../src/types.ts'
  10. const sessionId = 'session' as SessionId
  11. const info: WebTerminalInfo = { id: 'terminal' as WebTerminalId, shell: { name: 'bash', path: '/bin/bash', args: ['-i'] }, title: 'bash', cwd: '/workspace', rows: 24, cols: 80, state: 'running', exitCode: null }
  12. const environment: TerminalEnvironment = {
  13. cwd: info.cwd, maxInputBytes: 1000, maxCols: 200, maxRows: 100, scrollback: 100,
  14. }
  15. const success = <T>(value: T): RemoteResult<T> => ({ ok: true, value })
  16. const cleanups: (() => void | Promise<void>)[] = []
  17. afterEach(async () => { for (const close of cleanups.splice(0).reverse()) await close() })
  18. function untilAborted(signal?: AbortSignal): Promise<void> {
  19. return new Promise((resolve) => {
  20. if (signal?.aborted) resolve()
  21. else signal?.addEventListener('abort', () => { resolve() }, { once: true })
  22. })
  23. }
  24. function failure(message: string): RemoteResult<never> {
  25. return { ok: false, error: new RemoteError('gateway/bad-request', message, {}) }
  26. }
  27. function fixture(prepareStream?: <Item>(stream: RemoteStream<Item>) => void) {
  28. const remote: TerminalRemote = {
  29. environment: vi.fn<TerminalRemote['environment']>(async () => success(environment)), list: vi.fn<TerminalRemote['list']>(async () => success([])),
  30. create: vi.fn<TerminalRemote['create']>(async (_sessionId, request) => success({ ...info, id: request.id })),
  31. close: vi.fn<TerminalRemote['close']>(async () => success(undefined)), rename: vi.fn<TerminalRemote['rename']>(async () => success(undefined)),
  32. write: vi.fn<TerminalRemote['write']>(async () => success(undefined)), resize: vi.fn<TerminalRemote['resize']>(async () => success(undefined)),
  33. follow: vi.fn<TerminalRemote['follow']>(async function* (_sessionId, id, attachmentId, signal) {
  34. yield { type: 'snapshot', sequence: 0, screen: 'ready', info: { ...info, id, controllerId: attachmentId } }
  35. await untilAborted(signal)
  36. }),
  37. }
  38. const options: RemoteStreamOptions<unknown>[] = []
  39. const streams: { dispose(): Promise<void>; restart(): void }[] = []
  40. const generation = createSnapshotStore<ReturnType<ConstructorParameters<typeof RemoteStream>[0]['generation']['getSnapshot']>>(undefined)
  41. const gateway: Pick<ClientRemote, '$stream'> = {
  42. $stream: (option) => {
  43. options.push(option)
  44. const stream = new RemoteStream({ generation }, option)
  45. streams.push(stream)
  46. prepareStream?.(stream)
  47. return stream
  48. },
  49. }
  50. cleanups.push(async () => { await Promise.all(streams.map(stream => stream.dispose())) })
  51. const model = new TerminalView(sessionId, remote, gateway, info.id)
  52. cleanups.push(() => { model.dispose() })
  53. return { model, remote, gateway, options, streams, generation }
  54. }
  55. async function mount(model: TerminalView) {
  56. const detach = model.mount()
  57. await model.refresh()
  58. return detach
  59. }
  60. function acknowledge(model: TerminalView): void {
  61. const render = model.state.getSnapshot().render
  62. if (render !== undefined) model.acknowledge(render.revision)
  63. }
  64. async function connected(model: TerminalView): Promise<void> {
  65. await mount(model)
  66. await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
  67. acknowledge(model)
  68. }
  69. it('does not let a late input failure downgrade a newer connection', async () => {
  70. const { model, remote } = fixture()
  71. await mount(model)
  72. await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
  73. acknowledge(model)
  74. const input = Promise.withResolvers<RemoteResult<void>>()
  75. vi.mocked(remote.write).mockReturnValueOnce(input.promise)
  76. model.write('x')
  77. await expect.poll(() => vi.mocked(remote.write).mock.calls.length).toBe(1)
  78. model.connect()
  79. await expect.poll(() => vi.mocked(remote.follow).mock.calls.length).toBe(2)
  80. await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
  81. model.write('current input')
  82. input.reject(new Error('old attachment was replaced'))
  83. await expect.poll(() => vi.mocked(remote.write).mock.calls.some(call => call[3] === 'current input')).toBe(true)
  84. expect(model.state.getSnapshot()).toMatchObject({ phase: 'connected', writable: true, error: undefined })
  85. })
  86. it('waits for render acknowledgement before publishing subsequent output', async () => {
  87. const { model, remote } = fixture()
  88. vi.mocked(remote.follow).mockImplementation(async function* (_sessionId, id, controllerId, signal) {
  89. const frames: TerminalFrame[] = [
  90. { type: 'snapshot', sequence: 0, screen: '', info: { ...info, id, controllerId } },
  91. { type: 'output', sequence: 1, data: 'first' },
  92. { type: 'output', sequence: 2, data: 'second' },
  93. ]
  94. for (const frame of frames) yield frame
  95. await untilAborted(signal)
  96. })
  97. await mount(model)
  98. await expect.poll(() => model.state.getSnapshot().render?.frame.type).toBe('snapshot')
  99. acknowledge(model)
  100. await expect.poll(() => model.state.getSnapshot().render?.frame).toMatchObject({ type: 'output', sequence: 1 })
  101. acknowledge(model)
  102. await expect.poll(() => model.state.getSnapshot().render?.frame).toMatchObject({ type: 'output', sequence: 2 })
  103. })
  104. it('serializes input and resizes, clamps geometry, and suppresses unchanged sizes', async () => {
  105. const { model, remote } = fixture()
  106. await connected(model)
  107. const input = Promise.withResolvers<RemoteResult<void>>()
  108. vi.mocked(remote.write).mockReturnValueOnce(input.promise)
  109. model.resize(80, 24)
  110. model.write('first')
  111. model.write('second')
  112. model.resize(500, 300)
  113. await expect.poll(() => vi.mocked(remote.write).mock.calls.length).toBe(1)
  114. expect(remote.resize).not.toHaveBeenCalled()
  115. input.resolve(success(undefined))
  116. await expect.poll(() => vi.mocked(remote.resize).mock.calls.length).toBe(1)
  117. const attachmentId = vi.mocked(remote.follow).mock.calls[0]![2]
  118. const id = model.state.getSnapshot().info!.id
  119. expect(vi.mocked(remote.write).mock.calls.map(call => call[3])).toEqual(['first', 'second'])
  120. expect(remote.resize).toHaveBeenCalledWith(sessionId, id, attachmentId, 200, 100)
  121. model.resize(90, 24)
  122. await expect.poll(() => vi.mocked(remote.resize).mock.calls.length).toBe(2)
  123. })
  124. it('bounds queued input by UTF-8 bytes and releases the byte budget after settlement', async () => {
  125. const { model, remote } = fixture()
  126. vi.mocked(remote.environment).mockResolvedValue(success({ ...environment, maxInputBytes: 6 }))
  127. await connected(model)
  128. const input = Promise.withResolvers<RemoteResult<void>>()
  129. vi.mocked(remote.write).mockReturnValueOnce(input.promise)
  130. model.write('界界')
  131. await expect.poll(() => vi.mocked(remote.write).mock.calls.length).toBe(1)
  132. model.write('a')
  133. expect(model.state.getSnapshot()).toMatchObject({ phase: 'failed', error: 'Terminal input buffer is full' })
  134. input.resolve(success(undefined))
  135. model.connect()
  136. await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
  137. model.write('界界')
  138. await expect.poll(() => vi.mocked(remote.write).mock.calls.length).toBe(2)
  139. expect(vi.mocked(remote.write).mock.calls.map(call => call[3])).toEqual(['界界', '界界'])
  140. })
  141. it('drops queued commands from a detached attachment and ignores its late resize failure', async () => {
  142. const { model, remote } = fixture()
  143. await connected(model)
  144. const input = Promise.withResolvers<RemoteResult<void>>()
  145. vi.mocked(remote.resize).mockReturnValueOnce(input.promise)
  146. model.resize(100, 30)
  147. await expect.poll(() => vi.mocked(remote.resize).mock.calls.length).toBe(1)
  148. model.write('stale')
  149. model.resize(110, 35)
  150. model.connect()
  151. await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
  152. model.write('current')
  153. input.resolve(failure('old attachment'))
  154. await expect.poll(() => vi.mocked(remote.write).mock.calls.length).toBe(1)
  155. expect(vi.mocked(remote.write).mock.calls[0]?.[3]).toBe('current')
  156. expect(remote.resize).toHaveBeenCalledOnce()
  157. expect(model.state.getSnapshot().phase).toBe('connected')
  158. })
  159. it('publishes current input and resize failures and can reconnect for another attempt', async () => {
  160. const { model, remote } = fixture()
  161. await connected(model)
  162. vi.mocked(remote.write).mockResolvedValueOnce(failure('input refused'))
  163. model.write('x')
  164. await expect.poll(() => model.state.getSnapshot().error).toBe('input refused')
  165. model.connect()
  166. await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
  167. vi.mocked(remote.resize).mockResolvedValueOnce(failure('resize refused'))
  168. model.resize(100, 30)
  169. await expect.poll(() => model.state.getSnapshot().error).toBe('resize refused')
  170. })
  171. it('treats carrier loss as disconnected only for the active attachment', async () => {
  172. const { model, options } = fixture()
  173. await connected(model)
  174. const first = options[0]!
  175. first.carrierFailed?.(new RemoteStreamCarrierError('offline'))
  176. expect(model.state.getSnapshot()).toMatchObject({ phase: 'disconnected', writable: false })
  177. model.connect()
  178. await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
  179. first.carrierFailed?.(new RemoteStreamCarrierError('late old failure'))
  180. expect(model.state.getSnapshot().phase).toBe('connected')
  181. })
  182. it.each([
  183. ['output before snapshot', [{ type: 'output', sequence: 1, data: 'orphan' }], 'missing its screen snapshot'],
  184. ['sequence gap', [{ type: 'snapshot', sequence: 4, screen: '', info }, { type: 'output', sequence: 6, data: 'gap' }], 'sequence has a gap'],
  185. ['repeated snapshot', [{ type: 'snapshot', sequence: 4, screen: '', info }, { type: 'snapshot', sequence: 4, screen: '', info }], 'Unexpected terminal screen snapshot'],
  186. ] satisfies readonly (readonly [string, readonly TerminalFrame[], string])[])('refuses a malformed output stream: %s', async (_name, frames, message) => {
  187. const { model, remote } = fixture()
  188. vi.mocked(remote.follow).mockImplementation(async function* () { yield* frames })
  189. await mount(model)
  190. if (frames[0]?.type === 'snapshot') {
  191. await expect.poll(() => model.state.getSnapshot().render).toBeDefined()
  192. acknowledge(model)
  193. }
  194. await expect.poll(() => model.state.getSnapshot().error).toContain(message)
  195. expect(model.state.getSnapshot().writable).toBe(false)
  196. })
  197. it('retains an exited screen and closes controls when its stream ends', async () => {
  198. const { model, remote } = fixture()
  199. vi.mocked(remote.follow).mockImplementation(async function* (_sessionId, id, controllerId) {
  200. yield { type: 'snapshot', sequence: 0, screen: 'last screen', info: { ...info, id, controllerId } }
  201. yield { type: 'state', info: { ...info, id, controllerId, state: 'exited', exitCode: 3 } }
  202. })
  203. await connected(model)
  204. await expect.poll(() => model.state.getSnapshot().phase).toBe('closed')
  205. expect(model.state.getSnapshot()).toMatchObject({ writable: false, info: { state: 'exited', exitCode: 3 }, render: { frame: { screen: 'last screen' } } })
  206. })
  207. it('reports an attachment ending while the shell is still running and permits manual reconnect', async () => {
  208. const { model, remote } = fixture()
  209. vi.mocked(remote.follow).mockImplementationOnce(async function* (_sessionId, id, controllerId) {
  210. yield { type: 'snapshot', sequence: 0, screen: '', info: { ...info, id, controllerId } }
  211. })
  212. await connected(model)
  213. await expect.poll(() => model.state.getSnapshot().error).toContain('Terminal attachment ended')
  214. model.connect()
  215. await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
  216. })
  217. it('publishes remote control transfer without replacing the retained screen', async () => {
  218. const { model, remote } = fixture()
  219. vi.mocked(remote.follow).mockImplementation(async function* (_sessionId, id, controllerId, signal) {
  220. yield { type: 'snapshot', sequence: 0, screen: 'retained', info: { ...info, id, controllerId } }
  221. yield { type: 'state', info: { ...info, id } }
  222. await untilAborted(signal)
  223. })
  224. await connected(model)
  225. await expect.poll(() => model.state.getSnapshot().writable).toBe(false)
  226. expect(model.state.getSnapshot().render?.frame).toMatchObject({ type: 'snapshot', screen: 'retained' })
  227. })
  228. /** Pause delivery after the real Gateway iterator settles, before the model observes it. */
  229. function deliveryBarrier() {
  230. const ready = Promise.withResolvers<undefined>()
  231. const release = Promise.withResolvers<undefined>()
  232. let held = false
  233. function prepare<Item>(stream: RemoteStream<Item>): void {
  234. if (held) return
  235. held = true
  236. const iterator = stream[Symbol.asyncIterator]()
  237. let first = true
  238. vi.spyOn(stream, Symbol.asyncIterator).mockReturnValue({
  239. async next() {
  240. if (!first) return iterator.next()
  241. first = false
  242. try {
  243. return await iterator.next()
  244. } finally {
  245. ready.resolve(undefined)
  246. await release.promise
  247. }
  248. },
  249. async return() { return iterator.return!() },
  250. })
  251. }
  252. cleanups.push(() => { release.resolve(undefined) })
  253. return { ready: ready.promise, release: () => { release.resolve(undefined) }, prepare }
  254. }
  255. it('ignores an already delivered screen when its attachment is replaced before the model receives it', async () => {
  256. const barrier = deliveryBarrier()
  257. const { model, remote } = fixture(barrier.prepare)
  258. await mount(model)
  259. await barrier.ready
  260. model.connect()
  261. await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
  262. const current = model.state.getSnapshot()
  263. barrier.release()
  264. await model.rename('settled')
  265. expect(model.state.getSnapshot().render).toBe(current.render)
  266. expect(remote.follow).toHaveBeenCalledTimes(2)
  267. })
  268. it('ignores an already settled stream error after a newer attachment has become writable', async () => {
  269. const barrier = deliveryBarrier()
  270. const { model, remote } = fixture(barrier.prepare)
  271. vi.mocked(remote.follow).mockImplementationOnce(async function* () {
  272. yield* []
  273. throw new Error('retired attachment failed')
  274. })
  275. await mount(model)
  276. await barrier.ready
  277. model.connect()
  278. await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
  279. barrier.release()
  280. await model.rename('settled')
  281. expect(model.state.getSnapshot()).toMatchObject({ phase: 'connected', writable: true, error: undefined })
  282. })
  283. it('releases a pending screen render on carrier generation cancellation and accepts the replacement screen', async () => {
  284. const { model, remote, streams } = fixture()
  285. await mount(model)
  286. await expect.poll(() => model.state.getSnapshot().render).toBeDefined()
  287. const revision = model.state.getSnapshot().render!.revision
  288. streams[0]!.restart()
  289. await expect.poll(() => model.state.getSnapshot().render?.revision).toBe(revision + 1)
  290. expect(remote.follow).toHaveBeenCalledTimes(2)
  291. expect(model.state.getSnapshot().writable).toBe(true)
  292. })
  293. it('does not wait for the DOM callback of a screen whose generation was already cancelled at delivery', async () => {
  294. const barrier = deliveryBarrier()
  295. const { model, remote, streams } = fixture(barrier.prepare)
  296. await mount(model)
  297. await barrier.ready
  298. streams[0]!.restart()
  299. barrier.release()
  300. await expect.poll(() => model.state.getSnapshot().render?.revision).toBe(2)
  301. expect(remote.follow).toHaveBeenCalledTimes(2)
  302. expect(model.state.getSnapshot().writable).toBe(true)
  303. })
  304. it.each(['write', 'resize'] as const)('keeps a fresh attachment writable when a pending %s fails after automatic transport recovery', async (operation) => {
  305. const { model, remote, generation } = fixture()
  306. generation.set({ id: 1, host: { home: '/home/fixture' } })
  307. const disconnected = Promise.withResolvers<undefined>()
  308. vi.mocked(remote.follow).mockImplementationOnce(async function* (_sessionId, id, controllerId, signal) {
  309. yield { type: 'snapshot', sequence: 0, screen: 'before disconnect', info: { ...info, id, controllerId } }
  310. await Promise.race([disconnected.promise, untilAborted(signal)])
  311. if (signal?.aborted) return
  312. throw new RemoteStreamCarrierError('connection lost')
  313. })
  314. await connected(model)
  315. const pending = Promise.withResolvers<RemoteResult<void>>()
  316. if (operation === 'write') {
  317. vi.mocked(remote.write).mockReturnValueOnce(pending.promise)
  318. model.write('old input')
  319. } else {
  320. vi.mocked(remote.resize).mockReturnValueOnce(pending.promise)
  321. model.resize(100, 30)
  322. }
  323. await expect.poll(() => vi.mocked(remote[operation]).mock.calls.length).toBe(1)
  324. const oldAttachmentId = vi.mocked(remote.follow).mock.calls[0]![2]
  325. generation.set(undefined)
  326. disconnected.resolve(undefined)
  327. await expect.poll(() => model.state.getSnapshot().phase).toBe('disconnected')
  328. expect(model.state.getSnapshot().writable).toBe(false)
  329. expect(remote.follow).toHaveBeenCalledOnce()
  330. generation.set({ id: 2, host: { home: '/home/fixture' } })
  331. await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
  332. expect(remote.follow).toHaveBeenCalledTimes(2)
  333. const attachmentId = vi.mocked(remote.follow).mock.calls[1]![2]
  334. expect(attachmentId).not.toBe(oldAttachmentId)
  335. expect(model.state.getSnapshot().info?.controllerId).toBe(attachmentId)
  336. expect(model.state.getSnapshot().render?.frame).toMatchObject({ type: 'snapshot', screen: 'ready' })
  337. model.write('fresh input')
  338. pending.reject(new Error('old attachment was replaced'))
  339. await expect.poll(() => vi.mocked(remote.write).mock.calls.some(call => call[3] === 'fresh input')).toBe(true)
  340. expect(model.state.getSnapshot()).toMatchObject({ phase: 'connected', writable: true, error: undefined })
  341. expect(vi.mocked(remote.write).mock.calls.at(-1)?.[2]).toBe(attachmentId)
  342. expect(remote.create).toHaveBeenCalledOnce()
  343. expect(remote.close).not.toHaveBeenCalled()
  344. })
  345. it('ignores controls before discovery and reconnects an existing process after remount', async () => {
  346. const { model, remote } = fixture()
  347. model.connect()
  348. model.write('early')
  349. model.resize(100, 30)
  350. model.acknowledge(100)
  351. expect(remote.follow).not.toHaveBeenCalled()
  352. expect(remote.write).not.toHaveBeenCalled()
  353. expect(remote.resize).not.toHaveBeenCalled()
  354. const unmount = await mount(model)
  355. await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
  356. unmount()
  357. model.connect()
  358. model.write('detached')
  359. model.resize(100, 30)
  360. expect(remote.follow).toHaveBeenCalledOnce()
  361. expect(remote.write).not.toHaveBeenCalled()
  362. expect(remote.resize).not.toHaveBeenCalled()
  363. model.mount()
  364. await expect.poll(() => remote.follow).toHaveBeenCalledTimes(2)
  365. await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
  366. expect(remote.create).toHaveBeenCalledOnce()
  367. })
  368. it('keeps controls inert when process metadata or the attachment is unavailable', async () => {
  369. const { model, remote } = fixture()
  370. await connected(model)
  371. const state = model.state.getSnapshot()
  372. model.state.set({ ...state, info: undefined })
  373. model.write('missing metadata')
  374. model.resize(100, 30)
  375. expect(remote.write).not.toHaveBeenCalled()
  376. expect(remote.resize).not.toHaveBeenCalled()
  377. model.state.set({ ...state, environment: undefined })
  378. model.resize(100, 30)
  379. await expect.poll(() => remote.resize).toHaveBeenCalledOnce()
  380. expect(vi.mocked(remote.resize).mock.calls[0]?.slice(-2)).toEqual([100, 30])
  381. model.write('unknown budget')
  382. expect(model.state.getSnapshot().error).toBe('Terminal input buffer is full')
  383. expect(remote.write).not.toHaveBeenCalled()
  384. })
  385. it('renames an existing terminal, skips unchanged names, and exposes rename failures', async () => {
  386. const { model, remote } = fixture()
  387. await connected(model)
  388. await model.rename(` ${info.title} `)
  389. expect(remote.rename).not.toHaveBeenCalled()
  390. await model.rename(' Build ')
  391. expect(model.state.getSnapshot()).toMatchObject({ title: 'Build', info: { title: 'Build' } })
  392. vi.mocked(remote.rename).mockRejectedValueOnce('rename connection lost')
  393. await model.rename('Other')
  394. expect(model.state.getSnapshot()).toMatchObject({ phase: 'failed', error: 'rename connection lost', title: 'Build' })
  395. model.dispose()
  396. await model.rename('Ignored')
  397. expect(remote.rename).toHaveBeenCalledTimes(2)
  398. })
  399. it('classifies a discovery carrier failure as disconnected and supports explicit retry', async () => {
  400. const { model, remote } = fixture()
  401. vi.mocked(remote.environment).mockRejectedValueOnce(new RemoteStreamCarrierError('offline'))
  402. await model.refresh()
  403. expect(model.state.getSnapshot()).toMatchObject({ phase: 'disconnected', error: 'offline' })
  404. expect(remote.create).not.toHaveBeenCalled()
  405. await model.refresh()
  406. expect(model.state.getSnapshot().info?.id).toBe(info.id)
  407. expect(remote.create).toHaveBeenCalledOnce()
  408. })
  409. it('retains state when disposal overtakes successful allocation or a failed discovery', async () => {
  410. for (const operation of ['creation', 'discovery'] as const) {
  411. const { model, remote } = fixture()
  412. const creation = Promise.withResolvers<RemoteResult<WebTerminalInfo>>()
  413. const discovery = Promise.withResolvers<RemoteResult<TerminalEnvironment>>()
  414. if (operation === 'creation') vi.mocked(remote.create).mockReturnValueOnce(creation.promise)
  415. else vi.mocked(remote.environment).mockReturnValueOnce(discovery.promise)
  416. const loading = model.refresh()
  417. if (operation === 'creation') await expect.poll(() => remote.create).toHaveBeenCalledOnce()
  418. model.dispose()
  419. const before = model.state.getSnapshot()
  420. if (operation === 'creation') creation.resolve(success(info))
  421. else discovery.reject(new Error('late discovery failure'))
  422. await loading
  423. expect(model.state.getSnapshot()).toBe(before)
  424. expect(remote.follow).not.toHaveBeenCalled()
  425. }
  426. })
  427. it('ignores a successful rename after the view is disposed', async () => {
  428. const { model, remote } = fixture()
  429. await connected(model)
  430. const rename = Promise.withResolvers<RemoteResult<void>>()
  431. vi.mocked(remote.rename).mockReturnValueOnce(rename.promise)
  432. const pending = model.rename('Late')
  433. model.dispose()
  434. const before = model.state.getSnapshot()
  435. rename.resolve(success(undefined))
  436. await pending
  437. expect(model.state.getSnapshot()).toBe(before)
  438. })
  439. it('allows retry after failed process cleanup and never reconnects while close is pending', async () => {
  440. const { model, remote } = fixture()
  441. await connected(model)
  442. const closing = Promise.withResolvers<RemoteResult<void>>()
  443. vi.mocked(remote.close).mockReturnValueOnce(closing.promise)
  444. const first = model.close()
  445. expect(model.close()).toBe(first)
  446. model.connect()
  447. expect(remote.follow).toHaveBeenCalledOnce()
  448. closing.resolve(failure('close refused'))
  449. await expect(first).rejects.toThrow('close refused')
  450. expect(model.state.getSnapshot()).toMatchObject({ phase: 'failed', error: 'close refused' })
  451. await model.close()
  452. expect(model.state.getSnapshot()).toMatchObject({ phase: 'closed', writable: false })
  453. expect(remote.close).toHaveBeenCalledTimes(2)
  454. })
  455. it('does not publish a close result or reconnect after disposal', async () => {
  456. const { model, remote } = fixture()
  457. await connected(model)
  458. const closing = Promise.withResolvers<RemoteResult<void>>()
  459. vi.mocked(remote.close).mockReturnValueOnce(closing.promise)
  460. const pending = model.close()
  461. model.dispose()
  462. const before = model.state.getSnapshot()
  463. closing.resolve(success(undefined))
  464. await pending
  465. model.mount()
  466. model.connect()
  467. expect(model.state.getSnapshot()).toBe(before)
  468. expect(remote.follow).toHaveBeenCalledOnce()
  469. })