1
0

api-proxy-workspace.spec.ts 20 KB

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