@deepseek-ai/dsh-client-test-runtime 0.2.2-rc.1 → 0.2.2-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +1 -1
  3. package/README.zh.md +1 -1
  4. package/lib/index.js +9 -0
  5. package/lib/types/access.d.ts.map +1 -0
  6. package/lib/types/access.js.map +1 -0
  7. package/lib/types/assembly/bundle-roster.d.ts.map +1 -0
  8. package/lib/types/assembly/bundle-roster.js.map +1 -0
  9. package/lib/types/assembly/index.d.ts.map +1 -0
  10. package/lib/types/assembly/index.js.map +1 -0
  11. package/lib/types/assembly/modules.d.ts.map +1 -0
  12. package/lib/types/assembly/modules.js.map +1 -0
  13. package/lib/types/assembly/remote-default-responses.d.ts.map +1 -0
  14. package/lib/types/assembly/remote-default-responses.js.map +1 -0
  15. package/lib/types/assembly/remote-proxies.d.ts.map +1 -0
  16. package/lib/types/assembly/remote-proxies.js.map +1 -0
  17. package/lib/types/assembly/roster.d.ts.map +1 -0
  18. package/lib/types/assembly/roster.js.map +1 -0
  19. package/lib/types/assembly/test-client.d.ts +10 -2
  20. package/lib/types/assembly/test-client.d.ts.map +1 -0
  21. package/lib/types/assembly/test-client.js.map +1 -0
  22. package/lib/types/assembly/vitest.d.ts +1 -1
  23. package/lib/types/assembly/vitest.d.ts.map +1 -0
  24. package/lib/types/assembly/vitest.js.map +1 -0
  25. package/lib/types/config-form.d.ts.map +1 -0
  26. package/lib/types/config-form.js.map +1 -0
  27. package/lib/types/context-menu.d.ts.map +1 -0
  28. package/lib/types/context-menu.js.map +1 -0
  29. package/lib/types/fixtures.d.ts.map +1 -0
  30. package/lib/types/fixtures.js.map +1 -0
  31. package/lib/types/index.d.ts.map +1 -0
  32. package/lib/types/index.js.map +1 -0
  33. package/lib/types/locale-env.d.ts.map +1 -0
  34. package/lib/types/locale-env.js.map +1 -0
  35. package/lib/types/remote.d.ts.map +1 -0
  36. package/lib/types/remote.js.map +1 -0
  37. package/lib/types/sessions.d.ts +5 -0
  38. package/lib/types/sessions.d.ts.map +1 -0
  39. package/lib/types/sessions.js.map +1 -0
  40. package/lib/types/snapshot.d.ts.map +1 -0
  41. package/lib/types/snapshot.js.map +1 -0
  42. package/lib/types/translate.d.ts.map +1 -0
  43. package/lib/types/translate.js.map +1 -0
  44. package/lib/types/workspaces.d.ts.map +1 -0
  45. package/lib/types/workspaces.js.map +1 -0
  46. package/package.json +53 -50
  47. package/src/access.ts +95 -0
  48. package/src/assembly/bundle-roster.ts +167 -0
  49. package/src/assembly/index.ts +14 -0
  50. package/src/assembly/modules.ts +80 -0
  51. package/src/assembly/remote-default-responses.ts +64 -0
  52. package/src/assembly/remote-proxies.ts +87 -0
  53. package/src/assembly/roster.ts +163 -0
  54. package/src/assembly/test-client.ts +388 -0
  55. package/src/assembly/vitest.ts +60 -0
  56. package/src/config-form.ts +61 -0
  57. package/src/context-menu.ts +17 -0
  58. package/src/fixtures.ts +119 -0
  59. package/src/index.ts +490 -0
  60. package/src/locale-env.ts +29 -0
  61. package/src/remote.ts +103 -0
  62. package/src/sessions.ts +844 -0
  63. package/src/snapshot.ts +89 -0
  64. package/src/translate.ts +32 -0
  65. package/src/workspaces.ts +210 -0
