compact-task-status.test.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. import { describe, expect, it } from "vitest";
  2. import type { RuntimeAttachmentEntry } from "../src/agent/message-history.js";
  3. import { buildCompactTaskStatusEntries } from "../src/runtime/helpers/compact-task-status.js";
  4. import {
  5. InMemoryRuntimeTaskRegistry,
  6. type RuntimeTaskSnapshot,
  7. } from "../src/runtime-task/registry.js";
  8. import { registerRuntimeBackgroundTask } from "../src/tool/executor/background-task-registry.js";
  9. const NOW = new Date("2026-11-13T00:00:30.000Z");
  10. function agent(overrides: Partial<RuntimeTaskSnapshot> = {}): RuntimeTaskSnapshot {
  11. return {
  12. agentId: "agent_1",
  13. agentType: "general-purpose",
  14. branchGeneration: 0,
  15. description: "Audit child",
  16. isBackgrounded: true,
  17. outputFile: "/tmp/agent_1.output",
  18. startedAt: new Date("2026-11-13T00:00:00.000Z"),
  19. status: "running",
  20. taskId: "agent_1",
  21. taskType: "local_agent",
  22. type: "local_agent",
  23. ...overrides,
  24. };
  25. }
  26. function shell(overrides: Partial<RuntimeTaskSnapshot> = {}): RuntimeTaskSnapshot {
  27. return agent({
  28. agentId: "b1",
  29. agentType: "local_bash",
  30. command: "sleep 30",
  31. description: "Audit sleep",
  32. outputFile: "/tmp/b1.output",
  33. taskId: "b1",
  34. taskType: "local_bash",
  35. type: "local_bash",
  36. ...overrides,
  37. });
  38. }
  39. function build(
  40. tasks: RuntimeTaskSnapshot[],
  41. options: { canContinueAgent?: boolean; canReadOutputFile?: boolean } = {},
  42. ): string[] {
  43. return buildCompactTaskStatusEntries({
  44. branchGeneration: 0,
  45. canContinueAgent: options.canContinueAgent ?? true,
  46. canReadOutputFile: options.canReadOutputFile ?? true,
  47. now: NOW,
  48. tasks,
  49. }).map((entry: RuntimeAttachmentEntry) => {
  50. expect(entry.metadata.source).toBe("task_status");
  51. return entry.content;
  52. });
  53. }
  54. describe("compaction task status", () => {
  55. it("restates running agents and background shells, agents first", () => {
  56. expect(build([shell(), agent()])).toEqual([
  57. 'Background agent "Audit child" (agent_1) is still running. Do NOT spawn a duplicate. You will be notified when it completes. Send it a message with SendMessage if you need a progress report before then.',
  58. 'Background shell b1 ("Audit sleep") is still running (command, shown on one line: `sleep 30`). Do not start it again; to restart it, stop it with TaskStop first. You can read its output at /tmp/b1.output.',
  59. ]);
  60. });
  61. // 结束不到 30 秒的 agent 仍在列表里;超过 30 秒的不补回。
  62. it("restates agents that ended less than 30 seconds ago", () => {
  63. const ended = (seconds: number, status: RuntimeTaskSnapshot["status"], extra = {}) =>
  64. agent({
  65. completedAt: new Date(NOW.getTime() - seconds * 1000),
  66. status,
  67. ...extra,
  68. });
  69. expect(
  70. build([
  71. ended(29, "completed", { taskId: "agent_done", description: "Done child" }),
  72. ended(29, "failed", { taskId: "agent_failed", error: "boom" }),
  73. ended(10, "killed", { taskId: "agent_stopped" }),
  74. ended(31, "completed", { taskId: "agent_old" }),
  75. ]),
  76. ).toEqual([
  77. "Task agent_done (type: local_agent) (status: completed) (description: Done child) Send it a message with SendMessage to retrieve its result.",
  78. "Task agent_failed (type: local_agent) (status: failed) (description: Audit child) Delta: boom Send it a message with SendMessage to retrieve its result.",
  79. 'Task "Audit child" (agent_stopped) was stopped.',
  80. ]);
  81. });
  82. it("restates foreground agents like background ones", () => {
  83. expect(
  84. build([agent({ isBackgrounded: false, status: "completed", completedAt: NOW })]),
  85. ).toEqual([
  86. "Task agent_1 (type: local_agent) (status: completed) (description: Audit child) Send it a message with SendMessage to retrieve its result.",
  87. ]);
  88. });
  89. it("drops the SendMessage sentence without the tool and the output path without Read or Bash", () => {
  90. expect(
  91. build(
  92. [agent(), agent({ taskId: "agent_2", status: "completed", completedAt: NOW }), shell()],
  93. {
  94. canContinueAgent: false,
  95. canReadOutputFile: false,
  96. },
  97. ),
  98. ).toEqual([
  99. 'Background agent "Audit child" (agent_1) is still running. Do NOT spawn a duplicate. You will be notified when it completes.',
  100. "Task agent_2 (type: local_agent) (status: completed) (description: Audit child)",
  101. 'Background shell b1 ("Audit sleep") is still running (command, shown on one line: `sleep 30`). Do not start it again; to restart it, stop it with TaskStop first.',
  102. ]);
  103. });
  104. it("skips ended shells, workflows, tasks of other branches and shells without a command part", () => {
  105. expect(
  106. build([
  107. shell({ status: "completed", completedAt: NOW, taskId: "b_done" }),
  108. shell({ isBackgrounded: false, taskId: "b_fg" }),
  109. agent({ taskId: "wf", taskType: "local_dynamic_workflow", type: "local_dynamic_workflow" }),
  110. agent({ taskId: "agent_old_branch", branchGeneration: 1 }),
  111. shell({ command: undefined, outputFile: undefined, taskId: "b_plain" }),
  112. ]),
  113. ).toEqual([
  114. 'Background shell b_plain ("Audit sleep") is still running. Do not start it again; to restart it, stop it with TaskStop first.',
  115. ]);
  116. });
  117. // 描述和命令压成一行再截断;agent 文字里的 & < > 写成实体。
  118. it("puts shell text on one line, cuts it and escapes agent text", () => {
  119. const [shellText] = build([
  120. shell({
  121. command: `printf 'a\n\tb' ${"x".repeat(600)}`,
  122. description: `line one\nline two ${"d".repeat(250)}`,
  123. }),
  124. ]);
  125. const command = `printf 'a b' ${"x".repeat(600)}`;
  126. const description = `line one line two ${"d".repeat(250)}`;
  127. expect(shellText).toContain(
  128. `("${description.slice(0, 200)}\u2026 [+${description.length - 200} chars]")`,
  129. );
  130. expect(shellText).toContain(
  131. `\`${command.slice(0, 500)}\u2026 [+${command.length - 500} chars]\``,
  132. );
  133. expect(build([agent({ description: "fix <a> & b\u0007" })])[0]).toContain(
  134. '"fix &lt;a&gt; &amp; b&#7;"',
  135. );
  136. });
  137. // 不可见字符和控制字符一样去掉:零宽连接符、私用区、双向控制、格式字符、未分配码位、不成对的代理码位、BOM。
  138. it("drops invisible characters from shell text", () => {
  139. const [shellText] = build([
  140. shell({
  141. command: "echo a\u200Db\uE000c\u202Ed\u0600e\u0378f\uD800g",
  142. description: "x\uFEFFy\u{E0001}z",
  143. }),
  144. ]);
  145. expect(shellText).toContain('("xyz")');
  146. expect(shellText).toContain("`echo abcdefg`");
  147. });
  148. });
  149. describe("background shell registration", () => {
  150. it("stores the command so compaction can restate the running shell", () => {
  151. const runtimeTaskRegistry = new InMemoryRuntimeTaskRegistry();
  152. registerRuntimeBackgroundTask(
  153. { runtimeTaskRegistry } as never,
  154. {
  155. id: "toolu_bg",
  156. input: { command: "sleep 30", description: "Audit sleep", run_in_background: true },
  157. name: "Bash",
  158. } as never,
  159. "b1",
  160. { backgroundTaskId: "b1" },
  161. );
  162. expect(runtimeTaskRegistry.get("b1")).toMatchObject({
  163. command: "sleep 30",
  164. description: "Audit sleep",
  165. status: "running",
  166. type: "local_bash",
  167. });
  168. });
  169. });