taskNotificationOrchestrator.test.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. import { describe, expect, it } from "vitest";
  2. import type { ConversationSnapshot, SessionSummary } from "@zcode/shared/zcode-protocol-v4";
  3. import {
  4. collectPendingInteractionNotificationPayloads,
  5. collectTerminalTaskNotificationPayloads,
  6. } from "../src/lib/taskNotificationOrchestrator.js";
  7. const messages: Record<string, string> = {
  8. "notification.completed": "Task completed",
  9. "notification.completedBody": "Task completed",
  10. "notification.error": "Task error occurred",
  11. "notification.inputRequired": "Your response is needed",
  12. "notification.permissionRequired": "Your confirmation is needed",
  13. "notification.planApprovalBody": "Review the plan to continue.",
  14. "notification.planApprovalRequired": "Plan awaiting approval",
  15. "notification.taskWithTitle": "Task: {title}",
  16. };
  17. const formatMessage = (descriptor: { id: string }, values?: Record<string, string>) => {
  18. let message = messages[descriptor.id] ?? descriptor.id;
  19. for (const [key, value] of Object.entries(values ?? {})) {
  20. message = message.replaceAll(`{${key}}`, value);
  21. }
  22. return message;
  23. };
  24. function sessionSummary(
  25. phase: SessionSummary["phase"],
  26. overrides: Partial<SessionSummary> = {},
  27. ): SessionSummary {
  28. return {
  29. sessionId: "session-1",
  30. workspaceId: "workspace-1",
  31. title: "Build docs",
  32. phase,
  33. sessionEnded: phase === "completedSuccess" || phase === "completedInterrupted",
  34. hasBackgroundWork: false,
  35. lastActivityAt: 100,
  36. createdAt: 1,
  37. ...overrides,
  38. };
  39. }
  40. function snapshot(overrides: Partial<ConversationSnapshot> = {}): ConversationSnapshot {
  41. return {
  42. protocolVersion: 1,
  43. sessionId: "session-1",
  44. logEpoch: "epoch-1",
  45. seq: 1,
  46. revision: 1,
  47. control: {
  48. phase: "running",
  49. sessionEnded: false,
  50. canStop: true,
  51. stopState: "stoppable",
  52. stopTargetKind: "assistant",
  53. activeWorks: [],
  54. lastError: null,
  55. apiRetry: null,
  56. },
  57. availability: {
  58. fork: { allowed: true },
  59. compact: { allowed: false, reasonCode: "running" },
  60. switchModelConfig: { allowed: false, reasonCode: "running" },
  61. setFollowupMode: { allowed: true },
  62. queueEdit: { allowed: true },
  63. sendQueuedNow: { allowed: true },
  64. pauseGoal: { allowed: false, reasonCode: "noGoal" },
  65. resumeGoal: { allowed: false, reasonCode: "noGoal" },
  66. },
  67. inputRouting: { mode: "enqueue" },
  68. meta: { title: "Build docs", titleSource: "custom" },
  69. config: { provider: "", model: "", thought: "", followupMode: "queue", mode: "build" },
  70. usage: {
  71. contextWindow: null,
  72. cumulative: {
  73. inputTokens: 0,
  74. outputTokens: 0,
  75. cacheReadTokens: 0,
  76. cacheWriteTokens: 0,
  77. },
  78. },
  79. queue: { items: [], autoDrain: true },
  80. pendingInteractions: [],
  81. pendingCommands: [],
  82. backgroundWorks: [],
  83. goal: null,
  84. plan: null,
  85. rows: { window: [], totalCount: 0, firstRowId: null },
  86. ...overrides,
  87. };
  88. }
  89. describe("task notification orchestrator", () => {
  90. it("emits terminal notification only for observed non-terminal to terminal edges", () => {
  91. const previousBySessionId = new Map<string, SessionSummary>([
  92. ["session-1", sessionSummary("running")],
  93. ["session-2", sessionSummary("completedSuccess", { sessionId: "session-2" })],
  94. ]);
  95. expect(
  96. collectTerminalTaskNotificationPayloads({
  97. previousBySessionId,
  98. sessions: [
  99. sessionSummary("completedSuccess"),
  100. sessionSummary("error", { sessionId: "session-2", title: "Already done" }),
  101. sessionSummary("completedSuccess", { sessionId: "new-cold-session" }),
  102. ],
  103. formatMessage,
  104. }),
  105. ).toEqual([
  106. {
  107. taskId: "session-1",
  108. status: "completed",
  109. title: "Task completed",
  110. body: "Task: Build docs",
  111. },
  112. {
  113. taskId: "session-2",
  114. status: "failed",
  115. title: "Task error occurred",
  116. body: "Task: Already done",
  117. },
  118. ]);
  119. });
  120. it("emits pending interaction notifications only for unseen requests", () => {
  121. const seenRequestIds = new Set(["seen-permission"]);
  122. const payloads = collectPendingInteractionNotificationPayloads({
  123. snapshot: snapshot({
  124. pendingInteractions: [
  125. {
  126. interactionId: "seen-permission",
  127. kind: "permission",
  128. anchorRowId: null,
  129. createdAt: 1,
  130. payload: {
  131. kind: "permission",
  132. toolCallId: "tool-1",
  133. toolName: "Bash",
  134. summary: "Allow command?",
  135. detail: {},
  136. options: [],
  137. },
  138. },
  139. {
  140. interactionId: "new-question",
  141. kind: "userInput",
  142. anchorRowId: null,
  143. createdAt: 2,
  144. payload: {
  145. kind: "userInput",
  146. prompt: "Which branch should I use?",
  147. freeText: true,
  148. },
  149. },
  150. {
  151. interactionId: "workspace-review",
  152. kind: "workspaceHookReview",
  153. anchorRowId: null,
  154. createdAt: 3,
  155. payload: {
  156. kind: "workspaceHookReview",
  157. reviewFlowId: "flow-1",
  158. generation: 1,
  159. interactionId: "workspace-review",
  160. sessionId: "session-1",
  161. taskId: "session-1",
  162. runId: "run-1",
  163. workspaceIdentity: "/workspace",
  164. workspaceLabel: "workspace",
  165. bundleDigest: "a".repeat(64),
  166. createdAt: 3,
  167. deadlineAt: 603_000,
  168. sourceFiles: [],
  169. summary: { eventCount: 0, hookCount: 0, pendingCount: 0 },
  170. items: [],
  171. warningCode: "workspace_hooks_execute_code",
  172. },
  173. },
  174. {
  175. interactionId: "plan-approval",
  176. kind: "userInput",
  177. anchorRowId: null,
  178. createdAt: 3,
  179. payload: {
  180. kind: "userInput",
  181. prompt: "Review plan",
  182. freeText: true,
  183. schema: { interaction: "plan_approval", toolName: "ExitPlanMode" },
  184. },
  185. },
  186. ],
  187. }),
  188. seenRequestIds,
  189. formatMessage,
  190. });
  191. expect(payloads).toEqual([
  192. {
  193. taskId: "session-1",
  194. status: "elicitation_request",
  195. requestId: "new-question",
  196. title: "Your response is needed",
  197. body: "Which branch should I use?",
  198. },
  199. {
  200. taskId: "session-1",
  201. status: "elicitation_request",
  202. requestId: "plan-approval",
  203. title: "Plan awaiting approval",
  204. body: "Review the plan to continue.",
  205. },
  206. ]);
  207. });
  208. });