api-proxy-view.spec.ts 14 KB

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