api-proxy-view.spec.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. /**
  2. * Tool-card view computation over the mux live path: three standard card types
  3. * arrive on the frame, a presenterless tool ships no view field, and a throwing
  4. * presenter soft-falls to no view (the event still ships). Result pairing works
  5. * both through the live open-call table and the backscan fallback after
  6. * turn/end cleared it.
  7. */
  8. import { describe, expect, it } from 'vitest'
  9. import { Context } from 'cordis'
  10. import AgentRegistry from '@deepseek-ai/dsh-agent'
  11. import type { Agent } from '@deepseek-ai/dsh-agent'
  12. import SessionStore from '@deepseek-ai/dsh-session'
  13. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  14. import ToolRegistry from '@deepseek-ai/dsh-tools'
  15. import type { ContentBlock } from '@deepseek-ai/dsh-llm'
  16. import { CallId } from '@deepseek-ai/dsh-llm'
  17. import type { Session, SessionId } from '@deepseek-ai/dsh-session'
  18. import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
  19. import type { MuxFrame, RpcRequest } from '@deepseek-ai/dsh-host-apiproxy/api'
  20. import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
  21. import { createApiProxy } from '../src/api-proxy.ts'
  22. const reply = (text: string): Promise<ContentBlock[]> => Promise.resolve([{ type: 'text', text }])
  23. function tool(name: string, presenters: Pick<ToolDefinition, 'presentCall' | 'presentResult'>): ToolDefinition {
  24. return {
  25. name,
  26. description: `tool ${name}`,
  27. parameters: { type: 'object', properties: {} },
  28. execute: () => reply(`ran:${name}`),
  29. ...presenters,
  30. }
  31. }
  32. async function harness(): Promise<{ ctx: Context }> {
  33. const ctx = new Context()
  34. await ctx.plugin(SessionStore)
  35. await ctx.plugin(SystemPrompt, { persona: '' })
  36. await ctx.plugin(ToolRegistry)
  37. await ctx.plugin(AgentRegistry)
  38. ctx.tools.register(tool('gen', {
  39. presentCall: () => ({ card: 'generic', title: 'gen call' }),
  40. presentResult: (_args, result) => ({ card: 'generic', title: result.isError ? 'gen failed' : 'gen done' }),
  41. }))
  42. ctx.tools.register(tool('term', {
  43. presentCall: args => ({ card: 'terminal', title: (args as { cmd?: string }).cmd ?? '' }),
  44. presentResult: () => ({ card: 'terminal', output: 'done' }),
  45. }))
  46. ctx.tools.register(tool('diffy', {
  47. presentCall: () => ({ card: 'diff', title: 'Write f.txt', diffs: [{ path: 'f.txt', oldText: null, newText: 'x' }] }),
  48. }))
  49. ctx.tools.register(tool('plain', {}))
  50. ctx.tools.register(tool('boom', {
  51. presentCall: () => { throw new Error('presenter exploded') },
  52. }))
  53. return { ctx }
  54. }
  55. /** Drain frames from an open mux stream until `count` session/event frames arrived. */
  56. async function collect(iterable: AsyncIterable<RpcRequest<MuxFrame>>, count: number, abort: AbortController): Promise<MuxFrame[]> {
  57. const frames: MuxFrame[] = []
  58. for await (const frame of iterable) {
  59. frames.push(frame.payload)
  60. if (frames.filter(f => f.type === 'session/event').length >= count) abort.abort()
  61. }
  62. return frames
  63. }
  64. describe('mux live view computation', () => {
  65. it('attaches the three standard card views, omits view without a presenter, soft-falls on throw', async () => {
  66. const { ctx } = await harness()
  67. const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp' })
  68. const abort = new AbortController()
  69. const stream = api.events.mux({ rpcId: RpcId('t-mux'), payload: {} }, abort.signal)
  70. const collected = collect(stream, 7, abort)
  71. const session = ctx.sessions.create()
  72. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  73. session.append('tool/call', { turn: 1, step: 1, callId: CallId('c-gen'), name: 'gen', arguments: '{}' })
  74. session.append('tool/call', { turn: 1, step: 1, callId: CallId('c-term'), name: 'term', arguments: '{"cmd":"echo hi"}' })
  75. session.append('tool/call', { turn: 1, step: 1, callId: CallId('c-diff'), name: 'diffy', arguments: '{}' })
  76. session.append('tool/call', { turn: 1, step: 1, callId: CallId('c-plain'), name: 'plain', arguments: '{}' })
  77. session.append('tool/call', { turn: 1, step: 1, callId: CallId('c-boom'), name: 'boom', arguments: '{}' })
  78. session.append('tool/result', { turn: 1, step: 1, callId: CallId('c-gen'), content: [{ type: 'text', text: 'ok' }], isError: false }, { surfaceOp: 'append' })
  79. const frames = await collected
  80. const events = frames.filter(f => f.type === 'session/event')
  81. const byCall = new Map(events
  82. .filter(f => f.event.type === 'tool/call' || f.event.type === 'tool/result')
  83. .map(f => [`${f.event.type}:${(f.event.data as { callId: string }).callId}`, f]))
  84. expect(byCall.get('tool/call:c-gen')?.view).toEqual({ for: 'call', view: { card: 'generic', title: 'gen call' } })
  85. expect(byCall.get('tool/call:c-term')?.view).toEqual({ for: 'call', view: { card: 'terminal', title: 'echo hi' } })
  86. expect(byCall.get('tool/call:c-diff')?.view?.view.card).toBe('diff')
  87. // No presenter → the frame carries no view property at all.
  88. expect('view' in (byCall.get('tool/call:c-plain') ?? {})).toBe(false)
  89. // Throwing presenter → soft-fall: event ships, no view.
  90. expect(byCall.get('tool/call:c-boom')).toBeDefined()
  91. expect('view' in (byCall.get('tool/call:c-boom') ?? {})).toBe(false)
  92. // Result pairing through the live table: presentResult saw the call's args.
  93. expect(byCall.get('tool/result:c-gen')?.view).toEqual({ for: 'result', view: { card: 'generic', title: 'gen done' } })
  94. })
  95. it('serves history entries with call/result views, backscan pairing, and soft-falls', async () => {
  96. const { ctx } = await harness()
  97. const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp' })
  98. const session = ctx.sessions.create()
  99. // history resolves the agent first; a live structural stub is enough (only
  100. // .session is read on this path).
  101. ctx.agents.register({ id: session.id, session, status: 'idle', ctx } as Agent)
  102. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  103. session.append('tool/call', { turn: 1, step: 1, callId: CallId('h-term'), name: 'term', arguments: '{"cmd":"ls"}' })
  104. // meta rides through to presentResult's ToolResult (the spread arm).
  105. session.append('tool/result', { turn: 1, step: 1, callId: CallId('h-term'), content: [{ type: 'text', text: 'ok' }], isError: false, meta: { n: 1 } }, { surfaceOp: 'append' })
  106. // Unpaired result: no tool/call with this id anywhere in the page.
  107. session.append('tool/result', { turn: 1, step: 1, callId: CallId('h-orphan'), content: [{ type: 'text', text: 'x' }], isError: false }, { surfaceOp: 'append' })
  108. // Paired, but the call's stored arguments do not parse: backscan soft-falls.
  109. session.append('tool/call', { turn: 1, step: 1, callId: CallId('h-bad'), name: 'term', arguments: '{broken' })
  110. session.append('tool/result', { turn: 1, step: 1, callId: CallId('h-bad'), content: [{ type: 'text', text: 'y' }], isError: false }, { surfaceOp: 'append' })
  111. // Presenterless tool: pairing succeeds but presentResult is absent.
  112. session.append('tool/call', { turn: 1, step: 1, callId: CallId('h-plain'), name: 'plain', arguments: '{}' })
  113. session.append('tool/result', { turn: 1, step: 1, callId: CallId('h-plain'), content: [{ type: 'text', text: 'z' }], isError: false }, { surfaceOp: 'append' })
  114. const response = await api.sessions.history({ rpcId: RpcId('t-hist'), payload: { sessionId: session.id } })
  115. expect(response.result.ok).toBe(true)
  116. if (!response.result.ok) throw new Error('unreachable')
  117. const entries = response.result.value.events
  118. const byKey = new Map(entries
  119. .filter(entry => entry.event.type === 'tool/call' || entry.event.type === 'tool/result')
  120. .map(entry => [`${entry.event.type}:${(entry.event.data as { callId: string }).callId}`, entry]))
  121. expect(byKey.get('tool/call:h-term')?.view).toEqual({ for: 'call', view: { card: 'terminal', title: 'ls' } })
  122. expect(byKey.get('tool/result:h-term')?.view).toEqual({ for: 'result', view: { card: 'terminal', output: 'done' } })
  123. expect('view' in (byKey.get('tool/result:h-orphan') ?? {})).toBe(false)
  124. expect('view' in (byKey.get('tool/result:h-bad') ?? {})).toBe(false)
  125. expect('view' in (byKey.get('tool/result:h-plain') ?? {})).toBe(false)
  126. })
  127. it('drops a disposed session from the live open-call table (result after dispose gets no view)', async () => {
  128. const { ctx } = await harness()
  129. const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp' })
  130. const abort = new AbortController()
  131. const stream = api.events.mux({ rpcId: RpcId('t-mux3'), payload: {} }, abort.signal)
  132. let session: Session | undefined
  133. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  134. session = inner.sessions.create('session-doomed' as SessionId)
  135. }, { inject: ['sessions'] }))
  136. session?.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  137. session?.append('tool/call', { turn: 1, step: 1, callId: CallId('c-doomed'), name: 'term', arguments: '{"cmd":"x"}' })
  138. // Disposing the owning fiber detaches the session mid-stream; the
  139. // session/disposed listener must clear its open-call table entry.
  140. await fiber.dispose()
  141. const frames = await collect(stream, 2, abort)
  142. const call = frames.find(f => f.type === 'session/event' && f.event.type === 'tool/call')
  143. expect(call?.type === 'session/event' && call.view?.for).toBe('call')
  144. })
  145. it('pairs a result after turn/end via the in-memory backscan fallback', async () => {
  146. const { ctx } = await harness()
  147. const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp' })
  148. const abort = new AbortController()
  149. const stream = api.events.mux({ rpcId: RpcId('t-mux2'), payload: {} }, abort.signal)
  150. const collected = collect(stream, 4, abort)
  151. const session = ctx.sessions.create()
  152. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  153. session.append('tool/call', { turn: 1, step: 1, callId: CallId('c-late'), name: 'term', arguments: '{"cmd":"tail"}' })
  154. session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  155. // The turn/end above cleared the live table; pairing must fall back to
  156. // scanning the session's in-memory events.
  157. session.append('tool/result', { turn: 1, step: 1, callId: CallId('c-late'), content: [{ type: 'text', text: 'ok' }], isError: false }, { surfaceOp: 'append' })
  158. const frames = await collected
  159. const result = frames.find(f => f.type === 'session/event' && f.event.type === 'tool/result')
  160. expect(result?.type === 'session/event' && result.view).toEqual({ for: 'result', view: { card: 'terminal', output: 'done' } })
  161. })
  162. })