projectSidebarForegroundUnread.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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 { WindowHostTaskUnreadSignal } from "@zcode/shared";
  6. import { useProjectUnreadSignals } from "@/project-sidebar/useProjectUnreadSignals.js";
  7. import { createTabStore, type TabStore } from "@/store/tabStore.js";
  8. import { useZCodeSessionStore } from "@/store/zcodeSessionStore.js";
  9. const TARGET = {
  10. taskId: "task",
  11. workspacePath: "/repo",
  12. workspaceIdentity: "remote:server:source:/repo",
  13. };
  14. const mocks = vi.hoisted(() => ({
  15. services: null as unknown as {
  16. windowControllerService: {
  17. onDynamicTaskUnreadSignal: ReturnType<typeof vi.fn>;
  18. mutateTask: ReturnType<typeof vi.fn>;
  19. };
  20. zcodeTaskService: Record<string, unknown>;
  21. },
  22. tabs: null as TabStore | null,
  23. }));
  24. vi.mock("@/hooks/useWorkspaceServices.js", () => ({
  25. useBaseWorkspaceServices: () => mocks.services,
  26. }));
  27. vi.mock("@/store/TabStoreProvider.js", () => ({
  28. useTabStoreApi: () => mocks.tabs,
  29. }));
  30. vi.mock("@/hooks/usePlatform.js", () => ({
  31. useOptionalPlatform: () => null,
  32. }));
  33. const signalEmitter = new Emitter<WindowHostTaskUnreadSignal>();
  34. const refresh = vi.fn(async () => {});
  35. // mark-unread 回包带权威 marker(写未读的 CAS 凭据)
  36. const MARKER = 11;
  37. const fireTerminal = () =>
  38. signalEmitter.fire({
  39. address: { ...TARGET },
  40. updatedAt: Date.now(),
  41. status: "completed",
  42. });
  43. const mutateTaskCalls = () =>
  44. vi.mocked(mocks.services.windowControllerService.mutateTask).mock.calls;
  45. beforeEach(() => {
  46. mocks.tabs = createTabStore(null);
  47. mocks.services = {
  48. windowControllerService: {
  49. onDynamicTaskUnreadSignal: vi.fn(() => signalEmitter.event),
  50. mutateTask: vi.fn(async () => ({ unreadAt: MARKER })),
  51. },
  52. zcodeTaskService: { setTaskUnread: vi.fn() },
  53. };
  54. // 构造 isDesktopViewing 全部命中:workspace tab 激活 + 完整导航地址 + activeTaskId。
  55. mocks.tabs.getState().addTab("/repo", { workspaceIdentity: TARGET.workspaceIdentity });
  56. useZCodeSessionStore
  57. .getState()
  58. .setActiveTaskId("/repo", TARGET.taskId, TARGET.workspaceIdentity);
  59. useZCodeSessionStore.setState({
  60. taskNavHistory: {
  61. entries: [
  62. {
  63. kind: "task",
  64. taskId: TARGET.taskId,
  65. workspacePath: TARGET.workspacePath,
  66. workspaceIdentity: TARGET.workspaceIdentity,
  67. },
  68. ],
  69. cursor: 0,
  70. },
  71. });
  72. });
  73. afterEach(() => {
  74. cleanup();
  75. vi.restoreAllMocks();
  76. });
  77. describe("project sidebar foreground completion unread", () => {
  78. it("前台完成不立即写未读(等离开补写)", async () => {
  79. renderHook(() => useProjectUnreadSignals([{ workspacePath: "/repo" }], refresh));
  80. await act(async () => fireTerminal());
  81. await new Promise((resolve) => setTimeout(resolve, 20));
  82. expect(mutateTaskCalls()).toHaveLength(0);
  83. });
  84. it("离开窗口(blur)补写未读并刷新树", async () => {
  85. renderHook(() => useProjectUnreadSignals([{ workspacePath: "/repo" }], refresh));
  86. await act(async () => fireTerminal());
  87. await act(async () => {
  88. window.dispatchEvent(new Event("blur"));
  89. });
  90. await waitFor(() => expect(mutateTaskCalls()).toHaveLength(1));
  91. expect(mutateTaskCalls()[0]?.[0]).toEqual({
  92. address: {
  93. workspacePath: TARGET.workspacePath,
  94. workspaceIdentity: TARGET.workspaceIdentity,
  95. taskId: TARGET.taskId,
  96. // workspaceIdentity 解析出的 Source 身份会带进完整地址
  97. sourceServerId: "source",
  98. },
  99. mutation: { kind: "mark-unread" },
  100. });
  101. await waitFor(() => expect(refresh).toHaveBeenCalled());
  102. });
  103. it("信号到达时页面已隐藏(最小化)直接补写", async () => {
  104. vi.spyOn(document, "hidden", "get").mockReturnValue(true);
  105. renderHook(() => useProjectUnreadSignals([{ workspacePath: "/repo" }], refresh));
  106. await act(async () => fireTerminal());
  107. await waitFor(() => expect(mutateTaskCalls()).toHaveLength(1));
  108. expect(mutateTaskCalls()[0]?.[0]?.mutation).toEqual({ kind: "mark-unread" });
  109. });
  110. it("回到窗口且任务仍在面前时按 marker 自动清除(不逼用户点走再点回)", async () => {
  111. renderHook(() => useProjectUnreadSignals([{ workspacePath: "/repo" }], refresh));
  112. await act(async () => fireTerminal());
  113. await act(async () => {
  114. window.dispatchEvent(new Event("blur"));
  115. });
  116. await waitFor(() => expect(mutateTaskCalls()).toHaveLength(1));
  117. await act(async () => {
  118. window.dispatchEvent(new Event("focus"));
  119. });
  120. await waitFor(() => expect(mutateTaskCalls()).toHaveLength(2));
  121. expect(mutateTaskCalls()[1]?.[0]).toEqual({
  122. address: {
  123. workspacePath: TARGET.workspacePath,
  124. workspaceIdentity: TARGET.workspaceIdentity,
  125. taskId: TARGET.taskId,
  126. sourceServerId: "source",
  127. },
  128. mutation: { kind: "mark-read", expectedUnreadAt: MARKER },
  129. });
  130. // 自动清除后再次 focus 不重复写
  131. await act(async () => {
  132. window.dispatchEvent(new Event("focus"));
  133. });
  134. await new Promise((resolve) => setTimeout(resolve, 20));
  135. expect(mutateTaskCalls()).toHaveLength(2);
  136. });
  137. it("回到窗口但已不在查看:保留未读作为回来处理的提醒", async () => {
  138. renderHook(() => useProjectUnreadSignals([{ workspacePath: "/repo" }], refresh));
  139. await act(async () => fireTerminal());
  140. await act(async () => {
  141. window.dispatchEvent(new Event("blur"));
  142. });
  143. await waitFor(() => expect(mutateTaskCalls()).toHaveLength(1));
  144. // 直接改 store 不发导航提交事件:模拟用户回到窗口时停在别的任务上
  145. useZCodeSessionStore.setState({
  146. taskNavHistory: {
  147. entries: [
  148. {
  149. kind: "task",
  150. taskId: "other",
  151. workspacePath: "/repo",
  152. workspaceIdentity: TARGET.workspaceIdentity,
  153. },
  154. ],
  155. cursor: 0,
  156. },
  157. });
  158. await act(async () => {
  159. window.dispatchEvent(new Event("focus"));
  160. });
  161. await new Promise((resolve) => setTimeout(resolve, 20));
  162. expect(mutateTaskCalls()).toHaveLength(1);
  163. });
  164. it("补写失败不丢记录:下次 blur 重试成功(CR-01)", async () => {
  165. renderHook(() => useProjectUnreadSignals([{ workspacePath: "/repo" }], refresh));
  166. await act(async () => fireTerminal());
  167. vi
  168. .mocked(mocks.services.windowControllerService.mutateTask)
  169. .mockRejectedValueOnce(new Error("source temporarily offline"));
  170. await act(async () => {
  171. window.dispatchEvent(new Event("blur"));
  172. });
  173. await waitFor(() => expect(mutateTaskCalls()).toHaveLength(1));
  174. // 写失败:marker 未写入,提醒不能丢
  175. await act(async () => {
  176. window.dispatchEvent(new Event("blur"));
  177. });
  178. await waitFor(() => expect(mutateTaskCalls()).toHaveLength(2));
  179. expect(mutateTaskCalls()[1]?.[0]?.mutation).toEqual({ kind: "mark-unread" });
  180. });
  181. it("blur → 完成信号 → focus:聚焦时补写未读并自动清除(SG-01 事件顺序)", async () => {
  182. renderHook(() => useProjectUnreadSignals([{ workspacePath: "/repo" }], refresh));
  183. // 先失焦(页面仍可见,hidden=false)
  184. await act(async () => {
  185. window.dispatchEvent(new Event("blur"));
  186. });
  187. await new Promise((resolve) => setTimeout(resolve, 20));
  188. // 失焦期间前台完成:记录但不写(焦点不在,写了用户也看不到横幅以外的东西,
  189. // 等回到窗口再补上提醒)
  190. await act(async () => fireTerminal());
  191. await new Promise((resolve) => setTimeout(resolve, 20));
  192. expect(mutateTaskCalls()).toHaveLength(0);
  193. // 重新聚焦:补写未读,且任务仍在面前 → 紧接自动清除
  194. await act(async () => {
  195. window.dispatchEvent(new Event("focus"));
  196. });
  197. await waitFor(() => expect(mutateTaskCalls()).toHaveLength(2));
  198. expect(mutateTaskCalls()[0]?.[0]?.mutation).toEqual({ kind: "mark-unread" });
  199. expect(mutateTaskCalls()[1]?.[0]).toEqual({
  200. address: {
  201. workspacePath: TARGET.workspacePath,
  202. workspaceIdentity: TARGET.workspaceIdentity,
  203. taskId: TARGET.taskId,
  204. sourceServerId: "source",
  205. },
  206. mutation: { kind: "mark-read", expectedUnreadAt: MARKER },
  207. });
  208. });
  209. it("focus 与恢复可见连发只发一次自动 mark-read(SG-01 去重)", async () => {
  210. renderHook(() => useProjectUnreadSignals([{ workspacePath: "/repo" }], refresh));
  211. await act(async () => fireTerminal());
  212. await act(async () => {
  213. window.dispatchEvent(new Event("blur"));
  214. });
  215. await waitFor(() => expect(mutateTaskCalls()).toHaveLength(1));
  216. // focus 与 visibilitychange(恢复可见) 连续触发:在途清除去重,只发一次 mark-read
  217. await act(async () => {
  218. window.dispatchEvent(new Event("focus"));
  219. document.dispatchEvent(new Event("visibilitychange"));
  220. });
  221. await waitFor(() => expect(mutateTaskCalls()).toHaveLength(2));
  222. expect(mutateTaskCalls()[1]?.[0]?.mutation).toEqual({
  223. kind: "mark-read",
  224. expectedUnreadAt: MARKER,
  225. });
  226. await new Promise((resolve) => setTimeout(resolve, 20));
  227. expect(mutateTaskCalls()).toHaveLength(2);
  228. });
  229. it("effect 重跑不丢在途补写:写入跨 effect 收敛(CR-01 回归)", async () => {
  230. let release: () => void = () => {};
  231. const gate = new Promise<void>((resolve) => {
  232. release = resolve;
  233. });
  234. const { rerender } = renderHook(() =>
  235. useProjectUnreadSignals([{ workspacePath: "/repo" }], refresh),
  236. );
  237. await act(async () => fireTerminal());
  238. // 第一次 blur:补写挂在 gate 上(在途)
  239. const oldMutate = vi.mocked(mocks.services.windowControllerService.mutateTask);
  240. oldMutate.mockImplementationOnce(async () => {
  241. await gate;
  242. return { unreadAt: MARKER };
  243. });
  244. await act(async () => {
  245. window.dispatchEvent(new Event("blur"));
  246. });
  247. expect(oldMutate).toHaveBeenCalledTimes(1);
  248. // services 换新对象触发 effect 重跑:旧实例 disposed,在途补写完成时
  249. // written/marker 仍会写入共享记录( disposed 检查在 await 之前已通过)。
  250. await act(async () => {
  251. // services 换新对象 + rerender:触发 effect 重跑(旧实例 disposed)
  252. mocks.services = {
  253. ...mocks.services,
  254. windowControllerService: {
  255. onDynamicTaskUnreadSignal: vi.fn(() => signalEmitter.event),
  256. mutateTask: vi.fn(async () => ({ unreadAt: MARKER })),
  257. },
  258. };
  259. rerender();
  260. });
  261. const newMutate = vi.mocked(mocks.services.windowControllerService.mutateTask);
  262. await act(async () => {
  263. release();
  264. });
  265. await waitFor(() => expect(oldMutate).toHaveBeenCalledTimes(1));
  266. // 回到窗口:已写记录按 marker 自动清除,提醒不丢
  267. await act(async () => {
  268. window.dispatchEvent(new Event("focus"));
  269. });
  270. await waitFor(() => expect(newMutate).toHaveBeenCalledTimes(1));
  271. expect(newMutate.mock.calls[0]?.[0]?.mutation).toEqual({
  272. kind: "mark-read",
  273. expectedUnreadAt: MARKER,
  274. });
  275. });
  276. it("blur 补写在途时立即 focus:等待补写完成后自动清除(CR-01 交错时序)", async () => {
  277. let release: () => void = () => {};
  278. const gate = new Promise<void>((resolve) => {
  279. release = resolve;
  280. });
  281. renderHook(() => useProjectUnreadSignals([{ workspacePath: "/repo" }], refresh));
  282. await act(async () => fireTerminal());
  283. // blur 发起补写,mutate 挂在 gate 上(在途)
  284. vi
  285. .mocked(mocks.services.windowControllerService.mutateTask)
  286. .mockImplementationOnce(async () => {
  287. await gate;
  288. return { unreadAt: MARKER };
  289. });
  290. await act(async () => {
  291. window.dispatchEvent(new Event("blur"));
  292. });
  293. expect(mutateTaskCalls()).toHaveLength(1);
  294. // 补写未完成时立即回窗(focus),此时不应有 mark-read(marker 未就位)
  295. await act(async () => {
  296. window.dispatchEvent(new Event("focus"));
  297. });
  298. await new Promise((resolve) => setTimeout(resolve, 20));
  299. expect(mutateTaskCalls()).toHaveLength(1);
  300. // 释放补写:focus 侧的 flushThenClear 等到补写落定后,
  301. // 应自动补上 mark-read(不需要再次 focus/visibility 事件)
  302. await act(async () => {
  303. release();
  304. });
  305. await waitFor(() => expect(mutateTaskCalls()).toHaveLength(2));
  306. expect(mutateTaskCalls()[0]?.[0]?.mutation).toEqual({ kind: "mark-unread" });
  307. expect(mutateTaskCalls()[1]?.[0]).toEqual({
  308. address: {
  309. workspacePath: TARGET.workspacePath,
  310. workspaceIdentity: TARGET.workspaceIdentity,
  311. taskId: TARGET.taskId,
  312. sourceServerId: "source",
  313. },
  314. mutation: { kind: "mark-read", expectedUnreadAt: MARKER },
  315. });
  316. });
  317. it("非查看状态完成仍立即写未读(既有行为回归)", async () => {
  318. useZCodeSessionStore.setState({
  319. taskNavHistory: {
  320. entries: [
  321. {
  322. kind: "task",
  323. taskId: "other",
  324. workspacePath: "/repo",
  325. workspaceIdentity: TARGET.workspaceIdentity,
  326. },
  327. ],
  328. cursor: 0,
  329. },
  330. });
  331. renderHook(() => useProjectUnreadSignals([{ workspacePath: "/repo" }], refresh));
  332. await act(async () => fireTerminal());
  333. await waitFor(() => expect(mutateTaskCalls()).toHaveLength(1));
  334. expect(mutateTaskCalls()[0]?.[0]?.mutation).toEqual({ kind: "mark-unread" });
  335. });
  336. it("blur 补写失败 → focus 重试成功 → 任务仍在面前时自动清除(CR-01 闭环)", async () => {
  337. renderHook(() => useProjectUnreadSignals([{ workspacePath: "/repo" }], refresh));
  338. await act(async () => fireTerminal());
  339. // 首次补写失败
  340. vi
  341. .mocked(mocks.services.windowControllerService.mutateTask)
  342. .mockRejectedValueOnce(new Error("source temporarily offline"));
  343. await act(async () => {
  344. window.dispatchEvent(new Event("blur"));
  345. });
  346. await waitFor(() => expect(mutateTaskCalls()).toHaveLength(1));
  347. // 重回窗口:先重试补写成功,再自动清除(共 2 次调用)
  348. await act(async () => {
  349. window.dispatchEvent(new Event("focus"));
  350. });
  351. await waitFor(() => expect(mutateTaskCalls()).toHaveLength(3));
  352. expect(mutateTaskCalls()[1]?.[0]?.mutation).toEqual({ kind: "mark-unread" });
  353. expect(mutateTaskCalls()[2]?.[0]).toEqual({
  354. address: {
  355. workspacePath: TARGET.workspacePath,
  356. workspaceIdentity: TARGET.workspaceIdentity,
  357. taskId: TARGET.taskId,
  358. sourceServerId: "source",
  359. },
  360. mutation: { kind: "mark-read", expectedUnreadAt: MARKER },
  361. });
  362. });
  363. it("卸载后 focus 不再触发任何写入(监听器随 effect 清理)", async () => {
  364. const removeSpy = vi.spyOn(window, "removeEventListener");
  365. const { unmount } = renderHook(() =>
  366. useProjectUnreadSignals([{ workspacePath: "/repo" }], refresh),
  367. );
  368. unmount();
  369. expect(removeSpy).toHaveBeenCalledWith("focus", expect.any(Function));
  370. const callsBefore = mutateTaskCalls().length;
  371. await act(async () => {
  372. window.dispatchEvent(new Event("focus"));
  373. window.dispatchEvent(new Event("blur"));
  374. });
  375. await new Promise((resolve) => setTimeout(resolve, 20));
  376. expect(mutateTaskCalls().length).toBe(callsBefore);
  377. });
  378. it("多次前台完成只补写一次(去重),blur 后集合清空", async () => {
  379. renderHook(() => useProjectUnreadSignals([{ workspacePath: "/repo" }], refresh));
  380. await act(async () => {
  381. fireTerminal();
  382. fireTerminal();
  383. fireTerminal();
  384. });
  385. await act(async () => {
  386. window.dispatchEvent(new Event("blur"));
  387. });
  388. await waitFor(() => expect(mutateTaskCalls()).toHaveLength(1));
  389. await act(async () => {
  390. window.dispatchEvent(new Event("blur"));
  391. });
  392. await new Promise((resolve) => setTimeout(resolve, 20));
  393. expect(mutateTaskCalls()).toHaveLength(1);
  394. });
  395. });