session-cold.host.spec.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. /**
  2. * Cold-session and degenerate-composition paths of the Session Controller:
  3. * metadata-only listing, Agent-free history reads, subagent ownership
  4. * isolation, and prompt failure mapping.
  5. */
  6. import { mkdtempSync, writeFileSync } from 'node:fs'
  7. import { tmpdir } from 'node:os'
  8. import { join } from 'node:path'
  9. import { describe, expect, it, vi } from 'vitest'
  10. import { Context } from '@deepseek-ai/cordis'
  11. import SessionStore from '@deepseek-ai/dsh-session'
  12. import AgentRegistry from '@deepseek-ai/dsh-agent'
  13. import { SessionHistoryController } from '@deepseek-ai/dsh-api-session-controller/src/history.ts'
  14. import { TypertLookupFailure } from '@deepseek-ai/dsh-typert-protocol'
  15. import TypertRegistry from '@deepseek-ai/dsh-typert-registry'
  16. import { createUserMessage, MessageId } from '@deepseek-ai/dsh-llm'
  17. import type { Agent } from '@deepseek-ai/dsh-agent'
  18. import UserQuestionService from '@deepseek-ai/dsh-user-questions'
  19. import type { SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
  20. import type { SessionPromptRequest, SessionRequestId } from '../src/types.ts'
  21. import {
  22. PersistenceCoordinator,
  23. SessionPersistenceRevision,
  24. type PersistenceBackend,
  25. type StoredPrefix,
  26. } from '@deepseek-ai/dsh-session-persistence'
  27. import { createSessionTestRemote } from './test-remote.ts'
  28. const sid = (id: string): SessionId => id as SessionId
  29. function request<P>(payload: P): P {
  30. return payload
  31. }
  32. let nextRequestId = 1
  33. function promptRequest(
  34. payload: Omit<SessionPromptRequest, 'requestId'>,
  35. ): SessionPromptRequest {
  36. return {
  37. ...payload,
  38. requestId: `cold-${String(nextRequestId++)}` as SessionRequestId,
  39. }
  40. }
  41. function header(id: string, createdAt: number, extra: Partial<SessionHeader> = {}): SessionHeader {
  42. return { version: 0, id: sid(id), createdAt, cwd: '/proj', ...extra }
  43. }
  44. describe('sessions.list cold merge', () => {
  45. it('verifies only small possibly-blank artifacts and treats every unavailable probe as visible', async () => {
  46. const ctx = new Context()
  47. await ctx.plugin(SessionStore)
  48. await ctx.plugin(UserQuestionService)
  49. const root = mkdtempSync(join(tmpdir(), 'dsh-cold-'))
  50. const smallPath = join(root, 'small.log')
  51. const largePath = join(root, 'large.log')
  52. writeFileSync(smallPath, 'x'.repeat(1024))
  53. writeFileSync(largePath, 'x'.repeat(1025))
  54. const metas = [
  55. header('small-blank', 100),
  56. header('small-conversation', 200),
  57. header('large-unknown', 300),
  58. header('cached-nonblank', 400),
  59. header('locationless', 500, { parentSession: sid('session-parent'), origin: 'subagent' }),
  60. header('vanished', 600),
  61. header('read-failure', 700),
  62. ]
  63. const readFrom = vi.fn(async (id: SessionId) => {
  64. if (id === sid('small-blank')) {
  65. return {
  66. meta: metas[0]!,
  67. events: [{ type: 'session/end-seed', seq: 0, time: 700, data: {} }] as SessionEvent[],
  68. }
  69. }
  70. if (id === sid('small-conversation')) {
  71. return {
  72. meta: metas[1]!,
  73. events: [
  74. { type: 'turn/start', seq: 0, time: 800, data: { turn: 1 } },
  75. {
  76. type: 'user/message', seq: 1, time: 1200,
  77. data: createUserMessage({ content: [{ type: 'text', text: 'worked' }], source: { kind: 'user' } }),
  78. surfaceOp: 'append',
  79. },
  80. ] as SessionEvent[],
  81. }
  82. }
  83. if (id === sid('read-failure')) throw new Error('simulated read failure')
  84. throw new Error(`unexpected cold read: ${id}`)
  85. })
  86. ctx.provide('sessionPersistence', {
  87. list: () => Promise.resolve(metas),
  88. locate: (meta: SessionHeader) => {
  89. if (meta.id === sid('large-unknown')) return { kind: 'jsonl', path: largePath }
  90. if (meta.id === sid('locationless')) return undefined
  91. if (meta.id === sid('vanished')) return { kind: 'jsonl', path: join(root, 'vanished.log') }
  92. return { kind: 'jsonl', path: smallPath }
  93. },
  94. readFrom,
  95. } as never)
  96. ctx.provide('sessionProjectionCache', {
  97. cachedSnapshot: (meta: SessionHeader) => {
  98. if (meta.id === sid('small-blank')) {
  99. return { asOfSeq: 0, values: { sessionListMetadata: { blank: true, lastPromptAt: null } } }
  100. }
  101. if (meta.id === sid('small-conversation')) {
  102. return { asOfSeq: 0, values: { sessionListMetadata: { blank: true, lastPromptAt: 900 } } }
  103. }
  104. if (meta.id === sid('cached-nonblank')) {
  105. return { asOfSeq: 1, values: { sessionListMetadata: { blank: false, lastPromptAt: 1000 } } }
  106. }
  107. return undefined
  108. },
  109. } as never)
  110. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  111. const response = await remote.list(request({}))
  112. expect(response.ok).toBe(true)
  113. if (!response.ok) throw new Error('unreachable')
  114. const byId = Object.fromEntries(response.value.items.map(item => [item.sessionId, item]))
  115. expect(byId['small-blank']).toMatchObject({ blank: true, updatedAt: 100, running: false })
  116. // A stale true hint cannot hide the turn found in the bounded read.
  117. expect(byId['small-conversation']).toMatchObject({ blank: false, updatedAt: 1200 })
  118. expect(byId['large-unknown']).toMatchObject({ blank: false, updatedAt: 300 })
  119. // false is monotonic, so this row skips stat/read and keeps cached recency.
  120. expect(byId['cached-nonblank']).toMatchObject({ blank: false, updatedAt: 1000 })
  121. expect(byId['locationless']).toMatchObject({
  122. blank: false,
  123. updatedAt: 500,
  124. parentSessionId: 'session-parent',
  125. origin: 'subagent',
  126. })
  127. expect(byId['vanished']).toMatchObject({ blank: false, updatedAt: 600 })
  128. expect(byId['read-failure']).toMatchObject({ blank: false, updatedAt: 700 })
  129. expect(readFrom).toHaveBeenCalledTimes(3)
  130. expect(readFrom.mock.calls.map(([id]) => id)).toEqual(expect.arrayContaining([
  131. sid('small-blank'),
  132. sid('small-conversation'),
  133. sid('read-failure'),
  134. ]))
  135. })
  136. it('can disable bounded blank probes without hiding cold Sessions', async () => {
  137. const ctx = new Context()
  138. await ctx.plugin(SessionStore)
  139. await ctx.plugin(UserQuestionService)
  140. const meta = header('probe-disabled', 100)
  141. const readFrom = vi.fn()
  142. ctx.provide('sessionPersistence', {
  143. list: () => Promise.resolve([meta]),
  144. locate: () => ({ kind: 'jsonl', path: '/not-read' }),
  145. readFrom,
  146. } as never)
  147. const remote = createSessionTestRemote(ctx, {
  148. defaultModelSelection: () => ({ provider: 'p', model: 'm' }),
  149. cwd: '/tmp',
  150. coldBlankProbeMaxBytes: 0,
  151. })
  152. const response = await remote.list(request({}))
  153. if (!response.ok) throw new Error('unreachable')
  154. expect(response.value.items).toEqual([
  155. expect.objectContaining({ sessionId: meta.id, blank: false, updatedAt: meta.createdAt }),
  156. ])
  157. expect(readFrom).not.toHaveBeenCalled()
  158. })
  159. it('replaces a probed cold row with the live Session that attached during the read', async () => {
  160. const ctx = new Context()
  161. await ctx.plugin(SessionStore)
  162. await ctx.plugin(UserQuestionService)
  163. await ctx.plugin(AgentRegistry)
  164. const meta = header('attached-during-probe', 100)
  165. const root = mkdtempSync(join(tmpdir(), 'dsh-cold-race-'))
  166. const path = join(root, 'small.log')
  167. writeFileSync(path, 'x')
  168. const started = Promise.withResolvers<undefined>()
  169. const release = Promise.withResolvers<undefined>()
  170. ctx.provide('sessionPersistence', {
  171. list: () => Promise.resolve([meta]),
  172. locate: () => ({ kind: 'jsonl', path }),
  173. readFrom: async () => {
  174. started.resolve(undefined)
  175. await release.promise
  176. return {
  177. meta,
  178. events: [{ type: 'session/end-seed', seq: 0, time: 110, data: {} }] as SessionEvent[],
  179. }
  180. },
  181. } as never)
  182. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  183. const listing = remote.list(request({}))
  184. await started.promise
  185. const session = ctx.sessions.create(meta.id, {
  186. seed: [
  187. { type: 'turn/start', seq: 0, time: 200, data: { turn: 1 } },
  188. {
  189. type: 'user/message', seq: 1, time: 300,
  190. data: createUserMessage({ content: [{ type: 'text', text: 'live' }], source: { kind: 'user' } }),
  191. surfaceOp: 'append',
  192. },
  193. ],
  194. meta: {
  195. ...meta.cwd === undefined ? {} : { cwd: meta.cwd },
  196. createdAt: meta.createdAt,
  197. },
  198. })
  199. ctx.agents.register({ id: session.id, session, status: 'running', ctx } as Agent)
  200. release.resolve(undefined)
  201. const response = await listing
  202. if (!response.ok) throw new Error('list failed')
  203. expect(response.value.items).toEqual([
  204. expect.objectContaining({
  205. sessionId: meta.id,
  206. blank: false,
  207. running: true,
  208. updatedAt: 300,
  209. }),
  210. ])
  211. })
  212. })
  213. describe('attached updatedAt tracks human prompts', () => {
  214. it('ignores pickup and non-prompt work after the latest human message', async () => {
  215. const ctx = new Context()
  216. await ctx.plugin(SessionStore)
  217. await ctx.plugin(UserQuestionService)
  218. await ctx.plugin(AgentRegistry)
  219. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  220. // Old work, resumed just now: the log tail would report the pickup.
  221. const worked = 1_000_000
  222. const resumed = ctx.sessions.create(sid('resumed-untouched'), {
  223. seed: [
  224. { type: 'turn/start', seq: 0, time: worked, data: { turn: 1 } },
  225. {
  226. type: 'user/message', seq: 1, time: worked,
  227. data: createUserMessage({ content: [{ type: 'text', text: 'worked' }], source: { kind: 'user' } }),
  228. surfaceOp: 'append',
  229. },
  230. { type: 'turn/end', seq: 2, time: worked + 1, data: { turn: 1, reason: { kind: 'completed' } } },
  231. ],
  232. meta: { cwd: '/proj', createdAt: 500 },
  233. })
  234. ctx.agents.register({ id: resumed.id, session: resumed, status: 'idle', ctx } as Agent)
  235. const boundary = resumed.events.at(-1)
  236. expect(boundary?.type).toBe('session/end-seed')
  237. expect(boundary?.time).toBeGreaterThan(worked)
  238. const listed = await remote.list(request({}))
  239. if (!listed.ok) throw new Error('list failed')
  240. const summary = listed.value.items.find(item => item.sessionId === 'resumed-untouched')
  241. expect(summary?.updatedAt).toBe(worked)
  242. // A lifecycle boundary is not a human update.
  243. resumed.append('turn/start', { turn: 2 })
  244. const afterBoundary = await remote.list(request({}))
  245. if (!afterBoundary.ok) throw new Error('list failed')
  246. expect(afterBoundary.value.items.find(item => item.sessionId === 'resumed-untouched')?.updatedAt)
  247. .toBe(worked)
  248. const prompt = resumed.append('user/message', createUserMessage({
  249. content: [{ type: 'text', text: 'new prompt' }],
  250. source: { kind: 'user' },
  251. }), { surfaceOp: 'append' })
  252. const after = await remote.list(request({}))
  253. if (!after.ok) throw new Error('list failed')
  254. const moved = after.value.items.find(item => item.sessionId === 'resumed-untouched')
  255. expect(moved?.updatedAt).toBe(prompt.time)
  256. })
  257. })
  258. describe('cold history recovery view', () => {
  259. it('shows in-memory interruption repair without activating the session', async () => {
  260. const ctx = new Context()
  261. await ctx.plugin(SessionStore)
  262. await ctx.plugin(UserQuestionService)
  263. const sessionId = sid('session-interrupted')
  264. const meta = header(sessionId, 1000)
  265. const stored: StoredPrefix<never> = {
  266. meta,
  267. events: [{ type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }],
  268. revision: SessionPersistenceRevision('history-recovery-test:1'),
  269. }
  270. const backend: PersistenceBackend<never> = {
  271. name: 'history-recovery-test',
  272. loadStored: id => Promise.resolve(id === sessionId ? structuredClone(stored) : undefined),
  273. readStoredRevision: id => Promise.resolve(
  274. id === sessionId ? SessionPersistenceRevision('history-recovery-test:1') : undefined,
  275. ),
  276. appendBatch: () => Promise.resolve(),
  277. commitRepair: () => Promise.resolve(),
  278. list: () => Promise.resolve([structuredClone(meta)]),
  279. }
  280. const coordinator = new PersistenceCoordinator(ctx, backend)
  281. ctx.provide('sessionPersistence', {
  282. list: (signal?: AbortSignal) => backend.list(signal),
  283. inspect: (id: SessionId, signal?: AbortSignal) => coordinator.inspect(id, signal),
  284. locate: () => undefined,
  285. } as never)
  286. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  287. const history = await remote.page({
  288. address: { kind: 'session', sessionId },
  289. beforeSeq: 2,
  290. maxMessages: 10,
  291. })
  292. if (!history.ok) throw new Error('history failed')
  293. expect(history.value.events.map(entry => entry.event)).toMatchInlineSnapshot(`
  294. [
  295. {
  296. "data": {
  297. "turn": 1,
  298. },
  299. "seq": 0,
  300. "time": 1,
  301. "type": "turn/start",
  302. },
  303. {
  304. "data": {
  305. "reason": {
  306. "kind": "interrupted",
  307. },
  308. "turn": 1,
  309. },
  310. "seq": 1,
  311. "time": 1,
  312. "type": "turn/end",
  313. },
  314. ]
  315. `)
  316. expect(ctx.sessions.get(sessionId)).toBeUndefined()
  317. await ctx.fiber.dispose()
  318. })
  319. })
  320. describe('Remote Agent and Session lookup policy', () => {
  321. it('deduplicates a cold resume across Agent and Session parameters', async () => {
  322. const ctx = new Context()
  323. await ctx.plugin(TypertRegistry)
  324. await ctx.plugin(SessionStore)
  325. await ctx.plugin(AgentRegistry)
  326. await ctx.plugin(UserQuestionService)
  327. const sessionId = sid('session-remote-cold')
  328. const meta = header(sessionId, 1000)
  329. const inspect = vi.fn(() => Promise.resolve({ meta, events: [] as SessionEvent[] }))
  330. ctx.provide('sessionPersistence', {
  331. list: () => Promise.resolve([meta]),
  332. inspect,
  333. locate: () => undefined,
  334. } as never)
  335. const resumedSession = { id: sessionId, header: meta, events: [] } as unknown as import('@deepseek-ai/dsh-session').Session
  336. const resumedAgent = { id: sessionId, session: resumedSession, status: 'idle', ctx } as Agent
  337. const release = Promise.withResolvers<undefined>()
  338. const resume = vi.spyOn(ctx.agents, 'resume').mockImplementation(async () => {
  339. await release.promise
  340. return { agent: resumedAgent, dispose: () => Promise.resolve() }
  341. })
  342. const defaultAgentLookup = ctx.typert.lookups.get('agent')
  343. const defaultSessionLookup = ctx.typert.lookups.get('session')
  344. createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  345. await vi.waitFor(() => {
  346. expect(ctx.typert.lookups.get('agent')).not.toBe(defaultAgentLookup)
  347. expect(ctx.typert.lookups.get('session')).not.toBe(defaultSessionLookup)
  348. })
  349. const agentLookup = ctx.typert.lookups.get('agent')
  350. const sessionLookup = ctx.typert.lookups.get('session')
  351. if (agentLookup === undefined || sessionLookup === undefined) throw new Error('core lookup providers were not mounted')
  352. const resolvedAgent = Promise.resolve(agentLookup.resolve(sessionId))
  353. const resolvedSession = Promise.resolve(sessionLookup.resolve(sessionId))
  354. await vi.waitFor(() => { expect(resume).toHaveBeenCalledOnce() })
  355. release.resolve(undefined)
  356. await expect(resolvedAgent).resolves.toBe(resumedAgent)
  357. await expect(resolvedSession).resolves.toBe(resumedSession)
  358. expect(inspect).toHaveBeenCalledOnce()
  359. })
  360. it('preserves the subagent ownership fence for cold and live Remote lookups', async () => {
  361. const ctx = new Context()
  362. await ctx.plugin(TypertRegistry)
  363. await ctx.plugin(SessionStore)
  364. await ctx.plugin(AgentRegistry)
  365. await ctx.plugin(UserQuestionService)
  366. const coldId = sid('session-remote-cold-child')
  367. const coldMeta = header(coldId, 1000, {
  368. parentSession: sid('session-parent'),
  369. origin: 'subagent',
  370. })
  371. const inspect = vi.fn(() => Promise.resolve({ meta: coldMeta, events: [] as SessionEvent[] }))
  372. ctx.provide('sessionPersistence', {
  373. list: () => Promise.resolve([coldMeta]),
  374. inspect,
  375. locate: () => undefined,
  376. } as never)
  377. const liveSession = ctx.sessions.create(sid('session-remote-live-child'), {
  378. meta: { cwd: '/proj', parentSession: sid('session-parent'), origin: 'subagent' },
  379. })
  380. const liveAgent = { id: liveSession.id, session: liveSession, status: 'idle', ctx } as Agent
  381. ctx.agents.register(liveAgent)
  382. const resume = vi.spyOn(ctx.agents, 'resume')
  383. const defaultAgentLookup = ctx.typert.lookups.get('agent')
  384. const defaultSessionLookup = ctx.typert.lookups.get('session')
  385. createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  386. await vi.waitFor(() => {
  387. expect(ctx.typert.lookups.get('agent')).not.toBe(defaultAgentLookup)
  388. expect(ctx.typert.lookups.get('session')).not.toBe(defaultSessionLookup)
  389. })
  390. const agentLookup = ctx.typert.lookups.get('agent')
  391. const sessionLookup = ctx.typert.lookups.get('session')
  392. if (agentLookup === undefined || sessionLookup === undefined) throw new Error('core lookup providers were not mounted')
  393. const ownershipFailure = {
  394. failure: {
  395. code: 'agent-busy',
  396. details: { reason: 'use subagent delivery for this child session' },
  397. },
  398. }
  399. const coldFailure = Promise.resolve(agentLookup.resolve(coldId))
  400. const liveFailure = Promise.resolve(sessionLookup.resolve(liveSession.id))
  401. await expect(coldFailure).rejects.toBeInstanceOf(TypertLookupFailure)
  402. await expect(coldFailure).rejects.toMatchObject(ownershipFailure)
  403. await expect(liveFailure).rejects.toBeInstanceOf(TypertLookupFailure)
  404. await expect(liveFailure).rejects.toMatchObject(ownershipFailure)
  405. expect(resume).not.toHaveBeenCalled()
  406. expect(inspect).toHaveBeenCalledOnce()
  407. })
  408. })
  409. describe('subagent ownership fence', () => {
  410. it('reads a cold child without an Agent and rejects generic resume or adoption', async () => {
  411. const ctx = new Context()
  412. await ctx.plugin(SessionStore)
  413. await ctx.plugin(AgentRegistry)
  414. await ctx.plugin(UserQuestionService)
  415. const sessionId = sid('session-child')
  416. const meta = header('session-child', 1000, {
  417. parentSession: sid('session-parent'),
  418. seedLength: 0,
  419. origin: 'subagent',
  420. })
  421. const events = [
  422. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  423. {
  424. type: 'user/message',
  425. seq: 1,
  426. time: 2,
  427. data: { content: [{ type: 'text', text: 'work' }], source: { kind: 'user' } },
  428. surfaceOp: 'append',
  429. },
  430. {
  431. type: 'subagent/descriptor',
  432. seq: 2,
  433. time: 3,
  434. data: { version: 2, mode: 'continuable', provider: 'spawn', label: 'child' },
  435. },
  436. { type: 'turn/end', seq: 3, time: 4, data: { turn: 1, reason: { kind: 'completed' } } },
  437. ] as SessionEvent[]
  438. const inspect = vi.fn(() => Promise.resolve({ meta, events }))
  439. ctx.provide('sessionPersistence', {
  440. list: () => Promise.resolve([meta]),
  441. inspect,
  442. locate: () => undefined,
  443. } as never)
  444. const resume = vi.spyOn(ctx.agents, 'resume')
  445. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  446. const history = await new SessionHistoryController(ctx).page({
  447. address: {
  448. kind: 'subagent',
  449. parentSessionId: meta.parentSession as SessionId,
  450. childSessionId: sessionId,
  451. mode: 'continuable',
  452. },
  453. }, new AbortController().signal)
  454. expect(history.events.map(entry => entry.event.type)).toEqual(events.map(event => event.type))
  455. expect(ctx.agents.get(sessionId)).toBeUndefined()
  456. const prompt = await remote.prompt(promptRequest({
  457. sessionId,
  458. mode: 'queue',
  459. content: [{ type: 'text', text: 'follow up' }],
  460. }))
  461. expect(prompt.ok).toBe(false)
  462. if (!prompt.ok) {
  463. expect(prompt.error).toMatchObject({
  464. code: 'agent-busy',
  465. details: { reason: 'use subagent delivery for this child session' },
  466. })
  467. }
  468. const create = await remote.create(request({ sessionId, cwd: '/proj' }))
  469. expect(create.ok).toBe(false)
  470. if (!create.ok) expect(create.error.code).toBe('agent-busy')
  471. expect(resume).not.toHaveBeenCalled()
  472. expect(ctx.agents.get(sessionId)).toBeUndefined()
  473. expect(inspect).toHaveBeenCalledTimes(3)
  474. })
  475. it('no longer treats a descriptor-only cold child without origin as subagent-owned', async () => {
  476. const ctx = new Context()
  477. await ctx.plugin(SessionStore)
  478. await ctx.plugin(AgentRegistry)
  479. await ctx.plugin(UserQuestionService)
  480. const sessionId = sid('session-legacy-child')
  481. const meta = header('session-legacy-child', 1000, {
  482. parentSession: sid('session-parent'),
  483. seedLength: 0,
  484. })
  485. const events = [
  486. {
  487. type: 'subagent/descriptor',
  488. seq: 0,
  489. time: 1,
  490. data: { version: 2, mode: 'continuable', provider: 'spawn', label: 'child' },
  491. },
  492. ] as SessionEvent[]
  493. ctx.provide('sessionPersistence', {
  494. list: () => Promise.resolve([meta]),
  495. inspect: () => Promise.resolve({ meta, events }),
  496. locate: () => undefined,
  497. } as never)
  498. // Stores whose headers predate `origin` classify a child only through the
  499. // descriptor event; the pre-release decision stops recognizing them, so
  500. // the ownership fence lets generic resume reach the registry instead of
  501. // answering `agent-busy`.
  502. const resume = vi.spyOn(ctx.agents, 'resume')
  503. .mockRejectedValue(new Error('registry unavailable in this bench'))
  504. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  505. const prompt = await remote.prompt(promptRequest({
  506. sessionId,
  507. mode: 'queue',
  508. content: [{ type: 'text', text: 'follow up' }],
  509. }))
  510. expect(resume).toHaveBeenCalledTimes(1)
  511. expect(prompt.ok).toBe(false)
  512. if (!prompt.ok) expect(prompt.error.code).toBe('internal')
  513. })
  514. it('rejects origin-marked and runtime-owned live children from generic controls', async () => {
  515. const ctx = new Context()
  516. await ctx.plugin(SessionStore)
  517. await ctx.plugin(AgentRegistry)
  518. await ctx.plugin(UserQuestionService)
  519. const parentSession = ctx.sessions.create(sid('session-parent'), { meta: { cwd: '/proj' } })
  520. const parent = { id: parentSession.id, session: parentSession, status: 'idle', ctx } as Agent
  521. ctx.agents.register(parent)
  522. const originSession = ctx.sessions.create(sid('session-origin-child'), {
  523. meta: { cwd: '/proj', parentSession: parent.id, origin: 'subagent' },
  524. })
  525. const cancel = vi.fn()
  526. const updateInbox = vi.fn(() => 'applied' as const)
  527. const originChild = {
  528. id: originSession.id,
  529. session: originSession,
  530. status: 'idle',
  531. ctx,
  532. cancel,
  533. updateInbox,
  534. } as unknown as Agent
  535. ctx.agents.register(originChild)
  536. const startingSession = ctx.sessions.create(sid('session-starting-child'), {
  537. meta: { cwd: '/proj', parentSession: parent.id },
  538. })
  539. const startingChild = { id: startingSession.id, session: startingSession, status: 'idle', ctx } as Agent
  540. ctx.agents.enter(startingChild, parent)
  541. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  542. const stopped = await remote.cancel(request({ sessionId: originChild.id }))
  543. expect(stopped.ok).toBe(false)
  544. if (!stopped.ok) expect(stopped.error.code).toBe('agent-busy')
  545. expect(cancel).not.toHaveBeenCalled()
  546. const queued = await remote.updateQueue(request({
  547. sessionId: originChild.id,
  548. itemId: MessageId('queued-item'),
  549. action: { kind: 'remove' },
  550. }))
  551. expect(queued.ok).toBe(false)
  552. if (!queued.ok) expect(queued.error.code).toBe('agent-busy')
  553. expect(updateInbox).not.toHaveBeenCalled()
  554. const models = await remote.models(request({ sessionId: startingChild.id }))
  555. expect(models.ok).toBe(false)
  556. if (!models.ok) expect(models.error.code).toBe('agent-busy')
  557. const create = await remote.create(request({ sessionId: originChild.id, cwd: '/proj' }))
  558. expect(create.ok).toBe(false)
  559. if (!create.ok) expect(create.error.code).toBe('agent-busy')
  560. expect(ctx.agents.get(originChild.id)).toBe(originChild)
  561. })
  562. it('does not classify an ordinary fork from an inherited ancestor descriptor', async () => {
  563. const ctx = new Context()
  564. await ctx.plugin(SessionStore)
  565. await ctx.plugin(AgentRegistry)
  566. await ctx.plugin(UserQuestionService)
  567. const session = ctx.sessions.create(sid('session-ordinary-fork'), {
  568. seed: [{
  569. type: 'subagent/descriptor',
  570. seq: 0,
  571. time: 1,
  572. data: { version: 2, mode: 'continuable', provider: 'spawn', label: 'ancestor' },
  573. }],
  574. meta: { cwd: '/proj', parentSession: sid('session-source'), seedLength: 1 },
  575. })
  576. const followup = vi.fn()
  577. const agent = { id: session.id, session, status: 'idle', ctx, followup } as unknown as Agent
  578. ctx.agents.register(agent)
  579. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  580. const response = await remote.prompt(promptRequest({
  581. sessionId: agent.id,
  582. mode: 'queue',
  583. content: [{ type: 'text', text: 'ordinary work' }],
  584. }))
  585. expect(response.ok).toBe(true)
  586. expect(followup).toHaveBeenCalledOnce()
  587. })
  588. it('canonicalizes a supplied browser zone on the exact prompt and rejects invalid names', async () => {
  589. const ctx = new Context()
  590. await ctx.plugin(SessionStore)
  591. await ctx.plugin(AgentRegistry)
  592. await ctx.plugin(UserQuestionService)
  593. const session = ctx.sessions.create(sid('session-browser-zone'), { meta: { cwd: '/proj' } })
  594. const followup = vi.fn()
  595. const agent = { id: session.id, session, status: 'idle', ctx, followup } as unknown as Agent
  596. ctx.agents.register(agent)
  597. const remote = createSessionTestRemote(ctx, {
  598. defaultModelSelection: () => ({ provider: 'p', model: 'm' }),
  599. cwd: '/tmp',
  600. })
  601. const alias = 'US/Pacific'
  602. const canonical = new Intl.DateTimeFormat('en-US', { timeZone: alias })
  603. .resolvedOptions().timeZone
  604. const zonedRequest = promptRequest({
  605. sessionId: agent.id,
  606. mode: 'queue' as const,
  607. content: [{ type: 'text' as const, text: 'zoned work' }],
  608. clientTimeZone: alias,
  609. })
  610. await expect(remote.prompt(zonedRequest)).resolves.toMatchObject({ ok: true })
  611. expect(followup).toHaveBeenNthCalledWith(1, expect.objectContaining({
  612. source: { kind: 'user', rpcId: zonedRequest.requestId, clientTimeZone: canonical },
  613. }))
  614. const utcRequest = promptRequest({
  615. sessionId: agent.id,
  616. mode: 'queue' as const,
  617. content: [{ type: 'text' as const, text: 'UTC work' }],
  618. clientTimeZone: 'UTC',
  619. })
  620. await expect(remote.prompt(utcRequest)).resolves.toMatchObject({ ok: true })
  621. expect(followup).toHaveBeenNthCalledWith(2, expect.objectContaining({
  622. source: { kind: 'user', rpcId: utcRequest.requestId, clientTimeZone: 'UTC' },
  623. }))
  624. const unzonedRequest = promptRequest({
  625. sessionId: agent.id,
  626. mode: 'queue' as const,
  627. content: [{ type: 'text' as const, text: 'headless work' }],
  628. })
  629. await expect(remote.prompt(unzonedRequest)).resolves.toMatchObject({ ok: true })
  630. expect(followup).toHaveBeenNthCalledWith(3, expect.objectContaining({
  631. source: { kind: 'user', rpcId: unzonedRequest.requestId },
  632. }))
  633. for (const clientTimeZone of ['', ' UTC', 'CST', 'Not/A_Real_Zone']) {
  634. const invalid = await remote.prompt(promptRequest({
  635. sessionId: agent.id,
  636. mode: 'queue' as const,
  637. content: [{ type: 'text' as const, text: 'invalid zone' }],
  638. clientTimeZone,
  639. }))
  640. expect(invalid).toEqual({
  641. ok: false,
  642. error: {
  643. code: 'invalid-time-zone',
  644. message: 'clientTimeZone must be UTC or a valid IANA Area/Location name',
  645. details: { value: clientTimeZone },
  646. },
  647. })
  648. }
  649. expect(followup).toHaveBeenCalledTimes(3)
  650. })
  651. })
  652. describe('degenerate composition (no persistence, no factory)', () => {
  653. it('list skips the cold merge and history reports missing persistence as internal', async () => {
  654. const ctx = new Context()
  655. await ctx.plugin(SessionStore)
  656. await ctx.plugin(AgentRegistry)
  657. await ctx.plugin(UserQuestionService)
  658. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  659. const listed = await remote.list(request({}))
  660. expect(listed.ok).toBe(true)
  661. if (listed.ok) expect(listed.value.items).toEqual([])
  662. // No persistence means cold history cannot inspect a transcript.
  663. const response = await remote.page({
  664. address: { kind: 'session', sessionId: sid('session-ghost') },
  665. })
  666. expect(response.ok).toBe(false)
  667. if (!response.ok) {
  668. expect(response.error.code).toBe('internal')
  669. expect(response.error.message).toMatch(/session persistence is not configured/)
  670. }
  671. })
  672. it('maps a persistence catalog miss to session-not-found without inspection', async () => {
  673. const ctx = new Context()
  674. await ctx.plugin(SessionStore)
  675. await ctx.plugin(AgentRegistry)
  676. await ctx.plugin(UserQuestionService)
  677. const inspect = vi.fn()
  678. ctx.provide('sessionPersistence', {
  679. list: () => Promise.resolve([]),
  680. inspect,
  681. } as never)
  682. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  683. const response = await remote.page({
  684. address: { kind: 'session', sessionId: sid('session-missing') },
  685. })
  686. expect(response.ok).toBe(false)
  687. if (!response.ok) expect(response.error.code).toBe('session-not-found')
  688. expect(inspect).not.toHaveBeenCalled()
  689. })
  690. })
  691. describe('sessions.prompt synchronous rejection', () => {
  692. it('maps a synchronous send throw (disposed/invalid input) to agent-busy with the reason attached', async () => {
  693. const ctx = new Context()
  694. await ctx.plugin(SessionStore)
  695. await ctx.plugin(AgentRegistry)
  696. await ctx.plugin(UserQuestionService)
  697. const session = ctx.sessions.create(sid('session-throwing'))
  698. // A live structural stub whose delivery verbs throw synchronously, the
  699. // shape a disposed loop presents at this gateway boundary.
  700. ctx.agents.register({
  701. id: session.id,
  702. session,
  703. status: 'idle',
  704. ctx,
  705. followup: () => { throw new Error('agent "session-throwing" lifecycle disposed') },
  706. steer: () => { throw new Error('agent "session-throwing" lifecycle disposed') },
  707. } as unknown as Agent)
  708. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  709. for (const mode of ['queue', 'steer'] as const) {
  710. const response = await remote.prompt(promptRequest({
  711. sessionId: session.id, mode, content: [{ type: 'text' as const, text: 'x' }],
  712. }))
  713. expect(response.ok).toBe(false)
  714. if (!response.ok) {
  715. expect(response.error.code).toBe('agent-busy')
  716. expect(response.error.message).toBe('prompt rejected')
  717. expect(response.error.details).toEqual({
  718. reason: 'Error: agent "session-throwing" lifecycle disposed',
  719. })
  720. }
  721. }
  722. })
  723. it('classifies a raced cold-resume ID collision as agent-busy', async () => {
  724. const ctx = new Context()
  725. await ctx.plugin(SessionStore)
  726. await ctx.plugin(AgentRegistry)
  727. await ctx.plugin(UserQuestionService)
  728. const sessionId = sid('race-resume')
  729. const meta: SessionHeader = header('race-resume', 1000)
  730. ctx.provide('sessionPersistence', {
  731. list: () => Promise.resolve([meta]),
  732. inspect: () => Promise.resolve({ meta, events: [] as SessionEvent[] }),
  733. locate: () => undefined,
  734. } as never)
  735. // The raced winner: a live parent-owned subagent publishes the identity
  736. // while the generic cold resume is in flight, so the resume collides.
  737. const parentSession = ctx.sessions.create(sid('race-parent'), { meta: { cwd: '/proj' } })
  738. const parent = { id: parentSession.id, session: parentSession, status: 'idle', ctx } as Agent
  739. ctx.agents.register(parent)
  740. const childSession = ctx.sessions.create(sessionId, {
  741. meta: { cwd: '/proj', parentSession: parent.id, origin: 'subagent' },
  742. })
  743. const child = { id: sessionId, session: childSession, status: 'idle', ctx } as unknown as Agent
  744. vi.spyOn(ctx.agents, 'resume').mockImplementationOnce(async () => {
  745. // The parent's `enter()` wins the identity between the pre-resume
  746. // re-check and publication; the generic resume then collides.
  747. ctx.agents.register(child)
  748. throw new Error('session id already published')
  749. })
  750. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  751. const models = await remote.models(request({ sessionId }))
  752. expect(models.ok).toBe(false)
  753. if (!models.ok) {
  754. expect(models.error).toMatchObject({
  755. code: 'agent-busy',
  756. details: { reason: 'use subagent delivery for this child session' },
  757. })
  758. }
  759. })
  760. })