session-cold.host.spec.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  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 SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  19. import UserQuestionService from '@deepseek-ai/dsh-user-questions'
  20. import type { SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
  21. import type { SessionPromptRequest, SessionRequestId } from '../src/types.ts'
  22. import {
  23. PersistenceCoordinator,
  24. SessionPersistenceRevision,
  25. type PersistenceBackend,
  26. type StoredPrefix,
  27. } from '@deepseek-ai/dsh-session-persistence'
  28. import { createSessionTestRemote } from './test-remote.ts'
  29. const sid = (id: string): SessionId => id as SessionId
  30. function request<P>(payload: P): P {
  31. return payload
  32. }
  33. let nextRequestId = 1
  34. function promptRequest(
  35. payload: Omit<SessionPromptRequest, 'requestId'>,
  36. ): SessionPromptRequest {
  37. return {
  38. ...payload,
  39. requestId: `cold-${String(nextRequestId++)}` as SessionRequestId,
  40. }
  41. }
  42. function header(id: string, createdAt: number, extra: Partial<SessionHeader> = {}): SessionHeader {
  43. return { version: 0, id: sid(id), createdAt, cwd: '/proj', ...extra }
  44. }
  45. describe('sessions.list cold merge', () => {
  46. it('verifies only small possibly-blank artifacts and treats every unavailable probe as visible', async () => {
  47. const ctx = new Context()
  48. await ctx.plugin(SessionStore)
  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. // The detached cold-history path calls the cache's coldSnapshot; this
  110. // listing harness never detaches, so it is inert here.
  111. coldSnapshot: () => undefined,
  112. } as never)
  113. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  114. const response = await remote.list(request({}))
  115. expect(response.ok).toBe(true)
  116. if (!response.ok) throw new Error('unreachable')
  117. const byId = Object.fromEntries(response.value.items.map(item => [item.sessionId, item]))
  118. expect(byId['small-blank']).toMatchObject({ blank: true, updatedAt: 100, running: false })
  119. // A stale true hint cannot hide the turn found in the bounded read.
  120. expect(byId['small-conversation']).toMatchObject({ blank: false, updatedAt: 1200 })
  121. expect(byId['large-unknown']).toMatchObject({ blank: false, updatedAt: 300 })
  122. // false is monotonic, so this row skips stat/read and keeps cached recency.
  123. expect(byId['cached-nonblank']).toMatchObject({ blank: false, updatedAt: 1000 })
  124. expect(byId['locationless']).toMatchObject({
  125. blank: false,
  126. updatedAt: 500,
  127. parentSessionId: 'session-parent',
  128. origin: 'subagent',
  129. })
  130. expect(byId['vanished']).toMatchObject({ blank: false, updatedAt: 600 })
  131. expect(byId['read-failure']).toMatchObject({ blank: false, updatedAt: 700 })
  132. expect(readFrom).toHaveBeenCalledTimes(3)
  133. expect(readFrom.mock.calls.map(([id]) => id)).toEqual(expect.arrayContaining([
  134. sid('small-blank'),
  135. sid('small-conversation'),
  136. sid('read-failure'),
  137. ]))
  138. })
  139. it('can disable bounded blank probes without hiding cold Sessions', async () => {
  140. const ctx = new Context()
  141. await ctx.plugin(SessionStore)
  142. const meta = header('probe-disabled', 100)
  143. const readFrom = vi.fn()
  144. ctx.provide('sessionPersistence', {
  145. list: () => Promise.resolve([meta]),
  146. locate: () => ({ kind: 'jsonl', path: '/not-read' }),
  147. readFrom,
  148. } as never)
  149. const remote = createSessionTestRemote(ctx, {
  150. defaultModelSelection: () => ({ provider: 'p', model: 'm' }),
  151. cwd: '/tmp',
  152. coldBlankProbeMaxBytes: 0,
  153. })
  154. const response = await remote.list(request({}))
  155. if (!response.ok) throw new Error('unreachable')
  156. expect(response.value.items).toEqual([
  157. expect.objectContaining({ sessionId: meta.id, blank: false, updatedAt: meta.createdAt }),
  158. ])
  159. expect(readFrom).not.toHaveBeenCalled()
  160. })
  161. it('replaces a probed cold row with the live Session that attached during the read', async () => {
  162. const ctx = new Context()
  163. await ctx.plugin(SessionStore)
  164. await ctx.plugin(AgentRegistry)
  165. const meta = header('attached-during-probe', 100)
  166. const root = mkdtempSync(join(tmpdir(), 'dsh-cold-race-'))
  167. const path = join(root, 'small.log')
  168. writeFileSync(path, 'x')
  169. const started = Promise.withResolvers<undefined>()
  170. const release = Promise.withResolvers<undefined>()
  171. ctx.provide('sessionPersistence', {
  172. list: () => Promise.resolve([meta]),
  173. locate: () => ({ kind: 'jsonl', path }),
  174. readFrom: async () => {
  175. started.resolve(undefined)
  176. await release.promise
  177. return {
  178. meta,
  179. events: [{ type: 'session/end-seed', seq: 0, time: 110, data: {} }] as SessionEvent[],
  180. }
  181. },
  182. } as never)
  183. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  184. const listing = remote.list(request({}))
  185. await started.promise
  186. const session = ctx.sessions.create(meta.id, {
  187. seed: [
  188. { type: 'turn/start', seq: 0, time: 200, data: { turn: 1 } },
  189. {
  190. type: 'user/message', seq: 1, time: 300,
  191. data: createUserMessage({ content: [{ type: 'text', text: 'live' }], source: { kind: 'user' } }),
  192. surfaceOp: 'append',
  193. },
  194. ],
  195. meta: {
  196. ...meta.cwd === undefined ? {} : { cwd: meta.cwd },
  197. createdAt: meta.createdAt,
  198. },
  199. })
  200. ctx.agents.register({ id: session.id, session, status: 'running', ctx } as Agent)
  201. release.resolve(undefined)
  202. const response = await listing
  203. if (!response.ok) throw new Error('list failed')
  204. expect(response.value.items).toEqual([
  205. expect.objectContaining({
  206. sessionId: meta.id,
  207. blank: false,
  208. running: true,
  209. updatedAt: 300,
  210. }),
  211. ])
  212. })
  213. })
  214. describe('attached updatedAt tracks human prompts', () => {
  215. it('ignores pickup and non-prompt work after the latest human message', async () => {
  216. const ctx = new Context()
  217. await ctx.plugin(SessionStore)
  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. const sessionId = sid('session-interrupted')
  263. const meta = header(sessionId, 1000)
  264. const stored: StoredPrefix<never> = {
  265. meta,
  266. events: [{ type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }],
  267. revision: SessionPersistenceRevision('history-recovery-test:1'),
  268. }
  269. const backend: PersistenceBackend<never> = {
  270. name: 'history-recovery-test',
  271. loadStored: id => Promise.resolve(id === sessionId ? structuredClone(stored) : undefined),
  272. readStoredRevision: id => Promise.resolve(
  273. id === sessionId ? SessionPersistenceRevision('history-recovery-test:1') : undefined,
  274. ),
  275. appendBatch: () => Promise.resolve(),
  276. commitRepair: () => Promise.resolve(),
  277. list: () => Promise.resolve([structuredClone(meta)]),
  278. }
  279. const coordinator = new PersistenceCoordinator(ctx, backend)
  280. ctx.provide('sessionPersistence', {
  281. list: (signal?: AbortSignal) => backend.list(signal),
  282. inspect: (id: SessionId, signal?: AbortSignal) => coordinator.inspect(id, signal),
  283. locate: () => undefined,
  284. } as never)
  285. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  286. const history = await remote.page({
  287. address: { kind: 'session', sessionId },
  288. throughSeq: 1,
  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. const sessionId = sid('session-remote-cold')
  327. const meta = header(sessionId, 1000)
  328. const inspect = vi.fn(() => Promise.resolve({ meta, events: [] as SessionEvent[] }))
  329. ctx.provide('sessionPersistence', {
  330. list: () => Promise.resolve([meta]),
  331. inspect,
  332. locate: () => undefined,
  333. } as never)
  334. const resumedSession = { id: sessionId, header: meta, events: [] } as unknown as import('@deepseek-ai/dsh-session').Session
  335. const resumedAgent = { id: sessionId, session: resumedSession, status: 'idle', ctx } as Agent
  336. const release = Promise.withResolvers<undefined>()
  337. const resume = vi.spyOn(ctx.agents, 'resume').mockImplementation(async () => {
  338. await release.promise
  339. return { agent: resumedAgent, dispose: () => Promise.resolve() }
  340. })
  341. const defaultAgentLookup = ctx.typert.lookups.get('agent')
  342. const defaultSessionLookup = ctx.typert.lookups.get('session')
  343. createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  344. await vi.waitFor(() => {
  345. expect(ctx.typert.lookups.get('agent')).not.toBe(defaultAgentLookup)
  346. expect(ctx.typert.lookups.get('session')).not.toBe(defaultSessionLookup)
  347. })
  348. const agentLookup = ctx.typert.lookups.get('agent')
  349. const sessionLookup = ctx.typert.lookups.get('session')
  350. if (agentLookup === undefined || sessionLookup === undefined) throw new Error('core lookup providers were not mounted')
  351. const resolvedAgent = Promise.resolve(agentLookup.resolve(sessionId))
  352. const resolvedSession = Promise.resolve(sessionLookup.resolve(sessionId))
  353. await vi.waitFor(() => { expect(resume).toHaveBeenCalledOnce() })
  354. release.resolve(undefined)
  355. await expect(resolvedAgent).resolves.toBe(resumedAgent)
  356. await expect(resolvedSession).resolves.toBe(resumedSession)
  357. expect(inspect).toHaveBeenCalledOnce()
  358. })
  359. it('preserves the subagent ownership fence for cold and live Remote lookups', async () => {
  360. const ctx = new Context()
  361. await ctx.plugin(TypertRegistry)
  362. await ctx.plugin(SessionStore)
  363. await ctx.plugin(AgentRegistry)
  364. const coldId = sid('session-remote-cold-child')
  365. const coldMeta = header(coldId, 1000, {
  366. parentSession: sid('session-parent'),
  367. origin: 'subagent',
  368. })
  369. const inspect = vi.fn(() => Promise.resolve({ meta: coldMeta, events: [] as SessionEvent[] }))
  370. ctx.provide('sessionPersistence', {
  371. list: () => Promise.resolve([coldMeta]),
  372. inspect,
  373. locate: () => undefined,
  374. } as never)
  375. const liveSession = ctx.sessions.create(sid('session-remote-live-child'), {
  376. meta: { cwd: '/proj', parentSession: sid('session-parent'), origin: 'subagent' },
  377. })
  378. const liveAgent = { id: liveSession.id, session: liveSession, status: 'idle', ctx } as Agent
  379. ctx.agents.register(liveAgent)
  380. const resume = vi.spyOn(ctx.agents, 'resume')
  381. const defaultAgentLookup = ctx.typert.lookups.get('agent')
  382. const defaultSessionLookup = ctx.typert.lookups.get('session')
  383. createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  384. await vi.waitFor(() => {
  385. expect(ctx.typert.lookups.get('agent')).not.toBe(defaultAgentLookup)
  386. expect(ctx.typert.lookups.get('session')).not.toBe(defaultSessionLookup)
  387. })
  388. const agentLookup = ctx.typert.lookups.get('agent')
  389. const sessionLookup = ctx.typert.lookups.get('session')
  390. if (agentLookup === undefined || sessionLookup === undefined) throw new Error('core lookup providers were not mounted')
  391. const ownershipFailure = {
  392. failure: {
  393. code: 'agent-busy',
  394. details: { reason: 'use subagent delivery for this child session' },
  395. },
  396. }
  397. const coldFailure = Promise.resolve(agentLookup.resolve(coldId))
  398. const liveFailure = Promise.resolve(sessionLookup.resolve(liveSession.id))
  399. await expect(coldFailure).rejects.toBeInstanceOf(TypertLookupFailure)
  400. await expect(coldFailure).rejects.toMatchObject(ownershipFailure)
  401. await expect(liveFailure).rejects.toBeInstanceOf(TypertLookupFailure)
  402. await expect(liveFailure).rejects.toMatchObject(ownershipFailure)
  403. expect(resume).not.toHaveBeenCalled()
  404. expect(inspect).toHaveBeenCalledOnce()
  405. })
  406. })
  407. describe('subagent ownership fence', () => {
  408. it('reads a cold child without an Agent and rejects generic resume or adoption', async () => {
  409. const ctx = new Context()
  410. await ctx.plugin(SessionStore)
  411. await ctx.plugin(AgentRegistry)
  412. const sessionId = sid('session-child')
  413. const meta = header('session-child', 1000, {
  414. parentSession: sid('session-parent'),
  415. seedLength: 0,
  416. origin: 'subagent',
  417. })
  418. const events = [
  419. { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } },
  420. {
  421. type: 'user/message',
  422. seq: 1,
  423. time: 2,
  424. data: { content: [{ type: 'text', text: 'work' }], source: { kind: 'user' } },
  425. surfaceOp: 'append',
  426. },
  427. {
  428. type: 'subagent/descriptor',
  429. seq: 2,
  430. time: 3,
  431. data: { version: 2, mode: 'continuable', provider: 'spawn', label: 'child' },
  432. },
  433. { type: 'turn/end', seq: 3, time: 4, data: { turn: 1, reason: { kind: 'completed' } } },
  434. ] as SessionEvent[]
  435. const inspect = vi.fn(() => Promise.resolve({ meta, events }))
  436. ctx.provide('sessionPersistence', {
  437. list: () => Promise.resolve([meta]),
  438. inspect,
  439. locate: () => undefined,
  440. } as never)
  441. const resume = vi.spyOn(ctx.agents, 'resume')
  442. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  443. const history = await new SessionHistoryController(ctx).page({
  444. address: {
  445. kind: 'subagent',
  446. parentSessionId: meta.parentSession as SessionId,
  447. childSessionId: sessionId,
  448. mode: 'continuable',
  449. },
  450. throughSeq: 3,
  451. }, new AbortController().signal)
  452. expect(history.events.map(entry => entry.event.type)).toEqual(events.map(event => event.type))
  453. expect(ctx.agents.get(sessionId)).toBeUndefined()
  454. const prompt = await remote.prompt(promptRequest({
  455. sessionId,
  456. mode: 'queue',
  457. content: [{ type: 'text', text: 'follow up' }],
  458. }))
  459. expect(prompt.ok).toBe(false)
  460. if (!prompt.ok) {
  461. expect(prompt.error).toMatchObject({
  462. code: 'agent-busy',
  463. details: { reason: 'use subagent delivery for this child session' },
  464. })
  465. }
  466. const create = await remote.create(request({ sessionId, cwd: '/proj' }))
  467. expect(create.ok).toBe(false)
  468. if (!create.ok) expect(create.error.code).toBe('agent-busy')
  469. expect(resume).not.toHaveBeenCalled()
  470. expect(ctx.agents.get(sessionId)).toBeUndefined()
  471. expect(inspect).toHaveBeenCalledTimes(3)
  472. })
  473. it('hands the detached cold history to the cache, which owns the seeded fold and write-back', async () => {
  474. const ctx = new Context()
  475. await ctx.plugin(SessionStore)
  476. await ctx.plugin(AgentRegistry)
  477. await ctx.plugin(UserQuestionService)
  478. await ctx.plugin(SessionProjectionRegistry)
  479. const sessionId = sid('seeded-cold')
  480. const meta = header(sessionId, 1)
  481. const events = [
  482. { type: 'user/message', seq: 0, time: 1, data: { content: [{ type: 'text', text: 'm0' }], source: { kind: 'user' } } },
  483. { type: 'user/message', seq: 1, time: 2, data: { content: [{ type: 'text', text: 'm1' }], source: { kind: 'user' } } },
  484. { type: 'user/message', seq: 2, time: 3, data: { content: [{ type: 'text', text: 'm2' }], source: { kind: 'user' } } },
  485. ] as SessionEvent[]
  486. const inspect = vi.fn(() => Promise.resolve({ meta, events }))
  487. ctx.provide('sessionPersistence', {
  488. list: () => Promise.resolve([meta]),
  489. inspect,
  490. locate: () => undefined,
  491. } as never)
  492. // The cache owns the cold-read recipe (seed, prefix-skip, write-back);
  493. // the carrier's only job is to hand it the stored header and the full log.
  494. const coldSnapshot = vi.fn((_meta: SessionHeader, _events: readonly SessionEvent[]) =>
  495. ({ asOfSeq: 2, values: { 'test/last-user': { text: 'm2' } } }))
  496. ctx.provide('sessionProjectionCache', {
  497. cachedSnapshot: () => undefined,
  498. coldSnapshot,
  499. } as never)
  500. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  501. const history = await remote.page({ address: { kind: 'session', sessionId }, throughSeq: 2 })
  502. expect(history.ok).toBe(true)
  503. if (!history.ok) throw new Error('unreachable')
  504. expect(history.value.projections?.values['test/last-user']).toEqual({ text: 'm2' })
  505. // The full log (all events) was handed to the cache's cold snapshot.
  506. expect(coldSnapshot).toHaveBeenCalledTimes(1)
  507. expect(coldSnapshot.mock.calls[0]?.[0]?.id).toBe(sessionId)
  508. expect(coldSnapshot.mock.calls[0]?.[1]?.map(event => event.seq)).toEqual([0, 1, 2])
  509. })
  510. it('no longer treats a descriptor-only cold child without origin as subagent-owned', async () => {
  511. const ctx = new Context()
  512. await ctx.plugin(SessionStore)
  513. await ctx.plugin(AgentRegistry)
  514. const sessionId = sid('session-legacy-child')
  515. const meta = header('session-legacy-child', 1000, {
  516. parentSession: sid('session-parent'),
  517. seedLength: 0,
  518. })
  519. const events = [
  520. {
  521. type: 'subagent/descriptor',
  522. seq: 0,
  523. time: 1,
  524. data: { version: 2, mode: 'continuable', provider: 'spawn', label: 'child' },
  525. },
  526. ] as SessionEvent[]
  527. ctx.provide('sessionPersistence', {
  528. list: () => Promise.resolve([meta]),
  529. inspect: () => Promise.resolve({ meta, events }),
  530. locate: () => undefined,
  531. } as never)
  532. // Stores whose headers predate `origin` classify a child only through the
  533. // descriptor event; the pre-release decision stops recognizing them, so
  534. // the ownership fence lets generic resume reach the registry instead of
  535. // answering `agent-busy`.
  536. const resume = vi.spyOn(ctx.agents, 'resume')
  537. .mockRejectedValue(new Error('registry unavailable in this bench'))
  538. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  539. const prompt = await remote.prompt(promptRequest({
  540. sessionId,
  541. mode: 'queue',
  542. content: [{ type: 'text', text: 'follow up' }],
  543. }))
  544. expect(resume).toHaveBeenCalledTimes(1)
  545. expect(prompt.ok).toBe(false)
  546. if (!prompt.ok) expect(prompt.error.code).toBe('internal')
  547. })
  548. it('rejects origin-marked and runtime-owned live children from generic controls', async () => {
  549. const ctx = new Context()
  550. await ctx.plugin(SessionStore)
  551. await ctx.plugin(AgentRegistry)
  552. const parentSession = ctx.sessions.create(sid('session-parent'), { meta: { cwd: '/proj' } })
  553. const parent = { id: parentSession.id, session: parentSession, status: 'idle', ctx } as Agent
  554. ctx.agents.register(parent)
  555. const originSession = ctx.sessions.create(sid('session-origin-child'), {
  556. meta: { cwd: '/proj', parentSession: parent.id, origin: 'subagent' },
  557. })
  558. const cancel = vi.fn()
  559. const updateInbox = vi.fn(() => 'applied' as const)
  560. const originChild = {
  561. id: originSession.id,
  562. session: originSession,
  563. status: 'idle',
  564. ctx,
  565. cancel,
  566. updateInbox,
  567. } as unknown as Agent
  568. ctx.agents.register(originChild)
  569. const startingSession = ctx.sessions.create(sid('session-starting-child'), {
  570. meta: { cwd: '/proj', parentSession: parent.id },
  571. })
  572. const startingChild = { id: startingSession.id, session: startingSession, status: 'idle', ctx } as Agent
  573. ctx.agents.enter(startingChild, parent)
  574. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  575. const stopped = await remote.cancel(request({ sessionId: originChild.id }))
  576. expect(stopped.ok).toBe(false)
  577. if (!stopped.ok) expect(stopped.error.code).toBe('agent-busy')
  578. expect(cancel).not.toHaveBeenCalled()
  579. const queued = await remote.updateQueue(request({
  580. sessionId: originChild.id,
  581. itemId: MessageId('queued-item'),
  582. action: { kind: 'remove' },
  583. }))
  584. expect(queued.ok).toBe(false)
  585. if (!queued.ok) expect(queued.error.code).toBe('agent-busy')
  586. expect(updateInbox).not.toHaveBeenCalled()
  587. const models = await remote.models(request({ sessionId: startingChild.id }))
  588. expect(models.ok).toBe(false)
  589. if (!models.ok) expect(models.error.code).toBe('agent-busy')
  590. const create = await remote.create(request({ sessionId: originChild.id, cwd: '/proj' }))
  591. expect(create.ok).toBe(false)
  592. if (!create.ok) expect(create.error.code).toBe('agent-busy')
  593. expect(ctx.agents.get(originChild.id)).toBe(originChild)
  594. })
  595. it('does not classify an ordinary fork from an inherited ancestor descriptor', async () => {
  596. const ctx = new Context()
  597. await ctx.plugin(SessionStore)
  598. await ctx.plugin(AgentRegistry)
  599. const session = ctx.sessions.create(sid('session-ordinary-fork'), {
  600. seed: [{
  601. type: 'subagent/descriptor',
  602. seq: 0,
  603. time: 1,
  604. data: { version: 2, mode: 'continuable', provider: 'spawn', label: 'ancestor' },
  605. }],
  606. meta: { cwd: '/proj', parentSession: sid('session-source'), seedLength: 1 },
  607. })
  608. const followup = vi.fn()
  609. const agent = { id: session.id, session, status: 'idle', ctx, followup } as unknown as Agent
  610. ctx.agents.register(agent)
  611. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  612. const response = await remote.prompt(promptRequest({
  613. sessionId: agent.id,
  614. mode: 'queue',
  615. content: [{ type: 'text', text: 'ordinary work' }],
  616. }))
  617. expect(response.ok).toBe(true)
  618. expect(followup).toHaveBeenCalledOnce()
  619. })
  620. it('canonicalizes a supplied browser zone on the exact prompt and rejects invalid names', async () => {
  621. const ctx = new Context()
  622. await ctx.plugin(SessionStore)
  623. await ctx.plugin(AgentRegistry)
  624. const session = ctx.sessions.create(sid('session-browser-zone'), { meta: { cwd: '/proj' } })
  625. const followup = vi.fn()
  626. const agent = { id: session.id, session, status: 'idle', ctx, followup } as unknown as Agent
  627. ctx.agents.register(agent)
  628. const remote = createSessionTestRemote(ctx, {
  629. defaultModelSelection: () => ({ provider: 'p', model: 'm' }),
  630. cwd: '/tmp',
  631. })
  632. const alias = 'US/Pacific'
  633. const canonical = new Intl.DateTimeFormat('en-US', { timeZone: alias })
  634. .resolvedOptions().timeZone
  635. const zonedRequest = promptRequest({
  636. sessionId: agent.id,
  637. mode: 'queue' as const,
  638. content: [{ type: 'text' as const, text: 'zoned work' }],
  639. clientTimeZone: alias,
  640. })
  641. await expect(remote.prompt(zonedRequest)).resolves.toMatchObject({ ok: true })
  642. expect(followup).toHaveBeenNthCalledWith(1, expect.objectContaining({
  643. source: { kind: 'user', rpcId: zonedRequest.requestId, clientTimeZone: canonical },
  644. }))
  645. const utcRequest = promptRequest({
  646. sessionId: agent.id,
  647. mode: 'queue' as const,
  648. content: [{ type: 'text' as const, text: 'UTC work' }],
  649. clientTimeZone: 'UTC',
  650. })
  651. await expect(remote.prompt(utcRequest)).resolves.toMatchObject({ ok: true })
  652. expect(followup).toHaveBeenNthCalledWith(2, expect.objectContaining({
  653. source: { kind: 'user', rpcId: utcRequest.requestId, clientTimeZone: 'UTC' },
  654. }))
  655. const unzonedRequest = promptRequest({
  656. sessionId: agent.id,
  657. mode: 'queue' as const,
  658. content: [{ type: 'text' as const, text: 'headless work' }],
  659. })
  660. await expect(remote.prompt(unzonedRequest)).resolves.toMatchObject({ ok: true })
  661. expect(followup).toHaveBeenNthCalledWith(3, expect.objectContaining({
  662. source: { kind: 'user', rpcId: unzonedRequest.requestId },
  663. }))
  664. for (const clientTimeZone of ['', ' UTC', 'CST', 'Not/A_Real_Zone']) {
  665. const invalid = await remote.prompt(promptRequest({
  666. sessionId: agent.id,
  667. mode: 'queue' as const,
  668. content: [{ type: 'text' as const, text: 'invalid zone' }],
  669. clientTimeZone,
  670. }))
  671. expect(invalid).toEqual({
  672. ok: false,
  673. error: {
  674. code: 'invalid-time-zone',
  675. message: 'clientTimeZone must be UTC or a valid IANA Area/Location name',
  676. details: { value: clientTimeZone },
  677. },
  678. })
  679. }
  680. expect(followup).toHaveBeenCalledTimes(3)
  681. })
  682. })
  683. describe('degenerate composition (no persistence, no factory)', () => {
  684. it('list skips the cold merge and history reports missing persistence as internal', async () => {
  685. const ctx = new Context()
  686. await ctx.plugin(SessionStore)
  687. await ctx.plugin(AgentRegistry)
  688. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  689. const listed = await remote.list(request({}))
  690. expect(listed.ok).toBe(true)
  691. if (listed.ok) expect(listed.value.items).toEqual([])
  692. // No persistence means cold history cannot inspect a transcript.
  693. const response = await remote.page({
  694. address: { kind: 'session', sessionId: sid('session-ghost') },
  695. throughSeq: -1,
  696. })
  697. expect(response.ok).toBe(false)
  698. if (!response.ok) {
  699. expect(response.error.code).toBe('internal')
  700. expect(response.error.message).toMatch(/session persistence is not configured/)
  701. }
  702. })
  703. it('maps a persistence catalog miss to session-not-found without inspection', async () => {
  704. const ctx = new Context()
  705. await ctx.plugin(SessionStore)
  706. await ctx.plugin(AgentRegistry)
  707. const inspect = vi.fn()
  708. ctx.provide('sessionPersistence', {
  709. list: () => Promise.resolve([]),
  710. inspect,
  711. } as never)
  712. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  713. const response = await remote.page({
  714. address: { kind: 'session', sessionId: sid('session-missing') },
  715. throughSeq: -1,
  716. })
  717. expect(response.ok).toBe(false)
  718. if (!response.ok) expect(response.error.code).toBe('session-not-found')
  719. expect(inspect).not.toHaveBeenCalled()
  720. })
  721. })
  722. describe('sessions.prompt synchronous rejection', () => {
  723. it('maps a synchronous send throw (disposed/invalid input) to agent-busy with the reason attached', async () => {
  724. const ctx = new Context()
  725. await ctx.plugin(SessionStore)
  726. await ctx.plugin(AgentRegistry)
  727. const session = ctx.sessions.create(sid('session-throwing'))
  728. // A live structural stub whose delivery verbs throw synchronously, the
  729. // shape a disposed loop presents at this gateway boundary.
  730. ctx.agents.register({
  731. id: session.id,
  732. session,
  733. status: 'idle',
  734. ctx,
  735. followup: () => { throw new Error('agent "session-throwing" lifecycle disposed') },
  736. steer: () => { throw new Error('agent "session-throwing" lifecycle disposed') },
  737. } as unknown as Agent)
  738. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  739. for (const mode of ['queue', 'steer'] as const) {
  740. const response = await remote.prompt(promptRequest({
  741. sessionId: session.id, mode, content: [{ type: 'text' as const, text: 'x' }],
  742. }))
  743. expect(response.ok).toBe(false)
  744. if (!response.ok) {
  745. expect(response.error.code).toBe('agent-busy')
  746. expect(response.error.message).toBe('prompt rejected')
  747. expect(response.error.details).toEqual({
  748. reason: 'Error: agent "session-throwing" lifecycle disposed',
  749. })
  750. }
  751. }
  752. })
  753. it('classifies a raced cold-resume ID collision as agent-busy', async () => {
  754. const ctx = new Context()
  755. await ctx.plugin(SessionStore)
  756. await ctx.plugin(AgentRegistry)
  757. const sessionId = sid('race-resume')
  758. const meta: SessionHeader = header('race-resume', 1000)
  759. ctx.provide('sessionPersistence', {
  760. list: () => Promise.resolve([meta]),
  761. inspect: () => Promise.resolve({ meta, events: [] as SessionEvent[] }),
  762. locate: () => undefined,
  763. } as never)
  764. // The raced winner: a live parent-owned subagent publishes the identity
  765. // while the generic cold resume is in flight, so the resume collides.
  766. const parentSession = ctx.sessions.create(sid('race-parent'), { meta: { cwd: '/proj' } })
  767. const parent = { id: parentSession.id, session: parentSession, status: 'idle', ctx } as Agent
  768. ctx.agents.register(parent)
  769. const childSession = ctx.sessions.create(sessionId, {
  770. meta: { cwd: '/proj', parentSession: parent.id, origin: 'subagent' },
  771. })
  772. const child = { id: sessionId, session: childSession, status: 'idle', ctx } as unknown as Agent
  773. vi.spyOn(ctx.agents, 'resume').mockImplementationOnce(async () => {
  774. // The parent's `enter()` wins the identity between the pre-resume
  775. // re-check and publication; the generic resume then collides.
  776. ctx.agents.register(child)
  777. throw new Error('session id already published')
  778. })
  779. const remote = createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  780. const models = await remote.models(request({ sessionId }))
  781. expect(models.ok).toBe(false)
  782. if (!models.ok) {
  783. expect(models.error).toMatchObject({
  784. code: 'agent-busy',
  785. details: { reason: 'use subagent delivery for this child session' },
  786. })
  787. }
  788. })
  789. })