fake-api.client.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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, HostFrame, IApiClient, ModelSelection, MuxFrame,
  6. RpcError, RpcReceipt, RpcRequest, RpcResponse, SessionId, SessionModels, SessionSearchItem, SkillEntry,
  7. WorkspaceId, WorkspaceView,
  8. } from '@deepseek-ai/dsh-api-remotes/client'
  9. import { RpcId } from '@deepseek-ai/dsh-client-connection/client'
  10. import type { SessionRemotes } from '../src/client/sessions/remotes.ts'
  11. /** Programmable-default workspace row (branded id, ISO-ish times). */
  12. function fakeWorkspace(id: string, over: Partial<WorkspaceView> = {}): WorkspaceView {
  13. return {
  14. workspaceId: id as WorkspaceId,
  15. path: '/f/ws',
  16. title: 'ws',
  17. sessionIds: [],
  18. createdAt: '2026-01-01T00:00:00.000Z',
  19. updatedAt: '2026-01-01T00:00:00.000Z',
  20. ...over,
  21. }
  22. }
  23. export interface Deferred<T> {
  24. promise: Promise<T>
  25. resolve(value: T): void
  26. reject(error: unknown): void
  27. }
  28. /** Test-held settlement: the case decides when an RPC lands (history-pending injections etc.). */
  29. export function deferred<T>(): Deferred<T> {
  30. let resolve!: (value: T) => void
  31. let reject!: (error: unknown) => void
  32. const promise = new Promise<T>((res, rej) => {
  33. resolve = res
  34. reject = rej
  35. })
  36. return { promise, resolve, reject }
  37. }
  38. let nextRpc = 0
  39. export function ok<T>(value: T): RpcResponse<T> {
  40. return { rpcId: RpcId(`fake-${nextRpc++}`), result: { ok: true, value } }
  41. }
  42. export function err<T>(error: RpcError): RpcResponse<T> {
  43. return { rpcId: RpcId(`fake-${nextRpc++}`), result: { ok: false, error } }
  44. }
  45. type StreamItem<F> = { kind: 'frame'; envelope: RpcRequest<F> } | { kind: 'end' } | { kind: 'fail'; error: unknown }
  46. interface StreamConn<F> {
  47. feed(item: StreamItem<F>): void
  48. }
  49. /**
  50. * Commands Remote double: the generated face delivers the carrier's outcome, so
  51. * a test that programs nothing sees an empty catalog and an unmatched line.
  52. * @returns the Remote namespaces the session cluster calls.
  53. */
  54. export function fakeRemote(): SessionRemotes {
  55. return {
  56. commands: {
  57. list: () => Promise.resolve({ ok: true, value: [] }),
  58. execute: () => Promise.resolve({ ok: true, value: undefined }),
  59. },
  60. }
  61. }
  62. export class FakeApiClient implements IApiClient {
  63. /** Chronological call record: [method, payload]. */
  64. readonly calls: { method: string; payload: unknown }[] = []
  65. // Programmable slots (defaults answer OK-empty); reassign per case.
  66. onList: (payload: unknown) => Promise<RpcResponse<{ items: never[] }>> = () => Promise.resolve(ok({ items: [] }))
  67. onSearch: (payload: unknown) => Promise<RpcResponse<{ items: SessionSearchItem[]; hasMore: boolean }>> =
  68. () => Promise.resolve(ok({ items: [], hasMore: false }))
  69. onCreate: (payload: unknown) => Promise<RpcResponse<{ sessionId: SessionId }>> = () => Promise.resolve(ok({ sessionId: 'fk-new' as SessionId }))
  70. readonly defaultModel: ModelSelection = { provider: 'deepseek-official', model: 'deepseek-v4-flash' }
  71. onRename: (payload: unknown) => Promise<RpcResponse<{ title: string; seq: number }>> = () => Promise.resolve(ok({ title: 'fk-renamed', seq: 0 }))
  72. onFork: (payload: unknown) => Promise<RpcResponse<{ sessionId: SessionId }>> = () => Promise.resolve(ok({ sessionId: 'fk-fork' as SessionId }))
  73. onHistory: (payload: { sessionId: SessionId; beforeSeq?: number; maxMessages?: number })
  74. => Promise<RpcResponse<{ events: never[]; hasMore: boolean }>> =
  75. () => Promise.resolve(ok({ events: [], hasMore: false }))
  76. onModels: (payload: unknown) => Promise<RpcResponse<SessionModels>> = () => Promise.resolve(ok({
  77. current: this.defaultModel,
  78. routable: true,
  79. groups: [{
  80. id: 'deepseek-official',
  81. name: 'DeepSeek',
  82. models: [{ id: 'deepseek-v4-flash', name: 'DeepSeek V4 Flash' }],
  83. }],
  84. failures: [],
  85. }))
  86. onSelectModel: (payload: { provider: string; model: string }) =>
  87. Promise<RpcResponse<{ selected: ModelSelection }>> =
  88. payload => Promise.resolve(ok({ selected: { provider: payload.provider, model: payload.model } }))
  89. onPrompt: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  90. onAttachment: (payload: unknown) => Promise<RpcResponse<{ attachment: { attachmentId: never; mediaType: 'image/png'; bytes: number; width: number; height: number }; data: string }>> =
  91. () => Promise.resolve(ok({ attachment: { attachmentId: 'a' as never, mediaType: 'image/png', bytes: 1, width: 1, height: 1 }, data: 'AA==' }))
  92. onUpdateQueue: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  93. onCancel: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  94. onDescribe: (payload: unknown) => Promise<RpcResponse<{
  95. version: string
  96. cwd: string
  97. attachedSessions: number
  98. home: string
  99. canOpenPath: boolean
  100. }>> =
  101. () => Promise.resolve(ok({
  102. version: '0-fake', cwd: '/f', attachedSessions: 0, home: '/h', canOpenPath: true,
  103. }))
  104. onPickDirectory: (payload: unknown) => Promise<RpcResponse<{ path: string | null }>> =
  105. () => Promise.resolve(ok({ path: null }))
  106. onOpenPath: (payload: unknown) => Promise<RpcResponse<{ opened: true }>> =
  107. () => Promise.resolve(ok({ opened: true as const }))
  108. onListDirectory: (payload: unknown) => Promise<RpcResponse<{
  109. path: string
  110. home: string
  111. crumbs: { name: string; path: string; hidden: boolean }[]
  112. entries: { name: string; path: string; hidden: boolean }[]
  113. truncated: boolean
  114. }>> =
  115. () => Promise.resolve(ok({ path: '/home/fake', home: '/home/fake', crumbs: [{ name: '/', path: '/', hidden: false }], entries: [], truncated: false }))
  116. onCreateDirectory: (payload: unknown) => Promise<RpcResponse<{ path: string }>> =
  117. () => Promise.resolve(ok({ path: '/home/fake/new' }))
  118. private readonly muxConns: StreamConn<MuxFrame>[] = []
  119. private readonly hostConns: StreamConn<HostFrame>[] = []
  120. lastSearchSignal: AbortSignal | undefined
  121. // Parameters carry local structural annotations: the CI lint lane runs
  122. // without built lib/, so IApiClient's indexed-access types collapse to any
  123. // and inferred parameters would trip no-unsafe-argument.
  124. readonly sessions: IApiClient['sessions'] = {
  125. list: (payload: unknown) => this.record('session.list', payload, this.onList(payload)),
  126. search: (payload: unknown, signal?: AbortSignal) => {
  127. this.lastSearchSignal = signal
  128. return this.record('session.search', payload, this.onSearch(payload))
  129. },
  130. create: (payload: unknown) => this.record('session.create', payload, this.onCreate(payload)),
  131. history: (payload: { sessionId: SessionId; beforeSeq?: number; maxMessages?: number }) =>
  132. this.record('session.history', payload, this.onHistory(payload)),
  133. models: (payload: unknown) => this.record('session.models', payload, this.onModels(payload)),
  134. selectModel: (payload: { provider: string; model: string }) =>
  135. this.record('session.selectModel', payload, this.onSelectModel(payload)),
  136. rename: (payload: unknown) => this.record('session.rename', payload, this.onRename(payload)),
  137. fork: (payload: unknown) => this.record('session.fork', payload, this.onFork(payload)),
  138. prompt: (payload: unknown) => this.record('session.prompt', payload, this.onPrompt(payload)),
  139. attachment: (payload: unknown) => this.record('session.attachment', payload, this.onAttachment(payload)),
  140. updateQueue: (payload: unknown) => this.record('session.updateQueue', payload, this.onUpdateQueue(payload)),
  141. cancel: (payload: unknown) => this.record('session.cancel', payload, this.onCancel(payload)),
  142. }
  143. onSubagentList: (payload: unknown) => Promise<RpcResponse<{ entries: never[]; parentAvailable: boolean }>>
  144. = () => Promise.resolve(ok({ entries: [], parentAvailable: true }))
  145. onSubagentHistory: (payload: unknown) => Promise<RpcResponse<{ events: never[]; hasMore: boolean }>>
  146. = () => Promise.resolve(ok({ events: [], hasMore: false }))
  147. onSubagentPrompt: (payload: unknown) => Promise<RpcResponse<{ messageId: never }>>
  148. = () => Promise.resolve(ok({ messageId: 'fake-message' as never }))
  149. onSubagentInterrupt: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>>
  150. = () => Promise.resolve(ok({ accepted: true as const }))
  151. readonly subagents: IApiClient['subagents'] = {
  152. list: (payload: unknown) => this.record('subagent.list', payload, this.onSubagentList(payload)),
  153. history: (payload: unknown) => this.record('subagent.history', payload, this.onSubagentHistory(payload)),
  154. prompt: (payload: unknown) => this.record('subagent.prompt', payload, this.onSubagentPrompt(payload)),
  155. interrupt: (payload: unknown) => this.record('subagent.interrupt', payload, this.onSubagentInterrupt(payload)),
  156. }
  157. readonly host: IApiClient['host'] = {
  158. describe: (payload: unknown) => this.record('host.describe', payload, this.onDescribe(payload)),
  159. pickDirectory: (payload: unknown) => this.record('host.pickDirectory', payload, this.onPickDirectory(payload)),
  160. listDirectory: (payload: unknown) => this.record('host.listDirectory', payload, this.onListDirectory(payload)),
  161. createDirectory: (payload: unknown) => this.record('host.createDirectory', payload, this.onCreateDirectory(payload)),
  162. openPath: (payload: unknown) => this.record('host.openPath', payload, this.onOpenPath(payload)),
  163. }
  164. // The archive-set field defaults at the binding below so list stubs keep
  165. // the pre-archive `{ items }` shape; a stub carrying the field wins.
  166. onWorkspaceList: (payload: unknown) => Promise<RpcResponse<{ items: never[]; archivedSessionIds?: never[] }>> =
  167. () => Promise.resolve(ok({ items: [] }))
  168. onWorkspaceCreate: (payload: unknown) => Promise<RpcResponse<{ workspace: WorkspaceView; created: boolean }>> =
  169. () => Promise.resolve(ok({ workspace: fakeWorkspace('fk-ws'), created: true }))
  170. onWorkspaceRename: (payload: unknown) => Promise<RpcResponse<{ workspace: WorkspaceView }>> =
  171. () => Promise.resolve(ok({ workspace: fakeWorkspace('fk-ws') }))
  172. onWorkspaceDelete: (payload: unknown) => Promise<RpcResponse<{ deleted: true }>> =
  173. () => Promise.resolve(ok({ deleted: true }))
  174. onWorkspaceInsertBefore: (payload: unknown) => Promise<RpcResponse<{ workspaceIds: WorkspaceId[] }>> =
  175. () => Promise.resolve(ok({ workspaceIds: [] }))
  176. onWorkspaceInsertSessionBefore: (payload: unknown) => Promise<RpcResponse<{ workspace: WorkspaceView }>> =
  177. () => Promise.resolve(ok({ workspace: fakeWorkspace('fk-ws') }))
  178. onWorkspaceArchiveSession: (payload: unknown) => Promise<RpcResponse<{ archivedSessionIds: SessionId[] }>> =
  179. payload => Promise.resolve(ok({ archivedSessionIds: [(payload as { sessionId: SessionId }).sessionId] }))
  180. readonly workspace: IApiClient['workspace'] = {
  181. list: (payload: unknown) => this.record('workspace.list', payload, this.onWorkspaceList(payload).then(response => (
  182. response.result.ok
  183. ? { ...response, result: { ok: true as const, value: { archivedSessionIds: [] as never[], ...response.result.value } } }
  184. : response
  185. )) as ReturnType<IApiClient['workspace']['list']>),
  186. create: (payload: unknown) => this.record('workspace.create', payload, this.onWorkspaceCreate(payload)),
  187. rename: (payload: unknown) => this.record('workspace.rename', payload, this.onWorkspaceRename(payload)),
  188. delete: (payload: unknown) => this.record('workspace.delete', payload, this.onWorkspaceDelete(payload)),
  189. insertBefore: (payload: unknown) =>
  190. this.record('workspace.insertBefore', payload, this.onWorkspaceInsertBefore(payload)),
  191. insertSessionBefore: (payload: unknown) =>
  192. this.record('workspace.insertSessionBefore', payload, this.onWorkspaceInsertSessionBefore(payload)),
  193. archiveSession: (payload: unknown) =>
  194. this.record('workspace.archiveSession', payload, this.onWorkspaceArchiveSession(payload)),
  195. }
  196. // Payloads stay `unknown` (lint-lane note above); response rows are the real
  197. // wire shapes so cases can program requires-bearing catalogs and dual-address
  198. // skill lists without casts.
  199. onSkillList: (payload: unknown) => Promise<RpcResponse<{ skills: SkillEntry[] }>>
  200. = () => Promise.resolve(ok({ skills: [] }))
  201. readonly agentPresets: IApiClient['agentPresets'] = {
  202. list: (payload: unknown) => this.record('agentPreset.list', payload, Promise.resolve(ok({ presets: [], authorable: false, hasDocument: false }))),
  203. select: (payload: { agentPreset: string }) =>
  204. this.record('agentPreset.select', payload, Promise.resolve(ok({ agentPreset: payload.agentPreset }))),
  205. read: (payload: { agentPreset: string }) =>
  206. this.record('agentPreset.read', payload, Promise.resolve(ok({
  207. agentPreset: payload.agentPreset, trust: 'user' as const, content: '',
  208. }))),
  209. copy: (payload: { agentPreset: string }) =>
  210. this.record('agentPreset.copy', payload, Promise.resolve(ok({ agentPreset: payload.agentPreset }))),
  211. openDocument: (payload: { agentPreset: string }) =>
  212. this.record('agentPreset.openDocument', payload, Promise.resolve(ok({ opened: true as const }))),
  213. remove: (payload: { agentPreset: string }) =>
  214. this.record('agentPreset.remove', payload, Promise.resolve(ok({}))),
  215. }
  216. readonly skills: IApiClient['skills'] = {
  217. list: (payload: unknown) => this.record('skill.list', payload, this.onSkillList(payload)),
  218. }
  219. readonly goals: IApiClient['goals'] = {
  220. create: payload => this.record('goal.create', payload, Promise.resolve(ok({ ref: { id: 'fake-goal' as never, revision: 1 } }))),
  221. edit: payload => this.record('goal.edit', payload, Promise.resolve(ok({ ref: { id: 'fake-goal' as never, revision: 1 } }))),
  222. pause: payload => this.record('goal.pause', payload, Promise.resolve(ok({ ref: { id: 'fake-goal' as never, revision: 1 } }))),
  223. resume: payload => this.record('goal.resume', payload, Promise.resolve(ok({ ref: { id: 'fake-goal' as never, revision: 1 } }))),
  224. complete: payload => this.record('goal.complete', payload, Promise.resolve(ok({ ref: { id: 'fake-goal' as never, revision: 1 } }))),
  225. clear: payload => this.record('goal.clear', payload, Promise.resolve(ok({ cleared: true as const }))),
  226. }
  227. readonly settings: IApiClient['settings'] = {
  228. describe: payload => this.record('settings.describe', payload, Promise.resolve(ok({ writable: true, hasDocument: false, namespaces: [] }))),
  229. openDocument: payload => this.record('settings.openDocument', payload, Promise.resolve(ok({ opened: true as const }))),
  230. update: payload => this.record('settings.update', payload, Promise.resolve(ok({ ns: 'fake', schema: {}, value: {}, applies: 'live' as const, secrets: [], revision: 0 }))),
  231. replace: payload => this.record('settings.replace', payload, Promise.resolve(ok({ ns: 'fake', schema: {}, value: {}, applies: 'live' as const, secrets: [], revision: 0 }))),
  232. mutate: payload => this.record('settings.mutate', payload, Promise.resolve(ok({ ns: 'fake', schema: {}, value: {}, applies: 'live' as const, secrets: [], revision: 0 }))),
  233. }
  234. readonly credentials: IApiClient['credentials'] = {
  235. describe: payload => this.record('credentials.describe', payload, Promise.resolve(ok({ credentials: {} }))),
  236. set: payload => this.record('credentials.set', payload, Promise.resolve(ok({}))),
  237. unset: payload => this.record('credentials.unset', payload, Promise.resolve(ok({}))),
  238. }
  239. readonly llm: IApiClient['llm'] = {
  240. providers: payload => this.record('llm.providers', payload, Promise.resolve(ok({ providers: [] }))),
  241. models: payload => this.record('llm.models', payload, Promise.resolve(ok({ groups: [], failures: [] }))),
  242. discoverModels: payload => this.record('llm.discoverModels', payload, Promise.resolve(ok({ models: [] }))),
  243. }
  244. /** When true, streams never fire onOpen (misbehaving-carrier material for the handshake timeout guard). */
  245. suppressStreamOpen = false
  246. /** When true, onOpen callbacks are parked instead of fired; releaseStreamOpens() fires them.
  247. * Lets a case hold the readiness handshake open (describe done, streams not yet "established"). */
  248. holdStreamOpen = false
  249. private heldOpens: (() => void)[] = []
  250. releaseStreamOpens(): void {
  251. const held = this.heldOpens
  252. this.heldOpens = []
  253. for (const fire of held) fire()
  254. }
  255. readonly events: IApiClient['events'] = {
  256. mux: (_payload: unknown, signal: AbortSignal, onOpen?: () => void) => this.openStream(this.muxConns, signal, onOpen),
  257. host: (_payload: unknown, signal: AbortSignal, onOpen?: () => void) => this.openStream(this.hostConns, signal, onOpen),
  258. }
  259. onRespond: (message: ClientResponse) => Promise<RpcReceipt> = () => Promise.resolve({ accepted: true })
  260. respond(message: ClientResponse): Promise<RpcReceipt> {
  261. return this.record('respond', message, this.onRespond(message))
  262. }
  263. /** Push one mux frame to every open mux stream (rpcId minted unless pinned by the case). */
  264. pushMux(frame: MuxFrame, rpcId?: string): void {
  265. for (const conn of [...this.muxConns]) conn.feed({ kind: 'frame', envelope: { rpcId: RpcId(rpcId ?? `push-${nextRpc++}`), payload: frame } })
  266. }
  267. pushHost(frame: HostFrame, rpcId?: string): void {
  268. for (const conn of [...this.hostConns]) conn.feed({ kind: 'frame', envelope: { rpcId: RpcId(rpcId ?? `push-${nextRpc++}`), payload: frame } })
  269. }
  270. /** End (clean close) or fail (throw) every open stream — reconnect-path material. */
  271. endStreams(): void {
  272. for (const conn of [...this.muxConns, ...this.hostConns]) conn.feed({ kind: 'end' })
  273. }
  274. failStreams(error: unknown): void {
  275. for (const conn of [...this.muxConns, ...this.hostConns]) conn.feed({ kind: 'fail', error })
  276. }
  277. get openMuxCount(): number {
  278. return this.muxConns.length
  279. }
  280. callsOf(method: string): unknown[] {
  281. return this.calls.filter(c => c.method === method).map(c => c.payload)
  282. }
  283. private record<T>(method: string, payload: unknown, response: Promise<T>): Promise<T> {
  284. this.calls.push({ method, payload })
  285. return response
  286. }
  287. private async *openStream<F>(registry: StreamConn<F>[], signal: AbortSignal, onOpen?: () => void): AsyncGenerator<RpcRequest<F>> {
  288. const inbox: StreamItem<F>[] = []
  289. let wake: (() => void) | null = null
  290. const conn: StreamConn<F> = {
  291. feed: (item) => {
  292. inbox.push(item)
  293. wake?.()
  294. },
  295. }
  296. registry.push(conn)
  297. if (this.holdStreamOpen && onOpen !== undefined) this.heldOpens.push(onOpen)
  298. else if (!this.suppressStreamOpen) onOpen?.()
  299. try {
  300. while (!signal.aborted) {
  301. while (inbox.length > 0) {
  302. const item = inbox.shift() as StreamItem<F>
  303. if (item.kind === 'end') return
  304. if (item.kind === 'fail') throw item.error
  305. yield item.envelope
  306. }
  307. await new Promise<void>((resolve) => {
  308. wake = resolve
  309. signal.addEventListener('abort', () => { resolve() }, { once: true })
  310. })
  311. wake = null
  312. }
  313. } finally {
  314. registry.splice(registry.indexOf(conn), 1)
  315. }
  316. }
  317. }