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

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