ChatEmptyState.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. /**
  2. * ChatEmptyState — 对话为空时的空态展示组件
  3. *
  4. * 从 ChatView.tsx 拆出的 workspace 路径工具函数和空态下拉菜单组件。
  5. */
  6. /* eslint-disable max-lines -- 空态工作区菜单集中维护本地、远程与会话 workspace 的筛选和切换交互,局部样式扩展需保持同一套语义。 */
  7. import type { ReactNode } from "react";
  8. import { useMemo, useState } from "react";
  9. import { Button } from "@/components/ui/button.js";
  10. import {
  11. DropdownMenu,
  12. DropdownMenuCheckboxItem,
  13. DropdownMenuContent,
  14. DropdownMenuItem,
  15. DropdownMenuSeparator,
  16. DropdownMenuTrigger,
  17. } from "@/components/ui/dropdown-menu.js";
  18. import { InputGroup, InputGroupAddon } from "@/components/ui/input-group.js";
  19. import {
  20. ChevronDownIcon,
  21. Cloud,
  22. Folder,
  23. FolderPlus,
  24. House,
  25. MessageCircle,
  26. SearchIcon,
  27. X,
  28. } from "lucide-react";
  29. import { useZCodeIntl } from "@/i18n/IntlProvider.js";
  30. import { useRemoteConnectionEntryVisibility } from "@/hooks/useRemoteConnectionEntryVisibility.js";
  31. import { cn } from "@/components/lib/utils.js";
  32. import { getPathLeaf } from "@/lib/path.js";
  33. import {
  34. formatRemoteWorkspaceTargetSubtitle,
  35. hasRemoteWorkspaceIdentity,
  36. } from "@/lib/remoteWorkspaceHistory.js";
  37. import { logger } from "@/logger.js";
  38. import { SSHDialog } from "@/SSHDialog.js";
  39. import {
  40. TID_COMPOSER_PROJECT_DETACH,
  41. TID_COMPOSER_REMOTE_CONNECTION,
  42. TID_COMPOSER_WORK_OUTSIDE_PROJECT,
  43. TID_COMPOSER_WORKSPACE_TRIGGER,
  44. resolveWorkspaceKey,
  45. type RemoteTarget,
  46. type RemoteWorkspaceSessionEntry,
  47. type WorkspacePurpose,
  48. } from "@zcode/shared";
  49. import { runUserAction, runUserActionAsync } from "@/lib/userActionTelemetry.js";
  50. export {
  51. getScratchWorkspaceLocationHint,
  52. getScratchWorkspaceNameErrorKind,
  53. } from "@/ChatEmptyScratchWorkspaceDialog.js";
  54. // ---------------------------------------------------------------------------
  55. // Workspace 路径工具函数
  56. // ---------------------------------------------------------------------------
  57. function inferWorkspaceHomePath(path: string) {
  58. const normalizedPath = path.replace(/\\/g, "/").replace(/\/+$/, "");
  59. const homeMatch = normalizedPath.match(
  60. /^(\/Users\/[^/]+|\/home\/[^/]+|[A-Za-z]:\/Users\/[^/]+)(?:\/|$)/,
  61. );
  62. return homeMatch?.[1] ?? null;
  63. }
  64. function getWorkspaceMenuTitle(path: string, homeLabel: string) {
  65. const normalizedPath = path.replace(/\\/g, "/").replace(/\/+$/, "");
  66. if (
  67. /^(\/Users\/[^/]+|\/home\/[^/]+|[A-Za-z]:\/Users\/[^/]+)$/.test(
  68. normalizedPath,
  69. )
  70. ) {
  71. return homeLabel;
  72. }
  73. return getPathLeaf(path);
  74. }
  75. function getWorkspaceListTitle(path: string, homeLabel: string) {
  76. const normalizedPath = path.replace(/\\/g, "/").replace(/\/+$/, "");
  77. if (
  78. /^(\/Users\/[^/]+|\/home\/[^/]+|[A-Za-z]:\/Users\/[^/]+)$/.test(
  79. normalizedPath,
  80. )
  81. ) {
  82. return getPathLeaf(path);
  83. }
  84. return getWorkspaceMenuTitle(path, homeLabel);
  85. }
  86. export function getWorkspaceTriggerTitle(path: string, homeLabel: string) {
  87. const normalizedPath = path.replace(/\\/g, "/").replace(/\/+$/, "");
  88. if (
  89. /^(\/Users\/[^/]+|\/home\/[^/]+|[A-Za-z]:\/Users\/[^/]+)$/.test(
  90. normalizedPath,
  91. )
  92. ) {
  93. return getPathLeaf(path);
  94. }
  95. return getWorkspaceMenuTitle(path, homeLabel);
  96. }
  97. export interface ChatEmptyWorkspaceMenuTab {
  98. workspacePath: string;
  99. label: string;
  100. remoteSessionId?: string;
  101. remoteTarget?: RemoteTarget;
  102. workspaceIdentity?: string;
  103. workspacePurpose?: WorkspacePurpose;
  104. }
  105. export function isWorkspaceMenuTabSelected(
  106. workspaceTab: ChatEmptyWorkspaceMenuTab,
  107. current: { workspacePath: string; workspaceIdentity?: string },
  108. ): boolean {
  109. return resolveWorkspaceKey(workspaceTab) === resolveWorkspaceKey(current);
  110. }
  111. function getRemoteWorkspaceSearchText(workspaceTab: ChatEmptyWorkspaceMenuTab) {
  112. if (!workspaceTab.remoteTarget) {
  113. return workspaceTab.workspaceIdentity ?? "";
  114. }
  115. return [
  116. formatRemoteWorkspaceTargetSubtitle(workspaceTab.remoteTarget),
  117. workspaceTab.workspaceIdentity,
  118. ]
  119. .filter(Boolean)
  120. .join(" ");
  121. }
  122. export function filterVisibleWorkspaceMenuTabs({
  123. workspaceTabs,
  124. homeWorkspaceLabel,
  125. searchQuery,
  126. }: {
  127. workspaceTabs: ReadonlyArray<ChatEmptyWorkspaceMenuTab>;
  128. homeWorkspaceLabel: string;
  129. searchQuery: string;
  130. }) {
  131. const normalizedQuery = searchQuery.trim().toLowerCase();
  132. return workspaceTabs
  133. .filter((workspaceTab) => {
  134. const isDisconnectedRemoteWorkspace = Boolean(
  135. hasRemoteWorkspaceIdentity(workspaceTab) &&
  136. !workspaceTab.remoteSessionId,
  137. );
  138. // 空态菜单的 workspace 列表是给“立即切换可用上下文”用的。
  139. // 断连 remote workspace 继续出现在这里时,用户点进去只会得到一条当前不可用的上下文,
  140. // 和左侧 sidebar 的“保留断连项以便重连”职责不同。这里把断连 remote 从菜单列表里排除,
  141. // 仅保留可直接进入的 workspace;底部的固定入口保持不变。
  142. return !isDisconnectedRemoteWorkspace;
  143. })
  144. .filter((workspaceTab) => {
  145. if (!normalizedQuery) {
  146. return true;
  147. }
  148. const workspaceTitle = getWorkspaceListTitle(
  149. workspaceTab.workspacePath,
  150. homeWorkspaceLabel,
  151. );
  152. const searchableText = [
  153. workspaceTitle,
  154. workspaceTab.label,
  155. workspaceTab.workspacePath,
  156. getRemoteWorkspaceSearchText(workspaceTab),
  157. ]
  158. .join(" ")
  159. .toLowerCase();
  160. return searchableText.includes(normalizedQuery);
  161. })
  162. .slice(0, 5);
  163. }
  164. // ---------------------------------------------------------------------------
  165. // 空态组件
  166. // ---------------------------------------------------------------------------
  167. export function ChatEmptyWorkspacePreviewMenu({
  168. workspacePath,
  169. workspaceIdentity,
  170. isWindowsDesktop = false,
  171. compactForRemoteControl = false,
  172. workspaceTabs,
  173. allowConversationWorkspaceSelection = true,
  174. allowConversationWorkspaceDetach = allowConversationWorkspaceSelection,
  175. onSelectWorkspace,
  176. onSelectConversationWorkspace,
  177. onOpenFolder,
  178. allowOpenWorkspace = true,
  179. allowRemoteWorkspace = true,
  180. remoteWorkspaceSessions = [],
  181. onConnectRemote,
  182. onSelectRemoteProject,
  183. onCancelRemoteProject,
  184. containerClassName,
  185. triggerClassName,
  186. triggerIndicator,
  187. }: {
  188. workspacePath: string;
  189. workspaceIdentity?: string;
  190. isWindowsDesktop?: boolean;
  191. compactForRemoteControl?: boolean;
  192. workspaceTabs: ReadonlyArray<ChatEmptyWorkspaceMenuTab>;
  193. allowConversationWorkspaceSelection?: boolean;
  194. /** 是否显示项目 chip 的快捷脱离按钮;默认跟随非项目工作区选择能力。 */
  195. allowConversationWorkspaceDetach?: boolean;
  196. onSelectWorkspace: (workspaceTab: ChatEmptyWorkspaceMenuTab) => void;
  197. onSelectConversationWorkspace: () => void | Promise<void>;
  198. onOpenFolder: () => void;
  199. allowOpenWorkspace?: boolean;
  200. allowRemoteWorkspace?: boolean;
  201. remoteWorkspaceSessions?: RemoteWorkspaceSessionEntry[];
  202. onConnectRemote: (
  203. options: RemoteTarget,
  204. requestId?: string,
  205. ) => Promise<string>;
  206. onSelectRemoteProject: (
  207. sessionId: string,
  208. path: string,
  209. localWorkspacePath?: string,
  210. ) => Promise<void>;
  211. onCancelRemoteProject: (sessionId: string) => Promise<void>;
  212. /** 调用方局部调整 workspace chip 外层视觉,不改变普通会话默认样式。 */
  213. containerClassName?: string;
  214. /** 调用方局部调整 workspace trigger 视觉,不改变普通会话默认样式。 */
  215. triggerClassName?: string;
  216. /** 调用方局部替换尾部 indicator;普通会话继续使用默认 Lucide chevron。 */
  217. triggerIndicator?: ReactNode;
  218. }) {
  219. const { intl } = useZCodeIntl();
  220. const [sshDialogOpen, setSshDialogOpen] = useState(false);
  221. const [workspaceSearchQuery, setWorkspaceSearchQuery] = useState("");
  222. const showRemoteConnectionEntry = useRemoteConnectionEntryVisibility();
  223. // Web 普通模式没有完整远程 workspace 会话链路,不能只依赖全局 feature visibility。
  224. // 这里叠加壳层能力开关,确保本地 Web 模式的空态菜单不会露出必然失败的远程连接入口。
  225. const canUseRemoteWorkspace =
  226. allowRemoteWorkspace && showRemoteConnectionEntry;
  227. const currentWorkspaceTab =
  228. workspaceTabs.find((workspaceTab) =>
  229. isWorkspaceMenuTabSelected(workspaceTab, {
  230. workspacePath,
  231. workspaceIdentity,
  232. }),
  233. ) ?? null;
  234. const isConversationWorkspace =
  235. currentWorkspaceTab?.workspacePurpose === "conversation";
  236. const canDetachProject =
  237. allowConversationWorkspaceSelection &&
  238. allowConversationWorkspaceDetach &&
  239. !isConversationWorkspace;
  240. const localWorkspacePathForRemoteConnection =
  241. isConversationWorkspace ||
  242. currentWorkspaceTab?.remoteSessionId ||
  243. currentWorkspaceTab?.remoteTarget ||
  244. currentWorkspaceTab?.workspaceIdentity
  245. ? undefined
  246. : workspacePath;
  247. const homeWorkspacePath = inferWorkspaceHomePath(workspacePath);
  248. const homeWorkspaceLabel = intl.formatMessage({ id: "chat.empty.home" });
  249. const isCurrentRemoteWorkspace = hasRemoteWorkspaceIdentity(
  250. currentWorkspaceTab ?? {},
  251. );
  252. const visibleWorkspaceTabs = useMemo(
  253. () =>
  254. filterVisibleWorkspaceMenuTabs({
  255. workspaceTabs: workspaceTabs.filter(
  256. (workspaceTab) => workspaceTab.workspacePurpose !== "conversation",
  257. ),
  258. homeWorkspaceLabel,
  259. searchQuery: workspaceSearchQuery,
  260. }),
  261. [homeWorkspaceLabel, workspaceSearchQuery, workspaceTabs],
  262. );
  263. const currentWorkspaceTitle = isConversationWorkspace
  264. ? intl.formatMessage({ id: "chat.empty.selectProject" })
  265. : getWorkspaceTriggerTitle(workspacePath, homeWorkspaceLabel);
  266. const CurrentWorkspaceIcon = isCurrentRemoteWorkspace
  267. ? Cloud
  268. : homeWorkspacePath === workspacePath
  269. ? House
  270. : Folder;
  271. return (
  272. <DropdownMenu>
  273. <div
  274. className={cn(
  275. "group/workspace-chip relative flex min-w-0 items-center rounded-full hover:bg-surface-hover focus-within:bg-surface-hover",
  276. containerClassName,
  277. )}
  278. >
  279. {canDetachProject ? (
  280. <Button
  281. type="button"
  282. variant="ghost"
  283. size="icon-sm"
  284. className="pointer-events-none absolute left-1.5 z-10 rounded-full text-foreground-subtle opacity-0 transition-opacity group-hover/workspace-chip:pointer-events-auto group-hover/workspace-chip:opacity-100 group-focus-within/workspace-chip:pointer-events-auto group-focus-within/workspace-chip:opacity-100"
  285. aria-label={intl.formatMessage({ id: "chat.empty.detachProject" })}
  286. data-testid={TID_COMPOSER_PROJECT_DETACH}
  287. onClick={(event) => {
  288. event.stopPropagation();
  289. void runUserActionAsync({
  290. input: { featureId: "workspace.project_binding", action: "detach", trigger: "button" },
  291. operation: () => Promise.resolve(onSelectConversationWorkspace()),
  292. completed: { resultSource: "optimistic_projection" },
  293. failureStage: "project_detach",
  294. });
  295. }}
  296. >
  297. <X className="size-3.5" />
  298. </Button>
  299. ) : null}
  300. <DropdownMenuTrigger asChild>
  301. <Button
  302. type="button"
  303. variant="ghost"
  304. size="default"
  305. className={cn(
  306. "min-w-0 rounded-full bg-transparent text-ui-base/relaxed hover:bg-transparent",
  307. // Bugfix: 远程控制页面空态文案区域更窄,workspacePath 过长会把同一行挤坏。
  308. // 这里在远控模式收紧菜单触发按钮宽度,让超长路径在按钮内走省略号。
  309. compactForRemoteControl
  310. ? "max-w-44 pl-3 pr-2"
  311. : "max-w-[15rem] pl-3 pr-2",
  312. triggerClassName,
  313. )}
  314. aria-label={intl.formatMessage({ id: "chat.empty.workspaceMenu" })}
  315. data-testid={TID_COMPOSER_WORKSPACE_TRIGGER}
  316. >
  317. <CurrentWorkspaceIcon
  318. className={cn(
  319. "size-4 text-foreground-subtle transition-opacity",
  320. // 关闭按钮和项目图标占用同一位置。只有允许脱离项目时才隐藏底层图标,
  321. // 否则 X 会直接叠在图标上;定时任务禁用该能力时则让项目图标保持可见。
  322. canDetachProject &&
  323. "group-hover/workspace-chip:opacity-0 group-focus-within/workspace-chip:opacity-0",
  324. )}
  325. />
  326. <span className="block max-w-full truncate">
  327. {currentWorkspaceTitle}
  328. </span>
  329. {triggerIndicator ?? (
  330. <ChevronDownIcon className="size-3.5 text-foreground-subtle" />
  331. )}
  332. </Button>
  333. </DropdownMenuTrigger>
  334. </div>
  335. <DropdownMenuContent
  336. align="start"
  337. side="top"
  338. className="w-72 p-0"
  339. >
  340. <div
  341. data-slot="command-input-wrapper"
  342. className="p-1 border-b border-border"
  343. onKeyDown={(event) => event.stopPropagation()}
  344. >
  345. <InputGroup className="h-8 border-0 !bg-transparent hover:border-input-border-hover ">
  346. <input
  347. data-slot="command-input"
  348. value={workspaceSearchQuery}
  349. placeholder={intl.formatMessage({
  350. id: "chat.empty.workspaceSearchPlaceholder",
  351. })}
  352. onChange={(event) => setWorkspaceSearchQuery(event.target.value)}
  353. className="w-full text-ui-base/relaxed text-foreground outline-hidden placeholder:text-foreground-subtlest disabled:cursor-not-allowed disabled:opacity-50"
  354. />
  355. <InputGroupAddon>
  356. <SearchIcon className="size-4 shrink-0 text-foreground-subtlest" />
  357. </InputGroupAddon>
  358. </InputGroup>
  359. </div>
  360. <div className="p-1">
  361. {visibleWorkspaceTabs.map((workspaceTab, index) => {
  362. const workspaceTitle = getWorkspaceListTitle(
  363. workspaceTab.workspacePath,
  364. homeWorkspaceLabel,
  365. );
  366. const isRemoteWorkspace = hasRemoteWorkspaceIdentity(workspaceTab);
  367. const WorkspaceIcon = isRemoteWorkspace
  368. ? Cloud
  369. : inferWorkspaceHomePath(workspaceTab.workspacePath) ===
  370. workspaceTab.workspacePath
  371. ? House
  372. : Folder;
  373. return (
  374. <DropdownMenuCheckboxItem
  375. key={`${workspaceTab.workspaceIdentity ?? workspaceTab.remoteSessionId ?? "local"}:${workspaceTab.workspacePath}:${index}`}
  376. checked={isWorkspaceMenuTabSelected(workspaceTab, {
  377. workspacePath,
  378. workspaceIdentity,
  379. })}
  380. onSelect={() => {
  381. runUserAction({
  382. input: {
  383. featureId: isConversationWorkspace ? "workspace.project_binding" : "workspace.local.lifecycle",
  384. action: isConversationWorkspace ? "attach" : "switch",
  385. trigger: "menu",
  386. workspaceKind: isRemoteWorkspace ? "remote" : "local",
  387. },
  388. operation: () => onSelectWorkspace(workspaceTab),
  389. completed: { resultSource: "local_commit" },
  390. failureStage: "workspace_switch",
  391. });
  392. }}
  393. >
  394. <WorkspaceIcon className="size-4 text-foreground-subtle" />
  395. <span className="min-w-0 flex-1 truncate">
  396. {workspaceTitle}
  397. </span>
  398. </DropdownMenuCheckboxItem>
  399. );
  400. })}
  401. {visibleWorkspaceTabs.length === 0 ? (
  402. <div className="px-2 py-2 text-ui-base text-foreground-subtlest">
  403. {intl.formatMessage({ id: "chat.empty.workspaceSearchEmpty" })}
  404. </div>
  405. ) : null}
  406. <DropdownMenuSeparator />
  407. {allowOpenWorkspace ? (
  408. <DropdownMenuItem onSelect={onOpenFolder}>
  409. <FolderPlus className="size-4 text-foreground-subtle" />
  410. <span>{intl.formatMessage({ id: "workspace.openFolder" })}</span>
  411. </DropdownMenuItem>
  412. ) : null}
  413. {canUseRemoteWorkspace ? (
  414. <DropdownMenuItem
  415. data-testid={TID_COMPOSER_REMOTE_CONNECTION}
  416. onSelect={() => {
  417. // 打开远程弹窗时必须让 DropdownMenu 执行默认关闭流程。
  418. // 阻止默认 select 会让父菜单与 modal 同时保持打开,浮层层级调整后父菜单会覆盖弹窗。
  419. logger.info(
  420. `[ChatEmptyWorkspacePreviewMenu] open remote dialog from workspace menu workspace=${workspacePath}`,
  421. );
  422. runUserAction({
  423. input: { featureId: "workspace.remote.lifecycle", action: "open_dialog", trigger: "menu", workspaceKind: "remote" },
  424. operation: () => setSshDialogOpen(true),
  425. completed: { resultSource: "local_commit" },
  426. failureStage: "dialog_open",
  427. });
  428. }}
  429. >
  430. <Cloud className="size-4 text-foreground-subtle" />
  431. <span>{intl.formatMessage({ id: "remote.trigger" })}</span>
  432. </DropdownMenuItem>
  433. ) : null}
  434. {allowConversationWorkspaceSelection ? (
  435. <DropdownMenuCheckboxItem
  436. data-testid={TID_COMPOSER_WORK_OUTSIDE_PROJECT}
  437. checked={isConversationWorkspace}
  438. onSelect={() =>
  439. void runUserActionAsync({
  440. input: { featureId: "workspace.project_binding", action: "work_outside_project", trigger: "menu" },
  441. operation: () => Promise.resolve(onSelectConversationWorkspace()),
  442. completed: { resultSource: "optimistic_projection" },
  443. failureStage: "project_detach",
  444. })
  445. }
  446. >
  447. <MessageCircle className="size-4 text-foreground-subtle" />
  448. <span>
  449. {intl.formatMessage({ id: "chat.empty.workOutsideProject" })}
  450. </span>
  451. </DropdownMenuCheckboxItem>
  452. ) : null}
  453. </div>
  454. </DropdownMenuContent>
  455. {canUseRemoteWorkspace ? (
  456. <SSHDialog
  457. onConnect={onConnectRemote}
  458. onSelectProject={onSelectRemoteProject}
  459. onCancelSession={onCancelRemoteProject}
  460. localWorkspacePath={localWorkspacePathForRemoteConnection}
  461. isWindowsDesktop={isWindowsDesktop}
  462. remoteWorkspaceSessions={remoteWorkspaceSessions}
  463. open={sshDialogOpen}
  464. onOpenChange={setSshDialogOpen}
  465. hideTriggerWhenClosed
  466. />
  467. ) : null}
  468. </DropdownMenu>
  469. );
  470. }