v4-detached-child-hydration.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. // detached live child(dwf workflow actor / subagent child)的首次订阅 hydration。
  2. //
  3. // Bug 根因(本文件的存在理由):这类子会话没有自己的 bootstrap record——事件经
  4. // ingestDetachedLiveSession 走父 record 的 sink 路由。旧 loadPersistedEvents 用
  5. // context.sessions.get(childSessionId) 直取,取不到就返回 synthesized:false,
  6. // performHydration 因此走"保留健康 live publisher"早退分支,durable transcript 三源合并
  7. // 从不执行:只有本次 live 事件进入投影,任何**不以 live 事件形态出现**的持久正文全部丢失。
  8. // amend-resume 正是这种形态——它把前驱 actor 的 transcript 前缀直接复制进 session store
  9. // 来播种新 actor 会话(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md),侧栏于是只剩本轮增量。
  10. //
  11. // 覆盖面:
  12. // 1. child 无 record + 持久 parentID 指向 live 父 record → 播种前缀与 live 增量同时在投影里
  13. // 2. child 既无 record 又无法经 parentID 落到任何 record → 维持修复前行为(空、非合成)
  14. // 3. 自身有 record 的会话仍走直取 record,不被 parentID 回退改写
  15. import { mkdtemp, rm } from "node:fs/promises";
  16. import { tmpdir } from "node:os";
  17. import { join } from "node:path";
  18. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  19. import { createInMemorySessionEventStore, createSqliteSessionStore } from "@zcode/adapters/storage";
  20. import { conversationTopic } from "@zcode/shared/zcode-protocol-v4";
  21. import type {
  22. EventId,
  23. MessageId,
  24. MessagePart,
  25. ModelId,
  26. ModelProviderId,
  27. ProjectId,
  28. SessionEvent,
  29. SessionEventType as SessionEventTypeUnion,
  30. SessionEventStorePort,
  31. SessionId,
  32. TraceId,
  33. TurnId,
  34. } from "@zcode/contracts";
  35. import { SessionEventType } from "@zcode/contracts";
  36. import { createConversationV4Gateway } from "../src/zcode-protocol/v4-bridge.js";
  37. import type {
  38. ZCodeProtocolAgentServerContext,
  39. ZCodeProtocolSessionRecord,
  40. } from "../src/zcode-protocol/server-types.js";
  41. type TestSessionStore = ReturnType<typeof createSqliteSessionStore>;
  42. const WORKSPACE_PATH = "/tmp/zcode-detached-child";
  43. const PARENT_SESSION_ID = "sess_parent_chat" as SessionId;
  44. const CHILD_SESSION_ID = "sess_actor_child" as SessionId;
  45. class EventLog {
  46. private seq = 0;
  47. constructor(private readonly sessionId: string) {}
  48. push(type: SessionEventTypeUnion, payload: unknown, opts: { turnId?: string } = {}): SessionEvent {
  49. this.seq += 1;
  50. return {
  51. id: `${this.sessionId}-event-${this.seq}` as EventId,
  52. sessionId: this.sessionId as SessionId,
  53. turnId: opts.turnId as TurnId | undefined,
  54. type,
  55. timestamp: new Date(1_700_000_000_000 + this.seq * 1000),
  56. traceId: "trace-detached" as TraceId,
  57. sequenceNumber: this.seq,
  58. payload,
  59. } as SessionEvent;
  60. }
  61. }
  62. async function saveUserTextMessage(
  63. store: TestSessionStore,
  64. sessionId: SessionId,
  65. messageId: MessageId,
  66. text: string,
  67. created: number,
  68. ): Promise<void> {
  69. await store.saveMessage({
  70. id: messageId,
  71. sessionID: sessionId,
  72. role: "user",
  73. time: { created },
  74. agent: "zcode-agent",
  75. model: { providerID: "glm" as ModelProviderId, modelID: "glm-4-air" as ModelId },
  76. tools: {},
  77. });
  78. await store.savePart({
  79. id: `${messageId}_text` as MessagePart["id"],
  80. sessionID: sessionId,
  81. messageID: messageId,
  82. type: "text",
  83. text,
  84. time: { start: created, end: created },
  85. });
  86. }
  87. async function saveAssistantTextMessage(
  88. store: TestSessionStore,
  89. sessionId: SessionId,
  90. messageId: MessageId,
  91. parentMessageId: MessageId,
  92. text: string,
  93. created: number,
  94. ): Promise<void> {
  95. await store.saveMessage({
  96. id: messageId,
  97. sessionID: sessionId,
  98. role: "assistant",
  99. time: { created, completed: created },
  100. parentID: parentMessageId,
  101. providerID: "glm" as ModelProviderId,
  102. modelID: "glm-4-air" as ModelId,
  103. mode: "build",
  104. agent: "zcode-agent",
  105. path: { cwd: WORKSPACE_PATH, root: WORKSPACE_PATH },
  106. cost: 0,
  107. tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
  108. });
  109. await store.savePart({
  110. id: `${messageId}_text` as MessagePart["id"],
  111. sessionID: sessionId,
  112. messageID: messageId,
  113. type: "text",
  114. text,
  115. time: { start: created, end: created },
  116. });
  117. }
  118. /** amend-resume 的播种形态:前驱 transcript 前缀被直接复制进新 actor 会话的 store。 */
  119. async function seedActorTranscriptPrefix(
  120. store: TestSessionStore,
  121. sessionId: SessionId,
  122. label: string,
  123. ): Promise<void> {
  124. await saveUserTextMessage(
  125. store,
  126. sessionId,
  127. `${sessionId}-seed-0` as MessageId,
  128. `${label} 播种提问`,
  129. 1,
  130. );
  131. await saveAssistantTextMessage(
  132. store,
  133. sessionId,
  134. `${sessionId}-seed-1` as MessageId,
  135. `${sessionId}-seed-0` as MessageId,
  136. `${label} 播种回答`,
  137. 2,
  138. );
  139. }
  140. /**
  141. * 只包含 loadPersistedEvents 真正触碰到的字段:共享 event store、artifact reader、
  142. * contextWindow 解析用的 runtime 模型选择(getSessionModelSelection) 与 workspace。其余能力留空即可,
  143. * 缺失时 gateway 的 seed 钩子对 child 一律返回 null(child 本就没有 record)。
  144. */
  145. function makeBackingRecord(eventStore: SessionEventStorePort): ZCodeProtocolSessionRecord {
  146. return {
  147. app: {
  148. readToolResultArtifact: async () => ({ content: "" }),
  149. runtime: {
  150. getSessionModelSelection: () => ({ providerId: "glm", modelId: "glm-4-air" }),
  151. // listSessionSubagents 只在会话**自身**有 record 时读它(subagent 投影的 live 补充);
  152. // 这里没有 subagent,返回空投影即可。
  153. // readSessionContextUsage(staging 6d4c3cc571 起在 loadPersistedEvents 里同步读容量种子)要读
  154. // projection.contextWindow / contextUsed;给一份最小投影即可,子代理投影本就为空。
  155. getProjection: async () => ({ contextUsed: 0, contextWindow: 200_000 }) as never,
  156. },
  157. sessionId: PARENT_SESSION_ID,
  158. },
  159. createdAt: 0,
  160. eventStore,
  161. persistence: "immediate",
  162. stateRevision: 1,
  163. updatedAt: 0,
  164. workspace: {
  165. workspaceKey: `local:${WORKSPACE_PATH}`,
  166. workspacePath: WORKSPACE_PATH,
  167. },
  168. } as unknown as ZCodeProtocolSessionRecord;
  169. }
  170. function makeContext(input: {
  171. sessions: Map<string, ZCodeProtocolSessionRecord>;
  172. store: TestSessionStore;
  173. }): ZCodeProtocolAgentServerContext {
  174. const context = {
  175. appRuntimePreferences: {
  176. askUserQuestionAutoResolutionEnabled: false,
  177. modelIoFullRetentionEnabled: false,
  178. },
  179. deps: { sessionStore: input.store },
  180. notify: () => {},
  181. requestClient: async () => {
  182. throw new Error("detached-child hydration test does not issue reverse requests");
  183. },
  184. sessions: input.sessions,
  185. v4Interactions: { resolve: () => false },
  186. workspaceModelCatalogs: new Map(),
  187. } as unknown as ZCodeProtocolAgentServerContext;
  188. return context;
  189. }
  190. /** child 的 live in-flight turn:TurnStarted 无终结事件 → cold merge 认定为内存权威轮次。 */
  191. async function ingestLiveTurn(
  192. gateway: ReturnType<typeof createConversationV4Gateway>,
  193. eventStore: SessionEventStorePort,
  194. sessionId: string,
  195. liveText: string,
  196. ): Promise<void> {
  197. const log = new EventLog(sessionId);
  198. const events = [
  199. log.push(SessionEventType.SessionCreated, { mode: "build", contextWindow: 200_000 }),
  200. log.push(
  201. SessionEventType.TurnStarted,
  202. { turnNumber: 1, input: `${liveText} 提问` },
  203. { turnId: `${sessionId}-turn-live` },
  204. ),
  205. log.push(
  206. SessionEventType.ModelStreaming,
  207. { kind: "text_delta", delta: `${liveText} 增量`, done: false },
  208. { turnId: `${sessionId}-turn-live` },
  209. ),
  210. ];
  211. for (const event of events) {
  212. // 生产形态:子 runtime 与父 runtime 共享 event store(按子 sessionId 归档),
  213. // 同一条事件另经父 record 的外部 sink 路由到 gateway 的 detached live 通道。
  214. await eventStore.append(event);
  215. gateway.ingestDetachedLiveSession(sessionId, event);
  216. }
  217. }
  218. async function snapshotRowTexts(
  219. gateway: ReturnType<typeof createConversationV4Gateway>,
  220. sessionId: string,
  221. ): Promise<string[]> {
  222. const result = await gateway.subscribe({
  223. topic: conversationTopic(sessionId),
  224. connectionId: `conn-${sessionId}`,
  225. clientMode: "desktop-continuous",
  226. });
  227. const payload = result.initialFrame?.payload;
  228. if (payload?.kind !== "snapshot") throw new Error("Expected snapshot initial frame");
  229. return payload.snapshot.rows.window.flatMap((row) =>
  230. "text" in row && typeof row.text === "string" && row.text.length > 0 ? [row.text] : [],
  231. );
  232. }
  233. describe("v4 detached live child 的首次订阅 hydration", () => {
  234. let tempRoot: string;
  235. let store: TestSessionStore;
  236. beforeEach(async () => {
  237. tempRoot = await mkdtemp(join(tmpdir(), "zcode-detached-child-"));
  238. store = createSqliteSessionStore({ dbPath: join(tempRoot, "sessions.db") });
  239. });
  240. afterEach(async () => {
  241. store.close();
  242. await rm(tempRoot, { force: true, recursive: true });
  243. });
  244. async function createSessionRow(sessionId: SessionId, parentId?: SessionId): Promise<void> {
  245. await store.createSession({
  246. id: sessionId,
  247. ...(parentId ? { parentID: parentId } : {}),
  248. projectID: "project_detached_child" as ProjectId,
  249. slug: `slug-${sessionId}`,
  250. directory: WORKSPACE_PATH,
  251. path: WORKSPACE_PATH,
  252. title: `session ${sessionId}`,
  253. version: "test-version",
  254. time: { created: 1, updated: 4 },
  255. });
  256. }
  257. it("child 无 record:经持久 parentID 落到父 record,播种前缀与 live 增量同时可见", async () => {
  258. await createSessionRow(PARENT_SESSION_ID);
  259. await createSessionRow(CHILD_SESSION_ID, PARENT_SESSION_ID);
  260. await seedActorTranscriptPrefix(store, CHILD_SESSION_ID, "actor");
  261. const eventStore = createInMemorySessionEventStore();
  262. const sessions = new Map<string, ZCodeProtocolSessionRecord>([
  263. [PARENT_SESSION_ID, makeBackingRecord(eventStore)],
  264. ]);
  265. const context = makeContext({ sessions, store });
  266. const gateway = createConversationV4Gateway(context);
  267. context.v4Gateway = gateway;
  268. await ingestLiveTurn(gateway, eventStore, CHILD_SESSION_ID, "live");
  269. const texts = await snapshotRowTexts(gateway, CHILD_SESSION_ID);
  270. // 修复前这里只有 live 两行:播种前缀从不进入投影。
  271. expect(texts).toContain("actor 播种提问");
  272. expect(texts).toContain("actor 播种回答");
  273. expect(texts).toContain("live 提问");
  274. expect(texts).toContain("live 增量");
  275. // 顺序也必须是"播种前缀在前、live 轮次在后"。
  276. expect(texts.indexOf("actor 播种回答")).toBeLessThan(texts.indexOf("live 增量"));
  277. });
  278. it("child 既无 record、parentID 也落不到任何 record:维持修复前的空非合成 hydration", async () => {
  279. const orphanParentId = "sess_parent_not_resident" as SessionId;
  280. await createSessionRow(orphanParentId);
  281. await createSessionRow(CHILD_SESSION_ID, orphanParentId);
  282. await seedActorTranscriptPrefix(store, CHILD_SESSION_ID, "orphan");
  283. const eventStore = createInMemorySessionEventStore();
  284. // 注册表里只有一个与本 child 无关的会话:parentID 查不到常驻 record。
  285. const sessions = new Map<string, ZCodeProtocolSessionRecord>([
  286. [PARENT_SESSION_ID, makeBackingRecord(eventStore)],
  287. ]);
  288. const context = makeContext({ sessions, store });
  289. const gateway = createConversationV4Gateway(context);
  290. context.v4Gateway = gateway;
  291. await ingestLiveTurn(gateway, eventStore, CHILD_SESSION_ID, "live");
  292. const texts = await snapshotRowTexts(gateway, CHILD_SESSION_ID);
  293. expect(texts).toEqual(["live 提问", "live 增量"]);
  294. });
  295. it("自身有 record 的会话仍直取自己的 record,不被 parentID 回退改写", async () => {
  296. await createSessionRow(PARENT_SESSION_ID);
  297. // 该会话既有自己的 record,持久层又记着 parentID;直取必须优先。
  298. await createSessionRow(CHILD_SESSION_ID, PARENT_SESSION_ID);
  299. await seedActorTranscriptPrefix(store, CHILD_SESSION_ID, "self");
  300. const ownEventStore = createInMemorySessionEventStore();
  301. const parentEventStore = createInMemorySessionEventStore();
  302. const sessions = new Map<string, ZCodeProtocolSessionRecord>([
  303. [PARENT_SESSION_ID, makeBackingRecord(parentEventStore)],
  304. [CHILD_SESSION_ID, makeBackingRecord(ownEventStore)],
  305. ]);
  306. const context = makeContext({ sessions, store });
  307. const gateway = createConversationV4Gateway(context);
  308. context.v4Gateway = gateway;
  309. // 判别器:父 record 的 store 里放一条**只有走 parentID 回退才读得到**的伪造事件。
  310. // 直取生效时它不该出现在投影里。
  311. await ingestLiveTurn(gateway, ownEventStore, CHILD_SESSION_ID, "live");
  312. const decoy = new EventLog(`${CHILD_SESSION_ID}-decoy`);
  313. await parentEventStore.append({
  314. ...decoy.push(
  315. SessionEventType.ModelStreaming,
  316. { kind: "text_delta", delta: "父 record 污染", done: false },
  317. { turnId: `${CHILD_SESSION_ID}-turn-live` },
  318. ),
  319. sessionId: CHILD_SESSION_ID,
  320. });
  321. const texts = await snapshotRowTexts(gateway, CHILD_SESSION_ID);
  322. expect(texts).toContain("self 播种提问");
  323. expect(texts).toContain("live 增量");
  324. expect(texts.join("")).not.toContain("父 record 污染");
  325. });
  326. });