runtime-task-notification-usage.test.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. createMessageId,
  4. createRootTraceContext,
  5. createSessionId,
  6. SessionEventType,
  7. type ModelInputMessage,
  8. } from "@zcode/contracts";
  9. import type { RuntimeMessageEntry } from "../src/agent/message-history.js";
  10. import type { AgentRuntimeInternal } from "../src/runtime/internal.js";
  11. import { buildProviderRequestMessages } from "../src/runtime/helpers/provider-request-messages.js";
  12. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  13. import { createTestSessionEventStore } from "./test-event-store.js";
  14. import { createTestModelFactory, createTestRuntimeModel } from "./test-runtime-model.js";
  15. const contextBody = "project instructions already counted by sections";
  16. const notificationBody =
  17. "<task-notification>result one</task-notification>\n\n<task-notification>result two</task-notification>";
  18. describe("new-turn task notification context usage", () => {
  19. it.each([true, false])(
  20. "counts the full notification once without recounting sections, MCS=%s",
  21. (mcs) => {
  22. const sessionId = createSessionId("notification-usage-sections");
  23. const runtime = createTestAgentRuntime(
  24. sessionId,
  25. {},
  26. {
  27. eventStore: createTestSessionEventStore(),
  28. },
  29. ) as unknown as AgentRuntimeInternal;
  30. runtime.latestContextBuildResult = {
  31. sections: [
  32. {
  33. name: "Project instructions",
  34. source: "request_user_context",
  35. injectionTarget: "meta_user",
  36. cacheHint: "stable",
  37. chars: contextBody.length,
  38. tokens: 12,
  39. content: contextBody,
  40. preview: contextBody,
  41. },
  42. ],
  43. totalChars: contextBody.length,
  44. totalTokens: 12,
  45. systemMessages: [],
  46. metaUserAttachments: [],
  47. };
  48. const entries: RuntimeMessageEntry[] = [
  49. { kind: "attachment", content: contextBody, metadata: { source: "context_prefix" } },
  50. {
  51. message: { role: "user", content: "inspect results" },
  52. metadata: { source: "real_user" },
  53. },
  54. { message: { role: "assistant", content: "background launched" } },
  55. {
  56. message: { role: "user", content: notificationBody },
  57. metadata: { source: "legacy_synthetic", inputPresentation: "task_notification" },
  58. },
  59. ];
  60. const projection = buildProviderRequestMessages({ entries, useMidConversationSystem: mcs });
  61. const before = structuredClone(entries);
  62. const options = {
  63. ...projection,
  64. model: createTestRuntimeModel({
  65. generateText: async () => ({ text: "done", finishReason: "stop", usage: {} }),
  66. }),
  67. tools: [],
  68. events: [],
  69. assistantMessageId: createMessageId(),
  70. traceContext: createRootTraceContext({ sessionId }),
  71. };
  72. const snapshot = runtime.buildContextUsageSnapshot(options);
  73. const notification = projection.messages.at(-1)!;
  74. expect(notification.content).toContain(
  75. "<system-reminder>\n[SYSTEM NOTIFICATION - NOT USER INPUT]",
  76. );
  77. const expectedMessagesChars = [
  78. { role: "user", content: "inspect results" },
  79. { role: "assistant", content: "background launched" },
  80. { role: "user", content: notification.content },
  81. ].reduce((sum, message) => sum + JSON.stringify(message).length, 0);
  82. // 指令按请求里 context_prefix 公告的真实文本计(context-composition.md §3.1),不再按 section 估算。
  83. const instructionMessage = projection.messages[0]!;
  84. const expectedInstructionChars = JSON.stringify({
  85. role: instructionMessage.role,
  86. content: instructionMessage.content,
  87. }).length;
  88. expect(runtime.buildContextUsageBreakdownFromSnapshot(snapshot)).toEqual([
  89. { source: "meta_user_context", chars: expectedInstructionChars },
  90. { source: "messages", chars: expectedMessagesChars },
  91. ]);
  92. expect(snapshot.totalChars).toBe(expectedInstructionChars + expectedMessagesChars);
  93. expect(runtime.buildContextUsageSnapshot(options)).toEqual(snapshot);
  94. expect(entries).toEqual(before);
  95. expect(projection.diagnostics.latestRealUserMessageIndex).toBe(1);
  96. },
  97. );
  98. it.each([true, false])(
  99. "publishes notification usage through the real turn loop, MCS=%s",
  100. async (mcs) => {
  101. const sessionId = createSessionId(`notification-usage-loop-${mcs}`);
  102. const eventStore = createTestSessionEventStore();
  103. const requests: ModelInputMessage[][] = [];
  104. const runtime = createTestAgentRuntime(
  105. sessionId,
  106. {},
  107. {
  108. eventStore,
  109. modelFactory: createTestModelFactory({
  110. properties: { supportsMidConversationSystem: mcs },
  111. async generateText(request) {
  112. requests.push(request.messages);
  113. return {
  114. text: "done",
  115. finishReason: "stop",
  116. usage: { inputTokens: 100, outputTokens: 1 },
  117. };
  118. },
  119. }),
  120. },
  121. );
  122. await runtime.executeTurn("launch background work");
  123. (runtime as unknown as AgentRuntimeInternal).enqueueBackgroundTaskNotification({
  124. text: notificationBody,
  125. traceContext: createRootTraceContext({ sessionId }),
  126. });
  127. await vi.waitFor(async () => {
  128. const events = await eventStore.getEvents(sessionId);
  129. expect(
  130. events.filter((event) => event.type === SessionEventType.ModelComplete),
  131. ).toHaveLength(2);
  132. });
  133. expect(requests).toHaveLength(2);
  134. const notification = requests[1]!.at(-1)!;
  135. expect(notification.role).toBe("user");
  136. // 每条通知各自包装,正文逐条出现在请求里。
  137. for (const part of notificationBody.split("\n\n")) {
  138. expect(notification.content).toContain(part);
  139. }
  140. expect(JSON.stringify(requests)).not.toContain("sourceEntries");
  141. const completions = (await eventStore.getEvents(sessionId)).filter(
  142. (event) => event.type === SessionEventType.ModelComplete,
  143. );
  144. const chars = (index: number) =>
  145. (
  146. completions[index]!.payload as {
  147. contextUsageBreakdown: Array<{ source: string; chars: number }>;
  148. }
  149. ).contextUsageBreakdown.find((item) => item.source === "messages")!.chars;
  150. const expectedIncrease =
  151. JSON.stringify({ role: "assistant", content: "done" }).length +
  152. JSON.stringify({ role: "user", content: notification.content }).length;
  153. expect(chars(1) - chars(0)).toBe(expectedIncrease);
  154. expect(completions[1]!.payload).toMatchObject({
  155. usage: { inputTokens: 100, outputTokens: 1 },
  156. });
  157. },
  158. );
  159. });