dynamic-workflow-run-settings.test.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. // GUI「配置」的 runtime 方法(docs/dynamic-workflow/launch.md「Changing a run's settings from the
  2. // GUI」)。它是 `port.amend` 的第二个调用方,与 AmendWorkflow 工具共用三态归一,但不经模型轮、
  3. // 不开确认窗,并用一条排队的 controlOnly「设置轮」记下这件事。
  4. //
  5. // 钉住的不变式:
  6. // 1. 每一种拒绝都发生在 `port.amend` 之前——零 amend、零消息、零事件。
  7. // 2. 成功路径:amend 入参(沿用脚本、inheritArgs、新设置、settings- 前缀)+ 合成 AmendWorkflow
  8. // 追踪 + 设置轮(元数据带 amend 块、无 scope/path/script)。
  9. // 2b. 新 run 记下脚本文件:前驱的文件仍是这份字节就继续记它,否则写一份新草稿(与工具沿用脚本
  10. // 同一条规则,docs/dynamic-workflow/launch.md「Provenance」)。
  11. // 3. 主代理在一轮里时,设置轮等这一轮结束;活动 turn 的吸收在它这里停下,后到的通知排在它后面。
  12. import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
  13. import { tmpdir } from "node:os";
  14. import { join } from "node:path";
  15. import { afterAll, describe, expect, it } from "vitest";
  16. import {
  17. SessionEventType,
  18. WORKFLOW_DRAFTS_DIR,
  19. createSessionId,
  20. type CreateSessionInput,
  21. type DynamicWorkflowRunAmendRequest,
  22. type DynamicWorkflowRunRetuneRequest,
  23. type DynamicWorkflowRunRetuneResult,
  24. type DynamicWorkflowRunSnapshot,
  25. type MessageInfo,
  26. type MessagePart,
  27. type MessageWithParts,
  28. type ModelCatalogPort,
  29. type SessionEvent,
  30. type SessionInfo,
  31. } from "@zcode/contracts";
  32. import { AgentRuntime } from "../src/index.js";
  33. import { createRuntimeCommandId } from "../src/runtime/command-queue.js";
  34. import { drainPendingRuntimeCommandsForActiveLoop } from "../src/runtime/methods/runtime-command-active-loop.js";
  35. import { buildSettingsMessageText } from "../src/runtime/methods/dynamic-workflow-run-settings.js";
  36. import { createTestSessionEventStore } from "./test-event-store.js";
  37. const STORED_SCRIPT = [
  38. 'phase("plan");',
  39. 'const plan = await agent("planner").ask<string>("plan it");',
  40. "return plan;",
  41. ].join("\n");
  42. const BROKEN_SCRIPT = 'const x: number = "nope";\nreturn x;';
  43. const PREVIOUS = "dwfrun-prev";
  44. interface RecordingStore {
  45. createdSessions: CreateSessionInput[];
  46. savedMessages: MessageInfo[];
  47. savedParts: MessagePart[];
  48. }
  49. function createRecordingStore(): RecordingStore & Record<string, unknown> {
  50. const createdSessions: CreateSessionInput[] = [];
  51. const savedMessages: MessageInfo[] = [];
  52. const savedParts: MessagePart[] = [];
  53. const sessions = new Map<string, SessionInfo>();
  54. return {
  55. createdSessions,
  56. savedMessages,
  57. savedParts,
  58. async createSession(input: CreateSessionInput) {
  59. createdSessions.push(input);
  60. const now = Date.now();
  61. const session = {
  62. ...input,
  63. taskType: input.taskType ?? "interactive",
  64. time: { created: now, updated: now },
  65. } as SessionInfo;
  66. sessions.set(input.id, session);
  67. return session;
  68. },
  69. async getSession(id: string) {
  70. return sessions.get(id) ?? null;
  71. },
  72. async listSessions() {
  73. return Array.from(sessions.values());
  74. },
  75. async updateSession(input: { id: string }) {
  76. return sessions.get(input.id) ?? null;
  77. },
  78. async saveMessage(input: MessageInfo) {
  79. savedMessages.push(input);
  80. },
  81. async savePart(input: MessagePart) {
  82. savedParts.push(input);
  83. },
  84. async messages(input: { sessionID: string }): Promise<MessageWithParts[]> {
  85. return savedMessages
  86. .filter((message) => message.sessionID === input.sessionID)
  87. .map((info) => ({
  88. info,
  89. parts: savedParts.filter((part) => part.messageID === info.id),
  90. }));
  91. },
  92. };
  93. }
  94. const CATALOG: ModelCatalogPort = {
  95. listModels: () => [
  96. { providerId: "bigmodel", modelId: "GLM-5.3", reasoningLevels: [], current: true },
  97. { providerId: "bigmodel", modelId: "GLM-5.3-Flash", reasoningLevels: [] },
  98. ],
  99. };
  100. // 成功路径会在工作目录下写草稿,所以工作目录必须是用完即删的临时目录,而不是一个共享的 /tmp 路径。
  101. const SETTINGS_CWD = mkdtempSync(join(tmpdir(), "dwf-settings-"));
  102. afterAll(() => rmSync(SETTINGS_CWD, { recursive: true, force: true }));
  103. function makeRuntime(options: {
  104. name: string;
  105. snapshot?: Partial<DynamicWorkflowRunSnapshot> | null;
  106. script?: string | null;
  107. defaultConcurrency?: number;
  108. catalog?: ModelCatalogPort | null;
  109. amend?: (
  110. request: DynamicWorkflowRunAmendRequest,
  111. ) =>
  112. | { ok: true; runId: string; supersededRunId?: string }
  113. | { ok: false; reason: "run_not_found" | "missing_boundaries" };
  114. /**
  115. * `retuneConcurrency` 的答复(docs/dynamic-workflow/launch.md「The fork」)。缺席即端口没有这个
  116. * 方法(老宿主的形状)——那时只改并发的「配置」照旧落成一次修订。
  117. */
  118. retune?: DynamicWorkflowRunRetuneResult;
  119. }): {
  120. runtime: AgentRuntime;
  121. events: SessionEvent[];
  122. store: RecordingStore;
  123. amends: DynamicWorkflowRunAmendRequest[];
  124. retunes: DynamicWorkflowRunRetuneRequest[];
  125. getScriptCalls: string[];
  126. sessionId: string;
  127. } {
  128. const sessionId = createSessionId(options.name);
  129. const amends: DynamicWorkflowRunAmendRequest[] = [];
  130. const retunes: DynamicWorkflowRunRetuneRequest[] = [];
  131. const getScriptCalls: string[] = [];
  132. const store = createRecordingStore();
  133. const snapshot: DynamicWorkflowRunSnapshot | undefined =
  134. options.snapshot === null
  135. ? undefined
  136. : ({
  137. runId: PREVIOUS,
  138. taskId: PREVIOUS,
  139. startedAt: new Date(),
  140. status: "running",
  141. name: "triage",
  142. parentSessionId: sessionId,
  143. ...options.snapshot,
  144. } as DynamicWorkflowRunSnapshot);
  145. const runtime = new AgentRuntime(
  146. sessionId,
  147. { agentName: "dwf-settings-test", workingDirectory: SETTINGS_CWD },
  148. {
  149. eventStore: createTestSessionEventStore(),
  150. sessionStore: store as never,
  151. modelAdapter: {} as never,
  152. ...(options.catalog === null ? {} : { modelCatalogPort: options.catalog ?? CATALOG }),
  153. dynamicWorkflowRunPort: {
  154. async submit() {
  155. throw new Error("settings never submit");
  156. },
  157. async amend(request: DynamicWorkflowRunAmendRequest) {
  158. amends.push(request);
  159. return options.amend
  160. ? options.amend(request)
  161. : { ok: true, runId: "dwfrun-next", supersededRunId: PREVIOUS };
  162. },
  163. async getTask(runId: string) {
  164. if (runId === PREVIOUS) return snapshot;
  165. // 新 run 在追踪器眼里一直在跑(waiter 永不 settle),不产生任何通知。
  166. return {
  167. runId,
  168. taskId: runId,
  169. startedAt: new Date(),
  170. status: "running",
  171. parentSessionId: sessionId,
  172. } as DynamicWorkflowRunSnapshot;
  173. },
  174. async getScript(runId: string) {
  175. getScriptCalls.push(runId);
  176. if (runId !== PREVIOUS || options.script === null) return undefined;
  177. return options.script ?? STORED_SCRIPT;
  178. },
  179. ...(options.retune === undefined
  180. ? {}
  181. : {
  182. async retuneConcurrency(request: DynamicWorkflowRunRetuneRequest) {
  183. retunes.push(request);
  184. return options.retune as DynamicWorkflowRunRetuneResult;
  185. },
  186. }),
  187. defaultConcurrency: () => options.defaultConcurrency ?? 13,
  188. waitForTask: () => new Promise(() => {}),
  189. async cancel() {
  190. return true;
  191. },
  192. async listEvents() {
  193. return [];
  194. },
  195. } as never,
  196. },
  197. );
  198. const events: SessionEvent[] = [];
  199. runtime.subscribeEvents({ onSessionEvent: (event) => events.push(event) });
  200. return { runtime, events, store, amends, retunes, getScriptCalls, sessionId };
  201. }
  202. /** 设置轮经运行时队列落下;空闲会话里入队即跑,等到它的 TurnComplete。 */
  203. async function settleQueue(events: SessionEvent[]): Promise<void> {
  204. for (let attempt = 0; attempt < 50; attempt += 1) {
  205. if (events.some((event) => event.type === SessionEventType.TurnComplete)) return;
  206. await new Promise((resolve) => setTimeout(resolve, 0));
  207. }
  208. }
  209. describe("amendWorkflowRunSettings — 拒绝在 port.amend 之前", () => {
  210. it.each([
  211. ["not_found:没有这个 run", { snapshot: null }, { maxConcurrency: 4 }, "not_found"],
  212. [
  213. "not_found:run 属于别的会话",
  214. { snapshot: { parentSessionId: "sess_other" } },
  215. { maxConcurrency: 4 },
  216. "not_found",
  217. ],
  218. [
  219. "not_configurable:已完成",
  220. { snapshot: { runStatus: "completed", status: "completed" } },
  221. { maxConcurrency: 4 },
  222. "not_configurable",
  223. ],
  224. [
  225. "not_configurable:已被替代",
  226. { snapshot: { runStatus: "stopped", supersededBy: "dwfrun-x" } },
  227. { maxConcurrency: 4 },
  228. "not_configurable",
  229. ],
  230. ["script_missing:没有存下的脚本", { script: null }, { maxConcurrency: 4 }, "script_missing"],
  231. [
  232. "model_unavailable:目录里没有这个模型",
  233. {},
  234. { subagentModel: "bigmodel/GLM-9" },
  235. "model_unavailable",
  236. ],
  237. [
  238. "model_unavailable:没有目录却要换模型",
  239. { catalog: null },
  240. { subagentModel: "bigmodel/GLM-5.3-Flash" },
  241. "model_unavailable",
  242. ],
  243. ["unchanged:什么都没传", {}, {}, "unchanged"],
  244. [
  245. "unchanged:设成现在的值",
  246. { snapshot: { maxConcurrency: 4, subagentModel: "bigmodel/GLM-5.3-Flash" } },
  247. { maxConcurrency: 4, subagentModel: "bigmodel/GLM-5.3-Flash" },
  248. "unchanged",
  249. ],
  250. [
  251. "unchanged:停在默认并发上 = 本来就没有自己的界",
  252. { defaultConcurrency: 13 },
  253. { maxConcurrency: 13 },
  254. "unchanged",
  255. ],
  256. [
  257. "compile_failed:存下的脚本编不过",
  258. { script: BROKEN_SCRIPT },
  259. { maxConcurrency: 4 },
  260. "compile_failed",
  261. ],
  262. ] as const)("%s", async (_case, setup, change, reason) => {
  263. const { runtime, amends, store, events } = makeRuntime({
  264. name: `reject-${reason}`,
  265. ...(setup as Parameters<typeof makeRuntime>[0]),
  266. });
  267. const result = await runtime.amendWorkflowRunSettings({ runId: PREVIOUS, ...change });
  268. expect(result).toMatchObject({ ok: false, reason });
  269. expect(amends).toHaveLength(0);
  270. expect(store.savedMessages).toHaveLength(0);
  271. expect(events).toHaveLength(0);
  272. });
  273. it("编译诊断与模型解析诊断随 message 走", async () => {
  274. const broken = makeRuntime({ name: "diag-compile", script: BROKEN_SCRIPT });
  275. const compile = await broken.runtime.amendWorkflowRunSettings({
  276. runId: PREVIOUS,
  277. maxConcurrency: 4,
  278. });
  279. expect((compile as { message?: string }).message).toContain("not assignable");
  280. const unknown = makeRuntime({ name: "diag-model" });
  281. const model = await unknown.runtime.amendWorkflowRunSettings({
  282. runId: PREVIOUS,
  283. subagentModel: "bigmodel/GLM-9",
  284. });
  285. expect((model as { message?: string }).message).toBeTruthy();
  286. });
  287. it.each([
  288. ["run_not_found", "not_found"],
  289. ["missing_boundaries", "missing_boundaries"],
  290. ] as const)("端口拒绝 %s → %s,不记设置轮", async (portReason, reason) => {
  291. const { runtime, store, events } = makeRuntime({
  292. name: `port-${portReason}`,
  293. amend: () => ({ ok: false, reason: portReason }),
  294. });
  295. const result = await runtime.amendWorkflowRunSettings({ runId: PREVIOUS, maxConcurrency: 4 });
  296. expect(result).toEqual({ ok: false, reason });
  297. expect(store.savedMessages).toHaveLength(0);
  298. expect(events).toHaveLength(0);
  299. });
  300. it("端口抛错 → start_failed,message 是原因", async () => {
  301. const { runtime } = makeRuntime({
  302. name: "port-throw",
  303. amend: () => {
  304. throw new Error("journal locked");
  305. },
  306. });
  307. const result = await runtime.amendWorkflowRunSettings({ runId: PREVIOUS, maxConcurrency: 4 });
  308. expect(result).toEqual({ ok: false, reason: "start_failed", message: "journal locked" });
  309. });
  310. });
  311. // docs/dynamic-workflow/launch.md「On the agent」:重跑的是 run 自己的脚本,脚本点名的模型沿用
  312. // launch 时那张绑定表(用户在确认窗里换过的模型因此留得住),并对着目录再解析一遍。
  313. describe("amendWorkflowRunSettings — 脚本点名的模型", () => {
  314. const JUDGED_SCRIPT = [
  315. 'phase("judge");',
  316. 'const verdict = await agent("评审员", { model: "GLM-5.3-Flash" }).ask<string>("judge");',
  317. "return verdict;",
  318. ].join("\n");
  319. it("沿用前驱的绑定(不是按名字重新解析)交给 port.amend", async () => {
  320. const { runtime, amends } = makeRuntime({
  321. name: "models-kept",
  322. script: JUDGED_SCRIPT,
  323. // 用户在前驱确认窗里把 "GLM-5.3-Flash" 这一行换成了 GLM-5.3。
  324. snapshot: { modelBindings: { "GLM-5.3-Flash": "bigmodel/GLM-5.3" } },
  325. });
  326. const result = await runtime.amendWorkflowRunSettings({ runId: PREVIOUS, maxConcurrency: 4 });
  327. expect(result).toMatchObject({ ok: true });
  328. expect(amends[0]!.modelBindings).toEqual({
  329. "GLM-5.3-Flash": { providerId: "bigmodel", modelId: "GLM-5.3" },
  330. });
  331. });
  332. it("沿用的模型已不在目录里:model_unavailable,诊断随 message 走,零 amend", async () => {
  333. const { runtime, amends, store } = makeRuntime({
  334. name: "models-gone",
  335. script: JUDGED_SCRIPT,
  336. snapshot: { modelBindings: { "GLM-5.3-Flash": "retired/GLM-4" } },
  337. });
  338. const result = await runtime.amendWorkflowRunSettings({ runId: PREVIOUS, maxConcurrency: 4 });
  339. expect(result).toMatchObject({ ok: false, reason: "model_unavailable" });
  340. expect((result as { message?: string }).message).toContain("retired/GLM-4");
  341. expect(amends).toHaveLength(0);
  342. expect(store.savedMessages).toHaveLength(0);
  343. });
  344. });
  345. describe("amendWorkflowRunSettings — 成功路径", () => {
  346. it("沿用脚本与实参、带上新设置,登记合成 AmendWorkflow,并落一条设置轮", async () => {
  347. const { runtime, amends, store, events, sessionId } = makeRuntime({
  348. name: "ok",
  349. snapshot: { maxConcurrency: 8 },
  350. });
  351. const result = await runtime.amendWorkflowRunSettings({
  352. runId: PREVIOUS,
  353. subagentModel: "bigmodel/GLM-5.3-Flash",
  354. maxConcurrency: 4,
  355. });
  356. expect(result).toMatchObject({ ok: true, runId: "dwfrun-next", supersededRunId: PREVIOUS });
  357. const toolCallId = (result as { toolCallId: string }).toolCallId;
  358. expect(toolCallId).toMatch(/^settings-/);
  359. expect(amends).toHaveLength(1);
  360. expect(amends[0]).toMatchObject({
  361. scriptText: STORED_SCRIPT,
  362. predecessorRunId: PREVIOUS,
  363. parentSessionId: sessionId,
  364. toolCallId,
  365. maxConcurrency: 4,
  366. subagentModel: { providerId: "bigmodel", modelId: "GLM-5.3-Flash" },
  367. inheritArgs: true,
  368. phaseNames: ["plan"],
  369. });
  370. // 展示名不传:service 沿用前驱的名字。
  371. expect(amends[0]!.name).toBeUndefined();
  372. // 追踪:合成 AmendWorkflow 描述子 → BackgroundTaskStarted(workflow 面板、可取消)。
  373. const started = events.find((event) => event.type === SessionEventType.BackgroundTaskStarted);
  374. expect(started?.payload).toMatchObject({
  375. cancellable: true,
  376. taskId: "dwfrun-next",
  377. taskKind: "workflow",
  378. toolCallId,
  379. toolName: "AmendWorkflow",
  380. });
  381. await settleQueue(events);
  382. const message = store.savedMessages.find((m) => m.source === "workflow_launch");
  383. expect(message).toMatchObject({ role: "user", synthetic: true, visibility: "user-visible" });
  384. const meta = message?.metadata?.workflowLaunch as Record<string, unknown> | undefined;
  385. expect(meta).toMatchObject({
  386. runId: "dwfrun-next",
  387. toolCallId,
  388. name: "triage",
  389. amend: {
  390. predecessorRunId: PREVIOUS,
  391. subagentModel: { to: "bigmodel/GLM-5.3-Flash" },
  392. maxConcurrency: { from: 8, to: 4 },
  393. ceiling: 13,
  394. },
  395. });
  396. // 设置轮不指保存文件,也不带脚本(脚本是前驱的,侧板要的只是图)。
  397. expect(meta).not.toHaveProperty("scope");
  398. expect(meta).not.toHaveProperty("path");
  399. expect(meta).not.toHaveProperty("script");
  400. expect((meta?.display as { kind?: string } | undefined)?.kind).toBe("create_workflow");
  401. const turnStarted = events.find((event) => event.type === SessionEventType.TurnStarted);
  402. expect(turnStarted?.payload).toMatchObject({
  403. executionKind: "controlOnly",
  404. inputSource: "workflow_launch",
  405. workflowLaunch: { runId: "dwfrun-next", amend: { predecessorRunId: PREVIOUS } },
  406. });
  407. const part = store.savedParts.find(
  408. (candidate) => candidate.messageID === message?.id && candidate.type === "text",
  409. );
  410. expect((part as { text?: string } | undefined)?.text).toContain(
  411. `Changed the settings of workflow run ${PREVIOUS} ("triage") from the GUI`,
  412. );
  413. });
  414. it("null 回到默认:模型回会话模型、界回默认并发;端口两个键都缺席", async () => {
  415. const { runtime, amends, store, events } = makeRuntime({
  416. name: "reset",
  417. snapshot: { maxConcurrency: 4, subagentModel: "bigmodel/GLM-5.3-Flash" },
  418. });
  419. const result = await runtime.amendWorkflowRunSettings({
  420. runId: PREVIOUS,
  421. subagentModel: null,
  422. maxConcurrency: null,
  423. });
  424. expect(result.ok).toBe(true);
  425. expect(amends[0]).not.toHaveProperty("maxConcurrency");
  426. expect(amends[0]).not.toHaveProperty("subagentModel");
  427. await settleQueue(events);
  428. const meta = store.savedMessages.find((m) => m.source === "workflow_launch")?.metadata
  429. ?.workflowLaunch as { amend?: Record<string, unknown> } | undefined;
  430. expect(meta?.amend).toEqual({
  431. predecessorRunId: PREVIOUS,
  432. subagentModel: { from: "bigmodel/GLM-5.3-Flash" },
  433. maxConcurrency: { from: 4 },
  434. ceiling: 13,
  435. });
  436. });
  437. it("只改并发时模型沿用前驱的那一个(重新解析一遍),设置轮只记改了的那一项", async () => {
  438. const { runtime, amends, store, events } = makeRuntime({
  439. name: "keep-model",
  440. snapshot: { subagentModel: "bigmodel/GLM-5.3-Flash" },
  441. });
  442. await runtime.amendWorkflowRunSettings({ runId: PREVIOUS, maxConcurrency: 2 });
  443. expect(amends[0]).toMatchObject({
  444. maxConcurrency: 2,
  445. subagentModel: { providerId: "bigmodel", modelId: "GLM-5.3-Flash" },
  446. });
  447. await settleQueue(events);
  448. const meta = store.savedMessages.find((m) => m.source === "workflow_launch")?.metadata
  449. ?.workflowLaunch as { amend?: Record<string, unknown> } | undefined;
  450. expect(meta?.amend).not.toHaveProperty("subagentModel");
  451. expect(meta?.amend).toMatchObject({ maxConcurrency: { to: 2 } });
  452. });
  453. it("主代理在一轮里:设置轮排队,活动轮的吸收在它这里停下,后到的通知排在它后面", async () => {
  454. const { runtime, store } = makeRuntime({ name: "busy" });
  455. const internal = runtime as unknown as {
  456. runtimeCommandDrainActive: boolean;
  457. runtimeCommandQueue: { snapshot(): readonly { mode: string }[] };
  458. enqueueRuntimeCommand(command: unknown): void;
  459. branchGeneration: number;
  460. rootTraceContext: unknown;
  461. };
  462. // 制造「正在一轮里」:队列的 drain 被占着,新命令只能排队。
  463. internal.runtimeCommandDrainActive = true;
  464. const result = await runtime.amendWorkflowRunSettings({ runId: PREVIOUS, maxConcurrency: 4 });
  465. expect(result.ok).toBe(true);
  466. // 新 run 的通知在设置轮之后入队。
  467. internal.enqueueRuntimeCommand({
  468. branchGeneration: internal.branchGeneration,
  469. createdAt: new Date(),
  470. id: createRuntimeCommandId(),
  471. mode: "task-notification",
  472. priority: "next",
  473. source: "background_task",
  474. taskId: "dwfrun-next",
  475. text: "run dwfrun-next completed",
  476. traceContext: internal.rootTraceContext,
  477. });
  478. expect(store.savedMessages).toHaveLength(0);
  479. expect(internal.runtimeCommandQueue.snapshot().map((command) => command.mode)).toEqual([
  480. "control-only-turn",
  481. "task-notification",
  482. ]);
  483. // 活动轮的吸收不越过设置轮:通知要留给外层队列,排在设置轮之后。
  484. const drained = await drainPendingRuntimeCommandsForActiveLoop.call(runtime as never);
  485. expect(drained.drained).toBe(0);
  486. expect(internal.runtimeCommandQueue.snapshot()).toHaveLength(2);
  487. });
  488. });
  489. describe("amendWorkflowRunSettings — 新 run 的脚本文件", () => {
  490. it("前驱的脚本文件仍是这份字节:新 run 继续记它,不写新草稿", async () => {
  491. const dir = join(SETTINGS_CWD, WORKFLOW_DRAFTS_DIR);
  492. mkdirSync(dir, { recursive: true });
  493. const file = join(dir, "kept-by-settings.dwf.ts");
  494. writeFileSync(file, STORED_SCRIPT, "utf8");
  495. const { runtime, amends } = makeRuntime({ name: "keep-file", snapshot: { scriptPath: file } });
  496. const result = await runtime.amendWorkflowRunSettings({ runId: PREVIOUS, maxConcurrency: 4 });
  497. expect(result).toMatchObject({ ok: true });
  498. expect(amends[0]!.scriptPath).toBe(file);
  499. });
  500. it("前驱的文件已被改过(或没记过文件):写一份装着存档脚本的新草稿并记它", async () => {
  501. const dir = join(SETTINGS_CWD, WORKFLOW_DRAFTS_DIR);
  502. mkdirSync(dir, { recursive: true });
  503. const file = join(dir, "edited-since.dwf.ts");
  504. writeFileSync(file, `${STORED_SCRIPT}\n// edited\n`, "utf8");
  505. const { runtime, amends } = makeRuntime({
  506. name: "diverged-file",
  507. snapshot: { scriptPath: file, name: "settings diverged" },
  508. });
  509. const result = await runtime.amendWorkflowRunSettings({ runId: PREVIOUS, maxConcurrency: 4 });
  510. expect(result).toMatchObject({ ok: true });
  511. const recorded = amends[0]!.scriptPath;
  512. expect(recorded).toBe(join(dir, "settings-diverged.dwf.ts"));
  513. expect(readFileSync(recorded!, "utf8")).toBe(STORED_SCRIPT);
  514. expect(readFileSync(file, "utf8")).toContain("// edited");
  515. });
  516. it("拒绝的调用不落草稿:直到 port.amend 之前都是零副作用", async () => {
  517. const { runtime, amends } = makeRuntime({
  518. name: "unchanged-no-draft",
  519. snapshot: { name: "never written", maxConcurrency: 4 },
  520. });
  521. const result = await runtime.amendWorkflowRunSettings({ runId: PREVIOUS, maxConcurrency: 4 });
  522. expect(result).toMatchObject({ ok: false, reason: "unchanged" });
  523. expect(amends).toHaveLength(0);
  524. expect(() =>
  525. readFileSync(join(SETTINGS_CWD, WORKFLOW_DRAFTS_DIR, "never-written.dwf.ts")),
  526. ).toThrow();
  527. });
  528. });
  529. describe("amendWorkflowRunSettings — 无名 run", () => {
  530. // 2026-09-18 实机:无名 run 的设置轮曾兜底成名字 `run <id>`,卡片与侧板标题成了一串 run id。
  531. it("前驱没有名字:设置轮元数据与合成追踪都不带名字,规范句也不编一个", async () => {
  532. const { runtime, store, events } = makeRuntime({
  533. name: "unnamed",
  534. snapshot: { name: undefined },
  535. });
  536. const result = await runtime.amendWorkflowRunSettings({ runId: PREVIOUS, maxConcurrency: 4 });
  537. expect(result.ok).toBe(true);
  538. const started = events.find((event) => event.type === SessionEventType.BackgroundTaskStarted);
  539. expect((started?.payload as { description?: string } | undefined)?.description).not.toContain(
  540. "run dwfrun",
  541. );
  542. await settleQueue(events);
  543. const message = store.savedMessages.find((m) => m.source === "workflow_launch");
  544. expect(message?.metadata?.workflowLaunch).not.toHaveProperty("name");
  545. const part = store.savedParts.find(
  546. (candidate) => candidate.messageID === message?.id && candidate.type === "text",
  547. );
  548. expect((part as { text?: string } | undefined)?.text).toContain(
  549. `Changed the settings of workflow run ${PREVIOUS} from the GUI`,
  550. );
  551. });
  552. });
  553. // 只改并发、run 还活着 ⇒ 就地生效(docs/dynamic-workflow/launch.md「On the agent」的分叉行):
  554. // 同一个 runId、没有 supersededRunId、不登记第二个后台任务,设置轮的 amend 块不带
  555. // predecessorRunId(缺席即「就地生效」)。脚本读挪到分叉之后,所以没有存档脚本的 run 也能调。
  556. describe("amendWorkflowRunSettings — 只改并发即就地生效", () => {
  557. it("同一个 runId、无 supersededRunId、不 amend、不读脚本,设置轮记下这一手", async () => {
  558. const { runtime, amends, retunes, getScriptCalls, store, events } = makeRuntime({
  559. name: "retune-ok",
  560. snapshot: { maxConcurrency: 8 },
  561. retune: { ok: true, maxConcurrency: 4, previous: 8, defaultConcurrency: 13 },
  562. });
  563. const result = await runtime.amendWorkflowRunSettings({ runId: PREVIOUS, maxConcurrency: 4 });
  564. expect(result).toEqual({ ok: true, runId: PREVIOUS, toolCallId: expect.any(String) });
  565. expect((result as { toolCallId: string }).toolCallId).toMatch(/^settings-/);
  566. expect(retunes).toEqual([{ runId: PREVIOUS, maxConcurrency: 4 }]);
  567. expect(amends).toHaveLength(0);
  568. // 分叉在脚本读之前:这条路一份脚本都不需要。
  569. expect(getScriptCalls).toHaveLength(0);
  570. // run 本来就在追踪器里,不再登记第二个后台任务。
  571. expect(events.find((event) => event.type === SessionEventType.BackgroundTaskStarted)).toBe(
  572. undefined,
  573. );
  574. await settleQueue(events);
  575. const message = store.savedMessages.find((m) => m.source === "workflow_launch");
  576. const meta = message?.metadata?.workflowLaunch as Record<string, unknown> | undefined;
  577. expect(meta).toMatchObject({
  578. runId: PREVIOUS,
  579. name: "triage",
  580. amend: { maxConcurrency: { from: 8, to: 4 }, ceiling: 13 },
  581. });
  582. // 缺席即「就地生效」;这条路不编译,所以也没有 display。
  583. expect(meta?.amend).not.toHaveProperty("predecessorRunId");
  584. expect(meta).not.toHaveProperty("display");
  585. const part = store.savedParts.find(
  586. (candidate) => candidate.messageID === message?.id && candidate.type === "text",
  587. );
  588. const text = (part as { text?: string } | undefined)?.text ?? "";
  589. expect(text).toContain(
  590. `Changed the settings of workflow run ${PREVIOUS} ("triage") from the GUI`,
  591. );
  592. expect(text).toContain("at most 4 of its subagents run at once");
  593. expect(text).toContain("keeps running under the new limit");
  594. expect(text).not.toContain("supersedes");
  595. });
  596. it("回到默认并发:等于默认的那一端缺席,文案说上限回到默认", async () => {
  597. const { runtime, retunes, store, events } = makeRuntime({
  598. name: "retune-default",
  599. snapshot: { maxConcurrency: 4 },
  600. retune: { ok: true, maxConcurrency: 13, previous: 4, defaultConcurrency: 13 },
  601. });
  602. const result = await runtime.amendWorkflowRunSettings({
  603. runId: PREVIOUS,
  604. maxConcurrency: null,
  605. });
  606. expect(result).toMatchObject({ ok: true, runId: PREVIOUS });
  607. // 弹层的 `null` 原样走到端口:默认并发那个数只有端口知道。
  608. expect(retunes).toEqual([{ runId: PREVIOUS, maxConcurrency: null }]);
  609. await settleQueue(events);
  610. const message = store.savedMessages.find((m) => m.source === "workflow_launch");
  611. const meta = message?.metadata?.workflowLaunch as { amend?: Record<string, unknown> };
  612. expect(meta.amend).toEqual({ maxConcurrency: { from: 4 }, ceiling: 13 });
  613. const part = store.savedParts.find(
  614. (candidate) => candidate.messageID === message?.id && candidate.type === "text",
  615. );
  616. expect((part as { text?: string } | undefined)?.text).toContain(
  617. "the limit on subagents at once is back to the default",
  618. );
  619. });
  620. it("调到默认并发之上:就地生效,两端都是数", async () => {
  621. const { runtime, retunes, store, events } = makeRuntime({
  622. name: "retune-raise",
  623. snapshot: {},
  624. retune: { ok: true, maxConcurrency: 40, previous: 13, defaultConcurrency: 13 },
  625. });
  626. const result = await runtime.amendWorkflowRunSettings({ runId: PREVIOUS, maxConcurrency: 40 });
  627. expect(result).toMatchObject({ ok: true, runId: PREVIOUS });
  628. expect(retunes).toEqual([{ runId: PREVIOUS, maxConcurrency: 40 }]);
  629. await settleQueue(events);
  630. const message = store.savedMessages.find((m) => m.source === "workflow_launch");
  631. const meta = message?.metadata?.workflowLaunch as { amend?: Record<string, unknown> };
  632. expect(meta.amend).toEqual({ maxConcurrency: { to: 40 }, ceiling: 13 });
  633. });
  634. it("端口答 unchanged(值在分叉之后被挪过)→ 既有的 unchanged 拒绝", async () => {
  635. const { runtime, amends, store, events } = makeRuntime({
  636. name: "retune-unchanged",
  637. snapshot: { maxConcurrency: 8 },
  638. retune: { ok: false, reason: "unchanged", current: 4 },
  639. });
  640. const result = await runtime.amendWorkflowRunSettings({ runId: PREVIOUS, maxConcurrency: 4 });
  641. expect(result).toMatchObject({ ok: false, reason: "unchanged" });
  642. expect(amends).toHaveLength(0);
  643. expect(store.savedMessages).toHaveLength(0);
  644. expect(events).toHaveLength(0);
  645. });
  646. it("端口答 not_live → 平平落回今天的修订", async () => {
  647. const { runtime, amends, retunes, getScriptCalls } = makeRuntime({
  648. name: "retune-not-live",
  649. snapshot: { maxConcurrency: 8 },
  650. retune: { ok: false, reason: "not_live" },
  651. });
  652. const result = await runtime.amendWorkflowRunSettings({ runId: PREVIOUS, maxConcurrency: 4 });
  653. expect(retunes).toHaveLength(1);
  654. expect(result).toMatchObject({ ok: true, runId: "dwfrun-next", supersededRunId: PREVIOUS });
  655. expect(getScriptCalls).toEqual([PREVIOUS]);
  656. expect(amends).toHaveLength(1);
  657. expect(amends[0]?.maxConcurrency).toBe(4);
  658. });
  659. it("同时换模型 → 仍是一次修订,端口的 retuneConcurrency 一次都不碰", async () => {
  660. const { runtime, amends, retunes } = makeRuntime({
  661. name: "retune-with-model",
  662. snapshot: { maxConcurrency: 8 },
  663. retune: { ok: true, maxConcurrency: 4, previous: 8, defaultConcurrency: 13 },
  664. });
  665. const result = await runtime.amendWorkflowRunSettings({
  666. runId: PREVIOUS,
  667. maxConcurrency: 4,
  668. subagentModel: "bigmodel/GLM-5.3-Flash",
  669. });
  670. expect(retunes).toHaveLength(0);
  671. expect(result).toMatchObject({ ok: true, runId: "dwfrun-next" });
  672. expect(amends).toHaveLength(1);
  673. });
  674. it("端口没有 retuneConcurrency(老宿主)→ 照旧一次修订", async () => {
  675. const { runtime, amends } = makeRuntime({
  676. name: "retune-old-host",
  677. snapshot: { maxConcurrency: 8 },
  678. });
  679. const result = await runtime.amendWorkflowRunSettings({ runId: PREVIOUS, maxConcurrency: 4 });
  680. expect(result).toMatchObject({ ok: true, runId: "dwfrun-next" });
  681. expect(amends).toHaveLength(1);
  682. });
  683. });
  684. describe("buildSettingsMessageText", () => {
  685. it("只说改过的设置;两个 null 各有一句;已结算的前驱读作 takes over from", () => {
  686. const text = buildSettingsMessageText({
  687. name: "triage",
  688. previous: "dwfrun-a",
  689. runId: "dwfrun-b",
  690. superseded: false,
  691. amend: {
  692. predecessorRunId: "dwfrun-a",
  693. subagentModel: { from: "bigmodel/GLM-5.3" },
  694. maxConcurrency: { from: 4 },
  695. },
  696. });
  697. expect(text).toContain("its subagents are back on the session model");
  698. expect(text).toContain("the limit on subagents at once is back to the default");
  699. expect(text).toContain("which takes over from run dwfrun-a");
  700. expect(text).toContain("do not amend, resume or restart it");
  701. });
  702. // 缺席的 predecessorRunId 即「就地生效」:上面那句会让模型去找一个不存在的 run B。
  703. it("就地生效:只点名一个 run,说它继续在跑、没有新 run", () => {
  704. const text = buildSettingsMessageText({
  705. name: "triage",
  706. previous: "dwfrun-a",
  707. runId: "dwfrun-a",
  708. superseded: false,
  709. amend: { maxConcurrency: { from: 8, to: 2 }, ceiling: 13 },
  710. });
  711. expect(text).toContain('Changed the settings of workflow run dwfrun-a ("triage") from the GUI');
  712. expect(text).toContain("at most 2 of its subagents run at once");
  713. expect(text).toContain("Run dwfrun-a keeps running under the new limit");
  714. expect(text).toContain("nothing was stopped and no new run was started");
  715. expect(text).not.toContain("dwfrun-b");
  716. expect(text).not.toContain("takes over from");
  717. expect(text).toContain("do not amend, resume or restart it");
  718. });
  719. });