useAppPanelsBrowserViewLifecycle.test.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  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. it("展开创建新标签页,工具替换入口且最后一个标签关闭后收起", async () => {
  176. const { result } = renderBrowserViewLifecycleHook();
  177. expect(result.current.isSidePaneCollapsed).toBe(true);
  178. act(() => result.current.handleToggleSidePaneCollapse());
  179. expect(result.current.sidePaneState?.tabs).toMatchObject([
  180. { type: "new-tab", ownerTaskId: "sess-a" },
  181. ]);
  182. act(() => result.current.handleOpenBrowserTab());
  183. expect(result.current.sidePaneState?.tabs).toMatchObject([{ type: "browser" }]);
  184. const id = result.current.sidePaneState!.activeTabId;
  185. act(() => result.current.handleToggleSidePaneCollapse());
  186. act(() => result.current.handleToggleSidePaneCollapse());
  187. expect(result.current.sidePaneState!.activeTabId).toBe(id);
  188. await act(async () => result.current.handleCloseSidePaneTab(id));
  189. expect(result.current.isSidePaneCollapsed).toBe(true);
  190. expect(result.current.sidePaneState).toBeNull();
  191. act(() => result.current.handleToggleSidePaneCollapse());
  192. const launcherId = result.current.sidePaneState!.activeTabId;
  193. await act(async () => result.current.handleCloseSidePaneTab(launcherId));
  194. expect(result.current.isSidePaneCollapsed).toBe(true);
  195. expect(result.current.sidePaneState).toBeNull();
  196. expect(result.current.recentClosedSidePaneTabs.some(({ tab }) => tab.type === "new-tab")).toBe(
  197. false,
  198. );
  199. });
  200. beforeEach(() => {
  201. clearTaskSidePaneMemoryStateForTest();
  202. closeSessionMock.mockClear();
  203. });
  204. afterEach(() => {
  205. clearTaskSidePaneMemoryStateForTest();
  206. });
  207. it("设置页覆盖期间 Ready 仍挂载 tab 并按 scope 展开激活", () => {
  208. const { emitReady, result, unmount } = renderSettingsOverlayHook(false);
  209. act(() => {
  210. emitReady(readyPayload("tab-a"));
  211. });
  212. expect(result.current.sidePaneState).toMatchObject({
  213. activeTabId: "browser-use:tab-a",
  214. tabs: [{ id: "browser-use:tab-a", tabId: "tab-a" }],
  215. });
  216. expect(result.current.isSidePaneCollapsed).toBe(false);
  217. unmount();
  218. });
  219. it("切进设置页后 Ready 订阅不断开", () => {
  220. const { emitReady, rerender, result, unmount } = renderSettingsOverlayHook(true);
  221. act(() => {
  222. rerender({ isWorkspaceVisible: false });
  223. });
  224. act(() => {
  225. emitReady(readyPayload("tab-a"));
  226. });
  227. expect(result.current.sidePaneState).toMatchObject({
  228. tabs: [{ id: "browser-use:tab-a", tabId: "tab-a" }],
  229. });
  230. unmount();
  231. });
  232. it("设置页覆盖期间 visibility 仍能切换 active tab", () => {
  233. const { emitReady, emitVisibility, result, unmount } = renderSettingsOverlayHook(false);
  234. act(() => {
  235. emitReady(readyPayload("tab-a"));
  236. emitReady(readyPayload("tab-b"));
  237. });
  238. expect(result.current.sidePaneState?.activeTabId).toBe("browser-use:tab-b");
  239. act(() => {
  240. emitVisibility({ ...readyPayload("tab-a"), visible: true });
  241. });
  242. expect(result.current.sidePaneState?.activeTabId).toBe("browser-use:tab-a");
  243. unmount();
  244. });
  245. it("设置页覆盖期间 webview 的 target=_blank 仍能开右侧 browser tab", () => {
  246. const { emitOpenBrowserUrl, result, unmount } = renderSettingsOverlayHook(false);
  247. act(() => {
  248. emitOpenBrowserUrl({
  249. url: "https://example.com/",
  250. disposition: "foreground-tab",
  251. });
  252. });
  253. expect(result.current.sidePaneState?.tabs).toEqual([
  254. expect.objectContaining({ type: "browser" }),
  255. ]);
  256. expect(result.current.isSidePaneCollapsed).toBe(false);
  257. unmount();
  258. });
  259. it("非当前对话的 webview popup 只后台挂载,不抢当前对话焦点", () => {
  260. const { emitOpenBrowserUrl, result, unmount } = renderBrowserViewLifecycleHook();
  261. act(() => {
  262. emitOpenBrowserUrl({
  263. url: "https://example.com/from-session-b",
  264. disposition: "foreground-tab",
  265. workspaceKey: WORKSPACE_KEY,
  266. remoteSessionId: "remote-a",
  267. sessionId: "sess-b",
  268. browserId: "iab-a",
  269. browserGeneration: 2,
  270. sourceTabId: "tab-b",
  271. });
  272. });
  273. expect(result.current.sidePaneState?.activeTabId).not.toMatch(/^browser:/);
  274. expect(result.current.sidePaneState?.tabs).toEqual([
  275. expect.objectContaining({
  276. type: "browser",
  277. ownerTaskId: "sess-b",
  278. workspaceKey: WORKSPACE_KEY,
  279. initialUrl: "https://example.com/from-session-b",
  280. }),
  281. ]);
  282. expect(result.current.isSidePaneCollapsed).toBe(true);
  283. unmount();
  284. });
  285. it("同一 React batch 内按 Ready(A) → Ready(B) → visibility(B) 保留 shell 并激活 B", () => {
  286. const { emitReady, emitVisibility, result, unmount } = renderBrowserViewLifecycleHook();
  287. act(() => {
  288. emitReady(readyPayload("tab-a"));
  289. emitReady(readyPayload("tab-b"));
  290. emitVisibility({ ...readyPayload("tab-b"), visible: true });
  291. });
  292. expect(result.current.sidePaneState).toMatchObject({
  293. activeTabId: "browser-use:tab-b",
  294. tabs: [
  295. { id: "browser-use:tab-a", tabId: "tab-a" },
  296. { id: "browser-use:tab-b", tabId: "tab-b" },
  297. ],
  298. });
  299. expect(result.current.isSidePaneCollapsed).toBe(false);
  300. unmount();
  301. });
  302. it("同一 React batch 内普通 tab 打开先于 Ready 时保留两类 tab", () => {
  303. const { emitReady, result, unmount } = renderBrowserViewLifecycleHook();
  304. act(() => {
  305. result.current.handleToggleGit();
  306. emitReady(readyPayload("tab-a"));
  307. });
  308. expect(result.current.sidePaneState?.tabs.map((tab) => tab.type)).toEqual([
  309. "git",
  310. "browser-use",
  311. ]);
  312. expect(result.current.sidePaneState?.activeTabId).toBe("browser-use:tab-a");
  313. unmount();
  314. });
  315. it("同一 React batch 内普通激活先于 BrowserView operation 时不回滚 active tab", () => {
  316. const { emitOperation, emitReady, result, unmount } = renderBrowserViewLifecycleHook();
  317. act(() => emitReady(readyPayload("tab-a")));
  318. act(() => result.current.handleToggleGit());
  319. act(() => result.current.handleActivateSidePaneTab("browser-use:tab-a"));
  320. act(() => {
  321. result.current.handleActivateSidePaneTab("git");
  322. emitOperation(readyPayload("tab-a"));
  323. });
  324. expect(result.current.sidePaneState?.activeTabId).toBe("git");
  325. unmount();
  326. });
  327. it("同一 React batch 内普通排序先于 BrowserView operation 时不回滚 tab 顺序", () => {
  328. const { emitOperation, emitReady, result, unmount } = renderBrowserViewLifecycleHook();
  329. act(() => emitReady(readyPayload("tab-a")));
  330. act(() => emitReady(readyPayload("tab-b")));
  331. act(() => {
  332. result.current.handleReorderSidePaneTab("browser-use:tab-b", "browser-use:tab-a");
  333. emitOperation(readyPayload("tab-a"));
  334. });
  335. expect(result.current.sidePaneState?.tabs.map((tab) => tab.id)).toEqual([
  336. "browser-use:tab-b",
  337. "browser-use:tab-a",
  338. ]);
  339. unmount();
  340. });
  341. it("close(B) 后相邻到达的迟到 visibility(B) 不重建 shell", () => {
  342. const { emitClose, emitReady, emitVisibility, result, unmount } =
  343. renderBrowserViewLifecycleHook();
  344. act(() => emitReady(readyPayload("tab-a")));
  345. act(() => emitReady(readyPayload("tab-b")));
  346. act(() => {
  347. emitClose({ tabId: "tab-b" });
  348. emitVisibility({ ...readyPayload("tab-b"), visible: true });
  349. });
  350. expect(result.current.sidePaneState).toMatchObject({
  351. activeTabId: "browser-use:tab-a",
  352. tabs: [{ id: "browser-use:tab-a", tabId: "tab-a" }],
  353. });
  354. unmount();
  355. });
  356. it("用户关闭 B 获得 main authority 后,迟到 visibility(B) 不重建 shell", async () => {
  357. const { emitReady, emitVisibility, platform, result, unmount } =
  358. renderBrowserViewLifecycleHook();
  359. act(() => emitReady(readyPayload("tab-a")));
  360. act(() => emitReady(readyPayload("tab-b")));
  361. await act(async () => {
  362. result.current.handleCloseSidePaneTab("browser-use:tab-b");
  363. await Promise.resolve();
  364. await Promise.resolve();
  365. emitVisibility({ ...readyPayload("tab-b"), visible: true });
  366. });
  367. expect(platform.browserViewCloseTab).toHaveBeenCalledWith({
  368. tabId: "tab-b",
  369. workspaceKey: "ssh://host/repo",
  370. remoteSessionId: "remote-a",
  371. sessionId: "sess-a",
  372. });
  373. expect(result.current.sidePaneState).toMatchObject({
  374. activeTabId: "browser-use:tab-a",
  375. tabs: [{ id: "browser-use:tab-a", tabId: "tab-a" }],
  376. });
  377. unmount();
  378. });
  379. it("A 主动收起后关闭 B,仍有可见 tab 时保持收起和 owner 偏好", () => {
  380. const { emitClose, emitReady, result, unmount } = renderBrowserViewLifecycleHook();
  381. act(() => {
  382. emitReady(readyPayload("tab-a"));
  383. emitReady(readyPayload("tab-b"));
  384. });
  385. act(() => result.current.handleToggleSidePaneCollapse());
  386. expect(result.current.isSidePaneCollapsed).toBe(true);
  387. act(() => {
  388. emitClose({
  389. tabId: "tab-b",
  390. workspaceKey: WORKSPACE_KEY,
  391. remoteSessionId: "remote-a",
  392. sessionId: "sess-a",
  393. });
  394. });
  395. expect(result.current.sidePaneState?.tabs).toHaveLength(1);
  396. expect(result.current.isSidePaneCollapsed).toBe(true);
  397. const memoryKey = buildTaskSidePaneMemoryKey({
  398. workspacePath: "/repo",
  399. workspaceIdentity: WORKSPACE_KEY,
  400. taskId: "sess-a",
  401. });
  402. expect(getSidePaneCollapsedPreference(readTaskSidePaneMemoryState(memoryKey), "sess-a")).toBe(
  403. true,
  404. );
  405. unmount();
  406. });
  407. it("用户通过切换入口打开 Browser tab 时仍会展开面板", () => {
  408. const { result, unmount } = renderBrowserViewLifecycleHook();
  409. act(() => result.current.handleToggleBrowser());
  410. expect(result.current.sidePaneState?.tabs).toEqual([
  411. expect.objectContaining({ type: "browser" }),
  412. ]);
  413. expect(result.current.isSidePaneCollapsed).toBe(false);
  414. unmount();
  415. });
  416. it("用户通过切换入口打开 Git tab 时仍会展开面板", () => {
  417. const { result, unmount } = renderBrowserViewLifecycleHook();
  418. act(() => result.current.handleToggleGit());
  419. expect(result.current.sidePaneState?.tabs).toEqual([expect.objectContaining({ type: "git" })]);
  420. expect(result.current.isSidePaneCollapsed).toBe(false);
  421. unmount();
  422. });
  423. it("旧 generation 与不同 remote session 的 visibility 不改变 active tab", () => {
  424. const { emitReady, emitVisibility, result, unmount } = renderBrowserViewLifecycleHook();
  425. act(() => emitReady(readyPayload("tab-a")));
  426. act(() => emitReady(readyPayload("tab-b")));
  427. act(() => emitVisibility({ ...readyPayload("tab-a"), visible: true }));
  428. act(() => {
  429. emitVisibility({
  430. ...readyPayload("tab-b", { browserGeneration: 1 }),
  431. visible: true,
  432. });
  433. emitVisibility({
  434. ...readyPayload("tab-b", { remoteSessionId: "remote-b" }),
  435. visible: true,
  436. });
  437. });
  438. expect(result.current.sidePaneState?.activeTabId).toBe("browser-use:tab-a");
  439. expect(result.current.sidePaneState?.tabs).toHaveLength(2);
  440. unmount();
  441. });
  442. it("旧 generation 与不同 remote session 的 hide 不折叠当前 shell", () => {
  443. const { emitReady, emitVisibility, result, unmount } = renderBrowserViewLifecycleHook();
  444. act(() => emitReady(readyPayload("tab-a")));
  445. act(() => {
  446. emitVisibility({
  447. ...readyPayload("tab-a", { browserGeneration: 1 }),
  448. visible: false,
  449. });
  450. });
  451. expect(result.current.isSidePaneCollapsed).toBe(false);
  452. act(() => {
  453. emitVisibility({
  454. ...readyPayload("tab-a", { remoteSessionId: "remote-b" }),
  455. visible: false,
  456. });
  457. });
  458. expect(result.current.isSidePaneCollapsed).toBe(false);
  459. unmount();
  460. });
  461. it("Agent 在其他 workspace 活跃时关闭 tab,切回原 workspace 不残留幽灵 tab", () => {
  462. const { emitClose, emitReady, rerender, result, unmount } = renderCrossWorkspaceHook();
  463. act(() => emitReady(readyPayload("tab-a")));
  464. expect(result.current.sidePaneState?.tabs.map((tab) => tab.id)).toEqual(["browser-use:tab-a"]);
  465. // 用户切到另一个 workspace,原 workspace 的 side pane 状态被存入 memory。
  466. act(() => rerender({ workspaceIdentity: OTHER_WORKSPACE_KEY }));
  467. expect(result.current.sidePaneState?.tabs ?? []).toEqual([]);
  468. expect(result.current.isSidePaneCollapsed).toBe(true);
  469. // Bug 回归:Agent 此刻关掉 tab-a,通知只带 tabId 时 renderer 只能在“当前活跃 workspace”里找,
  470. // 找不到就静默丢弃;原 workspace 的持久化 memory 仍保留这个 tab,切回来就是关不掉的幽灵 tab。
  471. act(() =>
  472. emitClose({
  473. tabId: "tab-a",
  474. workspaceKey: WORKSPACE_KEY,
  475. remoteSessionId: "remote-a",
  476. sessionId: "sess-a",
  477. }),
  478. );
  479. act(() => rerender({ workspaceIdentity: WORKSPACE_KEY }));
  480. expect(result.current.sidePaneState).toBeNull();
  481. expect(result.current.isSidePaneCollapsed).toBe(true);
  482. unmount();
  483. });
  484. it("关闭通知带的 workspace scope 等于当前活跃 workspace 时立即从 UI 移除", () => {
  485. const { emitClose, emitReady, result, unmount } = renderCrossWorkspaceHook();
  486. act(() => emitReady(readyPayload("tab-a")));
  487. expect(result.current.sidePaneState?.tabs.map((tab) => tab.id)).toEqual(["browser-use:tab-a"]);
  488. // 修复后 main 会给每条通知都带上 owner scope,所以「没切 workspace 时 Agent 关 tab」这条
  489. // 生产最常见路径也走带 workspaceKey 的分支。它必须落回活跃分支、同步更新当前 React state,
  490. // 而不是绕进 memory 分支 —— 后者只改持久化状态,UI 上的 tab 不会消失,正是用户报的症状。
  491. // 这条用例锁的是 renderer 侧的分支选择:payload.workspaceKey 与当前活跃 workspace 相同时,
  492. // 必须判定为「当前 workspace」。注意它锁不住 main 侧 workspaceKey 的构造式 —— 这里的
  493. // WORKSPACE_KEY 是硬编码值,而 main 只是把 renderer attach 时传过去的 key 原样回声。
  494. // 字段拼装那一侧由 packages/desktop/test/browserCloseTabNotification.test.ts 守。
  495. act(() =>
  496. emitClose({
  497. tabId: "tab-a",
  498. workspaceKey: WORKSPACE_KEY,
  499. remoteSessionId: "remote-a",
  500. sessionId: "sess-a",
  501. }),
  502. );
  503. expect(result.current.sidePaneState).toBeNull();
  504. expect(result.current.isSidePaneCollapsed).toBe(true);
  505. unmount();
  506. });
  507. it("关闭通知带的 workspace scope 不匹配时不误删其他 workspace 的同名 tab", () => {
  508. const { emitClose, emitReady, rerender, result, unmount } = renderCrossWorkspaceHook();
  509. act(() => emitReady(readyPayload("tab-a")));
  510. act(() => rerender({ workspaceIdentity: OTHER_WORKSPACE_KEY }));
  511. act(() =>
  512. emitClose({
  513. tabId: "tab-a",
  514. workspaceKey: "ssh://host/unrelated",
  515. remoteSessionId: "remote-a",
  516. sessionId: "sess-a",
  517. }),
  518. );
  519. act(() => rerender({ workspaceIdentity: WORKSPACE_KEY }));
  520. expect(result.current.sidePaneState?.tabs.map((tab) => tab.id)).toEqual(["browser-use:tab-a"]);
  521. unmount();
  522. });
  523. it("远程下打开链接创建的 human tab,关闭请求必须带上 remoteSessionId", async () => {
  524. // Bug 回归(远程内置浏览器 tab 关不掉):attach 侧用 `tab.remoteSessionId ?? workspaceRemoteSessionId`
  525. // 兜底冻结了 main 侧 owner.remoteSessionId,close 侧却只取 tab.remoteSessionId。human tab 从不写该
  526. // 字段,且 stamp 会跳过已带 ownerTaskId 的 tab,于是远程下 close payload 缺 remoteSessionId,
  527. // main 判 scope 失配抛错,renderer 拿不到授权就永不移除 UI 壳 —— tab 永远关不掉。
  528. const { emitOpenBrowserUrl, platform, result, unmount } = renderBrowserViewLifecycleHook();
  529. act(() => {
  530. emitOpenBrowserUrl({
  531. url: "https://example.com/from-link",
  532. disposition: "foreground-tab",
  533. workspaceKey: WORKSPACE_KEY,
  534. remoteSessionId: "remote-a",
  535. sessionId: "sess-a",
  536. browserId: "iab-a",
  537. browserGeneration: 2,
  538. sourceTabId: "tab-a",
  539. });
  540. });
  541. const humanTab = result.current.sidePaneState?.tabs.find((tab) => tab.type === "browser");
  542. expect(humanTab).toMatchObject({ remoteSessionId: "remote-a" });
  543. await act(async () => {
  544. result.current.handleCloseSidePaneTab(humanTab!.id);
  545. await Promise.resolve();
  546. await Promise.resolve();
  547. });
  548. expect(platform.browserViewCloseTab).toHaveBeenCalledWith({
  549. tabId: humanTab!.id,
  550. workspaceKey: WORKSPACE_KEY,
  551. remoteSessionId: "remote-a",
  552. sessionId: "sess-a",
  553. });
  554. // 授权拿到后 Browser 壳必须移除,展开的面板保留新标签页。
  555. expect(
  556. (result.current.sidePaneState?.tabs ?? []).filter((tab) => tab.type === "browser"),
  557. ).toEqual([]);
  558. unmount();
  559. });
  560. });