loader-composition.spec.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. import { mkdtemp, rm, writeFile } from 'node:fs/promises'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { pathToFileURL } from 'node:url'
  5. import { afterEach, describe, expect, it } from 'vitest'
  6. import { Context } from '@deepseek-ai/cordis'
  7. import Include from '@deepseek-ai/cordis-plugin-include'
  8. import Loader from '@deepseek-ai/cordis-plugin-loader'
  9. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  10. import JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
  11. import { remoteMethods } from '@deepseek-ai/dsh-typert-protocol'
  12. import MessageFeedbackService from '../src/index.ts'
  13. import { appendMessageFixture } from './helpers.ts'
  14. let root: string | undefined
  15. const contexts: Context[] = []
  16. afterEach(async () => {
  17. await Promise.all(contexts.splice(0).map(ctx => ctx.fiber.dispose()))
  18. if (root !== undefined) await rm(root, { recursive: true, force: true })
  19. root = undefined
  20. })
  21. async function loadComposition(configPath: string): Promise<Context> {
  22. const ctx = new Context()
  23. contexts.push(ctx)
  24. ctx.baseUrl = pathToFileURL(root as string).href + '/'
  25. await ctx.plugin(Loader)
  26. ctx.loader.builtins.include = Include
  27. const modules = new Map<string, unknown>([
  28. ['@deepseek-ai/dsh-session', SessionStore],
  29. ['@deepseek-ai/dsh-session-persistence-jsonl', JsonlSessionPersistence],
  30. ['@deepseek-ai/dsh-message-feedback', MessageFeedbackService],
  31. ])
  32. ctx.loader.internal = {
  33. version: 'v2',
  34. async import(specifier: string) {
  35. if (!modules.has(specifier)) throw new Error(`unexpected Loader import: ${specifier}`)
  36. return modules.get(specifier)
  37. },
  38. } as unknown as NonNullable<typeof ctx.loader.internal>
  39. await ctx.loader.create({
  40. name: 'cordis:include',
  41. config: { path: pathToFileURL(configPath).href },
  42. })
  43. await ctx.loader.await()
  44. const unloaded = [...ctx.loader.entries()]
  45. .filter(entry => entry.fiber === undefined && !entry.disabled)
  46. .map(entry => entry.options.name)
  47. expect(unloaded).toEqual([])
  48. return ctx
  49. }
  50. describe('message feedback through a real Loader composition', () => {
  51. it('persists canonical feedback across live and cold operations', async () => {
  52. root = await mkdtemp(join(tmpdir(), 'dsh-message-feedback-loader-'))
  53. const configPath = join(root, 'cordis.yml')
  54. await writeFile(configPath, [
  55. "- name: '@deepseek-ai/dsh-session'",
  56. "- name: '@deepseek-ai/dsh-session-persistence-jsonl'",
  57. ' config:',
  58. ` root: ${JSON.stringify(join(root, 'sessions'))}`,
  59. ' compression: none',
  60. "- name: '@deepseek-ai/dsh-message-feedback'",
  61. ' config:',
  62. ' maxNoteBytes: 32',
  63. '',
  64. ].join('\n'))
  65. const first = await loadComposition(configPath)
  66. expect(first.messageFeedback.typertRemote.namespace).toBe('messageFeedback')
  67. expect(remoteMethods(first.messageFeedback).map(marker => marker.method))
  68. .toEqual(['list', 'put', 'delete'])
  69. const unowned = first.sessions.create(SessionId('unowned-feedback'))
  70. const unownedFixture = appendMessageFixture(unowned)
  71. const unownedRequest = {
  72. sessionId: unowned.id, messageId: unownedFixture.assistantMessageIds[0], rating: 'positive' as const, ifVersion: null,
  73. }
  74. // A mounted JSONL listener alone does not persist Sessions without a write handle.
  75. await expect(first.messageFeedback.put(unownedRequest)).rejects.toThrow(/not found/u)
  76. expect(await first.sessionPersistence.stat(unowned.id)).toBeUndefined()
  77. const unownedItems = await first.messageFeedback.list({ sessionId: unowned.id })
  78. if (!unownedItems.ok) throw new Error(unownedItems.error.code)
  79. await expect(first.messageFeedback.put({ ...unownedRequest, ifVersion: unownedItems.value.items[0]!.version }))
  80. .rejects.toThrow(/not found/u)
  81. const session = first.sessions.create(SessionId('loader-feedback'), {
  82. meta: { cwd: root },
  83. })
  84. // The mounted backend routes this published session's `session/event`
  85. // batches and `session/flush` barriers into its active write handle.
  86. const writeHandle = await first.sessionPersistence.create(session.header)
  87. const fixture = appendMessageFixture(session)
  88. const put = await first.messageFeedback.put({
  89. sessionId: session.id,
  90. messageId: fixture.assistantMessageIds[0],
  91. rating: 'positive',
  92. note: 'survives restart',
  93. ifVersion: null,
  94. })
  95. if (!put.ok) throw new Error(`expected put success, got ${put.error.code}`)
  96. const readHandle = await first.sessionPersistence.open(session.id, 'read')
  97. const { events: durableEvents } = await readHandle.read()
  98. await readHandle.close()
  99. expect(durableEvents.some(event =>
  100. event.type === 'assistant/message'
  101. && event.data.message.id === fixture.assistantMessageIds[0])).toBe(true)
  102. await writeHandle.close()
  103. await first.fiber.dispose()
  104. contexts.splice(contexts.indexOf(first), 1)
  105. const second = await loadComposition(configPath)
  106. await expect(second.messageFeedback.list({ sessionId: session.id })).resolves.toEqual({
  107. ok: true,
  108. value: { items: [put.value] },
  109. })
  110. const edited = await second.messageFeedback.put({
  111. sessionId: session.id,
  112. messageId: fixture.assistantMessageIds[0],
  113. rating: 'negative',
  114. note: 'cold edit',
  115. ifVersion: put.value.version,
  116. })
  117. if (!edited.ok) throw new Error(edited.error.code)
  118. await second.messageFeedback.delete({ sessionId: session.id, messageId: edited.value.messageId, ifVersion: edited.value.version })
  119. const coldHandle = await second.sessionPersistence.open(session.id, 'read')
  120. try {
  121. const { events: coldEvents } = await coldHandle.read()
  122. expect(coldEvents.slice(0, durableEvents.length)).toEqual(durableEvents)
  123. expect(coldEvents.slice(durableEvents.length).map(event => event.type)).toEqual(['feedback/message-put', 'feedback/message-delete'])
  124. } finally {
  125. await coldHandle.close()
  126. }
  127. expect(second.sessions.get(session.id)).toBeUndefined()
  128. })
  129. })