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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. import { ProductProjection } from "../src/zcode-protocol-v4/index.js";
  12. import {
  13. eventsCoverTranscript,
  14. synthesizeEventsFromMessages,
  15. } from "../src/zcode-protocol-v4/transcript-hydration.js";
  16. const parentId = "fork-sql-parent" as SessionId;
  17. const ids = ["user-first", "assistant-first", "user-next", "assistant-active"] as MessageId[];
  18. const worktreeCreation = {
  19. path: "/workspace-worktrees/a1b2/repo",
  20. sha: "0123456789abcdef0123456789abcdef01234567",
  21. ref: null,
  22. output: "Preparing worktree (detached HEAD 0123456)\n",
  23. };
  24. function history(): MessageWithParts[] {
  25. return ids.map((id, index) => {
  26. const user = index % 2 === 0;
  27. const time = { created: index + 1, completed: index + 2 };
  28. return {
  29. info: {
  30. id,
  31. sessionID: parentId,
  32. role: user ? "user" : "assistant",
  33. time,
  34. agent: "build",
  35. tools: {},
  36. ...(user
  37. ? { modelSelection: { providerId: "glm", modelId: "glm-4-air" } }
  38. : {
  39. parentID: ids[index - 1],
  40. providerId: "glm",
  41. modelId: "glm-4-air",
  42. cost: 0,
  43. tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
  44. }),
  45. anchor: {
  46. origin: user ? "realUser" : "assistant",
  47. turnId: `turn-${Math.floor(index / 2)}`,
  48. productTurnId: `product-${Math.floor(index / 2)}`,
  49. },
  50. },
  51. parts: [
  52. {
  53. id: `text-${index}`,
  54. messageID: id,
  55. sessionID: parentId,
  56. type: "text",
  57. text: `body ${id}: ${"large output ".repeat(500)}`,
  58. },
  59. ],
  60. } as MessageWithParts;
  61. });
  62. }
  63. /** 与 `persistAssistantTimelinePartForSession` 写入的时间线标记同形:kind=timeline_event、UI 可见。 */
  64. function timelineMessage(
  65. id: string,
  66. created: number,
  67. parts: Record<string, unknown>[],
  68. ): MessageWithParts {
  69. return {
  70. info: {
  71. id,
  72. sessionID: parentId,
  73. role: "assistant",
  74. time: { created, completed: created },
  75. parentID: id,
  76. providerId: "glm",
  77. modelId: "glm-4-air",
  78. agent: "build",
  79. cost: 0,
  80. tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  81. finish: "completed",
  82. semantics: {
  83. origin: "system",
  84. kind: "timeline_event",
  85. uiVisibility: "visible",
  86. providerVisibility: "hidden",
  87. transcriptVisibility: "visible",
  88. },
  89. },
  90. parts: parts.map((part, index) => ({
  91. id: `${id}-part-${index}`,
  92. sessionID: parentId,
  93. messageID: id,
  94. type: "timeline",
  95. status: "completed",
  96. ...part,
  97. })),
  98. } as MessageWithParts;
  99. }
  100. describe("selection side chat SQLite fork integration", () => {
  101. it.each(["idle", "active", "rewound"] as const)(
  102. "copies the correct %s branch with child-local references and complete payloads",
  103. async (state) => {
  104. const store = await createSqliteSessionStore({ dbPath: ":memory:" });
  105. try {
  106. await store.createSession({
  107. id: parentId,
  108. projectID: "project" as never,
  109. slug: "parent",
  110. directory: "/workspace",
  111. title: "parent",
  112. version: "test",
  113. });
  114. const messages = history();
  115. const assistant = messages[1]!;
  116. assistant.parts.push({
  117. id: "tool-first",
  118. sessionID: parentId,
  119. messageID: assistant.info.id,
  120. type: "tool",
  121. tool: "Read",
  122. callID: "source-call",
  123. state: {
  124. status: "completed",
  125. input: { source: "user-first" },
  126. output: "assistant-first body",
  127. title: "Read",
  128. metadata: {},
  129. time: { start: 1, end: 2 },
  130. attachments: [
  131. {
  132. id: "nested-file",
  133. sessionID: parentId,
  134. messageID: assistant.info.id,
  135. type: "file",
  136. mime: "image/png",
  137. url: "data:image/png;base64,source-call",
  138. },
  139. ],
  140. },
  141. } as never);
  142. assistant.parts.push({
  143. id: "compact-first",
  144. sessionID: parentId,
  145. messageID: assistant.info.id,
  146. type: "compaction",
  147. auto: false,
  148. summaryMessageId: assistant.info.id,
  149. tail_start_id: ids[0],
  150. metadata: { compactLeadingMessageIds: [ids[0], "outside-old-branch"] },
  151. compactBoundary: {
  152. summaryMessageIds: [assistant.info.id],
  153. lastSummarizedMessageId: ids[0],
  154. attachmentMessageIds: [ids[0]],
  155. hookResultMessageIds: [ids[0]],
  156. preservedSegment: {
  157. headMessageId: ids[0],
  158. anchorMessageId: ids[0],
  159. tailMessageId: assistant.info.id,
  160. },
  161. turnId: "turn-0",
  162. },
  163. } as never);
  164. assistant.parts.push({
  165. id: "timeline-first",
  166. sessionID: parentId,
  167. messageID: assistant.info.id,
  168. type: "timeline",
  169. timelineType: "context_compaction",
  170. anchorMessageId: ids[0],
  171. anchorTurnId: "turn-0",
  172. summaryMessageId: assistant.info.id,
  173. } as never);
  174. for (const message of messages) {
  175. await store.saveMessage(message.info);
  176. for (const part of message.parts) await store.savePart(part);
  177. }
  178. if (state === "rewound")
  179. await store.updateSession({
  180. id: parentId,
  181. revert: {
  182. targetMessageID: ids[2],
  183. keptMessageIDs: ids.slice(0, 2),
  184. branchCutAfterMessageID: ids[3],
  185. } as SessionRevert,
  186. });
  187. const parentBefore = await store.messages({ sessionID: parentId });
  188. const measured: SessionStorePort = new Proxy(store, {
  189. get(target, property) {
  190. if (property === "messages")
  191. return () => {
  192. throw new Error("fork must not read full bodies into JS");
  193. };
  194. const value = Reflect.get(target, property);
  195. return typeof value === "function" ? value.bind(target) : value;
  196. },
  197. });
  198. const runtime = {
  199. sessionId: parentId,
  200. sessionStore: measured,
  201. activeTurn: state === "active" ? { turnId: "turn-1" } : null,
  202. rootTraceContext: { traceId: "trace-fork-sql" },
  203. config: { agentName: "build", mode: "build" },
  204. getSessionModelSelection: () => ({ providerId: "glm", modelId: "glm-4-air" }),
  205. workingDirectory: "/workspace",
  206. workspaceRoot: "/workspace",
  207. };
  208. const result = await createSelectionSideConversation.call(runtime as never, {
  209. sourceCommandId: "create-child",
  210. });
  211. const child = await store.messages({ sessionID: result.forkedSessionId });
  212. const count = state === "idle" ? 4 : state === "active" ? 3 : 2;
  213. expect(result.copiedMessageCount).toBe(count);
  214. expect(child).toHaveLength(count + 1);
  215. expect(child.slice(0, count).map((message) => message.info.visibility)).toEqual(
  216. Array(count).fill("model-only"),
  217. );
  218. expect(child.slice(0, count).map((message) => message.parts[0])).toEqual(
  219. parentBefore.slice(0, count).map((message, index) => ({
  220. ...message.parts[0],
  221. id: child[index]!.parts[0]!.id,
  222. sessionID: result.forkedSessionId,
  223. messageID: child[index]!.info.id,
  224. })),
  225. );
  226. expect(child[1]!.info).toMatchObject({ parentID: child[0]!.info.id });
  227. expect(child[0]!.info.anchor?.turnId).not.toBe("turn-0");
  228. expect(child[1]!.parts[1]).toMatchObject({
  229. state: {
  230. input: { source: "user-first" },
  231. output: "assistant-first body",
  232. attachments: [
  233. {
  234. sessionID: result.forkedSessionId,
  235. messageID: child[1]!.info.id,
  236. url: "data:image/png;base64,source-call",
  237. },
  238. ],
  239. },
  240. });
  241. expect(child[1]!.parts[1]).not.toMatchObject({ callID: "source-call" });
  242. expect(child[1]!.parts[2]).toMatchObject({
  243. summaryMessageId: child[1]!.info.id,
  244. tail_start_id: child[0]!.info.id,
  245. metadata: { compactLeadingMessageIds: [child[0]!.info.id] },
  246. compactBoundary: {
  247. summaryMessageIds: [child[1]!.info.id],
  248. preservedSegment: {
  249. headMessageId: child[0]!.info.id,
  250. anchorMessageId: child[0]!.info.id,
  251. tailMessageId: child[1]!.info.id,
  252. },
  253. },
  254. });
  255. expect(child[1]!.parts[3]).toMatchObject({
  256. anchorMessageId: child[0]!.info.id,
  257. anchorTurnId: child[0]!.info.anchor!.turnId,
  258. summaryMessageId: child[1]!.info.id,
  259. });
  260. expect(child.at(-1)!.info).toMatchObject({ source: "selection_side_chat" });
  261. expect(await store.messages({ sessionID: parentId })).toEqual(parentBefore);
  262. const duplicate = await createSelectionSideConversation.call(runtime as never, {
  263. sourceCommandId: "create-child",
  264. });
  265. expect(duplicate.forkedSessionId).toBe(result.forkedSessionId);
  266. expect(await store.messages({ sessionID: result.forkedSessionId })).toEqual(child);
  267. } finally {
  268. store.close();
  269. }
  270. },
  271. );
  272. // SSC19:worktree 任务首条「已创建 worktree」和 fork 到新 worktree 的分叉标记都是 timeline_event。
  273. // 复制进辅助对话时只改可见性、保留 kind;冷恢复必须按继承历史隐藏,不能显示在辅助对话里。
  274. it("keeps inherited timeline markers out of the child timeline", async () => {
  275. const store = await createSqliteSessionStore({ dbPath: ":memory:" });
  276. try {
  277. await store.createSession({
  278. id: parentId,
  279. projectID: "project" as never,
  280. slug: "parent",
  281. directory: worktreeCreation.path,
  282. title: "parent",
  283. version: "test",
  284. });
  285. const messages = [
  286. timelineMessage("worktree-created", 0, [
  287. { timelineType: "worktree_creation", display: "worklog", worktreeCreation },
  288. ]),
  289. ...history(),
  290. timelineMessage("fork-notice", 9, [
  291. {
  292. timelineType: "session_fork",
  293. display: "separator",
  294. anchorMessageId: ids[3],
  295. anchorTurnId: "turn-1",
  296. parentSessionId: "grandparent",
  297. targetMessageId: "grandparent-message",
  298. restoredFileCount: 0,
  299. },
  300. {
  301. timelineType: "worktree_creation",
  302. display: "worklog",
  303. anchorMessageId: ids[3],
  304. anchorTurnId: "turn-1",
  305. worktreeCreation,
  306. },
  307. ]),
  308. ];
  309. for (const message of messages) {
  310. await store.saveMessage(message.info);
  311. for (const part of message.parts) await store.savePart(part);
  312. }
  313. const runtime = {
  314. sessionId: parentId,
  315. sessionStore: store,
  316. activeTurn: null,
  317. rootTraceContext: { traceId: "trace-fork-sql-timeline" },
  318. config: { agentName: "build", mode: "build" },
  319. getSessionModelSelection: () => ({ providerId: "glm", modelId: "glm-4-air" }),
  320. workingDirectory: worktreeCreation.path,
  321. workspaceRoot: worktreeCreation.path,
  322. };
  323. const result = await createSelectionSideConversation.call(runtime as never, {
  324. sourceCommandId: "create-child-timeline",
  325. });
  326. // 「已创建 worktree」暂存到首个 TurnStarted 才落位,所以要有辅助对话自己的第一问。
  327. const questionId = "side-question" as MessageId;
  328. await store.saveMessage({
  329. id: questionId,
  330. sessionID: result.forkedSessionId,
  331. role: "user",
  332. time: { created: 20 },
  333. agent: "build",
  334. modelSelection: { providerId: "glm", modelId: "glm-4-air" },
  335. } as MessageWithParts["info"]);
  336. await store.savePart({
  337. id: "side-question-text",
  338. sessionID: result.forkedSessionId,
  339. messageID: questionId,
  340. type: "text",
  341. text: "side question",
  342. } as MessageWithParts["parts"][number]);
  343. const child = await store.messages({ sessionID: result.forkedSessionId });
  344. expect(child[0]!.info).toMatchObject({
  345. visibility: "model-only",
  346. semantics: { kind: "timeline_event", uiVisibility: "hidden" },
  347. });
  348. const events = synthesizeEventsFromMessages(child, { sessionId: result.forkedSessionId });
  349. const projection = new ProductProjection(result.forkedSessionId, "epoch");
  350. for (const event of events) projection.applyEvent(event);
  351. const rows = projection.getSnapshot().rows.window;
  352. expect(rows.filter((row) => row.kind === "timelineMarker")).toEqual([]);
  353. expect(rows.flatMap((row) => (row.kind === "userInput" ? [row.text] : []))).toEqual([
  354. "side question",
  355. ]);
  356. expect(eventsCoverTranscript(events, child)).toBe(true);
  357. } finally {
  358. store.close();
  359. }
  360. });
  361. });