workspaceHeaderTitleSection.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. // @vitest-environment jsdom
  2. import { render, cleanup, act } from "@testing-library/react";
  3. import { useRemoteWorkspaceSessionStore } from "@/store/remoteWorkspaceSessionStore.js";
  4. import { RemoteProjectPresentationProvider } from "@/hooks/RemoteProjectPresentationContext.js";
  5. import { getSourceServerStatusRegistry } from "@/store/sourceServerStatusRegistry.js";
  6. import { getSourceServerDisplayNameRegistry } from "@/store/sourceServerDisplayNameRegistry.js";
  7. import { createElement, type ReactNode } from "react";
  8. import { renderToStaticMarkup } from "react-dom/server";
  9. import { describe, expect, it, vi } from "vitest";
  10. import {
  11. TID_WORKSPACE_MORE_BUTTON,
  12. TID_WORKSPACE_PATH,
  13. TID_WORKSPACE_TITLE,
  14. } from "@zcode/shared/test-ids";
  15. const headerManagement = vi.hoisted(() => ({
  16. getSnapshot: vi.fn(async () => ({
  17. servers: [
  18. {
  19. sourceServerId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
  20. displayName: "Dev",
  21. installState: "installed",
  22. },
  23. ],
  24. profiles: [
  25. {
  26. profileId: "p",
  27. sourceServerId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
  28. target: { kind: "ssh", host: "dev", username: "user" },
  29. },
  30. ],
  31. states: [{ profileId: "p", state: "online", updatedAt: 1 }],
  32. })),
  33. onDidChangeState: () => ({ dispose() {} }),
  34. onDidChangeDirectory: () => ({ dispose() {} }),
  35. }));
  36. const capturedGitBranchSwitcherProps = vi.hoisted(() => [] as Array<Record<string, unknown>>);
  37. vi.mock("lucide-react", async (importOriginal) => {
  38. const actual = await importOriginal<typeof import("lucide-react")>();
  39. const createIcon = (name: string) => (props: Record<string, unknown>) =>
  40. createElement("svg", { "data-icon": name, ...props });
  41. // 共享组件(RemoteSyncActions 等)的图标随迭代增减,枚举 mock 会反复缺导出;
  42. // 保留既有命名映射,其余图标名用 Proxy 兜底为占位 svg。
  43. const icons: Record<string, unknown> = {
  44. ...actual,
  45. Cloud: createIcon("cloud"),
  46. Ellipsis: createIcon("ellipsis"),
  47. Folder: createIcon("folder"),
  48. GitBranch: createIcon("git-branch"),
  49. LoaderIcon: createIcon("loader"),
  50. UploadCloud: createIcon("upload-cloud"),
  51. };
  52. return new Proxy(icons, {
  53. // vitest 对具名导出做 `in` 检查,动态图标必须声明存在。
  54. has: (target, name) => typeof name === "string" || Reflect.has(target, name),
  55. get: (target, name) => {
  56. if (typeof name !== "string") return Reflect.get(target, name);
  57. if (name === "default" || name === "then" || name === "__esModule") {
  58. return Reflect.get(target, name);
  59. }
  60. return (
  61. target[name] ??
  62. createIcon(
  63. name
  64. .replace(/Icon$/u, "")
  65. .replace(/([a-z0-9])([A-Z])/gu, "$1-$2")
  66. .toLowerCase(),
  67. )
  68. );
  69. },
  70. });
  71. });
  72. vi.mock("@/ControlHintTooltip.js", () => ({
  73. ControlHintTooltip: ({ children }: { children: ReactNode }) => children,
  74. }));
  75. vi.mock("@/components/ui/button.js", () => ({
  76. Button: ({ children, ...props }: { children: ReactNode }) =>
  77. createElement("button", props, children),
  78. }));
  79. vi.mock("@/components/ui/dialog.js", () => ({
  80. Dialog: ({ children }: { children: ReactNode }) => createElement("div", null, children),
  81. DialogContent: ({ children }: { children: ReactNode }) => createElement("div", null, children),
  82. DialogFooter: ({ children }: { children: ReactNode }) => createElement("div", null, children),
  83. DialogHeader: ({ children }: { children: ReactNode }) => createElement("div", null, children),
  84. DialogTitle: ({ children }: { children: ReactNode }) => createElement("div", null, children),
  85. }));
  86. vi.mock("@/components/ui/dropdown-menu.js", () => ({
  87. DropdownMenu: ({ children }: { children: ReactNode }) =>
  88. createElement("div", { "data-testid": "dropdown-menu" }, children),
  89. DropdownMenuContent: ({ children }: { children: ReactNode }) =>
  90. createElement("div", { "data-testid": "dropdown-content" }, children),
  91. DropdownMenuItem: ({ children }: { children: ReactNode }) =>
  92. createElement("div", { "data-testid": "dropdown-item" }, children),
  93. DropdownMenuSeparator: () => createElement("hr"),
  94. DropdownMenuTrigger: ({ children }: { children: ReactNode }) => children,
  95. }));
  96. vi.mock("@/components/ui/input.js", () => ({
  97. Input: (props: Record<string, unknown>) => createElement("input", props),
  98. }));
  99. vi.mock("@/components/ui/toast.js", () => ({
  100. toast: vi.fn(),
  101. }));
  102. vi.mock("@/GitBranchSwitcher.js", () => ({
  103. GitBranchSwitcher: (props: Record<string, unknown>) => {
  104. capturedGitBranchSwitcherProps.push(props);
  105. return createElement("span", {
  106. "data-testid": "git-branch",
  107. "data-trigger-class-name": String(props.triggerClassName ?? ""),
  108. });
  109. },
  110. }));
  111. vi.mock("@/TaskActionMenuContent.js", () => ({
  112. TaskActionMenuContent: () => createElement("div", { "data-testid": "task-action-menu" }),
  113. }));
  114. vi.mock("@/settings/RemoteSkillSyncDialog.js", () => ({
  115. RemoteSkillSyncDialog: () => createElement("div", { "data-testid": "remote-skill-sync-dialog" }),
  116. }));
  117. vi.mock("@/settings/RemoteMcpSyncDialog.js", () => ({
  118. RemoteMcpSyncDialog: () => createElement("div", { "data-testid": "remote-mcp-sync-dialog" }),
  119. }));
  120. vi.mock("@/settings/RemotePluginSyncDialog.js", () => ({
  121. RemotePluginSyncDialog: () =>
  122. createElement("div", { "data-testid": "remote-plugin-sync-dialog" }),
  123. }));
  124. vi.mock("@/hooks/useConfirmDialog.js", () => ({
  125. useConfirmDialog: () => vi.fn(async () => true),
  126. }));
  127. vi.mock("@/hooks/useGlobalTaskList.js", () => ({
  128. useGlobalTaskList: () => ({ items: [], loading: false }),
  129. }));
  130. vi.mock("@/hooks/usePlatform.js", () => ({
  131. usePlatform: () => ({}),
  132. }));
  133. vi.mock("@/hooks/useWorkspaceServices.js", () => ({
  134. // Bugfix: Header 现在同时读取 workspace services 和 base services;
  135. // 测试 mock 需要覆盖同模块全部被用到的 hook,避免新增导出后静态渲染直接崩溃。
  136. useBaseWorkspaceServices: () => ({
  137. sourceServerManagementService: headerManagement,
  138. skillSyncService: {},
  139. mcpSyncService: {},
  140. pluginSyncService: {},
  141. }),
  142. useWorkspaceServices: () => ({
  143. skillSyncService: {},
  144. mcpSyncService: {},
  145. pluginSyncService: {},
  146. zcodeTaskService: {
  147. archiveTask: vi.fn(),
  148. renameTask: vi.fn(),
  149. setTaskPinned: vi.fn(),
  150. setTaskUnread: vi.fn(),
  151. },
  152. }),
  153. }));
  154. vi.mock("@/useTaskListItemContextActions.js", () => ({
  155. useTaskListItemContextActions: () => ({
  156. taskSessionFile: { path: "/tmp/session.json", exists: true },
  157. taskNativeSessionLogFile: { path: "/tmp/session.log", exists: true },
  158. providerConfigFile: { path: "/tmp/provider.json", exists: true },
  159. fileManagerLabel: "Finder",
  160. handleCopyText: vi.fn(),
  161. handleOpenTaskPathInFileManager: vi.fn(),
  162. handleOpenProviderConfig: vi.fn(),
  163. }),
  164. }));
  165. vi.mock("@/i18n/IntlProvider.js", () => ({
  166. useZCodeIntl: () => ({
  167. intl: {
  168. formatMessage: ({ id }: { id: string }) => id,
  169. },
  170. }),
  171. }));
  172. vi.mock("@/feedback/feedbackStore.js", () => ({
  173. useFeedbackStore: (selector: (state: { openSubmit: () => void }) => unknown) =>
  174. selector({ openSubmit: vi.fn() }),
  175. }));
  176. vi.mock("@/store/taskQueryCacheStore.js", () => ({
  177. applyTaskQueryCacheMutation: vi.fn(),
  178. }));
  179. vi.mock("@/store/zcodeSessionStore.js", () => ({
  180. useZCodeSessionStore: (selector: (state: Record<string, unknown>) => unknown) =>
  181. selector({
  182. removeTaskState: vi.fn(),
  183. removeOptimisticTaskListItem: vi.fn(),
  184. setTaskUnreadIndicator: vi.fn(),
  185. upsertOptimisticTaskListItem: vi.fn(),
  186. }),
  187. }));
  188. vi.mock("@/store/modelTrajectoryStore.js", () => ({
  189. useModelTrajectoryStore: {
  190. getState: () => ({
  191. requestOpen: vi.fn(),
  192. }),
  193. },
  194. }));
  195. describe("WorkspaceHeaderTitleSection", () => {
  196. it("hides task-only title, context and menus in the local draft variant", async () => {
  197. capturedGitBranchSwitcherProps.length = 0;
  198. const { WorkspaceHeaderTitleSection } = await import("@/WorkspaceHeaderSections.js");
  199. const html = renderToStaticMarkup(
  200. createElement(WorkspaceHeaderTitleSection, {
  201. variant: "draft",
  202. workspaceAbsPath: "/workspace/zcode-cli",
  203. projectName: "zcode-cli",
  204. activeTaskTitle: "New task",
  205. activeTaskId: null,
  206. activeTraceId: null,
  207. activeSessionId: null,
  208. activeTaskProvider: null,
  209. gitSummary: { isRepository: true, branchName: "main" },
  210. gitDirtyFileCount: 0,
  211. sessionLogPath: null,
  212. nativeSessionLogProvider: null,
  213. nativeSessionLogPath: null,
  214. nativeSessionLogExists: false,
  215. nativeSessionLogLoading: false,
  216. providerWorkspaceConfigPath: null,
  217. providerWorkspaceConfigExists: false,
  218. providerWorkspaceConfigLoading: false,
  219. workspaceHeaderState: { selectedProvider: "codex" },
  220. selectedEditor: null,
  221. onRefreshGit: vi.fn(),
  222. }),
  223. );
  224. expect(html).not.toContain(`data-testid="${TID_WORKSPACE_TITLE}"`);
  225. expect(html).not.toContain(`data-testid="${TID_WORKSPACE_PATH}"`);
  226. expect(html).not.toContain(`data-testid="${TID_WORKSPACE_MORE_BUTTON}"`);
  227. expect(capturedGitBranchSwitcherProps).toHaveLength(0);
  228. });
  229. it("places the workspace icon before the title and removes the inline branch in mobile mode", async () => {
  230. capturedGitBranchSwitcherProps.length = 0;
  231. const { WorkspaceHeaderTitleSection } = await import("@/WorkspaceHeaderSections.js");
  232. const html = renderToStaticMarkup(
  233. createElement(WorkspaceHeaderTitleSection, {
  234. workspaceAbsPath: "/workspace/zcode-cli",
  235. projectName: "zcode-cli",
  236. activeTaskTitle: "hello",
  237. activeTaskId: "task-1",
  238. activeTraceId: "trace-1",
  239. activeSessionId: "session-1",
  240. activeTaskProvider: "glm",
  241. gitSummary: {
  242. isGitAvailable: true,
  243. isRepository: true,
  244. branchName: "main",
  245. headRefType: "branch",
  246. },
  247. gitDirtyFileCount: 0,
  248. sessionLogPath: null,
  249. nativeSessionLogProvider: null,
  250. nativeSessionLogPath: null,
  251. nativeSessionLogExists: false,
  252. nativeSessionLogLoading: false,
  253. providerWorkspaceConfigPath: null,
  254. providerWorkspaceConfigExists: false,
  255. providerWorkspaceConfigLoading: false,
  256. workspaceHeaderState: { selectedProvider: "glm" },
  257. selectedEditor: null,
  258. simplifyForNarrowRemote: true,
  259. onRefreshGit: vi.fn(),
  260. }),
  261. );
  262. expect(capturedGitBranchSwitcherProps).toHaveLength(0);
  263. expect(html).toContain('data-icon="folder"');
  264. expect(html).toContain('aria-label="zcode-cli · main"');
  265. // 回归保护:aria-label 只有显示名,e2e 判定“header 属于哪个工作区”依赖这个绝对路径
  266. // 数据属性。上一次它以 DOM title 形式存在,被 tooltip 重构顺手删掉后无人发现。
  267. expect(html).toContain('data-workspace-abs-path="/workspace/zcode-cli"');
  268. expect(html.indexOf(`data-testid="${TID_WORKSPACE_PATH}"`)).toBeLessThan(
  269. html.indexOf(`data-testid="${TID_WORKSPACE_TITLE}"`),
  270. );
  271. });
  272. it.each(["task", "draft"] as const)(
  273. "keeps device context visible in the remote %s header",
  274. async (variant) => {
  275. const { WorkspaceHeaderTitleSection } = await import("@/WorkspaceHeaderSections.js");
  276. const html = renderToStaticMarkup(
  277. createElement(WorkspaceHeaderTitleSection, {
  278. variant,
  279. workspaceAbsPath: "/root",
  280. remoteSessionId: "remote-session-1",
  281. workspaceIdentity: "remote:ssh:localhost:2223:root:/root",
  282. remoteTarget: {
  283. kind: "ssh",
  284. host: "localhost",
  285. port: 2223,
  286. username: "root",
  287. sshConfigAlias: "linux-arm64",
  288. },
  289. projectName: "root",
  290. activeTaskTitle: "hello",
  291. activeTaskId: "task-1",
  292. activeTraceId: "trace-1",
  293. activeSessionId: "session-1",
  294. activeTaskProvider: "glm",
  295. gitSummary: { isRepository: false },
  296. gitDirtyFileCount: 0,
  297. sessionLogPath: null,
  298. nativeSessionLogProvider: null,
  299. nativeSessionLogPath: null,
  300. nativeSessionLogExists: false,
  301. nativeSessionLogLoading: false,
  302. providerWorkspaceConfigPath: null,
  303. providerWorkspaceConfigExists: false,
  304. providerWorkspaceConfigLoading: false,
  305. workspaceHeaderState: { selectedProvider: "glm" },
  306. selectedEditor: null,
  307. onRefreshGit: vi.fn(),
  308. }),
  309. );
  310. expect(html).toContain('data-workspace-device-name=""');
  311. expect(html).toContain(">linux-arm64</span>");
  312. expect(html).toContain('aria-label="root"');
  313. expect(html).toContain('data-remote-state-icon="cloud-off"');
  314. expect(html).not.toContain("[SSH: linux-arm64]");
  315. expect(html).not.toContain(">root</span><span");
  316. },
  317. );
  318. it("shows Skills and MCP sync actions for connected SSH workspace header menu", async () => {
  319. const { WorkspaceHeaderTitleSection } = await import("@/WorkspaceHeaderSections.js");
  320. const html = renderToStaticMarkup(
  321. createElement(WorkspaceHeaderTitleSection, {
  322. workspaceAbsPath: "/root/folder1",
  323. remoteSessionId: "remote-session-1",
  324. workspaceIdentity: "remote:ssh:localhost:2223:root:/root/folder1",
  325. remoteTarget: {
  326. kind: "ssh",
  327. host: "localhost",
  328. port: 2223,
  329. username: "root",
  330. sshConfigAlias: "linux-arm64",
  331. },
  332. projectName: "folder1",
  333. activeTaskTitle: "hello",
  334. activeTaskId: "task-1",
  335. activeTraceId: "trace-1",
  336. activeSessionId: "session-1",
  337. activeTaskProvider: "glm",
  338. gitSummary: { isRepository: false },
  339. gitDirtyFileCount: 0,
  340. sessionLogPath: null,
  341. nativeSessionLogProvider: null,
  342. nativeSessionLogPath: null,
  343. nativeSessionLogExists: false,
  344. nativeSessionLogLoading: false,
  345. providerWorkspaceConfigPath: null,
  346. providerWorkspaceConfigExists: false,
  347. providerWorkspaceConfigLoading: false,
  348. workspaceHeaderState: { selectedProvider: "glm" },
  349. selectedEditor: null,
  350. onRefreshGit: vi.fn(),
  351. }),
  352. );
  353. // 同步菜单已按原型 L1197-1203 收敛为 remote.sync* key 与分化图标(wand/cable)。
  354. expect(html).toContain("remote.syncSkills");
  355. expect(html).toContain("remote.syncMcp");
  356. });
  357. });
  358. it.each([false, true])("头部读取项目错误/恢复事实(恢复=%s)", async (recovering) => {
  359. getSourceServerStatusRegistry(headerManagement as never);
  360. getSourceServerDisplayNameRegistry(headerManagement as never);
  361. await Promise.resolve();
  362. const { WorkspaceHeaderTitleSection } = await import("@/WorkspaceHeaderSections.js");
  363. const identity = "remote:server:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa:/srv";
  364. const child = createElement(WorkspaceHeaderTitleSection, {
  365. workspaceAbsPath: "/srv",
  366. workspaceIdentity: identity,
  367. remoteTarget: { kind: "ssh", host: "dev", username: "user" },
  368. projectName: "Project",
  369. activeTaskTitle: "task",
  370. activeTaskId: "task",
  371. activeTaskProvider: "glm",
  372. gitSummary: { isRepository: false },
  373. gitDirtyFileCount: 0,
  374. sessionLogPath: null,
  375. nativeSessionLogProvider: null,
  376. nativeSessionLogPath: null,
  377. nativeSessionLogExists: false,
  378. nativeSessionLogLoading: false,
  379. providerWorkspaceConfigPath: null,
  380. providerWorkspaceConfigExists: false,
  381. providerWorkspaceConfigLoading: false,
  382. workspaceHeaderState: { selectedProvider: "glm" },
  383. selectedEditor: null,
  384. onRefreshGit: vi.fn(),
  385. });
  386. const html = renderToStaticMarkup(
  387. createElement(RemoteProjectPresentationProvider, {
  388. reconnectingKeys: recovering ? [identity] : [],
  389. errors: { [identity]: "attachment failed" },
  390. recovery: recovering ? { [identity]: { mode: "automatic", attempt: 2, limit: 3 } } : {},
  391. children: child,
  392. }),
  393. );
  394. expect(html).toContain(
  395. recovering ? "workspaceSidebar.recoveringAutomaticAttempt" : "remote.status.failed",
  396. );
  397. expect(html).toContain(
  398. recovering ? "text-progress-surface-foreground" : "text-destructive-surface-foreground",
  399. );
  400. });
  401. const headerDirectory = vi.hoisted(() => ({ current: null as unknown }));
  402. vi.mock("@/project-sidebar/index.js", () => ({
  403. useOptionalProjectDirectory: () => headerDirectory.current,
  404. }));
  405. it("远控 Header 从身份索引读取连接并从同一 Host 读取名称,连接换代和删除会更新", async () => {
  406. const identity = "remote:server:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb:/srv";
  407. const store = useRemoteWorkspaceSessionStore;
  408. headerDirectory.current = {
  409. directory: {
  410. hosts: [
  411. {
  412. id: "remote:server:other",
  413. target: { kind: "ssh", host: "wrong.example", username: "dev" },
  414. },
  415. {
  416. id: "remote:server:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
  417. target: {
  418. kind: "ssh",
  419. host: "right.example",
  420. username: "dev",
  421. sshConfigAlias: "Remote Dev",
  422. },
  423. },
  424. ],
  425. },
  426. };
  427. store.getState().registerSession({ sessionId: "bridge", services: {} as never });
  428. store.getState().bindWorkspaceIdentity(identity, "bridge");
  429. const { WorkspaceHeaderTitleSection } = await import("@/WorkspaceHeaderSections.js");
  430. const props = {
  431. workspaceAbsPath: "/srv",
  432. workspaceIdentity: identity,
  433. projectName: "Project",
  434. activeTaskTitle: "task",
  435. activeTaskId: "task",
  436. activeTraceId: null,
  437. activeSessionId: null,
  438. activeTaskProvider: null,
  439. gitSummary: { isRepository: false },
  440. gitDirtyFileCount: 0,
  441. sessionLogPath: null,
  442. nativeSessionLogProvider: null,
  443. nativeSessionLogPath: null,
  444. nativeSessionLogExists: false,
  445. nativeSessionLogLoading: false,
  446. providerWorkspaceConfigPath: null,
  447. providerWorkspaceConfigExists: false,
  448. providerWorkspaceConfigLoading: false,
  449. workspaceHeaderState: { selectedProvider: "glm" },
  450. selectedEditor: null,
  451. onRefreshGit: vi.fn(),
  452. isWebRemoteControl: true,
  453. } satisfies import("@/WorkspaceHeaderSections.js").WorkspaceHeaderTitleSectionProps;
  454. const view = render(createElement(WorkspaceHeaderTitleSection, props));
  455. try {
  456. const header = () => view.container.querySelector('[data-testid="workspace-path"]')!;
  457. expect(header().getAttribute("aria-description")).toBe("remote.status.online");
  458. expect(header().textContent).toBe("Remote Dev");
  459. act(() => store.getState().unregisterSession("bridge"));
  460. expect(header().getAttribute("aria-description")).toBe("remote.status.offline");
  461. act(() => {
  462. store.getState().registerSession({ sessionId: "replacement", services: {} as never });
  463. store.getState().bindWorkspaceIdentity(identity, "replacement");
  464. });
  465. expect(header().getAttribute("aria-description")).toBe("remote.status.online");
  466. } finally {
  467. cleanup();
  468. store.getState().unregisterSession("bridge");
  469. store.getState().unregisterSession("replacement");
  470. headerDirectory.current = null;
  471. }
  472. });