workspaceSidebarWebRemoteMobileLayout.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. // @vitest-environment jsdom
  2. import { createElement, type ReactNode } from "react";
  3. import { readFileSync } from "node:fs";
  4. import { resolve } from "node:path";
  5. import { cleanup, fireEvent, render, screen } from "@testing-library/react";
  6. import { renderToStaticMarkup } from "react-dom/server";
  7. import { afterEach, describe, expect, it, vi } from "vitest";
  8. import type { IPlatformService } from "@zcode/shared";
  9. const { setPendingSettingsSectionMock } = vi.hoisted(() => ({
  10. setPendingSettingsSectionMock: vi.fn(),
  11. }));
  12. vi.stubGlobal(
  13. "ResizeObserver",
  14. class ResizeObserverMock {
  15. disconnect() {}
  16. observe() {}
  17. unobserve() {}
  18. },
  19. );
  20. const workspaceTab = {
  21. id: "tab-1",
  22. kind: "workspace" as const,
  23. label: "Project",
  24. workspacePath: "/tmp/project",
  25. };
  26. const tabStoreState = {
  27. activeTabId: workspaceTab.id,
  28. tabs: [workspaceTab],
  29. expandedWorkspacePaths: new Set([workspaceTab.workspacePath]),
  30. activateTab: vi.fn(),
  31. closeTab: vi.fn(),
  32. collapseAllWorkspaceTabs: vi.fn(),
  33. expandAllWorkspaceTabs: vi.fn(),
  34. openSettingsTab: vi.fn(),
  35. reorderWorkspaceTabs: vi.fn(),
  36. toggleWorkspaceExpanded: vi.fn(),
  37. };
  38. vi.mock("@dnd-kit/core", () => ({
  39. DndContext: ({ children }: { children: ReactNode }) => createElement("div", null, children),
  40. DragOverlay: ({ children }: { children: ReactNode }) => createElement("div", null, children),
  41. KeyboardSensor: function KeyboardSensor() {},
  42. PointerSensor: function PointerSensor() {},
  43. closestCenter: vi.fn(),
  44. useSensor: vi.fn(() => ({})),
  45. useSensors: vi.fn(() => []),
  46. }));
  47. vi.mock("@dnd-kit/sortable", () => ({
  48. SortableContext: ({ children }: { children: ReactNode }) => createElement("div", null, children),
  49. sortableKeyboardCoordinates: vi.fn(),
  50. useSortable: vi.fn(() => ({
  51. attributes: {},
  52. isDragging: false,
  53. listeners: {},
  54. setActivatorNodeRef: vi.fn(),
  55. setNodeRef: vi.fn(),
  56. transform: null,
  57. transition: undefined,
  58. })),
  59. verticalListSortingStrategy: {},
  60. }));
  61. vi.mock("@/ControlHintTooltip.js", () => ({
  62. ControlHintTooltip: ({ children }: { children: ReactNode }) => children,
  63. }));
  64. vi.mock("@/NewTaskButtonGroup.js", () => ({
  65. NewTaskButtonGroup: () => createElement("div", { "data-testid": "new-task-button-group" }),
  66. }));
  67. vi.mock("@/TaskSearchDialog.js", () => ({
  68. TaskSearchDialog: () => null,
  69. }));
  70. vi.mock("@/BotsDialog.js", () => ({
  71. BotsDialog: () => null,
  72. }));
  73. vi.mock("@/WebRemoteControlTaskIndex.js", () => ({
  74. WebRemoteControlTaskIndex: ({
  75. renderBeforePinnedTasks,
  76. }: {
  77. renderBeforePinnedTasks?: () => ReactNode;
  78. }) => createElement("div", { "data-testid": "remote-task-index" }, renderBeforePinnedTasks?.()),
  79. }));
  80. vi.mock("@/WorkspaceArchivedTasksFlatSection.js", () => ({
  81. WorkspaceArchivedTasksFlatSection: () =>
  82. createElement("div", { "data-testid": "archived-tasks" }),
  83. }));
  84. vi.mock("@/WorkspacePinnedTasksSection.js", () => ({
  85. WorkspacePinnedTasksSection: () => createElement("div", { "data-testid": "pinned-tasks" }),
  86. }));
  87. vi.mock("@/WorkspaceTimelineTasksSection.js", () => ({
  88. WorkspaceTimelineTasksSection: () => createElement("div", { "data-testid": "timeline-tasks" }),
  89. }));
  90. vi.mock("@/WorkspaceGroupedTasksSection.js", () => ({
  91. WorkspaceGroupedTasksSection: () => createElement("div", { "data-testid": "grouped-tasks" }),
  92. }));
  93. vi.mock("@/WorkspaceSidebarFooter.js", () => ({
  94. WorkspaceSidebarFooter: () => createElement("footer", { "data-testid": "sidebar-footer" }),
  95. }));
  96. vi.mock("@/SortableWorkspaceSidebar.js", () => ({
  97. SortableWorkspaceSidebarItem: ({ tab }: { tab: typeof workspaceTab }) =>
  98. createElement("li", { "data-testid": "workspace-sidebar-item" }, tab.label),
  99. restrictVerticalDragWithinContainer: vi.fn(),
  100. }));
  101. vi.mock("@/hooks/useWorkspaceTaskLists.js", () => ({
  102. useWorkspaceTaskLists: () => ({
  103. groups: [],
  104. loadingByWorkspaceKey: {},
  105. }),
  106. }));
  107. vi.mock("@/i18n/IntlProvider.js", () => ({
  108. useZCodeIntl: () => ({
  109. intl: {
  110. formatMessage: ({ id }: { id: string }) => id,
  111. },
  112. localePreference: "en-US",
  113. setLocalePreference: vi.fn(),
  114. }),
  115. }));
  116. vi.mock("@/store/zcodeSessionStore.js", () => ({
  117. selectWorkspaceZCodeState: () => ({ activeTaskId: "task-1" }),
  118. useZCodeSessionStore: (selector: (state: { selectDraftProvider: () => void }) => unknown) =>
  119. selector({ selectDraftProvider: vi.fn() }),
  120. }));
  121. vi.mock("@/store/StoreProvider.js", () => ({
  122. useZCodeStore: (selector: (state: { setTheme: () => void }) => unknown) =>
  123. selector({ setTheme: vi.fn() }),
  124. }));
  125. vi.mock("@/store/TabStoreProvider.js", () => ({
  126. useTabStore: (selector: (state: typeof tabStoreState) => unknown) => selector(tabStoreState),
  127. }));
  128. vi.mock("@/settings/CodingPlanUpgradeDialogProvider.js", () => ({
  129. useCodingPlanUpgradeDialog: () => ({
  130. openCodingPlanUpgrade: vi.fn(),
  131. }),
  132. }));
  133. vi.mock("@/lib/settingsNavigation.js", () => ({
  134. setPendingSettingsSection: setPendingSettingsSectionMock,
  135. }));
  136. function createSidebarProps(overrides: Record<string, unknown> = {}) {
  137. return {
  138. isDesktop: false,
  139. isWindowsDesktop: false,
  140. onCancelRemoteProject: vi.fn(async () => {}),
  141. onConnectRemote: vi.fn(async () => ""),
  142. onCreateTask: vi.fn(),
  143. onLogin: vi.fn(),
  144. onLogout: vi.fn(),
  145. onReconnectRemoteWorkspace: vi.fn(async () => {}),
  146. onSelectRemoteProject: vi.fn(async () => {}),
  147. onSelectTask: vi.fn(),
  148. reconnectingRemoteWorkspaceKeys: [],
  149. remoteWorkspaceErrorByWorkspaceKey: {},
  150. selectedProvider: "codex",
  151. theme: "light",
  152. user: null,
  153. webRemoteControlWorkspaceSwitcher: {
  154. listWorkspaces: vi.fn(async () => ({ tasks: [], workspaces: [] })),
  155. switchWorkspace: vi.fn(async () => {}),
  156. },
  157. workspacePath: workspaceTab.workspacePath,
  158. ...overrides,
  159. };
  160. }
  161. async function createSidebarElement(overrides: Record<string, unknown> = {}) {
  162. const { WorkspaceSidebar } = await import("@/WorkspaceSidebar.js");
  163. // 快捷键特性后侧栏经 useShortcutCommandLabel → useSettings 读 ServiceContext 与 PlatformContext,
  164. // 裸渲染需提供最小 ServiceProvider/PlatformProvider(onSettingsChanged 可选,空 platform 即可)
  165. const { ServiceProvider } = await import("@/hooks/useServices.js");
  166. const { PlatformProvider } = await import("@/hooks/usePlatform.js");
  167. const { createSettingsTestServices } = await import("./lib/settingsTestServices.js");
  168. return createElement(
  169. ServiceProvider,
  170. { services: createSettingsTestServices() },
  171. createElement(
  172. PlatformProvider,
  173. { platform: {} as unknown as IPlatformService },
  174. createElement(
  175. WorkspaceSidebar,
  176. createSidebarProps(overrides) as Parameters<typeof WorkspaceSidebar>[0],
  177. ),
  178. ),
  179. );
  180. }
  181. async function renderSidebar(overrides: Record<string, unknown> = {}) {
  182. return renderToStaticMarkup(await createSidebarElement(overrides));
  183. }
  184. describe("WorkspaceSidebar Web remote mobile layout", () => {
  185. afterEach(() => {
  186. cleanup();
  187. vi.clearAllMocks();
  188. });
  189. // Bugfix: 该用例需要 SSR WorkspaceSidebar;pre-push 全量并发时首次导入和渲染偶尔超过默认 5s。
  190. // 子组件已经尽量 mock,剩余成本来自被测布局自身,局部放宽避免误报。
  191. it("places remote tasks and workspace navigation in one mobile scroll area", async () => {
  192. const html = await renderSidebar();
  193. expect(html).toContain('data-web-remote-navigation-scroll="true"');
  194. expect(html).toContain("max-md:overflow-y-auto");
  195. expect(html).toContain('data-testid="remote-task-index"');
  196. // Bugfix: 远控模式已把全局任务索引合并进主任务区,不再渲染重复的 workspace 列表项。
  197. // 这里显式断言缺失,防止回归到“同屏两段列表”。
  198. expect(html).not.toContain('data-testid="workspace-sidebar-item"');
  199. expect(html).toContain("max-md:hidden");
  200. expect(html).not.toContain("bots.title");
  201. expect(html).not.toContain("workspace.openWorkspace");
  202. const newTaskIndex = html.indexOf('data-testid="new-task-button-group"');
  203. const filterIndex = html.indexOf("workspaceSidebar.taskViewOptions");
  204. const topSearchIndex = html.indexOf("commandCenter.open");
  205. const automationsIndex = html.indexOf("workspace.openScheduledSettings");
  206. const pluginsIndex = html.indexOf("workspace.openPluginsSettings");
  207. expect(newTaskIndex).toBeGreaterThan(-1);
  208. expect(filterIndex).toBeGreaterThan(-1);
  209. expect(topSearchIndex).toBeGreaterThan(newTaskIndex);
  210. // D37:手机 /remote 不承载 Automations;合并 main 后不能恢复桌面入口。
  211. expect(automationsIndex).toBe(-1);
  212. expect(pluginsIndex).toBeGreaterThan(topSearchIndex);
  213. expect(pluginsIndex).toBeLessThan(filterIndex);
  214. expect(topSearchIndex).toBeLessThan(filterIndex);
  215. expect(html.lastIndexOf("commandCenter.open")).toBe(topSearchIndex);
  216. }, 15_000);
  217. it("opens the workspace plugin marketplace from the home shortcut", async () => {
  218. const onOpenPluginStore = vi.fn();
  219. render(await createSidebarElement({ onOpenPluginStore }));
  220. fireEvent.click(screen.getByRole("button", { name: "workspace.openPluginsSettings" }));
  221. expect(onOpenPluginStore).toHaveBeenCalledTimes(1);
  222. expect(setPendingSettingsSectionMock).not.toHaveBeenCalled();
  223. expect(tabStoreState.openSettingsTab).not.toHaveBeenCalled();
  224. });
  225. it("归档视图打开后将关闭按钮的 tooltip label 切换为 Close", async () => {
  226. render(await createSidebarElement());
  227. const archiveButton = screen.getByRole("button", {
  228. name: "workspaceSidebar.toggleArchivedTasks",
  229. });
  230. fireEvent.click(archiveButton);
  231. expect(screen.getByRole("button", { name: "common.close" })).toBe(archiveButton);
  232. });
  233. it("places plugins immediately after automations on the desktop home sidebar", async () => {
  234. render(await createSidebarElement({ webRemoteControlWorkspaceSwitcher: undefined }));
  235. const automationsButton = screen.getByRole("button", {
  236. name: "workspace.openScheduledSettings",
  237. });
  238. const pluginsButton = screen.getByRole("button", {
  239. name: "workspace.openPluginsSettings",
  240. });
  241. expect(pluginsButton.querySelector("svg")?.classList.contains("lucide-blocks")).toBe(true);
  242. expect(
  243. automationsButton.compareDocumentPosition(pluginsButton) & Node.DOCUMENT_POSITION_FOLLOWING,
  244. ).toBeTruthy();
  245. });
  246. it("does not keep the removed task toolbar search state", () => {
  247. const sidebarSource = readFileSync(
  248. resolve(process.cwd(), "packages/ui/src/WorkspaceSidebar.tsx"),
  249. "utf8",
  250. );
  251. expect(sidebarSource).not.toContain("webRemoteTaskSearchOpen");
  252. expect(sidebarSource).not.toContain("webRemoteTaskSearchQuery");
  253. });
  254. });