rootNewTaskWorkbenchContext.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. // @vitest-environment jsdom
  2. import { act, renderHook } from "@testing-library/react";
  3. import { beforeEach, describe, expect, it, vi } from "vitest";
  4. import { readV4ComposerDraft } from "@/v4/composer/composerDraftStore.js";
  5. import type { CreateTaskOptions } from "@/app-shell/types.js";
  6. import { useRootWorkspaceActions } from "@/root/useRootWorkspaceActions.js";
  7. import { useZCodeSessionStore } from "@/store/zcodeSessionStore.js";
  8. import { onTaskNavigationCommitted } from "@/store/zcodeSessionStoreNavigation.js";
  9. import {
  10. INITIAL_PANE_LAYOUT,
  11. V4_PRIMARY_PANE_ID,
  12. countPanes,
  13. usePaneLayoutStore,
  14. } from "@/v4/paneLayoutStore.js";
  15. import { useWorkbenchGroupStore } from "@/v4/workbenchGroupStore.js";
  16. function fixture(
  17. clientMode: "desktop-continuous" | "web-remote-replayable" = "desktop-continuous",
  18. openRemoteProjectWorkspace?: (target: {
  19. workspacePath: string;
  20. workspaceIdentity?: string;
  21. hostId: string;
  22. }) => Promise<void>,
  23. openMobileProjectDraft?: (request: CreateTaskOptions) => Promise<void>,
  24. ) {
  25. let next = 0;
  26. const prepared = new Map<string, string>();
  27. const prepareSession = vi.fn(
  28. async (input?: {
  29. projectId?: string;
  30. draftId?: string;
  31. reuseDraft?: boolean;
  32. hostId?: string;
  33. }) => {
  34. const path = input?.projectId
  35. ? "/project-primary"
  36. : (input?.draftId && prepared.get(input.draftId)) || `/managed/${++next}`;
  37. if (input?.draftId) prepared.set(input.draftId, path);
  38. return {
  39. workspacePath: path,
  40. projectId: input?.projectId ?? null,
  41. additionalDirectories: [],
  42. };
  43. },
  44. );
  45. const readTree = vi.fn(async (_input?: unknown) => ({
  46. tasks: [] as {
  47. taskId: string;
  48. workspacePath: string;
  49. workspaceIdentity?: string;
  50. projectId: string | null;
  51. }[],
  52. }));
  53. const addTab = vi.fn();
  54. const state = {
  55. tabs: [],
  56. activeWorkspacePath: "/old",
  57. activeWorkspaceIdentity: null,
  58. activateTabByPath: vi.fn(() => true),
  59. };
  60. const options = {
  61. intl: { formatMessage: ({ id }: { id: string }) => id } as never,
  62. platform: {} as never,
  63. services: { projectService: { prepareSession, readTree } } as never,
  64. tabStoreApi: { getState: () => state } as never,
  65. addTab,
  66. activeWorkspacePath: "/old",
  67. activeWorkspaceIdentity: null,
  68. supportsSettings: true,
  69. allowOpenWorkspace: true,
  70. preferDirectoryBrowser: false,
  71. refreshProviderState: vi.fn(),
  72. updateAppSettings: vi.fn(),
  73. setOAuthError: vi.fn(),
  74. setUser: vi.fn(),
  75. workbenchGroupClientMode: clientMode,
  76. openMobileProjectDraft,
  77. };
  78. const { result, rerender } = renderHook(
  79. ({ opener }) => useRootWorkspaceActions({ ...options, openRemoteProjectWorkspace: opener }),
  80. { initialProps: { opener: openRemoteProjectWorkspace } },
  81. );
  82. return { result, rerender, prepareSession, readTree, addTab, state };
  83. }
  84. beforeEach(() => {
  85. localStorage.clear();
  86. useZCodeSessionStore.setState({ workspaces: {} });
  87. usePaneLayoutStore.setState(INITIAL_PANE_LAYOUT);
  88. useWorkbenchGroupStore.getState().resetWorkbenchGroups();
  89. });
  90. describe("project-aware new task creation", () => {
  91. it("keeps new-task callbacks stable while using the latest committed remote opener", async () => {
  92. const previous = vi.fn(async () => {});
  93. const latest = vi.fn(async () => {});
  94. const { result, rerender, prepareSession } = fixture("desktop-continuous", previous);
  95. const create = result.current.handleCreateTask;
  96. const createConversation = result.current.handleCreateConversationTask;
  97. rerender({ opener: latest });
  98. expect(result.current.handleCreateTask).toBe(create);
  99. expect(result.current.handleCreateConversationTask).toBe(createConversation);
  100. prepareSession.mockResolvedValueOnce({
  101. workspacePath: "/remote",
  102. workspaceIdentity: "remote:server:s:/remote",
  103. projectId: "p",
  104. additionalDirectories: [],
  105. } as never);
  106. await act(async () => create({ projectId: "p", hostId: "remote:server:s" }));
  107. expect(previous).not.toHaveBeenCalled();
  108. expect(latest).toHaveBeenCalledWith(
  109. expect.objectContaining({ workspaceIdentity: "remote:server:s:/remote", projectId: "p" }),
  110. );
  111. });
  112. it.each([true, false])(
  113. "publishes a settings return only after tab activation succeeds (%s)",
  114. (activated) => {
  115. useZCodeSessionStore.getState().setActiveTaskId("/old", "old-session");
  116. const { result, state } = fixture();
  117. state.activateTabByPath.mockReturnValue(activated);
  118. const history = useZCodeSessionStore.getState().taskNavHistory;
  119. const viewed = vi.fn();
  120. const subscription = onTaskNavigationCommitted(viewed);
  121. try {
  122. act(() => result.current.handleBackFromSettings());
  123. expect(viewed).toHaveBeenCalledTimes(activated ? 1 : 0);
  124. if (activated)
  125. expect(viewed).toHaveBeenCalledWith({
  126. kind: "task",
  127. workspacePath: "/old",
  128. taskId: "old-session",
  129. workspaceIdentity: undefined,
  130. });
  131. expect(useZCodeSessionStore.getState().taskNavHistory).toBe(history);
  132. } finally {
  133. subscription.dispose();
  134. }
  135. },
  136. );
  137. it("routes the selected Host and binds its attachment before creating a draft under the returned identity", async () => {
  138. const open = vi.fn(async () => {});
  139. const { result, prepareSession, addTab } = fixture("desktop-continuous", open);
  140. prepareSession.mockResolvedValueOnce({
  141. workspacePath: "/remote",
  142. workspaceIdentity: "remote:server:s:/remote",
  143. projectId: "p",
  144. additionalDirectories: [],
  145. } as never);
  146. await act(async () => {
  147. await result.current.handleCreateTask({ projectId: "p", hostId: "remote:server:s" });
  148. });
  149. expect(prepareSession).toHaveBeenCalledWith({ projectId: "p", hostId: "remote:server:s" });
  150. expect(open).toHaveBeenCalledWith(
  151. expect.objectContaining({
  152. hostId: "remote:server:s",
  153. workspacePath: "/remote",
  154. workspaceIdentity: "remote:server:s:/remote",
  155. }),
  156. );
  157. expect(addTab).not.toHaveBeenCalled();
  158. expect(
  159. useZCodeSessionStore.getState().getWorkspaceState("/remote", "remote:server:s:/remote")
  160. .draftProjectId,
  161. ).toBe("p");
  162. expect(useZCodeSessionStore.getState().workspaces["/remote"]).toBeUndefined();
  163. });
  164. it.each(["desktop-continuous"] as const)(
  165. "PD01 连续新建复用未发送目录,显式 local Host 也保持同一身份(%s)",
  166. async (mode) => {
  167. useZCodeSessionStore.getState().setActiveTaskId("/old", "old-session");
  168. const { result, prepareSession, addTab } = fixture(mode);
  169. await act(async () => {
  170. await result.current.handleCreateTask({ projectId: null, hostId: "local" });
  171. await result.current.handleCreateTask({ projectId: null, hostId: "local" });
  172. });
  173. expect(prepareSession).toHaveBeenCalledTimes(2);
  174. expect(addTab).toHaveBeenNthCalledWith(1, "/managed/1", { workspacePurpose: "conversation" });
  175. expect(addTab).toHaveBeenNthCalledWith(2, "/managed/1", { workspacePurpose: "conversation" });
  176. expect(
  177. useZCodeSessionStore.getState().getWorkspaceState("/managed/1").draftProjectId,
  178. ).toBeNull();
  179. expect(useZCodeSessionStore.getState().getWorkspaceState("/old").activeTaskId).toBe(
  180. "old-session",
  181. );
  182. },
  183. );
  184. it("uses the selected project primary directory, exits split view and preserves mention spacing", async () => {
  185. const { result, prepareSession } = fixture();
  186. usePaneLayoutStore.getState().splitPaneWithBinding(V4_PRIMARY_PANE_ID, "right", {
  187. workspaceScope: { workspacePath: "/unrelated" },
  188. sessionId: "another",
  189. });
  190. const mention = {
  191. id: "skill:creator",
  192. category: "skills" as const,
  193. label: "creator",
  194. value: "creator",
  195. markdown: "$creator",
  196. };
  197. await act(async () => {
  198. await result.current.handleCreateTask({
  199. projectId: "project-a",
  200. initialPrompt: "$creator ",
  201. initialPromptMention: mention,
  202. });
  203. });
  204. expect(prepareSession).toHaveBeenCalledWith({ projectId: "project-a" });
  205. const draft = useZCodeSessionStore.getState().getWorkspaceState("/project-primary");
  206. expect(draft.draftProjectId).toBe("project-a");
  207. expect(draft.composerTextInsertRequest).toMatchObject({ text: "$creator ", mention });
  208. expect(countPanes(usePaneLayoutStore.getState())).toBe(1);
  209. expect(useWorkbenchGroupStore.getState().activeGroupId).toBeNull();
  210. });
  211. it("leaves the current session intact when directory preparation fails", async () => {
  212. useZCodeSessionStore.getState().setActiveTaskId("/old", "old-session");
  213. const { result, prepareSession, addTab } = fixture();
  214. prepareSession.mockRejectedValueOnce(new Error("directory unavailable"));
  215. await act(async () => {
  216. await result.current.handleCreateTask();
  217. });
  218. expect(addTab).not.toHaveBeenCalled();
  219. expect(useZCodeSessionStore.getState().getWorkspaceState("/old").activeTaskId).toBe(
  220. "old-session",
  221. );
  222. expect(result.current.workspaceActionError).toContain("directory unavailable");
  223. });
  224. });
  225. it("hands mobile project intent to the bridge owner without preparing or mutating the old Root", async () => {
  226. let finish!: () => void;
  227. const openMobileProjectDraft = vi.fn(
  228. () =>
  229. new Promise<void>((resolve) => {
  230. finish = resolve;
  231. }),
  232. );
  233. const { result, prepareSession, addTab } = fixture(
  234. "web-remote-replayable",
  235. undefined,
  236. openMobileProjectDraft,
  237. );
  238. useZCodeSessionStore.getState().setActiveTaskId("/old", "old-session");
  239. const request = { projectId: "p", hostId: "remote:server:s", initialPrompt: "$creator " };
  240. let pending!: Promise<void>;
  241. await act(async () => {
  242. pending = result.current.handleCreateTask(request);
  243. });
  244. expect(openMobileProjectDraft).toHaveBeenCalledWith(request);
  245. expect(prepareSession).not.toHaveBeenCalled();
  246. useZCodeSessionStore
  247. .getState()
  248. .startDraft("/new", undefined, "remote:server:s:/new", { projectId: "p" });
  249. await act(async () => {
  250. finish();
  251. await pending;
  252. });
  253. expect(addTab).not.toHaveBeenCalled();
  254. expect(useZCodeSessionStore.getState().getWorkspaceState("/old").activeTaskId).toBe(
  255. "old-session",
  256. );
  257. expect(
  258. useZCodeSessionStore.getState().getWorkspaceState("/new", "remote:server:s:/new")
  259. .draftProjectId,
  260. ).toBe("p");
  261. });
  262. it("initializes a handed off draft with its project and exact input under the new identity", () => {
  263. const { result } = fixture("web-remote-replayable");
  264. const mention = {
  265. id: "skill:creator",
  266. category: "skills" as const,
  267. label: "creator",
  268. value: "creator",
  269. markdown: "$creator",
  270. };
  271. act(() =>
  272. result.current.startDraftInWorkspace("/new", "remote:server:s:/new", {
  273. projectId: "p",
  274. provider: "zcode",
  275. initialPrompt: "$creator ",
  276. initialPromptMention: mention,
  277. }),
  278. );
  279. const draft = useZCodeSessionStore.getState().getWorkspaceState("/new", "remote:server:s:/new");
  280. expect(draft.draftProjectId).toBe("p");
  281. expect(draft.composerTextInsertRequest).toMatchObject({ text: "$creator ", mention });
  282. expect(useZCodeSessionStore.getState().workspaces["/new"]).toBeUndefined();
  283. });
  284. it("does not allocate a directory when the mobile peer lacks project admission", async () => {
  285. const { result, prepareSession, addTab } = fixture("web-remote-replayable");
  286. await act(async () => {
  287. await result.current.handleCreateTask();
  288. });
  289. expect(prepareSession).not.toHaveBeenCalled();
  290. expect(addTab).not.toHaveBeenCalled();
  291. expect(result.current.workspaceActionError).toBe("project.remote-navigation-unavailable");
  292. });
  293. it.each(["desktop-continuous", "web-remote-replayable"] as const)(
  294. "TD07 %s 空白创建意图只留在内存,文字出现时才保存项目和分组",
  295. (mode) => {
  296. const { result } = fixture(mode);
  297. act(() =>
  298. result.current.startDraftInWorkspace("/metadata", "remote:server:s:/metadata", {
  299. projectId: "p",
  300. taskGroupId: "g",
  301. }),
  302. );
  303. expect(
  304. useZCodeSessionStore.getState().getWorkspaceState("/metadata", "remote:server:s:/metadata"),
  305. ).toMatchObject({ draftProjectId: "p", draftTaskGroupId: "g" });
  306. expect(
  307. readV4ComposerDraft("/metadata", "remote:server:s:/metadata", "__draft__", {
  308. clientNamespace: "desktop",
  309. hostId: "remote:server:s",
  310. projectId: "p",
  311. }),
  312. ).toBeNull();
  313. act(() =>
  314. result.current.startDraftInWorkspace("/metadata", "remote:server:s:/metadata", {
  315. projectId: "p",
  316. taskGroupId: "g",
  317. initialPrompt: "draft",
  318. }),
  319. );
  320. expect(
  321. readV4ComposerDraft("/metadata", "remote:server:s:/metadata", "__draft__", {
  322. clientNamespace: "desktop",
  323. hostId: "remote:server:s",
  324. projectId: "p",
  325. }),
  326. ).toMatchObject({ text: "draft", projectId: "p", taskGroupId: "g" });
  327. },
  328. );
  329. it.each(["desktop-continuous", "web-remote-replayable"] as const)(
  330. "D3 %s inherits the current session project by exact task identity",
  331. async (mode) => {
  332. useZCodeSessionStore.getState().setActiveTaskId("/old", "session");
  333. const open = vi.fn(async () => {});
  334. const { result, prepareSession, readTree } = fixture(mode, undefined, open);
  335. readTree.mockResolvedValueOnce({
  336. tasks: [
  337. { taskId: "session", workspacePath: "/other", projectId: "wrong" },
  338. { taskId: "session", workspacePath: "/old", projectId: "current" },
  339. ],
  340. });
  341. await act(async () => {
  342. await result.current.handleCreateTask();
  343. });
  344. if (mode === "desktop-continuous") {
  345. expect(prepareSession).toHaveBeenCalledWith({ projectId: "current" });
  346. } else {
  347. expect(open).toHaveBeenCalledWith({ projectId: "current" });
  348. expect(prepareSession).not.toHaveBeenCalled();
  349. }
  350. },
  351. );
  352. it("D3 inherits draft project without reading task history; explicit null opts out", async () => {
  353. useZCodeSessionStore
  354. .getState()
  355. .startDraft("/old", undefined, undefined, { projectId: "draft-project" });
  356. const { result, prepareSession, readTree } = fixture();
  357. await act(async () => {
  358. await result.current.handleCreateTask();
  359. });
  360. expect(prepareSession).toHaveBeenLastCalledWith({ projectId: "draft-project" });
  361. expect(readTree).not.toHaveBeenCalled();
  362. await act(async () => {
  363. await result.current.handleCreateTask({ projectId: null });
  364. });
  365. expect(prepareSession).toHaveBeenLastCalledWith({
  366. draftId: expect.any(String),
  367. reuseDraft: false,
  368. });
  369. });
  370. it("D3 discards project lookup after the user selects another session", async () => {
  371. useZCodeSessionStore.getState().setActiveTaskId("/old", "session");
  372. const { result, prepareSession, readTree, addTab } = fixture();
  373. let finish!: (tree: Awaited<ReturnType<typeof readTree>>) => void;
  374. readTree.mockImplementationOnce(
  375. () =>
  376. new Promise((resolve) => {
  377. finish = resolve;
  378. }),
  379. );
  380. let pending!: Promise<void>;
  381. await act(async () => {
  382. pending = result.current.handleCreateTask();
  383. });
  384. act(() => useZCodeSessionStore.getState().setActiveTaskId("/old", "other"));
  385. await act(async () => {
  386. finish({ tasks: [{ taskId: "session", workspacePath: "/old", projectId: "current" }] });
  387. await pending;
  388. });
  389. expect(prepareSession).not.toHaveBeenCalled();
  390. expect(addTab).not.toHaveBeenCalled();
  391. });