sessions-service.client.spec.ts 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  1. /**
  2. * ClientSessions: list store projection (manager → {ids, byId, current}
  3. * with derived titles), the current-selection account (open validation and
  4. * persisted mask semantics), scope-tree
  5. * lifecycle (lazy mint / frozen survival / removed teardown with staged
  6. * deferral — the stage follows list.current), binding identity, breadcrumb
  7. * projection, create.
  8. */
  9. import { Context } from '@deepseek-ai/cordis'
  10. import { afterEach, describe, expect, vi } from 'vitest'
  11. import type { SessionId } from '@deepseek-ai/dsh-api-remotes/client'
  12. import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
  13. import { LlmAttemptId } from '@deepseek-ai/dsh-llm'
  14. import { RemoteStreamCarrierError } from '@deepseek-ai/dsh-api-gateway/client'
  15. import { SESSION_FORMAT_VERSION, SessionSeq } from '@deepseek-ai/dsh-session/types'
  16. import { ok, type RemoteMock } from '@deepseek-ai/dsh-remote-mock'
  17. import { createClientTest, webApp } from '@deepseek-ai/dsh-client-test-runtime/src/assembly/index.ts'
  18. import { ClientSessions, SessionCreateError } from '../src/client/sessions/service.ts'
  19. import { scopeOf } from '../src/client/scope.ts'
  20. import type {
  21. SessionAssistantStreamBaseline, SessionFollowFrame, SessionFollowRequest,
  22. } from '../src/types.ts'
  23. import { FOLLOW, err, followScript, sessionWorld } from './remote/session.client.ts'
  24. const sid = (s: string): SessionId => s as SessionId
  25. /** ClientSessions uses the Gateway client for stream supervision and the native Remote mocks for responses. */
  26. const API_ROSTER = webApp.closure(['@deepseek-ai/dsh-api-gateway'])
  27. /** The first client boot pays the cold module transform of the api cone. */
  28. const COLD_BOOT_TIMEOUT_MS = 60_000
  29. interface Bench {
  30. ctx: Context
  31. mock: RemoteMock
  32. svc: ClientSessions
  33. }
  34. type BenchFactory = () => Bench
  35. const it = createClientTest({ roster: API_ROSTER }).extend<{ bench: BenchFactory }>({
  36. bench: async ({ mock, start }, use) => {
  37. mock.load(sessionWorld)
  38. const client = await start()
  39. const contexts: Context[] = []
  40. try {
  41. await use(() => {
  42. const ctx = new Context()
  43. contexts.push(ctx)
  44. const svc = new ClientSessions(ctx, client.ctx.remote)
  45. return { ctx, mock, svc }
  46. })
  47. } finally {
  48. await Promise.all(contexts.map(ctx => ctx.fiber.dispose()))
  49. }
  50. },
  51. })
  52. /** Refresh the manager list from programmable rows and flush the microtask batch. */
  53. type FeedRow = {
  54. id: string
  55. cwd?: string
  56. parentId?: string
  57. origin?: 'subagent'
  58. running?: boolean
  59. blank?: boolean
  60. projections?: Record<string, unknown>
  61. }
  62. async function feedList(b: Bench, rows: FeedRow[]): Promise<void> {
  63. b.mock.remote.session.list.mockResolvedValue(ok({
  64. items: rows.map(r => ({
  65. sessionId: sid(r.id), updatedAt: 1, running: r.running ?? false, blank: r.blank ?? false,
  66. ...(r.cwd !== undefined ? { cwd: r.cwd } : {}),
  67. ...(r.parentId !== undefined ? { parentSessionId: sid(r.parentId) } : {}),
  68. ...(r.origin !== undefined ? { origin: r.origin } : {}),
  69. ...(r.projections === undefined
  70. ? {}
  71. : { projections: { asOfSeq: 0, values: r.projections } }),
  72. })),
  73. }) as never)
  74. await b.svc.refresh()
  75. await Promise.resolve() // manager notifier flush
  76. }
  77. describe('list store projection', () => {
  78. it('projects durable titles separately from cwd/id display fallbacks and parent links', async ({ bench }) => {
  79. const b = bench()
  80. b.svc.handleControlFrame({
  81. type: 'projection', sessionId: sid('s1'), key: 'title', value: 'Durable title', seq: 2,
  82. })
  83. await feedList(b, [
  84. { id: 's1', cwd: '/home/u/proj-a/' },
  85. { id: 's2', parentId: 's1', origin: 'subagent', running: true },
  86. ])
  87. const state = b.svc.list.getSnapshot()
  88. expect(state.ids).toEqual(['s1', 's2'])
  89. expect(state.byId[sid('s1')]).toMatchObject({ title: 'Durable title', displayTitle: 'Durable title', cwd: '/home/u/proj-a/' })
  90. expect(state.byId[sid('s2')]).toMatchObject({
  91. displayTitle: 's2', parentId: 's1', origin: 'subagent', running: true,
  92. })
  93. expect(state.byId[sid('s2')]?.title).toBeUndefined()
  94. }, COLD_BOOT_TIMEOUT_MS)
  95. it('reprojects a blank session from the generic agent-preset projection', async ({ bench }) => {
  96. const b = bench()
  97. await feedList(b, [{ id: 's1', blank: true, projections: { agentPreset: 'standard' } }])
  98. expect(b.svc.list.getSnapshot().byId[sid('s1')]?.projectionValues?.agentPreset).toBe('standard')
  99. b.svc.handleControlFrame({
  100. type: 'projection', sessionId: sid('s1'), key: 'agentPreset', value: 'minimal', seq: 1,
  101. })
  102. await Promise.resolve()
  103. expect(b.svc.list.getSnapshot().byId[sid('s1')]?.projectionValues?.agentPreset).toBe('minimal')
  104. })
  105. it('reflects live increments (host stream via manager) into the store', async ({ bench }) => {
  106. const b = bench()
  107. await feedList(b, [{ id: 's1' }])
  108. b.svc.handleSessionAdded({
  109. sessionId: sid('s2'), updatedAt: 2, running: false, blank: true,
  110. })
  111. await Promise.resolve()
  112. expect(b.svc.list.getSnapshot().ids).toContain('s2')
  113. })
  114. })
  115. describe('search', () => {
  116. it('delegates transient content search without changing the list snapshot', async ({ bench }) => {
  117. const b = bench()
  118. await feedList(b, [{ id: 's1' }])
  119. const before = b.svc.list.getSnapshot()
  120. b.mock.remote.session.search.mockResolvedValue(ok({
  121. items: [{ sessionId: sid('s1'), snippet: 'matching excerpt' }],
  122. hasMore: false,
  123. }))
  124. const signal = new AbortController().signal
  125. const call = vi.spyOn(b.mock.rpc, 'call')
  126. await expect(b.svc.search('needle', signal)).resolves.toEqual({
  127. ok: true,
  128. value: {
  129. items: [{ sessionId: 's1', snippet: 'matching excerpt' }],
  130. hasMore: false,
  131. },
  132. })
  133. expect(call.mock.calls.find(([, endpoint]) => endpoint === 'session/search')?.[3]).toBe(signal)
  134. expect(b.svc.list.getSnapshot()).toBe(before)
  135. })
  136. })
  137. describe('scope tree', () => {
  138. it('publishes transient Assistant chunks and the named durable v2 settlement through one event source', async ({ bench }) => {
  139. const b = bench()
  140. await feedList(b, [{ id: 's1' }])
  141. b.svc.open(sid('s1'))
  142. const binding = b.svc.binding(sid('s1'))
  143. if (binding === undefined) throw new Error('expected Session binding')
  144. await vi.waitFor(() => {
  145. expect(binding.session.getSnapshot().openState).toBe('open')
  146. })
  147. const attemptId = LlmAttemptId('web-live-attempt')
  148. const durableMessage = {
  149. type: 'event' as const,
  150. event: {
  151. type: 'assistant/message', seq: 0, time: 2,
  152. data: {
  153. turn: 1,
  154. step: 1,
  155. message: {
  156. role: 'assistant',
  157. content: [{ type: 'text', text: 'live' }],
  158. source: { kind: 'model', provider: 'p', model: 'm' },
  159. id: 'message-1',
  160. },
  161. stream: [{ type: 'text-chunks', time0: 1, index: 0, dt: [], texts: ['live'] }],
  162. },
  163. surfaceOp: 'append' as const,
  164. },
  165. }
  166. const publications: string[][] = []
  167. const dispose = binding.eventSource.subscribe(() => {
  168. publications.push(binding.eventSource.getSnapshot().entries.map(entry => entry.event.type))
  169. })
  170. b.mock.streams.push(FOLLOW, {
  171. type: 'assistant-stream',
  172. frame: {
  173. type: 'start', attemptId, revision: 1, startedAfterSeq: -1,
  174. turn: 1, step: 1,
  175. },
  176. })
  177. await b.mock.streams.drained(FOLLOW)
  178. b.mock.streams.push(FOLLOW, {
  179. type: 'assistant-stream',
  180. frame: {
  181. type: 'chunk', attemptId, revision: 2, index: 0,
  182. time: 1,
  183. chunk: { type: 'text-delta', index: 0, text: 'live' },
  184. },
  185. })
  186. await b.mock.streams.drained(FOLLOW)
  187. await vi.waitFor(() => {
  188. expect(binding.eventSource.getSnapshot().entries).toHaveLength(1)
  189. })
  190. b.mock.streams.push(FOLLOW, durableMessage)
  191. await b.mock.streams.drained(FOLLOW)
  192. await Promise.resolve()
  193. expect(binding.eventSource.getSnapshot().entries).toHaveLength(1)
  194. b.mock.streams.push(FOLLOW, {
  195. type: 'assistant-stream',
  196. frame: {
  197. type: 'end', attemptId, revision: 3, index: 1,
  198. outcome: { kind: 'committed', eventType: 'assistant/message', seq: 0 },
  199. },
  200. })
  201. await b.mock.streams.drained(FOLLOW)
  202. await vi.waitFor(() => {
  203. expect(binding.eventSource.getSnapshot().entries).toHaveLength(1)
  204. })
  205. expect(publications).toEqual([
  206. ['assistant/live-chunk'],
  207. ['assistant/message'],
  208. ])
  209. dispose()
  210. })
  211. it('replaces an active assistant baseline on reconnect without duplicate chunks', async ({ bench }) => {
  212. const b = bench()
  213. const attemptId = LlmAttemptId('reconnect-attempt')
  214. let records: never[] = []
  215. let assistantStreamBaseline: SessionAssistantStreamBaseline = {
  216. revision: 2,
  217. activeAttempt: {
  218. attemptId, startedAfterSeq: -1, turn: 1, step: 1,
  219. nextIndex: 1,
  220. stream: [{ type: 'text-chunks', time0: 1, index: 0, dt: [], texts: ['a'] }],
  221. },
  222. }
  223. b.mock.stream(FOLLOW, followScript(
  224. () => ok({ records, hasMore: false }),
  225. { assistantStream: () => assistantStreamBaseline },
  226. ))
  227. await feedList(b, [{ id: 's1' }])
  228. b.svc.open(sid('s1'))
  229. const binding = b.svc.binding(sid('s1'))
  230. if (binding === undefined) throw new Error('expected Session binding')
  231. await vi.waitFor(() => {
  232. expect(binding.eventSource.getSnapshot().entries).toHaveLength(1)
  233. })
  234. records = []
  235. assistantStreamBaseline = {
  236. revision: 3,
  237. activeAttempt: {
  238. attemptId, startedAfterSeq: -1, turn: 1, step: 1,
  239. nextIndex: 2,
  240. stream: [{ type: 'text-chunks', time0: 1, index: 0, dt: [1], texts: ['a', 'b'] }],
  241. },
  242. }
  243. b.mock.streams.fail(FOLLOW, new RemoteStreamCarrierError('lost'))
  244. await vi.waitFor(() => {
  245. expect(b.mock.log.requests(FOLLOW)).toHaveLength(2)
  246. expect(binding.eventSource.getSnapshot().entries).toHaveLength(2)
  247. })
  248. expect(binding.eventSource.getSnapshot().entries.map(entry => (
  249. entry.event.type === 'assistant/live-chunk' && entry.event.data.chunk.type === 'text-delta'
  250. ? entry.event.data.chunk.text
  251. : undefined
  252. ))).toEqual(['a', 'b'])
  253. })
  254. it('stages a post-opening assistant settlement behind its exact active attempt', async ({ bench }) => {
  255. const b = bench()
  256. const attemptId = LlmAttemptId('reconnect-settlement-attempt')
  257. const priorMessage = {
  258. type: 'event' as const,
  259. event: {
  260. type: 'assistant/message', seq: 0, time: 30,
  261. data: {
  262. turn: 1,
  263. step: 1,
  264. message: {
  265. role: 'assistant',
  266. content: [{ type: 'text', text: 'retry ' }],
  267. source: { kind: 'model', provider: 'p', model: 'm' },
  268. id: 'prior-attempt-message',
  269. },
  270. stream: [{ type: 'text-chunks', time0: 10, index: 0, dt: [], texts: ['retry '] }],
  271. },
  272. surfaceOp: 'append' as const,
  273. },
  274. }
  275. const currentMessage = {
  276. type: 'event' as const,
  277. event: {
  278. type: 'assistant/message', seq: 1, time: 19,
  279. data: {
  280. turn: 1,
  281. step: 1,
  282. message: {
  283. role: 'assistant',
  284. content: [{ type: 'text', text: 'settled' }],
  285. source: { kind: 'model', provider: 'p', model: 'm' },
  286. id: 'current-attempt-message',
  287. },
  288. stream: [{ type: 'text-chunks', time0: 20, index: 0, dt: [], texts: ['settled'] }],
  289. },
  290. surfaceOp: 'append' as const,
  291. },
  292. }
  293. const history = ok({
  294. records: [priorMessage] as never[],
  295. hasMore: false,
  296. })
  297. const assistantStreamBaseline: SessionAssistantStreamBaseline = {
  298. revision: 2,
  299. activeAttempt: {
  300. attemptId,
  301. startedAfterSeq: SessionSeq(0),
  302. turn: 1,
  303. step: 1,
  304. nextIndex: 1,
  305. stream: currentMessage.event.data.stream,
  306. },
  307. }
  308. b.mock.stream(FOLLOW, followScript(history, { assistantStream: assistantStreamBaseline }))
  309. await feedList(b, [{ id: 's1' }])
  310. b.svc.open(sid('s1'))
  311. const binding = b.svc.binding(sid('s1'))
  312. if (binding === undefined) throw new Error('expected Session binding')
  313. await vi.waitFor(() => {
  314. expect(binding.session.getSnapshot().openState).toBe('open')
  315. })
  316. expect(binding.eventSource.getSnapshot().entries.map(entry => entry.event.type))
  317. .toEqual(['assistant/message', 'assistant/live-chunk'])
  318. expect(binding.eventSource.getSnapshot().entries[0]?.event).toBe(priorMessage.event)
  319. b.mock.streams.push(FOLLOW, currentMessage)
  320. await b.mock.streams.drained(FOLLOW)
  321. await Promise.resolve()
  322. expect(binding.eventSource.getSnapshot().entries.map(entry => entry.event.type))
  323. .toEqual(['assistant/message', 'assistant/live-chunk'])
  324. b.mock.streams.push(FOLLOW, {
  325. type: 'assistant-stream',
  326. frame: {
  327. type: 'end', attemptId, revision: 3, index: 1,
  328. outcome: { kind: 'committed', eventType: 'assistant/message', seq: 1 },
  329. },
  330. })
  331. await b.mock.streams.drained(FOLLOW)
  332. await vi.waitFor(() => {
  333. expect(binding.eventSource.getSnapshot().entries.map(entry => entry.event.type))
  334. .toEqual(['assistant/message', 'assistant/message'])
  335. })
  336. expect(binding.eventSource.getSnapshot().change).toEqual({
  337. kind: 'settle-assistant', attemptId: String(attemptId), entry: currentMessage,
  338. })
  339. })
  340. it('replaces an invalid settlement with the authoritative post-end baseline', async ({ bench }) => {
  341. const b = bench()
  342. const attemptId = LlmAttemptId('reconnect-end-index-attempt')
  343. const prior = {
  344. type: 'event' as const,
  345. event: { type: 'turn/start', seq: 0, time: 19, data: { turn: 1 } },
  346. }
  347. const message = {
  348. type: 'event' as const,
  349. event: {
  350. type: 'assistant/message', seq: 1, time: 21,
  351. data: {
  352. turn: 1,
  353. step: 1,
  354. message: {
  355. role: 'assistant',
  356. content: [{ type: 'text', text: 'settled' }],
  357. source: { kind: 'model', provider: 'p', model: 'm' },
  358. id: 'current-attempt-message',
  359. },
  360. stream: [{ type: 'text-chunks', time0: 20, index: 0, dt: [], texts: ['settled'] }],
  361. },
  362. surfaceOp: 'append' as const,
  363. },
  364. }
  365. let records = [prior] as never[]
  366. let assistantStreamBaseline: SessionAssistantStreamBaseline = {
  367. revision: 2,
  368. activeAttempt: {
  369. attemptId,
  370. startedAfterSeq: SessionSeq(0),
  371. turn: 1,
  372. step: 1,
  373. nextIndex: 1,
  374. stream: message.event.data.stream,
  375. },
  376. }
  377. b.mock.stream(FOLLOW, followScript(
  378. () => ok({ records, hasMore: false }),
  379. { assistantStream: () => assistantStreamBaseline },
  380. ))
  381. await feedList(b, [{ id: 's1' }])
  382. b.svc.open(sid('s1'))
  383. const binding = b.svc.binding(sid('s1'))
  384. if (binding === undefined) throw new Error('expected Session binding')
  385. await vi.waitFor(() => {
  386. expect(binding.eventSource.getSnapshot().entries.map(entry => entry.event.type))
  387. .toEqual(['turn/start', 'assistant/live-chunk'])
  388. })
  389. const openingRevision = binding.eventSource.getSnapshot().revision
  390. b.mock.streams.push(FOLLOW, message)
  391. await b.mock.streams.drained(FOLLOW)
  392. await Promise.resolve()
  393. expect(binding.eventSource.getSnapshot().entries.map(entry => entry.event.type))
  394. .toEqual(['turn/start', 'assistant/live-chunk'])
  395. records = [prior, message] as never[]
  396. assistantStreamBaseline = { revision: 3 }
  397. b.mock.streams.push(FOLLOW, {
  398. type: 'assistant-stream',
  399. frame: {
  400. type: 'end', attemptId, revision: 3, index: 0,
  401. outcome: { kind: 'committed', eventType: 'assistant/message', seq: 0 },
  402. },
  403. })
  404. await b.mock.streams.drained(FOLLOW)
  405. await vi.waitFor(() => {
  406. expect(b.mock.log.requests(FOLLOW)).toHaveLength(2)
  407. expect(b.mock.log.streams(FOLLOW).filter(stream => stream.state === 'open')).toHaveLength(1)
  408. expect(binding.eventSource.getSnapshot().revision).toBeGreaterThan(openingRevision)
  409. expect(binding.eventSource.getSnapshot().entries.map(entry => entry.event.type))
  410. .toEqual(['turn/start', 'assistant/message'])
  411. })
  412. })
  413. it('retains a Host-addressed scope until the first Session baseline owns pruning', async ({ bench }) => {
  414. const b = bench()
  415. const scoped = b.svc.resolveAgentScope(sid('s-early'))
  416. expect(scopeOf(scoped)).toBe('s-early')
  417. b.svc.handleControlFrame({
  418. type: 'baseline',
  419. value: { jobs: {}, projections: {} },
  420. })
  421. await Promise.resolve()
  422. expect(b.svc.resolveAgentScope(sid('s-early'))).toBe(scoped)
  423. await feedList(b, [])
  424. expect(b.svc.scope(sid('s-early'))).toBeUndefined()
  425. })
  426. it('mints lazily on first resolution, tags the ctx, and keeps binding identity stable', async ({ bench }) => {
  427. const b = bench()
  428. await feedList(b, [{ id: 's1' }])
  429. expect(b.svc.scope(sid('unknown'))).toBeUndefined()
  430. const scoped = b.svc.scope(sid('s1'))
  431. expect(scoped).toBeDefined()
  432. expect(scopeOf(scoped as Context)).toBe('s1')
  433. expect(scopeOf(b.ctx)).toBeUndefined()
  434. const binding = b.svc.binding(sid('s1'))
  435. b.svc.open(sid('s1'))
  436. expect(b.svc.sessionOf(scoped as Context)).toBe(binding?.session)
  437. expect(b.svc.binding(sid('s1'))).toBe(binding)
  438. expect(binding?.ctx).toBe(scoped)
  439. })
  440. it('tears down an off-stage removed session but defers the staged one until the stage moves', async ({ bench }) => {
  441. const b = bench()
  442. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  443. const ctx1 = b.svc.scope(sid('s1'))
  444. b.svc.open(sid('s1')) // s1 staged (current)
  445. b.svc.scope(sid('s2')) // s2 scoped but off stage
  446. await feedList(b, [{ id: 's1' }]) // s2 removed, off stage: torn down
  447. expect(b.svc.scope(sid('s2'))).toBeUndefined()
  448. await feedList(b, []) // s1 removed while staged (current masks): deferred, scope survives
  449. expect(b.svc.scope(sid('s1'))).toBe(ctx1)
  450. await feedList(b, [{ id: 's3' }])
  451. b.svc.open(sid('s3')) // stage moves: deferred teardown sweeps s1
  452. expect(b.svc.scope(sid('s1'))).toBeUndefined()
  453. })
  454. it('keeps the scope when the session merely stops running (frozen ≠ removed)', async ({ bench }) => {
  455. const b = bench()
  456. await feedList(b, [{ id: 's1', running: true }])
  457. const scoped = b.svc.scope(sid('s1'))
  458. await feedList(b, [{ id: 's1', running: false }])
  459. expect(b.svc.scope(sid('s1'))).toBe(scoped)
  460. })
  461. it('cancels a deferred teardown when the id reappears in the list', async ({ bench }) => {
  462. const b = bench()
  463. await feedList(b, [{ id: 's1' }])
  464. const scoped = b.svc.scope(sid('s1'))
  465. b.svc.open(sid('s1'))
  466. await feedList(b, []) // removed while staged → deferred
  467. await feedList(b, [{ id: 's1' }, { id: 's2' }]) // reappears (current resurfaces, stage unchanged)
  468. b.svc.open(sid('s2')) // stage moves; sweep must NOT tear down the re-listed s1
  469. expect(b.svc.scope(sid('s1'))).toBe(scoped)
  470. })
  471. it('closes an opened journal when its removed scope drops', async ({ bench }) => {
  472. const b = bench()
  473. const follows = () => b.mock.log.streams(FOLLOW).filter(({ args }) => {
  474. const request = args[0] as SessionFollowRequest
  475. return request.address.kind === 'session' && request.address.sessionId === sid('s1')
  476. })
  477. await feedList(b, [{ id: 's1' }])
  478. b.svc.open(sid('s1'))
  479. const session = b.svc.binding(sid('s1'))?.session
  480. if (session === undefined) throw new Error('expected the selected Session binding')
  481. await vi.waitFor(() => { expect(follows().filter(stream => stream.state === 'open')).toHaveLength(1) })
  482. const notified = vi.fn()
  483. session.subscribe(notified)
  484. await feedList(b, [])
  485. await feedList(b, [{ id: 's2' }])
  486. b.svc.open(sid('s2'))
  487. await vi.waitFor(() => { expect(follows().filter(stream => stream.state === 'open')).toHaveLength(0) })
  488. notified.mockClear()
  489. expect(b.mock.streams.push(FOLLOW, {
  490. type: 'event',
  491. event: { seq: 0, timestamp: 0, type: 'turn/start', data: { turn: 0 } } as never,
  492. }, ([request]) => {
  493. const address = (request as SessionFollowRequest).address
  494. return address.kind === 'session' && address.sessionId === sid('s1')
  495. })).toBe(0)
  496. await b.mock.streams.drained(FOLLOW)
  497. await Promise.resolve()
  498. expect(follows()).toHaveLength(1)
  499. expect(notified).not.toHaveBeenCalled()
  500. })
  501. })
  502. describe('Agent scope disposal lifecycle', () => {
  503. it('root disposal runs Agent scope effects', async ({ bench }) => {
  504. const b = bench()
  505. const readiness = b.ctx.plugin(() => undefined)
  506. await readiness
  507. b.svc.handleSessionAdded({
  508. sessionId: sid('live'), updatedAt: 1, running: false, blank: true,
  509. })
  510. await Promise.resolve()
  511. const scoped = b.svc.scope(sid('live'))
  512. if (scoped === undefined) throw new Error('fixture Agent Context was not minted')
  513. await scoped.fiber.await()
  514. const scopeDisposed = vi.fn()
  515. scoped.effect(() => scopeDisposed, 'fixture Agent scope effect')
  516. await b.ctx.fiber.dispose()
  517. expect(scopeDisposed).toHaveBeenCalledOnce()
  518. expect(b.svc.sessionOf(scoped)).toBeUndefined()
  519. })
  520. it('root disposal waits for an opened Session source to finish closing', async ({ bench }) => {
  521. const closeGate = Promise.withResolvers<undefined>()
  522. const abortObserved = vi.fn()
  523. let followSignal: AbortSignal | undefined
  524. const b = bench()
  525. b.mock.remote.session.follow.mockImplementation((request, signal) => {
  526. if (signal === undefined) throw new Error('fixture requires a signal')
  527. followSignal = signal
  528. let opened = false
  529. return {
  530. [Symbol.asyncIterator]: () => ({
  531. next: () => {
  532. if (!opened) {
  533. opened = true
  534. return Promise.resolve({
  535. done: false,
  536. value: {
  537. type: 'snapshot',
  538. header: {
  539. version: SESSION_FORMAT_VERSION,
  540. id: request.address.kind === 'session'
  541. ? request.address.sessionId
  542. : request.address.childSessionId,
  543. createdAt: 0,
  544. isSeeded: false,
  545. },
  546. cursor: -1,
  547. records: [],
  548. hasMore: false,
  549. projections: { asOfSeq: -1, values: {} },
  550. assistantStream: { revision: 0 },
  551. } as const,
  552. })
  553. }
  554. return new Promise((_resolve, reject) => {
  555. signal.addEventListener('abort', () => {
  556. abortObserved()
  557. void closeGate.promise.then(() => {
  558. reject(signal.reason instanceof Error
  559. ? signal.reason
  560. : new Error(String(signal.reason)))
  561. })
  562. }, { once: true })
  563. })
  564. },
  565. }),
  566. }
  567. })
  568. const readiness = b.ctx.plugin(() => undefined)
  569. await readiness
  570. await feedList(b, [{ id: 's1' }])
  571. b.svc.open(sid('s1'))
  572. await vi.waitFor(() => {
  573. expect(b.svc.binding(sid('s1'))?.session.getSnapshot().openState).toBe('open')
  574. })
  575. const disposal = b.ctx.fiber.dispose()
  576. const settled = vi.fn()
  577. const observed = disposal.then(settled)
  578. await vi.waitFor(() => { expect(abortObserved).toHaveBeenCalledOnce() })
  579. expect(followSignal?.aborted).toBe(true)
  580. expect(settled).not.toHaveBeenCalled()
  581. closeGate.resolve(undefined)
  582. await observed
  583. expect(settled).toHaveBeenCalledOnce()
  584. })
  585. it('root disposal joins every Session drop already started by pruning under load', async ({ bench }) => {
  586. const closeGates = new Map<SessionId, PromiseWithResolvers<undefined>>()
  587. const aborted = new Set<SessionId>()
  588. const b = bench()
  589. b.mock.remote.session.follow.mockImplementation((request, signal) => {
  590. if (signal === undefined) throw new Error('fixture requires a signal')
  591. const sessionId = request.address.kind === 'session'
  592. ? request.address.sessionId
  593. : request.address.childSessionId
  594. const closeGate = Promise.withResolvers<undefined>()
  595. closeGates.set(sessionId, closeGate)
  596. let opened = false
  597. return {
  598. [Symbol.asyncIterator]: () => ({
  599. next: () => {
  600. if (!opened) {
  601. opened = true
  602. return Promise.resolve({
  603. done: false,
  604. value: {
  605. type: 'snapshot',
  606. header: { version: SESSION_FORMAT_VERSION, id: sessionId, createdAt: 0, isSeeded: false },
  607. cursor: -1,
  608. records: [],
  609. hasMore: false,
  610. projections: { asOfSeq: -1, values: {} },
  611. assistantStream: { revision: 0 },
  612. } as const,
  613. })
  614. }
  615. return new Promise<IteratorResult<SessionFollowFrame>>((_resolve, reject) => {
  616. signal.addEventListener('abort', () => {
  617. aborted.add(sessionId)
  618. void closeGate.promise.then(() => {
  619. reject(signal.reason instanceof Error
  620. ? signal.reason
  621. : new Error(String(signal.reason)))
  622. })
  623. }, { once: true })
  624. })
  625. },
  626. }),
  627. }
  628. })
  629. const readiness = b.ctx.plugin(() => undefined)
  630. await readiness
  631. const sessionIds = Array.from({ length: 24 }, (_, index) => sid(`load-${String(index)}`))
  632. const retained = sessionIds.at(-1)
  633. const held = sessionIds[0]
  634. if (retained === undefined || held === undefined) throw new Error('fixture requires sessions')
  635. await feedList(b, sessionIds.map(id => ({ id })))
  636. for (const id of sessionIds) b.svc.open(id)
  637. await vi.waitFor(() => {
  638. for (const id of sessionIds) {
  639. expect(b.svc.binding(id)?.session.getSnapshot().openState).toBe('open')
  640. }
  641. })
  642. const pruned = sessionIds.slice(0, -1)
  643. await feedList(b, [{ id: retained }])
  644. await vi.waitFor(() => { expect(aborted.size).toBe(pruned.length) })
  645. for (const id of pruned) expect(b.svc.scope(id)).toBeUndefined()
  646. const disposal = b.ctx.fiber.dispose()
  647. const settled = vi.fn()
  648. const observed = disposal.then(settled)
  649. await vi.waitFor(() => { expect(aborted.size).toBe(sessionIds.length) })
  650. const otherClosures: Promise<void>[] = []
  651. for (const [id, gate] of closeGates) {
  652. if (id === held) continue
  653. gate.resolve(undefined)
  654. otherClosures.push(gate.promise)
  655. }
  656. await Promise.all(otherClosures)
  657. await new Promise((resolve) => { setTimeout(resolve, 0) })
  658. expect(settled).not.toHaveBeenCalled()
  659. closeGates.get(held)?.resolve(undefined)
  660. await observed
  661. expect(settled).toHaveBeenCalledOnce()
  662. })
  663. })
  664. describe('current selection (migrated from ui-layout, arbitrated into the list snapshot)', () => {
  665. afterEach(() => { vi.unstubAllGlobals() })
  666. it('open() writes list.current; unknown ids fail loud', async ({ bench }) => {
  667. const b = bench()
  668. await feedList(b, [{ id: 's1' }])
  669. expect(b.svc.list.getSnapshot().current).toBeUndefined()
  670. b.svc.open(sid('s1'))
  671. expect(b.svc.list.getSnapshot().current).toBe('s1')
  672. expect(() => { b.svc.open(sid('ghost')) }).toThrow(/unknown session ghost/)
  673. expect(b.svc.list.getSnapshot().current).toBe('s1') // failed open leaves the selection alone
  674. })
  675. it('clear() blanks list.current and the persisted selection', async ({ bench }) => {
  676. const storage = new Map<string, string>()
  677. vi.stubGlobal('localStorage', {
  678. getItem: (k: string) => storage.get(k) ?? null,
  679. setItem: (k: string, v: string) => { storage.set(k, v) },
  680. removeItem: (k: string) => { storage.delete(k) },
  681. clear: () => { storage.clear() },
  682. })
  683. const b = bench()
  684. await feedList(b, [{ id: 's1' }])
  685. b.svc.open(sid('s1'))
  686. expect(storage.get('dsh.sessions.current')).toContain('s1')
  687. b.svc.clear()
  688. expect(b.svc.list.getSnapshot().current).toBeUndefined()
  689. // Persisted wipe: a fresh service with the same storage stays on empty.
  690. const again = bench()
  691. await feedList(again, [{ id: 's1' }])
  692. expect(again.svc.list.getSnapshot().current).toBeUndefined()
  693. })
  694. it('masks (not destroys) the selection while its session is off the list', async ({ bench }) => {
  695. const b = bench()
  696. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  697. b.svc.open(sid('s1'))
  698. await feedList(b, [{ id: 's2' }]) // s1 removed → current falls to the empty state
  699. expect(b.svc.list.getSnapshot().current).toBeUndefined()
  700. await feedList(b, [{ id: 's1' }, { id: 's2' }]) // s1 returns → selection resurfaces
  701. expect(b.svc.list.getSnapshot().current).toBe('s1')
  702. })
  703. it('persists the selection under dsh.sessions.current and rehydrates it into a fresh service', async ({ bench }) => {
  704. const storage = new Map<string, string>()
  705. vi.stubGlobal('localStorage', {
  706. getItem: (k: string) => storage.get(k) ?? null,
  707. setItem: (k: string, v: string) => { storage.set(k, v) },
  708. })
  709. const first = bench()
  710. await feedList(first, [{ id: 's1' }])
  711. first.svc.open(sid('s1'))
  712. expect(storage.get('dsh.sessions.current')).toContain('s1')
  713. // A fresh boot (same storage) recovers the selection once the list holds the session.
  714. const second = bench()
  715. await feedList(second, [{ id: 's1' }])
  716. expect(second.svc.list.getSnapshot().current).toBe('s1')
  717. })
  718. })
  719. describe('binding and stage lifecycle', () => {
  720. it('binding() is pure resolution: no staging, no deferred sweep', async ({ bench }) => {
  721. const b = bench()
  722. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  723. b.svc.open(sid('s1')) // staged
  724. b.svc.binding(sid('s2')) // resolution only — must NOT move the stage
  725. await feedList(b, [{ id: 's2' }]) // s1 removed: still staged → deferred, scope survives
  726. expect(b.svc.scope(sid('s1'))).toBeDefined()
  727. })
  728. it('staging (current write) opens the session event window; resolution and re-staging do not re-pull', async ({ bench }) => {
  729. const b = bench()
  730. await feedList(b, [{ id: 's1' }, { id: 's2' }])
  731. const followStarts = () => b.mock.log.requests(FOLLOW).map((request) => {
  732. const address = (request as SessionFollowRequest).address
  733. return String(address.kind === 'session' ? address.sessionId : address.childSessionId)
  734. })
  735. // Resolution is addressing, not staging: no window pull.
  736. b.svc.scope(sid('s1'))
  737. b.svc.binding(sid('s1'))
  738. expect(followStarts()).toEqual([])
  739. b.svc.open(sid('s1'))
  740. await vi.waitFor(() => {
  741. expect(followStarts()).toEqual(['s1'])
  742. })
  743. // Same current again: no second pull.
  744. b.svc.open(sid('s1'))
  745. expect(followStarts()).toHaveLength(1)
  746. // Stage moves: the new occupant opens.
  747. b.svc.open(sid('s2'))
  748. await vi.waitFor(() => {
  749. expect(followStarts()).toEqual(['s1', 's2'])
  750. })
  751. })
  752. it('startup restore: a persisted selection validated by the first projection opens its window unprompted', async ({ bench }) => {
  753. const storage = new Map<string, string>([
  754. ['dsh.sessions.current', JSON.stringify({ sessionId: 's1' })],
  755. ])
  756. vi.stubGlobal('localStorage', {
  757. getItem: (k: string) => storage.get(k) ?? null,
  758. setItem: (k: string, v: string) => { storage.set(k, v) },
  759. })
  760. try {
  761. const b = bench()
  762. expect(b.mock.log.requests(FOLLOW)).toEqual([])
  763. await feedList(b, [{ id: 's1' }]) // projection validates the persisted id → current lands → stage follows
  764. await vi.waitFor(() => {
  765. expect(b.mock.log.requests(FOLLOW).map((request) => {
  766. const address = (request as SessionFollowRequest).address
  767. return String(address.kind === 'session' ? address.sessionId : address.childSessionId)
  768. })).toEqual(['s1'])
  769. })
  770. } finally {
  771. vi.unstubAllGlobals()
  772. }
  773. })
  774. })
  775. describe('catalog-addressed navigation', () => {
  776. it('uses catalog labels for a listed addressed route', async ({ bench }) => {
  777. const b = bench()
  778. b.mock.remote.subagents.list.mockImplementation((payload) => {
  779. const parentSessionId = payload
  780. if (parentSessionId === sid('root')) {
  781. return Promise.resolve(ok({
  782. entries: [{
  783. kind: 'child', id: sid('child'), mode: 'continuable', label: 'Child',
  784. activity: 'inactive', hasChildren: true,
  785. }] as never[],
  786. parentAvailable: true,
  787. }))
  788. }
  789. if (parentSessionId === sid('child')) {
  790. return Promise.resolve(ok({
  791. entries: [{
  792. kind: 'child', id: sid('grandchild'), mode: 'continuable', label: 'Grandchild',
  793. activity: 'inactive', hasChildren: false,
  794. }] as never[],
  795. parentAvailable: false,
  796. }))
  797. }
  798. return Promise.resolve(ok({ entries: [], parentAvailable: false }))
  799. })
  800. await feedList(b, [
  801. { id: 'root' },
  802. { id: 'child', cwd: '/summary-child', parentId: 'root', origin: 'subagent' },
  803. { id: 'grandchild', cwd: '/summary-grandchild', parentId: 'child', origin: 'subagent' },
  804. ])
  805. await b.svc.refreshSubagents(sid('root'))
  806. await b.svc.refreshSubagents(sid('child'))
  807. b.svc.openSubagent({
  808. parentSessionId: sid('child'), childSessionId: sid('grandchild'), mode: 'continuable',
  809. })
  810. expect(b.svc.list.getSnapshot().byId[sid('child')]?.displayTitle).toBe('Child')
  811. expect(b.svc.list.getSnapshot().byId[sid('grandchild')]?.displayTitle).toBe('Grandchild')
  812. })
  813. it('projects a directly opened descendant route without retaining ancestor scopes or addresses', async ({ bench }) => {
  814. const b = bench()
  815. b.mock.remote.subagents.list.mockImplementation((payload) => {
  816. const parentSessionId = payload
  817. if (parentSessionId === sid('root')) {
  818. return Promise.resolve(ok({
  819. entries: [{
  820. kind: 'child', id: sid('child'), mode: 'continuable', label: 'Child',
  821. activity: 'inactive', hasChildren: true,
  822. }] as never[],
  823. parentAvailable: true,
  824. }))
  825. }
  826. if (parentSessionId === sid('child')) {
  827. return Promise.resolve(ok({
  828. entries: [{
  829. kind: 'child', id: sid('grandchild'), mode: 'continuable', label: 'Grandchild',
  830. activity: 'inactive', hasChildren: false,
  831. }] as never[],
  832. parentAvailable: false,
  833. }))
  834. }
  835. return Promise.resolve(ok({ entries: [], parentAvailable: false }))
  836. })
  837. await feedList(b, [{ id: 'root' }])
  838. await b.svc.refreshSubagents(sid('root'))
  839. await b.svc.refreshSubagents(sid('child'))
  840. b.svc.openSubagent({
  841. parentSessionId: sid('child'), childSessionId: sid('grandchild'), mode: 'continuable',
  842. })
  843. const list = b.svc.list.getSnapshot()
  844. expect(list.ids).toEqual([sid('root')])
  845. expect(list.byId[sid('child')]).toMatchObject({ parentId: sid('root'), origin: 'subagent' })
  846. expect(list.byId[sid('grandchild')]).toMatchObject({ parentId: sid('child'), origin: 'subagent' })
  847. expect(b.svc.binding(sid('child'))).toBeUndefined()
  848. expect(b.svc.subagentAddress(sid('child'))).toBeUndefined()
  849. b.svc.open(sid('child'))
  850. expect(b.svc.list.getSnapshot().current).toBe(sid('child'))
  851. expect(b.svc.subagentAddress(sid('child'))).toEqual({
  852. parentSessionId: sid('root'), childSessionId: sid('child'), mode: 'continuable',
  853. })
  854. })
  855. })
  856. describe('create', () => {
  857. it('passes a preallocated id and preserves it on ordinary failure', async ({ bench }) => {
  858. const b = bench()
  859. b.mock.remote.session.create.mockResolvedValue(ok({ sessionId: sid('fresh') }))
  860. await expect(b.svc.create({ cwd: '/w', sessionId: sid('fresh') })).resolves.toBe('fresh')
  861. expect(b.mock.remote.session.create).toHaveBeenCalledExactlyOnceWith({ cwd: '/w', sessionId: 'fresh' })
  862. b.mock.remote.session.create.mockResolvedValue(err(new RemoteError('gateway/internal', '爆了', {})))
  863. const failure = await b.svc.create({ sessionId: sid('candidate') }).catch((error: unknown) => error)
  864. expect(failure).toBeInstanceOf(SessionCreateError)
  865. expect(failure).toMatchObject({
  866. requestedSessionId: 'candidate',
  867. rpcError: { code: 'gateway/internal', message: '爆了' },
  868. })
  869. })
  870. it('resolves with the session already listed and binding-resolvable (no flush wait)', async ({ bench }) => {
  871. const b = bench()
  872. b.mock.remote.session.create.mockResolvedValue(ok({ sessionId: sid('born') }))
  873. const born = await b.svc.create({ workspaceId: 'ws' as never })
  874. // Synchronously after resolution — the draft hand-off contract: the
  875. // create echo IS the entity entering the client's view (blank row +
  876. // resolvable scope/binding), no notifier flush in between.
  877. expect(b.svc.list.getSnapshot().byId[born]).toMatchObject({ id: 'born', blank: true })
  878. expect(b.svc.binding(born)).toBeDefined()
  879. expect(b.svc.scope(born)).toBeDefined()
  880. })
  881. it('lists the published id after Workspace attachment fails (publication precedes attachment)', async ({ bench }) => {
  882. const b = bench()
  883. b.mock.remote.session.create.mockResolvedValue(err(new RemoteError(
  884. 'session/workspace-attach-failed',
  885. 'ledger unavailable',
  886. { sessionId: sid('published'), workspaceId: 'ws' },
  887. )))
  888. const failure = await b.svc.create({
  889. workspaceId: 'ws' as never,
  890. sessionId: sid('published'),
  891. }).catch((error: unknown) => error)
  892. await Promise.resolve()
  893. expect(failure).toBeInstanceOf(SessionCreateError)
  894. expect(failure).toMatchObject({
  895. requestedSessionId: 'published',
  896. rpcError: { code: 'session/workspace-attach-failed' },
  897. })
  898. expect(b.svc.list.getSnapshot().byId[sid('published')]).toMatchObject({ id: 'published', blank: true })
  899. })
  900. })
  901. describe('fork', () => {
  902. it.for([
  903. ['Roadmap', 'Roadmap (1)'],
  904. ['Roadmap (1)', 'Roadmap (2)'],
  905. ['计划(1)', '计划(2)'],
  906. ['计划 (9)', '计划 (10)'],
  907. ] as const)('increments the durable title %j after the child is published', async ([sourceTitle, childTitle], { bench }) => {
  908. const b = bench()
  909. b.svc.handleControlFrame({
  910. type: 'projection', sessionId: sid('source'), key: 'title', value: sourceTitle, seq: 2,
  911. })
  912. await feedList(b, [{ id: 'source', cwd: '/work' }])
  913. b.mock.remote.session.fork.mockResolvedValue(ok({ sessionId: sid('child') }))
  914. b.mock.remote.session.rename.mockImplementation((payload) => {
  915. const { title } = payload as { title: string }
  916. return Promise.resolve(ok({ title, seq: 3 }))
  917. })
  918. await expect(b.svc.fork({
  919. sessionId: sid('source'), atSeq: 7, increaseTitle: true,
  920. })).resolves.toBe('child')
  921. expect(b.mock.remote.session.fork).toHaveBeenCalledExactlyOnceWith({ sessionId: 'source', atSeq: 7 })
  922. expect(b.mock.remote.session.rename).toHaveBeenCalledExactlyOnceWith({ sessionId: 'child', title: childTitle })
  923. await Promise.resolve()
  924. expect(b.svc.list.getSnapshot().byId[sid('child')]).toMatchObject({
  925. title: childTitle,
  926. displayTitle: childTitle,
  927. parentId: 'source',
  928. })
  929. })
  930. it('floors a fractional anchor to the real event seq the wire accepts', async ({ bench }) => {
  931. const b = bench()
  932. await feedList(b, [{ id: 'source', cwd: '/work' }])
  933. b.mock.remote.session.fork.mockResolvedValue(ok({ sessionId: sid('child') }))
  934. // The frozen node of an interrupted turn carries turnEnd.seq - 0.9.
  935. await expect(b.svc.fork({ sessionId: sid('source'), atSeq: 41.1 })).resolves.toBe('child')
  936. expect(b.mock.remote.session.fork).toHaveBeenCalledExactlyOnceWith({ sessionId: 'source', atSeq: 41 })
  937. })
  938. it('does not rename without the title policy or a durable source title', async ({ bench }) => {
  939. const b = bench()
  940. await feedList(b, [{ id: 'source', cwd: '/work' }])
  941. b.mock.remote.session.fork.mockResolvedValue(ok({ sessionId: sid('child') }))
  942. await expect(b.svc.fork({ sessionId: sid('source'), increaseTitle: true })).resolves.toBe('child')
  943. expect(b.mock.remote.session.rename).not.toHaveBeenCalled()
  944. b.mock.remote.session.fork.mockResolvedValue(ok({ sessionId: sid('child-2') }))
  945. await expect(b.svc.fork({ sessionId: sid('source') })).resolves.toBe('child-2')
  946. expect(b.mock.remote.session.rename).not.toHaveBeenCalled()
  947. })
  948. it('rejects when child rename fails while keeping the published child addressable', async ({ bench }) => {
  949. const b = bench()
  950. b.svc.handleControlFrame({
  951. type: 'projection', sessionId: sid('source'), key: 'title', value: 'Roadmap', seq: 2,
  952. })
  953. await feedList(b, [{ id: 'source' }])
  954. b.mock.remote.session.fork.mockResolvedValue(ok({ sessionId: sid('child') }))
  955. b.mock.remote.session.rename.mockResolvedValue(err(new RemoteError('session/title-invalid', 'rejected', { sessionId: sid('child') })))
  956. await expect(b.svc.fork({ sessionId: sid('source'), increaseTitle: true }))
  957. .rejects.toThrow('fork child rename failed: session/title-invalid: rejected')
  958. expect(b.svc.binding(sid('child'))).toBeDefined()
  959. })
  960. })
  961. describe('scope lifecycle rides the list mirror (entity parity: no client-side pre-birth)', () => {
  962. it('a session-added frame births the row (blank) and makes the scope resolvable; removal prunes it', async ({ bench }) => {
  963. const b = bench()
  964. await feedList(b, [])
  965. expect(b.svc.scope(sid('s-new'))).toBeUndefined() // not in view: no scope, no exceptions
  966. b.svc.handleSessionAdded({
  967. sessionId: sid('s-new'), updatedAt: 2, running: false, blank: true, cwd: '/w/a',
  968. })
  969. await Promise.resolve()
  970. const scoped = b.svc.scope(sid('s-new'))
  971. expect(scoped).toBeDefined()
  972. expect(scopeOf(scoped as Context)).toBe('s-new')
  973. b.svc.handleSessionRemoved(sid('s-new'))
  974. await Promise.resolve()
  975. expect(b.svc.scope(sid('s-new'))).toBeUndefined()
  976. })
  977. })
  978. describe('blank mirror', () => {
  979. it('flips blank=false from the running:true status frame (cross-client conversion)', async ({ bench }) => {
  980. const b = bench()
  981. await feedList(b, [{ id: 's1', blank: true }])
  982. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: true })
  983. b.svc.handleSessionStatus(sid('s1'), true)
  984. await Promise.resolve()
  985. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: false, running: true })
  986. // The instantiated Session mirrors the same flip.
  987. expect(b.svc.binding(sid('s1'))?.session.getSnapshot().blank).toBe(false)
  988. })
  989. it('flips blank=false on prompt ACCEPTANCE, not on the attempt', async ({ bench }) => {
  990. const b = bench()
  991. await feedList(b, [{ id: 's1', blank: true, cwd: '/w/a' }])
  992. const session = b.svc.binding(sid('s1'))!.session
  993. expect(session.getSnapshot().blank).toBe(true)
  994. const gate = Promise.withResolvers<Awaited<ReturnType<typeof b.mock.remote.session.prompt>>>()
  995. b.mock.remote.session.prompt.mockReturnValue(gate.promise)
  996. const send = session.prompt([{ type: 'text', text: 'hi' }], 'queue')
  997. // In flight: still blank (the flip point is the success response, which
  998. // proves the user message reached the host log).
  999. expect(session.getSnapshot().blank).toBe(true)
  1000. gate.resolve(ok({ accepted: true as const }))
  1001. await send
  1002. expect(session.getSnapshot().blank).toBe(false)
  1003. await Promise.resolve()
  1004. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: false })
  1005. })
  1006. it('keeps a rejected first prompt blank: hidden and still reusable', async ({ bench }) => {
  1007. const b = bench()
  1008. await feedList(b, [{ id: 's1', blank: true, cwd: '/w/a' }])
  1009. const session = b.svc.binding(sid('s1'))!.session
  1010. b.mock.remote.session.prompt.mockResolvedValue(err(new RemoteError('gateway/internal', 'agent busy', {})))
  1011. const result = await session.prompt([{ type: 'text', text: 'hi' }], 'queue')
  1012. expect(result.ok).toBe(false)
  1013. // No flip on failure: local stays aligned with the host authority
  1014. // (events.length still 0), so the session stays hidden and reusable.
  1015. expect(session.getSnapshot().blank).toBe(true)
  1016. await Promise.resolve()
  1017. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: true })
  1018. })
  1019. it('takes session-added blank=true as the hidden birth and list blank as reconnect authority', async ({ bench }) => {
  1020. const b = bench()
  1021. await feedList(b, [])
  1022. b.svc.handleSessionAdded({
  1023. sessionId: sid('s-new'), updatedAt: 2, running: false, blank: true, cwd: '/w/a',
  1024. })
  1025. await Promise.resolve()
  1026. expect(b.svc.list.getSnapshot().byId[sid('s-new')]).toMatchObject({ blank: true })
  1027. // Reconnect re-pull: the summary's blank=false wins (authoritative alignment).
  1028. await feedList(b, [{ id: 's-new', blank: false, cwd: '/w/a' }])
  1029. expect(b.svc.list.getSnapshot().byId[sid('s-new')]).toMatchObject({ blank: false })
  1030. })
  1031. it('never re-blanks: a stale blank=true summary cannot hide an engaged session', async ({ bench }) => {
  1032. const b = bench()
  1033. await feedList(b, [{ id: 's1', blank: true }])
  1034. const session = b.svc.binding(sid('s1'))!.session
  1035. await session.prompt([{ type: 'text', text: 'hi' }], 'queue')
  1036. await Promise.resolve()
  1037. expect(b.svc.list.getSnapshot().byId[sid('s1')]).toMatchObject({ blank: false })
  1038. // The next list pull still claims blank (host hasn't logged the message yet).
  1039. await feedList(b, [{ id: 's1', blank: true }])
  1040. expect(b.svc.binding(sid('s1'))?.session.getSnapshot().blank).toBe(false)
  1041. })
  1042. })
  1043. describe('coverage tails (branch duals)', () => {
  1044. it('displayTitleOf falls back to the id for empty and separator-only cwd', async ({ bench }) => {
  1045. const b = bench()
  1046. await feedList(b, [{ id: 'no-base', cwd: '///' }, { id: 'empty-cwd', cwd: '' }])
  1047. const { byId } = b.svc.list.getSnapshot()
  1048. expect(byId[sid('no-base')]?.displayTitle).toBe('no-base')
  1049. expect(byId[sid('empty-cwd')]?.displayTitle).toBe('empty-cwd')
  1050. expect(byId[sid('no-base')]?.title).toBeUndefined()
  1051. })
  1052. it('binding for an unknown session returns undefined and leaves the staged scope intact', async ({ bench }) => {
  1053. const b = bench()
  1054. await feedList(b, [{ id: 's1' }])
  1055. b.svc.open(sid('s1'))
  1056. expect(b.svc.binding(sid('ghost'))).toBeUndefined()
  1057. // Stage unchanged: removing s1 defers (still staged), proving the ghost lookup touched nothing.
  1058. await feedList(b, [])
  1059. expect(b.svc.scope(sid('s1'))).toBeDefined()
  1060. })
  1061. it('a masked current gap holds the stage (no teardown, no re-open) until the stage moves', async ({ bench }) => {
  1062. const b = bench()
  1063. await feedList(b, [{ id: 's1' }])
  1064. b.svc.open(sid('s1'))
  1065. await vi.waitFor(() => { expect(b.mock.log.requests(FOLLOW)).toHaveLength(1) })
  1066. await feedList(b, []) // removed while staged: current masks to undefined, stage holds → deferred
  1067. expect(b.svc.scope(sid('s1'))).toBeDefined()
  1068. // Resurfacing re-projects current = s1: same stage occupant, no second pull.
  1069. await feedList(b, [{ id: 's1' }])
  1070. expect(b.mock.log.requests(FOLLOW)).toHaveLength(1)
  1071. expect(b.svc.list.getSnapshot().current).toBe('s1')
  1072. })
  1073. it('sweep hits both deferral edges: staged-id skip and an already-vacated scope record', async ({ bench }) => {
  1074. const b = bench()
  1075. await feedList(b, [{ id: 'a' }, { id: 'b' }])
  1076. b.svc.scope(sid('a'))
  1077. b.svc.open(sid('b')) // stage: b; both scoped
  1078. await feedList(b, []) // a removed off stage → torn immediately; b removed staged → deferred
  1079. // Move the stage to a THIRD id while b stays deferred: sweep walks a set
  1080. // containing b (torn).
  1081. await feedList(b, [{ id: 'c' }])
  1082. b.svc.open(sid('c'))
  1083. expect(b.svc.scope(sid('b'))).toBeUndefined()
  1084. // Deferral for an id whose record was never minted: force the deferral
  1085. // via removed list state — sweep must tolerate the missing record.
  1086. await feedList(b, []) // c removed while staged → deferred (scope exists)
  1087. await feedList(b, [{ id: 'd' }])
  1088. b.svc.open(sid('d')) // sweep tears c
  1089. expect(b.svc.scope(sid('c'))).toBeUndefined()
  1090. })
  1091. })