api-proxy-workspace.spec.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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 '@deepseek-ai/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. root = realpathSync.native(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. defaultModelSelection: () => ({ provider: 'test', model: 'test-model' }),
  97. cwd: root,
  98. ...extras.openPath === undefined ? {} : { openPath: extras.openPath },
  99. })
  100. return { api, ctx, storageDomain, root }
  101. }
  102. /** Stage one directory under the harness root for path adoption. */
  103. function stageDir(root: string, name: string): string {
  104. const path = join(root, name)
  105. mkdirSync(path)
  106. return path
  107. }
  108. describe('host.pickDirectory', () => {
  109. it('returns a selected path or explicit cancellation from the native capability', async () => {
  110. const selected = await harness(undefined, { kind: 'native', pick: async () => '/tmp/project' })
  111. expect((await selected.api.host.pickDirectory(request({}), new AbortController().signal)).result)
  112. .toEqual({ ok: true, value: { path: '/tmp/project' } })
  113. const cancelled = await harness(undefined, { kind: 'native', pick: async () => null })
  114. expect((await cancelled.api.host.pickDirectory(request({}), new AbortController().signal)).result)
  115. .toEqual({ ok: true, value: { path: null } })
  116. })
  117. it('propagates abort into the native capability as a cancelled RPC error', async () => {
  118. const { api } = await harness(undefined, {
  119. kind: 'native',
  120. pick: signal => new Promise((_resolve, reject) => {
  121. signal.addEventListener('abort', () => { reject(new Error('aborted')) }, { once: true })
  122. }),
  123. })
  124. const abort = new AbortController()
  125. const pending = api.host.pickDirectory(request({}), abort.signal)
  126. abort.abort()
  127. expect((await pending).result).toMatchObject({ ok: false, error: { code: 'cancelled' } })
  128. })
  129. it('folds a non-abort native-chooser failure into an internal error', async () => {
  130. const { api } = await harness(undefined, { kind: 'native', pick: async () => { throw new Error('no chooser installed') } })
  131. const response = await api.host.pickDirectory(request({}), new AbortController().signal)
  132. expect(response.result).toMatchObject({ ok: false, error: { code: 'internal' } })
  133. })
  134. it('refuses the native RPC under a browse composition', async () => {
  135. const { api } = await harness(undefined, BROWSE_STUB)
  136. const response = await api.host.pickDirectory(request({}), new AbortController().signal)
  137. expect(response.result).toMatchObject({
  138. ok: false,
  139. error: { code: 'directory-picker-unavailable', details: { capability: 'browse' } },
  140. })
  141. })
  142. })
  143. /** Canned browse capability: one listing, one created path, typed failures on demand. */
  144. const BROWSE_STUB: DirectoryPickerCapability = {
  145. kind: 'browse',
  146. list: async (path) => {
  147. if (path === '/denied') throw new DirectoryPickerError('directory-unreadable', '/denied', 'cannot list /denied')
  148. const target = path ?? '/home/user'
  149. return {
  150. path: target,
  151. home: '/home/user',
  152. crumbs: [{ name: '/', path: '/', hidden: false }],
  153. entries: [{ name: 'projects', path: `${target}/projects`, hidden: false }],
  154. truncated: false,
  155. }
  156. },
  157. createDirectory: async (path, name) => {
  158. if (name === 'taken') throw new DirectoryPickerError('directory-exists', `${path}/${name}`, 'already exists')
  159. if (name === 'unwritable') throw new Error('disk detached')
  160. return `${path}/${name}`
  161. },
  162. }
  163. describe('host.listDirectory / host.createDirectory', () => {
  164. it('serves listings and creation through the browse capability, defaulting to home', async () => {
  165. const { api } = await harness(undefined, BROWSE_STUB)
  166. const home = await api.host.listDirectory(request({}), new AbortController().signal)
  167. expect(home.result).toMatchObject({ ok: true, value: { path: '/home/user', home: '/home/user' } })
  168. const listed = await api.host.listDirectory(request({ path: '/home/user/projects' }), new AbortController().signal)
  169. expect(listed.result).toMatchObject({ ok: true, value: { path: '/home/user/projects' } })
  170. const created = await api.host.createDirectory(request({ path: '/home/user', name: 'fresh' }))
  171. expect(created.result).toEqual({ ok: true, value: { path: '/home/user/fresh' } })
  172. })
  173. it('maps typed picker failures onto the wire error codes and folds unknown throws to internal', async () => {
  174. const { api } = await harness(undefined, BROWSE_STUB)
  175. expect((await api.host.listDirectory(request({ path: '/denied' }), new AbortController().signal)).result).toMatchObject({
  176. ok: false, error: { code: 'directory-unreadable', details: { path: '/denied' } },
  177. })
  178. expect((await api.host.createDirectory(request({ path: '/home/user', name: 'taken' }))).result).toMatchObject({
  179. ok: false, error: { code: 'directory-exists' },
  180. })
  181. expect((await api.host.createDirectory(request({ path: '/home/user', name: 'unwritable' }))).result).toMatchObject({
  182. ok: false, error: { code: 'internal' },
  183. })
  184. })
  185. it('reports an aborted listing as cancelled, like the other signal-following RPCs', async () => {
  186. const { api } = await harness(undefined, {
  187. kind: 'browse',
  188. list: (_path, signal) => new Promise((_resolve, reject) => {
  189. signal?.addEventListener('abort', () => { reject(new Error('scan aborted')) }, { once: true })
  190. }),
  191. createDirectory: async () => '/never',
  192. })
  193. const abort = new AbortController()
  194. const pending = api.host.listDirectory(request({}), abort.signal)
  195. abort.abort()
  196. expect((await pending).result).toMatchObject({ ok: false, error: { code: 'cancelled' } })
  197. })
  198. it('refuses the browse RPCs under a native composition', async () => {
  199. const { api } = await harness()
  200. expect((await api.host.listDirectory(request({}), new AbortController().signal)).result).toMatchObject({
  201. ok: false, error: { code: 'directory-picker-unavailable', details: { capability: 'native' } },
  202. })
  203. expect((await api.host.createDirectory(request({ path: '/x', name: 'y' }))).result).toMatchObject({
  204. ok: false, error: { code: 'directory-picker-unavailable', details: { capability: 'native' } },
  205. })
  206. })
  207. })
  208. describe('host.openPath', () => {
  209. it('opens through the injected native boundary', async () => {
  210. const opened: string[] = []
  211. const { api } = await harness(undefined, undefined, {
  212. openPath: async (path) => { opened.push(path) },
  213. })
  214. expect((await api.host.openPath(request({ path: '/tmp/a.txt' }), new AbortController().signal)).result)
  215. .toEqual({ ok: true, value: { opened: true } })
  216. expect(opened).toEqual(['/tmp/a.txt'])
  217. })
  218. it('propagates abort into the native boundary as a cancelled RPC error', async () => {
  219. const { api } = await harness(undefined, undefined, {
  220. openPath: (_path, signal) => new Promise((_resolve, reject) => {
  221. signal.addEventListener('abort', () => { reject(new Error('aborted')) }, { once: true })
  222. }),
  223. })
  224. const abort = new AbortController()
  225. const pending = api.host.openPath(request({ path: '/tmp/a.txt' }), abort.signal)
  226. abort.abort()
  227. expect((await pending).result).toMatchObject({ ok: false, error: { code: 'cancelled' } })
  228. })
  229. })
  230. describe('workspace.create', () => {
  231. it('serializes concurrent creates of one path into a single registration', async () => {
  232. const { api, root } = await harness()
  233. const target = stageDir(root, 'alpha')
  234. const responses = await Promise.all([
  235. api.workspace.create(request({ path: target })),
  236. api.workspace.create(request({ path: target })),
  237. ])
  238. const values = responses.map(response => expectOk(response))
  239. const created = values.find(value => value.created)
  240. const resolved = values.find(value => !value.created)
  241. expect(created).toMatchObject({ workspace: { path: target, title: 'alpha' } })
  242. expect(resolved?.workspace.workspaceId).toBe(created?.workspace.workspaceId)
  243. expect(expectOk(await api.workspace.list(request({}))).items).toHaveLength(1)
  244. })
  245. it('adopts only existing directories', async () => {
  246. const { api, root } = await harness()
  247. const existing = stageDir(root, 'existing')
  248. const first = expectOk(await api.workspace.create(request({ path: existing })))
  249. const repeated = expectOk(await api.workspace.create(request({ path: existing })))
  250. expect(first).toMatchObject({ created: true, workspace: { path: existing, title: 'existing' } })
  251. expect(repeated).toMatchObject({ created: false, workspace: { workspaceId: first.workspace.workspaceId } })
  252. expectOk(await api.workspace.rename(request({
  253. workspaceId: first.workspace.workspaceId,
  254. title: 'renamed-existing',
  255. })))
  256. const reopened = expectOk(await api.workspace.create(request({ path: existing })))
  257. expect(reopened.workspace.title).toBe('renamed-existing')
  258. const missing = join(root, 'missing')
  259. const missingResult = await api.workspace.create(request({ path: missing }))
  260. expect(missingResult.result).toMatchObject({ ok: false, error: { code: 'workspace-invalid-path' } })
  261. expect(existsSync(missing)).toBe(false)
  262. })
  263. it('adopts different paths that derive the same Workspace title', async () => {
  264. const { api, root } = await harness()
  265. const first = join(root, 'one', 'project')
  266. const second = join(root, 'two', 'project')
  267. mkdirSync(first, { recursive: true })
  268. mkdirSync(second, { recursive: true })
  269. const firstResult = expectOk(await api.workspace.create(request({ path: first })))
  270. const secondResult = expectOk(await api.workspace.create(request({ path: second })))
  271. expect(firstResult).toMatchObject({
  272. created: true,
  273. workspace: { path: first, title: 'project' },
  274. })
  275. expect(secondResult).toMatchObject({
  276. created: true,
  277. workspace: { path: second, title: 'project' },
  278. })
  279. expect(secondResult.workspace.workspaceId).not.toBe(firstResult.workspace.workspaceId)
  280. expect(expectOk(await api.workspace.list(request({}))).items.map(workspace => workspace.path))
  281. .toEqual([second, first])
  282. })
  283. })
  284. describe('session creation and Workspace membership', () => {
  285. it('attaches a preallocated idempotent session while cwd-only sessions stay ungrouped', async () => {
  286. const { api, ctx, root } = await harness()
  287. const workspace = expectOk(await api.workspace.create(request({ path: stageDir(root, 'project') }))).workspace
  288. const sessionId = SessionId('session-workspace-preallocated')
  289. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId })))
  290. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId })))
  291. expect(expectOk(await api.workspace.list(request({}))).items[0]?.sessionIds).toEqual([sessionId])
  292. expect(ctx.agents.list().filter(agent => agent.id === sessionId)).toHaveLength(1)
  293. const ungrouped = SessionId('session-cwd-only')
  294. expectOk(await api.sessions.create(request({ cwd: workspace.path, sessionId: ungrouped })))
  295. expect(expectOk(await api.workspace.list(request({}))).items[0]?.sessionIds).toEqual([sessionId])
  296. expect(expectOk(await api.sessions.list(request({}))).items.map(item => item.sessionId)).toContain(ungrouped)
  297. const conflict = await api.sessions.create(request({ cwd: join(workspace.path, 'other'), sessionId }))
  298. expect(conflict.result).toMatchObject({
  299. ok: false,
  300. error: { code: 'session-conflict', details: { sessionId, existingCwd: workspace.path } },
  301. })
  302. const missing = await api.sessions.create(request({
  303. workspaceId: 'missing-workspace' as WorkspaceId,
  304. sessionId: SessionId('session-missing-workspace'),
  305. }))
  306. expect(missing.result).toMatchObject({ ok: false, error: { code: 'workspace-not-found' } })
  307. })
  308. it('retains a published session when attachment fails and repairs it on retry', async () => {
  309. const { api, ctx, root } = await harness()
  310. const created = expectOk(await api.workspace.create(request({ path: stageDir(root, 'project') }))).workspace
  311. const workspace = ctx.workspace.list()[0]
  312. if (workspace === undefined) throw new Error('workspace missing from registry')
  313. vi.spyOn(workspace, 'attachSession').mockRejectedValueOnce(new Error('simulated write failure'))
  314. const sessionId = SessionId('session-attach-retry')
  315. const failed = await api.sessions.create(request({ workspaceId: created.workspaceId, sessionId }))
  316. expect(failed.result).toMatchObject({
  317. ok: false,
  318. error: { code: 'workspace-attach-failed', details: { sessionId, workspaceId: created.workspaceId } },
  319. })
  320. expect(ctx.agents.get(sessionId)).toBeDefined()
  321. expectOk(await api.sessions.create(request({ workspaceId: created.workspaceId, sessionId })))
  322. expect(expectOk(await api.workspace.list(request({}))).items[0]?.sessionIds).toEqual([sessionId])
  323. })
  324. })
  325. describe('Host Workspace increments', () => {
  326. it('projects subagent origin in attached summaries and creation increments', async () => {
  327. const { api, ctx } = await harness()
  328. const abort = new AbortController()
  329. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  330. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  331. const pending = nextHostFrame(stream)
  332. const childId = SessionId('session-subagent-child')
  333. ctx.sessions.create(childId, {
  334. meta: {
  335. cwd: '/tmp',
  336. parentSession: SessionId('session-parent'),
  337. origin: 'subagent',
  338. },
  339. })
  340. expect(await pending).toMatchObject({
  341. payload: {
  342. type: 'host/session-added',
  343. sessionId: childId,
  344. parentSessionId: 'session-parent',
  345. origin: 'subagent',
  346. },
  347. })
  348. expect(expectOk(await api.sessions.list(request({}))).items).toContainEqual(
  349. expect.objectContaining({ sessionId: childId, origin: 'subagent' }),
  350. )
  351. abort.abort()
  352. })
  353. it('streams committed Workspace and Session increments after empty baselines', async () => {
  354. const { api, root } = await harness()
  355. expect(expectOk(await api.workspace.list(request({}))).items).toEqual([])
  356. expect(expectOk(await api.sessions.list(request({}))).items).toEqual([])
  357. const abort = new AbortController()
  358. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  359. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  360. const workspaceIncrement = nextHostFrame(stream)
  361. const workspace = expectOk(await api.workspace.create(request({ path: stageDir(root, 'project') }))).workspace
  362. expect(await workspaceIncrement).toMatchObject({
  363. payload: { type: 'host/workspace-changed', workspace: { workspaceId: workspace.workspaceId } },
  364. })
  365. const sessionId = SessionId('session-streamed-workspace')
  366. const pending = nextHostFrame(stream)
  367. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId })))
  368. const increments: HostFrame[] = []
  369. increments.push((await pending).payload)
  370. while (increments.length < 2) {
  371. const next = await stream.next()
  372. if (next.done === true) throw new Error('Host stream ended before both increments')
  373. increments.push(next.value.payload)
  374. }
  375. expect(increments.find(increment => increment.type === 'host/session-added')).toMatchObject({
  376. // A just-created session has no events: the frame constantly carries blank:true.
  377. type: 'host/session-added', sessionId, blank: true, cwd: workspace.path,
  378. })
  379. const workspaceChanged = increments.find(
  380. (increment): increment is Extract<HostFrame, { type: 'host/workspace-changed' }> =>
  381. increment.type === 'host/workspace-changed',
  382. )
  383. expect(workspaceChanged?.workspace.sessionIds).toEqual([sessionId])
  384. abort.abort()
  385. })
  386. it('does not publish a Workspace whose registry-order commit fails', async () => {
  387. const { api, storageDomain, root } = await harness()
  388. const domain = storageDomain.get('workspace')
  389. if (domain === undefined) throw new Error('workspace domain is not open')
  390. vi.spyOn(domain.global, 'set').mockRejectedValueOnce(new Error('simulated registry order failure'))
  391. const abort = new AbortController()
  392. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  393. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  394. const next = stream.next()
  395. const failed = await api.workspace.create(request({ path: stageDir(root, 'ghost') }))
  396. expect(failed.result.ok).toBe(false)
  397. expect(expectOk(await api.workspace.list(request({}))).items).toEqual([])
  398. abort.abort()
  399. expect(await next).toMatchObject({ done: true })
  400. })
  401. it('deletes the registration, keeps its session and folder, and streams one removal', async () => {
  402. const { api, ctx, root } = await harness()
  403. const workspace = expectOk(await api.workspace.create(request({ path: stageDir(root, 'delete-me') }))).workspace
  404. const sessionId = SessionId('session-kept-after-workspace-delete')
  405. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId })))
  406. const abort = new AbortController()
  407. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  408. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  409. const removed = nextHostFrame(stream)
  410. expectOk(await api.workspace.delete(request({ workspaceId: workspace.workspaceId })))
  411. expect(await removed).toMatchObject({
  412. payload: { type: 'host/workspace-removed', workspaceId: workspace.workspaceId },
  413. })
  414. expect(expectOk(await api.workspace.list(request({}))).items).toEqual([])
  415. expect(expectOk(await api.sessions.list(request({}))).items.map(item => item.sessionId)).toContain(sessionId)
  416. expect(ctx.agents.get(sessionId)).toBeDefined()
  417. expect(existsSync(workspace.path)).toBe(true)
  418. const missing = await api.workspace.delete(request({ workspaceId: workspace.workspaceId }))
  419. expect(missing.result).toMatchObject({
  420. ok: false,
  421. error: { code: 'workspace-not-found', details: { workspaceId: workspace.workspaceId } },
  422. })
  423. const reregistered = expectOk(await api.workspace.create(request({ path: workspace.path }))).workspace
  424. expect(reregistered.workspaceId).not.toBe(workspace.workspaceId)
  425. expect(reregistered.path).toBe(workspace.path)
  426. expect(reregistered.sessionIds).toEqual([])
  427. expect(expectOk(await api.sessions.list(request({}))).items.map(item => item.sessionId)).toContain(sessionId)
  428. abort.abort()
  429. })
  430. it('archives a session into the global set, keeps its accounting, and streams the set once', async () => {
  431. const { api, root } = await harness()
  432. const workspace = expectOk(await api.workspace.create(request({ path: stageDir(root, 'archive-home') }))).workspace
  433. const sessionId = SessionId('session-to-archive')
  434. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId })))
  435. expect(expectOk(await api.workspace.list(request({}))).archivedSessionIds).toEqual([])
  436. const abort = new AbortController()
  437. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  438. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  439. const changed = nextHostFrame(stream)
  440. expect(expectOk(await api.workspace.archiveSession(request({ sessionId }))).archivedSessionIds)
  441. .toEqual([sessionId])
  442. expect(await changed).toMatchObject({
  443. payload: { type: 'host/archived-sessions-changed', archivedSessionIds: [sessionId] },
  444. })
  445. // Accounting and the session itself are untouched; list re-baselines the set.
  446. const listed = expectOk(await api.workspace.list(request({})))
  447. expect(listed.archivedSessionIds).toEqual([sessionId])
  448. expect(listed.items[0]?.sessionIds).toEqual([sessionId])
  449. expect(expectOk(await api.sessions.list(request({}))).items.map(item => item.sessionId)).toContain(sessionId)
  450. // The idempotent repeat emits no second frame: the next observed frame is
  451. // the workspace-changed of a later attach, not another archive snapshot.
  452. const after = nextHostFrame(stream)
  453. expect(expectOk(await api.workspace.archiveSession(request({ sessionId }))).archivedSessionIds)
  454. .toEqual([sessionId])
  455. const otherSession = SessionId('session-after-archive')
  456. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId: otherSession })))
  457. expect((await after).payload.type).not.toBe('host/archived-sessions-changed')
  458. const missing = await api.workspace.archiveSession(request({ sessionId: SessionId('session-ghost') }))
  459. expect(missing.result).toMatchObject({
  460. ok: false,
  461. error: { code: 'session-not-found', details: { sessionId: 'session-ghost' } },
  462. })
  463. abort.abort()
  464. })
  465. })