new-task-rendering.fixture.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. import { useCallback, useState } from "react";
  2. import { Event, ProxyChannel } from "@zcode/rpc";
  3. import { useRemoteWorkspaceHistory } from "@/root/useRemoteWorkspaceHistory.js";
  4. import { createRoot } from "react-dom/client";
  5. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  6. import { ChatLoading } from "@/components/ai-elements/chat-loading.js";
  7. import { Spinner } from "@/components/ui/spinner.js";
  8. import { ServiceProvider } from "@/hooks/useServices.js";
  9. import { WorkspaceHeaderTitleSection } from "@/WorkspaceHeaderSections.js";
  10. import { buildRemoteHostWorkspaceIdentity } from "@zcode/shared";
  11. import { TooltipProvider } from "@/components/ui/tooltip.js";
  12. import {
  13. ProjectDirectoryProvider,
  14. ProjectSidebar,
  15. useOptionalProjectDirectory,
  16. useOptionalProjectDirectoryActions,
  17. ProjectComposerMenu,
  18. } from "@/project-sidebar/index.js";
  19. import { useRootWorkspaceActions } from "@/root/useRootWorkspaceActions.js";
  20. import { useZCodeSessionStore } from "@/store/zcodeSessionStore.js";
  21. import type { ProjectTree, ProjectSidebarProps } from "@/project-sidebar/contract.js";
  22. import type { IServiceAccessor } from "@zcode/services";
  23. import { attachTaskListRowActivity } from "@/v4/taskListRowActivity.js";
  24. import "@/styles.css";
  25. const params = new URLSearchParams(location.search);
  26. const theme = params.get("theme") === "dark" ? "dark" : "light";
  27. const mobile = params.get("mobile") === "1";
  28. const activity = params.get("activity") === "1";
  29. const expansion = params.get("expansion") === "1";
  30. const boundaries = params.get("boundaries") === "1";
  31. const tooltips = params.get("tooltips") === "1";
  32. const sessionSwitch = params.get("sessionSwitch") === "1";
  33. document.documentElement.className = `${theme} theme-zai-${theme}`;
  34. const noop = () => {};
  35. const activate = () => true;
  36. const dispose = () => ({ dispose: noop });
  37. const tree: ProjectTree = {
  38. projects: Array.from({ length: 44 }, (_, index) => ({
  39. id: `p${index}`,
  40. hostId: "local",
  41. name: `Project ${index}`,
  42. roots:
  43. tooltips || sessionSwitch ? [{ rootPath: "/example", position: 0, isPrimary: true }] : [],
  44. pinned: false,
  45. deleted: false,
  46. position: index,
  47. createdAt: 1,
  48. updatedAt: 1,
  49. nameOverridden: true,
  50. })),
  51. tasks: activity
  52. ? [
  53. {
  54. taskId: "running-task",
  55. traceId: "running-task",
  56. mode: "build",
  57. workspacePath: "/example",
  58. hostId: "local",
  59. projectId: "p0",
  60. title: "Running task",
  61. createdAt: 1,
  62. updatedAt: 1,
  63. pinned: false,
  64. archived: false,
  65. },
  66. ]
  67. : [],
  68. };
  69. if (expansion)
  70. tree.tasks.push(
  71. ...Array.from({ length: 5 }, (_, index) => ({
  72. taskId: `expansion-task-${index}`,
  73. traceId: `expansion-task-${index}`,
  74. mode: "build" as const,
  75. workspacePath: "/example",
  76. hostId: "local",
  77. projectId: "p0",
  78. title: `Expansion task ${index}`,
  79. createdAt: 1,
  80. updatedAt: 1,
  81. pinned: false,
  82. archived: false,
  83. })),
  84. );
  85. if (sessionSwitch)
  86. tree.tasks.push(
  87. ...Array.from({ length: 4 }, (_, index) => ({
  88. taskId: index === 3 ? "switch-0" : `switch-${index}`,
  89. traceId: `switch-${index}`,
  90. mode: "build" as const,
  91. workspacePath: index === 3 ? "/other" : "/example",
  92. hostId: "local",
  93. projectId: index === 3 ? "p1" : "p0",
  94. title: `Switch task ${index}`,
  95. createdAt: 1,
  96. updatedAt: 1,
  97. pinned: false,
  98. archived: false,
  99. })),
  100. );
  101. if (boundaries)
  102. tree.tasks.push(
  103. ...Array.from({ length: 8 }, (_, index) => ({
  104. ...tree.tasks[0]!,
  105. taskId: `unrelated-${index}`,
  106. title: `Unrelated ${index}`,
  107. projectId: null,
  108. })),
  109. );
  110. let activitySnapshot = {
  111. items: activity
  112. ? [
  113. attachTaskListRowActivity(tree.tasks[0]!, {
  114. phase: "running",
  115. lastActivityAt: 1,
  116. hasBackgroundWork: false,
  117. }),
  118. ]
  119. : [],
  120. };
  121. const activityListeners = new Set<() => void>();
  122. const activityStore = {
  123. getSnapshot: () => activitySnapshot,
  124. subscribe: (listener: () => void) => {
  125. activityListeners.add(listener);
  126. return () => activityListeners.delete(listener);
  127. },
  128. update: (complete = false) => {
  129. activitySnapshot = {
  130. items: [
  131. attachTaskListRowActivity(tree.tasks[0]!, {
  132. phase: complete ? "completedSuccess" : "running",
  133. lastActivityAt: activitySnapshot.items[0]!.__zcodeSessionActivity.lastActivityAt + 1,
  134. hasBackgroundWork: false,
  135. }),
  136. ],
  137. };
  138. activityListeners.forEach((listener) => listener());
  139. },
  140. };
  141. const tabState = {
  142. tabs: [],
  143. activeWorkspacePath: "/example",
  144. activeWorkspaceIdentity: null,
  145. openSettingsTab: noop,
  146. };
  147. const tabStore = { getState: () => tabState, subscribe: () => noop };
  148. const remoteDirectory = {
  149. hosts: [
  150. {
  151. id: "remote:server:header-host",
  152. kind: "ssh",
  153. target: { kind: "ssh", host: "original.example.com", username: "dev", port: 22 },
  154. connectionStatus: "offline",
  155. position: 0,
  156. },
  157. ],
  158. entries: [],
  159. };
  160. const services = {
  161. credentialService: ProxyChannel.toService({
  162. call: async <T,>() => null as T,
  163. listen: () => Event.None,
  164. }),
  165. settingService: { get: async () => ({}), update: async () => {} },
  166. projectService: {
  167. readTree: async () => structuredClone(tree),
  168. saveProject: async (input: { id: string; pinned: boolean }) => {
  169. tree.projects.find((project) => project.id === input.id)!.pinned = input.pinned;
  170. },
  171. prepareSession: async () => ({
  172. workspacePath: "/example",
  173. projectId: null,
  174. additionalDirectories: [],
  175. }),
  176. },
  177. remoteProjectService: {
  178. readDirectory: async () =>
  179. expansion ? structuredClone(remoteDirectory) : { hosts: [], entries: [] },
  180. },
  181. broadcastService: { onMessage: dispose },
  182. zcodeTaskService: {
  183. onDynamicWorkspaceEvent: () => dispose,
  184. getTaskSessionFilePath: async () => ({ path: null, exists: false }),
  185. getTaskNativeSessionLogFile: async () => ({ path: null, exists: false }),
  186. getWorkspaceProviderConfigFile: async () => ({ path: null, exists: false }),
  187. },
  188. } as unknown as IServiceAccessor;
  189. Object.assign(window, { __renderFixture: { services, tabStore, activityStore } });
  190. useZCodeSessionStore.getState().setActiveTaskId("/example", sessionSwitch ? null : "old-session");
  191. const common = {
  192. workspacePath: "/example",
  193. theme,
  194. isDesktop: !mobile,
  195. isWebRemoteControl: mobile,
  196. onSelectTask: (...args: unknown[]) => {
  197. Object.assign(window, { __selectedTask: args });
  198. if (sessionSwitch)
  199. useZCodeSessionStore.getState().setActiveTaskId(args[0] as string, args[1] as string);
  200. },
  201. onStartDraftInWorkspace: noop,
  202. onOpenFolderFromWorkspaceMenu: noop,
  203. onConnectRemote: async () => "remote",
  204. onSelectRemoteProject: async () => {},
  205. onCancelRemoteProject: async () => {},
  206. onReconnectRemoteWorkspace: async () => {},
  207. reconnectingRemoteWorkspaceKeys: [],
  208. remoteWorkspaceErrorByWorkspaceKey: {},
  209. onOpenCommandCenter: noop,
  210. } satisfies Omit<ProjectSidebarProps, "onCreateTask" | "onCreateConversationTask">;
  211. const actions = {
  212. intl: { formatMessage: ({ id }: { id: string }) => id } as never,
  213. platform: {
  214. onRemoteConnectionLog: () => noop,
  215. onRemoteSessionClosed: () => noop,
  216. onRemoteSessionReconnected: () => noop,
  217. } as never,
  218. services,
  219. tabStoreApi: tabStore as never,
  220. addTab: () => "/example",
  221. activeWorkspacePath: "/example",
  222. activeWorkspaceIdentity: null,
  223. supportsSettings: true,
  224. allowOpenWorkspace: true,
  225. preferDirectoryBrowser: false,
  226. refreshProviderState: async () => {},
  227. updateAppSettings: async () => {},
  228. setOAuthError: noop,
  229. setUser: noop,
  230. workbenchGroupClientMode: mobile
  231. ? ("web-remote-replayable" as const)
  232. : ("desktop-continuous" as const),
  233. // 手机 bridge 只模拟导航完成;Renderer 仍走实际 replayable 分支。
  234. openMobileProjectDraft: async () => {
  235. useZCodeSessionStore.getState().startDraft("/example");
  236. },
  237. };
  238. function Controls() {
  239. const directory = useOptionalProjectDirectory()!;
  240. const [refreshes, setRefreshes] = useState(0);
  241. const taskActivity = (
  242. directory.tree.tasks[0] as (typeof activitySnapshot.items)[number] | undefined
  243. )?.__zcodeSessionActivity;
  244. return (
  245. <>
  246. {activity && (
  247. <>
  248. <ChatLoading
  249. data-testid="fixture-chat-loading"
  250. loading={taskActivity?.phase === "running"}
  251. />
  252. <button
  253. data-testid="activate-task"
  254. onClick={() =>
  255. useZCodeSessionStore.getState().setActiveTaskId("/example", "running-task")
  256. }
  257. >
  258. Activate task
  259. </button>
  260. <button data-testid="activity-tick" onClick={() => activityStore.update()}>
  261. Tick
  262. </button>
  263. <button data-testid="activity-complete" onClick={() => activityStore.update(true)}>
  264. Complete
  265. </button>
  266. <button
  267. data-testid="change-task"
  268. onClick={async () => {
  269. tree.tasks[0] = { ...tree.tasks[0]!, title: "Renamed task", unreadAt: 100 };
  270. await directory.refresh();
  271. }}
  272. >
  273. Change task
  274. </button>
  275. <output data-testid="activity-version">
  276. {
  277. (directory.tree.tasks[0] as (typeof activitySnapshot.items)[number])
  278. ?.__zcodeSessionActivity?.lastActivityAt
  279. }
  280. </output>
  281. </>
  282. )}
  283. <button
  284. data-testid="change-header-device"
  285. onClick={() => {
  286. remoteDirectory.hosts[0]!.target.host = "updated.example.com";
  287. void directory.refresh();
  288. }}
  289. >
  290. Change header device
  291. </button>
  292. <button
  293. data-testid="refresh-directory"
  294. onClick={async () => {
  295. await directory.refresh();
  296. setRefreshes((value) => value + 1);
  297. }}
  298. >
  299. Refresh
  300. </button>
  301. <output data-testid="refresh-count">{refreshes}</output>
  302. <button
  303. data-testid="rename-project"
  304. onClick={() => {
  305. tree.projects[0]!.name = "Renamed project";
  306. void directory.refresh();
  307. }}
  308. >
  309. Rename
  310. </button>
  311. </>
  312. );
  313. }
  314. function DirectoryCommandConsumer() {
  315. useOptionalProjectDirectoryActions();
  316. return null;
  317. }
  318. function Fixture() {
  319. const [revision, setRevision] = useState(0);
  320. const [fileRevision, setFileRevision] = useState(0);
  321. const openFiles = useCallback(
  322. (target: unknown) => Object.assign(window, { __openedFiles: { target, fileRevision } }),
  323. [fileRevision],
  324. );
  325. const [headerTitle, setHeaderTitle] = useState("Existing session");
  326. const [navigationPage, setNavigationPage] = useState("chat");
  327. const openAutomations = useCallback(() => setNavigationPage("automations"), []);
  328. const openPlugins = useCallback(() => setNavigationPage("plugins"), []);
  329. const task = useZCodeSessionStore((state) => state.workspaces["/example"]?.activeTaskId);
  330. // 模拟 Root 每轮装配导航实现;执行和侧栏均使用真实生产 hook/组件。
  331. const remote = useRemoteWorkspaceHistory({
  332. intl: actions.intl,
  333. services,
  334. platform: actions.platform,
  335. supportsSettings: false,
  336. isDesktop: !mobile,
  337. allowRemoteWorkspace: false,
  338. tabStoreApi: actions.tabStoreApi,
  339. activateTabByPath: activate,
  340. addTab: noop,
  341. });
  342. const navigation = useRootWorkspaceActions({
  343. ...actions,
  344. openRemoteProjectWorkspace: async () => {},
  345. });
  346. return (
  347. <ProjectDirectoryProvider isDesktop={!mobile}>
  348. <div className="flex h-screen bg-background text-foreground">
  349. <div className="w-64 shrink-0 bg-sidebar">
  350. <ProjectSidebar
  351. {...common}
  352. canGoBack={sessionSwitch ? Boolean(task) : undefined}
  353. onOpenFileManager={sessionSwitch ? openFiles : undefined}
  354. onCreateTask={navigation.handleCreateTask}
  355. onCreateConversationTask={navigation.handleCreateConversationTask}
  356. onSelectRemoteProject={remote.handleSelectRemoteProject}
  357. onReconnectRemoteWorkspace={remote.handleReconnectRemoteWorkspace}
  358. onOpenAutomations={openAutomations}
  359. automationsActive={navigationPage === "automations"}
  360. onOpenPluginStore={openPlugins}
  361. pluginStoreActive={navigationPage === "plugins"}
  362. />
  363. </div>
  364. <main className="min-w-0 p-2 text-ui-sm">
  365. {expansion && (
  366. <>
  367. <WorkspaceHeaderTitleSection
  368. workspaceAbsPath="/example"
  369. workspaceIdentity={
  370. mobile
  371. ? buildRemoteHostWorkspaceIdentity("remote:server:header-host", "/example")
  372. : undefined
  373. }
  374. isWebRemoteControl={mobile}
  375. projectName="Project 0"
  376. activeTaskTitle={headerTitle}
  377. activeTaskId="old-session"
  378. activeTraceId={null}
  379. activeSessionId={null}
  380. activeTaskProvider={null}
  381. gitSummary={{
  382. workspacePath: "/example",
  383. repoRoot: "",
  384. workspaceInRepoPath: "",
  385. autoRefreshWatchPaths: [],
  386. branchName: null,
  387. trackingBranchName: null,
  388. headRefType: "branch",
  389. ahead: 0,
  390. behind: 0,
  391. isDirty: false,
  392. isGitAvailable: false,
  393. isRepository: false,
  394. }}
  395. gitDirtyFileCount={0}
  396. sessionLogPath={null}
  397. nativeSessionLogProvider={null}
  398. nativeSessionLogPath={null}
  399. nativeSessionLogExists={false}
  400. nativeSessionLogLoading={false}
  401. providerWorkspaceConfigPath={null}
  402. providerWorkspaceConfigExists={false}
  403. providerWorkspaceConfigLoading={false}
  404. onRefreshGit={noop}
  405. workspaceHeaderState={{ selectedProvider: "glm" }}
  406. selectedEditor={null}
  407. />
  408. <button data-testid="rename-header" onClick={() => setHeaderTitle("Renamed session")}>
  409. Rename session
  410. </button>
  411. </>
  412. )}
  413. <output data-testid="current-task">{task ?? "draft"}</output>
  414. <button data-testid="shell-update" onClick={() => setRevision(revision + 1)}>
  415. Update {revision}
  416. </button>
  417. <Controls />
  418. {sessionSwitch && (
  419. <button
  420. data-testid="replace-file-handler"
  421. onClick={() => setFileRevision((n) => n + 1)}
  422. >
  423. Replace file handler
  424. </button>
  425. )}
  426. {boundaries && (
  427. <>
  428. <DirectoryCommandConsumer />
  429. <ProjectComposerMenu
  430. workspacePath="/example"
  431. onCreateTask={noop}
  432. onSelectConversationWorkspace={noop}
  433. />
  434. </>
  435. )}
  436. </main>
  437. </div>
  438. </ProjectDirectoryProvider>
  439. );
  440. }
  441. createRoot(document.getElementById("root")!).render(
  442. <ZCodeIntlProvider initialLocale={params.get("locale") === "zh-CN" ? "zh-CN" : "en-US"}>
  443. <TooltipProvider>
  444. {params.get("spinner") === "1" ? (
  445. <Spinner className="size-5 text-foreground-subtle" />
  446. ) : (
  447. // 侧栏新增 worktree 创建行后会读取全局服务,夹具必须提供同一份服务上下文。
  448. <ServiceProvider services={services as never}>
  449. <Fixture />
  450. </ServiceProvider>
  451. )}
  452. </TooltipProvider>
  453. </ZCodeIntlProvider>,
  454. );