fake-api.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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 { CommandId } from '@deepseek-ai/dsh-commands/brand'
  5. import type {
  6. CommandDescriptor, HostFrame, IApiClient, ModelTarget, MuxFrame,
  7. RpcRequest, RpcResponse, SessionId, SessionModels, SessionSearchItem, SkillEntry,
  8. } from '../src/client/api.ts'
  9. import { RpcId } from '../src/client/api.ts'
  10. export interface Deferred<T> {
  11. promise: Promise<T>
  12. resolve(value: T): void
  13. reject(error: unknown): void
  14. }
  15. /** Test-held settlement: the case decides when an RPC lands (history-pending injections etc.). */
  16. export function deferred<T>(): Deferred<T> {
  17. let resolve!: (value: T) => void
  18. let reject!: (error: unknown) => void
  19. const promise = new Promise<T>((res, rej) => {
  20. resolve = res
  21. reject = rej
  22. })
  23. return { promise, resolve, reject }
  24. }
  25. let nextRpc = 0
  26. export function ok<T>(value: T): RpcResponse<T> {
  27. return { rpcId: RpcId(`fake-${nextRpc++}`), result: { ok: true, value } }
  28. }
  29. type StreamItem<F> = { kind: 'frame'; envelope: RpcRequest<F> } | { kind: 'end' } | { kind: 'fail'; error: unknown }
  30. interface StreamConn<F> {
  31. feed(item: StreamItem<F>): void
  32. }
  33. export class FakeApiClient implements IApiClient {
  34. /** Chronological call record: [method, payload]. */
  35. readonly calls: { method: string; payload: unknown }[] = []
  36. // Programmable slots (defaults answer OK-empty); reassign per case.
  37. onList: (payload: unknown) => Promise<RpcResponse<{ items: never[] }>> = () => Promise.resolve(ok({ items: [] }))
  38. onSearch: (payload: unknown) => Promise<RpcResponse<{ items: SessionSearchItem[]; hasMore: boolean }>> =
  39. () => Promise.resolve(ok({ items: [], hasMore: false }))
  40. onCreate: (payload: unknown) => Promise<RpcResponse<{ sessionId: SessionId }>> = () => Promise.resolve(ok({ sessionId: 'fk-new' as SessionId }))
  41. onRename: (payload: unknown) => Promise<RpcResponse<{ title: string; seq: number }>> = () => Promise.resolve(ok({ title: 'fk-renamed', seq: 0 }))
  42. onFork: (payload: unknown) => Promise<RpcResponse<{ sessionId: SessionId }>> = () => Promise.resolve(ok({ sessionId: 'fk-fork' as SessionId }))
  43. onHistory: (payload: { sessionId: SessionId; beforeSeq?: number; maxMessages?: number })
  44. => Promise<RpcResponse<{ events: never[]; hasMore: boolean; modelTarget: ModelTarget }>> =
  45. () => Promise.resolve(ok({
  46. events: [],
  47. hasMore: false,
  48. modelTarget: { provider: 'deepseek-official', model: 'deepseek-chat' },
  49. }))
  50. onModels: (payload: unknown) => Promise<RpcResponse<SessionModels>> = () => Promise.resolve(ok({
  51. current: { provider: 'deepseek-official', model: 'deepseek-chat' },
  52. groups: [],
  53. failures: [],
  54. }))
  55. onSelectModel: (payload: ModelTarget & { sessionId: SessionId })
  56. => Promise<RpcResponse<{ selected: ModelTarget }>> =
  57. payload => Promise.resolve(ok({ selected: { provider: payload.provider, model: payload.model } }))
  58. onPrompt: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  59. onUpdateQueue: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  60. onCancel: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  61. onDescribe: (payload: unknown) => Promise<RpcResponse<{ version: string; cwd: string; attachedSessions: number }>> =
  62. () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0 }))
  63. onPickDirectory: (payload: unknown) => Promise<RpcResponse<{ path: string | null }>> =
  64. () => Promise.resolve(ok({ path: null }))
  65. onOpenPath: (payload: unknown) => Promise<RpcResponse<{ opened: true }>> =
  66. () => Promise.resolve(ok({ opened: true as const }))
  67. onListDirectory: (payload: unknown) => Promise<RpcResponse<{
  68. path: string
  69. home: string
  70. crumbs: { name: string; path: string; hidden: boolean }[]
  71. entries: { name: string; path: string; hidden: boolean }[]
  72. truncated: boolean
  73. }>> =
  74. () => Promise.resolve(ok({ path: '/home/fake', home: '/home/fake', crumbs: [{ name: '/', path: '/', hidden: false }], entries: [], truncated: false }))
  75. onCreateDirectory: (payload: unknown) => Promise<RpcResponse<{ path: string }>> =
  76. () => Promise.resolve(ok({ path: '/home/fake/new' }))
  77. private readonly muxConns: StreamConn<MuxFrame>[] = []
  78. private readonly hostConns: StreamConn<HostFrame>[] = []
  79. lastSearchSignal: AbortSignal | undefined
  80. // Parameter annotations below are local structural types on purpose: the CI
  81. // lint lane runs without built artifacts, where IApiClient's wire types
  82. // (apiproxy subpath) resolve to any and inferred params trip no-unsafe-argument.
  83. readonly sessions: IApiClient['sessions'] = {
  84. list: (payload: unknown) => this.record('session.list', payload, this.onList(payload)),
  85. search: (payload: unknown, signal?: AbortSignal) => {
  86. this.lastSearchSignal = signal
  87. return this.record('session.search', payload, this.onSearch(payload))
  88. },
  89. create: (payload: unknown) => this.record('session.create', payload, this.onCreate(payload)),
  90. history: (payload: { sessionId: SessionId; beforeSeq?: number; maxMessages?: number }) =>
  91. this.record('session.history', payload, this.onHistory(payload)),
  92. models: (payload: unknown) => this.record('session.models', payload, this.onModels(payload)),
  93. selectModel: (payload: ModelTarget & { sessionId: SessionId }) =>
  94. this.record('session.selectModel', payload, this.onSelectModel(payload)),
  95. rename: (payload: unknown) => this.record('session.rename', payload, this.onRename(payload)),
  96. fork: (payload: unknown) => this.record('session.fork', payload, this.onFork(payload)),
  97. prompt: (payload: unknown) => this.record('session.prompt', payload, this.onPrompt(payload)),
  98. updateQueue: (payload: unknown) => this.record('session.updateQueue', payload, this.onUpdateQueue(payload)),
  99. cancel: (payload: unknown) => this.record('session.cancel', payload, this.onCancel(payload)),
  100. }
  101. readonly subagents: IApiClient['subagents'] = {
  102. list: (payload: unknown) => this.record('subagent.list', payload, Promise.resolve(ok({
  103. entries: [],
  104. parentAvailable: true,
  105. }))),
  106. history: (payload: unknown) => this.record('subagent.history', payload, Promise.resolve(ok({
  107. events: [],
  108. hasMore: false,
  109. }))),
  110. prompt: (payload: unknown) => this.record('subagent.prompt', payload, Promise.resolve(ok({
  111. messageId: 'fake-message' as never,
  112. }))),
  113. }
  114. readonly host: IApiClient['host'] = {
  115. describe: payload => this.record('host.describe', payload, this.onDescribe(payload)),
  116. pickDirectory: payload => this.record('host.pickDirectory', payload, this.onPickDirectory(payload)),
  117. listDirectory: payload => this.record('host.listDirectory', payload, this.onListDirectory(payload)),
  118. createDirectory: payload => this.record('host.createDirectory', payload, this.onCreateDirectory(payload)),
  119. openPath: payload => this.record('host.openPath', payload, this.onOpenPath(payload)),
  120. }
  121. readonly workspace: IApiClient['workspace'] = {
  122. list: (payload: unknown) => this.record('workspace.list', payload, Promise.resolve(ok({ items: [], archivedSessionIds: [] }))),
  123. create: (payload: unknown) => this.record('workspace.create', payload, Promise.resolve(ok({
  124. workspace: { workspaceId: 'fk-ws' as never, path: '/f/ws', title: 'ws', sessionIds: [], createdAt: '0', updatedAt: '0' },
  125. created: true,
  126. }))),
  127. rename: (payload: unknown) => this.record('workspace.rename', payload, Promise.resolve(ok({
  128. workspace: { workspaceId: 'fk-ws' as never, path: '/f/ws', title: 'ws', sessionIds: [], createdAt: '0', updatedAt: '0' },
  129. }))),
  130. delete: (payload: unknown) => this.record('workspace.delete', payload, Promise.resolve(ok({ deleted: true as const }))),
  131. insertSessionBefore: (payload: unknown) => this.record('workspace.insertSessionBefore', payload, Promise.resolve(ok({
  132. workspace: { workspaceId: 'fk-ws' as never, path: '/f/ws', title: 'ws', sessionIds: [], createdAt: '0', updatedAt: '0' },
  133. }))),
  134. archiveSession: (payload: unknown) => this.record('workspace.archiveSession', payload, Promise.resolve(ok({
  135. archivedSessionIds: [(payload as { sessionId: SessionId }).sessionId],
  136. }))),
  137. }
  138. // Payloads stay `unknown` (lint-lane note above); response rows are the real
  139. // wire shapes so cases can program catalogs and skill lists without casts.
  140. onCommandList: (payload: unknown) => Promise<RpcResponse<{ commands: CommandDescriptor[] }>>
  141. = () => Promise.resolve(ok({ commands: [] }))
  142. onCommandExecute: (payload: unknown) => Promise<RpcResponse<{ matched: boolean; commandId?: CommandId }>>
  143. = () => Promise.resolve(ok({ matched: false }))
  144. onSkillList: (payload: unknown) => Promise<RpcResponse<{ skills: SkillEntry[] }>>
  145. = () => Promise.resolve(ok({ skills: [] }))
  146. readonly commands: IApiClient['commands'] = {
  147. list: (payload: unknown) => this.record('command.list', payload, this.onCommandList(payload)),
  148. execute: (payload: unknown) => this.record('command.execute', payload, this.onCommandExecute(payload)),
  149. }
  150. readonly skills: IApiClient['skills'] = {
  151. list: (payload: unknown) => this.record('skill.list', payload, this.onSkillList(payload)),
  152. }
  153. readonly goals: IApiClient['goals'] = {
  154. create: payload => this.record('goal.create', payload, Promise.resolve(ok({ ref: { id: 'fake-goal' as never, revision: 1 } }))),
  155. edit: payload => this.record('goal.edit', payload, Promise.resolve(ok({ ref: { id: 'fake-goal' as never, revision: 1 } }))),
  156. pause: payload => this.record('goal.pause', payload, Promise.resolve(ok({ ref: { id: 'fake-goal' as never, revision: 1 } }))),
  157. resume: payload => this.record('goal.resume', payload, Promise.resolve(ok({ ref: { id: 'fake-goal' as never, revision: 1 } }))),
  158. complete: payload => this.record('goal.complete', payload, Promise.resolve(ok({ ref: { id: 'fake-goal' as never, revision: 1 } }))),
  159. clear: payload => this.record('goal.clear', payload, Promise.resolve(ok({ cleared: true as const }))),
  160. }
  161. readonly settings: IApiClient['settings'] = {
  162. describe: payload => this.record('settings.describe', payload, Promise.resolve(ok({ writable: true, hasDocument: false, namespaces: [] }))),
  163. openDocument: payload => this.record('settings.openDocument', payload, Promise.resolve(ok({ opened: true as const }))),
  164. update: payload => this.record('settings.update', payload, Promise.resolve(ok({ ns: 'fake', schema: {}, value: {}, applies: 'live' as const, secrets: [], revision: 0 }))),
  165. replace: payload => this.record('settings.replace', payload, Promise.resolve(ok({ ns: 'fake', schema: {}, value: {}, applies: 'live' as const, secrets: [], revision: 0 }))),
  166. mutate: payload => this.record('settings.mutate', payload, Promise.resolve(ok({ ns: 'fake', schema: {}, value: {}, applies: 'live' as const, secrets: [], revision: 0 }))),
  167. }
  168. readonly credentials: IApiClient['credentials'] = {
  169. describe: payload => this.record('credentials.describe', payload, Promise.resolve(ok({ credentials: {} }))),
  170. set: payload => this.record('credentials.set', payload, Promise.resolve(ok({}))),
  171. unset: payload => this.record('credentials.unset', payload, Promise.resolve(ok({}))),
  172. }
  173. readonly llm: IApiClient['llm'] = {
  174. providers: payload => this.record('llm.providers', payload, Promise.resolve(ok({ providers: [] }))),
  175. models: payload => this.record('llm.models', payload, Promise.resolve(ok({ groups: [], failures: [] }))),
  176. }
  177. /** When true, streams never fire onOpen (misbehaving-carrier material for the handshake timeout guard). */
  178. suppressStreamOpen = false
  179. /** When true, onOpen callbacks are parked instead of fired; releaseStreamOpens() fires them.
  180. * Lets a case hold the readiness handshake open (describe done, streams not yet "established"). */
  181. holdStreamOpen = false
  182. private heldOpens: (() => void)[] = []
  183. releaseStreamOpens(): void {
  184. const held = this.heldOpens
  185. this.heldOpens = []
  186. for (const fire of held) fire()
  187. }
  188. readonly events: IApiClient['events'] = {
  189. mux: (_payload: unknown, signal: AbortSignal, onOpen?: () => void) =>
  190. this.openStream(this.muxConns, signal, onOpen),
  191. host: (_payload: unknown, signal: AbortSignal, onOpen?: () => void) =>
  192. this.openStream(this.hostConns, signal, onOpen),
  193. }
  194. respond(): Promise<{ accepted: false; reason: 'not-pending' }> {
  195. return Promise.resolve({ accepted: false, reason: 'not-pending' })
  196. }
  197. /** Push one mux frame to every open mux stream (rpcId minted unless pinned by the case). */
  198. pushMux(frame: MuxFrame, rpcId?: string): void {
  199. for (const conn of [...this.muxConns]) conn.feed({ kind: 'frame', envelope: { rpcId: RpcId(rpcId ?? `push-${nextRpc++}`), payload: frame } })
  200. }
  201. pushHost(frame: HostFrame, rpcId?: string): void {
  202. for (const conn of [...this.hostConns]) conn.feed({ kind: 'frame', envelope: { rpcId: RpcId(rpcId ?? `push-${nextRpc++}`), payload: frame } })
  203. }
  204. /** End (clean close) or fail (throw) every open stream — reconnect-path material. */
  205. endStreams(): void {
  206. for (const conn of [...this.muxConns, ...this.hostConns]) conn.feed({ kind: 'end' })
  207. }
  208. failStreams(error: unknown): void {
  209. for (const conn of [...this.muxConns, ...this.hostConns]) conn.feed({ kind: 'fail', error })
  210. }
  211. get openMuxCount(): number {
  212. return this.muxConns.length
  213. }
  214. callsOf(method: string): unknown[] {
  215. return this.calls.filter(c => c.method === method).map(c => c.payload)
  216. }
  217. private record<T>(method: string, payload: unknown, response: Promise<T>): Promise<T> {
  218. this.calls.push({ method, payload })
  219. return response
  220. }
  221. private async *openStream<F>(registry: StreamConn<F>[], signal: AbortSignal, onOpen?: () => void): AsyncGenerator<RpcRequest<F>> {
  222. const inbox: StreamItem<F>[] = []
  223. let wake: (() => void) | null = null
  224. const conn: StreamConn<F> = {
  225. feed: (item) => {
  226. inbox.push(item)
  227. wake?.()
  228. },
  229. }
  230. registry.push(conn)
  231. if (this.holdStreamOpen && onOpen !== undefined) this.heldOpens.push(onOpen)
  232. else if (!this.suppressStreamOpen) onOpen?.()
  233. try {
  234. while (!signal.aborted) {
  235. while (inbox.length > 0) {
  236. const item = inbox.shift() as StreamItem<F>
  237. if (item.kind === 'end') return
  238. if (item.kind === 'fail') throw item.error
  239. yield item.envelope
  240. }
  241. await new Promise<void>((resolve) => {
  242. wake = resolve
  243. signal.addEventListener('abort', () => { resolve() }, { once: true })
  244. })
  245. wake = null
  246. }
  247. } finally {
  248. registry.splice(registry.indexOf(conn), 1)
  249. }
  250. }
  251. }