api-proxy-view.spec.ts 12 KB

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