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

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