@@ -0,0 +1,844 @@
1
+ /** Test-owned Session Controller faces over declarative fixtures. */
2
+ import type { Context } from '@deepseek-ai/cordis'
3
+ import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
4
+ import {
5
+ createScope, MutableSessionEventSource, scopeOf, SESSION_SEARCH_RESULT_LIMIT,
6
+ } from '@deepseek-ai/dsh-api-session-controller/client'
7
+ import type {
8
+ AgentContext, ISessions, ProjectionsFace, SessionBinding, SessionFace, SessionListState,
9
+ SessionEventLikeEntry, SessionLiveEventEntry, SessionSearchResultItem,
10
+ SessionReference, SessionReferenceSource, SessionRetainInfo, SessionRetainOptions,
11
+ SessionSnapshot, SessionSummary, SessionTarget, SubmissionHandle,
12
+ } from '@deepseek-ai/dsh-api-session-controller/client'
13
+ import { scopeIdentityOf } from '@deepseek-ai/dsh-api-session-controller/src/client/scope.ts'
14
+ import type { SessionRequestId } from '@deepseek-ai/dsh-api-session-controller/types'
15
+ import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client'
16
+ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
17
+ import type { ObservableSnapshot, SnapshotStore } from '@deepseek-ai/dsh-client-store'
18
+ import type { SessionId } from '@deepseek-ai/dsh-session/types'
19
+ import { sessionSnapshot } from './fixtures.ts'
20
+ import type {
21
+ SessionFixture, SessionFixtureSnapshot, Stabilizer,
22
+ } from './fixtures.ts'
23
+
24
+ declare module '@deepseek-ai/dsh-api-session-controller/client' {
25
+ interface SessionReferenceSourceMap {
26
+ testFixture: unknown
27
+ testView: unknown
28
+ testOperation: unknown
29
+ }
30
+ }
31
+
32
+ /**
33
+ * The fixture-backed session face: lifecycle reads delegate to the fixture's
34
+ * snapshot store; Session verbs are fail-loud stubs unless the
35
+ * fixture supplies them (the runtime never fakes behavior a test did not
36
+ * declare — an unstubbed call names itself instead of half-working). Extra
37
+ * fixture methods are grafted verbatim for feature-side casts.
38
+ */
39
+ export class FixtureSession implements SessionFace {
40
+ /** Mutable event source consumed only by Conversation assembly. */
41
+ readonly eventSource = new MutableSessionEventSource()
42
+
43
+ /**
44
+ * Identity-stable per-key faces over fixture-controlled projection values.
45
+ */
46
+ readonly projections: ProjectionsFace & { set(key: string, value: unknown): void }
47
+
48
+ /**
49
+ * @param sessionId - host identity (branded view of the fixture id).
50
+ * @param store - Session Controller snapshot store.
51
+ * @param overrides - fixture-declared behavior face, grafted over the stubs.
52
+ */
53
+ constructor(
54
+ readonly sessionId: SessionId,
55
+ private readonly store: SnapshotStore<SessionFixtureSnapshot>,
56
+ overrides: Record<string, unknown>,
57
+ ) {
58
+ const values = new Map<string, unknown>()
59
+ const listeners = new Map<string, Set<() => void>>()
60
+ const faces = new Map<string, ObservableSnapshot<unknown>>()
61
+ this.projections = {
62
+ faceOf: (key: string) => {
63
+ let face = faces.get(key)
64
+ if (face === undefined) {
65
+ face = {
66
+ getSnapshot: () => values.get(key),
67
+ subscribe: (fn: () => void) => {
68
+ const set = listeners.get(key) ?? new Set()
69
+ set.add(fn)
70
+ listeners.set(key, set)
71
+ return () => { set.delete(fn) }
72
+ },
73
+ }
74
+ faces.set(key, face)
75
+ }
76
+ return face
77
+ },
78
+ set: (key: string, value: unknown) => {
79
+ values.set(key, value)
80
+ for (const fn of [...(listeners.get(key) ?? [])]) fn()
81
+ },
82
+ }
83
+ Object.assign(this, overrides)
84
+ }
85
+
86
+ /** @returns the fixture Session Controller snapshot (useSession read side). */
87
+ getSnapshot(): SessionSnapshot {
88
+ return this.store.getSnapshot()
89
+ }
90
+
91
+ /**
92
+ * Subscribe to fixture snapshot changes.
93
+ * @param fn - change callback.
94
+ * @returns unsubscribe.
95
+ */
96
+ subscribe(fn: () => void): () => void {
97
+ return this.store.subscribe(fn)
98
+ }
99
+
100
+ /**
101
+ * Fail-loud stub; supply `prompt` on the fixture's session face to exercise it.
102
+ * @returns never — always throws.
103
+ */
104
+ prompt(): never {
105
+ throw new Error(`test session "${this.sessionId}": prompt is not stubbed — supply it on the fixture's session face`)
106
+ }
107
+
108
+ /**
109
+ * Minimal local-echo registration: mints an identity without touching the
110
+ * fixture snapshot (submission echoes are client-only presentation state).
111
+ * Supply `beginSubmission` on the fixture's session face to observe echoes.
112
+ * @returns a handle whose abandon is a no-op.
113
+ */
114
+ beginSubmission(): SubmissionHandle {
115
+ this.submissionSeq += 1
116
+ return {
117
+ requestId: `test-submission-${this.submissionSeq}` as SessionRequestId,
118
+ abandon: () => {},
119
+ }
120
+ }
121
+
122
+ private submissionSeq = 0
123
+
124
+ /**
125
+ * Fail-loud stub; supply `readAttachment` on the fixture's session face to exercise it.
126
+ * @param _attachment - complete durable image reference.
127
+ * @returns never — always throws.
128
+ */
129
+ readAttachment(_attachment: ImageAttachmentRef): never {
130
+ throw new Error(`test session "${this.sessionId}": readAttachment is not stubbed — supply it on the fixture's session face`)
131
+ }
132
+
133
+ /**
134
+ * Fail-loud stub; supply `updateQueue` on the fixture's session face to exercise it.
135
+ * @returns never — always throws.
136
+ */
137
+ updateQueue(): never {
138
+ throw new Error(`test session "${this.sessionId}": updateQueue is not stubbed — supply it on the fixture's session face`)
139
+ }
140
+
141
+ /**
142
+ * Fail-loud stub; supply `cancel` on the fixture's session face to exercise it.
143
+ * @returns never — always throws.
144
+ */
145
+ cancel(): never {
146
+ throw new Error(`test session "${this.sessionId}": cancel is not stubbed — supply it on the fixture's session face`)
147
+ }
148
+
149
+ /**
150
+ * Fail-loud stub; supply `command` on the fixture's session face to exercise it.
151
+ * @returns never — always throws.
152
+ */
153
+ command(): never {
154
+ throw new Error(`test session "${this.sessionId}": command is not stubbed — supply it on the fixture's session face`)
155
+ }
156
+
157
+ /**
158
+ * Fail-loud stub; supply `loadOlder` on the fixture's session face to exercise it.
159
+ * @returns never — always throws.
160
+ */
161
+ loadOlder(): never {
162
+ throw new Error(`test session "${this.sessionId}": loadOlder is not stubbed — supply it on the fixture's session face`)
163
+ }
164
+
165
+ /**
166
+ * Fail-loud stub; supply `consumeOlder` on the fixture's session face to exercise it.
167
+ * @returns never — always throws.
168
+ */
169
+ consumeOlder(): never {
170
+ throw new Error(`test session "${this.sessionId}": consumeOlder is not stubbed — supply it on the fixture's session face`)
171
+ }
172
+
173
+ /**
174
+ * Fail-loud stub; supply `loadThrough` on the fixture's session face to exercise it.
175
+ * @returns never — always throws.
176
+ */
177
+ loadThrough(): never {
178
+ throw new Error(`test session "${this.sessionId}": loadThrough is not stubbed — supply it on the fixture's session face`)
179
+ }
180
+
181
+ /**
182
+ * Fail-loud stub; supply `rename` on the fixture's session face to exercise it.
183
+ * @returns never — always throws.
184
+ */
185
+ rename(): never {
186
+ throw new Error(`test session "${this.sessionId}": rename is not stubbed — supply it on the fixture's session face`)
187
+ }
188
+ }
189
+
190
+ /** Catalog fixture data remains available across live Client generations. */
191
+ interface SessionRecord {
192
+ summary: SessionSummary
193
+ snapshot: SnapshotStore<SessionFixtureSnapshot>
194
+ session: FixtureSession
195
+ overrides: Record<string, unknown>
196
+ projections: Map<string, unknown>
197
+ initialOpen: SessionFixture['initialOpen']
198
+ }
199
+
200
+ interface SessionGeneration {
201
+ readonly binding: SessionBinding
202
+ readonly snapshot: SnapshotStore<SessionFixtureSnapshot>
203
+ readonly session: FixtureSession
204
+ readonly fiber: { dispose(): Promise<void> }
205
+ readonly lifetime: AbortController
206
+ readonly opening: Promise<void>
207
+ retention: SessionRetainInfo
208
+ live: boolean
209
+ }
210
+
211
+ interface OpeningControl {
212
+ readonly promise: Promise<void>
213
+ readonly resolve: () => void
214
+ readonly reject: (error: unknown) => void
215
+ }
216
+
217
+ function freezeRetainedBy(
218
+ counts: Partial<Record<SessionReferenceSource, number>>,
219
+ ): SessionRetainInfo['retainedBy'] {
220
+ Object.setPrototypeOf(counts, null)
221
+ return Object.freeze(counts)
222
+ }
223
+
224
+ const EMPTY_RETAIN_INFO: SessionRetainInfo = Object.freeze({
225
+ referenceCount: 0,
226
+ retainedBy: freezeRetainedBy({}),
227
+ })
228
+
229
+ // TestSessions implements SessionReference against its fixture-owned
230
+ // SessionGeneration without importing the production service's private record.
231
+ /* jscpd:ignore-start -- The fixture intentionally mirrors production SessionReference settlement and release semantics. */
232
+ async function waitForOpen(opening: Promise<void>, signal?: AbortSignal): Promise<void> {
233
+ /* v8 ignore next -- TestSessionReference always supplies its release-composed signal. */
234
+ if (signal === undefined) return opening
235
+ const aborted = Promise.withResolvers<never>()
236
+ const onAbort = (): void => { aborted.reject(signal.reason) }
237
+ signal.addEventListener('abort', onAbort, { once: true })
238
+ try {
239
+ if (signal.aborted) onAbort()
240
+ await Promise.race([opening, aborted.promise])
241
+ } finally {
242
+ signal.removeEventListener('abort', onAbort)
243
+ }
244
+ }
245
+
246
+ class TestSessionReference implements SessionReference {
247
+ private readonly released = new AbortController()
248
+ private readonly readiness = Promise.withResolvers<SessionBinding>()
249
+ readonly ready = this.readiness.promise
250
+
251
+ constructor(
252
+ readonly sessionId: SessionId,
253
+ private generation: SessionGeneration | undefined,
254
+ private releaseReference: (() => void) | undefined,
255
+ ) {
256
+ void this.ready.catch(() => {})
257
+ }
258
+
259
+ get binding(): SessionBinding {
260
+ if (this.generation === undefined || !this.generation.live) {
261
+ throw new Error(`Session reference "${this.sessionId}" is released`)
262
+ }
263
+ return this.generation.binding
264
+ }
265
+
266
+ attachOpening(opening: Promise<void>, signal?: AbortSignal): void {
267
+ const waitSignal = signal === undefined
268
+ ? this.released.signal
269
+ : AbortSignal.any([this.released.signal, signal])
270
+ void waitForOpen(opening, waitSignal).then(
271
+ () => {
272
+ try {
273
+ waitSignal.throwIfAborted()
274
+ this.readiness.resolve(this.binding)
275
+ } catch (error: unknown) {
276
+ this.readiness.reject(error)
277
+ }
278
+ },
279
+ (error: unknown) => { this.readiness.reject(error) },
280
+ )
281
+ }
282
+
283
+ release(): void {
284
+ const reason = new Error(`Session reference "${this.sessionId}" is released`)
285
+ const release = this.releaseReference
286
+ this.released.abort(reason)
287
+ this.readiness.reject(reason)
288
+ this.generation = undefined
289
+ this.releaseReference = undefined
290
+ release?.()
291
+ }
292
+
293
+ [Symbol.dispose](): void {
294
+ this.release()
295
+ }
296
+ }
297
+ /* jscpd:ignore-end */
298
+
299
+ /**
300
+ * Sessions test double behind the renderer host and feature injects: owns the
301
+ * catalog observable, scope minting through the production `createScope`,
302
+ * stable Controller bindings, and the session behavior face supplied per
303
+ * fixture. `ui-session` owns standard-source materialization.
304
+ *
305
+ * Implements the same ISessions face features receive as `ctx.sessions`, so
306
+ * a production face change breaks this double at compile time; the extra
307
+ * members (add/updateSessionSnapshot/event-window drivers/remove/
308
+ * behavior/calls/stubs) are bench-only surface.
309
+ */
310
+ export class TestSessions implements ISessions {
311
+ /** The useSessions catalog feed, independent of view ownership. */
312
+ readonly list: SnapshotStore<SessionListState>
313
+ private readonly records = new Map<SessionId, SessionRecord>()
314
+ private readonly generations = new Map<SessionId, SessionGeneration>()
315
+ private readonly addresses = new Map<SessionId, SubagentAddress>()
316
+ private readonly retentionStores = new Map<SessionId, SnapshotStore<SessionRetainInfo>>()
317
+ private readonly pendingDrops = new Set<Promise<void>>()
318
+ private closed = false
319
+
320
+ /** Calls observed on the service-level face, newest last. */
321
+ readonly calls: {
322
+ method: 'create' | 'refreshProjections' | 'refresh' | 'search' | 'fork'
323
+ args: unknown[]
324
+ }[] = []
325
+
326
+ /** The wire schema's `session.search` result bound (production parity). */
327
+ readonly searchResultLimit = SESSION_SEARCH_RESULT_LIMIT
328
+
329
+ /** Replaceable search behavior (see {@link TestSessions.stubSearch}). */
330
+ private searchStub: ((query: string, signal: AbortSignal) => { items: SessionSearchResultItem[]; hasMore: boolean }) | undefined
331
+ private createStub: ((opts: Parameters<ISessions['create']>[0]) => Promise<SessionId>) | undefined
332
+
333
+ /**
334
+ * @param stabilize - the owning runtime's act wrapper.
335
+ * @param rootCtx - the runtime's Cordis root; scope fibers mount under it.
336
+ */
337
+ constructor(private readonly stabilize: Stabilizer, private readonly rootCtx: Context) {
338
+ this.list = createSnapshotStore<SessionListState>({
339
+ ids: [], byId: {}, phase: 'ready', projectionsBySession: {},
340
+ })
341
+ rootCtx.effect(() => async () => {
342
+ this.closed = true
343
+ for (const [id, generation] of this.generations) {
344
+ generation.live = false
345
+ generation.retention = EMPTY_RETAIN_INFO
346
+ generation.lifetime.abort(new Error('test Session Controller is disposed'))
347
+ this.publishRetention(id)
348
+ }
349
+ this.generations.clear()
350
+ await this.drainDrops()
351
+ }, 'test sessions: Client generations')
352
+ }
353
+
354
+ /**
355
+ * Add a Session fixture to the catalog without retaining a generation.
356
+ * @param fixture - identity + snapshot/summary overrides + behavior face.
357
+ * @returns the stable session id (branded view of `fixture.id`).
358
+ */
359
+ async add(fixture: SessionFixture): Promise<SessionId> {
360
+ const id = fixture.id as SessionId
361
+ if (this.records.has(id)) throw new Error(`test session "${id}" already added`)
362
+ const summary: SessionSummary = {
363
+ id,
364
+ displayTitle: fixture.id,
365
+ running: false,
366
+ blank: false,
367
+ updatedAt: this.records.size + 1,
368
+ ...fixture.summary,
369
+ retainedBy: this.retentionSnapshot(id).retainedBy,
370
+ }
371
+ const snapshot = createSnapshotStore<SessionFixtureSnapshot>({
372
+ ...sessionSnapshot(id),
373
+ ...fixture.snapshot,
374
+ })
375
+ const session = new FixtureSession(id, snapshot, fixture.session ?? {})
376
+ if (fixture.events !== undefined || fixture.hasMore === true) {
377
+ session.eventSource.replace(fixture.events ?? [], fixture.hasMore ?? false)
378
+ }
379
+ this.records.set(id, {
380
+ summary,
381
+ snapshot,
382
+ session,
383
+ overrides: fixture.session ?? {},
384
+ projections: new Map(),
385
+ initialOpen: fixture.initialOpen,
386
+ })
387
+ await this.stabilize(() => {
388
+ this.list.update((draft) => {
389
+ draft.ids.push(id)
390
+ draft.byId[id] = summary
391
+ })
392
+ })
393
+ return id
394
+ }
395
+
396
+ /**
397
+ * Update Session Controller lifecycle state through an immer draft.
398
+ * @param id - session id.
399
+ * @param mutate - draft mutator.
400
+ */
401
+ async updateSessionSnapshot(
402
+ id: string,
403
+ mutate: (draft: SessionFixtureSnapshot) => void,
404
+ ): Promise<void> {
405
+ const record = this.require(id)
406
+ await this.stabilize(() => {
407
+ record.snapshot.update(mutate)
408
+ this.generations.get(id as SessionId)?.snapshot.set(record.snapshot.getSnapshot())
409
+ })
410
+ }
411
+
412
+ /**
413
+ * Publish one complete projection value through the fixture Session face.
414
+ * @param id - session id.
415
+ * @param key - registered projection key.
416
+ * @param value - complete value for that key.
417
+ */
418
+ async setProjection(id: string, key: string, value: unknown): Promise<void> {
419
+ const record = this.require(id)
420
+ record.projections.set(key, value)
421
+ await this.stabilize(() => {
422
+ record.session.projections.set(key, value)
423
+ this.generations.get(id as SessionId)?.session.projections.set(key, value)
424
+ })
425
+ }
426
+
427
+ /**
428
+ * Replace a Session's complete contiguous event window.
429
+ * @param id - Session identity.
430
+ * @param entries - complete event window.
431
+ * @param hasMore - whether older history remains.
432
+ */
433
+ async replaceEvents(
434
+ id: string,
435
+ entries: readonly SessionEventLikeEntry[],
436
+ hasMore = false,
437
+ ): Promise<void> {
438
+ await this.stabilize(() => {
439
+ this.require(id).session.eventSource.replace(entries, hasMore)
440
+ this.generations.get(id as SessionId)?.session.eventSource.replace(entries, hasMore)
441
+ })
442
+ }
443
+
444
+ /**
445
+ * Prepend one older contiguous event page.
446
+ * @param id - Session identity.
447
+ * @param entries - older entries.
448
+ * @param hasMore - whether another older page remains.
449
+ */
450
+ async prependEvents(
451
+ id: string,
452
+ entries: readonly SessionEventLikeEntry[],
453
+ hasMore = false,
454
+ ): Promise<void> {
455
+ await this.stabilize(() => {
456
+ this.require(id).session.eventSource.prepend(entries, hasMore)
457
+ this.generations.get(id as SessionId)?.session.eventSource.prepend(entries, hasMore)
458
+ })
459
+ }
460
+
461
+ /**
462
+ * Append one live event to a Session's contiguous window.
463
+ * @param id - Session identity.
464
+ * @param entry - live event entry.
465
+ */
466
+ async appendEvent(id: string, entry: SessionLiveEventEntry): Promise<void> {
467
+ await this.stabilize(() => {
468
+ this.require(id).session.eventSource.append(entry)
469
+ this.generations.get(id as SessionId)?.session.eventSource.append(entry)
470
+ })
471
+ }
472
+
473
+ /**
474
+ * Update a session's list row (the wire-echo stand-in: title settles,
475
+ * running flips — components subscribed via useSessions re-render).
476
+ * @param id - session id.
477
+ * @param patch - summary fields to merge over the row.
478
+ */
479
+ async updateSummary(id: string, patch: Partial<Omit<SessionSummary, 'id'>>): Promise<void> {
480
+ const record = this.require(id)
481
+ record.summary = {
482
+ ...record.summary,
483
+ ...patch,
484
+ retainedBy: this.retentionSnapshot(id as SessionId).retainedBy,
485
+ }
486
+ await this.stabilize(() => {
487
+ this.list.update((draft) => { draft.byId[id as SessionId] = record.summary })
488
+ })
489
+ }
490
+
491
+ /**
492
+ * Remove a catalog row and mark its retained Session removed without releasing owners.
493
+ * @param id - session id.
494
+ */
495
+ async remove(id: string): Promise<void> {
496
+ this.require(id)
497
+ this.records.delete(id as SessionId)
498
+ await this.stabilize(() => {
499
+ this.list.update((draft) => {
500
+ draft.ids = draft.ids.filter(existing => existing !== id)
501
+ const { [id as SessionId]: _dead, ...rest } = draft.byId
502
+ draft.byId = rest
503
+ })
504
+ this.generations.get(id as SessionId)?.snapshot.update((draft) => { draft.removed = true })
505
+ })
506
+ }
507
+
508
+ /**
509
+ * Borrow the already-retained session-scoped Cordis context.
510
+ * @param id - session id.
511
+ * @returns the scoped context, or undefined without a live reference.
512
+ */
513
+ scope(id: string): AgentContext | undefined {
514
+ return this.generations.get(id as SessionId)?.binding.ctx
515
+ }
516
+
517
+ /**
518
+ * Session assembly binding (inject factories and provide resolvers receive it).
519
+ * @param id - session id.
520
+ * @returns the live generation's binding, or undefined without a reference.
521
+ */
522
+ binding(id: string): SessionBinding | undefined {
523
+ return this.generations.get(id as SessionId)?.binding
524
+ }
525
+
526
+ /* jscpd:ignore-start -- The fixture intentionally mirrors production SessionReference acquisition and release semantics. */
527
+ retain(
528
+ target: SessionTarget,
529
+ options: SessionRetainOptions = { source: 'testFixture' },
530
+ ): SessionReference {
531
+ const { source, signal } = options
532
+ signal?.throwIfAborted()
533
+ if (this.closed) throw new Error('test Session Controller is disposed')
534
+ const id = this.resolveTarget(target)
535
+ const generation = this.generations.get(id) ?? this.materialize(id, this.require(id))
536
+ const reference = this.retainGeneration(id, generation, source)
537
+ try {
538
+ reference.attachOpening(generation.opening, signal)
539
+ return reference
540
+ } catch (error: unknown) {
541
+ reference.release()
542
+ throw error
543
+ }
544
+ }
545
+
546
+ async using<T>(
547
+ target: SessionTarget,
548
+ options: SessionRetainOptions,
549
+ operation: (reference: SessionReference) => T | Promise<T>,
550
+ ): Promise<T> {
551
+ const reference = this.retain(target, options)
552
+ try {
553
+ await reference.ready
554
+ return await operation(reference)
555
+ } finally {
556
+ reference.release()
557
+ }
558
+ }
559
+ /* jscpd:ignore-end */
560
+
561
+ retainInfo(id: SessionId): ObservableSnapshot<SessionRetainInfo> {
562
+ let store = this.retentionStores.get(id)
563
+ if (store === undefined) {
564
+ store = createSnapshotStore(this.retentionSnapshot(id))
565
+ this.retentionStores.set(id, store)
566
+ }
567
+ return store
568
+ }
569
+
570
+ /**
571
+ * Retain one fixture Session until the supplied Cordis owner stops.
572
+ * @param ownerCtx - context whose disposal releases the reference.
573
+ * @param target - fixture Session identity or subagent address.
574
+ * @param options - reference source and optional readiness cancellation.
575
+ * @returns the owned reference immediately.
576
+ */
577
+ retainFor(
578
+ ownerCtx: Context,
579
+ target: SessionTarget,
580
+ options: SessionRetainOptions = { source: 'testFixture' },
581
+ ): SessionReference {
582
+ const reference = this.retain(target, options)
583
+ try {
584
+ ownerCtx.effect(() => () => { reference.release() }, 'test sessions: owned reference')
585
+ return reference
586
+ } catch (error: unknown) {
587
+ reference.release()
588
+ throw error
589
+ }
590
+ }
591
+
592
+ /**
593
+ * Read the session scope tag off a context (service-method boundary mirror).
594
+ * @param ctx - any client context.
595
+ * @returns the session id, or undefined on root contexts.
596
+ */
597
+ scopeOf(ctx: Context): SessionId | undefined {
598
+ return scopeOf(ctx)
599
+ }
600
+
601
+ /**
602
+ * Resolve the scoped session face off a context (production `sessionOf`
603
+ * mirror).
604
+ * @param ctx - any client context.
605
+ * @returns the fixture session face, or undefined off-scope.
606
+ */
607
+ sessionOf(ctx: Context): SessionFace | undefined {
608
+ const id = scopeOf(ctx)
609
+ if (id === undefined) return undefined
610
+ const generation = this.generations.get(id)
611
+ return generation !== undefined
612
+ && scopeIdentityOf(generation.binding.ctx) === scopeIdentityOf(ctx)
613
+ ? generation.session
614
+ : undefined
615
+ }
616
+
617
+ /**
618
+ * Install Session creation behavior for navigation tests.
619
+ * @param impl - implementation that must return an already-added fixture id.
620
+ */
621
+ stubCreate(impl: (opts: Parameters<ISessions['create']>[0]) => Promise<SessionId>): void {
622
+ this.createStub = impl
623
+ }
624
+
625
+ /** Create through the installed test behavior and require a catalogued fixture. */
626
+ async create(opts?: Parameters<ISessions['create']>[0]): Promise<SessionId> {
627
+ this.calls.push({ method: 'create', args: [opts] })
628
+ if (this.createStub === undefined) {
629
+ throw new Error('test sessions: create is not stubbed — call stubCreate() first')
630
+ }
631
+ const id = await this.createStub(opts)
632
+ this.require(id)
633
+ return id
634
+ }
635
+
636
+ /** Resolve a retained or catalog-derived address independently of a view. */
637
+ subagentAddress(id: SessionId): SubagentAddress | undefined {
638
+ const retained = this.addresses.get(id)
639
+ if (retained !== undefined) return retained
640
+ for (const [parentSessionId, projections] of Object.entries(this.list.getSnapshot().projectionsBySession)) {
641
+ const child = projections.values.subagentCatalog?.find(entry => entry.id === id)
642
+ if (child !== undefined && child.mode !== 'external') {
643
+ return { parentSessionId: parentSessionId as SessionId, childSessionId: id, mode: child.mode }
644
+ }
645
+ }
646
+ return undefined
647
+ }
648
+
649
+ /** Record a projection refresh; fixture callers drive snapshots explicitly. */
650
+ refreshProjections(sessionId: SessionId): Promise<void> {
651
+ this.calls.push({ method: 'refreshProjections', args: [sessionId] })
652
+ return Promise.resolve()
653
+ }
654
+
655
+ /** Record a list refresh; fixture callers publish list state explicitly. */
656
+ refresh(): Promise<void> {
657
+ this.calls.push({ method: 'refresh', args: [] })
658
+ return Promise.resolve()
659
+ }
660
+
661
+ /**
662
+ * Replace the sidebar-search result page (the call is still recorded).
663
+ * @param impl - hits for a query, as the Host would rank them.
664
+ */
665
+ stubSearch(impl: (query: string, signal: AbortSignal) => { items: SessionSearchResultItem[]; hasMore: boolean }): void {
666
+ this.searchStub = impl
667
+ }
668
+
669
+ /**
670
+ * Content search over the fixture corpus (recorded). The default answers an
671
+ * empty page: content ranking is Host behavior, so a scenario that asserts
672
+ * hits declares them through {@link TestSessions.stubSearch}.
673
+ * @param query - non-blank literal phrase.
674
+ * @param signal - cancellation for a superseded search (recorded and forwarded).
675
+ * @returns the stubbed or empty result page.
676
+ */
677
+ search(query: string, signal: AbortSignal): ReturnType<ISessions['search']> {
678
+ this.calls.push({ method: 'search', args: [query, signal] })
679
+ return Promise.resolve({ ok: true, value: this.searchStub?.(query, signal) ?? { items: [], hasMore: false } })
680
+ }
681
+
682
+ /**
683
+ * Recorded fork stub: no child materializes (benches asserting the full
684
+ * fork flow drive the production service; this face only proves the call).
685
+ * @param opts - source session id, optional cut anchor, and client title policy.
686
+ * @returns the source id (no child record is created).
687
+ */
688
+ fork(opts: Parameters<ISessions['fork']>[0]): Promise<SessionId> {
689
+ this.calls.push({ method: 'fork', args: [opts] })
690
+ return Promise.resolve(opts.sessionId)
691
+ }
692
+
693
+ /**
694
+ * The session face of a fixture (typed view for assertions; fixture
695
+ * behavior methods are grafted onto it).
696
+ * @param id - session id.
697
+ * @returns the FixtureSession carried by the Controller binding.
698
+ */
699
+ behavior(id: string): FixtureSession {
700
+ return this.generations.get(id as SessionId)?.session ?? this.require(id).session
701
+ }
702
+
703
+ /** Dispose minted scope fibers (runtime dispose path). */
704
+ async disposeScopes(): Promise<void> {
705
+ this.closed = true
706
+ for (const [id, generation] of this.generations) this.drop(id, generation)
707
+ await this.drainDrops()
708
+ }
709
+
710
+ private resolveTarget(target: SessionTarget): SessionId {
711
+ const id = typeof target === 'string' ? target : target.childSessionId
712
+ if (typeof target !== 'string') {
713
+ this.addresses.set(id, target)
714
+ }
715
+ this.require(id)
716
+ return id
717
+ }
718
+
719
+ private retainGeneration(
720
+ id: SessionId,
721
+ generation: SessionGeneration,
722
+ source: SessionReferenceSource,
723
+ ): TestSessionReference {
724
+ const previous = generation.retention
725
+ generation.retention = Object.freeze({
726
+ referenceCount: previous.referenceCount + 1,
727
+ retainedBy: freezeRetainedBy({
728
+ ...previous.retainedBy,
729
+ [source]: (previous.retainedBy[source] ?? 0) + 1,
730
+ }),
731
+ })
732
+ const reference = new TestSessionReference(id, generation, () => {
733
+ if (!generation.live) return
734
+ const count = generation.retention.referenceCount - 1
735
+ const { [source]: sourceCount = 0, ...otherSources } = generation.retention.retainedBy
736
+ const retainedBy = sourceCount > 1
737
+ ? { ...otherSources, [source]: sourceCount - 1 }
738
+ : otherSources
739
+ generation.retention = count === 0
740
+ ? EMPTY_RETAIN_INFO
741
+ : Object.freeze({ referenceCount: count, retainedBy: freezeRetainedBy(retainedBy) })
742
+ if (count === 0) this.drop(id, generation)
743
+ else this.publishRetention(id)
744
+ })
745
+ this.publishRetention(id)
746
+ return reference
747
+ }
748
+
749
+ private retentionSnapshot(id: SessionId): SessionRetainInfo {
750
+ return this.generations.get(id)?.retention ?? EMPTY_RETAIN_INFO
751
+ }
752
+
753
+ private publishRetention(id: SessionId): void {
754
+ const retention = this.retentionSnapshot(id)
755
+ const store = this.retentionStores.get(id)
756
+ if (store !== undefined && store.getSnapshot() !== retention) store.set(retention)
757
+ const state = this.list.getSnapshot()
758
+ const row = state.byId[id]
759
+ if (row === undefined || row.retainedBy === retention.retainedBy) return
760
+ const summary = { ...row, retainedBy: retention.retainedBy }
761
+ const record = this.records.get(id)
762
+ /* v8 ignore next -- a catalog row and its fixture record are inserted and removed together. */
763
+ if (record !== undefined) record.summary = summary
764
+ this.list.set({ ...state, byId: { ...state.byId, [id]: summary } })
765
+ }
766
+
767
+ private materialize(id: SessionId, fixture: SessionRecord): SessionGeneration {
768
+ const { ctx, fiber } = createScope(this.rootCtx, id)
769
+ const snapshot = createSnapshotStore(fixture.snapshot.getSnapshot())
770
+ const session = new FixtureSession(id, snapshot, fixture.overrides)
771
+ const window = fixture.session.eventSource.getSnapshot()
772
+ session.eventSource.replace(window.entries, window.hasMore)
773
+ for (const [key, value] of fixture.projections) session.projections.set(key, value)
774
+ const opening = Promise.withResolvers<void>()
775
+ void opening.promise.catch(() => {})
776
+ const lifetime = new AbortController()
777
+ const generation: SessionGeneration = {
778
+ binding: { sessionId: id, session, eventSource: session.eventSource, ctx },
779
+ snapshot,
780
+ session,
781
+ fiber,
782
+ lifetime,
783
+ opening: opening.promise,
784
+ retention: EMPTY_RETAIN_INFO,
785
+ live: true,
786
+ }
787
+ this.generations.set(id, generation)
788
+ ctx.effect(() => async () => {
789
+ if (generation.live) {
790
+ generation.live = false
791
+ generation.retention = EMPTY_RETAIN_INFO
792
+ if (this.generations.get(id) === generation) this.generations.delete(id)
793
+ this.publishRetention(id)
794
+ }
795
+ lifetime.abort(new Error(`test Session generation "${id}" is disposed`))
796
+ await Promise.allSettled([generation.opening])
797
+ }, 'test sessions: exact generation')
798
+ this.startOpening(fixture.initialOpen, lifetime.signal, opening)
799
+ return generation
800
+ }
801
+
802
+ private startOpening(
803
+ initialOpen: SessionFixture['initialOpen'],
804
+ signal: AbortSignal,
805
+ opening: OpeningControl,
806
+ ): void {
807
+ try {
808
+ Promise.resolve(initialOpen?.(signal)).then(opening.resolve, opening.reject)
809
+ } catch (error: unknown) {
810
+ opening.reject(error)
811
+ }
812
+ }
813
+
814
+ private drop(id: SessionId, generation: SessionGeneration): void {
815
+ /* v8 ignore next -- only the live generation's retained callback can enter drop. */
816
+ if (!generation.live) return
817
+ generation.live = false
818
+ generation.retention = EMPTY_RETAIN_INFO
819
+ /* v8 ignore next -- this synchronous path drops only the generation currently stored for id. */
820
+ if (this.generations.get(id) === generation) this.generations.delete(id)
821
+ generation.lifetime.abort(new Error(`test Session generation "${id}" is released`))
822
+ this.publishRetention(id)
823
+ const disposal = generation.fiber.dispose()
824
+ this.pendingDrops.add(disposal)
825
+ void disposal.then(
826
+ () => { this.pendingDrops.delete(disposal) },
827
+ (error: unknown) => {
828
+ this.pendingDrops.delete(disposal)
829
+ this.rootCtx.logger.warn('test Session scope disposal failed:', error)
830
+ },
831
+ )
832
+ }
833
+
834
+ private async drainDrops(): Promise<void> {
835
+ while (this.pendingDrops.size !== 0) await Promise.all([...this.pendingDrops])
836
+ }
837
+
838
+ private require(id: string): SessionRecord {
839
+ const record = this.records.get(id as SessionId)
840
+ if (record === undefined) throw new Error(`test session "${id}" is not added`)
841
+ return record
842
+ }
843
+
844
+ }