dynamic-workflow-run-workspace.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. // 工作区 transcript 的读面(docs/dynamic-workflow/transcript-and-notifications.md):
  2. // 授权链(run 属于本会话)、清单的行映射、正文的保形有界化。
  3. //
  4. // 与 run service 的产物读面测试同一取向:负例逐条断言「什么都没放行」,而不是只看正例。
  5. // 存储层用一个带 `listWorldNodes` 的内存 journal 替身——它的形状就是 adapters 的
  6. // `DwfRunIntrospectionQueries.listWorldNodes`(那边的 SQL 在 adapters 的测试里钉)。
  7. import { describe, expect, it } from "vitest";
  8. import type { DwfWorldNodeRow } from "@zcode/adapters/storage";
  9. import { InMemoryJournalStore } from "@zcode/dynamic-workflow";
  10. import type { NodeRecord, RunRecord } from "@zcode/dynamic-workflow";
  11. import {
  12. boundWorkspaceResult,
  13. listWorkspaceNodesFrom,
  14. readWorkspaceNodeResultFrom,
  15. supportsWorkspaceReads,
  16. } from "../src/app/dynamic-workflow-run-workspace.js";
  17. const PARENT = "ses_parent";
  18. const RUN = "dwfrun-1";
  19. /** 内存 journal + 一条 `listWorldNodes`:按 kind 过滤、按落库先后、不带正文、带库内摘要。 */
  20. class WorkspaceJournal extends InMemoryJournalStore {
  21. private order = 0;
  22. private readonly seen = new Map<string, number>();
  23. override putNode(record: NodeRecord): void {
  24. const key = `${record.runId}/${record.siteId}@${record.ordinal}`;
  25. if (!this.seen.has(key)) this.seen.set(key, ++this.order);
  26. super.putNode(record);
  27. }
  28. listWorldNodes(runId: string): DwfWorldNodeRow[] {
  29. return this.listNodes(runId, { kinds: "all", withResult: true })
  30. .filter((node) => node.kind === "world-read" || node.kind === "world-run")
  31. .sort(
  32. (a, b) =>
  33. this.seen.get(`${a.runId}/${a.siteId}@${a.ordinal}`)! -
  34. this.seen.get(`${b.runId}/${b.siteId}@${b.ordinal}`)!,
  35. )
  36. .map((node) => {
  37. const { result, ...rest } = node;
  38. const serialized = result === undefined ? undefined : JSON.stringify(result);
  39. const summary =
  40. serialized === undefined
  41. ? {}
  42. : {
  43. resultBytes: Buffer.byteLength(serialized, "utf8"),
  44. ...(Array.isArray(result) ? { resultCount: result.length } : {}),
  45. ...(typeof result === "object" && result !== null && !Array.isArray(result)
  46. ? {
  47. exitCode: (result as { exitCode: number }).exitCode,
  48. stdoutBytes: Buffer.byteLength((result as { stdout: string }).stdout),
  49. stderrBytes: Buffer.byteLength((result as { stderr: string }).stderr),
  50. }
  51. : {}),
  52. };
  53. return { ...rest, timeCreated: 1_000, timeUpdated: 2_300, ...summary };
  54. });
  55. }
  56. }
  57. function run(overrides: Partial<RunRecord> = {}): RunRecord {
  58. return {
  59. runId: RUN,
  60. parentSessionId: PARENT,
  61. caps: { maxConcurrency: 4 },
  62. spentTokens: 0,
  63. status: "running",
  64. ...overrides,
  65. };
  66. }
  67. function seed(journal: WorkspaceJournal, runOverrides: Partial<RunRecord> = {}) {
  68. journal.createRun(run(runOverrides));
  69. journal.putNode({
  70. runId: RUN,
  71. siteId: "world-read#1",
  72. ordinal: 1,
  73. kind: "world-read",
  74. inputHash: "g",
  75. input: { op: "glob", args: ["src/**/*.ts"] },
  76. status: "completed",
  77. result: ["src/a.ts", "src/b.ts"],
  78. });
  79. journal.putNode({
  80. runId: RUN,
  81. siteId: "ask#1",
  82. ordinal: 1,
  83. kind: "ask",
  84. inputHash: "a",
  85. status: "completed",
  86. result: { text: "done" },
  87. });
  88. journal.putNode({
  89. runId: RUN,
  90. siteId: "world-read#2",
  91. ordinal: 1,
  92. kind: "world-run",
  93. inputHash: "r",
  94. input: { op: "run", args: ["pnpm", ["test"]] },
  95. status: "completed",
  96. result: { exitCode: 1, stdout: "1 failed\n", stderr: "boom" },
  97. });
  98. journal.putNode({
  99. runId: RUN,
  100. siteId: "world-read#2",
  101. ordinal: 2,
  102. kind: "world-run",
  103. inputHash: "r2",
  104. input: { op: "run", args: ["pnpm", ["test"]] },
  105. status: "failed",
  106. error: { code: "DriverError", message: "x".repeat(3_000) },
  107. });
  108. journal.putNode({
  109. runId: RUN,
  110. siteId: "world-read#3",
  111. ordinal: 1,
  112. kind: "world-read",
  113. inputHash: "old",
  114. status: "running",
  115. });
  116. }
  117. describe("dynamic workflow run workspace — 能力探测", () => {
  118. it("只认带 listWorldNodes 的 journal;纯引擎 journal 整个读面缺席", () => {
  119. expect(supportsWorkspaceReads(new InMemoryJournalStore())).toBe(false);
  120. expect(supportsWorkspaceReads(new WorkspaceJournal())).toBe(true);
  121. });
  122. it("不带读面的 journal:清单回 undefined(网关归一成空清单),正文也不放行", async () => {
  123. const journal = new InMemoryJournalStore();
  124. journal.createRun(run());
  125. expect(await listWorkspaceNodesFrom({ journal, parentSessionId: PARENT }, RUN)).toBeUndefined();
  126. });
  127. });
  128. describe("dynamic workflow run workspace — 清单", () => {
  129. it("只回 world 行、按落库先后、不带正文;op / args 来自 input,摘要来自库内计算", async () => {
  130. const journal = new WorkspaceJournal();
  131. seed(journal);
  132. const nodes = await listWorkspaceNodesFrom({ journal, parentSessionId: PARENT }, RUN);
  133. expect(nodes?.map((node) => `${node.siteId}@${node.ordinal}`)).toEqual([
  134. "world-read#1@1",
  135. "world-read#2@1",
  136. "world-read#2@2",
  137. "world-read#3@1",
  138. ]);
  139. expect(nodes?.[0]).toEqual({
  140. siteId: "world-read#1",
  141. ordinal: 1,
  142. kind: "world-read",
  143. op: "glob",
  144. args: ["src/**/*.ts"],
  145. status: "completed",
  146. summary: { resultBytes: JSON.stringify(["src/a.ts", "src/b.ts"]).length, resultCount: 2 },
  147. createdAt: 1_000,
  148. updatedAt: 2_300,
  149. });
  150. expect(nodes?.[1]).toMatchObject({
  151. kind: "world-run",
  152. op: "run",
  153. summary: { exitCode: 1, stdoutBytes: 9, stderrBytes: 4 },
  154. });
  155. for (const node of nodes ?? []) expect("result" in node).toBe(false);
  156. });
  157. it("失败行带切尾的 error、没有摘要;running 行两者都没有;历史行没有 op / args", async () => {
  158. const journal = new WorkspaceJournal();
  159. seed(journal);
  160. const nodes = (await listWorkspaceNodesFrom({ journal, parentSessionId: PARENT }, RUN))!;
  161. const failed = nodes[2]!;
  162. expect(failed.status).toBe("failed");
  163. expect(failed.error?.code).toBe("DriverError");
  164. expect(failed.error?.message.length).toBe(2_000);
  165. expect(failed.error?.message.endsWith("…")).toBe(true);
  166. expect("summary" in failed).toBe(false);
  167. const running = nodes[3]!;
  168. expect(running.status).toBe("running");
  169. expect("op" in running).toBe(false);
  170. expect("args" in running).toBe(false);
  171. expect("summary" in running).toBe(false);
  172. });
  173. it("截断过的 input 把 inputTruncated 透出", async () => {
  174. const journal = new WorkspaceJournal();
  175. journal.createRun(run());
  176. journal.putNode({
  177. runId: RUN,
  178. siteId: "world-read#1",
  179. ordinal: 1,
  180. kind: "world-run",
  181. inputHash: "t",
  182. input: { op: "run", args: ["node", '["-e","…'], truncated: true },
  183. status: "running",
  184. });
  185. const nodes = await listWorkspaceNodesFrom({ journal, parentSessionId: PARENT }, RUN);
  186. expect(nodes?.[0]).toMatchObject({ op: "run", inputTruncated: true });
  187. });
  188. it("授权负例:不是本会话的 run、parentSessionId 为 NULL 的老行、未知 run 都回 undefined,三者不可区分", async () => {
  189. const other = new WorkspaceJournal();
  190. seed(other, { parentSessionId: "ses_other" });
  191. expect(
  192. await listWorkspaceNodesFrom({ journal: other, parentSessionId: PARENT }, RUN),
  193. ).toBeUndefined();
  194. const legacy = new WorkspaceJournal();
  195. seed(legacy, { parentSessionId: undefined });
  196. expect(
  197. await listWorkspaceNodesFrom({ journal: legacy, parentSessionId: PARENT }, RUN),
  198. ).toBeUndefined();
  199. const mine = new WorkspaceJournal();
  200. seed(mine);
  201. expect(
  202. await listWorkspaceNodesFrom({ journal: mine, parentSessionId: PARENT }, "dwfrun-nope"),
  203. ).toBeUndefined();
  204. });
  205. });
  206. describe("dynamic workflow run workspace — 正文", () => {
  207. const deps = () => {
  208. const journal = new WorkspaceJournal();
  209. seed(journal);
  210. return { journal, parentSessionId: PARENT };
  211. };
  212. it("completed 行回正文;failed 行只有 error;running 行两者都没有", async () => {
  213. const d = deps();
  214. expect(
  215. await readWorkspaceNodeResultFrom(d, RUN, "world-read#2", 1, { maxBytes: 32_768 }),
  216. ).toEqual({
  217. status: "completed",
  218. result: { exitCode: 1, stdout: "1 failed\n", stderr: "boom" },
  219. truncated: false,
  220. totalBytes: JSON.stringify({ exitCode: 1, stdout: "1 failed\n", stderr: "boom" }).length,
  221. });
  222. const failed = await readWorkspaceNodeResultFrom(d, RUN, "world-read#2", 2, {
  223. maxBytes: 32_768,
  224. });
  225. expect(failed).toMatchObject({ status: "failed", truncated: false, totalBytes: 0 });
  226. expect(failed?.error?.code).toBe("DriverError");
  227. expect("result" in failed!).toBe(false);
  228. expect(
  229. await readWorkspaceNodeResultFrom(d, RUN, "world-read#3", 1, { maxBytes: 32_768 }),
  230. ).toEqual({
  231. status: "running",
  232. truncated: false,
  233. totalBytes: 0,
  234. });
  235. });
  236. it("授权负例:ask 行、未知节点、不是本会话的 run 都回 undefined", async () => {
  237. const d = deps();
  238. expect(
  239. await readWorkspaceNodeResultFrom(d, RUN, "ask#1", 1, { maxBytes: 32_768 }),
  240. ).toBeUndefined();
  241. expect(
  242. await readWorkspaceNodeResultFrom(d, RUN, "world-read#9", 1, { maxBytes: 32_768 }),
  243. ).toBeUndefined();
  244. expect(
  245. await readWorkspaceNodeResultFrom(
  246. { ...d, parentSessionId: "ses_other" },
  247. RUN,
  248. "world-read#2",
  249. 1,
  250. {
  251. maxBytes: 32_768,
  252. },
  253. ),
  254. ).toBeUndefined();
  255. });
  256. });
  257. describe("boundWorkspaceResult — 保形有界化", () => {
  258. it("不超限原样回,truncated=false", () => {
  259. expect(boundWorkspaceResult(["a", "b"], 1024)).toEqual({
  260. result: ["a", "b"],
  261. truncated: false,
  262. totalBytes: 9,
  263. });
  264. });
  265. it("字符串切尾到 ≤ maxBytes 个 UTF-8 字节,不切在多字节字符中间", () => {
  266. const text = "é".repeat(100); // 每个 2 字节
  267. const bounded = boundWorkspaceResult(text, 51);
  268. expect(bounded.truncated).toBe(true);
  269. expect(bounded.totalBytes).toBe(202);
  270. expect(typeof bounded.result).toBe("string");
  271. expect(Buffer.byteLength(bounded.result as string, "utf8")).toBeLessThanOrEqual(51);
  272. expect(bounded.result).toBe("é".repeat(25));
  273. });
  274. it("数组逐项累加、放不下的去尾", () => {
  275. const items = Array.from({ length: 50 }, (_, i) => `src/file-${i}.ts`);
  276. const bounded = boundWorkspaceResult(items, 200);
  277. expect(bounded.truncated).toBe(true);
  278. expect(Array.isArray(bounded.result)).toBe(true);
  279. const kept = bounded.result as string[];
  280. expect(kept.length).toBeGreaterThan(0);
  281. expect(kept.length).toBeLessThan(50);
  282. expect(kept).toEqual(items.slice(0, kept.length));
  283. expect(Buffer.byteLength(JSON.stringify(kept), "utf8")).toBeLessThanOrEqual(200);
  284. });
  285. it("world.run 的正文:exitCode 恒保留,stdout / stderr 各分预算,一路用不完的让给另一路", () => {
  286. const result = { exitCode: 2, stdout: "o".repeat(10_000), stderr: "e".repeat(10) };
  287. const bounded = boundWorkspaceResult(result, 1_024);
  288. expect(bounded.truncated).toBe(true);
  289. const value = bounded.result as { exitCode: number; stdout: string; stderr: string };
  290. expect(value.exitCode).toBe(2);
  291. expect(value.stderr).toBe("e".repeat(10));
  292. expect(value.stdout.length).toBeGreaterThan(900);
  293. expect(Buffer.byteLength(JSON.stringify(value), "utf8")).toBeLessThanOrEqual(1_024);
  294. });
  295. it("其它形状超限时退化成切尾的 JSON 文本", () => {
  296. const bounded = boundWorkspaceResult({ big: "x".repeat(5_000) }, 100);
  297. expect(bounded.truncated).toBe(true);
  298. expect(typeof bounded.result).toBe("string");
  299. expect((bounded.result as string).startsWith('{"big":"xxx')).toBe(true);
  300. });
  301. });