selection-side-chat-sqlite-fork.test.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. import { describe, expect, it } from "vitest";
  2. import type {
  3. MessageId,
  4. MessageWithParts,
  5. SessionId,
  6. SessionRevert,
  7. SessionStorePort,
  8. } from "@zcode/contracts";
  9. import { createSqliteSessionStore } from "../../adapters/src/storage/session-store/sqlite-session-store.js";
  10. import { createSelectionSideConversation } from "../../core/src/runtime/methods/session-fork.js";
  11. const parentId = "fork-sql-parent" as SessionId;
  12. const ids = ["user-first", "assistant-first", "user-next", "assistant-active"] as MessageId[];
  13. function history(): MessageWithParts[] {
  14. return ids.map((id, index) => {
  15. const user = index % 2 === 0;
  16. const time = { created: index + 1, completed: index + 2 };
  17. return {
  18. info: {
  19. id,
  20. sessionID: parentId,
  21. role: user ? "user" : "assistant",
  22. time,
  23. agent: "build",
  24. tools: {},
  25. ...(user
  26. ? { modelSelection: { providerId: "glm", modelId: "glm-4-air" } }
  27. : {
  28. parentID: ids[index - 1],
  29. providerId: "glm",
  30. modelId: "glm-4-air",
  31. cost: 0,
  32. tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
  33. }),
  34. anchor: {
  35. origin: user ? "realUser" : "assistant",
  36. turnId: `turn-${Math.floor(index / 2)}`,
  37. productTurnId: `product-${Math.floor(index / 2)}`,
  38. },
  39. },
  40. parts: [
  41. {
  42. id: `text-${index}`,
  43. messageID: id,
  44. sessionID: parentId,
  45. type: "text",
  46. text: `body ${id}: ${"large output ".repeat(500)}`,
  47. },
  48. ],
  49. } as MessageWithParts;
  50. });
  51. }
  52. describe("selection side chat SQLite fork integration", () => {
  53. it.each(["idle", "active", "rewound"] as const)(
  54. "copies the correct %s branch with child-local references and complete payloads",
  55. async (state) => {
  56. const store = await createSqliteSessionStore({ dbPath: ":memory:" });
  57. try {
  58. await store.createSession({
  59. id: parentId,
  60. projectID: "project" as never,
  61. slug: "parent",
  62. directory: "/workspace",
  63. title: "parent",
  64. version: "test",
  65. });
  66. const messages = history();
  67. const assistant = messages[1]!;
  68. assistant.parts.push({
  69. id: "tool-first",
  70. sessionID: parentId,
  71. messageID: assistant.info.id,
  72. type: "tool",
  73. tool: "Read",
  74. callID: "source-call",
  75. state: {
  76. status: "completed",
  77. input: { source: "user-first" },
  78. output: "assistant-first body",
  79. title: "Read",
  80. metadata: {},
  81. time: { start: 1, end: 2 },
  82. attachments: [
  83. {
  84. id: "nested-file",
  85. sessionID: parentId,
  86. messageID: assistant.info.id,
  87. type: "file",
  88. mime: "image/png",
  89. url: "data:image/png;base64,source-call",
  90. },
  91. ],
  92. },
  93. } as never);
  94. assistant.parts.push({
  95. id: "compact-first",
  96. sessionID: parentId,
  97. messageID: assistant.info.id,
  98. type: "compaction",
  99. auto: false,
  100. summaryMessageId: assistant.info.id,
  101. tail_start_id: ids[0],
  102. metadata: { compactLeadingMessageIds: [ids[0], "outside-old-branch"] },
  103. compactBoundary: {
  104. summaryMessageIds: [assistant.info.id],
  105. lastSummarizedMessageId: ids[0],
  106. attachmentMessageIds: [ids[0]],
  107. hookResultMessageIds: [ids[0]],
  108. preservedSegment: {
  109. headMessageId: ids[0],
  110. anchorMessageId: ids[0],
  111. tailMessageId: assistant.info.id,
  112. },
  113. turnId: "turn-0",
  114. },
  115. } as never);
  116. assistant.parts.push({
  117. id: "timeline-first",
  118. sessionID: parentId,
  119. messageID: assistant.info.id,
  120. type: "timeline",
  121. timelineType: "context_compaction",
  122. anchorMessageId: ids[0],
  123. anchorTurnId: "turn-0",
  124. summaryMessageId: assistant.info.id,
  125. } as never);
  126. for (const message of messages) {
  127. await store.saveMessage(message.info);
  128. for (const part of message.parts) await store.savePart(part);
  129. }
  130. if (state === "rewound")
  131. await store.updateSession({
  132. id: parentId,
  133. revert: {
  134. targetMessageID: ids[2],
  135. keptMessageIDs: ids.slice(0, 2),
  136. branchCutAfterMessageID: ids[3],
  137. } as SessionRevert,
  138. });
  139. const parentBefore = await store.messages({ sessionID: parentId });
  140. const measured: SessionStorePort = new Proxy(store, {
  141. get(target, property) {
  142. if (property === "messages")
  143. return () => {
  144. throw new Error("fork must not read full bodies into JS");
  145. };
  146. const value = Reflect.get(target, property);
  147. return typeof value === "function" ? value.bind(target) : value;
  148. },
  149. });
  150. const runtime = {
  151. sessionId: parentId,
  152. sessionStore: measured,
  153. activeTurn: state === "active" ? { turnId: "turn-1" } : null,
  154. rootTraceContext: { traceId: "trace-fork-sql" },
  155. config: { agentName: "build", mode: "build" },
  156. getSessionModelSelection: () => ({ providerId: "glm", modelId: "glm-4-air" }),
  157. workingDirectory: "/workspace",
  158. workspaceRoot: "/workspace",
  159. };
  160. const result = await createSelectionSideConversation.call(runtime as never, {
  161. sourceCommandId: "create-child",
  162. });
  163. const child = await store.messages({ sessionID: result.forkedSessionId });
  164. const count = state === "idle" ? 4 : state === "active" ? 3 : 2;
  165. expect(result.copiedMessageCount).toBe(count);
  166. expect(child).toHaveLength(count + 1);
  167. expect(child.slice(0, count).map((message) => message.info.visibility)).toEqual(
  168. Array(count).fill("model-only"),
  169. );
  170. expect(child.slice(0, count).map((message) => message.parts[0])).toEqual(
  171. parentBefore.slice(0, count).map((message, index) => ({
  172. ...message.parts[0],
  173. id: child[index]!.parts[0]!.id,
  174. sessionID: result.forkedSessionId,
  175. messageID: child[index]!.info.id,
  176. })),
  177. );
  178. expect(child[1]!.info).toMatchObject({ parentID: child[0]!.info.id });
  179. expect(child[0]!.info.anchor?.turnId).not.toBe("turn-0");
  180. expect(child[1]!.parts[1]).toMatchObject({
  181. state: {
  182. input: { source: "user-first" },
  183. output: "assistant-first body",
  184. attachments: [
  185. {
  186. sessionID: result.forkedSessionId,
  187. messageID: child[1]!.info.id,
  188. url: "data:image/png;base64,source-call",
  189. },
  190. ],
  191. },
  192. });
  193. expect(child[1]!.parts[1]).not.toMatchObject({ callID: "source-call" });
  194. expect(child[1]!.parts[2]).toMatchObject({
  195. summaryMessageId: child[1]!.info.id,
  196. tail_start_id: child[0]!.info.id,
  197. metadata: { compactLeadingMessageIds: [child[0]!.info.id] },
  198. compactBoundary: {
  199. summaryMessageIds: [child[1]!.info.id],
  200. preservedSegment: {
  201. headMessageId: child[0]!.info.id,
  202. anchorMessageId: child[0]!.info.id,
  203. tailMessageId: child[1]!.info.id,
  204. },
  205. },
  206. });
  207. expect(child[1]!.parts[3]).toMatchObject({
  208. anchorMessageId: child[0]!.info.id,
  209. anchorTurnId: child[0]!.info.anchor!.turnId,
  210. summaryMessageId: child[1]!.info.id,
  211. });
  212. expect(child.at(-1)!.info).toMatchObject({ source: "selection_side_chat" });
  213. expect(await store.messages({ sessionID: parentId })).toEqual(parentBefore);
  214. const duplicate = await createSelectionSideConversation.call(runtime as never, {
  215. sourceCommandId: "create-child",
  216. });
  217. expect(duplicate.forkedSessionId).toBe(result.forkedSessionId);
  218. expect(await store.messages({ sessionID: result.forkedSessionId })).toEqual(child);
  219. } finally {
  220. store.close();
  221. }
  222. },
  223. );
  224. });