v4ConversationRuntimeRecycleSelfHeal.test.ts 19 KB

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