api-proxy-workspace.spec.ts 25 KB

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