command-compact.spec.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import Loader from '@cordisjs/plugin-loader'
  4. import type { Agent } from '@deepseek-ai/dsh-agent'
  5. import CommandService from '@deepseek-ai/dsh-commands'
  6. import {
  7. CompactService,
  8. ManualCompactionError,
  9. type CompactAgentContext,
  10. type CompactionResult,
  11. type CompactionTrigger,
  12. type ManualCompactAgentContext,
  13. } from '@deepseek-ai/dsh-compact'
  14. import { Session, SessionId } from '@deepseek-ai/dsh-session'
  15. import * as commandCompact from '@deepseek-ai/dsh-command-compact'
  16. const RESULT: CompactionResult = {
  17. startSeq: 10,
  18. summarySeq: 11,
  19. endSeq: 13,
  20. summary: [{ type: 'text', text: 'summary' }],
  21. shadowedRange: { start: 1, end: 7 },
  22. shadowedSeqs: [1, 3, 7],
  23. shadowedTokenCount: 42,
  24. }
  25. class StubCompactService extends CompactService {
  26. result: CompactionResult | null = RESULT
  27. failure: unknown
  28. operation: (() => Promise<CompactionResult | null>) | undefined
  29. calls: { agent: ManualCompactAgentContext; signal: AbortSignal }[] = []
  30. override compactIfNeeded(
  31. _agent: CompactAgentContext,
  32. _trigger: CompactionTrigger,
  33. _signal: AbortSignal,
  34. ): Promise<CompactionResult | null> {
  35. return Promise.resolve(null)
  36. }
  37. override compactRegion(): Promise<CompactionResult> {
  38. return Promise.resolve(RESULT)
  39. }
  40. override compactNow(
  41. agent: ManualCompactAgentContext,
  42. signal: AbortSignal,
  43. ): Promise<CompactionResult | null> {
  44. this.calls.push({ agent, signal })
  45. if (this.operation !== undefined) return this.operation()
  46. return this.failure === undefined
  47. ? Promise.resolve(this.result)
  48. // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- exercise arbitrary backend rejection values.
  49. : Promise.reject(this.failure)
  50. }
  51. }
  52. interface Harness {
  53. readonly ctx: Context
  54. readonly compact: StubCompactService
  55. readonly agent: Agent
  56. readonly plugin: Awaited<ReturnType<Context['plugin']>>
  57. }
  58. async function harness(): Promise<Harness> {
  59. const ctx = new Context()
  60. await ctx.plugin(CommandService)
  61. const compact = new StubCompactService(ctx)
  62. const plugin = await ctx.plugin(commandCompact)
  63. const session = new Session(SessionId('command-compact'))
  64. const agent = {
  65. session,
  66. status: 'idle',
  67. options: {},
  68. reserveTurnAdmission: () => () => undefined,
  69. } as unknown as Agent
  70. return { ctx, compact, agent, plugin }
  71. }
  72. async function run(
  73. test: Harness,
  74. suffix = '',
  75. controller = new AbortController(),
  76. ): Promise<NonNullable<Awaited<ReturnType<CommandService['execute']>>>> {
  77. const execution = await test.ctx.commands.execute(test.agent, `/compact${suffix}`, controller.signal)
  78. if (execution === undefined) throw new Error('compact command was not registered')
  79. return execution
  80. }
  81. /** Assert the executor-owned lifecycle pair and absence from model history. */
  82. function expectLastLifecycle(
  83. test: Harness,
  84. args: string,
  85. outcome: { readonly kind: 'success' | 'error'; readonly text?: string },
  86. ): string {
  87. const lifecycle = test.agent.session.events.slice(-2)
  88. const runEvent = lifecycle[0]
  89. const doneEvent = lifecycle[1]
  90. if (runEvent?.type !== 'command/run' || doneEvent?.type !== 'command/done') {
  91. throw new Error(`expected command lifecycle pair, got ${lifecycle.map(event => event.type).join(',')}`)
  92. }
  93. expect(lifecycle.map(event => ({ type: event.type, data: event.data }))).toEqual([
  94. {
  95. type: 'command/run',
  96. data: {
  97. commandId: runEvent.data.commandId,
  98. name: 'compact',
  99. args,
  100. source: { kind: 'user' },
  101. },
  102. },
  103. {
  104. type: 'command/done',
  105. data: {
  106. commandId: runEvent.data.commandId,
  107. ...outcome,
  108. },
  109. },
  110. ])
  111. expect(doneEvent.data.commandId).toBe(runEvent.data.commandId)
  112. expect(test.agent.session.surface.nodes).toEqual([])
  113. expect(test.agent.session.deriveMessages()).toEqual([])
  114. return runEvent.data.commandId
  115. }
  116. describe('@deepseek-ai/dsh-command-compact registration', () => {
  117. it('registers one argument-free command with Loader-safe exports and disposes it', async () => {
  118. const test = await harness()
  119. expect(commandCompact.name).toBe('command-compact')
  120. expect(commandCompact.inject).toEqual(['commands', 'compact'])
  121. expect('default' in commandCompact).toBe(false)
  122. const loader = Object.create(Loader.prototype) as Loader
  123. expect(loader.unwrapExports(commandCompact)).toBe(commandCompact)
  124. expect(test.ctx.commands.list(test.agent)).toContainEqual({
  125. name: 'compact',
  126. description: 'Compact older conversation history',
  127. })
  128. await test.plugin.dispose()
  129. expect(test.ctx.commands.find(test.agent, 'compact')).toBeUndefined()
  130. })
  131. })
  132. describe('/compact human command', () => {
  133. it('reports success with useful accounting and forwards the exact target and signal', async () => {
  134. const test = await harness()
  135. const controller = new AbortController()
  136. const execution = await run(test, '', controller)
  137. expect(execution.result).toEqual({
  138. kind: 'success',
  139. text: 'Compacted 3 history items (~42 tokens).',
  140. })
  141. expect(execution.commandId).toBe(expectLastLifecycle(test, '', execution.result))
  142. expect(test.compact.calls).toEqual([{ agent: test.agent, signal: controller.signal }])
  143. })
  144. it('returns direct no-history and argument-rejection results', async () => {
  145. const test = await harness()
  146. test.compact.result = null
  147. const empty = await run(test)
  148. expect(empty.result).toEqual({
  149. kind: 'success',
  150. text: 'No compactable history yet.',
  151. })
  152. expect(empty.commandId).toBe(expectLastLifecycle(test, '', empty.result))
  153. const rejected = await run(test, ' now')
  154. expect(rejected.result).toEqual({
  155. kind: 'error',
  156. text: 'Usage: /compact (no arguments)',
  157. })
  158. expect(rejected.commandId).toBe(expectLastLifecycle(test, ' now', rejected.result))
  159. expect(test.compact.calls).toHaveLength(1)
  160. })
  161. it.each([
  162. ['busy', 'Compaction is unavailable because this process has an active compaction, or the agent is not idle.'],
  163. ['changed', 'The history selected for compaction changed before it could be replaced. The conversation is unchanged; the attempt is recorded in the session log.'],
  164. ['summary', 'Compaction could not produce a useful summary. The conversation is unchanged; the attempt is recorded in the session log.'],
  165. ['commit', 'Compaction did not finish cleanly; some session history may have changed. Inspect the current session state before retrying.'],
  166. ['persistence', 'Compaction finished, but the session could not be saved.'],
  167. ] as const)('maps expected %s failures to direct errors', async (code, text) => {
  168. const test = await harness()
  169. test.compact.failure = new ManualCompactionError(code, 'backend detail')
  170. const execution = await run(test)
  171. expect(execution.result).toEqual({ kind: 'error', text })
  172. expect(execution.commandId).toBe(expectLastLifecycle(test, '', execution.result))
  173. })
  174. it('preserves cancellation and unexpected implementation failures', async () => {
  175. const cancelled = await harness()
  176. const controller = new AbortController()
  177. const abort = new Error('operator cancelled')
  178. cancelled.compact.operation = () => {
  179. controller.abort(abort)
  180. return Promise.reject(new ManualCompactionError('summary', 'late failure'))
  181. }
  182. await expect(run(cancelled, '', controller)).rejects.toBe(abort)
  183. expectLastLifecycle(cancelled, '', { kind: 'error', text: abort.message })
  184. const unexpected = await harness()
  185. const bug = new Error('unexpected backend bug')
  186. unexpected.compact.failure = bug
  187. await expect(run(unexpected)).rejects.toBe(bug)
  188. expectLastLifecycle(unexpected, '', { kind: 'error', text: bug.message })
  189. })
  190. })