fake-api.client.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. // Test-local programmable IApiClient fake (NOT the fixture: fixture is a demo
  2. // data source on a real clock; behavior tests need per-case responses and
  3. // deferred-controlled timing). Session streams are hand pumps: pushFollow/pushControl.
  4. import type {
  5. IApiClient,
  6. RpcError, RpcResponse, SessionId, SessionSearchItem, SkillEntry,
  7. WorkspaceId, WorkspaceView,
  8. } from '@deepseek-ai/dsh-api-remotes/client'
  9. import type {
  10. SessionAddress,
  11. SessionControlBaseline,
  12. SessionControlFrame,
  13. SessionFollowFrame,
  14. SessionFollowRequest,
  15. SessionPage,
  16. SessionPageRequest,
  17. SessionProjectionBaseline,
  18. SessionSelectModelRequest,
  19. SessionSelectModelValue,
  20. } from '@deepseek-ai/dsh-api-session-controller/types'
  21. import type { WorkspaceRemote } from '@deepseek-ai/dsh-api-workspace-controller/client'
  22. import type { WorkspaceFollowFrame } from '@deepseek-ai/dsh-api-workspace-controller/types'
  23. import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
  24. import {
  25. RemoteStream,
  26. RemoteStreamError,
  27. type RemoteStreamOptions,
  28. } from '@deepseek-ai/dsh-api-gateway/client'
  29. import { RpcId } from '@deepseek-ai/dsh-client-connection/client'
  30. import type { SessionRemotes } from '../src/client/sessions/remotes.ts'
  31. import { historyRecordLastSeq } from '../src/client/sessions/history-records.ts'
  32. const AVAILABLE_STREAM_CONNECTION = {
  33. hostDescription: {
  34. getSnapshot: () => ({
  35. version: 'fixture', cwd: '/f', attachedSessions: 0, home: '/h', canOpenPath: true,
  36. }),
  37. subscribe: () => () => {},
  38. },
  39. }
  40. /** Programmable-default workspace row (branded id, ISO-ish times). */
  41. function fakeWorkspace(id: string, over: Partial<WorkspaceView> = {}): WorkspaceView {
  42. return {
  43. workspaceId: id as WorkspaceId,
  44. path: '/f/ws',
  45. title: 'ws',
  46. sessionIds: [],
  47. createdAt: '2026-01-01T00:00:00.000Z',
  48. updatedAt: '2026-01-01T00:00:00.000Z',
  49. ...over,
  50. }
  51. }
  52. function addressSessionId(address: SessionAddress): SessionId {
  53. return address.kind === 'session' ? address.sessionId : address.childSessionId
  54. }
  55. export interface Deferred<T> {
  56. promise: Promise<T>
  57. resolve(value: T): void
  58. reject(error: unknown): void
  59. }
  60. /** Test-held settlement: the case decides when an RPC lands (history-pending injections etc.). */
  61. export function deferred<T>(): Deferred<T> {
  62. let resolve!: (value: T) => void
  63. let reject!: (error: unknown) => void
  64. const promise = new Promise<T>((res, rej) => {
  65. resolve = res
  66. reject = rej
  67. })
  68. return { promise, resolve, reject }
  69. }
  70. let nextRpc = 0
  71. export function ok<T>(value: T): RpcResponse<T> {
  72. return { rpcId: RpcId(`fake-${nextRpc++}`), result: { ok: true, value } }
  73. }
  74. export function err<T>(error: RpcError): RpcResponse<T> {
  75. return { rpcId: RpcId(`fake-${nextRpc++}`), result: { ok: false, error } }
  76. }
  77. /** Successful generated Remote result for programmable domain fakes. */
  78. function remoteOk<T>(value: T): RemoteResult<T> {
  79. return { ok: true, value }
  80. }
  81. type ValueStreamItem<F> =
  82. | { kind: 'frame'; value: F; delivered?: () => void }
  83. | { kind: 'end' }
  84. | { kind: 'fail'; error: unknown }
  85. interface ValueStreamConn<F> {
  86. feed(item: ValueStreamItem<F>): void
  87. }
  88. interface OpenValueStream<F> {
  89. readonly values: AsyncGenerator<F>
  90. dispose(): void
  91. }
  92. /**
  93. * Commands Remote double: the generated face delivers the carrier's outcome, so
  94. * a test that programs nothing sees an empty catalog and an unmatched line.
  95. * @returns the Remote namespaces the session cluster calls.
  96. */
  97. export type RuntimeRemotes = SessionRemotes & { readonly workspace: WorkspaceRemote }
  98. export function fakeRemote(api = new FakeApiClient()): RuntimeRemotes {
  99. return api.sessionRemotes()
  100. }
  101. export class FakeApiClient implements IApiClient {
  102. /** Chronological call record: [method, payload]. */
  103. readonly calls: { method: string; payload: unknown }[] = []
  104. /** Session ids in physical follow-generation opening order. */
  105. readonly followStarts: SessionId[] = []
  106. // Programmable slots (defaults answer OK-empty); reassign per case.
  107. onList: (payload: unknown) => Promise<RpcResponse<{ items: never[] }>> = () => Promise.resolve(ok({ items: [] }))
  108. onSearch: (payload: unknown) => Promise<RpcResponse<{ items: SessionSearchItem[]; hasMore: boolean }>> =
  109. () => Promise.resolve(ok({ items: [], hasMore: false }))
  110. onCreate: (payload: unknown) => Promise<RpcResponse<{ sessionId: SessionId }>> = () => Promise.resolve(ok({ sessionId: 'fk-new' as SessionId }))
  111. onSelectModel: (payload: SessionSelectModelRequest) => Promise<RpcResponse<SessionSelectModelValue>> =
  112. payload => Promise.resolve(ok({
  113. selected: {
  114. provider: payload.provider,
  115. model: payload.model,
  116. ...(payload.reasoningEffort === undefined
  117. ? {}
  118. : { reasoningEffort: payload.reasoningEffort }),
  119. },
  120. }))
  121. onRename: (payload: unknown) => Promise<RpcResponse<{ title: string; seq: number }>> = () => Promise.resolve(ok({ title: 'fk-renamed', seq: 0 }))
  122. onFork: (payload: unknown) => Promise<RpcResponse<{ sessionId: SessionId }>> = () => Promise.resolve(ok({ sessionId: 'fk-fork' as SessionId }))
  123. onHistory: (payload: { sessionId: SessionId; throughSeq?: number; beforeSeq?: number; maxMessages?: number })
  124. => Promise<RpcResponse<SessionPage & { readonly projections?: SessionProjectionBaseline }>> =
  125. () => Promise.resolve(ok({ records: [], hasMore: false }))
  126. onPrompt: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  127. onAttachment: (payload: unknown) => Promise<RpcResponse<{ attachment: { attachmentId: never; mediaType: 'image/png'; bytes: number; width: number; height: number }; data: string }>> =
  128. () => Promise.resolve(ok({ attachment: { attachmentId: 'a' as never, mediaType: 'image/png', bytes: 1, width: 1, height: 1 }, data: 'AA==' }))
  129. onUpdateQueue: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  130. onCancel: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  131. onDescribe: (payload: unknown) => Promise<RpcResponse<{
  132. version: string
  133. cwd: string
  134. attachedSessions: number
  135. home: string
  136. canOpenPath: boolean
  137. }>> =
  138. () => Promise.resolve(ok({
  139. version: '0-fake', cwd: '/f', attachedSessions: 0, home: '/h', canOpenPath: true,
  140. }))
  141. onPickDirectory: (payload: unknown) => Promise<RpcResponse<{ path: string | null }>> =
  142. () => Promise.resolve(ok({ path: null }))
  143. onOpenPath: (payload: unknown) => Promise<RpcResponse<{ opened: true }>> =
  144. () => Promise.resolve(ok({ opened: true as const }))
  145. onListDirectory: (payload: unknown) => Promise<RpcResponse<{
  146. path: string
  147. home: string
  148. crumbs: { name: string; path: string; hidden: boolean }[]
  149. entries: { name: string; path: string; hidden: boolean }[]
  150. truncated: boolean
  151. }>> =
  152. () => Promise.resolve(ok({ path: '/home/fake', home: '/home/fake', crumbs: [{ name: '/', path: '/', hidden: false }], entries: [], truncated: false }))
  153. onCreateDirectory: (payload: unknown) => Promise<RpcResponse<{ path: string }>> =
  154. () => Promise.resolve(ok({ path: '/home/fake/new' }))
  155. private readonly followConns = new Map<SessionId, ValueStreamConn<SessionFollowFrame>[]>()
  156. private readonly controlConns: ValueStreamConn<SessionControlFrame>[] = []
  157. private readonly workspaceConns: ValueStreamConn<WorkspaceFollowFrame>[] = []
  158. /** Optional Host opening cursor override for stale-page and reconnect tests. */
  159. followCursor: number | undefined
  160. controlBaseline: SessionControlBaseline = {
  161. queues: {},
  162. jobs: {},
  163. projections: {},
  164. }
  165. workspaceBaseline: Extract<WorkspaceFollowFrame, { type: 'baseline' }>['value'] = {
  166. items: [],
  167. archivedSessionIds: [],
  168. }
  169. lastSearchSignal: AbortSignal | undefined
  170. onSubagentList: (payload: unknown) => Promise<RpcResponse<{ entries: never[]; parentAvailable: boolean }>>
  171. = () => Promise.resolve(ok({ entries: [], parentAvailable: true }))
  172. onSubagentPrompt: (payload: unknown) => Promise<RpcResponse<{ messageId: never }>>
  173. = () => Promise.resolve(ok({ messageId: 'fake-message' as never }))
  174. onSubagentInterrupt: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>>
  175. = () => Promise.resolve(ok({ accepted: true as const }))
  176. readonly subagents: IApiClient['subagents'] = {
  177. list: (payload: unknown) => this.record('subagent.list', payload, this.onSubagentList(payload)),
  178. prompt: (payload: unknown) => this.record('subagent.prompt', payload, this.onSubagentPrompt(payload)),
  179. interrupt: (payload: unknown) => this.record('subagent.interrupt', payload, this.onSubagentInterrupt(payload)),
  180. }
  181. readonly host: IApiClient['host'] = {
  182. describe: (payload: unknown) => this.record('host.describe', payload, this.onDescribe(payload)),
  183. pickDirectory: (payload: unknown) => this.record('host.pickDirectory', payload, this.onPickDirectory(payload)),
  184. listDirectory: (payload: unknown) => this.record('host.listDirectory', payload, this.onListDirectory(payload)),
  185. createDirectory: (payload: unknown) => this.record('host.createDirectory', payload, this.onCreateDirectory(payload)),
  186. openPath: (payload: unknown) => this.record('host.openPath', payload, this.onOpenPath(payload)),
  187. }
  188. onWorkspaceCreate: (payload: unknown) => Promise<RemoteResult<{ workspace: WorkspaceView; created: boolean }>> =
  189. () => Promise.resolve(remoteOk({ workspace: fakeWorkspace('fk-ws'), created: true }))
  190. onWorkspaceRename: (payload: unknown) => Promise<RemoteResult<{ workspace: WorkspaceView }>> =
  191. () => Promise.resolve(remoteOk({ workspace: fakeWorkspace('fk-ws') }))
  192. onWorkspaceDelete: (payload: unknown) => Promise<RemoteResult<{ deleted: true }>> =
  193. () => Promise.resolve(remoteOk({ deleted: true }))
  194. onWorkspaceInsertBefore: (payload: unknown) => Promise<RemoteResult<{ workspaceIds: WorkspaceId[] }>> =
  195. () => Promise.resolve(remoteOk({ workspaceIds: [] }))
  196. onWorkspaceInsertSessionBefore: (payload: unknown) => Promise<RemoteResult<{ workspace: WorkspaceView }>> =
  197. () => Promise.resolve(remoteOk({ workspace: fakeWorkspace('fk-ws') }))
  198. onWorkspaceArchiveSession: (payload: unknown) => Promise<RemoteResult<{ archivedSessionIds: SessionId[] }>> =
  199. payload => Promise.resolve(remoteOk({ archivedSessionIds: [(payload as { sessionId: SessionId }).sessionId] }))
  200. // Payloads stay `unknown` (lint-lane note above); response rows are the real
  201. // wire shapes so cases can program requires-bearing catalogs and dual-address
  202. // skill lists without casts.
  203. onSkillList: (payload: unknown) => Promise<RpcResponse<{ skills: SkillEntry[] }>>
  204. = () => Promise.resolve(ok({ skills: [] }))
  205. readonly agentPresets: IApiClient['agentPresets'] = {
  206. list: (payload: unknown) => this.record('agentPreset.list', payload, Promise.resolve(ok({ presets: [], authorable: false, hasDocument: false }))),
  207. select: (payload: { agentPreset: string }) =>
  208. this.record('agentPreset.select', payload, Promise.resolve(ok({ agentPreset: payload.agentPreset }))),
  209. read: (payload: { agentPreset: string }) =>
  210. this.record('agentPreset.read', payload, Promise.resolve(ok({
  211. agentPreset: payload.agentPreset, trust: 'user' as const, content: '',
  212. }))),
  213. copy: (payload: { agentPreset: string }) =>
  214. this.record('agentPreset.copy', payload, Promise.resolve(ok({ agentPreset: payload.agentPreset }))),
  215. openDocument: (payload: { agentPreset: string }) =>
  216. this.record('agentPreset.openDocument', payload, Promise.resolve(ok({ opened: true as const }))),
  217. remove: (payload: { agentPreset: string }) =>
  218. this.record('agentPreset.remove', payload, Promise.resolve(ok({}))),
  219. }
  220. readonly skills: IApiClient['skills'] = {
  221. list: (payload: unknown) => this.record('skill.list', payload, this.onSkillList(payload)),
  222. }
  223. readonly goals: IApiClient['goals'] = {
  224. create: payload => this.record('goal.create', payload, Promise.resolve(ok({ ref: { id: 'fake-goal' as never, revision: 1 } }))),
  225. edit: payload => this.record('goal.edit', payload, Promise.resolve(ok({ ref: { id: 'fake-goal' as never, revision: 1 } }))),
  226. pause: payload => this.record('goal.pause', payload, Promise.resolve(ok({ ref: { id: 'fake-goal' as never, revision: 1 } }))),
  227. resume: payload => this.record('goal.resume', payload, Promise.resolve(ok({ ref: { id: 'fake-goal' as never, revision: 1 } }))),
  228. complete: payload => this.record('goal.complete', payload, Promise.resolve(ok({ ref: { id: 'fake-goal' as never, revision: 1 } }))),
  229. clear: payload => this.record('goal.clear', payload, Promise.resolve(ok({ cleared: true as const }))),
  230. }
  231. readonly settings: IApiClient['settings'] = {
  232. describe: payload => this.record('settings.describe', payload, Promise.resolve(ok({ writable: true, hasDocument: false, namespaces: [] }))),
  233. openDocument: payload => this.record('settings.openDocument', payload, Promise.resolve(ok({ opened: true as const }))),
  234. update: payload => this.record('settings.update', payload, Promise.resolve(ok({ ns: 'fake', schema: {}, value: {}, applies: 'live' as const, secrets: [], revision: 0 }))),
  235. replace: payload => this.record('settings.replace', payload, Promise.resolve(ok({ ns: 'fake', schema: {}, value: {}, applies: 'live' as const, secrets: [], revision: 0 }))),
  236. mutate: payload => this.record('settings.mutate', payload, Promise.resolve(ok({ ns: 'fake', schema: {}, value: {}, applies: 'live' as const, secrets: [], revision: 0 }))),
  237. }
  238. readonly credentials: IApiClient['credentials'] = {
  239. describe: payload => this.record('credentials.describe', payload, Promise.resolve(ok({ credentials: {} }))),
  240. set: payload => this.record('credentials.set', payload, Promise.resolve(ok({}))),
  241. unset: payload => this.record('credentials.unset', payload, Promise.resolve(ok({}))),
  242. }
  243. readonly llm: IApiClient['llm'] = {
  244. providers: payload => this.record('llm.providers', payload, Promise.resolve(ok({ providers: [] }))),
  245. models: payload => this.record('llm.models', payload, Promise.resolve(ok({
  246. default: { provider: 'fixture', model: 'fixture' },
  247. routableProviders: [],
  248. groups: [],
  249. failures: [],
  250. }))),
  251. discoverModels: payload => this.record('llm.discoverModels', payload, Promise.resolve(ok({ models: [] }))),
  252. }
  253. /** Remote namespaces bound to this fake's programmable unary slots and stream pumps. */
  254. sessionRemotes(): RuntimeRemotes {
  255. return {
  256. $stream: <Item>(options: RemoteStreamOptions<Item>) => (
  257. new RemoteStream(AVAILABLE_STREAM_CONNECTION, options)
  258. ),
  259. commands: {
  260. execute: () => Promise.resolve({ ok: true, value: undefined }),
  261. },
  262. session: {
  263. list: payload => this.remoteResult('session.list', payload, this.onList(payload)),
  264. search: (payload, signal) => {
  265. this.lastSearchSignal = signal
  266. return this.remoteResult('session.search', payload, this.onSearch(payload))
  267. },
  268. create: payload => this.remoteResult('session.create', payload, this.onCreate(payload)),
  269. selectModel: payload => this.remoteResult(
  270. 'session.selectModel',
  271. payload,
  272. this.onSelectModel(payload),
  273. ),
  274. rename: payload => this.remoteResult('session.rename', payload, this.onRename(payload)),
  275. fork: payload => this.remoteResult('session.fork', payload, this.onFork(payload)),
  276. prompt: payload => this.remoteResult('session.prompt', payload, this.onPrompt(payload)),
  277. attachment: payload => this.remoteResult('session.attachment', payload, this.onAttachment(payload)),
  278. updateQueue: payload => this.remoteResult('session.updateQueue', payload, this.onUpdateQueue(payload)),
  279. cancel: payload => this.remoteResult('session.cancel', payload, this.onCancel(payload)),
  280. page: request => this.page(request),
  281. follow: (request, signal) => this.openFollow(request, signal),
  282. control: signal => this.openControl(signal),
  283. },
  284. workspace: {
  285. create: payload => this.record('workspace.create', payload, this.onWorkspaceCreate(payload)),
  286. rename: payload => this.record('workspace.rename', payload, this.onWorkspaceRename(payload)),
  287. delete: payload => this.record('workspace.delete', payload, this.onWorkspaceDelete(payload)),
  288. insertBefore: payload => this.record(
  289. 'workspace.insertBefore',
  290. payload,
  291. this.onWorkspaceInsertBefore(payload),
  292. ),
  293. insertSessionBefore: payload => this.record(
  294. 'workspace.insertSessionBefore',
  295. payload,
  296. this.onWorkspaceInsertSessionBefore(payload),
  297. ),
  298. archiveSession: payload => this.record(
  299. 'workspace.archiveSession',
  300. payload,
  301. this.onWorkspaceArchiveSession(payload),
  302. ),
  303. follow: signal => this.openWorkspace(signal),
  304. },
  305. }
  306. }
  307. /** Push one live Session event to every follower of that Session. */
  308. async pushFollow(
  309. sessionId: SessionId,
  310. frame: Extract<SessionFollowFrame, { type: 'event' }>,
  311. ): Promise<void> {
  312. await Promise.all([...(this.followConns.get(sessionId) ?? [])].map(conn => new Promise<void>((resolve) => {
  313. conn.feed({ kind: 'frame', value: frame, delivered: resolve })
  314. })))
  315. }
  316. /** Push one Host-wide control update. */
  317. pushControl(frame: Exclude<SessionControlFrame, { type: 'baseline' }>): void {
  318. for (const conn of [...this.controlConns]) conn.feed({ kind: 'frame', value: frame })
  319. }
  320. /** Push one Workspace projection increment. */
  321. pushWorkspace(frame: Exclude<WorkspaceFollowFrame, { type: 'baseline' }>): void {
  322. for (const conn of [...this.workspaceConns]) conn.feed({ kind: 'frame', value: frame })
  323. }
  324. /** End (clean close) or fail (throw) every open stream — reconnect-path material. */
  325. endStreams(): void {
  326. for (const conns of this.followConns.values()) {
  327. for (const conn of [...conns]) conn.feed({ kind: 'end' })
  328. }
  329. for (const conn of [...this.controlConns]) conn.feed({ kind: 'end' })
  330. for (const conn of [...this.workspaceConns]) conn.feed({ kind: 'end' })
  331. }
  332. failStreams(error: unknown): void {
  333. for (const conns of this.followConns.values()) {
  334. for (const conn of [...conns]) conn.feed({ kind: 'fail', error })
  335. }
  336. for (const conn of [...this.controlConns]) conn.feed({ kind: 'fail', error })
  337. for (const conn of [...this.workspaceConns]) conn.feed({ kind: 'fail', error })
  338. }
  339. callsOf(method: string): unknown[] {
  340. return this.calls.filter(c => c.method === method).map(c => c.payload)
  341. }
  342. /** Number of currently attached journal generations for one Session. */
  343. activeFollows(sessionId: SessionId): number {
  344. return this.followConns.get(sessionId)?.length ?? 0
  345. }
  346. private record<T>(method: string, payload: unknown, response: Promise<T>): Promise<T> {
  347. this.calls.push({ method, payload })
  348. return response
  349. }
  350. private async remoteResult<T>(
  351. method: string,
  352. payload: unknown,
  353. response: Promise<RpcResponse<T>>,
  354. ): Promise<RemoteResult<T>> {
  355. return (await this.record(method, payload, response)).result
  356. }
  357. private page(request: SessionPageRequest): Promise<RemoteResult<SessionPage>> {
  358. return this.fetchPage(request)
  359. }
  360. private async fetchPage(
  361. request: SessionPageRequest,
  362. response?: Promise<RpcResponse<SessionPage>>,
  363. ): Promise<RemoteResult<SessionPage>> {
  364. const sessionId = addressSessionId(request.address)
  365. const payload = request.address.kind === 'session'
  366. ? {
  367. sessionId,
  368. throughSeq: request.throughSeq,
  369. ...request.beforeSeq === undefined ? {} : { beforeSeq: request.beforeSeq },
  370. ...request.maxMessages === undefined ? {} : { maxMessages: request.maxMessages },
  371. }
  372. : {
  373. parentSessionId: request.address.parentSessionId,
  374. childSessionId: request.address.childSessionId,
  375. mode: request.address.mode,
  376. throughSeq: request.throughSeq,
  377. ...request.beforeSeq === undefined ? {} : { beforeSeq: request.beforeSeq },
  378. ...request.maxMessages === undefined ? {} : { maxMessages: request.maxMessages },
  379. }
  380. const method = request.address.kind === 'session' ? 'session.history' : 'subagent.history'
  381. const result = await this.remoteResult(method, payload, response ?? this.onHistory({
  382. sessionId,
  383. throughSeq: request.throughSeq,
  384. ...request.beforeSeq === undefined ? {} : { beforeSeq: request.beforeSeq },
  385. ...request.maxMessages === undefined ? {} : { maxMessages: request.maxMessages },
  386. }))
  387. if (!result.ok) return result
  388. return {
  389. ok: true,
  390. value: {
  391. ...result.value,
  392. records: result.value.records
  393. .filter(record => historyRecordLastSeq(record) <= request.throughSeq),
  394. },
  395. }
  396. }
  397. private async *openFollow(
  398. request: SessionFollowRequest,
  399. signal: AbortSignal = new AbortController().signal,
  400. ): AsyncGenerator<SessionFollowFrame> {
  401. const sessionId = addressSessionId(request.address)
  402. this.followStarts.push(sessionId)
  403. this.calls.push({ method: 'session.follow', payload: request })
  404. const conns = this.followConns.get(sessionId) ?? []
  405. if (!this.followConns.has(sessionId)) this.followConns.set(sessionId, conns)
  406. const stream = this.openValueStream(conns, signal)
  407. try {
  408. const response = await this.onHistory({
  409. sessionId,
  410. maxMessages: request.maxMessages ?? 50,
  411. })
  412. if (!response.result.ok) {
  413. throw new RemoteStreamError(
  414. response.result.error.code,
  415. response.result.error.message,
  416. response.result.error.details,
  417. )
  418. }
  419. const page = response.result.value
  420. const tail = page.records.at(-1)
  421. const cursor = this.followCursor ?? (tail === undefined ? -1 : historyRecordLastSeq(tail))
  422. yield {
  423. type: 'snapshot',
  424. header: {
  425. version: 0,
  426. id: sessionId,
  427. createdAt: 0,
  428. ...(request.address.kind === 'subagent'
  429. ? { origin: 'subagent' as const, parentSession: request.address.parentSessionId }
  430. : {}),
  431. },
  432. cursor,
  433. records: page.records.filter(record => historyRecordLastSeq(record) <= cursor),
  434. hasMore: page.hasMore,
  435. projections: page.projections ?? { asOfSeq: cursor, values: {} },
  436. }
  437. yield* stream.values
  438. } finally {
  439. stream.dispose()
  440. }
  441. }
  442. private async *openControl(
  443. signal: AbortSignal = new AbortController().signal,
  444. ): AsyncGenerator<SessionControlFrame> {
  445. const stream = this.openValueStream(this.controlConns, signal)
  446. try {
  447. yield { type: 'baseline', value: this.controlBaseline }
  448. yield* stream.values
  449. } finally {
  450. stream.dispose()
  451. }
  452. }
  453. private async *openWorkspace(
  454. signal: AbortSignal = new AbortController().signal,
  455. ): AsyncGenerator<WorkspaceFollowFrame> {
  456. const stream = this.openValueStream(this.workspaceConns, signal)
  457. try {
  458. yield { type: 'baseline', value: this.workspaceBaseline }
  459. yield* stream.values
  460. } finally {
  461. stream.dispose()
  462. }
  463. }
  464. private openValueStream<F>(
  465. registry: ValueStreamConn<F>[],
  466. signal: AbortSignal,
  467. ): OpenValueStream<F> {
  468. const inbox: ValueStreamItem<F>[] = []
  469. let wake: (() => void) | null = null
  470. let inFlightDelivered: (() => void) | undefined
  471. let disposed = false
  472. const conn: ValueStreamConn<F> = {
  473. feed: (item) => {
  474. inbox.push(item)
  475. wake?.()
  476. },
  477. }
  478. registry.push(conn)
  479. const dispose = (): void => {
  480. if (disposed) return
  481. disposed = true
  482. inFlightDelivered?.()
  483. for (const item of inbox) {
  484. if (item.kind === 'frame') item.delivered?.()
  485. }
  486. const index = registry.indexOf(conn)
  487. if (index >= 0) registry.splice(index, 1)
  488. wake?.()
  489. }
  490. const values = (async function* (): AsyncGenerator<F> {
  491. try {
  492. while (!signal.aborted && !disposed) {
  493. while (inbox.length > 0) {
  494. const item = inbox.shift() as ValueStreamItem<F>
  495. if (item.kind === 'end') return
  496. if (item.kind === 'fail') throw item.error
  497. inFlightDelivered = item.delivered
  498. yield item.value
  499. inFlightDelivered?.()
  500. inFlightDelivered = undefined
  501. }
  502. await new Promise<void>((resolve) => {
  503. wake = resolve
  504. signal.addEventListener('abort', () => { resolve() }, { once: true })
  505. })
  506. wake = null
  507. }
  508. } finally {
  509. dispose()
  510. }
  511. })()
  512. return { values, dispose }
  513. }
  514. }