projectTreeBackgroundUnread.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. // @vitest-environment jsdom
  2. import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
  3. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  4. import { Emitter } from "@zcode/rpc";
  5. import type { IServiceAccessor, IZCodeTaskService, ProjectTask } from "@zcode/services";
  6. import type {
  7. IPlatformService,
  8. WebRemoteControlMobileTaskView,
  9. WebRemoteControlStatus,
  10. ZCodeTaskMeta,
  11. ZCodeWorkspaceEvent,
  12. } from "@zcode/shared";
  13. import { useProjectTree } from "@/project-sidebar/useProjectTree.js";
  14. import { useWorkspaceTaskNavigation } from "@/app-shell/useWorkspaceTaskNavigation.js";
  15. import { ensureTaskNavigationWorkspace } from "@/app-shell/taskNavigationWorkspace.js";
  16. import { createTabStore, type TabStore } from "@/store/tabStore.js";
  17. import { useZCodeSessionStore } from "@/store/zcodeSessionStore.js";
  18. import { createWindowHostControllerRuntime } from "@desktop/host/windowHostControllerService.js";
  19. const mocks = vi.hoisted(() => ({
  20. services: {} as IServiceAccessor,
  21. tabs: null as TabStore | null,
  22. readTree: vi.fn(),
  23. status: { status: "active" } as WebRemoteControlStatus,
  24. statusListeners: new Set<(status: WebRemoteControlStatus) => void>(),
  25. statusRead: null as Promise<WebRemoteControlStatus> | null,
  26. platform: null as Pick<
  27. IPlatformService,
  28. "getWebRemoteControlStatus" | "onWebRemoteControlStatusChanged"
  29. > | null,
  30. }));
  31. vi.mock("@/hooks/usePlatform.js", () => ({ useOptionalPlatform: () => mocks.platform }));
  32. vi.mock("@/hooks/useWorkspaceServices.js", () => ({
  33. useBaseWorkspaceServices: () => mocks.services,
  34. }));
  35. vi.mock("@/store/TabStoreProvider.js", () => ({
  36. useTabStore: (select: (state: ReturnType<TabStore["getState"]>) => unknown) =>
  37. select(mocks.tabs!.getState()),
  38. useTabStoreApi: () => mocks.tabs,
  39. }));
  40. vi.mock("@/v4/useWorkspaceSessionsIndexItems.js", () => ({
  41. useWorkspaceSessionsIndexItems: () => ({ items: [] }),
  42. }));
  43. vi.mock("@/project-sidebar/project-tree-reader.js", () => ({
  44. readProjectSidebarTree: (...args: unknown[]) => mocks.readTree(...args),
  45. }));
  46. beforeEach(() => {
  47. mocks.status = { status: "active" };
  48. mocks.statusRead = null;
  49. mocks.statusListeners.clear();
  50. mocks.platform = {
  51. getWebRemoteControlStatus: vi.fn(() => mocks.statusRead ?? Promise.resolve(mocks.status)),
  52. onWebRemoteControlStatusChanged: (callback: (status: WebRemoteControlStatus) => void) => {
  53. mocks.statusListeners.add(callback);
  54. return () => mocks.statusListeners.delete(callback);
  55. },
  56. };
  57. mocks.tabs = createTabStore(null);
  58. useZCodeSessionStore.setState({ workspaces: {}, taskNavHistory: { entries: [], cursor: -1 } });
  59. });
  60. afterEach(cleanup);
  61. async function fixture(
  62. controller = true,
  63. desktop = true,
  64. source?: {
  65. identity?: string;
  66. remoteSessionId?: string;
  67. sourceServerId?: string | null;
  68. },
  69. ) {
  70. const identity = source?.identity ?? "remote:server:source:/repo";
  71. const task: ProjectTask = {
  72. taskId: "task",
  73. traceId: "trace",
  74. title: "Task",
  75. workspacePath: "/repo",
  76. workspaceIdentity: identity,
  77. hostId: "remote:server:source",
  78. projectId: "project",
  79. createdAt: 1,
  80. updatedAt: 2,
  81. mode: "default",
  82. pinned: false,
  83. archived: false,
  84. };
  85. const events = new Emitter<ZCodeWorkspaceEvent>();
  86. let marker = 10;
  87. let delay: Promise<void> | undefined;
  88. const setTaskUnread = vi.fn(async (params: Parameters<IZCodeTaskService["setTaskUnread"]>[0]) => {
  89. if (params.unread) task.unreadAt = ++marker;
  90. else if (params.expectedUnreadAt == null || task.unreadAt === params.expectedUnreadAt)
  91. delete task.unreadAt;
  92. const response = { ...task };
  93. if (params.unread) await delay;
  94. events.fire({
  95. type: "workspace_task_list_changed",
  96. workspacePath: "/repo",
  97. workspaceIdentity: identity,
  98. taskId: task.taskId,
  99. reason: "task_meta_changed",
  100. taskMeta: { ...task },
  101. });
  102. return response;
  103. });
  104. const getTaskMeta = vi.fn(async (): Promise<ZCodeTaskMeta | null> => ({ ...task }));
  105. const service = {
  106. getTaskMeta,
  107. listTasks: vi.fn(async () => [{ ...task }]),
  108. listPinnedTasks: async () => [],
  109. listArchivedTasks: async () => [],
  110. onDynamicWorkspaceEvent: () => events.event,
  111. setTaskUnread,
  112. } as unknown as IZCodeTaskService;
  113. const runtime = createWindowHostControllerRuntime({
  114. createId: () => crypto.randomUUID(),
  115. resolveSource: () => ({
  116. scope: {
  117. kind: "remote",
  118. sourceServerId:
  119. source?.sourceServerId === null ? undefined : (source?.sourceServerId ?? "source"),
  120. remoteSessionId: source?.remoteSessionId,
  121. workspacePath: "/repo",
  122. workspaceIdentity: identity,
  123. },
  124. sourceAvailability: "online",
  125. taskService: service,
  126. }),
  127. });
  128. mocks.readTree.mockImplementation(async () => ({
  129. tree: { projects: [], tasks: [{ ...task }] },
  130. availability: new Map(),
  131. directory: { hosts: [], entries: [] },
  132. }));
  133. mocks.services = {
  134. projectService: {},
  135. ...(controller ? { windowControllerService: runtime.service } : {}),
  136. zcodeTaskService: service,
  137. broadcastService: { onMessage: () => ({ dispose() {} }) },
  138. } as unknown as IServiceAccessor;
  139. const hook = renderHook(() => useProjectTree(desktop));
  140. await waitFor(() => expect(hook.result.current.tree.tasks).toHaveLength(1));
  141. if (controller) await waitFor(() => expect(service.listTasks).toHaveBeenCalled());
  142. const complete = async (options: { signal?: boolean; updatedAt?: number } = {}) => {
  143. await act(async () =>
  144. events.fire({
  145. type: "workspace_task_list_changed",
  146. workspacePath: "/repo",
  147. workspaceIdentity: identity,
  148. taskId: task.taskId,
  149. reason: "task_status_changed",
  150. ...(options.signal === false ? {} : { unreadSignal: "background_terminal" }),
  151. taskMeta: { ...task, updatedAt: options.updatedAt ?? 2, status: "completed" },
  152. }),
  153. );
  154. };
  155. const focus = (workspaceIdentity = identity) => {
  156. mocks.tabs!.getState().addTab("/repo", { workspaceIdentity });
  157. useZCodeSessionStore.getState().setActiveTaskId("/repo", "task", workspaceIdentity);
  158. };
  159. return {
  160. ...hook,
  161. runtime,
  162. task,
  163. setTaskUnread,
  164. getTaskMeta,
  165. listTasks: vi.mocked(service.listTasks),
  166. complete,
  167. focus,
  168. delay: (promise: Promise<void>) => {
  169. delay = promise;
  170. },
  171. };
  172. }
  173. describe("project directory background unread", () => {
  174. it.each([
  175. { controller: true, draft: false },
  176. { controller: false, draft: false },
  177. { controller: true, draft: true },
  178. { controller: false, draft: true },
  179. ])(
  180. "does not read a cached task across workspaces (Controller=$controller, draft=$draft)",
  181. async ({ controller, draft }) => {
  182. const identity = "remote:server:source:/repo";
  183. mocks.tabs!.getState().addTab("/repo", { workspaceIdentity: identity });
  184. useZCodeSessionStore.getState().setActiveTaskId("/repo", "task", identity);
  185. mocks.tabs!.getState().addTab("/workspace-a");
  186. // 同名 task ID 也必须按完整 workspace 地址隔离;先建齐 scope,避免测试中途换代 owner。
  187. if (draft) useZCodeSessionStore.getState().startDraft("/workspace-a");
  188. else useZCodeSessionStore.getState().setActiveTaskId("/workspace-a", "task");
  189. const f = await fixture(controller);
  190. const blocked = Promise.withResolvers<void>();
  191. const navigation = renderHook(() =>
  192. useWorkspaceTaskNavigation({
  193. intl: { formatMessage: ({ id }) => id },
  194. workspaceAbsPath: "/workspace-a",
  195. activateTabByPath: mocks.tabs!.getState().activateTabByPath,
  196. }),
  197. );
  198. try {
  199. f.delay(blocked.promise);
  200. await f.complete();
  201. await waitFor(() => expect(f.setTaskUnread).toHaveBeenCalledTimes(1));
  202. act(() => {
  203. // 真实 Shell 会在导航 hook 之前先确保 tab;只交换 hook 内更新顺序不足以修复。
  204. expect(
  205. ensureTaskNavigationWorkspace({
  206. workspacePath: f.task.workspacePath,
  207. workspaceIdentity: f.task.workspaceIdentity,
  208. activateTabByPath: mocks.tabs!.getState().activateTabByPath,
  209. addLocalWorkspaceTab: (path) => mocks.tabs!.getState().addTab(path),
  210. }).accepted,
  211. ).toBe(true);
  212. navigation.result.current.handleSelectTask(
  213. f.task.workspacePath,
  214. "task-2",
  215. f.task.workspaceIdentity,
  216. );
  217. });
  218. await act(async () => blocked.resolve());
  219. expect(
  220. useZCodeSessionStore
  221. .getState()
  222. .getWorkspaceState(f.task.workspacePath, f.task.workspaceIdentity).activeTaskId,
  223. ).toBe("task-2");
  224. expect(f.setTaskUnread).toHaveBeenCalledTimes(1);
  225. expect(f.task.unreadAt).toBe(11);
  226. } finally {
  227. blocked.resolve();
  228. navigation.unmount();
  229. f.unmount();
  230. f.runtime.dispose();
  231. }
  232. },
  233. );
  234. it.each(["other-task", "other-identity", "missing", "automations"])(
  235. "does not infer a viewed task from an incomplete navigation target (%s)",
  236. async (route) => {
  237. const f = await fixture();
  238. try {
  239. act(() => {
  240. f.focus();
  241. useZCodeSessionStore.setState({
  242. taskNavHistory:
  243. route === "missing"
  244. ? { entries: [], cursor: -1 }
  245. : {
  246. entries: [
  247. route === "automations"
  248. ? {
  249. kind: "automations",
  250. workspacePath: "/repo",
  251. workspaceIdentity: f.task.workspaceIdentity,
  252. }
  253. : {
  254. kind: "task",
  255. workspacePath: "/repo",
  256. workspaceIdentity:
  257. route === "other-identity"
  258. ? "remote:server:other:/repo"
  259. : f.task.workspaceIdentity,
  260. taskId: route === "other-task" ? "task-2" : f.task.taskId,
  261. },
  262. ],
  263. cursor: 0,
  264. },
  265. });
  266. });
  267. await f.complete();
  268. await waitFor(() => expect(f.setTaskUnread).toHaveBeenCalledTimes(1));
  269. expect(f.task.unreadAt).toBe(11);
  270. } finally {
  271. f.unmount();
  272. f.runtime.dispose();
  273. }
  274. },
  275. );
  276. it.each([true, false])(
  277. "persists one unread for a live completion (Controller=%s) and displays the owner row",
  278. async (controller) => {
  279. const f = await fixture(controller);
  280. try {
  281. await f.complete();
  282. await waitFor(() => expect(f.setTaskUnread).toHaveBeenCalledTimes(1));
  283. await waitFor(() => expect(f.result.current.tree.tasks[0]?.unreadAt).toBe(11));
  284. await f.complete();
  285. expect(f.setTaskUnread).toHaveBeenCalledTimes(1);
  286. expect(f.result.current.tree.tasks[0]?.updatedAt).toBe(2);
  287. } finally {
  288. f.unmount();
  289. f.runtime.dispose();
  290. }
  291. },
  292. );
  293. it("does not infer a completion from ordinary status refresh or the selected task", async () => {
  294. const f = await fixture();
  295. try {
  296. await f.complete({ signal: false });
  297. expect(f.setTaskUnread).not.toHaveBeenCalled();
  298. act(() => f.focus());
  299. await f.complete();
  300. expect(f.setTaskUnread).not.toHaveBeenCalled();
  301. } finally {
  302. f.unmount();
  303. f.runtime.dispose();
  304. }
  305. });
  306. it("keeps a completion read when the task was viewed during the projection refresh", async () => {
  307. const f = await fixture();
  308. const blockedRead = Promise.withResolvers<void>();
  309. const beganRead = Promise.withResolvers<void>();
  310. try {
  311. f.listTasks.mockImplementationOnce(async () => {
  312. beganRead.resolve();
  313. await blockedRead.promise;
  314. return [{ ...f.task }];
  315. });
  316. await f.complete();
  317. await beganRead.promise;
  318. // 列表 IO 尚未完成时用户已看过又切走,必须保留这次查看并清除本轮 marker。
  319. act(() => f.focus());
  320. act(() => f.focus("remote:server:other:/repo"));
  321. await act(async () => blockedRead.resolve());
  322. expect(f.setTaskUnread).toHaveBeenCalledWith(
  323. expect.objectContaining({ unread: false, expectedUnreadAt: 11 }),
  324. );
  325. expect(f.task.unreadAt).toBeUndefined();
  326. } finally {
  327. blockedRead.resolve();
  328. f.unmount();
  329. f.runtime.dispose();
  330. }
  331. });
  332. it("keeps a foreground completion read after switching away during the projection refresh", async () => {
  333. const f = await fixture();
  334. const blockedRead = Promise.withResolvers<void>();
  335. const beganRead = Promise.withResolvers<void>();
  336. try {
  337. act(() => f.focus());
  338. f.listTasks.mockImplementationOnce(async () => {
  339. beganRead.resolve();
  340. await blockedRead.promise;
  341. return [{ ...f.task }];
  342. });
  343. await f.complete();
  344. await beganRead.promise;
  345. // 完成时任务仍在前台,之后切走不能让迟到的列表读取制造未读。
  346. act(() => f.focus("remote:server:other:/repo"));
  347. await act(async () => blockedRead.resolve());
  348. expect(f.setTaskUnread).not.toHaveBeenCalled();
  349. expect(f.task.unreadAt).toBeUndefined();
  350. } finally {
  351. blockedRead.resolve();
  352. f.unmount();
  353. f.runtime.dispose();
  354. }
  355. });
  356. it("isolates identical task IDs on the same path across remote identities", async () => {
  357. const f = await fixture();
  358. try {
  359. act(() => f.focus("remote:server:other:/repo"));
  360. await f.complete();
  361. await waitFor(() =>
  362. expect(f.setTaskUnread).toHaveBeenCalledWith(
  363. expect.objectContaining({ workspaceIdentity: f.task.workspaceIdentity, unread: true }),
  364. ),
  365. );
  366. } finally {
  367. f.unmount();
  368. f.runtime.dispose();
  369. }
  370. });
  371. it("compare-clears only its own unread marker when the task was viewed before the write reply", async () => {
  372. const f = await fixture();
  373. const pending = Promise.withResolvers<void>();
  374. try {
  375. f.delay(pending.promise);
  376. await f.complete();
  377. await waitFor(() => expect(f.setTaskUnread).toHaveBeenCalledTimes(1));
  378. act(() => f.focus());
  379. act(() => f.focus("remote:server:other:/repo"));
  380. f.task.unreadAt = 99;
  381. await act(async () => pending.resolve());
  382. await waitFor(() =>
  383. expect(f.setTaskUnread).toHaveBeenCalledWith(
  384. expect.objectContaining({ unread: false, expectedUnreadAt: 11 }),
  385. ),
  386. );
  387. expect(f.task.unreadAt).toBe(99);
  388. } finally {
  389. pending.resolve();
  390. f.unmount();
  391. f.runtime.dispose();
  392. }
  393. });
  394. it("does not start a late compare-clear after the directory writer was disposed", async () => {
  395. const f = await fixture();
  396. const pending = Promise.withResolvers<void>();
  397. try {
  398. f.delay(pending.promise);
  399. await f.complete();
  400. await waitFor(() => expect(f.setTaskUnread).toHaveBeenCalledTimes(1));
  401. act(() => f.focus());
  402. f.unmount();
  403. await act(async () => pending.resolve());
  404. expect(f.setTaskUnread).toHaveBeenCalledTimes(1);
  405. } finally {
  406. pending.resolve();
  407. f.runtime.dispose();
  408. }
  409. });
  410. it("allocates a new marker for a newer completion while the previous row is unread", async () => {
  411. const f = await fixture();
  412. try {
  413. await f.complete();
  414. await waitFor(() => expect(f.result.current.tree.tasks[0]?.unreadAt).toBe(11));
  415. await f.complete({ updatedAt: 3 });
  416. await waitFor(() => expect(f.result.current.tree.tasks[0]?.unreadAt).toBe(12));
  417. expect(f.setTaskUnread).toHaveBeenCalledTimes(2);
  418. } finally {
  419. f.unmount();
  420. f.runtime.dispose();
  421. }
  422. });
  423. it("allows a failed live signal to be retried without creating renderer-only unread state", async () => {
  424. const f = await fixture();
  425. try {
  426. f.setTaskUnread.mockRejectedValueOnce(new Error("write failed"));
  427. await f.complete();
  428. await waitFor(() => expect(f.setTaskUnread).toHaveBeenCalledTimes(1));
  429. expect(f.result.current.tree.tasks[0]?.unreadAt).toBeUndefined();
  430. await f.complete();
  431. await waitFor(() => expect(f.result.current.tree.tasks[0]?.unreadAt).toBe(11));
  432. expect(f.setTaskUnread).toHaveBeenCalledTimes(2);
  433. } finally {
  434. f.unmount();
  435. f.runtime.dispose();
  436. }
  437. });
  438. });
  439. function status(view: WebRemoteControlStatus["mobileTaskView"] = null) {
  440. mocks.status = { status: "active", mobileTaskView: view };
  441. for (const listener of mocks.statusListeners) listener(mocks.status);
  442. }
  443. const targetView: WebRemoteControlMobileTaskView = {
  444. workspacePath: "/repo",
  445. workspaceIdentity: "remote:server:source:/repo",
  446. taskId: "task",
  447. };
  448. it("foreground mobile completion stays read", async () => {
  449. const f = await fixture();
  450. try {
  451. act(() => status(targetView));
  452. await f.complete();
  453. expect(f.setTaskUnread).not.toHaveBeenCalled();
  454. } finally {
  455. f.unmount();
  456. f.runtime.dispose();
  457. }
  458. });
  459. it("direct events preserve viewed then left while unread response is in flight", async () => {
  460. const f = await fixture();
  461. const blocked = Promise.withResolvers<void>();
  462. try {
  463. f.delay(blocked.promise);
  464. await f.complete();
  465. await waitFor(() => expect(f.setTaskUnread).toHaveBeenCalledTimes(1));
  466. act(() => {
  467. status(targetView);
  468. status();
  469. });
  470. await act(async () => blocked.resolve());
  471. expect(f.setTaskUnread).toHaveBeenCalledWith(
  472. expect.objectContaining({ unread: false, expectedUnreadAt: 11 }),
  473. );
  474. expect(f.task.unreadAt).toBeUndefined();
  475. } finally {
  476. blocked.resolve();
  477. f.unmount();
  478. f.runtime.dispose();
  479. }
  480. });
  481. it("late CAS does not clear a newer completion after mobile leaves", async () => {
  482. const f = await fixture();
  483. const blocked = Promise.withResolvers<void>();
  484. try {
  485. f.delay(blocked.promise);
  486. await f.complete();
  487. await waitFor(() => expect(f.setTaskUnread).toHaveBeenCalledTimes(1));
  488. act(() => {
  489. status(targetView);
  490. status();
  491. });
  492. f.task.unreadAt = 99;
  493. await act(async () => blocked.resolve());
  494. expect(f.task.unreadAt).toBe(99);
  495. expect(f.setTaskUnread).toHaveBeenCalledWith(
  496. expect.objectContaining({ unread: false, expectedUnreadAt: 11 }),
  497. );
  498. } finally {
  499. blocked.resolve();
  500. f.unmount();
  501. f.runtime.dispose();
  502. }
  503. });
  504. it("cleared remote view does not suppress completion", async () => {
  505. const f = await fixture();
  506. try {
  507. act(() => {
  508. status(targetView);
  509. status();
  510. });
  511. await f.complete();
  512. await waitFor(() => expect(f.task.unreadAt).toBe(11));
  513. } finally {
  514. f.unmount();
  515. f.runtime.dispose();
  516. }
  517. });
  518. it("same task/path on another remote identity is not viewed", async () => {
  519. const f = await fixture();
  520. try {
  521. act(() => status({ ...targetView, workspaceIdentity: "remote:server:other:/repo" }));
  522. await f.complete();
  523. await waitFor(() => expect(f.task.unreadAt).toBe(11));
  524. } finally {
  525. f.unmount();
  526. f.runtime.dispose();
  527. }
  528. });
  529. it("stale initial status response cannot override newer live disconnect", async () => {
  530. const pending = Promise.withResolvers<WebRemoteControlStatus>();
  531. mocks.statusRead = pending.promise;
  532. const f = await fixture();
  533. try {
  534. act(() => status());
  535. await act(async () => pending.resolve({ status: "active", mobileTaskView: targetView }));
  536. await f.complete();
  537. await waitFor(() => expect(f.task.unreadAt).toBe(11));
  538. } finally {
  539. pending.resolve({ status: "idle" });
  540. f.unmount();
  541. f.runtime.dispose();
  542. }
  543. });
  544. it("completion waits for initial view snapshot without a timeout", async () => {
  545. const pending = Promise.withResolvers<WebRemoteControlStatus>();
  546. mocks.statusRead = pending.promise;
  547. const f = await fixture();
  548. try {
  549. await f.complete();
  550. expect(f.setTaskUnread).not.toHaveBeenCalled();
  551. await act(async () => pending.resolve({ status: "active", mobileTaskView: targetView }));
  552. expect(f.setTaskUnread).not.toHaveBeenCalled();
  553. } finally {
  554. pending.resolve({ status: "idle" });
  555. f.unmount();
  556. f.runtime.dispose();
  557. }
  558. });
  559. it("already committed completion is cleared by a later view even after pending was removed", async () => {
  560. const f = await fixture();
  561. try {
  562. await f.complete();
  563. await waitFor(() => expect(f.task.unreadAt).toBe(11));
  564. await act(async () => {});
  565. act(() => status(targetView));
  566. await waitFor(() => expect(f.task.unreadAt).toBeUndefined());
  567. expect(f.getTaskMeta).toHaveBeenCalled();
  568. } finally {
  569. f.unmount();
  570. f.runtime.dispose();
  571. }
  572. });
  573. it("slow view lookup cannot consume a completion accepted after leaving", async () => {
  574. const f = await fixture();
  575. const read = Promise.withResolvers<void>();
  576. const started = Promise.withResolvers<void>();
  577. try {
  578. await f.complete();
  579. await waitFor(() => expect(f.task.unreadAt).toBe(11));
  580. await act(async () => {});
  581. f.getTaskMeta.mockImplementationOnce(async () => {
  582. started.resolve();
  583. await read.promise;
  584. return { ...f.task };
  585. });
  586. act(() => status(targetView));
  587. await started.promise;
  588. act(() => status());
  589. await f.complete({ updatedAt: 3 });
  590. expect(f.setTaskUnread.mock.calls.filter(([p]) => p.unread)).toHaveLength(1);
  591. await act(async () => read.resolve());
  592. await waitFor(() => expect(f.task.unreadAt).toBe(12));
  593. expect(f.setTaskUnread.mock.calls.map(([p]) => [p.unread, p.expectedUnreadAt])).toEqual([
  594. [true, undefined],
  595. [false, 11],
  596. [true, undefined],
  597. ]);
  598. } finally {
  599. read.resolve();
  600. f.unmount();
  601. f.runtime.dispose();
  602. }
  603. });
  604. it("slow unread response, view enter/leave and next completion preserve the next marker", async () => {
  605. const f = await fixture();
  606. const write = Promise.withResolvers<void>();
  607. try {
  608. f.delay(write.promise);
  609. await f.complete();
  610. await waitFor(() => expect(f.setTaskUnread).toHaveBeenCalledTimes(1));
  611. act(() => {
  612. status(targetView);
  613. status();
  614. });
  615. await f.complete({ updatedAt: 3 });
  616. expect(f.setTaskUnread).toHaveBeenCalledTimes(1);
  617. await act(async () => write.resolve());
  618. await waitFor(() => expect(f.task.unreadAt).toBe(12));
  619. expect(f.setTaskUnread.mock.calls.map(([p]) => [p.unread, p.expectedUnreadAt])).toEqual([
  620. [true, undefined],
  621. [false, 11],
  622. [true, undefined],
  623. ]);
  624. } finally {
  625. write.resolve();
  626. f.unmount();
  627. f.runtime.dispose();
  628. }
  629. });
  630. it("repeated same-task status does not erase a manual unread marker", async () => {
  631. const f = await fixture();
  632. try {
  633. act(() => status(targetView));
  634. await waitFor(() => expect(f.getTaskMeta).toHaveBeenCalledTimes(1));
  635. await act(async () => {});
  636. f.task.unreadAt = 99;
  637. act(() => {
  638. status({ ...targetView });
  639. status({ ...targetView });
  640. });
  641. await act(async () => {});
  642. expect(f.getTaskMeta).toHaveBeenCalledTimes(1);
  643. expect(f.task.unreadAt).toBe(99);
  644. act(() => {
  645. status();
  646. status(targetView);
  647. });
  648. await waitFor(() => expect(f.task.unreadAt).toBeUndefined());
  649. } finally {
  650. f.unmount();
  651. f.runtime.dispose();
  652. }
  653. });
  654. it("Web tree never becomes a second remote-view reader/writer", async () => {
  655. const f = await fixture(true, false);
  656. try {
  657. f.task.unreadAt = 99;
  658. act(() => status(targetView));
  659. await act(async () => {});
  660. expect(mocks.platform!.getWebRemoteControlStatus).not.toHaveBeenCalled();
  661. expect(mocks.statusListeners.size).toBe(0);
  662. expect(f.getTaskMeta).not.toHaveBeenCalled();
  663. expect(f.setTaskUnread).not.toHaveBeenCalled();
  664. expect(f.task.unreadAt).toBe(99);
  665. } finally {
  666. f.unmount();
  667. f.runtime.dispose();
  668. }
  669. });
  670. it("reconnecting the same visible task clears a completion from the disconnected interval", async () => {
  671. const f = await fixture();
  672. try {
  673. act(() => status(targetView));
  674. await waitFor(() => expect(f.getTaskMeta).toHaveBeenCalledTimes(1));
  675. act(() => status());
  676. await f.complete();
  677. await waitFor(() => expect(f.task.unreadAt).toBe(11));
  678. await act(async () => {});
  679. act(() => status({ ...targetView }));
  680. await waitFor(() => expect(f.task.unreadAt).toBeUndefined());
  681. expect(f.getTaskMeta).toHaveBeenCalledTimes(2);
  682. } finally {
  683. f.unmount();
  684. f.runtime.dispose();
  685. }
  686. });
  687. it("reads and clears a legacy remote marker through the trusted viewing attachment", async () => {
  688. const identity = "remote:ssh:example.test:22:dev:/repo";
  689. const f = await fixture(true, true, {
  690. identity,
  691. sourceServerId: null,
  692. remoteSessionId: "legacy-attachment",
  693. });
  694. try {
  695. await f.complete();
  696. await waitFor(() => expect(f.task.unreadAt).toBe(11));
  697. await act(async () => {});
  698. act(() =>
  699. status({
  700. workspacePath: "/repo",
  701. workspaceIdentity: identity,
  702. taskId: "task",
  703. remoteSessionId: "legacy-attachment",
  704. }),
  705. );
  706. await waitFor(() => expect(f.task.unreadAt).toBeUndefined());
  707. expect(f.getTaskMeta).toHaveBeenCalledWith({
  708. workspacePath: "/repo",
  709. workspaceIdentity: identity,
  710. taskId: "task",
  711. });
  712. expect(f.setTaskUnread).toHaveBeenLastCalledWith(
  713. expect.objectContaining({ unread: false, expectedUnreadAt: 11 }),
  714. );
  715. } finally {
  716. f.unmount();
  717. f.runtime.dispose();
  718. }
  719. });
  720. it("does not suppress a new attachment completion using the old attachment viewing status", async () => {
  721. const f = await fixture(true, true, { remoteSessionId: "current-attachment" });
  722. try {
  723. act(() => status({ ...targetView, remoteSessionId: "stale-attachment" }));
  724. await f.complete();
  725. await waitFor(() => expect(f.task.unreadAt).toBe(11));
  726. } finally {
  727. f.unmount();
  728. f.runtime.dispose();
  729. }
  730. });