workspaceConnectionRegistry.test.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. // 分屏二期:conversation 连接注册表单测(引用计数 / keep-warm / agentService 换代)。
  2. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  3. import { Emitter } from "@zcode/rpc";
  4. import type { IServiceAccessor } from "@zcode/services";
  5. import type {
  6. ConversationRow,
  7. ConversationSnapshot,
  8. ConversationTopicFrame,
  9. ConversationTopicWireFrame,
  10. } from "@zcode/shared/zcode-protocol-v4";
  11. import {
  12. WORKSPACE_CONNECTION_KEEP_WARM_MS,
  13. acquireWorkspaceConnection,
  14. buildWorkspaceConnectionKey,
  15. workspaceConnectionRegistrySize,
  16. type WorkspaceConnectionAgentService,
  17. } from "@/v4/workspaceConnectionRegistry.js";
  18. import { createCommandEnvelope } from "@/v4/commandFactory.js";
  19. import {
  20. registerRemoteWorkspaceSession,
  21. unregisterRemoteWorkspaceSession,
  22. } from "@/store/remoteWorkspaceSessionStore.js";
  23. function mockAgentService(): WorkspaceConnectionAgentService {
  24. const runtimeRestarts = new Emitter<{ workspaceKey: string }>();
  25. return {
  26. helloConversationV4: vi.fn(async () => ({
  27. kind: "hello" as const,
  28. protocolVersion: 3 as const,
  29. connectionId: "test-connection",
  30. clientMode: "desktop-continuous" as const,
  31. deliveryProfile: "continuous" as const,
  32. serverTime: 1,
  33. capabilities: {
  34. nativeDialogs: true,
  35. localTerminal: true,
  36. binaryFrames: false,
  37. compression: "none" as const,
  38. },
  39. auth: {},
  40. })),
  41. initializeConversationV4: vi.fn(async () => {}),
  42. subscribeConversationV4: vi.fn(async () => ({
  43. ack: {
  44. subscriptionId: "sub-1",
  45. mode: "snapshot" as const,
  46. logEpoch: "e1",
  47. },
  48. })),
  49. resyncConversationV4: vi.fn(async (params) => ({
  50. ack: {
  51. subscriptionId: params.subscriptionId,
  52. mode: "snapshot" as const,
  53. logEpoch: "e1",
  54. },
  55. })),
  56. unsubscribeConversationV4: vi.fn(async () => {}),
  57. sendConversationCommandV4: vi.fn(async () => ({}) as never),
  58. conversationRowsRangeV4: vi.fn(async () => ({}) as never),
  59. conversationPlansV4: vi.fn(async () => ({}) as never),
  60. attachmentBeginV4: vi.fn(async () => ({}) as never),
  61. attachmentChunkV4: vi.fn(async () => ({}) as never),
  62. attachmentCommitV4: vi.fn(async () => ({}) as never),
  63. attachmentAbortV4: vi.fn(async () => {}),
  64. attachmentReadV4: vi.fn(async () => ({}) as never),
  65. onDynamicConversationFrame: vi.fn(() => () => ({ dispose: () => {} })),
  66. onAgentRuntimeRestarted: runtimeRestarts.event,
  67. } as unknown as WorkspaceConnectionAgentService;
  68. }
  69. function makeSnapshot(sessionId: string, text: string): ConversationSnapshot {
  70. const row: ConversationRow = {
  71. rowId: 1,
  72. turnId: "turn-1",
  73. createdAt: 1,
  74. createdAtSeq: 1,
  75. kind: "assistantText",
  76. text,
  77. state: "complete",
  78. };
  79. return {
  80. protocolVersion: 1,
  81. sessionId,
  82. logEpoch: "epoch-1",
  83. seq: 1,
  84. revision: 1,
  85. control: {
  86. phase: "draft",
  87. sessionEnded: false,
  88. canStop: false,
  89. stopState: "idle",
  90. stopTargetKind: "unknown",
  91. activeWorks: [],
  92. lastError: null,
  93. apiRetry: null,
  94. },
  95. availability: {
  96. fork: { allowed: true },
  97. compact: { allowed: false, reasonCode: "idleCannotCompact" },
  98. switchModelConfig: { allowed: true },
  99. setFollowupMode: { allowed: true },
  100. queueEdit: { allowed: true },
  101. sendQueuedNow: { allowed: false, reasonCode: "sendQueuedNowRequiresRunning" },
  102. pauseGoal: { allowed: false, reasonCode: "noGoalToPause" },
  103. resumeGoal: { allowed: false, reasonCode: "noGoalToResume" },
  104. },
  105. inputRouting: { mode: "startNow" },
  106. config: { provider: "", model: "", thought: "", followupMode: "queue" },
  107. modelTransition: null,
  108. usage: {
  109. contextWindow: null,
  110. cumulative: {
  111. inputTokens: 0,
  112. outputTokens: 0,
  113. cacheReadTokens: 0,
  114. cacheWriteTokens: 0,
  115. },
  116. },
  117. queue: { items: [], autoDrain: true },
  118. pendingInteractions: [],
  119. pendingCommands: [],
  120. backgroundWorks: [],
  121. goal: null,
  122. plan: null,
  123. rows: { window: [row], totalCount: 1, firstRowId: 1 },
  124. };
  125. }
  126. function createReplacingRemoteServices(clientMode: "desktop-continuous" | "web-remote-replayable") {
  127. let nextSubscription = 1;
  128. let nextLogicalFrame = 1;
  129. const createService = (
  130. serviceKey: string,
  131. snapshotText: string,
  132. ): WorkspaceConnectionAgentService => {
  133. const runtimeRestarts = new Emitter<{ workspaceKey: string }>();
  134. const frames = new Emitter<ConversationTopicWireFrame>();
  135. return {
  136. helloConversationV4: vi.fn(async () => ({
  137. kind: "hello" as const,
  138. protocolVersion: 3 as const,
  139. connectionId: "shared-remote-connection",
  140. clientMode,
  141. deliveryProfile:
  142. clientMode === "desktop-continuous" ? ("continuous" as const) : ("replayable" as const),
  143. serverTime: 1,
  144. capabilities: {
  145. nativeDialogs: true,
  146. localTerminal: true,
  147. binaryFrames: false,
  148. compression: "none" as const,
  149. },
  150. auth: {},
  151. })),
  152. initializeConversationV4: vi.fn(async () => {}),
  153. subscribeConversationV4: vi.fn(async (params) => {
  154. const subscriptionId = `${serviceKey}-sub-${nextSubscription++}`;
  155. const frame: ConversationTopicFrame = {
  156. topic: `conversation/${params.sessionId}`,
  157. subscriptionId,
  158. fromSeq: 0,
  159. toSeq: 1,
  160. sentAt: 1,
  161. payload: {
  162. kind: "snapshot",
  163. snapshot: makeSnapshot(params.sessionId, snapshotText),
  164. },
  165. };
  166. frames.fire({
  167. wireVersion: 3,
  168. kind: "complete",
  169. deliveryKind: "initial",
  170. logicalFrameId: `logical-${nextLogicalFrame}`,
  171. logicalFrameOrdinal: nextLogicalFrame++,
  172. topic: frame.topic,
  173. subscriptionId,
  174. frame,
  175. });
  176. return {
  177. ack: {
  178. subscriptionId,
  179. mode: "snapshot" as const,
  180. logEpoch: "epoch-1",
  181. },
  182. };
  183. }),
  184. resyncConversationV4: vi.fn(async (params) => ({
  185. ack: {
  186. subscriptionId: params.subscriptionId,
  187. mode: "snapshot" as const,
  188. logEpoch: "epoch-1",
  189. },
  190. })),
  191. unsubscribeConversationV4: vi.fn(async () => {}),
  192. sendConversationCommandV4: vi.fn(async (params) => ({
  193. commandId: params.envelope.commandId,
  194. status: "accepted" as const,
  195. revisionAtDecision: 1,
  196. })),
  197. queryConversationCommandsV4: vi.fn(async () => ({ results: [] })),
  198. conversationRowsRangeV4: vi.fn(async () => ({
  199. rows: [],
  200. atSeq: 1,
  201. atLogEpoch: "epoch-1",
  202. hasMore: false,
  203. })),
  204. conversationPlansV4: vi.fn(async () => ({
  205. plans: [],
  206. atSeq: 1,
  207. atLogEpoch: "epoch-1",
  208. })),
  209. conversationFileChangesV4: vi.fn(async () => ({}) as never),
  210. conversationFileRewindPreviewV4: vi.fn(async () => ({}) as never),
  211. attachmentBeginV4: vi.fn(async () => ({}) as never),
  212. attachmentChunkV4: vi.fn(async () => ({}) as never),
  213. attachmentCommitV4: vi.fn(async () => ({}) as never),
  214. attachmentAbortV4: vi.fn(async () => {}),
  215. attachmentReadV4: vi.fn(async () => ({}) as never),
  216. onDynamicConversationFrame: vi.fn(() => frames.event),
  217. onAgentRuntimeRestarted: runtimeRestarts.event,
  218. } as unknown as WorkspaceConnectionAgentService;
  219. };
  220. return {
  221. oldService: createService("old", "old snapshot"),
  222. newService: createService("new", "new snapshot"),
  223. };
  224. }
  225. describe("workspaceConnectionRegistry", () => {
  226. beforeEach(() => {
  227. vi.useFakeTimers();
  228. });
  229. afterEach(() => {
  230. // 清场:跑掉所有 keep-warm 定时器,避免条目跨用例泄漏。
  231. vi.runAllTimers();
  232. vi.useRealTimers();
  233. });
  234. it("key = endpoint + workspaceKey(identity 优先,endpoint 缺省 __base__)", () => {
  235. expect(buildWorkspaceConnectionKey({ workspacePath: "/a" })).toBe("__base__ /a");
  236. expect(
  237. buildWorkspaceConnectionKey({
  238. workspacePath: "/mnt/b",
  239. workspaceIdentity: "ssh://host/mnt/b",
  240. remoteSessionId: "remote-1",
  241. }),
  242. ).toBe("remote-1 ssh://host/mnt/b");
  243. });
  244. it("引用计数:同 scope 复用同一 layer/transport(帧监听只挂一次)", () => {
  245. const service = mockAgentService();
  246. const scope = { workspacePath: "/ws/a" };
  247. const a = acquireWorkspaceConnection(scope, service);
  248. const b = acquireWorkspaceConnection(scope, service);
  249. expect(a.layer).toBe(b.layer);
  250. expect(a.transport).toBe(b.transport);
  251. expect(workspaceConnectionRegistrySize()).toBe(1);
  252. expect(service.onDynamicConversationFrame).toHaveBeenCalledTimes(1);
  253. a.release();
  254. b.release();
  255. vi.runAllTimers();
  256. expect(workspaceConnectionRegistrySize()).toBe(0);
  257. });
  258. it("keep-warm:归零后窗口期内 re-acquire 复活同一条目,窗口期满才移除", () => {
  259. const service = mockAgentService();
  260. const scope = { workspacePath: "/ws/a" };
  261. const a = acquireWorkspaceConnection(scope, service);
  262. const layer = a.layer;
  263. a.release();
  264. // 归零但仍在 keep-warm:条目保留
  265. expect(workspaceConnectionRegistrySize()).toBe(1);
  266. vi.advanceTimersByTime(WORKSPACE_CONNECTION_KEEP_WARM_MS - 1);
  267. const b = acquireWorkspaceConnection(scope, service);
  268. expect(b.layer).toBe(layer);
  269. // 复活后定时器取消:窗口期满不移除
  270. vi.advanceTimersByTime(WORKSPACE_CONNECTION_KEEP_WARM_MS * 2);
  271. expect(workspaceConnectionRegistrySize()).toBe(1);
  272. b.release();
  273. vi.advanceTimersByTime(WORKSPACE_CONNECTION_KEEP_WARM_MS);
  274. expect(workspaceConnectionRegistrySize()).toBe(0);
  275. });
  276. it("release 幂等:重复 release 不重复减计数", () => {
  277. const service = mockAgentService();
  278. const scope = { workspacePath: "/ws/a" };
  279. const a = acquireWorkspaceConnection(scope, service);
  280. const b = acquireWorkspaceConnection(scope, service);
  281. a.release();
  282. a.release();
  283. a.release();
  284. // b 仍持有 → 条目在场且无 keep-warm 移除
  285. vi.runAllTimers();
  286. expect(workspaceConnectionRegistrySize()).toBe(1);
  287. b.release();
  288. vi.runAllTimers();
  289. expect(workspaceConnectionRegistrySize()).toBe(0);
  290. });
  291. it("不同 endpoint / 不同 workspaceKey 各自独立条目", () => {
  292. const local = mockAgentService();
  293. const remote = mockAgentService();
  294. const a = acquireWorkspaceConnection({ workspacePath: "/ws" }, local);
  295. const b = acquireWorkspaceConnection(
  296. {
  297. workspacePath: "/ws",
  298. workspaceIdentity: "ssh://host/ws",
  299. remoteSessionId: "remote-1",
  300. },
  301. remote,
  302. );
  303. expect(a.layer).not.toBe(b.layer);
  304. expect(workspaceConnectionRegistrySize()).toBe(2);
  305. a.release();
  306. b.release();
  307. vi.runAllTimers();
  308. expect(workspaceConnectionRegistrySize()).toBe(0);
  309. });
  310. it("远程 agentService 换代:新旧消费者复用同一 layer/transport", () => {
  311. const oldService = mockAgentService();
  312. const newService = mockAgentService();
  313. const scope = {
  314. workspacePath: "/ws",
  315. workspaceIdentity: "ssh://host/ws",
  316. remoteSessionId: "remote-1",
  317. };
  318. const oldLease = acquireWorkspaceConnection(scope, oldService);
  319. const newLease = acquireWorkspaceConnection(scope, newService);
  320. try {
  321. expect(newLease.layer).toBe(oldLease.layer);
  322. expect(newLease.transport).toBe(oldLease.transport);
  323. expect(workspaceConnectionRegistrySize()).toBe(1);
  324. // 新 consumer 先 cleanup 后,旧 consumer 仍持有同一有效数据层。
  325. newLease.release();
  326. const sessionLease = oldLease.layer.acquire("sess-x");
  327. sessionLease.release();
  328. oldLease.release();
  329. vi.runAllTimers();
  330. expect(workspaceConnectionRegistrySize()).toBe(0);
  331. } finally {
  332. newLease.release();
  333. oldLease.release();
  334. vi.runAllTimers();
  335. }
  336. });
  337. it("远程 agentService 换代:所有存量 lease 的命令都发送到最新 service", async () => {
  338. const oldService = mockAgentService();
  339. const newService = mockAgentService();
  340. const scope = {
  341. workspacePath: "/ws",
  342. workspaceIdentity: "ssh://host/ws",
  343. remoteSessionId: "remote-1",
  344. };
  345. const oldLease = acquireWorkspaceConnection(scope, oldService);
  346. const newLease = acquireWorkspaceConnection(scope, newService);
  347. try {
  348. newLease.activateRemoteService();
  349. const envelope = createCommandEnvelope({
  350. type: "sendText",
  351. sessionId: "sess-x",
  352. payload: { text: "hello" },
  353. });
  354. await oldLease.transport.sendCommand(envelope);
  355. expect(oldService.sendConversationCommandV4).not.toHaveBeenCalled();
  356. expect(newService.sendConversationCommandV4).toHaveBeenCalledWith({
  357. workspacePath: "/ws",
  358. workspaceIdentity: "ssh://host/ws",
  359. envelope,
  360. });
  361. expect(newLease.transport).toBe(oldLease.transport);
  362. } finally {
  363. newLease.release();
  364. oldLease.release();
  365. vi.runAllTimers();
  366. }
  367. });
  368. it("远程 agentService 换代:acquire 只登记候选,commit 阶段激活后才切换 service", async () => {
  369. const oldService = mockAgentService();
  370. const newService = mockAgentService();
  371. const scope = {
  372. workspacePath: "/ws",
  373. workspaceIdentity: "ssh://host/ws",
  374. remoteSessionId: "remote-1",
  375. };
  376. const oldLease = acquireWorkspaceConnection(scope, oldService);
  377. const newLease = acquireWorkspaceConnection(scope, newService);
  378. try {
  379. const beforeCommit = createCommandEnvelope({
  380. type: "sendText",
  381. sessionId: "sess-x",
  382. payload: { text: "before commit" },
  383. });
  384. await oldLease.transport.sendCommand(beforeCommit);
  385. expect(oldService.sendConversationCommandV4).toHaveBeenCalledWith({
  386. workspacePath: "/ws",
  387. workspaceIdentity: "ssh://host/ws",
  388. envelope: beforeCommit,
  389. });
  390. expect(newService.sendConversationCommandV4).not.toHaveBeenCalled();
  391. newLease.activateRemoteService();
  392. const afterCommit = createCommandEnvelope({
  393. type: "sendText",
  394. sessionId: "sess-x",
  395. payload: { text: "after commit" },
  396. });
  397. await oldLease.transport.sendCommand(afterCommit);
  398. expect(newService.sendConversationCommandV4).toHaveBeenCalledWith({
  399. workspacePath: "/ws",
  400. workspaceIdentity: "ssh://host/ws",
  401. envelope: afterCommit,
  402. });
  403. } finally {
  404. newLease.release();
  405. oldLease.release();
  406. vi.runAllTimers();
  407. }
  408. });
  409. it.each(["desktop-continuous", "web-remote-replayable"] as const)(
  410. "远程 agentService 换代:存量 store 携当前水位从新 proxy 恢复(%s)",
  411. async (clientMode) => {
  412. const scope = {
  413. workspacePath: "/ws",
  414. workspaceIdentity: "ssh://host/ws",
  415. remoteSessionId: "remote-1",
  416. };
  417. const { oldService, newService } = createReplacingRemoteServices(clientMode);
  418. const oldLease = acquireWorkspaceConnection(scope, oldService);
  419. const sessionLease = oldLease.layer.acquire("sess-x");
  420. let newLease: ReturnType<typeof acquireWorkspaceConnection> | null = null;
  421. try {
  422. await vi.waitFor(() =>
  423. expect(sessionLease.store.getState().snapshot?.rows.window[0]).toMatchObject({
  424. kind: "assistantText",
  425. text: "old snapshot",
  426. }),
  427. );
  428. newLease = acquireWorkspaceConnection(scope, newService);
  429. newLease.activateRemoteService();
  430. expect(newLease.layer).toBe(oldLease.layer);
  431. expect(newLease.transport).toBe(oldLease.transport);
  432. await vi.waitFor(() =>
  433. expect(sessionLease.store.getState().snapshot?.rows.window[0]).toMatchObject({
  434. kind: "assistantText",
  435. text: "new snapshot",
  436. }),
  437. );
  438. expect(sessionLease.store.getState()).toMatchObject({
  439. status: "live",
  440. lastError: null,
  441. });
  442. expect(oldService.unsubscribeConversationV4).toHaveBeenCalledTimes(1);
  443. expect(newService.subscribeConversationV4).toHaveBeenCalledTimes(1);
  444. expect(newService.subscribeConversationV4).toHaveBeenCalledWith({
  445. workspacePath: "/ws",
  446. workspaceIdentity: "ssh://host/ws",
  447. sessionId: "sess-x",
  448. base: { logEpoch: "epoch-1", seq: 1 },
  449. });
  450. } finally {
  451. sessionLease.release();
  452. newLease?.release();
  453. oldLease.release();
  454. vi.runAllTimers();
  455. }
  456. },
  457. );
  458. it("远程 service 连续换代时,迟到旧 consumer 不能把 transport 切回去", async () => {
  459. const firstService = mockAgentService();
  460. const staleMiddleService = mockAgentService();
  461. const latestService = mockAgentService();
  462. const scope = {
  463. workspacePath: "/ws",
  464. workspaceIdentity: "ssh://host/ws",
  465. remoteSessionId: "remote-1",
  466. };
  467. const register = (agentService: WorkspaceConnectionAgentService) =>
  468. registerRemoteWorkspaceSession({
  469. sessionId: scope.remoteSessionId,
  470. services: { zcodeAgentService: agentService } as unknown as IServiceAccessor,
  471. });
  472. register(firstService);
  473. register(staleMiddleService);
  474. register(latestService);
  475. const firstLease = acquireWorkspaceConnection(scope, firstService);
  476. const latestLease = acquireWorkspaceConnection(scope, latestService);
  477. const staleLease = acquireWorkspaceConnection(scope, staleMiddleService);
  478. try {
  479. latestLease.activateRemoteService();
  480. staleLease.activateRemoteService();
  481. const envelope = createCommandEnvelope({
  482. type: "sendText",
  483. sessionId: "sess-x",
  484. payload: { text: "latest" },
  485. });
  486. await staleLease.transport.sendCommand(envelope);
  487. expect(staleMiddleService.sendConversationCommandV4).not.toHaveBeenCalled();
  488. expect(latestService.sendConversationCommandV4).toHaveBeenCalledTimes(1);
  489. expect(staleLease.layer).toBe(firstLease.layer);
  490. expect(latestLease.layer).toBe(firstLease.layer);
  491. } finally {
  492. staleLease.release();
  493. latestLease.release();
  494. firstLease.release();
  495. vi.runAllTimers();
  496. unregisterRemoteWorkspaceSession(scope.remoteSessionId);
  497. }
  498. });
  499. it("远程旧订阅一直未完成时,新 service 仍可立即接管 conversation store", async () => {
  500. const oldService = mockAgentService();
  501. const newService = mockAgentService();
  502. const scope = {
  503. workspacePath: "/ws",
  504. workspaceIdentity: "ssh://host/ws",
  505. remoteSessionId: "remote-1",
  506. };
  507. vi.mocked(oldService.subscribeConversationV4).mockImplementation(() => new Promise(() => {}));
  508. const oldLease = acquireWorkspaceConnection(scope, oldService);
  509. const sessionLease = oldLease.layer.acquire("sess-x");
  510. const newLease = acquireWorkspaceConnection(scope, newService);
  511. try {
  512. newLease.activateRemoteService();
  513. expect(newLease.layer).toBe(oldLease.layer);
  514. await vi.waitFor(() => expect(newService.subscribeConversationV4).toHaveBeenCalledTimes(1));
  515. expect(sessionLease.store.getState().status).toBe("live");
  516. } finally {
  517. sessionLease.release();
  518. newLease.release();
  519. oldLease.release();
  520. vi.runAllTimers();
  521. }
  522. });
  523. it("远程旧退订一直未完成时,新 service 的 snapshot 恢复不被阻塞", async () => {
  524. const scope = {
  525. workspacePath: "/ws",
  526. workspaceIdentity: "ssh://host/ws",
  527. remoteSessionId: "remote-1",
  528. };
  529. const { oldService, newService } = createReplacingRemoteServices("desktop-continuous");
  530. vi.mocked(oldService.unsubscribeConversationV4).mockImplementation(() => new Promise(() => {}));
  531. const oldLease = acquireWorkspaceConnection(scope, oldService);
  532. const sessionLease = oldLease.layer.acquire("sess-x");
  533. let newLease: ReturnType<typeof acquireWorkspaceConnection> | null = null;
  534. try {
  535. await vi.waitFor(() =>
  536. expect(sessionLease.store.getState().snapshot?.rows.window[0]).toMatchObject({
  537. text: "old snapshot",
  538. }),
  539. );
  540. newLease = acquireWorkspaceConnection(scope, newService);
  541. newLease.activateRemoteService();
  542. await vi.waitFor(() =>
  543. expect(sessionLease.store.getState().snapshot?.rows.window[0]).toMatchObject({
  544. text: "new snapshot",
  545. }),
  546. );
  547. } finally {
  548. sessionLease.release();
  549. newLease?.release();
  550. oldLease.release();
  551. vi.runAllTimers();
  552. }
  553. });
  554. it("agentService 换代:旧条目无人持有(keep-warm 中)→ 立即清场", () => {
  555. const oldService = mockAgentService();
  556. const newService = mockAgentService();
  557. const scope = { workspacePath: "/ws/a" };
  558. const oldLease = acquireWorkspaceConnection(scope, oldService);
  559. const oldLayer = oldLease.layer;
  560. oldLease.release();
  561. // keep-warm 中换代
  562. const newLease = acquireWorkspaceConnection(scope, newService);
  563. expect(() => oldLayer.acquire("sess-x")).toThrow();
  564. expect(workspaceConnectionRegistrySize()).toBe(1);
  565. newLease.release();
  566. vi.runAllTimers();
  567. expect(workspaceConnectionRegistrySize()).toBe(0);
  568. });
  569. });