rootNewTaskWorkbenchContext.test.ts 18 KB

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