api-proxy-workspace.spec.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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('workspace.insertBefore', () => {
  285. it('commits the complete order, streams one order frame, and maps unknown ids', async () => {
  286. const { api, ctx, root } = await harness()
  287. const first = expectOk(await api.workspace.create(request({ path: stageDir(root, 'first') }))).workspace
  288. const second = expectOk(await api.workspace.create(request({ path: stageDir(root, 'second') }))).workspace
  289. const third = expectOk(await api.workspace.create(request({ path: stageDir(root, 'third') }))).workspace
  290. const abort = new AbortController()
  291. const listWorkspaces = vi.spyOn(ctx.workspace, 'list')
  292. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  293. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  294. expect(listWorkspaces).toHaveBeenCalledTimes(1)
  295. const changed = nextHostFrame(stream)
  296. const reordered = expectOk(await api.workspace.insertBefore(request({
  297. workspaceId: first.workspaceId,
  298. beforeWorkspaceId: second.workspaceId,
  299. })))
  300. expect(reordered.workspaceIds).toEqual([third.workspaceId, first.workspaceId, second.workspaceId])
  301. expect(await changed).toMatchObject({
  302. payload: {
  303. type: 'host/workspace-order-changed',
  304. workspaceIds: [third.workspaceId, first.workspaceId, second.workspaceId],
  305. },
  306. })
  307. expect(expectOk(await api.workspace.list(request({}))).items.map(item => item.workspaceId))
  308. .toEqual(reordered.workspaceIds)
  309. const missingSource = await api.workspace.insertBefore(request({
  310. workspaceId: 'missing' as WorkspaceId,
  311. }))
  312. expect(missingSource.result).toMatchObject({
  313. ok: false, error: { code: 'workspace-not-found', details: { workspaceId: 'missing' } },
  314. })
  315. const missingAnchor = await api.workspace.insertBefore(request({
  316. workspaceId: first.workspaceId,
  317. beforeWorkspaceId: 'missing-anchor' as WorkspaceId,
  318. }))
  319. expect(missingAnchor.result).toMatchObject({
  320. ok: false, error: { code: 'workspace-not-found', details: { workspaceId: 'missing-anchor' } },
  321. })
  322. abort.abort()
  323. })
  324. })
  325. describe('session creation and Workspace membership', () => {
  326. it('attaches a preallocated idempotent session while cwd-only sessions stay ungrouped', async () => {
  327. const { api, ctx, root } = await harness()
  328. const workspace = expectOk(await api.workspace.create(request({ path: stageDir(root, 'project') }))).workspace
  329. const sessionId = SessionId('session-workspace-preallocated')
  330. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId })))
  331. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId })))
  332. expect(expectOk(await api.workspace.list(request({}))).items[0]?.sessionIds).toEqual([sessionId])
  333. expect(ctx.agents.list().filter(agent => agent.id === sessionId)).toHaveLength(1)
  334. const ungrouped = SessionId('session-cwd-only')
  335. expectOk(await api.sessions.create(request({ cwd: workspace.path, sessionId: ungrouped })))
  336. expect(expectOk(await api.workspace.list(request({}))).items[0]?.sessionIds).toEqual([sessionId])
  337. expect(expectOk(await api.sessions.list(request({}))).items.map(item => item.sessionId)).toContain(ungrouped)
  338. const conflict = await api.sessions.create(request({ cwd: join(workspace.path, 'other'), sessionId }))
  339. expect(conflict.result).toMatchObject({
  340. ok: false,
  341. error: { code: 'session-conflict', details: { sessionId, existingCwd: workspace.path } },
  342. })
  343. const missing = await api.sessions.create(request({
  344. workspaceId: 'missing-workspace' as WorkspaceId,
  345. sessionId: SessionId('session-missing-workspace'),
  346. }))
  347. expect(missing.result).toMatchObject({ ok: false, error: { code: 'workspace-not-found' } })
  348. })
  349. it('retains a published session when attachment fails and repairs it on retry', async () => {
  350. const { api, ctx, root } = await harness()
  351. const created = expectOk(await api.workspace.create(request({ path: stageDir(root, 'project') }))).workspace
  352. const workspace = ctx.workspace.list()[0]
  353. if (workspace === undefined) throw new Error('workspace missing from registry')
  354. vi.spyOn(workspace, 'attachSession').mockRejectedValueOnce(new Error('simulated write failure'))
  355. const sessionId = SessionId('session-attach-retry')
  356. const failed = await api.sessions.create(request({ workspaceId: created.workspaceId, sessionId }))
  357. expect(failed.result).toMatchObject({
  358. ok: false,
  359. error: { code: 'workspace-attach-failed', details: { sessionId, workspaceId: created.workspaceId } },
  360. })
  361. expect(ctx.agents.get(sessionId)).toBeDefined()
  362. expectOk(await api.sessions.create(request({ workspaceId: created.workspaceId, sessionId })))
  363. expect(expectOk(await api.workspace.list(request({}))).items[0]?.sessionIds).toEqual([sessionId])
  364. })
  365. })
  366. describe('Host Workspace increments', () => {
  367. it('projects subagent origin in attached summaries and creation increments', async () => {
  368. const { api, ctx } = await harness()
  369. const abort = new AbortController()
  370. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  371. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  372. const pending = nextHostFrame(stream)
  373. const childId = SessionId('session-subagent-child')
  374. ctx.sessions.create(childId, {
  375. meta: {
  376. cwd: '/tmp',
  377. parentSession: SessionId('session-parent'),
  378. origin: 'subagent',
  379. },
  380. })
  381. expect(await pending).toMatchObject({
  382. payload: {
  383. type: 'host/session-added',
  384. sessionId: childId,
  385. parentSessionId: 'session-parent',
  386. origin: 'subagent',
  387. },
  388. })
  389. expect(expectOk(await api.sessions.list(request({}))).items).toContainEqual(
  390. expect.objectContaining({ sessionId: childId, origin: 'subagent' }),
  391. )
  392. abort.abort()
  393. })
  394. it('streams committed Workspace and Session increments after empty baselines', async () => {
  395. const { api, root } = await harness()
  396. expect(expectOk(await api.workspace.list(request({}))).items).toEqual([])
  397. expect(expectOk(await api.sessions.list(request({}))).items).toEqual([])
  398. const abort = new AbortController()
  399. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  400. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  401. const workspaceIncrement = nextHostFrame(stream)
  402. const workspace = expectOk(await api.workspace.create(request({ path: stageDir(root, 'project') }))).workspace
  403. expect(await workspaceIncrement).toMatchObject({
  404. payload: { type: 'host/workspace-changed', workspace: { workspaceId: workspace.workspaceId } },
  405. })
  406. const sessionId = SessionId('session-streamed-workspace')
  407. const pending = nextHostFrame(stream)
  408. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId })))
  409. const increments: HostFrame[] = []
  410. increments.push((await pending).payload)
  411. while (increments.length < 2) {
  412. const next = await stream.next()
  413. if (next.done === true) throw new Error('Host stream ended before both increments')
  414. increments.push(next.value.payload)
  415. }
  416. expect(increments.find(increment => increment.type === 'host/session-added')).toMatchObject({
  417. // A just-created session has no events: the frame constantly carries blank:true.
  418. type: 'host/session-added', sessionId, blank: true, cwd: workspace.path,
  419. })
  420. const workspaceChanged = increments.find(
  421. (increment): increment is Extract<HostFrame, { type: 'host/workspace-changed' }> =>
  422. increment.type === 'host/workspace-changed',
  423. )
  424. expect(workspaceChanged?.workspace.sessionIds).toEqual([sessionId])
  425. abort.abort()
  426. })
  427. it('does not publish a Workspace whose registry-order commit fails', async () => {
  428. const { api, storageDomain, root } = await harness()
  429. const domain = storageDomain.get('workspace')
  430. if (domain === undefined) throw new Error('workspace domain is not open')
  431. vi.spyOn(domain.global, 'set').mockRejectedValueOnce(new Error('simulated registry order failure'))
  432. const abort = new AbortController()
  433. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  434. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  435. const next = stream.next()
  436. const failed = await api.workspace.create(request({ path: stageDir(root, 'ghost') }))
  437. expect(failed.result.ok).toBe(false)
  438. expect(expectOk(await api.workspace.list(request({}))).items).toEqual([])
  439. abort.abort()
  440. expect(await next).toMatchObject({ done: true })
  441. })
  442. it('deletes the registration, keeps its session and folder, and streams one removal', async () => {
  443. const { api, ctx, root } = await harness()
  444. const workspace = expectOk(await api.workspace.create(request({ path: stageDir(root, 'delete-me') }))).workspace
  445. const sessionId = SessionId('session-kept-after-workspace-delete')
  446. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId })))
  447. const abort = new AbortController()
  448. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  449. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  450. const removed = nextHostFrame(stream)
  451. expectOk(await api.workspace.delete(request({ workspaceId: workspace.workspaceId })))
  452. expect(await removed).toMatchObject({
  453. payload: { type: 'host/workspace-removed', workspaceId: workspace.workspaceId },
  454. })
  455. expect(expectOk(await api.workspace.list(request({}))).items).toEqual([])
  456. expect(expectOk(await api.sessions.list(request({}))).items.map(item => item.sessionId)).toContain(sessionId)
  457. expect(ctx.agents.get(sessionId)).toBeDefined()
  458. expect(existsSync(workspace.path)).toBe(true)
  459. const missing = await api.workspace.delete(request({ workspaceId: workspace.workspaceId }))
  460. expect(missing.result).toMatchObject({
  461. ok: false,
  462. error: { code: 'workspace-not-found', details: { workspaceId: workspace.workspaceId } },
  463. })
  464. const reregistered = expectOk(await api.workspace.create(request({ path: workspace.path }))).workspace
  465. expect(reregistered.workspaceId).not.toBe(workspace.workspaceId)
  466. expect(reregistered.path).toBe(workspace.path)
  467. expect(reregistered.sessionIds).toEqual([])
  468. expect(expectOk(await api.sessions.list(request({}))).items.map(item => item.sessionId)).toContain(sessionId)
  469. abort.abort()
  470. })
  471. it('archives a session into the global set, keeps its accounting, and streams the set once', async () => {
  472. const { api, root } = await harness()
  473. const workspace = expectOk(await api.workspace.create(request({ path: stageDir(root, 'archive-home') }))).workspace
  474. const sessionId = SessionId('session-to-archive')
  475. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId })))
  476. expect(expectOk(await api.workspace.list(request({}))).archivedSessionIds).toEqual([])
  477. const abort = new AbortController()
  478. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  479. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  480. const changed = nextHostFrame(stream)
  481. expect(expectOk(await api.workspace.archiveSession(request({ sessionId }))).archivedSessionIds)
  482. .toEqual([sessionId])
  483. expect(await changed).toMatchObject({
  484. payload: { type: 'host/archived-sessions-changed', archivedSessionIds: [sessionId] },
  485. })
  486. // Accounting and the session itself are untouched; list re-baselines the set.
  487. const listed = expectOk(await api.workspace.list(request({})))
  488. expect(listed.archivedSessionIds).toEqual([sessionId])
  489. expect(listed.items[0]?.sessionIds).toEqual([sessionId])
  490. expect(expectOk(await api.sessions.list(request({}))).items.map(item => item.sessionId)).toContain(sessionId)
  491. // The idempotent repeat emits no second frame: the next observed frame is
  492. // the workspace-changed of a later attach, not another archive snapshot.
  493. const after = nextHostFrame(stream)
  494. expect(expectOk(await api.workspace.archiveSession(request({ sessionId }))).archivedSessionIds)
  495. .toEqual([sessionId])
  496. const otherSession = SessionId('session-after-archive')
  497. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId: otherSession })))
  498. expect((await after).payload.type).not.toBe('host/archived-sessions-changed')
  499. const missing = await api.workspace.archiveSession(request({ sessionId: SessionId('session-ghost') }))
  500. expect(missing.result).toMatchObject({
  501. ok: false,
  502. error: { code: 'session-not-found', details: { sessionId: 'session-ghost' } },
  503. })
  504. abort.abort()
  505. })
  506. })