command-feedback.spec.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import Loader from '@cordisjs/plugin-loader'
  4. import AgentRegistry from '@deepseek-ai/dsh-agent'
  5. import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent'
  6. import CommandService from '@deepseek-ai/dsh-commands'
  7. import SessionStore, { foldSurface, Session, SessionId } from '@deepseek-ai/dsh-session'
  8. import * as commandFeedback from '@deepseek-ai/dsh-command-feedback'
  9. interface Harness {
  10. readonly ctx: Context
  11. readonly agent: Agent
  12. readonly session: Session
  13. readonly plugin: Awaited<ReturnType<Context['plugin']>>
  14. }
  15. /** Build a live idle agent over a store-owned session, as an app's spine does. */
  16. function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } {
  17. const session = ctx.sessions.create(SessionId(id))
  18. let status: AgentStatus = 'idle'
  19. const agent: Agent = {
  20. id: session.id,
  21. options: {},
  22. session,
  23. ctx: new Context(),
  24. get status() { return status },
  25. get acceptsNextStep() { return status === 'running' },
  26. send: () => {},
  27. followup: () => {},
  28. steer: () => {},
  29. inject: () => {},
  30. cancel() { status = 'idle' },
  31. whenIdle() { return Promise.resolve() },
  32. }
  33. return { agent, session }
  34. }
  35. /** Mount the real command registry and this producer. */
  36. async function harness(): Promise<Harness> {
  37. const ctx = new Context()
  38. await ctx.plugin(CommandService)
  39. await ctx.plugin(AgentRegistry)
  40. await ctx.plugin(SessionStore)
  41. const plugin = await ctx.plugin(commandFeedback)
  42. const { agent, session } = stubAgent(ctx, `command-feedback-${Math.random()}`)
  43. ctx.agents.register(agent)
  44. return { ctx, agent, session, plugin }
  45. }
  46. /** Execute `/feedback` through the same registry boundary as a UI adapter. */
  47. async function run(test: Harness, suffix = ''): Promise<{ kind: string; text?: string }> {
  48. const settled = await test.ctx.commands.execute(
  49. test.agent,
  50. `/feedback${suffix}`,
  51. new AbortController().signal,
  52. )
  53. if (settled === undefined) throw new Error('feedback command was not registered')
  54. return settled.result
  55. }
  56. /** Authoritative feedback payloads in log order. */
  57. function feedbackTexts(session: Session): string[] {
  58. return session.events
  59. .filter(event => event.type === 'feedback/record')
  60. .map(event => event.data.text)
  61. }
  62. describe('@deepseek-ai/dsh-command-feedback registration', () => {
  63. it('registers one global command with Loader-safe exports and disposes it', async () => {
  64. const test = await harness()
  65. expect(commandFeedback.name).toBe('command-feedback')
  66. expect(commandFeedback.inject).toEqual(['commands'])
  67. expect('default' in commandFeedback).toBe(false)
  68. const loader = Object.create(Loader.prototype) as Loader
  69. expect(loader.unwrapExports(commandFeedback)).toBe(commandFeedback)
  70. expect(test.ctx.commands.list(test.agent)).toContainEqual({
  71. name: 'feedback',
  72. description: 'record feedback about this session',
  73. input: { hint: '<text>' },
  74. })
  75. expect(test.ctx.commands.find(test.agent, 'feedback')).toMatchObject({ recordInput: false })
  76. await test.plugin.dispose()
  77. expect(test.ctx.commands.find(test.agent, 'feedback')).toBeUndefined()
  78. })
  79. })
  80. describe('/feedback human command', () => {
  81. it('acknowledges feedback and records its payload exactly once in the domain event', async () => {
  82. const test = await harness()
  83. await expect(run(test, ' the diff view is unreadable')).resolves.toEqual({
  84. kind: 'success',
  85. text: 'Feedback recorded.',
  86. })
  87. expect(feedbackTexts(test.session)).toEqual(['the diff view is unreadable'])
  88. const commandRun = test.session.events.find(event => event.type === 'command/run')
  89. expect(commandRun?.type === 'command/run' && Object.hasOwn(commandRun.data, 'args')).toBe(false)
  90. expect(JSON.stringify(test.session.events).match(/the diff view is unreadable/gu)).toHaveLength(1)
  91. })
  92. it('exports a command-independent feedback producer', async () => {
  93. const test = await harness()
  94. commandFeedback.recordFeedback(test.session, ' recorded outside a command ')
  95. expect(test.session.events.map(event => event.type)).toEqual(['feedback/record'])
  96. expect(feedbackTexts(test.session)).toEqual(['recorded outside a command'])
  97. expect(() => { commandFeedback.recordFeedback(test.session, ' \n\t ') })
  98. .toThrow('feedback text must not be empty')
  99. expect(feedbackTexts(test.session)).toEqual(['recorded outside a command'])
  100. })
  101. it('keeps command bookkeeping around the authoritative feedback event', async () => {
  102. const test = await harness()
  103. await run(test, ' nothing else happens')
  104. expect(test.session.events.map(event => event.type)).toEqual([
  105. 'command/run', 'feedback/record', 'command/done',
  106. ])
  107. })
  108. it('normalizes surrounding whitespace without parsing command-like content', async () => {
  109. const test = await harness()
  110. await run(test, ' /plan felt SLOW\n\ttwice today ')
  111. expect(feedbackTexts(test.session)).toEqual(['/plan felt SLOW\n\ttwice today'])
  112. })
  113. it('records each entry separately without replacing earlier ones', async () => {
  114. const test = await harness()
  115. await run(test, ' first')
  116. await run(test, ' second')
  117. expect(feedbackTexts(test.session)).toEqual(['first', 'second'])
  118. })
  119. it('records concurrent submissions in dispatch order', async () => {
  120. const test = await harness()
  121. const signal = new AbortController().signal
  122. // The shipped TUI dispatches commands fire-and-forget.
  123. const settled = await Promise.all([
  124. test.ctx.commands.execute(test.agent, '/feedback first', signal),
  125. test.ctx.commands.execute(test.agent, '/feedback second', signal),
  126. ])
  127. expect(settled.map(item => item?.result)).toEqual([
  128. { kind: 'success', text: 'Feedback recorded.' },
  129. { kind: 'success', text: 'Feedback recorded.' },
  130. ])
  131. expect(feedbackTexts(test.session)).toEqual(['first', 'second'])
  132. })
  133. it('keeps every recorded event off the model surface and out of derived history', async () => {
  134. const test = await harness()
  135. await run(test, ' invisible to the model')
  136. for (const event of test.session.events) {
  137. expect('surfaceOp' in event).toBe(false)
  138. expect(test.session.deriveEventMessage(event)).toBeNull()
  139. }
  140. expect(foldSurface(test.session.events).nodes).toEqual([])
  141. expect(test.session.surface.nodes).toEqual([])
  142. expect(test.session.deriveMessages()).toEqual([])
  143. })
  144. it('rejects empty and whitespace-only input as a failed command record', async () => {
  145. const test = await harness()
  146. const expected = {
  147. kind: 'error',
  148. text: 'Feedback text is required. Usage: /feedback <text>',
  149. }
  150. await expect(run(test)).resolves.toEqual(expected)
  151. await expect(run(test, ' \n\t ')).resolves.toEqual(expected)
  152. expect(feedbackTexts(test.session)).toEqual([])
  153. const done = test.session.events.filter(event => event.type === 'command/done')
  154. expect(done.map(event => event.data.kind)).toEqual(['error', 'error'])
  155. for (const event of test.session.events) {
  156. if (event.type === 'command/run') expect(Object.hasOwn(event.data, 'args')).toBe(false)
  157. }
  158. })
  159. it('records nothing when dispatch rejects an already-cancelled request', async () => {
  160. const test = await harness()
  161. const controller = new AbortController()
  162. controller.abort(new Error('user cancelled the command'))
  163. await expect(test.ctx.commands.execute(test.agent, '/feedback too late', controller.signal))
  164. .rejects.toThrow('user cancelled the command')
  165. expect(test.session.events).toEqual([])
  166. })
  167. })