api-proxy-workspace.spec.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. import { existsSync, mkdirSync, mkdtempSync, realpathSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { describe, expect, it, vi } from 'vitest'
  5. import { Context } from 'cordis'
  6. import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent'
  7. import type { Agent, AgentFactory } from '@deepseek-ai/dsh-agent'
  8. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  9. import type { Session } from '@deepseek-ai/dsh-session'
  10. import Storage from '@deepseek-ai/dsh-storage'
  11. import { DomainFacility } from '@deepseek-ai/dsh-storage-domain'
  12. import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
  13. import { DirectoryPickerError } from '@deepseek-ai/dsh-host-directory-picker'
  14. import type { DirectoryPickerCapability } from '@deepseek-ai/dsh-host-directory-picker'
  15. import WorkspaceRegistry from '@deepseek-ai/dsh-workspace'
  16. import type { HostFrame, WorkspaceId } from '@deepseek-ai/dsh-host-apiproxy/api'
  17. import type { RpcRequest, RpcResponse } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
  18. import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
  19. import { createApiProxy } from '@deepseek-ai/dsh-host-apiproxy'
  20. import { MemoryStorageBackend } from '../../../storage/storage-domain/tests/helpers/memory-backend.ts'
  21. let nextRpc = 1
  22. function request<P>(payload: P): RpcRequest<P> {
  23. return { rpcId: RpcId(`workspace-${String(nextRpc++)}`), payload }
  24. }
  25. function expectOk<T>(response: RpcResponse<T>): T {
  26. expect(response.result.ok).toBe(true)
  27. if (!response.result.ok) throw new Error('unreachable')
  28. return response.result.value
  29. }
  30. async function nextHostFrame(
  31. stream: AsyncIterator<RpcRequest<HostFrame>>,
  32. ): Promise<RpcRequest<HostFrame>> {
  33. const next = await stream.next()
  34. if (next.done === true) throw new Error('Host stream ended before the expected increment')
  35. return next.value
  36. }
  37. function stubAgent(session: Session): Agent {
  38. return {
  39. id: session.id,
  40. options: {},
  41. session,
  42. inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }),
  43. status: 'idle',
  44. ctx: new Context(),
  45. send: () => {},
  46. followup: () => {},
  47. steer: () => ({ outcome: Promise.resolve({ status: 'rejected' as const }) }),
  48. inject: () => {},
  49. cancel() {},
  50. runMaintenance: task => task(new AbortController().signal),
  51. whenIdle: () => Promise.resolve(),
  52. }
  53. }
  54. /** Compose the API over real Session, Agent, Storage, Domain, and Workspace services. */
  55. async function harness(
  56. workspaceRoot = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-apiproxy-workspace-'))),
  57. picker: DirectoryPickerCapability = { kind: 'native', pick: async () => null },
  58. extras: { openPath?: (path: string, signal: AbortSignal) => Promise<void> } = {},
  59. ) {
  60. const ctx = new Context()
  61. await ctx.plugin(SessionStore)
  62. await ctx.plugin(AgentRegistry)
  63. await ctx.plugin(UserInteractionService)
  64. await ctx.plugin(Storage)
  65. ctx.storage.backend.register('memory', new MemoryStorageBackend())
  66. const storageDomain = new DomainFacility(ctx, { backend: 'memory', routes: {} })
  67. ctx.storage.mount('domain', storageDomain)
  68. ctx.provide('storageDomain', storageDomain)
  69. ctx.provide('sessionPersistence', { list: () => Promise.resolve([]) } as never)
  70. await ctx.plugin(WorkspaceRegistry)
  71. const factory: AgentFactory = {
  72. async createAgent(_ownerCtx, options) {
  73. const session = ctx.sessions.create(
  74. options.sessionId,
  75. options.meta === undefined ? {} : { meta: options.meta },
  76. )
  77. const agent = stubAgent(session)
  78. const unregister = ctx.agents.register(agent)
  79. return {
  80. agent,
  81. dispose: () => {
  82. unregister()
  83. return Promise.resolve()
  84. },
  85. }
  86. },
  87. async resume() {
  88. throw new Error('test harness has no persisted sessions')
  89. },
  90. }
  91. ctx.agents.setFactory(factory)
  92. // Structural picker fake: the gateway only reads capability(); a stable
  93. // object per harness mirrors the seam's stability contract.
  94. ctx.provide('directoryPicker', { capability: () => picker } as never)
  95. const api = createApiProxy(ctx, {
  96. defaultTarget: () => ({ provider: 'test', model: 'test-model' }),
  97. cwd: workspaceRoot,
  98. workspaceRoot,
  99. ...extras.openPath === undefined ? {} : { openPath: extras.openPath },
  100. })
  101. return { api, ctx, storageDomain, workspaceRoot }
  102. }
  103. describe('host.pickDirectory', () => {
  104. it('returns a selected path or explicit cancellation from the native capability', async () => {
  105. const selected = await harness(undefined, { kind: 'native', pick: async () => '/tmp/project' })
  106. expect((await selected.api.host.pickDirectory(request({}), new AbortController().signal)).result)
  107. .toEqual({ ok: true, value: { path: '/tmp/project' } })
  108. const cancelled = await harness(undefined, { kind: 'native', pick: async () => null })
  109. expect((await cancelled.api.host.pickDirectory(request({}), new AbortController().signal)).result)
  110. .toEqual({ ok: true, value: { path: null } })
  111. })
  112. it('propagates abort into the native capability as a cancelled RPC error', async () => {
  113. const { api } = await harness(undefined, {
  114. kind: 'native',
  115. pick: signal => new Promise((_resolve, reject) => {
  116. signal.addEventListener('abort', () => { reject(new Error('aborted')) }, { once: true })
  117. }),
  118. })
  119. const abort = new AbortController()
  120. const pending = api.host.pickDirectory(request({}), abort.signal)
  121. abort.abort()
  122. expect((await pending).result).toMatchObject({ ok: false, error: { code: 'cancelled' } })
  123. })
  124. it('folds a non-abort native-chooser failure into an internal error', async () => {
  125. const { api } = await harness(undefined, { kind: 'native', pick: async () => { throw new Error('no chooser installed') } })
  126. const response = await api.host.pickDirectory(request({}), new AbortController().signal)
  127. expect(response.result).toMatchObject({ ok: false, error: { code: 'internal' } })
  128. })
  129. it('refuses the native RPC under a browse composition', async () => {
  130. const { api } = await harness(undefined, BROWSE_STUB)
  131. const response = await api.host.pickDirectory(request({}), new AbortController().signal)
  132. expect(response.result).toMatchObject({
  133. ok: false,
  134. error: { code: 'directory-picker-unavailable', details: { capability: 'browse' } },
  135. })
  136. })
  137. })
  138. /** Canned browse capability: one listing, one created path, typed failures on demand. */
  139. const BROWSE_STUB: DirectoryPickerCapability = {
  140. kind: 'browse',
  141. list: async (path) => {
  142. if (path === '/denied') throw new DirectoryPickerError('directory-unreadable', '/denied', 'cannot list /denied')
  143. const target = path ?? '/home/user'
  144. return {
  145. path: target,
  146. home: '/home/user',
  147. crumbs: [{ name: '/', path: '/', hidden: false }],
  148. entries: [{ name: 'projects', path: `${target}/projects`, hidden: false }],
  149. truncated: false,
  150. }
  151. },
  152. createDirectory: async (path, name) => {
  153. if (name === 'taken') throw new DirectoryPickerError('directory-exists', `${path}/${name}`, 'already exists')
  154. if (name === 'unwritable') throw new Error('disk detached')
  155. return `${path}/${name}`
  156. },
  157. }
  158. describe('host.listDirectory / host.createDirectory', () => {
  159. it('serves listings and creation through the browse capability, defaulting to home', async () => {
  160. const { api } = await harness(undefined, BROWSE_STUB)
  161. const home = await api.host.listDirectory(request({}), new AbortController().signal)
  162. expect(home.result).toMatchObject({ ok: true, value: { path: '/home/user', home: '/home/user' } })
  163. const listed = await api.host.listDirectory(request({ path: '/home/user/projects' }), new AbortController().signal)
  164. expect(listed.result).toMatchObject({ ok: true, value: { path: '/home/user/projects' } })
  165. const created = await api.host.createDirectory(request({ path: '/home/user', name: 'fresh' }))
  166. expect(created.result).toEqual({ ok: true, value: { path: '/home/user/fresh' } })
  167. })
  168. it('maps typed picker failures onto the wire error codes and folds unknown throws to internal', async () => {
  169. const { api } = await harness(undefined, BROWSE_STUB)
  170. expect((await api.host.listDirectory(request({ path: '/denied' }), new AbortController().signal)).result).toMatchObject({
  171. ok: false, error: { code: 'directory-unreadable', details: { path: '/denied' } },
  172. })
  173. expect((await api.host.createDirectory(request({ path: '/home/user', name: 'taken' }))).result).toMatchObject({
  174. ok: false, error: { code: 'directory-exists' },
  175. })
  176. expect((await api.host.createDirectory(request({ path: '/home/user', name: 'unwritable' }))).result).toMatchObject({
  177. ok: false, error: { code: 'internal' },
  178. })
  179. })
  180. it('reports an aborted listing as cancelled, like the other signal-following RPCs', async () => {
  181. const { api } = await harness(undefined, {
  182. kind: 'browse',
  183. list: (_path, signal) => new Promise((_resolve, reject) => {
  184. signal?.addEventListener('abort', () => { reject(new Error('scan aborted')) }, { once: true })
  185. }),
  186. createDirectory: async () => '/never',
  187. })
  188. const abort = new AbortController()
  189. const pending = api.host.listDirectory(request({}), abort.signal)
  190. abort.abort()
  191. expect((await pending).result).toMatchObject({ ok: false, error: { code: 'cancelled' } })
  192. })
  193. it('refuses the browse RPCs under a native composition', async () => {
  194. const { api } = await harness()
  195. expect((await api.host.listDirectory(request({}), new AbortController().signal)).result).toMatchObject({
  196. ok: false, error: { code: 'directory-picker-unavailable', details: { capability: 'native' } },
  197. })
  198. expect((await api.host.createDirectory(request({ path: '/x', name: 'y' }))).result).toMatchObject({
  199. ok: false, error: { code: 'directory-picker-unavailable', details: { capability: 'native' } },
  200. })
  201. })
  202. })
  203. describe('host.openPath', () => {
  204. it('opens through the injected native boundary', async () => {
  205. const opened: string[] = []
  206. const { api } = await harness(undefined, undefined, {
  207. openPath: async (path) => { opened.push(path) },
  208. })
  209. expect((await api.host.openPath(request({ path: '/tmp/a.txt' }), new AbortController().signal)).result)
  210. .toEqual({ ok: true, value: { opened: true } })
  211. expect(opened).toEqual(['/tmp/a.txt'])
  212. })
  213. it('propagates abort into the native boundary as a cancelled RPC error', async () => {
  214. const { api } = await harness(undefined, undefined, {
  215. openPath: (_path, signal) => new Promise((_resolve, reject) => {
  216. signal.addEventListener('abort', () => { reject(new Error('aborted')) }, { once: true })
  217. }),
  218. })
  219. const abort = new AbortController()
  220. const pending = api.host.openPath(request({ path: '/tmp/a.txt' }), abort.signal)
  221. abort.abort()
  222. expect((await pending).result).toMatchObject({ ok: false, error: { code: 'cancelled' } })
  223. })
  224. })
  225. describe('workspace.create', () => {
  226. it('serializes concurrent names and rejects the duplicate', async () => {
  227. const { api, workspaceRoot } = await harness()
  228. const responses = await Promise.all([
  229. api.workspace.create(request({ name: 'alpha' })),
  230. api.workspace.create(request({ name: 'alpha' })),
  231. ])
  232. const created = responses.find(response => response.result.ok)
  233. const duplicate = responses.find(response => !response.result.ok)
  234. expect(created).toBeDefined()
  235. expect(expectOk(created!)).toMatchObject({
  236. created: true,
  237. workspace: { path: join(workspaceRoot, 'alpha'), title: 'alpha' },
  238. })
  239. expect(duplicate?.result).toMatchObject({
  240. ok: false,
  241. error: { code: 'workspace-name-conflict', details: { name: 'alpha' } },
  242. })
  243. expect(existsSync(join(workspaceRoot, 'alpha'))).toBe(true)
  244. })
  245. it('adopts only existing directories and rejects unsafe names', async () => {
  246. const { api, workspaceRoot } = await harness()
  247. const existing = join(workspaceRoot, 'existing')
  248. mkdirSync(existing)
  249. const first = expectOk(await api.workspace.create(request({ path: existing })))
  250. const repeated = expectOk(await api.workspace.create(request({ path: existing })))
  251. expect(first).toMatchObject({ created: true, workspace: { path: existing, title: 'existing' } })
  252. expect(repeated).toMatchObject({ created: false, workspace: { workspaceId: first.workspace.workspaceId } })
  253. expectOk(await api.workspace.rename(request({
  254. workspaceId: first.workspace.workspaceId,
  255. title: 'renamed-existing',
  256. })))
  257. const reopened = expectOk(await api.workspace.create(request({ path: existing })))
  258. expect(reopened.workspace.title).toBe('renamed-existing')
  259. const missing = join(workspaceRoot, 'missing')
  260. const missingResult = await api.workspace.create(request({ path: missing }))
  261. expect(missingResult.result).toMatchObject({ ok: false, error: { code: 'workspace-invalid-path' } })
  262. expect(existsSync(missing)).toBe(false)
  263. for (const name of ['', '.', '..', 'a/b', 'a\\b']) {
  264. const invalid = await api.workspace.create(request({ name }))
  265. expect(invalid.result).toMatchObject({ ok: false, error: { code: 'workspace-invalid-path' } })
  266. }
  267. })
  268. it('adopts different paths that derive the same Workspace title', async () => {
  269. const { api, workspaceRoot } = await harness()
  270. const first = join(workspaceRoot, 'one', 'project')
  271. const second = join(workspaceRoot, 'two', 'project')
  272. mkdirSync(first, { recursive: true })
  273. mkdirSync(second, { recursive: true })
  274. const firstResult = expectOk(await api.workspace.create(request({ path: first })))
  275. const secondResult = expectOk(await api.workspace.create(request({ path: second })))
  276. expect(firstResult).toMatchObject({
  277. created: true,
  278. workspace: { path: first, title: 'project' },
  279. })
  280. expect(secondResult).toMatchObject({
  281. created: true,
  282. workspace: { path: second, title: 'project' },
  283. })
  284. expect(secondResult.workspace.workspaceId).not.toBe(firstResult.workspace.workspaceId)
  285. expect(expectOk(await api.workspace.list(request({}))).items.map(workspace => workspace.path))
  286. .toEqual([second, first])
  287. })
  288. })
  289. describe('session creation and Workspace membership', () => {
  290. it('attaches a preallocated idempotent session while cwd-only sessions stay ungrouped', async () => {
  291. const { api, ctx } = await harness()
  292. const workspace = expectOk(await api.workspace.create(request({ name: 'project' }))).workspace
  293. const sessionId = SessionId('session-workspace-preallocated')
  294. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId })))
  295. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId })))
  296. expect(expectOk(await api.workspace.list(request({}))).items[0]?.sessionIds).toEqual([sessionId])
  297. expect(ctx.agents.list().filter(agent => agent.id === sessionId)).toHaveLength(1)
  298. const ungrouped = SessionId('session-cwd-only')
  299. expectOk(await api.sessions.create(request({ cwd: workspace.path, sessionId: ungrouped })))
  300. expect(expectOk(await api.workspace.list(request({}))).items[0]?.sessionIds).toEqual([sessionId])
  301. expect(expectOk(await api.sessions.list(request({}))).items.map(item => item.sessionId)).toContain(ungrouped)
  302. const conflict = await api.sessions.create(request({ cwd: join(workspace.path, 'other'), sessionId }))
  303. expect(conflict.result).toMatchObject({
  304. ok: false,
  305. error: { code: 'session-conflict', details: { sessionId, existingCwd: workspace.path } },
  306. })
  307. const missing = await api.sessions.create(request({
  308. workspaceId: 'missing-workspace' as WorkspaceId,
  309. sessionId: SessionId('session-missing-workspace'),
  310. }))
  311. expect(missing.result).toMatchObject({ ok: false, error: { code: 'workspace-not-found' } })
  312. })
  313. it('retains a published session when attachment fails and repairs it on retry', async () => {
  314. const { api, ctx } = await harness()
  315. const created = expectOk(await api.workspace.create(request({ name: 'project' }))).workspace
  316. const workspace = ctx.workspace.list()[0]
  317. if (workspace === undefined) throw new Error('workspace missing from registry')
  318. vi.spyOn(workspace, 'attachSession').mockRejectedValueOnce(new Error('simulated write failure'))
  319. const sessionId = SessionId('session-attach-retry')
  320. const failed = await api.sessions.create(request({ workspaceId: created.workspaceId, sessionId }))
  321. expect(failed.result).toMatchObject({
  322. ok: false,
  323. error: { code: 'workspace-attach-failed', details: { sessionId, workspaceId: created.workspaceId } },
  324. })
  325. expect(ctx.agents.get(sessionId)).toBeDefined()
  326. expectOk(await api.sessions.create(request({ workspaceId: created.workspaceId, sessionId })))
  327. expect(expectOk(await api.workspace.list(request({}))).items[0]?.sessionIds).toEqual([sessionId])
  328. })
  329. })
  330. describe('Host Workspace increments', () => {
  331. it('projects subagent origin in attached summaries and creation increments', async () => {
  332. const { api, ctx } = await harness()
  333. const abort = new AbortController()
  334. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  335. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  336. const pending = nextHostFrame(stream)
  337. const childId = SessionId('session-subagent-child')
  338. ctx.sessions.create(childId, {
  339. meta: {
  340. cwd: '/tmp',
  341. parentSession: SessionId('session-parent'),
  342. origin: 'subagent',
  343. },
  344. })
  345. expect(await pending).toMatchObject({
  346. payload: {
  347. type: 'host/session-added',
  348. sessionId: childId,
  349. parentSessionId: 'session-parent',
  350. origin: 'subagent',
  351. },
  352. })
  353. expect(expectOk(await api.sessions.list(request({}))).items).toContainEqual(
  354. expect.objectContaining({ sessionId: childId, origin: 'subagent' }),
  355. )
  356. abort.abort()
  357. })
  358. it('streams committed Workspace and Session increments after empty baselines', async () => {
  359. const { api } = await harness()
  360. expect(expectOk(await api.workspace.list(request({}))).items).toEqual([])
  361. expect(expectOk(await api.sessions.list(request({}))).items).toEqual([])
  362. const abort = new AbortController()
  363. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  364. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  365. const workspaceIncrement = nextHostFrame(stream)
  366. const workspace = expectOk(await api.workspace.create(request({ name: 'project' }))).workspace
  367. expect(await workspaceIncrement).toMatchObject({
  368. payload: { type: 'host/workspace-changed', workspace: { workspaceId: workspace.workspaceId } },
  369. })
  370. const sessionId = SessionId('session-streamed-workspace')
  371. const pending = nextHostFrame(stream)
  372. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId })))
  373. const increments: HostFrame[] = []
  374. increments.push((await pending).payload)
  375. while (increments.length < 2) {
  376. const next = await stream.next()
  377. if (next.done === true) throw new Error('Host stream ended before both increments')
  378. increments.push(next.value.payload)
  379. }
  380. expect(increments.find(increment => increment.type === 'host/session-added')).toMatchObject({
  381. // A just-created session has no events: the frame constantly carries blank:true.
  382. type: 'host/session-added', sessionId, blank: true, cwd: workspace.path,
  383. })
  384. const workspaceChanged = increments.find(
  385. (increment): increment is Extract<HostFrame, { type: 'host/workspace-changed' }> =>
  386. increment.type === 'host/workspace-changed',
  387. )
  388. expect(workspaceChanged?.workspace.sessionIds).toEqual([sessionId])
  389. abort.abort()
  390. })
  391. it('does not publish a Workspace whose registry-order commit fails', async () => {
  392. const { api, storageDomain } = await harness()
  393. const domain = storageDomain.get('workspace')
  394. if (domain === undefined) throw new Error('workspace domain is not open')
  395. vi.spyOn(domain.global, 'set').mockRejectedValueOnce(new Error('simulated registry order failure'))
  396. const abort = new AbortController()
  397. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  398. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  399. const next = stream.next()
  400. const failed = await api.workspace.create(request({ name: 'ghost' }))
  401. expect(failed.result.ok).toBe(false)
  402. expect(expectOk(await api.workspace.list(request({}))).items).toEqual([])
  403. abort.abort()
  404. expect(await next).toMatchObject({ done: true })
  405. })
  406. it('deletes the registration, keeps its session and folder, and streams one removal', async () => {
  407. const { api, ctx } = await harness()
  408. const workspace = expectOk(await api.workspace.create(request({ name: 'delete-me' }))).workspace
  409. const sessionId = SessionId('session-kept-after-workspace-delete')
  410. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId })))
  411. const abort = new AbortController()
  412. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  413. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  414. const removed = nextHostFrame(stream)
  415. expectOk(await api.workspace.delete(request({ workspaceId: workspace.workspaceId })))
  416. expect(await removed).toMatchObject({
  417. payload: { type: 'host/workspace-removed', workspaceId: workspace.workspaceId },
  418. })
  419. expect(expectOk(await api.workspace.list(request({}))).items).toEqual([])
  420. expect(expectOk(await api.sessions.list(request({}))).items.map(item => item.sessionId)).toContain(sessionId)
  421. expect(ctx.agents.get(sessionId)).toBeDefined()
  422. expect(existsSync(workspace.path)).toBe(true)
  423. const missing = await api.workspace.delete(request({ workspaceId: workspace.workspaceId }))
  424. expect(missing.result).toMatchObject({
  425. ok: false,
  426. error: { code: 'workspace-not-found', details: { workspaceId: workspace.workspaceId } },
  427. })
  428. const reregistered = expectOk(await api.workspace.create(request({ path: workspace.path }))).workspace
  429. expect(reregistered.workspaceId).not.toBe(workspace.workspaceId)
  430. expect(reregistered.path).toBe(workspace.path)
  431. expect(reregistered.sessionIds).toEqual([])
  432. expect(expectOk(await api.sessions.list(request({}))).items.map(item => item.sessionId)).toContain(sessionId)
  433. abort.abort()
  434. })
  435. it('archives a session into the global set, keeps its accounting, and streams the set once', async () => {
  436. const { api } = await harness()
  437. const workspace = expectOk(await api.workspace.create(request({ name: 'archive-home' }))).workspace
  438. const sessionId = SessionId('session-to-archive')
  439. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId })))
  440. expect(expectOk(await api.workspace.list(request({}))).archivedSessionIds).toEqual([])
  441. const abort = new AbortController()
  442. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  443. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  444. const changed = nextHostFrame(stream)
  445. expect(expectOk(await api.workspace.archiveSession(request({ sessionId }))).archivedSessionIds)
  446. .toEqual([sessionId])
  447. expect(await changed).toMatchObject({
  448. payload: { type: 'host/archived-sessions-changed', archivedSessionIds: [sessionId] },
  449. })
  450. // Accounting and the session itself are untouched; list re-baselines the set.
  451. const listed = expectOk(await api.workspace.list(request({})))
  452. expect(listed.archivedSessionIds).toEqual([sessionId])
  453. expect(listed.items[0]?.sessionIds).toEqual([sessionId])
  454. expect(expectOk(await api.sessions.list(request({}))).items.map(item => item.sessionId)).toContain(sessionId)
  455. // The idempotent repeat emits no second frame: the next observed frame is
  456. // the workspace-changed of a later attach, not another archive snapshot.
  457. const after = nextHostFrame(stream)
  458. expect(expectOk(await api.workspace.archiveSession(request({ sessionId }))).archivedSessionIds)
  459. .toEqual([sessionId])
  460. const otherSession = SessionId('session-after-archive')
  461. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId: otherSession })))
  462. expect((await after).payload.type).not.toBe('host/archived-sessions-changed')
  463. const missing = await api.workspace.archiveSession(request({ sessionId: SessionId('session-ghost') }))
  464. expect(missing.result).toMatchObject({
  465. ok: false,
  466. error: { code: 'session-not-found', details: { sessionId: 'session-ghost' } },
  467. })
  468. abort.abort()
  469. })
  470. })