sessions-service.client.spec.ts 45 KB

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