v4ConversationRuntimeRecycleSelfHeal.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. // CUA Helper 冷启动就绪会回收 agent runtime,已打开的对话面板必须自愈。
  2. //
  3. // 线上/dev 复现时序(2026-08-22 dev 日志):
  4. // 17:26:41.5 用户点开已有对话 → subscribeConversationV4 在途(agent 仍在 warmup)
  5. // 17:26:44.395 [cua-product-helper] cua helper ready
  6. // → reconcileRecoveredHelper → recycleUntilStable → disposeWorkspace
  7. // 17:26:44.719 在途 subscribe 被 transport.onClose 的 rejectAll 打断:
  8. // Error: ZCode agent transport closed
  9. // 17:26:44.96 ZCode agent process exited terminationReason='workspace-dispose'
  10. //
  11. // 修复前 store 的两处缺陷让面板永久卡死(SessionPane 的 errored 分支整块替换成红字+重连按钮):
  12. // 1. constructor 无条件只订阅 onRuntimeRestart。但 transport.ts 已写明:dispose 当场只有
  13. // onRuntimeLifecycle 的 unavailable 可观测,onRuntimeRestart 要等新进程 spawn 才发;
  14. // agent 是懒启动,用户只看历史不发消息则永不 spawn,换代信号永不到达。
  15. // 2. connect() 的 catch 除 initialFrameStagingOverflow 外一律定格 status="error",
  16. // 没有 sessionsIndexStore 那样的有界退避。
  17. //
  18. // 自愈成立的前提(zcodeAgentService.ts:5581):subscribeConversationV4 走
  19. // getReadOnlyClient(params) 默认 start-if-needed,重订阅本身会把 agent 拉起来——这与侧栏
  20. // subscribeSessionsIndexV4 显式用 existing-only + dormant 的策略差异是故意设计的。
  21. import { Emitter } from "@zcode/rpc";
  22. import type { ConversationTopicWireFrame } from "@zcode/shared/zcode-protocol-v4";
  23. import {
  24. createZCodeAgentConnectionScope,
  25. readTrustedZCodeAgentV4Connection,
  26. type IZCodeAgentService,
  27. } from "@zcode/services";
  28. import { describe, expect, it, vi } from "vitest";
  29. import { createAgentConversationTransport } from "@/v4/agentConversationTransport.js";
  30. import { ConversationProjectionStore } from "@/v4/conversationProjectionStore.js";
  31. import { ReplaceableConversationTransport } from "@/v4/replaceableConversationTransport.js";
  32. const TOPIC = "conversation/s1";
  33. const WORKSPACE_PATH = "/repo";
  34. type LifecycleEvent = {
  35. workspaceKey: string;
  36. workspacePath: string;
  37. runtimeIdentity: { generation: number; identity: string; workspaceKey: string };
  38. state: "available" | "unavailable";
  39. };
  40. /** connectionScope 的 unavailable 分支要读 runtimeIdentity.generation 来失效本地 owner。 */
  41. function lifecycleEvent(state: "available" | "unavailable", generation: number): LifecycleEvent {
  42. return {
  43. workspaceKey: WORKSPACE_PATH,
  44. workspacePath: WORKSPACE_PATH,
  45. runtimeIdentity: {
  46. generation,
  47. identity: `runtime-${generation}`,
  48. workspaceKey: WORKSPACE_PATH,
  49. },
  50. state,
  51. };
  52. }
  53. /** workspace-dispose 打断在途 subscribe 时,ZCodeProtocolClient.rejectAll 抛出的真实文案。 */
  54. const TRANSPORT_CLOSED = "ZCode agent transport closed";
  55. /** 与实现的 RUNTIME_RECYCLE_RETRY_DELAYS_MS 长度一致(250/1000/3000ms)。 */
  56. const RUNTIME_RECYCLE_RETRY_ATTEMPTS = 3;
  57. function setupBase(options: { withLifecycle?: boolean } = {}) {
  58. const conversationFrames = new Emitter<ConversationTopicWireFrame>();
  59. const runtimeRestarts = new Emitter<{ workspaceKey: string }>();
  60. const runtimeLifecycle = new Emitter<LifecycleEvent>();
  61. const nextSerialByConnection = new Map<string, number>();
  62. const nextId = (params: unknown) => {
  63. const connection = readTrustedZCodeAgentV4Connection(params);
  64. if (!connection) throw new Error("missing trusted connection");
  65. const serial = (nextSerialByConnection.get(connection.connectionId) ?? 0) + 1;
  66. nextSerialByConnection.set(connection.connectionId, serial);
  67. return `sub-${connection.connectionId}-${serial}`;
  68. };
  69. /** 每次 subscribe 依次消费一个错误;用尽后正常 ACK。 */
  70. const pendingFailures: Error[] = [];
  71. const mocks = {
  72. helloConversationV4: vi.fn(),
  73. initializeConversationV4: vi.fn(),
  74. subscribeConversationV4: vi.fn(async (params: unknown) => {
  75. const failure = pendingFailures.shift();
  76. if (failure) throw failure;
  77. return {
  78. ack: {
  79. subscriptionId: nextId(params),
  80. mode: "snapshot" as const,
  81. logEpoch: "epoch-1",
  82. },
  83. };
  84. }),
  85. unsubscribeConversationV4: vi.fn(async () => {}),
  86. resyncConversationV4: vi.fn(async (params: { subscriptionId: string }) => ({
  87. ack: {
  88. subscriptionId: params.subscriptionId,
  89. mode: "resume" as const,
  90. logEpoch: "epoch-1",
  91. },
  92. })),
  93. sendConversationCommandV4: vi.fn(async (params: { envelope: { commandId: string } }) => ({
  94. commandId: params.envelope.commandId,
  95. status: "accepted" as const,
  96. revisionAtDecision: 1,
  97. })),
  98. onDynamicConversationFrame: vi.fn(() => conversationFrames.event),
  99. onAgentRuntimeRestarted: vi.fn((listener: (event: { workspaceKey: string }) => void) =>
  100. runtimeRestarts.event(listener),
  101. ),
  102. setConnectionFlowStateV4: vi.fn(async () => {}),
  103. ...(options.withLifecycle
  104. ? {
  105. onAgentRuntimeLifecycle: vi.fn((listener: (event: LifecycleEvent) => void) =>
  106. runtimeLifecycle.event(listener),
  107. ),
  108. }
  109. : {}),
  110. };
  111. return {
  112. base: mocks as unknown as IZCodeAgentService,
  113. mocks,
  114. runtimeLifecycle,
  115. runtimeRestarts,
  116. pendingFailures,
  117. };
  118. }
  119. function createStore(
  120. base: IZCodeAgentService,
  121. connectionId: string,
  122. clientMode: "desktop-continuous" | "web-remote-replayable" = "desktop-continuous",
  123. ) {
  124. const scope = createZCodeAgentConnectionScope(base, {
  125. connectionId,
  126. clientMode,
  127. });
  128. const transport = createAgentConversationTransport(scope.service, {
  129. workspacePath: WORKSPACE_PATH,
  130. });
  131. return { transport, store: new ConversationProjectionStore(TOPIC, transport) };
  132. }
  133. describe("conversation projection 在 CUA Helper 回收 agent runtime 后自愈", () => {
  134. it.each(["desktop-continuous", "web-remote-replayable"] as const)(
  135. "%s 冷订阅期间收到 restart,过期 ACK 后自动重新订阅",
  136. async (clientMode) => {
  137. vi.useFakeTimers();
  138. try {
  139. const { base, mocks, runtimeLifecycle, runtimeRestarts } = setupBase({
  140. withLifecycle: true,
  141. });
  142. const { store } = createStore(base, "cold-restart", clientMode);
  143. mocks.subscribeConversationV4.mockImplementationOnce(async () => {
  144. runtimeRestarts.fire({ workspaceKey: WORKSPACE_PATH });
  145. runtimeLifecycle.fire(lifecycleEvent("available", 2));
  146. return { ack: { subscriptionId: "stale", mode: "snapshot", logEpoch: "epoch-1" } };
  147. });
  148. await store.connect();
  149. expect(store.getState().status).toBe("connecting");
  150. await vi.advanceTimersByTimeAsync(250);
  151. expect(mocks.subscribeConversationV4).toHaveBeenCalledTimes(2);
  152. expect(store.getState().status).toBe("live");
  153. expect(store.getState().lastError).toBeNull();
  154. expect(mocks.unsubscribeConversationV4).not.toHaveBeenCalledWith(
  155. expect.objectContaining({ subscriptionId: "stale" }),
  156. );
  157. } finally {
  158. vi.useRealTimers();
  159. }
  160. },
  161. );
  162. it("runtime available 到达时重新订阅(transport 暴露 lifecycle 时不能只依赖 onRuntimeRestart)", async () => {
  163. const { base, mocks, runtimeLifecycle } = setupBase({ withLifecycle: true });
  164. const { transport, store } = createStore(base, "conn-lifecycle");
  165. expect(transport.onRuntimeLifecycle).toBeTypeOf("function");
  166. await store.connect();
  167. expect(store.getState().status).toBe("live");
  168. expect(mocks.subscribeConversationV4).toHaveBeenCalledTimes(1);
  169. // workspace-dispose 当场:唯一可观测信号。此时新 runtime 尚不存在,不可重订阅。
  170. runtimeLifecycle.fire(lifecycleEvent("unavailable", 2));
  171. await Promise.resolve();
  172. expect(mocks.subscribeConversationV4).toHaveBeenCalledTimes(1);
  173. // 新 runtime 就绪:必须自动重订阅,否则面板永久停在旧订阅/错误态。
  174. runtimeLifecycle.fire(lifecycleEvent("available", 2));
  175. await new Promise<void>((resolve) => setTimeout(resolve, 0));
  176. expect(mocks.subscribeConversationV4).toHaveBeenCalledTimes(2);
  177. expect(store.getState().status).toBe("live");
  178. });
  179. it("首次 subscribe 在途时 runtime available 不应再开第二条订阅", async () => {
  180. const { base, mocks, runtimeLifecycle } = setupBase({ withLifecycle: true });
  181. let resolveSubscribe:
  182. | ((value: { ack: { subscriptionId: string; mode: "snapshot"; logEpoch: string } }) => void)
  183. | null = null;
  184. mocks.subscribeConversationV4.mockImplementationOnce(
  185. () =>
  186. new Promise((resolve) => {
  187. resolveSubscribe = resolve;
  188. }),
  189. );
  190. const { store } = createStore(base, "conn-initial-available");
  191. const connectPromise = store.connect();
  192. await vi.waitFor(() => expect(mocks.subscribeConversationV4).toHaveBeenCalledTimes(1));
  193. // 冷启动时 agent spawn 会先广播 available;首次 subscribe 已在途时,
  194. // 该通知不应把同一个 pane 再推进一轮 connect,避免旧 ACK 立刻被退订。
  195. runtimeLifecycle.fire(lifecycleEvent("available", 1));
  196. await Promise.resolve();
  197. expect(mocks.subscribeConversationV4).toHaveBeenCalledTimes(1);
  198. resolveSubscribe?.({
  199. ack: { subscriptionId: "sub-initial-available", mode: "snapshot", logEpoch: "epoch-1" },
  200. });
  201. await connectPromise;
  202. expect(store.getState().status).toBe("live");
  203. expect(store.getState().subscriptionId).toBe("sub-initial-available");
  204. });
  205. it("live 订阅被回收且 available 永不到达时,退避重连自行拉起 runtime", async () => {
  206. vi.useFakeTimers();
  207. try {
  208. const { base, mocks, runtimeLifecycle } = setupBase({ withLifecycle: true });
  209. const { store } = createStore(base, "conn-dormant");
  210. await store.connect();
  211. expect(store.getState().status).toBe("live");
  212. // 只发 unavailable,不发 available——正是懒启动下的真实情形:dispose 后无人拉起
  213. // agent,onRuntimeRestart/available 都永不到达。若此处仅 dormant,面板会永久转圈。
  214. runtimeLifecycle.fire(lifecycleEvent("unavailable", 2));
  215. await vi.advanceTimersByTimeAsync(0);
  216. expect(mocks.subscribeConversationV4).toHaveBeenCalledTimes(1);
  217. // 重订阅走 start-if-needed,自身会把 runtime 拉起来。
  218. await vi.advanceTimersByTimeAsync(1_000);
  219. expect(mocks.subscribeConversationV4).toHaveBeenCalledTimes(2);
  220. expect(store.getState().status).toBe("live");
  221. } finally {
  222. vi.useRealTimers();
  223. }
  224. });
  225. // 回归保护(非 TDD 驱动,实现时已正确):退避必须有界,耗尽后把失败暴露成 error,
  226. // SessionPane 的 errored 分支才会渲染「重新连接」按钮。
  227. it("退避耗尽后落 error 暴露「重新连接」入口", async () => {
  228. vi.useFakeTimers();
  229. try {
  230. const { base, mocks, runtimeLifecycle, pendingFailures } = setupBase({
  231. withLifecycle: true,
  232. });
  233. const { store } = createStore(base, "conn-exhausted");
  234. await store.connect();
  235. expect(store.getState().status).toBe("live");
  236. for (let i = 0; i < 8; i += 1) pendingFailures.push(new Error(TRANSPORT_CLOSED));
  237. runtimeLifecycle.fire(lifecycleEvent("unavailable", 2));
  238. await vi.advanceTimersByTimeAsync(30_000);
  239. expect(store.getState().status).toBe("error");
  240. expect(store.getState().lastError).toContain(TRANSPORT_CLOSED);
  241. expect(mocks.subscribeConversationV4.mock.calls.length).toBeLessThanOrEqual(
  242. 1 + RUNTIME_RECYCLE_RETRY_ATTEMPTS,
  243. );
  244. } finally {
  245. vi.useRealTimers();
  246. }
  247. });
  248. it("runtime 反复回收(连续 unavailable)耗尽退避后落 error,不静默停在 connecting", async () => {
  249. vi.useFakeTimers();
  250. try {
  251. const { base, runtimeLifecycle } = setupBase({ withLifecycle: true });
  252. const { store } = createStore(base, "conn-flapping");
  253. await store.connect();
  254. expect(store.getState().status).toBe("live");
  255. // Helper 反复崩溃/liveness 反复判死时,unavailable 会连续到达而中间没有 available,
  256. // 每一次都消耗一格退避额度。额度用尽的那次若只清状态不落 error,面板永久转圈。
  257. for (let i = 0; i < RUNTIME_RECYCLE_RETRY_ATTEMPTS + 1; i += 1) {
  258. runtimeLifecycle.fire(lifecycleEvent("unavailable", i + 2));
  259. await vi.advanceTimersByTimeAsync(0);
  260. }
  261. expect(store.getState().status).toBe("error");
  262. expect(store.getState().lastError).not.toBeNull();
  263. } finally {
  264. vi.useRealTimers();
  265. }
  266. });
  267. // CR-01 回归:远程 workspace 的 proxy 换代只走 onRuntimeRestart("transportReplaced"),
  268. // ReplaceableConversationTransport.replace() 不发任何 lifecycle 事件。若 store 在
  269. // lifecycle 模式下完全放弃 restart 通道,这条通知无人接收——replace() 已 best-effort
  270. // 退订旧 proxy 上的订阅,store 却停在 live + 旧 subscriptionId,帧流静默中断且不自愈。
  271. it("lifecycle 模式下仍接收 proxy 换代(transportReplaced),携原水位重订阅", async () => {
  272. const { base, mocks } = setupBase({ withLifecycle: true });
  273. const scope = createZCodeAgentConnectionScope(base, {
  274. connectionId: "conn-proxy-1",
  275. clientMode: "desktop-continuous",
  276. });
  277. const replaceable = new ReplaceableConversationTransport(
  278. createAgentConversationTransport(scope.service, { workspacePath: WORKSPACE_PATH }),
  279. );
  280. // 远程 registry 的真实形态:底层支持 lifecycle,故 Replaceable 也暴露它。
  281. expect(replaceable.onRuntimeLifecycle).toBeTypeOf("function");
  282. const store = new ConversationProjectionStore(TOPIC, replaceable);
  283. await store.connect();
  284. expect(store.getState().status).toBe("live");
  285. expect(mocks.subscribeConversationV4).toHaveBeenCalledTimes(1);
  286. // activateRemoteService() → replace():新 proxy 接管,旧订阅已被退订。
  287. const nextScope = createZCodeAgentConnectionScope(base, {
  288. connectionId: "conn-proxy-2",
  289. clientMode: "desktop-continuous",
  290. });
  291. replaceable.replace(
  292. createAgentConversationTransport(nextScope.service, { workspacePath: WORKSPACE_PATH }),
  293. );
  294. await new Promise<void>((resolve) => setTimeout(resolve, 0));
  295. expect(mocks.subscribeConversationV4).toHaveBeenCalledTimes(2);
  296. expect(store.getState().status).toBe("live");
  297. });
  298. // CR-01 的对偶约束:加回 restart 通道后不能让同一次 runtime 换代被两条通道各处理一次
  299. // (会白建订阅、重复拉起 runtime)。判据是 reason——直连 transport 转发时传 "runtimeRestart",
  300. // Replaceable 转发底层时传 undefined,两者都必须被过滤掉,只有 "transportReplaced" 放行。
  301. it("runtime 换代同时到达两条通道时只重订阅一次", async () => {
  302. const { base, mocks, runtimeLifecycle, runtimeRestarts } = setupBase({ withLifecycle: true });
  303. const { store } = createStore(base, "conn-no-double");
  304. await store.connect();
  305. expect(mocks.subscribeConversationV4).toHaveBeenCalledTimes(1);
  306. // 真实的 runtime 换代:available 与 onAgentRuntimeRestarted 同刻到达。
  307. runtimeRestarts.fire({ workspaceKey: WORKSPACE_PATH });
  308. runtimeLifecycle.fire(lifecycleEvent("available", 2));
  309. await new Promise<void>((resolve) => setTimeout(resolve, 0));
  310. expect(mocks.subscribeConversationV4).toHaveBeenCalledTimes(2);
  311. expect(store.getState().status).toBe("live");
  312. });
  313. it("在途 subscribe 被 workspace-dispose 打断后有界退避重连,不定格 error", async () => {
  314. vi.useFakeTimers();
  315. try {
  316. const { base, mocks, pendingFailures } = setupBase();
  317. pendingFailures.push(new Error(TRANSPORT_CLOSED));
  318. const { store } = createStore(base, "conn-retry");
  319. await store.connect();
  320. // 修复前:这里已是 status="error" + lastError="ZCode agent transport closed",
  321. // 且没有任何 timer——面板从此只能靠用户点「重新连接」。
  322. expect(store.getState().status).not.toBe("error");
  323. expect(mocks.subscribeConversationV4).toHaveBeenCalledTimes(1);
  324. // 退避窗口内自动重订阅并恢复 live。
  325. await vi.advanceTimersByTimeAsync(1_000);
  326. expect(mocks.subscribeConversationV4).toHaveBeenCalledTimes(2);
  327. expect(store.getState().status).toBe("live");
  328. expect(store.getState().lastError).toBeNull();
  329. } finally {
  330. vi.useRealTimers();
  331. }
  332. });
  333. });