command-feedback.spec.ts 10 KB

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