fake-api.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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). Streams are hand pumps: pushMux/pushHost.
  4. import type {
  5. ClientResponse, CommandDescriptor, CommandExecuteResult, HostFrame, IApiClient, MuxFrame,
  6. RpcError, RpcReceipt, RpcRequest, RpcResponse, SessionId, SkillEntry,
  7. WorkspaceId, WorkspaceView,
  8. } from '@deepseek-ai/dsh-client-connection/client'
  9. import { RpcId } from '@deepseek-ai/dsh-client-connection/client'
  10. /** Programmable-default workspace row (branded id, ISO-ish times). */
  11. function fakeWorkspace(id: string, over: Partial<WorkspaceView> = {}): WorkspaceView {
  12. return {
  13. workspaceId: id as WorkspaceId,
  14. path: '/f/ws',
  15. title: 'ws',
  16. sessionIds: [],
  17. createdAt: '2026-01-01T00:00:00.000Z',
  18. updatedAt: '2026-01-01T00:00:00.000Z',
  19. ...over,
  20. }
  21. }
  22. export interface Deferred<T> {
  23. promise: Promise<T>
  24. resolve(value: T): void
  25. reject(error: unknown): void
  26. }
  27. /** Test-held settlement: the case decides when an RPC lands (history-pending injections etc.). */
  28. export function deferred<T>(): Deferred<T> {
  29. let resolve!: (value: T) => void
  30. let reject!: (error: unknown) => void
  31. const promise = new Promise<T>((res, rej) => {
  32. resolve = res
  33. reject = rej
  34. })
  35. return { promise, resolve, reject }
  36. }
  37. let nextRpc = 0
  38. export function ok<T>(value: T): RpcResponse<T> {
  39. return { rpcId: RpcId(`fake-${nextRpc++}`), result: { ok: true, value } }
  40. }
  41. export function err<T>(error: RpcError): RpcResponse<T> {
  42. return { rpcId: RpcId(`fake-${nextRpc++}`), result: { ok: false, error } }
  43. }
  44. type StreamItem<F> = { kind: 'frame'; envelope: RpcRequest<F> } | { kind: 'end' } | { kind: 'fail'; error: unknown }
  45. interface StreamConn<F> {
  46. feed(item: StreamItem<F>): void
  47. }
  48. export class FakeApiClient implements IApiClient {
  49. /** Chronological call record: [method, payload]. */
  50. readonly calls: { method: string; payload: unknown }[] = []
  51. // Programmable slots (defaults answer OK-empty); reassign per case.
  52. onList: (payload: unknown) => Promise<RpcResponse<{ items: never[] }>> = () => Promise.resolve(ok({ items: [] }))
  53. onCreate: (payload: unknown) => Promise<RpcResponse<{ sessionId: SessionId }>> = () => Promise.resolve(ok({ sessionId: 'fk-new' as SessionId }))
  54. onHistory: (payload: { sessionId: SessionId; beforeSeq?: number; maxMessages?: number })
  55. => Promise<RpcResponse<{ events: never[]; hasMore: boolean; todos?: { content: string; status: 'pending' | 'in_progress' | 'completed' }[] }>> =
  56. () => Promise.resolve(ok({ events: [], hasMore: false }))
  57. onPrompt: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  58. onCancel: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  59. onDescribe: (payload: unknown) => Promise<RpcResponse<{ version: string; cwd: string; attachedSessions: number }>> =
  60. () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0 }))
  61. private readonly muxConns: StreamConn<MuxFrame>[] = []
  62. private readonly hostConns: StreamConn<HostFrame>[] = []
  63. // Parameters carry local structural annotations: the CI lint lane runs
  64. // without built lib/, so IApiClient's indexed-access types collapse to any
  65. // and inferred parameters would trip no-unsafe-argument.
  66. readonly sessions: IApiClient['sessions'] = {
  67. list: (payload: unknown) => this.record('session.list', payload, this.onList(payload)),
  68. create: (payload: unknown) => this.record('session.create', payload, this.onCreate(payload)),
  69. history: (payload: { sessionId: SessionId; beforeSeq?: number; maxMessages?: number }) =>
  70. this.record('session.history', payload, this.onHistory(payload)),
  71. prompt: (payload: unknown) => this.record('session.prompt', payload, this.onPrompt(payload)),
  72. cancel: (payload: unknown) => this.record('session.cancel', payload, this.onCancel(payload)),
  73. }
  74. readonly host: IApiClient['host'] = {
  75. describe: (payload: unknown) => this.record('host.describe', payload, this.onDescribe(payload)),
  76. }
  77. onWorkspaceList: (payload: unknown) => Promise<RpcResponse<{ items: never[] }>> = () => Promise.resolve(ok({ items: [] }))
  78. onWorkspaceCreate: (payload: unknown) => Promise<RpcResponse<{ workspace: WorkspaceView; created: boolean }>> =
  79. () => Promise.resolve(ok({ workspace: fakeWorkspace('fk-ws'), created: true }))
  80. onWorkspaceRename: (payload: unknown) => Promise<RpcResponse<{ workspace: WorkspaceView }>> =
  81. () => Promise.resolve(ok({ workspace: fakeWorkspace('fk-ws') }))
  82. onWorkspaceDelete: (payload: unknown) => Promise<RpcResponse<{ deleted: true }>> =
  83. () => Promise.resolve(ok({ deleted: true }))
  84. onWorkspaceInsertSessionBefore: (payload: unknown) => Promise<RpcResponse<{ workspace: WorkspaceView }>> =
  85. () => Promise.resolve(ok({ workspace: fakeWorkspace('fk-ws') }))
  86. readonly workspace: IApiClient['workspace'] = {
  87. list: (payload: unknown) => this.record('workspace.list', payload, this.onWorkspaceList(payload)),
  88. create: (payload: unknown) => this.record('workspace.create', payload, this.onWorkspaceCreate(payload)),
  89. rename: (payload: unknown) => this.record('workspace.rename', payload, this.onWorkspaceRename(payload)),
  90. delete: (payload: unknown) => this.record('workspace.delete', payload, this.onWorkspaceDelete(payload)),
  91. insertSessionBefore: (payload: unknown) =>
  92. this.record('workspace.insertSessionBefore', payload, this.onWorkspaceInsertSessionBefore(payload)),
  93. }
  94. // Payloads stay `unknown` (lint-lane note above); response rows are the real
  95. // wire shapes so cases can program requires-bearing catalogs and dual-address
  96. // skill lists without casts.
  97. onCommandList: (payload: unknown) => Promise<RpcResponse<{ commands: CommandDescriptor[] }>>
  98. = () => Promise.resolve(ok({ commands: [] }))
  99. onCommandExecute: (payload: unknown) => Promise<RpcResponse<{ matched: boolean; result?: CommandExecuteResult }>>
  100. = () => Promise.resolve(ok({ matched: false }))
  101. onSkillList: (payload: unknown) => Promise<RpcResponse<{ skills: SkillEntry[] }>>
  102. = () => Promise.resolve(ok({ skills: [] }))
  103. readonly commands: IApiClient['commands'] = {
  104. list: (payload: unknown) => this.record('command.list', payload, this.onCommandList(payload)),
  105. execute: (payload: unknown) => this.record('command.execute', payload, this.onCommandExecute(payload)),
  106. }
  107. readonly skills: IApiClient['skills'] = {
  108. list: (payload: unknown) => this.record('skill.list', payload, this.onSkillList(payload)),
  109. }
  110. /** When true, streams never fire onOpen (misbehaving-carrier material for the handshake timeout guard). */
  111. suppressStreamOpen = false
  112. /** When true, onOpen callbacks are parked instead of fired; releaseStreamOpens() fires them.
  113. * Lets a case hold the readiness handshake open (describe done, streams not yet "established"). */
  114. holdStreamOpen = false
  115. private heldOpens: (() => void)[] = []
  116. releaseStreamOpens(): void {
  117. const held = this.heldOpens
  118. this.heldOpens = []
  119. for (const fire of held) fire()
  120. }
  121. readonly events: IApiClient['events'] = {
  122. mux: (_payload: unknown, signal: AbortSignal, onOpen?: () => void) => this.openStream(this.muxConns, signal, onOpen),
  123. host: (_payload: unknown, signal: AbortSignal, onOpen?: () => void) => this.openStream(this.hostConns, signal, onOpen),
  124. }
  125. onRespond: (message: ClientResponse) => Promise<RpcReceipt> = () => Promise.resolve({ accepted: true })
  126. respond(message: ClientResponse): Promise<RpcReceipt> {
  127. return this.record('respond', message, this.onRespond(message))
  128. }
  129. /** Push one mux frame to every open mux stream (rpcId minted unless pinned by the case). */
  130. pushMux(frame: MuxFrame, rpcId?: string): void {
  131. for (const conn of [...this.muxConns]) conn.feed({ kind: 'frame', envelope: { rpcId: RpcId(rpcId ?? `push-${nextRpc++}`), payload: frame } })
  132. }
  133. pushHost(frame: HostFrame, rpcId?: string): void {
  134. for (const conn of [...this.hostConns]) conn.feed({ kind: 'frame', envelope: { rpcId: RpcId(rpcId ?? `push-${nextRpc++}`), payload: frame } })
  135. }
  136. /** End (clean close) or fail (throw) every open stream — reconnect-path material. */
  137. endStreams(): void {
  138. for (const conn of [...this.muxConns, ...this.hostConns]) conn.feed({ kind: 'end' })
  139. }
  140. failStreams(error: unknown): void {
  141. for (const conn of [...this.muxConns, ...this.hostConns]) conn.feed({ kind: 'fail', error })
  142. }
  143. get openMuxCount(): number {
  144. return this.muxConns.length
  145. }
  146. callsOf(method: string): unknown[] {
  147. return this.calls.filter(c => c.method === method).map(c => c.payload)
  148. }
  149. private record<T>(method: string, payload: unknown, response: Promise<T>): Promise<T> {
  150. this.calls.push({ method, payload })
  151. return response
  152. }
  153. private async *openStream<F>(registry: StreamConn<F>[], signal: AbortSignal, onOpen?: () => void): AsyncGenerator<RpcRequest<F>> {
  154. const inbox: StreamItem<F>[] = []
  155. let wake: (() => void) | null = null
  156. const conn: StreamConn<F> = {
  157. feed: (item) => {
  158. inbox.push(item)
  159. wake?.()
  160. },
  161. }
  162. registry.push(conn)
  163. if (this.holdStreamOpen && onOpen !== undefined) this.heldOpens.push(onOpen)
  164. else if (!this.suppressStreamOpen) onOpen?.()
  165. try {
  166. while (!signal.aborted) {
  167. while (inbox.length > 0) {
  168. const item = inbox.shift() as StreamItem<F>
  169. if (item.kind === 'end') return
  170. if (item.kind === 'fail') throw item.error
  171. yield item.envelope
  172. }
  173. await new Promise<void>((resolve) => {
  174. wake = resolve
  175. signal.addEventListener('abort', () => { resolve() }, { once: true })
  176. })
  177. wake = null
  178. }
  179. } finally {
  180. registry.splice(registry.indexOf(conn), 1)
  181. }
  182. }
  183. }