api-proxy-workspace.spec.ts 29 KB

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