hooksSection.test.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. import type { IHooksService } from "@zcode/services";
  2. import type { Hook } from "@zcode/shared";
  3. import { readFileSync } from "node:fs";
  4. import { createElement } from "react";
  5. import { renderToStaticMarkup } from "react-dom/server";
  6. import { afterEach, describe, expect, it } from "vitest";
  7. import { TooltipProvider } from "@/components/ui/tooltip.js";
  8. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  9. import { HookForm } from "@/settings/HookForm.js";
  10. import { HooksList, groupHookSections } from "@/settings/HooksList.js";
  11. import {
  12. buildPluginHookRows,
  13. filterPluginHooksByScope,
  14. isReadOnlyZCodeHook,
  15. resolveLatestReviewScopeTarget,
  16. } from "@/settings/HooksSection.js";
  17. import { useHooksStore } from "@/store/hooksStore.js";
  18. afterEach(() => {
  19. useHooksStore.setState({
  20. workspacePath: null,
  21. workspaceIdentity: null,
  22. loadedWorkspaceKey: null,
  23. hooks: [],
  24. loading: false,
  25. error: null,
  26. operatingHookId: null,
  27. });
  28. });
  29. describe("Hooks settings page", () => {
  30. it("keeps same-name plugin hooks in separate marketplace groups", () => {
  31. const sections = groupHookSections(
  32. [],
  33. [],
  34. [
  35. {
  36. pluginId: "computer-use@zcode-plugins-official",
  37. pluginName: "computer-use",
  38. detail: { event: "PreToolUse", type: "command", command: "official" },
  39. pluginEnabled: true,
  40. },
  41. {
  42. pluginId: "zcode-cua@custom-marketplace",
  43. pluginName: "zcode-cua",
  44. detail: { event: "PreToolUse", type: "command", command: "custom" },
  45. pluginEnabled: true,
  46. },
  47. ],
  48. );
  49. expect(sections.filter((section) => section.kind === "plugin")).toHaveLength(2);
  50. expect(
  51. sections
  52. .filter((section) => section.kind === "plugin")
  53. .flatMap((section) => section.hooks.map((hook) => hook.pluginId)),
  54. ).toEqual([
  55. "computer-use@zcode-plugins-official",
  56. "zcode-cua@custom-marketplace",
  57. ]);
  58. });
  59. it("only exposes connected Workspaces to Hooks scope routing", () => {
  60. const source = readFileSync(
  61. new URL("../src/settings/HooksSection.tsx", import.meta.url),
  62. "utf8",
  63. );
  64. expect(source).toContain("isPluginScopeWorkspaceConnected");
  65. expect(source).toContain(".filter(isPluginScopeWorkspaceConnected)");
  66. });
  67. it("does not classify plugin hooks as user when overview scope is unavailable", () => {
  68. const pluginRows = buildPluginHookRows(
  69. [
  70. {
  71. id: "quality@official",
  72. name: "quality",
  73. enabled: true,
  74. hookDetails: [
  75. {
  76. event: "PreToolUse",
  77. type: "command",
  78. command: "./check.sh",
  79. sourcePath: "/plugins/quality/hooks/hooks.json",
  80. runnable: true,
  81. },
  82. ],
  83. },
  84. ],
  85. [],
  86. false,
  87. );
  88. expect(pluginRows).toHaveLength(1);
  89. expect(pluginRows[0]?.pluginScope).toBeUndefined();
  90. expect(filterPluginHooksByScope(pluginRows, "user")).toEqual(pluginRows);
  91. expect(filterPluginHooksByScope(pluginRows, "project")).toEqual(pluginRows);
  92. const workspaceRows = buildPluginHookRows(
  93. [
  94. {
  95. id: "quality@official",
  96. name: "quality",
  97. enabled: true,
  98. hookDetails: pluginRows.map((row) => row.detail),
  99. },
  100. ],
  101. [{ id: "quality@official", scope: "workspace" }],
  102. true,
  103. );
  104. expect(filterPluginHooksByScope(workspaceRows, "user")).toEqual([]);
  105. expect(filterPluginHooksByScope(workspaceRows, "project")).toEqual(workspaceRows);
  106. });
  107. it("persists per-hook enabled state through saveHooks with workspace identity", async () => {
  108. const saved: Array<Parameters<IHooksService["saveHooks"]>[0]> = [];
  109. let persistedHooks = [configuredHook()];
  110. const service: IHooksService = {
  111. async loadHooks() {
  112. return {
  113. hooks: persistedHooks,
  114. hooksEnabled: persistedHooks.some((hook) => hook.enabled),
  115. };
  116. },
  117. async saveHooks(params) {
  118. saved.push(params);
  119. persistedHooks = params.hooks;
  120. },
  121. };
  122. useHooksStore.setState({
  123. workspacePath: "/workspace",
  124. workspaceIdentity: "ssh://dev/workspace",
  125. hooks: persistedHooks,
  126. });
  127. await useHooksStore.getState().toggleHook("configured", false, service);
  128. expect(saved).toHaveLength(1);
  129. expect(saved[0]).toMatchObject({
  130. workspacePath: "/workspace",
  131. workspaceIdentity: "ssh://dev/workspace",
  132. });
  133. expect(saved[0]?.hooks[0]).toMatchObject({
  134. id: "configured",
  135. enabled: false,
  136. });
  137. });
  138. // Bugfix 回归:store 是单例,慢 workspace 的加载结果后到时曾无条件覆盖当前投影,
  139. // 之后任一写操作会把上一个 workspace 的整组 hooks 落盘到当前 workspace。
  140. it("discards a stale hooks load after the workspace scope changed", async () => {
  141. const hookA: Hook = { ...configuredHook(), id: "hook-a", command: "echo a" };
  142. const hookB: Hook = { ...configuredHook(), id: "hook-b", command: "echo b" };
  143. let releaseSlowLoad: (() => void) | undefined;
  144. const slowLoad = new Promise<void>((resolve) => {
  145. releaseSlowLoad = resolve;
  146. });
  147. const saved: Array<Parameters<IHooksService["saveHooks"]>[0]> = [];
  148. const service: IHooksService = {
  149. async loadHooks(params) {
  150. if (params.workspacePath === "/workspace-a") {
  151. await slowLoad;
  152. return { hooks: [hookA], hooksEnabled: true };
  153. }
  154. return { hooks: [hookB], hooksEnabled: true };
  155. },
  156. async saveHooks(params) {
  157. saved.push(params);
  158. },
  159. };
  160. const slowInitialize = useHooksStore
  161. .getState()
  162. .initialize("/workspace-a", undefined, service);
  163. await useHooksStore.getState().initialize("/workspace-b", undefined, service);
  164. releaseSlowLoad?.();
  165. await slowInitialize;
  166. expect(useHooksStore.getState().loadedWorkspaceKey).toBe("/workspace-b");
  167. expect(useHooksStore.getState().hooks.map((hook) => hook.id)).toEqual(["hook-b"]);
  168. await useHooksStore.getState().toggleHook("hook-b", false, service);
  169. expect(saved).toHaveLength(1);
  170. expect(saved[0]?.workspacePath).toBe("/workspace-b");
  171. expect(saved[0]?.hooks.map((hook) => hook.id)).toEqual(["hook-b"]);
  172. });
  173. it("imports a compatibility hook as an enabled ZCode hook", async () => {
  174. const legacy: Hook = {
  175. id: "legacy",
  176. event: "Stop",
  177. type: "command",
  178. command: "echo legacy",
  179. enabled: false,
  180. location: {
  181. source: "claude",
  182. scope: "project",
  183. directoryPath: "/workspace/.claude",
  184. projectPath: "/workspace",
  185. },
  186. };
  187. let persistedHooks = [legacy];
  188. const service: IHooksService = {
  189. async loadHooks() {
  190. return {
  191. hooks: persistedHooks,
  192. hooksEnabled: persistedHooks.some((hook) => hook.enabled),
  193. };
  194. },
  195. async saveHooks(params) {
  196. persistedHooks = params.hooks;
  197. },
  198. };
  199. useHooksStore.setState({
  200. workspacePath: "/workspace",
  201. hooks: persistedHooks,
  202. });
  203. await useHooksStore.getState().importHook("legacy", service);
  204. expect(persistedHooks).toContainEqual(
  205. expect.objectContaining({
  206. event: "Stop",
  207. command: "echo legacy",
  208. enabled: true,
  209. location: expect.objectContaining({
  210. source: "zcode",
  211. scope: "project",
  212. }),
  213. }),
  214. );
  215. });
  216. it("groups direct, plugin, and compatibility hooks by source", () => {
  217. const legacy: Hook = {
  218. id: "legacy",
  219. event: "Stop",
  220. type: "command",
  221. command: "echo legacy",
  222. enabled: false,
  223. location: {
  224. source: "claude",
  225. scope: "project",
  226. directoryPath: "/workspace/.claude",
  227. },
  228. };
  229. const sections = groupHookSections(
  230. [configuredHook(), { ...configuredHook(), id: "configured-2", event: "Stop" }],
  231. [legacy],
  232. [
  233. {
  234. pluginId: "quality@official",
  235. pluginName: "quality",
  236. pluginEnabled: true,
  237. pluginScope: undefined,
  238. detail: {
  239. event: "PostToolUse",
  240. matcher: "Write",
  241. type: "command",
  242. command: "./check.sh",
  243. sourcePath: "/plugins/quality/hooks/hooks.json",
  244. runnable: true,
  245. },
  246. },
  247. ],
  248. );
  249. expect(sections.map((section) => section.kind)).toEqual(["installed", "plugin", "legacy"]);
  250. expect(sections[1]).toMatchObject({ title: "quality", count: 1 });
  251. const html = renderToStaticMarkup(
  252. createElement(
  253. ZCodeIntlProvider,
  254. { initialLocale: "en-US" },
  255. createElement(
  256. TooltipProvider,
  257. null,
  258. createElement(HooksList, {
  259. compatibilityHooks: [legacy],
  260. editableHooks: [configuredHook(), { ...configuredHook(), id: "configured-2", event: "Stop" }],
  261. operatingHookId: null,
  262. pluginHooks: [
  263. {
  264. pluginId: "quality@official",
  265. pluginName: "quality",
  266. pluginEnabled: true,
  267. pluginScope: undefined,
  268. pluginIconItem: { name: "quality", listing: undefined },
  269. detail: {
  270. event: "PostToolUse",
  271. matcher: "Write",
  272. type: "command",
  273. command: "./check.sh",
  274. sourcePath: "/plugins/quality/hooks/hooks.json",
  275. runnable: true,
  276. },
  277. },
  278. ],
  279. onDelete: async () => {},
  280. onEdit: () => {},
  281. onImport: async () => {},
  282. onToggle: async () => {},
  283. installedAction: createElement("button", null, "New"),
  284. showInstalledSection: true,
  285. }),
  286. ),
  287. ),
  288. );
  289. expect(html).toContain("PreToolUse");
  290. expect(html).toContain("Stop");
  291. expect(html).toContain("Installed");
  292. expect(html).toContain("New");
  293. expect(html).toContain(
  294. "flex flex-wrap items-center justify-between gap-3",
  295. );
  296. expect(html).not.toContain("flex h-7 items-center justify-between");
  297. expect(html).toContain("Legacy");
  298. expect(html).toContain("PostToolUse");
  299. expect(html).toContain("quality");
  300. expect(html).toContain("Scope unknown");
  301. expect(html).toContain("plugin-hook-row");
  302. expect(html).toContain("lucide-anchor");
  303. expect(html).not.toContain("lucide-webhook");
  304. expect(html).toContain("overflow-hidden rounded-xl bg-surface");
  305. expect(html).toContain("h-px bg-border/50");
  306. expect(html).toContain("font-mono text-ui-sm text-foreground-subtle");
  307. expect(html).toContain("hover:bg-hover");
  308. expect(html).not.toContain("Configured hooks");
  309. expect(html).not.toContain("Plugin hooks");
  310. });
  311. it("omits empty groups after filtering", () => {
  312. expect(groupHookSections([], [], [])).toEqual([]);
  313. });
  314. it("localizes built-in hook group titles", () => {
  315. const legacy: Hook = {
  316. id: "legacy-zh",
  317. event: "Stop",
  318. type: "command",
  319. command: "echo legacy",
  320. enabled: false,
  321. location: {
  322. source: "claude",
  323. scope: "user",
  324. directoryPath: "/home/.claude",
  325. },
  326. };
  327. const html = renderToStaticMarkup(
  328. createElement(
  329. ZCodeIntlProvider,
  330. { initialLocale: "zh-CN" },
  331. createElement(
  332. TooltipProvider,
  333. null,
  334. createElement(HooksList, {
  335. compatibilityHooks: [legacy],
  336. editableHooks: [configuredHook()],
  337. operatingHookId: null,
  338. pluginHooks: [],
  339. onEdit: () => {},
  340. onImport: async () => {},
  341. onToggle: async () => {},
  342. }),
  343. ),
  344. ),
  345. );
  346. expect(html).toContain("已安装");
  347. expect(html).toContain("旧版");
  348. expect(html).not.toContain(">Installed<");
  349. expect(html).not.toContain(">Legacy<");
  350. });
  351. it("renders an existing status message as an editable typed field", () => {
  352. const html = renderToStaticMarkup(
  353. createElement(
  354. ZCodeIntlProvider,
  355. { initialLocale: "en-US" },
  356. createElement(HookForm, {
  357. hook: {
  358. ...configuredHook(),
  359. type: "command",
  360. command: "echo verify",
  361. statusMessage: "Preparing workspace",
  362. },
  363. workspaceAvailable: true,
  364. onSave: () => {},
  365. onCancel: () => {},
  366. isEditing: true,
  367. }),
  368. ),
  369. );
  370. expect(html).toContain("Status message");
  371. expect(html).toContain('value="Preparing workspace"');
  372. expect(html).toContain('data-variant="ghost" data-size="lg"');
  373. expect(html).toContain("Manage task lifecycle hooks");
  374. expect(html).toContain("space-y-3 rounded-xl border border-border p-4");
  375. expect(html).not.toContain("rounded-xl border border-border bg-card p-4");
  376. expect(html).toContain('data-size="lg"');
  377. expect(html).toContain("flex flex-col gap-2 pt-1 sm:flex-row sm:items-center");
  378. expect(html).toContain("sm:ml-auto");
  379. expect(html).toContain("flex flex-wrap items-start justify-between gap-3");
  380. expect(html).toContain("items-center justify-end gap-2");
  381. expect(html).toContain('data-plugin-scope-trigger="true"');
  382. expect(html).toContain("sm:grid-cols-2");
  383. expect(html).toContain('id="hook-runner"');
  384. expect(html).not.toContain('aria-pressed="true"');
  385. expect(html).toContain("<details");
  386. expect(html).toContain("Advanced");
  387. expect(html).toContain("group-open/advanced:rotate-90");
  388. });
  389. // workspace-hook-trust:未信任的工作区 Hook 在任何 review 状态下都显示行内 Trust 按钮;
  390. // 信任状态不通过徽章展示,避免与运行时权威投影产生第二事实来源。
  391. it("无需活跃 review 也给未信任 Workspace Hook 显示行内信任按钮,并删除推导状态徽章", () => {
  392. const untrusted = {
  393. ...workspaceConfiguredHook("pending_trust"),
  394. id: "untrusted-disabled-row",
  395. enabled: false,
  396. workspaceHook: {
  397. ...workspaceConfiguredHook("pending_trust").workspaceHook!,
  398. configuredEnabled: false,
  399. reviewItemId: "untrusted-review-item",
  400. },
  401. };
  402. const trusted = {
  403. ...workspaceConfiguredHook("trusted_persistent"),
  404. id: "trusted-hook",
  405. workspaceHook: {
  406. ...workspaceConfiguredHook("trusted_persistent").workspaceHook!,
  407. reviewItemId: "trusted-hook",
  408. },
  409. };
  410. const html = renderToStaticMarkup(
  411. createElement(
  412. ZCodeIntlProvider,
  413. { initialLocale: "en-US" },
  414. createElement(
  415. TooltipProvider,
  416. null,
  417. createElement(HooksList, {
  418. compatibilityHooks: [],
  419. editableHooks: [untrusted, trusted],
  420. operatingHookId: null,
  421. pluginHooks: [],
  422. trustActionAvailable: true,
  423. trustingHookId: null,
  424. onEdit: () => {},
  425. onImport: async () => {},
  426. onToggle: async () => {},
  427. onTrust: async () => {},
  428. }),
  429. ),
  430. ),
  431. );
  432. expect(html.match(/>Trust</gu)).toHaveLength(1);
  433. expect(html.indexOf(">Trust<")).toBeLessThan(html.indexOf('role="switch"'));
  434. expect(html).not.toContain("Configured on");
  435. expect(html).not.toContain("Configured off");
  436. expect(html).not.toContain("Needs review");
  437. expect(html).not.toContain("Trusted");
  438. expect(html).not.toContain("Will run");
  439. expect(html).not.toContain("Will not run");
  440. });
  441. it("未信任 Hook 的有效运行开关固定关闭并锁定,且不修改传入配置状态", () => {
  442. const untrustedConfiguredOn = workspaceConfiguredHook("pending_trust");
  443. const html = renderToStaticMarkup(
  444. createElement(
  445. ZCodeIntlProvider,
  446. { initialLocale: "en-US" },
  447. createElement(
  448. TooltipProvider,
  449. null,
  450. createElement(HooksList, {
  451. compatibilityHooks: [],
  452. editableHooks: [untrustedConfiguredOn],
  453. operatingHookId: null,
  454. pluginHooks: [],
  455. trustActionAvailable: false,
  456. trustingHookId: null,
  457. onEdit: () => {},
  458. onImport: async () => {},
  459. onToggle: async () => {},
  460. onTrust: async () => {},
  461. }),
  462. ),
  463. ),
  464. );
  465. expect(untrustedConfiguredOn.enabled).toBe(true);
  466. expect(html).toContain(">Trust<");
  467. expect(html).toMatch(/<button[^>]*disabled=""[^>]*>[^<]*<svg[^>]*lucide-shield-check/su);
  468. expect(html).toMatch(/role="switch"[^>]*aria-checked="false"[^>]*disabled=""/u);
  469. });
  470. it("持久信任后隐藏 Trust,并恢复配置开关的真实值与可操作性", () => {
  471. const html = renderToStaticMarkup(
  472. createElement(
  473. ZCodeIntlProvider,
  474. { initialLocale: "en-US" },
  475. createElement(
  476. TooltipProvider,
  477. null,
  478. createElement(HooksList, {
  479. compatibilityHooks: [],
  480. editableHooks: [workspaceConfiguredHook("trusted_persistent")],
  481. operatingHookId: null,
  482. pluginHooks: [],
  483. trustActionAvailable: true,
  484. trustingHookId: null,
  485. onEdit: () => {},
  486. onImport: async () => {},
  487. onToggle: async () => {},
  488. onTrust: async () => {},
  489. }),
  490. ),
  491. ),
  492. );
  493. expect(html).not.toContain(">Trust<");
  494. expect(html).toMatch(/role="switch"[^>]*aria-checked="true"/u);
  495. expect(html).not.toMatch(/role="switch"[^>]*disabled=""/u);
  496. });
  497. // P3 回归:editable=false 的上游/祖先 zcode.json Hook 是只读工作区 Hook,必须留在
  498. // Installed 分组走行内 Trust,而不是进 Legacy 显示必然失败的 Import。
  499. it("readonly zcode workspace hook stays in installed section with trust, not legacy import", () => {
  500. const readOnlyHook: Hook = {
  501. ...workspaceConfiguredHook("pending_trust"),
  502. editable: false,
  503. location: {
  504. source: "zcode",
  505. scope: "project",
  506. directoryPath: "/ancestor/.zcode",
  507. projectPath: "/workspace",
  508. },
  509. };
  510. expect(isReadOnlyZCodeHook(readOnlyHook)).toBe(true);
  511. expect(isReadOnlyZCodeHook(workspaceConfiguredHook("pending_trust"))).toBe(false);
  512. const html = renderToStaticMarkup(
  513. createElement(
  514. ZCodeIntlProvider,
  515. { initialLocale: "en-US" },
  516. createElement(
  517. TooltipProvider,
  518. null,
  519. createElement(HooksList, {
  520. compatibilityHooks: [],
  521. editableHooks: [readOnlyHook],
  522. operatingHookId: null,
  523. pluginHooks: [],
  524. trustActionAvailable: true,
  525. trustingHookId: null,
  526. onEdit: () => {},
  527. onImport: async () => {},
  528. onToggle: async () => {},
  529. onTrust: async () => {},
  530. }),
  531. ),
  532. ),
  533. );
  534. expect(html).toContain("Installed");
  535. expect(html).not.toContain("Legacy");
  536. expect(html).toContain(">Trust<");
  537. expect(html).not.toContain(">Import<");
  538. // 只读行未信任:Switch 强制关闭并禁用(readOnly 且 requiresTrust 双重锁定)。
  539. expect(html).toMatch(/role="switch"[^>]*aria-checked="false"[^>]*disabled=""/u);
  540. });
  541. // P2 回归:refresh 发起时 target 已不是当前 workspace,必须整体放弃——
  542. // 不得 set({loading:true}),否则结果因 key 不匹配被丢弃后 loading 永远不复位。
  543. it("discards a stale refresh before it starts and never claims loading", async () => {
  544. let releaseLoad: (() => void) | undefined;
  545. const gate = new Promise<void>((resolve) => {
  546. releaseLoad = resolve;
  547. });
  548. let loadCalls = 0;
  549. const service: IHooksService = {
  550. async loadHooks() {
  551. loadCalls += 1;
  552. await gate;
  553. return { hooks: [], hooksEnabled: false };
  554. },
  555. async saveHooks() {},
  556. };
  557. // store 当前停在 workspace B;refresh 携带的却是 A 的三元组(Trust 等待期间切走)。
  558. useHooksStore.setState({ workspacePath: "/workspace-b", workspaceIdentity: null });
  559. const pending = useHooksStore.getState().refresh(service, { workspacePath: "/workspace-a" });
  560. // 同步段过后 loading 必须仍为 false:过期请求无权占用全局 loading。
  561. expect(useHooksStore.getState().loading).toBe(false);
  562. releaseLoad?.();
  563. await pending;
  564. expect(loadCalls).toBe(0);
  565. expect(useHooksStore.getState().loading).toBe(false);
  566. });
  567. // P2 回归:refresh 等待期间切走 → 结果丢弃,但 loading 归新 workspace 的
  568. // initialize 所有,丢弃路径不得把 loading 复位成影响新投影的状态。
  569. it("leaves loading ownership to the new workspace when refresh target drifts mid-flight", async () => {
  570. let releaseLoad: (() => void) | undefined;
  571. const gate = new Promise<void>((resolve) => {
  572. releaseLoad = resolve;
  573. });
  574. const service: IHooksService = {
  575. async loadHooks(params) {
  576. if (params.workspacePath === "/workspace-a") {
  577. await gate;
  578. return { hooks: [], hooksEnabled: false };
  579. }
  580. return { hooks: [configuredHook()], hooksEnabled: true };
  581. },
  582. async saveHooks() {},
  583. };
  584. useHooksStore.setState({ workspacePath: "/workspace-a", workspaceIdentity: null });
  585. const refreshA = useHooksStore.getState().refresh(service, { workspacePath: "/workspace-a" });
  586. // A 的 load 挂起期间切到 B 并完成 B 的 initialize(loading=true 属于 B 的加载)。
  587. const initB = useHooksStore.getState().initialize("/workspace-b", undefined, service);
  588. releaseLoad?.();
  589. await Promise.all([refreshA, initB]);
  590. // B 的投影完好,A 的过期结果没有污染;loading 最终由 B 的生命周期复位。
  591. expect(useHooksStore.getState().loadedWorkspaceKey).toBe("/workspace-b");
  592. expect(useHooksStore.getState().loading).toBe(false);
  593. });
  594. });
  595. describe("resolveLatestReviewScopeTarget", () => {
  596. const tabs = [
  597. { workspacePath: "/local/repo", workspaceIdentity: undefined },
  598. { workspacePath: "/remote/repo", workspaceIdentity: "ssh://dev/remote/repo" },
  599. ];
  600. it("maps the latest binding to a known workspace scope key by identity", () => {
  601. const target = resolveLatestReviewScopeTarget(
  602. {
  603. s1: {
  604. request: { interactionId: "i-1", createdAt: 1, workspaceIdentity: "ssh://dev/remote/repo" },
  605. workspacePath: "/remote/repo",
  606. },
  607. },
  608. tabs,
  609. );
  610. expect(target).toEqual({ interactionId: "i-1", scopeKey: "ssh://dev/remote/repo" });
  611. });
  612. it("falls back to workspacePath matching only for identity-less legacy bindings", () => {
  613. const target = resolveLatestReviewScopeTarget(
  614. {
  615. s1: {
  616. request: { interactionId: "i-2", createdAt: 2, workspaceIdentity: undefined },
  617. workspacePath: "/local/repo",
  618. },
  619. },
  620. tabs,
  621. );
  622. expect(target).toEqual({ interactionId: "i-2", scopeKey: "/local/repo" });
  623. });
  624. it("picks the newest interaction when multiple bindings exist", () => {
  625. const target = resolveLatestReviewScopeTarget(
  626. {
  627. s1: {
  628. request: { interactionId: "i-old", createdAt: 1, workspaceIdentity: "ssh://dev/remote/repo" },
  629. workspacePath: "/remote/repo",
  630. },
  631. s2: {
  632. request: { interactionId: "i-new", createdAt: 5, workspaceIdentity: undefined },
  633. workspacePath: "/local/repo",
  634. },
  635. },
  636. tabs,
  637. );
  638. expect(target).toEqual({ interactionId: "i-new", scopeKey: "/local/repo" });
  639. });
  640. // P2 回归:binding 指向已关闭/未知的 workspace 时返回 null——调用方不得
  641. // 把 scope 切过去(否则设置页会持续停在 Connecting,且与失效 scope 重置 user
  642. // 的 effect 形成乒乓循环)。
  643. it("returns null when the binding workspace no longer exists in tabs", () => {
  644. const target = resolveLatestReviewScopeTarget(
  645. {
  646. s1: {
  647. request: { interactionId: "i-gone", createdAt: 3, workspaceIdentity: "ssh://gone/repo" },
  648. workspacePath: "/gone/repo",
  649. },
  650. },
  651. tabs,
  652. );
  653. expect(target).toBeNull();
  654. });
  655. it("returns null when there are no bindings", () => {
  656. expect(resolveLatestReviewScopeTarget({}, tabs)).toBeNull();
  657. });
  658. });
  659. function configuredHook(): Hook {
  660. return {
  661. id: "configured",
  662. event: "PreToolUse",
  663. matcher: "Write",
  664. type: "process",
  665. command: "node",
  666. args: ["hook.mjs"],
  667. enabled: true,
  668. location: {
  669. source: "zcode",
  670. scope: "project",
  671. directoryPath: "/workspace/.zcode",
  672. projectPath: "/workspace",
  673. },
  674. };
  675. }
  676. function workspaceConfiguredHook(
  677. trustState: NonNullable<NonNullable<Hook["workspaceHook"]>["trustState"]>,
  678. ): Hook {
  679. return {
  680. ...configuredHook(),
  681. workspaceHook: {
  682. reviewItemId: "configured",
  683. workspaceIdentity: "local:/workspace",
  684. bundleDigest: "b".repeat(64),
  685. hookDeclarationDigest: "a".repeat(64),
  686. sourceFileIndex: 0,
  687. sourceRootEnabled: true,
  688. declarationEnabled: true,
  689. runtimeHooksEnabled: true,
  690. configuredEnabled: true,
  691. sourcePath: ".zcode/config.json",
  692. trustState,
  693. },
  694. };
  695. }