useAppPanelsBrowserViewLifecycle.test.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. // @vitest-environment jsdom
  2. import { act, renderHook } from "@testing-library/react";
  3. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  4. import type { IPlatformService } from "@zcode/shared";
  5. import { useAppPanels } from "@/hooks/useAppPanels.js";
  6. import {
  7. buildTaskSidePaneMemoryKey,
  8. clearTaskSidePaneMemoryStateForTest,
  9. getSidePaneCollapsedPreference,
  10. readTaskSidePaneMemoryState,
  11. } from "@/lib/taskSidePaneMemory.js";
  12. const { closeSessionMock } = vi.hoisted(() => ({
  13. closeSessionMock: vi.fn(async () => {}),
  14. }));
  15. vi.mock("@/hooks/useServices.js", () => ({
  16. useServices: () => ({
  17. zcodeSessionService: { closeSession: closeSessionMock },
  18. }),
  19. }));
  20. vi.mock("@/logger.js", () => ({
  21. logger: {
  22. debug: vi.fn(),
  23. error: vi.fn(),
  24. info: vi.fn(),
  25. warn: vi.fn(),
  26. },
  27. }));
  28. type ReadyHandler = Parameters<NonNullable<IPlatformService["onBrowserViewReady"]>>[0];
  29. type ReadyPayload = Parameters<ReadyHandler>[0];
  30. type VisibilityHandler = Parameters<NonNullable<IPlatformService["onBrowserViewVisibility"]>>[0];
  31. type VisibilityPayload = Parameters<VisibilityHandler>[0];
  32. type CloseHandler = Parameters<NonNullable<IPlatformService["onBrowserViewCloseTab"]>>[0];
  33. type OperationHandler = Parameters<NonNullable<IPlatformService["onBrowserViewOperation"]>>[0];
  34. type OpenBrowserUrlHandler = Parameters<NonNullable<IPlatformService["onOpenBrowserUrl"]>>[0];
  35. function createBrowserViewPlatformHarness() {
  36. let readyHandler: ReadyHandler | null = null;
  37. let visibilityHandler: VisibilityHandler | null = null;
  38. let closeHandler: CloseHandler | null = null;
  39. let operationHandler: OperationHandler | null = null;
  40. let openBrowserUrlHandler: OpenBrowserUrlHandler | null = null;
  41. const platform = {
  42. browserViewCloseTab: vi.fn(async () => {}),
  43. onBrowserViewCloseTab: vi.fn((handler: CloseHandler) => {
  44. closeHandler = handler;
  45. return () => {
  46. if (closeHandler === handler) closeHandler = null;
  47. };
  48. }),
  49. onOpenBrowserUrl: vi.fn((handler: OpenBrowserUrlHandler) => {
  50. openBrowserUrlHandler = handler;
  51. return () => {
  52. if (openBrowserUrlHandler === handler) openBrowserUrlHandler = null;
  53. };
  54. }),
  55. onBrowserViewReady: vi.fn((handler: ReadyHandler) => {
  56. readyHandler = handler;
  57. return () => {
  58. if (readyHandler === handler) readyHandler = null;
  59. };
  60. }),
  61. onBrowserViewOperation: vi.fn((handler: OperationHandler) => {
  62. operationHandler = handler;
  63. return () => {
  64. if (operationHandler === handler) operationHandler = null;
  65. };
  66. }),
  67. onBrowserViewVisibility: vi.fn((handler: VisibilityHandler) => {
  68. visibilityHandler = handler;
  69. return () => {
  70. if (visibilityHandler === handler) visibilityHandler = null;
  71. };
  72. }),
  73. } as NonNullable<Parameters<typeof useAppPanels>[0]["platform"]>;
  74. return {
  75. emitClose(payload: Parameters<CloseHandler>[0]) {
  76. if (!closeHandler) throw new Error("close handler 尚未注册");
  77. closeHandler(payload);
  78. },
  79. emitOperation(payload: Parameters<OperationHandler>[0]) {
  80. if (!operationHandler) throw new Error("operation handler 尚未注册");
  81. operationHandler(payload);
  82. },
  83. emitOpenBrowserUrl(payload: Parameters<OpenBrowserUrlHandler>[0]) {
  84. if (!openBrowserUrlHandler) throw new Error("open browser url handler 尚未注册");
  85. openBrowserUrlHandler(payload);
  86. },
  87. emitReady(payload: ReadyPayload) {
  88. if (!readyHandler) throw new Error("ready handler 尚未注册");
  89. readyHandler(payload);
  90. },
  91. emitVisibility(payload: VisibilityPayload) {
  92. if (!visibilityHandler) throw new Error("visibility handler 尚未注册");
  93. visibilityHandler(payload);
  94. },
  95. platform,
  96. };
  97. }
  98. function readyPayload(tabId: string, overrides: Partial<ReadyPayload> = {}): ReadyPayload {
  99. return {
  100. workspaceKey: "ssh://host/repo",
  101. remoteSessionId: "remote-a",
  102. sessionId: "sess-a",
  103. tabId,
  104. browserId: "iab-a",
  105. browserGeneration: 2,
  106. ...overrides,
  107. };
  108. }
  109. function renderBrowserViewLifecycleHook() {
  110. const harness = createBrowserViewPlatformHarness();
  111. const rendered = renderHook(() =>
  112. useAppPanels({
  113. workspaceAbsPath: "/repo",
  114. workspaceIdentity: "ssh://host/repo",
  115. workspaceRemoteSessionId: "remote-a",
  116. activeTaskId: "sess-a",
  117. sidePaneOwnerId: "sess-a",
  118. isDesktop: true,
  119. isWorkspaceVisible: true,
  120. supportsEmbeddedBrowser: true,
  121. defaultWhiteboardNamePrefix: "Whiteboard",
  122. platform: harness.platform,
  123. }),
  124. );
  125. return { ...harness, ...rendered };
  126. }
  127. const WORKSPACE_KEY = "ssh://host/repo";
  128. const OTHER_WORKSPACE_KEY = "ssh://host/other";
  129. /**
  130. * 设置页是覆盖层,App 不卸载但 isWorkspaceVisible 会变 false。
  131. * 这个 helper 让用例能在渲染后切换该标志,覆盖“订阅是否被可见性误关”的场景。
  132. */
  133. function renderSettingsOverlayHook(initialIsWorkspaceVisible: boolean) {
  134. const harness = createBrowserViewPlatformHarness();
  135. const rendered = renderHook(
  136. ({ isWorkspaceVisible }: { isWorkspaceVisible: boolean }) =>
  137. useAppPanels({
  138. workspaceAbsPath: "/repo",
  139. workspaceIdentity: WORKSPACE_KEY,
  140. workspaceRemoteSessionId: "remote-a",
  141. activeTaskId: "sess-a",
  142. sidePaneOwnerId: "sess-a",
  143. isDesktop: true,
  144. isWorkspaceVisible,
  145. supportsEmbeddedBrowser: true,
  146. defaultWhiteboardNamePrefix: "Whiteboard",
  147. platform: harness.platform,
  148. }),
  149. { initialProps: { isWorkspaceVisible: initialIsWorkspaceVisible } },
  150. );
  151. return { ...harness, ...rendered };
  152. }
  153. /** side pane memory 按 workspace 隔离,切换 workspace 才能覆盖“通知落在非活跃 workspace”的场景。 */
  154. function renderCrossWorkspaceHook() {
  155. const harness = createBrowserViewPlatformHarness();
  156. const rendered = renderHook(
  157. ({ workspaceIdentity }: { workspaceIdentity: string }) =>
  158. useAppPanels({
  159. workspaceAbsPath: "/repo",
  160. workspaceIdentity,
  161. workspaceRemoteSessionId: "remote-a",
  162. activeTaskId: "sess-a",
  163. sidePaneOwnerId: "sess-a",
  164. isDesktop: true,
  165. isWorkspaceVisible: true,
  166. supportsEmbeddedBrowser: true,
  167. defaultWhiteboardNamePrefix: "Whiteboard",
  168. platform: harness.platform,
  169. }),
  170. { initialProps: { workspaceIdentity: WORKSPACE_KEY } },
  171. );
  172. return { ...harness, ...rendered };
  173. }
  174. describe("useAppPanels BrowserView lifecycle", () => {
  175. beforeEach(() => {
  176. clearTaskSidePaneMemoryStateForTest();
  177. closeSessionMock.mockClear();
  178. });
  179. afterEach(() => {
  180. clearTaskSidePaneMemoryStateForTest();
  181. });
  182. it("设置页覆盖期间 Ready 仍挂载 tab 并按 scope 展开激活", () => {
  183. const { emitReady, result, unmount } = renderSettingsOverlayHook(false);
  184. act(() => {
  185. emitReady(readyPayload("tab-a"));
  186. });
  187. expect(result.current.sidePaneState).toMatchObject({
  188. activeTabId: "browser-use:tab-a",
  189. tabs: [{ id: "browser-use:tab-a", tabId: "tab-a" }],
  190. });
  191. expect(result.current.isSidePaneCollapsed).toBe(false);
  192. unmount();
  193. });
  194. it("切进设置页后 Ready 订阅不断开", () => {
  195. const { emitReady, rerender, result, unmount } = renderSettingsOverlayHook(true);
  196. act(() => {
  197. rerender({ isWorkspaceVisible: false });
  198. });
  199. act(() => {
  200. emitReady(readyPayload("tab-a"));
  201. });
  202. expect(result.current.sidePaneState).toMatchObject({
  203. tabs: [{ id: "browser-use:tab-a", tabId: "tab-a" }],
  204. });
  205. unmount();
  206. });
  207. it("设置页覆盖期间 visibility 仍能切换 active tab", () => {
  208. const { emitReady, emitVisibility, result, unmount } = renderSettingsOverlayHook(false);
  209. act(() => {
  210. emitReady(readyPayload("tab-a"));
  211. emitReady(readyPayload("tab-b"));
  212. });
  213. expect(result.current.sidePaneState?.activeTabId).toBe("browser-use:tab-b");
  214. act(() => {
  215. emitVisibility({ ...readyPayload("tab-a"), visible: true });
  216. });
  217. expect(result.current.sidePaneState?.activeTabId).toBe("browser-use:tab-a");
  218. unmount();
  219. });
  220. it("设置页覆盖期间 webview 的 target=_blank 仍能开右侧 browser tab", () => {
  221. const { emitOpenBrowserUrl, result, unmount } = renderSettingsOverlayHook(false);
  222. act(() => {
  223. emitOpenBrowserUrl({
  224. url: "https://example.com/",
  225. disposition: "foreground-tab",
  226. });
  227. });
  228. expect(result.current.sidePaneState?.tabs).toEqual([
  229. expect.objectContaining({ type: "browser" }),
  230. ]);
  231. expect(result.current.isSidePaneCollapsed).toBe(false);
  232. unmount();
  233. });
  234. it("非当前对话的 webview popup 只后台挂载,不抢当前对话焦点", () => {
  235. const { emitOpenBrowserUrl, result, unmount } = renderBrowserViewLifecycleHook();
  236. act(() => {
  237. emitOpenBrowserUrl({
  238. url: "https://example.com/from-session-b",
  239. disposition: "foreground-tab",
  240. workspaceKey: WORKSPACE_KEY,
  241. remoteSessionId: "remote-a",
  242. sessionId: "sess-b",
  243. browserId: "iab-a",
  244. browserGeneration: 2,
  245. sourceTabId: "tab-b",
  246. });
  247. });
  248. expect(result.current.sidePaneState?.activeTabId).not.toMatch(/^browser:/);
  249. expect(result.current.sidePaneState?.tabs).toEqual([
  250. expect.objectContaining({
  251. type: "browser",
  252. ownerTaskId: "sess-b",
  253. workspaceKey: WORKSPACE_KEY,
  254. initialUrl: "https://example.com/from-session-b",
  255. }),
  256. ]);
  257. expect(result.current.isSidePaneCollapsed).toBe(true);
  258. unmount();
  259. });
  260. it("同一 React batch 内按 Ready(A) → Ready(B) → visibility(B) 保留 shell 并激活 B", () => {
  261. const { emitReady, emitVisibility, result, unmount } = renderBrowserViewLifecycleHook();
  262. act(() => {
  263. emitReady(readyPayload("tab-a"));
  264. emitReady(readyPayload("tab-b"));
  265. emitVisibility({ ...readyPayload("tab-b"), visible: true });
  266. });
  267. expect(result.current.sidePaneState).toMatchObject({
  268. activeTabId: "browser-use:tab-b",
  269. tabs: [
  270. { id: "browser-use:tab-a", tabId: "tab-a" },
  271. { id: "browser-use:tab-b", tabId: "tab-b" },
  272. ],
  273. });
  274. expect(result.current.isSidePaneCollapsed).toBe(false);
  275. unmount();
  276. });
  277. it("同一 React batch 内普通 tab 打开先于 Ready 时保留两类 tab", () => {
  278. const { emitReady, result, unmount } = renderBrowserViewLifecycleHook();
  279. act(() => {
  280. result.current.handleToggleGit();
  281. emitReady(readyPayload("tab-a"));
  282. });
  283. expect(result.current.sidePaneState?.tabs.map((tab) => tab.type)).toEqual([
  284. "git",
  285. "browser-use",
  286. ]);
  287. expect(result.current.sidePaneState?.activeTabId).toBe("browser-use:tab-a");
  288. unmount();
  289. });
  290. it("同一 React batch 内普通激活先于 BrowserView operation 时不回滚 active tab", () => {
  291. const { emitOperation, emitReady, result, unmount } = renderBrowserViewLifecycleHook();
  292. act(() => emitReady(readyPayload("tab-a")));
  293. act(() => result.current.handleToggleGit());
  294. act(() => result.current.handleActivateSidePaneTab("browser-use:tab-a"));
  295. act(() => {
  296. result.current.handleActivateSidePaneTab("git");
  297. emitOperation(readyPayload("tab-a"));
  298. });
  299. expect(result.current.sidePaneState?.activeTabId).toBe("git");
  300. unmount();
  301. });
  302. it("同一 React batch 内普通排序先于 BrowserView operation 时不回滚 tab 顺序", () => {
  303. const { emitOperation, emitReady, result, unmount } = renderBrowserViewLifecycleHook();
  304. act(() => emitReady(readyPayload("tab-a")));
  305. act(() => emitReady(readyPayload("tab-b")));
  306. act(() => {
  307. result.current.handleReorderSidePaneTab("browser-use:tab-b", "browser-use:tab-a");
  308. emitOperation(readyPayload("tab-a"));
  309. });
  310. expect(result.current.sidePaneState?.tabs.map((tab) => tab.id)).toEqual([
  311. "browser-use:tab-b",
  312. "browser-use:tab-a",
  313. ]);
  314. unmount();
  315. });
  316. it("close(B) 后相邻到达的迟到 visibility(B) 不重建 shell", () => {
  317. const { emitClose, emitReady, emitVisibility, result, unmount } =
  318. renderBrowserViewLifecycleHook();
  319. act(() => emitReady(readyPayload("tab-a")));
  320. act(() => emitReady(readyPayload("tab-b")));
  321. act(() => {
  322. emitClose({ tabId: "tab-b" });
  323. emitVisibility({ ...readyPayload("tab-b"), visible: true });
  324. });
  325. expect(result.current.sidePaneState).toMatchObject({
  326. activeTabId: "browser-use:tab-a",
  327. tabs: [{ id: "browser-use:tab-a", tabId: "tab-a" }],
  328. });
  329. unmount();
  330. });
  331. it("用户关闭 B 获得 main authority 后,迟到 visibility(B) 不重建 shell", async () => {
  332. const { emitReady, emitVisibility, platform, result, unmount } =
  333. renderBrowserViewLifecycleHook();
  334. act(() => emitReady(readyPayload("tab-a")));
  335. act(() => emitReady(readyPayload("tab-b")));
  336. await act(async () => {
  337. result.current.handleCloseSidePaneTab("browser-use:tab-b");
  338. await Promise.resolve();
  339. await Promise.resolve();
  340. emitVisibility({ ...readyPayload("tab-b"), visible: true });
  341. });
  342. expect(platform.browserViewCloseTab).toHaveBeenCalledWith({
  343. tabId: "tab-b",
  344. workspaceKey: "ssh://host/repo",
  345. remoteSessionId: "remote-a",
  346. sessionId: "sess-a",
  347. });
  348. expect(result.current.sidePaneState).toMatchObject({
  349. activeTabId: "browser-use:tab-a",
  350. tabs: [{ id: "browser-use:tab-a", tabId: "tab-a" }],
  351. });
  352. unmount();
  353. });
  354. it("A 主动收起后关闭 B,仍有可见 tab 时保持收起和 owner 偏好", () => {
  355. const { emitClose, emitReady, result, unmount } = renderBrowserViewLifecycleHook();
  356. act(() => {
  357. emitReady(readyPayload("tab-a"));
  358. emitReady(readyPayload("tab-b"));
  359. });
  360. act(() => result.current.handleToggleSidePaneCollapse());
  361. expect(result.current.isSidePaneCollapsed).toBe(true);
  362. act(() => {
  363. emitClose({
  364. tabId: "tab-b",
  365. workspaceKey: WORKSPACE_KEY,
  366. remoteSessionId: "remote-a",
  367. sessionId: "sess-a",
  368. });
  369. });
  370. expect(result.current.sidePaneState?.tabs).toHaveLength(1);
  371. expect(result.current.isSidePaneCollapsed).toBe(true);
  372. const memoryKey = buildTaskSidePaneMemoryKey({
  373. workspacePath: "/repo",
  374. workspaceIdentity: WORKSPACE_KEY,
  375. taskId: "sess-a",
  376. });
  377. expect(getSidePaneCollapsedPreference(readTaskSidePaneMemoryState(memoryKey), "sess-a")).toBe(
  378. true,
  379. );
  380. unmount();
  381. });
  382. it("用户通过切换入口打开 Browser tab 时仍会展开面板", () => {
  383. const { result, unmount } = renderBrowserViewLifecycleHook();
  384. act(() => result.current.handleToggleBrowser());
  385. expect(result.current.sidePaneState?.tabs).toEqual([
  386. expect.objectContaining({ type: "browser" }),
  387. ]);
  388. expect(result.current.isSidePaneCollapsed).toBe(false);
  389. unmount();
  390. });
  391. it("用户通过切换入口打开 Git tab 时仍会展开面板", () => {
  392. const { result, unmount } = renderBrowserViewLifecycleHook();
  393. act(() => result.current.handleToggleGit());
  394. expect(result.current.sidePaneState?.tabs).toEqual([expect.objectContaining({ type: "git" })]);
  395. expect(result.current.isSidePaneCollapsed).toBe(false);
  396. unmount();
  397. });
  398. it("旧 generation 与不同 remote session 的 visibility 不改变 active tab", () => {
  399. const { emitReady, emitVisibility, result, unmount } = renderBrowserViewLifecycleHook();
  400. act(() => emitReady(readyPayload("tab-a")));
  401. act(() => emitReady(readyPayload("tab-b")));
  402. act(() => emitVisibility({ ...readyPayload("tab-a"), visible: true }));
  403. act(() => {
  404. emitVisibility({
  405. ...readyPayload("tab-b", { browserGeneration: 1 }),
  406. visible: true,
  407. });
  408. emitVisibility({
  409. ...readyPayload("tab-b", { remoteSessionId: "remote-b" }),
  410. visible: true,
  411. });
  412. });
  413. expect(result.current.sidePaneState?.activeTabId).toBe("browser-use:tab-a");
  414. expect(result.current.sidePaneState?.tabs).toHaveLength(2);
  415. unmount();
  416. });
  417. it("旧 generation 与不同 remote session 的 hide 不折叠当前 shell", () => {
  418. const { emitReady, emitVisibility, result, unmount } = renderBrowserViewLifecycleHook();
  419. act(() => emitReady(readyPayload("tab-a")));
  420. act(() => {
  421. emitVisibility({
  422. ...readyPayload("tab-a", { browserGeneration: 1 }),
  423. visible: false,
  424. });
  425. });
  426. expect(result.current.isSidePaneCollapsed).toBe(false);
  427. act(() => {
  428. emitVisibility({
  429. ...readyPayload("tab-a", { remoteSessionId: "remote-b" }),
  430. visible: false,
  431. });
  432. });
  433. expect(result.current.isSidePaneCollapsed).toBe(false);
  434. unmount();
  435. });
  436. it("Agent 在其他 workspace 活跃时关闭 tab,切回原 workspace 不残留幽灵 tab", () => {
  437. const { emitClose, emitReady, rerender, result, unmount } = renderCrossWorkspaceHook();
  438. act(() => emitReady(readyPayload("tab-a")));
  439. expect(result.current.sidePaneState?.tabs.map((tab) => tab.id)).toEqual(["browser-use:tab-a"]);
  440. // 用户切到另一个 workspace,原 workspace 的 side pane 状态被存入 memory。
  441. act(() => rerender({ workspaceIdentity: OTHER_WORKSPACE_KEY }));
  442. expect(result.current.sidePaneState?.tabs ?? []).toEqual([]);
  443. // Bug 回归:Agent 此刻关掉 tab-a,通知只带 tabId 时 renderer 只能在“当前活跃 workspace”里找,
  444. // 找不到就静默丢弃;原 workspace 的持久化 memory 仍保留这个 tab,切回来就是关不掉的幽灵 tab。
  445. act(() =>
  446. emitClose({
  447. tabId: "tab-a",
  448. workspaceKey: WORKSPACE_KEY,
  449. remoteSessionId: "remote-a",
  450. sessionId: "sess-a",
  451. }),
  452. );
  453. act(() => rerender({ workspaceIdentity: WORKSPACE_KEY }));
  454. expect(result.current.sidePaneState?.tabs ?? []).toEqual([]);
  455. unmount();
  456. });
  457. it("关闭通知带的 workspace scope 等于当前活跃 workspace 时立即从 UI 移除", () => {
  458. const { emitClose, emitReady, result, unmount } = renderCrossWorkspaceHook();
  459. act(() => emitReady(readyPayload("tab-a")));
  460. expect(result.current.sidePaneState?.tabs.map((tab) => tab.id)).toEqual(["browser-use:tab-a"]);
  461. // 修复后 main 会给每条通知都带上 owner scope,所以「没切 workspace 时 Agent 关 tab」这条
  462. // 生产最常见路径也走带 workspaceKey 的分支。它必须落回活跃分支、同步更新当前 React state,
  463. // 而不是绕进 memory 分支 —— 后者只改持久化状态,UI 上的 tab 不会消失,正是用户报的症状。
  464. // 这条用例锁的是 renderer 侧的分支选择:payload.workspaceKey 与当前活跃 workspace 相同时,
  465. // 必须判定为「当前 workspace」。注意它锁不住 main 侧 workspaceKey 的构造式 —— 这里的
  466. // WORKSPACE_KEY 是硬编码值,而 main 只是把 renderer attach 时传过去的 key 原样回声。
  467. // 字段拼装那一侧由 packages/desktop/test/browserCloseTabNotification.test.ts 守。
  468. act(() =>
  469. emitClose({
  470. tabId: "tab-a",
  471. workspaceKey: WORKSPACE_KEY,
  472. remoteSessionId: "remote-a",
  473. sessionId: "sess-a",
  474. }),
  475. );
  476. expect(result.current.sidePaneState?.tabs ?? []).toEqual([]);
  477. unmount();
  478. });
  479. it("关闭通知带的 workspace scope 不匹配时不误删其他 workspace 的同名 tab", () => {
  480. const { emitClose, emitReady, rerender, result, unmount } = renderCrossWorkspaceHook();
  481. act(() => emitReady(readyPayload("tab-a")));
  482. act(() => rerender({ workspaceIdentity: OTHER_WORKSPACE_KEY }));
  483. act(() =>
  484. emitClose({
  485. tabId: "tab-a",
  486. workspaceKey: "ssh://host/unrelated",
  487. remoteSessionId: "remote-a",
  488. sessionId: "sess-a",
  489. }),
  490. );
  491. act(() => rerender({ workspaceIdentity: WORKSPACE_KEY }));
  492. expect(result.current.sidePaneState?.tabs.map((tab) => tab.id)).toEqual(["browser-use:tab-a"]);
  493. unmount();
  494. });
  495. it("远程下打开链接创建的 human tab,关闭请求必须带上 remoteSessionId", async () => {
  496. // Bug 回归(远程内置浏览器 tab 关不掉):attach 侧用 `tab.remoteSessionId ?? workspaceRemoteSessionId`
  497. // 兜底冻结了 main 侧 owner.remoteSessionId,close 侧却只取 tab.remoteSessionId。human tab 从不写该
  498. // 字段,且 stamp 会跳过已带 ownerTaskId 的 tab,于是远程下 close payload 缺 remoteSessionId,
  499. // main 判 scope 失配抛错,renderer 拿不到授权就永不移除 UI 壳 —— tab 永远关不掉。
  500. const { emitOpenBrowserUrl, platform, result, unmount } = renderBrowserViewLifecycleHook();
  501. act(() => {
  502. emitOpenBrowserUrl({
  503. url: "https://example.com/from-link",
  504. disposition: "foreground-tab",
  505. workspaceKey: WORKSPACE_KEY,
  506. remoteSessionId: "remote-a",
  507. sessionId: "sess-a",
  508. browserId: "iab-a",
  509. browserGeneration: 2,
  510. sourceTabId: "tab-a",
  511. });
  512. });
  513. const humanTab = result.current.sidePaneState?.tabs.find((tab) => tab.type === "browser");
  514. expect(humanTab).toMatchObject({ remoteSessionId: "remote-a" });
  515. await act(async () => {
  516. result.current.handleCloseSidePaneTab(humanTab!.id);
  517. await Promise.resolve();
  518. await Promise.resolve();
  519. });
  520. expect(platform.browserViewCloseTab).toHaveBeenCalledWith({
  521. tabId: humanTab!.id,
  522. workspaceKey: WORKSPACE_KEY,
  523. remoteSessionId: "remote-a",
  524. sessionId: "sess-a",
  525. });
  526. // 授权拿到后 UI 壳必须真的移除(tab 清空后 sidePaneState 本身会归空)。
  527. expect((result.current.sidePaneState?.tabs ?? []).filter((tab) => tab.type === "browser")).toEqual(
  528. [],
  529. );
  530. unmount();
  531. });
  532. });