command-feedback.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. import { beforeEach, describe, expect, it, vi } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import Loader from '@deepseek-ai/cordis-plugin-loader'
  4. import AgentRegistry from '@deepseek-ai/dsh-agent'
  5. import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent'
  6. import CommandRuntime 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. import type { FeedbackRecord } from '@deepseek-ai/dsh-command-feedback/types'
  10. import { remoteMethods } from '@deepseek-ai/dsh-typert-protocol'
  11. import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit'
  12. const { USER_ID, getOrCreateAnonymousUserId } = vi.hoisted(() => {
  13. const USER_ID = '01234567-89ab-4cde-8f01-23456789abcd'
  14. return { USER_ID, getOrCreateAnonymousUserId: vi.fn(() => USER_ID) }
  15. })
  16. vi.mock('@deepseek-ai/dsh-anonymous-user-id', () => ({
  17. getOrCreateAnonymousUserId,
  18. }))
  19. beforeEach(() => getOrCreateAnonymousUserId.mockClear())
  20. interface Harness {
  21. readonly ctx: Context
  22. readonly agent: Agent
  23. readonly session: Session
  24. readonly plugin: Awaited<ReturnType<Context['plugin']>>
  25. }
  26. /** Build a live idle agent over a store-owned session, as an app's spine does. */
  27. function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } {
  28. const session = ctx.sessions.create(SessionId(id))
  29. let status: AgentStatus = 'idle'
  30. const agent: Agent = {
  31. id: session.id,
  32. options: {},
  33. session,
  34. inbox: unsupportedInbox(),
  35. ctx: new Context(),
  36. get status() { return status },
  37. send: () => {},
  38. followup: () => {},
  39. steer: () => {},
  40. inject: () => {},
  41. cancel() { status = 'idle' },
  42. runMaintenance: task => task(new AbortController().signal),
  43. whenIdle() { return Promise.resolve() },
  44. }
  45. return { agent, session }
  46. }
  47. async function harness(): Promise<Harness> {
  48. const ctx = new Context()
  49. await ctx.plugin(CommandRuntime)
  50. await ctx.plugin(AgentRegistry)
  51. await ctx.plugin(SessionStore)
  52. const plugin = await ctx.plugin(commandFeedback)
  53. const { agent, session } = stubAgent(ctx, `command-feedback-${Math.random()}`)
  54. ctx.agents.register(agent)
  55. return { ctx, agent, session, plugin }
  56. }
  57. /** Execute `/feedback` through the same registry boundary as a UI adapter. */
  58. async function run(test: Harness, suffix = ''): Promise<{ kind: string; text?: string }> {
  59. const settled = await test.ctx.commands.execute(
  60. test.agent,
  61. `/feedback${suffix}`,
  62. [],
  63. new AbortController().signal,
  64. )
  65. if (settled === undefined) throw new Error('feedback command was not registered')
  66. return settled.result
  67. }
  68. /** Authoritative feedback payloads in log order. */
  69. function feedbackRecords(session: Session): FeedbackRecord[] {
  70. return session.snapshotEvents()
  71. .filter(event => event.type === 'feedback/record')
  72. .map(event => event.data)
  73. }
  74. /** The text of each authoritative feedback payload in log order. */
  75. function feedbackTexts(session: Session): (string | undefined)[] {
  76. return feedbackRecords(session).map(record => record.text)
  77. }
  78. describe('@deepseek-ai/dsh-command-feedback registration', () => {
  79. it('registers one global command with Loader-safe exports and disposes it', async () => {
  80. const test = await harness()
  81. expect(commandFeedback.name).toBe('command-feedback')
  82. expect(commandFeedback.inject).toEqual(['commands'])
  83. expect('default' in commandFeedback).toBe(false)
  84. const loader = Object.create(Loader.prototype) as Loader
  85. expect(loader.unwrapExports(commandFeedback)).toBe(commandFeedback)
  86. expect(test.ctx.commands.list(test.agent)).toContainEqual({
  87. name: 'feedback',
  88. description: 'record feedback about this session',
  89. input: { hint: '<text>' },
  90. })
  91. expect(test.ctx.commands.find(test.agent, 'feedback')).toMatchObject({ recordInput: false })
  92. await test.plugin.dispose()
  93. expect(test.ctx.commands.find(test.agent, 'feedback')).toBeUndefined()
  94. })
  95. })
  96. describe('sessionFeedback Host Remote', () => {
  97. it('publishes the exact Gateway namespace and Remote method name', async () => {
  98. const test = await harness()
  99. const binding = test.ctx.sessionFeedback.typertRemote
  100. expect(binding.serviceKey).toBe('sessionFeedback')
  101. expect(binding.namespace).toBe('sessionFeedback')
  102. expect(remoteMethods(test.ctx.sessionFeedback)).toEqual([
  103. { method: 'record', invocation: { kind: 'direct' } },
  104. ])
  105. })
  106. it('records a remark on the live Session without command bookkeeping', async () => {
  107. const test = await harness()
  108. await expect(test.ctx.sessionFeedback.record({
  109. sessionId: test.session.id, text: ' the diff view is unreadable ', category: 'product-interaction',
  110. })).resolves.toEqual({ ok: true, value: { recorded: true } })
  111. await expect(test.ctx.sessionFeedback.record({ sessionId: test.session.id }))
  112. .resolves.toEqual({ ok: true, value: { recorded: true } })
  113. expect(test.session.snapshotEvents().map(event => event.type)).toEqual(['feedback/record', 'feedback/record'])
  114. expect(feedbackRecords(test.session)).toEqual([
  115. { text: 'the diff view is unreadable', category: 'product-interaction' },
  116. {},
  117. ])
  118. expect(getOrCreateAnonymousUserId).not.toHaveBeenCalled()
  119. })
  120. it('reports session-not-found for a Session no live owner carries', async () => {
  121. const test = await harness()
  122. const missing = SessionId('no-such-session')
  123. await expect(test.ctx.sessionFeedback.record({ sessionId: missing, text: 'lost' }))
  124. .resolves.toEqual({ ok: false, error: { code: 'session-not-found', sessionId: missing } })
  125. expect(test.session.snapshotEvents()).toEqual([])
  126. })
  127. it('is mounted and unmounted with the plugin', async () => {
  128. const test = await harness()
  129. expect(test.ctx.get('sessionFeedback')).toBeDefined()
  130. await test.plugin.dispose()
  131. expect(test.ctx.get('sessionFeedback')).toBeUndefined()
  132. })
  133. })
  134. describe('/feedback human command', () => {
  135. it('acknowledges feedback and records its payload exactly once in the domain event', async () => {
  136. const test = await harness()
  137. await expect(run(test, ' the diff view is unreadable')).resolves.toEqual({
  138. kind: 'success',
  139. text: `Feedback recorded for session ${test.session.id}\nAnonymous user: ${USER_ID}.`,
  140. })
  141. expect(feedbackTexts(test.session)).toEqual(['the diff view is unreadable'])
  142. const commandRun = test.session.snapshotEvents().find(event => event.type === 'command/run')
  143. expect(commandRun?.type === 'command/run' && Object.hasOwn(commandRun.data, 'args')).toBe(false)
  144. expect(JSON.stringify(test.session.snapshotEvents()).match(/the diff view is unreadable/gu)).toHaveLength(1)
  145. })
  146. it('exports a command-independent feedback producer', async () => {
  147. const test = await harness()
  148. commandFeedback.recordFeedback(test.session, { text: ' recorded outside a command ' })
  149. commandFeedback.recordFeedback(test.session, { text: ' \n\t ', category: 'service-stability' })
  150. commandFeedback.recordFeedback(test.session, {})
  151. expect(test.session.snapshotEvents().map(event => event.type))
  152. .toEqual(['feedback/record', 'feedback/record', 'feedback/record'])
  153. // Blank text is recorded as absent; an entry with neither member still records.
  154. expect(feedbackRecords(test.session)).toEqual([
  155. { text: 'recorded outside a command' },
  156. { category: 'service-stability' },
  157. {},
  158. ])
  159. })
  160. it('publishes the fixed category taxonomy in presentation order', () => {
  161. expect(commandFeedback.FEEDBACK_CATEGORIES).toEqual([
  162. 'task-result', 'instruction-following', 'product-interaction', 'service-stability',
  163. 'resource-cost', 'security-privacy-permission', 'other',
  164. ])
  165. })
  166. it('keeps command bookkeeping around the authoritative feedback event', async () => {
  167. const test = await harness()
  168. await run(test, ' nothing else happens')
  169. expect(test.session.snapshotEvents().map(event => event.type)).toEqual([
  170. 'command/run', 'feedback/record', 'command/done',
  171. ])
  172. })
  173. it('normalizes surrounding whitespace without parsing command-like content', async () => {
  174. const test = await harness()
  175. await run(test, ' /plan felt SLOW\n\ttwice today ')
  176. expect(feedbackTexts(test.session)).toEqual(['/plan felt SLOW\n\ttwice today'])
  177. })
  178. it('records each entry separately without replacing earlier ones', async () => {
  179. const test = await harness()
  180. await run(test, ' first')
  181. await run(test, ' second')
  182. expect(feedbackTexts(test.session)).toEqual(['first', 'second'])
  183. })
  184. it('records concurrent submissions in dispatch order', async () => {
  185. const test = await harness()
  186. const signal = new AbortController().signal
  187. // Command adapters may dispatch concurrent requests without awaiting one another.
  188. const settled = await Promise.all([
  189. test.ctx.commands.execute(test.agent, '/feedback first', [], signal),
  190. test.ctx.commands.execute(test.agent, '/feedback second', [], signal),
  191. ])
  192. expect(settled.map(item => item?.result)).toEqual([
  193. { kind: 'success', text: `Feedback recorded for session ${test.session.id}\nAnonymous user: ${USER_ID}.` },
  194. { kind: 'success', text: `Feedback recorded for session ${test.session.id}\nAnonymous user: ${USER_ID}.` },
  195. ])
  196. expect(feedbackTexts(test.session)).toEqual(['first', 'second'])
  197. })
  198. it('keeps every recorded event out of model context and derived history', async () => {
  199. const test = await harness()
  200. await run(test, ' invisible to the model')
  201. for (const event of test.session.snapshotEvents()) {
  202. expect('surfaceOp' in event).toBe(false)
  203. expect(test.session.deriveEventMessage(event)).toBeNull()
  204. }
  205. expect(foldSurface(test.session.snapshotEvents()).nodes).toEqual([])
  206. expect(test.session.surface.nodes).toEqual([])
  207. expect(test.session.deriveMessages()).toEqual([])
  208. })
  209. it('rejects empty and whitespace-only input as a failed command record', async () => {
  210. const test = await harness()
  211. const expected = {
  212. kind: 'error',
  213. text: 'Feedback text is required. Usage: /feedback <text>',
  214. }
  215. await expect(run(test)).resolves.toEqual(expected)
  216. await expect(run(test, ' \n\t ')).resolves.toEqual(expected)
  217. expect(getOrCreateAnonymousUserId).not.toHaveBeenCalled()
  218. expect(feedbackTexts(test.session)).toEqual([])
  219. const done = test.session.snapshotEvents().filter(event => event.type === 'command/done')
  220. expect(done.map(event => event.data.kind)).toEqual(['error', 'error'])
  221. for (const event of test.session.snapshotEvents()) {
  222. if (event.type === 'command/run') expect(Object.hasOwn(event.data, 'args')).toBe(false)
  223. }
  224. })
  225. it('records nothing when dispatch rejects an already-cancelled request', async () => {
  226. const test = await harness()
  227. const controller = new AbortController()
  228. controller.abort(new Error('user cancelled the command'))
  229. await expect(test.ctx.commands.execute(test.agent, '/feedback too late', [], controller.signal))
  230. .rejects.toThrow('user cancelled the command')
  231. expect(test.session.snapshotEvents()).toEqual([])
  232. })
  233. })