api-proxy-workspace.spec.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. import { existsSync, mkdirSync, mkdtempSync, realpathSync } from 'node:fs'
  2. import { homedir, 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 UserQuestionService from '@deepseek-ai/dsh-user-questions'
  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: job => job(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(UserQuestionService)
  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. expect(expectOk(await visible.api.host.describe(request({}))).home).toBe(homedir())
  219. })
  220. it('opens through the injected native boundary', async () => {
  221. const opened: string[] = []
  222. const { api } = await harness(undefined, undefined, {
  223. openPath: async (path) => { opened.push(path) },
  224. })
  225. expect((await api.host.openPath(request({ path: '/tmp/a.txt' }), new AbortController().signal)).result)
  226. .toEqual({ ok: true, value: { opened: true } })
  227. expect(opened).toEqual(['/tmp/a.txt'])
  228. })
  229. it('propagates abort into the native boundary as a cancelled RPC error', async () => {
  230. const { api } = await harness(undefined, undefined, {
  231. openPath: (_path, signal) => new Promise((_resolve, reject) => {
  232. signal.addEventListener('abort', () => { reject(new Error('aborted')) }, { once: true })
  233. }),
  234. })
  235. const abort = new AbortController()
  236. const pending = api.host.openPath(request({ path: '/tmp/a.txt' }), abort.signal)
  237. abort.abort()
  238. expect((await pending).result).toMatchObject({ ok: false, error: { code: 'cancelled' } })
  239. })
  240. })
  241. describe('workspace.create', () => {
  242. it('serializes concurrent creates of one path into a single registration', async () => {
  243. const { api, root } = await harness()
  244. const target = stageDir(root, 'alpha')
  245. const responses = await Promise.all([
  246. api.workspace.create(request({ path: target })),
  247. api.workspace.create(request({ path: target })),
  248. ])
  249. const values = responses.map(response => expectOk(response))
  250. const created = values.find(value => value.created)
  251. const resolved = values.find(value => !value.created)
  252. expect(created).toMatchObject({ workspace: { path: target, title: 'alpha' } })
  253. expect(resolved?.workspace.workspaceId).toBe(created?.workspace.workspaceId)
  254. expect(expectOk(await api.workspace.list(request({}))).items).toHaveLength(1)
  255. })
  256. it('adopts only existing directories', async () => {
  257. const { api, root } = await harness()
  258. const existing = stageDir(root, 'existing')
  259. const first = expectOk(await api.workspace.create(request({ path: existing })))
  260. const repeated = expectOk(await api.workspace.create(request({ path: existing })))
  261. expect(first).toMatchObject({ created: true, workspace: { path: existing, title: 'existing' } })
  262. expect(repeated).toMatchObject({ created: false, workspace: { workspaceId: first.workspace.workspaceId } })
  263. expectOk(await api.workspace.rename(request({
  264. workspaceId: first.workspace.workspaceId,
  265. title: 'renamed-existing',
  266. })))
  267. const reopened = expectOk(await api.workspace.create(request({ path: existing })))
  268. expect(reopened.workspace.title).toBe('renamed-existing')
  269. const missing = join(root, 'missing')
  270. const missingResult = await api.workspace.create(request({ path: missing }))
  271. expect(missingResult.result).toMatchObject({ ok: false, error: { code: 'workspace-invalid-path' } })
  272. expect(existsSync(missing)).toBe(false)
  273. })
  274. it('adopts different paths that derive the same Workspace title', async () => {
  275. const { api, root } = await harness()
  276. const first = join(root, 'one', 'project')
  277. const second = join(root, 'two', 'project')
  278. mkdirSync(first, { recursive: true })
  279. mkdirSync(second, { recursive: true })
  280. const firstResult = expectOk(await api.workspace.create(request({ path: first })))
  281. const secondResult = expectOk(await api.workspace.create(request({ path: second })))
  282. expect(firstResult).toMatchObject({
  283. created: true,
  284. workspace: { path: first, title: 'project' },
  285. })
  286. expect(secondResult).toMatchObject({
  287. created: true,
  288. workspace: { path: second, title: 'project' },
  289. })
  290. expect(secondResult.workspace.workspaceId).not.toBe(firstResult.workspace.workspaceId)
  291. expect(expectOk(await api.workspace.list(request({}))).items.map(workspace => workspace.path))
  292. .toEqual([second, first])
  293. })
  294. })
  295. describe('workspace.insertBefore', () => {
  296. it('commits the complete order, streams one order frame, and maps unknown ids', async () => {
  297. const { api, ctx, root } = await harness()
  298. const first = expectOk(await api.workspace.create(request({ path: stageDir(root, 'first') }))).workspace
  299. const second = expectOk(await api.workspace.create(request({ path: stageDir(root, 'second') }))).workspace
  300. const third = expectOk(await api.workspace.create(request({ path: stageDir(root, 'third') }))).workspace
  301. const abort = new AbortController()
  302. const listWorkspaces = vi.spyOn(ctx.workspaceRegistry, 'list')
  303. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  304. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  305. expect(listWorkspaces).toHaveBeenCalledTimes(1)
  306. const changed = nextHostFrame(stream)
  307. const reordered = expectOk(await api.workspace.insertBefore(request({
  308. workspaceId: first.workspaceId,
  309. beforeWorkspaceId: second.workspaceId,
  310. })))
  311. expect(reordered.workspaceIds).toEqual([third.workspaceId, first.workspaceId, second.workspaceId])
  312. expect(await changed).toMatchObject({
  313. payload: {
  314. type: 'host/workspace-order-changed',
  315. workspaceIds: [third.workspaceId, first.workspaceId, second.workspaceId],
  316. },
  317. })
  318. expect(expectOk(await api.workspace.list(request({}))).items.map(item => item.workspaceId))
  319. .toEqual(reordered.workspaceIds)
  320. const missingSource = await api.workspace.insertBefore(request({
  321. workspaceId: 'missing' as WorkspaceId,
  322. }))
  323. expect(missingSource.result).toMatchObject({
  324. ok: false, error: { code: 'workspace-not-found', details: { workspaceId: 'missing' } },
  325. })
  326. const missingAnchor = await api.workspace.insertBefore(request({
  327. workspaceId: first.workspaceId,
  328. beforeWorkspaceId: 'missing-anchor' as WorkspaceId,
  329. }))
  330. expect(missingAnchor.result).toMatchObject({
  331. ok: false, error: { code: 'workspace-not-found', details: { workspaceId: 'missing-anchor' } },
  332. })
  333. abort.abort()
  334. })
  335. })
  336. describe('session creation and Workspace membership', () => {
  337. it('attaches a preallocated idempotent session while cwd-only sessions stay ungrouped', async () => {
  338. const { api, ctx, root } = await harness()
  339. const workspace = expectOk(await api.workspace.create(request({ path: stageDir(root, 'project') }))).workspace
  340. const sessionId = SessionId('session-workspace-preallocated')
  341. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId })))
  342. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId })))
  343. expect(expectOk(await api.workspace.list(request({}))).items[0]?.sessionIds).toEqual([sessionId])
  344. expect(ctx.agents.list().filter(agent => agent.id === sessionId)).toHaveLength(1)
  345. const ungrouped = SessionId('session-cwd-only')
  346. expectOk(await api.sessions.create(request({ cwd: workspace.path, sessionId: ungrouped })))
  347. expect(expectOk(await api.workspace.list(request({}))).items[0]?.sessionIds).toEqual([sessionId])
  348. expect(expectOk(await api.sessions.list(request({}))).items.map(item => item.sessionId)).toContain(ungrouped)
  349. const conflict = await api.sessions.create(request({ cwd: join(workspace.path, 'other'), sessionId }))
  350. expect(conflict.result).toMatchObject({
  351. ok: false,
  352. error: { code: 'session-conflict', details: { sessionId, existingCwd: workspace.path } },
  353. })
  354. const missing = await api.sessions.create(request({
  355. workspaceId: 'missing-workspace' as WorkspaceId,
  356. sessionId: SessionId('session-missing-workspace'),
  357. }))
  358. expect(missing.result).toMatchObject({ ok: false, error: { code: 'workspace-not-found' } })
  359. })
  360. it('retains a published session when attachment fails and repairs it on retry', async () => {
  361. const { api, ctx, root } = await harness()
  362. const created = expectOk(await api.workspace.create(request({ path: stageDir(root, 'project') }))).workspace
  363. const workspace = ctx.workspaceRegistry.list()[0]
  364. if (workspace === undefined) throw new Error('workspace missing from registry')
  365. vi.spyOn(workspace, 'attachSession').mockRejectedValueOnce(new Error('simulated write failure'))
  366. const sessionId = SessionId('session-attach-retry')
  367. const failed = await api.sessions.create(request({ workspaceId: created.workspaceId, sessionId }))
  368. expect(failed.result).toMatchObject({
  369. ok: false,
  370. error: { code: 'workspace-attach-failed', details: { sessionId, workspaceId: created.workspaceId } },
  371. })
  372. expect(ctx.agents.get(sessionId)).toBeDefined()
  373. expectOk(await api.sessions.create(request({ workspaceId: created.workspaceId, sessionId })))
  374. expect(expectOk(await api.workspace.list(request({}))).items[0]?.sessionIds).toEqual([sessionId])
  375. })
  376. })
  377. describe('Host Workspace increments', () => {
  378. it('projects subagent origin in attached summaries and creation increments', async () => {
  379. const { api, ctx } = await harness()
  380. const abort = new AbortController()
  381. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  382. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  383. const pending = nextHostFrame(stream)
  384. const childId = SessionId('session-subagent-child')
  385. ctx.sessions.create(childId, {
  386. meta: {
  387. cwd: '/tmp',
  388. parentSession: SessionId('session-parent'),
  389. origin: 'subagent',
  390. },
  391. })
  392. expect(await pending).toMatchObject({
  393. payload: {
  394. type: 'host/session-added',
  395. sessionId: childId,
  396. parentSessionId: 'session-parent',
  397. origin: 'subagent',
  398. },
  399. })
  400. expect(expectOk(await api.sessions.list(request({}))).items).toContainEqual(
  401. expect.objectContaining({ sessionId: childId, origin: 'subagent' }),
  402. )
  403. abort.abort()
  404. })
  405. it('streams committed Workspace and Session increments after empty baselines', async () => {
  406. const { api, root } = await harness()
  407. expect(expectOk(await api.workspace.list(request({}))).items).toEqual([])
  408. expect(expectOk(await api.sessions.list(request({}))).items).toEqual([])
  409. const abort = new AbortController()
  410. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  411. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  412. const workspaceIncrement = nextHostFrame(stream)
  413. const workspace = expectOk(await api.workspace.create(request({ path: stageDir(root, 'project') }))).workspace
  414. expect(await workspaceIncrement).toMatchObject({
  415. payload: { type: 'host/workspace-changed', workspace: { workspaceId: workspace.workspaceId } },
  416. })
  417. const sessionId = SessionId('session-streamed-workspace')
  418. const pending = nextHostFrame(stream)
  419. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId })))
  420. const increments: HostFrame[] = []
  421. increments.push((await pending).payload)
  422. while (increments.length < 2) {
  423. const next = await stream.next()
  424. if (next.done === true) throw new Error('Host stream ended before both increments')
  425. increments.push(next.value.payload)
  426. }
  427. expect(increments.find(increment => increment.type === 'host/session-added')).toMatchObject({
  428. // A just-created session has no events: the frame constantly carries blank:true.
  429. type: 'host/session-added', sessionId, blank: true, cwd: workspace.path,
  430. })
  431. const workspaceChanged = increments.find(
  432. (increment): increment is Extract<HostFrame, { type: 'host/workspace-changed' }> =>
  433. increment.type === 'host/workspace-changed',
  434. )
  435. expect(workspaceChanged?.workspace.sessionIds).toEqual([sessionId])
  436. abort.abort()
  437. })
  438. it('does not publish a Workspace whose registry-order commit fails', async () => {
  439. const { api, storageDomain, root } = await harness()
  440. const domain = storageDomain.get('workspace')
  441. if (domain === undefined) throw new Error('workspace domain is not open')
  442. vi.spyOn(domain.global, 'set').mockRejectedValueOnce(new Error('simulated registry order failure'))
  443. const abort = new AbortController()
  444. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  445. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  446. const next = stream.next()
  447. const failed = await api.workspace.create(request({ path: stageDir(root, 'ghost') }))
  448. expect(failed.result.ok).toBe(false)
  449. expect(expectOk(await api.workspace.list(request({}))).items).toEqual([])
  450. abort.abort()
  451. expect(await next).toMatchObject({ done: true })
  452. })
  453. it('deletes the registration, keeps its session and folder, and streams one removal', async () => {
  454. const { api, ctx, root } = await harness()
  455. const workspace = expectOk(await api.workspace.create(request({ path: stageDir(root, 'delete-me') }))).workspace
  456. const sessionId = SessionId('session-kept-after-workspace-delete')
  457. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId })))
  458. const abort = new AbortController()
  459. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  460. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  461. const removed = nextHostFrame(stream)
  462. expectOk(await api.workspace.delete(request({ workspaceId: workspace.workspaceId })))
  463. expect(await removed).toMatchObject({
  464. payload: { type: 'host/workspace-removed', workspaceId: workspace.workspaceId },
  465. })
  466. expect(expectOk(await api.workspace.list(request({}))).items).toEqual([])
  467. expect(expectOk(await api.sessions.list(request({}))).items.map(item => item.sessionId)).toContain(sessionId)
  468. expect(ctx.agents.get(sessionId)).toBeDefined()
  469. expect(existsSync(workspace.path)).toBe(true)
  470. const missing = await api.workspace.delete(request({ workspaceId: workspace.workspaceId }))
  471. expect(missing.result).toMatchObject({
  472. ok: false,
  473. error: { code: 'workspace-not-found', details: { workspaceId: workspace.workspaceId } },
  474. })
  475. const reregistered = expectOk(await api.workspace.create(request({ path: workspace.path }))).workspace
  476. expect(reregistered.workspaceId).not.toBe(workspace.workspaceId)
  477. expect(reregistered.path).toBe(workspace.path)
  478. expect(reregistered.sessionIds).toEqual([])
  479. expect(expectOk(await api.sessions.list(request({}))).items.map(item => item.sessionId)).toContain(sessionId)
  480. abort.abort()
  481. })
  482. it('archives a session into the global set, keeps its accounting, and streams the set once', async () => {
  483. const { api, root } = await harness()
  484. const workspace = expectOk(await api.workspace.create(request({ path: stageDir(root, 'archive-home') }))).workspace
  485. const sessionId = SessionId('session-to-archive')
  486. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId })))
  487. expect(expectOk(await api.workspace.list(request({}))).archivedSessionIds).toEqual([])
  488. const abort = new AbortController()
  489. const stream: AsyncIterator<RpcRequest<HostFrame>> =
  490. api.events.host(request({}), abort.signal)[Symbol.asyncIterator]()
  491. const changed = nextHostFrame(stream)
  492. expect(expectOk(await api.workspace.archiveSession(request({ sessionId }))).archivedSessionIds)
  493. .toEqual([sessionId])
  494. expect(await changed).toMatchObject({
  495. payload: { type: 'host/archived-sessions-changed', archivedSessionIds: [sessionId] },
  496. })
  497. // Accounting and the session itself are untouched; list re-baselines the set.
  498. const listed = expectOk(await api.workspace.list(request({})))
  499. expect(listed.archivedSessionIds).toEqual([sessionId])
  500. expect(listed.items[0]?.sessionIds).toEqual([sessionId])
  501. expect(expectOk(await api.sessions.list(request({}))).items.map(item => item.sessionId)).toContain(sessionId)
  502. // The idempotent repeat emits no second frame: the next observed frame is
  503. // the workspace-changed of a later attach, not another archive snapshot.
  504. const after = nextHostFrame(stream)
  505. expect(expectOk(await api.workspace.archiveSession(request({ sessionId }))).archivedSessionIds)
  506. .toEqual([sessionId])
  507. const otherSession = SessionId('session-after-archive')
  508. expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId: otherSession })))
  509. expect((await after).payload.type).not.toBe('host/archived-sessions-changed')
  510. const missing = await api.workspace.archiveSession(request({ sessionId: SessionId('session-ghost') }))
  511. expect(missing.result).toMatchObject({
  512. ok: false,
  513. error: { code: 'session-not-found', details: { sessionId: 'session-ghost' } },
  514. })
  515. abort.abort()
  516. })
  517. })