WorkspaceSidebarItem.tsx 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  1. /* eslint-disable max-lines -- workspace 行同时承载折叠、远端状态和快捷操作,先保持同文件收口。 */
  2. import {
  3. memo,
  4. useCallback,
  5. useEffect,
  6. useRef,
  7. useState,
  8. type CSSProperties,
  9. type MouseEvent,
  10. } from "react";
  11. import {
  12. CheckIcon,
  13. CircleAlert,
  14. Cloud,
  15. CopyIcon,
  16. Ellipsis,
  17. Folder,
  18. FolderOpen,
  19. House,
  20. InfoIcon,
  21. ListTree,
  22. ListTodo,
  23. LoaderCircle,
  24. RefreshCwIcon,
  25. MessageCirclePlus,
  26. Pencil,
  27. XIcon,
  28. } from "lucide-react";
  29. import type { useSortable } from "@dnd-kit/sortable";
  30. import { BorderBeam } from "border-beam";
  31. import { STATUS_DOT } from "@/components/workflow-graph/run-status-presentation.js";
  32. import { Button, buttonVariants } from "@/components/ui/button.js";
  33. import {
  34. Collapsible,
  35. CollapsibleContent,
  36. CollapsibleTrigger,
  37. } from "@/components/ui/collapsible.js";
  38. import {
  39. DropdownMenu,
  40. DropdownMenuContent,
  41. DropdownMenuItem,
  42. DropdownMenuTrigger,
  43. } from "@/components/ui/dropdown-menu.js";
  44. import {
  45. Tooltip,
  46. TooltipContent,
  47. TooltipProvider,
  48. TooltipTrigger,
  49. } from "@/components/ui/tooltip.js";
  50. import { ControlHintTooltip } from "@/ControlHintTooltip.js";
  51. import { useZCodeIntl } from "@/i18n/IntlProvider.js";
  52. import {
  53. buildWorkspaceSessionKey,
  54. formatRemoteWorkspaceDisplayLabel,
  55. } from "@/lib/remoteWorkspaceHistory.js";
  56. import { TaskList } from "@/TaskList.js";
  57. import { TaskRenameDialog } from "@/TaskRenameDialog.js";
  58. import { useWorkspaceAliases } from "@/hooks/useWorkspaceAliases.js";
  59. import { selectWorkspaceZCodeState, useZCodeSessionStore } from "@/store/zcodeSessionStore.js";
  60. import type { WorkspaceTabState } from "@/store/tabStore.js";
  61. import type { RemoteConnectionLogEntry } from "@/hooks/useRemoteConnectionLogs.js";
  62. import { ReconnectingRemoteWorkspaceLogTooltip } from "@/WorkspaceSidebar/ReconnectingRemoteWorkspaceLogTooltip.js";
  63. import { cn } from "@/components/lib/utils.js";
  64. import {
  65. TID_WORKSPACE_CLOSE,
  66. TID_WORKSPACE_FILE_TREE_BUTTON,
  67. TID_WORKSPACE_ITEM,
  68. testId,
  69. } from "@zcode/shared";
  70. import type { ZCodeTaskMeta } from "@zcode/shared";
  71. import { useBaseWorkspaceServices, useWorkspaceServices } from "@/hooks/useWorkspaceServices.js";
  72. import {
  73. applyTaskQueryCacheMutation,
  74. invalidateTaskQueryCacheByScopes,
  75. } from "@/store/taskQueryCacheStore.js";
  76. import { useRemotePinnedTaskStore } from "@/store/remotePinnedTaskStore.js";
  77. import { useRemoteTimelineTaskStore } from "@/store/remoteTimelineTaskStore.js";
  78. import { logger } from "@/logger.js";
  79. import {
  80. RemoteSyncDialogs,
  81. RemoteSyncMenuItems,
  82. shouldShowRemoteSyncActions,
  83. } from "@/settings/RemoteSyncActions.js";
  84. import { invalidateDeferredDraftSessionForSkillChange } from "@/lib/zcodeDraftSkillInvalidation.js";
  85. import { refreshSharedSkillStoreForWorkspace } from "@/lib/skillStoreRefresh.js";
  86. import { refreshWorkspacePluginCapabilitiesAfterRemoteSync } from "@/lib/remotePluginSyncRefresh.js";
  87. import { useMcpStore } from "@/store/mcpStore.js";
  88. import { TaskRowActionButton } from "@/workspace-grouped-tasks/task-row-action-button.js";
  89. import { releaseWorkspaceRuntimeAfterProjectRemoval } from "@/lib/workspaceRuntimeRelease.js";
  90. import {
  91. hasRunningWorkspaceChat,
  92. scanWindowsReservedDeviceNameFiles,
  93. } from "@/lib/workspaceRemovalSafety.js";
  94. import { useConfirmDialog } from "@/hooks/useConfirmDialog.js";
  95. import { toast } from "@/components/ui/toast.js";
  96. export type SortableBindings = Pick<ReturnType<typeof useSortable>, "attributes" | "listeners">;
  97. // workspace 行在流式工具事件期间会因父级刷新而重渲染;
  98. // TaskList 如果每次收到新的空数组,会把等价数据误判成变化并连带刷新任务行。
  99. const EMPTY_PINNED_TASKS: ZCodeTaskMeta[] = [];
  100. function isHomeWorkspacePath(path: string): boolean {
  101. const normalizedPath = path.replace(/\\/g, "/").replace(/\/+$/, "");
  102. return /^(\/Users\/[^/]+|\/home\/[^/]+|[A-Za-z]:\/Users\/[^/]+)$/.test(normalizedPath);
  103. }
  104. type SshRemoteTarget = Extract<NonNullable<WorkspaceTabState["remoteTarget"]>, { kind: "ssh" }>;
  105. interface SshWorkspaceTooltipDetails {
  106. alias: string | null;
  107. hostLabel: string;
  108. workspacePath: string;
  109. }
  110. function formatSshRemoteHostLabel(target: SshRemoteTarget): string {
  111. const username = target.username.trim();
  112. const host = target.host.trim();
  113. const port = target.port ?? 22;
  114. return `${username}@${host}:${port}`;
  115. }
  116. function getSshWorkspaceTooltipDetails(tab: WorkspaceTabState): SshWorkspaceTooltipDetails | null {
  117. if (tab.remoteTarget?.kind !== "ssh") {
  118. return null;
  119. }
  120. return {
  121. alias: tab.remoteTarget.sshConfigAlias?.trim() || null,
  122. hostLabel: formatSshRemoteHostLabel(tab.remoteTarget),
  123. workspacePath: tab.workspacePath,
  124. };
  125. }
  126. export const WorkspaceSidebarItem = memo(function WorkspaceSidebarItem({
  127. tab,
  128. isActiveWorkspace,
  129. isExpanded,
  130. closeTab,
  131. toggleWorkspaceExpanded,
  132. onSelectTask,
  133. onStartDraftInWorkspace,
  134. taskItems,
  135. taskListLoading,
  136. taskListHasMore,
  137. taskListHasUnread = false,
  138. taskListLiveWorkflowCount = 0,
  139. mobileActiveTaskKey,
  140. isWebRemoteControl = false,
  141. onShowMoreTasks,
  142. reconnectingRemoteWorkspaceKeys,
  143. remoteWorkspaceErrorByWorkspaceKey,
  144. reconnectingRemoteWorkspaceLogsByWorkspaceKey,
  145. onReconnectRemoteWorkspace,
  146. onOpenFileTree,
  147. onDispatchTasks,
  148. itemRef,
  149. itemStyle,
  150. sortableBindings,
  151. isDragging = false,
  152. }: {
  153. tab: WorkspaceTabState;
  154. isActiveWorkspace: boolean;
  155. isExpanded: boolean;
  156. activateTab: (tabId: string) => void;
  157. closeTab: (tabId: string) => void;
  158. toggleWorkspaceExpanded: (workspacePath: string) => void;
  159. onSelectTask: (
  160. targetWorkspacePath: string,
  161. taskId: string,
  162. targetWorkspaceIdentity?: string,
  163. ) => void;
  164. onStartDraftInWorkspace: (targetWorkspacePath: string, targetWorkspaceIdentity?: string) => void;
  165. taskItems: ZCodeTaskMeta[];
  166. taskListLoading: boolean;
  167. taskListHasMore: boolean;
  168. taskListHasUnread?: boolean;
  169. /** 组内在跑的工作流 run 数;项目收起时在未读点旁画脉冲灯(>1 带数量)。 */
  170. taskListLiveWorkflowCount?: number;
  171. mobileActiveTaskKey?: string | null;
  172. isWebRemoteControl?: boolean;
  173. onShowMoreTasks: () => void;
  174. reconnectingRemoteWorkspaceKeys: string[];
  175. remoteWorkspaceErrorByWorkspaceKey: Record<string, string>;
  176. reconnectingRemoteWorkspaceLogsByWorkspaceKey: Record<string, RemoteConnectionLogEntry[]>;
  177. onReconnectRemoteWorkspace: (workspaceKey: string) => Promise<void>;
  178. onOpenFileTree?: (target: {
  179. workspacePath: string;
  180. workspaceName: string;
  181. workspaceIdentity?: string;
  182. workspaceRemoteSessionId?: string;
  183. }) => void;
  184. /** 项目级任务分收入口:在目标 workspace 打开预填规划提示词的新任务草稿。 */
  185. onDispatchTasks?: (target: {
  186. workspacePath: string;
  187. workspaceIdentity?: string;
  188. }) => void;
  189. itemRef?: (node: HTMLLIElement | null) => void;
  190. itemStyle?: CSSProperties;
  191. sortableBindings?: SortableBindings;
  192. isDragging?: boolean;
  193. }) {
  194. const { intl } = useZCodeIntl();
  195. const workspaceZCodeState = useZCodeSessionStore((state) =>
  196. selectWorkspaceZCodeState(state, tab.workspacePath, tab.workspaceIdentity),
  197. );
  198. const activeTaskId = workspaceZCodeState.activeTaskId;
  199. const removeTaskState = useZCodeSessionStore((state) => state.removeTaskState);
  200. const upsertOptimisticTaskListItem = useZCodeSessionStore(
  201. (state) => state.upsertOptimisticTaskListItem,
  202. );
  203. const removeOptimisticTaskListItem = useZCodeSessionStore(
  204. (state) => state.removeOptimisticTaskListItem,
  205. );
  206. const setTaskUnreadIndicator = useZCodeSessionStore((state) => state.setTaskUnreadIndicator);
  207. const services = useWorkspaceServices(
  208. tab.workspacePath,
  209. tab.remoteSessionId,
  210. tab.workspaceIdentity,
  211. tab.remoteTarget,
  212. );
  213. const confirmDialog = useConfirmDialog();
  214. const baseServices = useBaseWorkspaceServices();
  215. const zcodeTaskService = services.zcodeTaskService;
  216. const taskItemsRef = useRef(taskItems);
  217. taskItemsRef.current = taskItems;
  218. const workspaceZCodeStateRef = useRef(workspaceZCodeState);
  219. workspaceZCodeStateRef.current = workspaceZCodeState;
  220. const findCurrentTaskItem = useCallback((taskId: string) => {
  221. // 流式刷新会重建 taskItems 数组,任务操作回调如果直接依赖数组,
  222. // 即使任务语义没变也会换引用,继续击穿 TaskListItem 的 memo。
  223. // 用 ref 在调用时读取最新列表,既保持回调稳定,也避免乐观更新拿到过期 meta。
  224. return taskItemsRef.current.find((task) => task.taskId === taskId) ?? null;
  225. }, []);
  226. const isHomeWorkspace = isHomeWorkspacePath(tab.workspacePath);
  227. const readOnlyReason =
  228. tab.availability === "unavailable-local-directory"
  229. ? intl.formatMessage({ id: "workspaceSidebar.unavailableLocalDirectory" })
  230. : undefined;
  231. const remoteWorkspaceKey = buildWorkspaceSessionKey(tab);
  232. const isRemoteWorkspace = Boolean(
  233. tab.remoteSessionId || tab.remoteTarget || tab.workspaceIdentity,
  234. );
  235. const isDisconnectedRemoteWorkspace = Boolean(isRemoteWorkspace && !tab.remoteSessionId);
  236. const isReconnectPending = Boolean(
  237. isDisconnectedRemoteWorkspace && reconnectingRemoteWorkspaceKeys.includes(remoteWorkspaceKey),
  238. );
  239. const remoteWorkspaceError = remoteWorkspaceErrorByWorkspaceKey[remoteWorkspaceKey];
  240. // 项目显示别名:settings 持久化、纯展示层覆盖,不改 tab/路径/身份(重开不丢)。
  241. // key 用全局 workspaceKey 规则(workspaceIdentity?.trim() || workspacePath)。
  242. const workspaceKey = tab.workspaceIdentity?.trim() || tab.workspacePath;
  243. const { resolveWorkspaceAlias, setWorkspaceAlias } = useWorkspaceAliases();
  244. const workspaceDisplayAlias = resolveWorkspaceAlias(workspaceKey);
  245. const [workspaceAliasDialogOpen, setWorkspaceAliasDialogOpen] = useState(false);
  246. const [workspaceAliasDraft, setWorkspaceAliasDraft] = useState("");
  247. const workspaceAliasInputRef = useRef<HTMLInputElement | null>(null);
  248. const handleOpenWorkspaceAliasDialog = useCallback(() => {
  249. setWorkspaceAliasDraft(workspaceDisplayAlias ?? "");
  250. setWorkspaceAliasDialogOpen(true);
  251. }, [workspaceDisplayAlias]);
  252. const handleConfirmWorkspaceAlias = useCallback(() => {
  253. setWorkspaceAliasDialogOpen(false);
  254. void setWorkspaceAlias(workspaceKey, workspaceAliasDraft).catch((error) => {
  255. logger.error("[WorkspaceSidebarItem] 保存项目别名失败", { workspaceKey, error });
  256. toast(intl.formatMessage({ id: "workspaceSidebar.renameProjectFailed" }));
  257. });
  258. }, [intl, setWorkspaceAlias, workspaceAliasDraft, workspaceKey]);
  259. const workspaceSidebarLabel =
  260. workspaceDisplayAlias ?? formatRemoteWorkspaceDisplayLabel(tab.label, tab.remoteTarget);
  261. const sshWorkspaceTooltipDetails = getSshWorkspaceTooltipDetails(tab);
  262. const reconnectRuntimeLogs =
  263. reconnectingRemoteWorkspaceLogsByWorkspaceKey[remoteWorkspaceKey] ?? [];
  264. const showRemoteConnectionErrorNotice = Boolean(
  265. // 远程项目只要处于“断连”就显示叹号,会把“尚未连接/已断开但无错误”和“真实连接失败”混在一起,
  266. // 用户看到列表里的 warning 图标时无法判断是否真有故障。
  267. // 这里收敛成只有存在连接错误正文时才显示叹号,普通未连接状态仅保留重连入口。
  268. isDisconnectedRemoteWorkspace && !isReconnectPending && remoteWorkspaceError?.trim(),
  269. );
  270. const showReconnectAction = Boolean(isDisconnectedRemoteWorkspace);
  271. const showFileTreeAction = Boolean(onOpenFileTree && !isDisconnectedRemoteWorkspace);
  272. const showRemoteSkillSyncAction = shouldShowRemoteSyncActions({
  273. remoteSessionId: tab.remoteSessionId,
  274. remoteTarget: tab.remoteTarget,
  275. clientMode: isWebRemoteControl ? "web-remote-replayable" : "desktop-continuous",
  276. hasLocalSourceService: Boolean(baseServices.skillSyncService),
  277. });
  278. // 远端工作区在“重连中”时,之前只有轻微背景呼吸效果,
  279. // 在侧边栏高密度列表里不够醒目,用户很难快速判断哪个容器仍在连接。
  280. // 这里复用 BorderBeam,只在重连进行中激活,让连接态反馈更清晰,
  281. // 同时避免在普通空闲态或断连态误显示为“仍在运行”。
  282. const shouldShowRemoteConnectingBorderBeam = isReconnectPending;
  283. const [isRemoteErrorCopied, setIsRemoteErrorCopied] = useState(false);
  284. const [remoteSkillSyncOpen, setRemoteSkillSyncOpen] = useState(false);
  285. const [remoteMcpSyncOpen, setRemoteMcpSyncOpen] = useState(false);
  286. const [remotePluginSyncOpen, setRemotePluginSyncOpen] = useState(false);
  287. const [workspaceRowHovered, setWorkspaceRowHovered] = useState(false);
  288. const [workspaceRowFocusWithin, setWorkspaceRowFocusWithin] = useState(false);
  289. const [workspaceActionMenuOpen, setWorkspaceActionMenuOpen] = useState(false);
  290. const [isHoverNone] = useState(
  291. () =>
  292. typeof window !== "undefined" &&
  293. typeof window.matchMedia === "function" &&
  294. window.matchMedia("(hover: none)").matches,
  295. );
  296. const shouldMountWorkspaceRowActions =
  297. // workspace action 以前常驻 DOM,仅靠 opacity 隐藏;相邻 tooltip 会在
  298. // 浮层定位完成前误认隐藏 trigger,短暂显示到错误位置。改为交互时挂载,菜单打开时保活。
  299. workspaceRowHovered ||
  300. workspaceRowFocusWithin ||
  301. workspaceActionMenuOpen ||
  302. isHoverNone;
  303. const remoteErrorCopyResetRef = useRef<number | null>(null);
  304. useEffect(() => {
  305. return () => {
  306. if (remoteErrorCopyResetRef.current !== null) {
  307. window.clearTimeout(remoteErrorCopyResetRef.current);
  308. }
  309. };
  310. }, []);
  311. const handleWorkspaceOpenChange = useCallback(
  312. (nextOpen: boolean) => {
  313. if (isDisconnectedRemoteWorkspace) {
  314. return;
  315. }
  316. // workspace 草稿导航本身会把 workspace 标记为展开。
  317. // 之前在 Collapsible 的 onOpenChange 里无论展开/收起都先激活 workspace,
  318. // 收起后的下一次点击会先被激活路径展开,再被 toggleWorkspaceExpanded 反向切回收起,
  319. // 表现出来就是"收起后再也打不开"。
  320. // 这里把职责拆开:展开时只走草稿导航;收起时只做 toggle,避免两条状态更新互相抵消。
  321. if (nextOpen) {
  322. if (!isExpanded) {
  323. // workspace 行表达“打开这个 workspace”,不是恢复它上次选中的 session。
  324. // 统一走上层草稿导航事务,让 workspace identity、group/pane 清理和 draft 聚焦一起收口。
  325. onStartDraftInWorkspace(tab.workspacePath, tab.workspaceIdentity);
  326. }
  327. } else if (isExpanded) {
  328. toggleWorkspaceExpanded(tab.workspacePath);
  329. }
  330. },
  331. [
  332. isDisconnectedRemoteWorkspace,
  333. isExpanded,
  334. onStartDraftInWorkspace,
  335. tab.workspaceIdentity,
  336. tab.workspacePath,
  337. toggleWorkspaceExpanded,
  338. ],
  339. );
  340. const handleSelectTask = useCallback(
  341. (taskId: string) => {
  342. // 性能优化:上层 handleSelectTask 已经会按 workspacePath 激活 tab。
  343. // 这里重复 activate 会额外触发一轮 tab store 更新,把整列 workspace 行都带着重渲染一次。
  344. onSelectTask(tab.workspacePath, taskId, tab.workspaceIdentity);
  345. },
  346. [onSelectTask, tab.workspaceIdentity, tab.workspacePath],
  347. );
  348. const handleActionMouseDown = useCallback((event: MouseEvent<HTMLElement>) => {
  349. event.preventDefault();
  350. event.stopPropagation();
  351. }, []);
  352. const handleActionMenuClick = useCallback((event: MouseEvent<HTMLElement>) => {
  353. // DropdownMenuContent 虽然通过 Portal 渲染到行外,React 合成 click 仍会沿组件树
  354. // 冒泡到外层 CollapsibleTrigger。收起的 workspace 点“移除”时,会先 closeTab,再被展开回调
  355. // 当成“打开 workspace”重新 addTab,表现为删不掉。菜单层统一截断 click,保留菜单选择与键盘语义。
  356. event.stopPropagation();
  357. }, []);
  358. const handleCreateThreadClick = useCallback(
  359. (event: MouseEvent<HTMLButtonElement>) => {
  360. event.preventDefault();
  361. event.stopPropagation();
  362. if (readOnlyReason) {
  363. return;
  364. }
  365. onStartDraftInWorkspace(tab.workspacePath, tab.workspaceIdentity);
  366. },
  367. [onStartDraftInWorkspace, readOnlyReason, tab.workspaceIdentity, tab.workspacePath],
  368. );
  369. const handleRemoveWorkspace = useCallback(async () => {
  370. const workspaceKey = tab.workspaceIdentity?.trim() || tab.workspacePath;
  371. logger.debug("[WorkspaceSidebarItem] 移除 workspace", {
  372. isExpanded,
  373. workspaceKey,
  374. });
  375. if (
  376. hasRunningWorkspaceChat({
  377. workspaceState: workspaceZCodeStateRef.current,
  378. taskItems: taskItemsRef.current,
  379. })
  380. ) {
  381. const confirmed = await confirmDialog({
  382. title: intl.formatMessage({ id: "workspaceSidebar.removeRunningWorkspace.title" }),
  383. description: intl.formatMessage({
  384. id: "workspaceSidebar.removeRunningWorkspace.description",
  385. }),
  386. confirmLabel: intl.formatMessage({ id: "workspaceSidebar.removeRunningWorkspace.confirm" }),
  387. cancelLabel: intl.formatMessage({ id: "common.cancel" }),
  388. confirmVariant: "destructive",
  389. });
  390. if (!confirmed) {
  391. logger.debug("[WorkspaceSidebarItem] 用户取消移除运行中 workspace", { workspaceKey });
  392. return;
  393. }
  394. }
  395. closeTab(tab.id);
  396. releaseWorkspaceRuntimeAfterProjectRemoval({
  397. tab: {
  398. workspacePath: tab.workspacePath,
  399. workspaceIdentity: tab.workspaceIdentity,
  400. },
  401. zcodeTaskService,
  402. });
  403. // 移除 workspace 只是移除入口和连接历史,不代表用户要隐藏历史任务:
  404. // 这里只失效缓存,保留 sqlite 任务索引原状态,避免重连同一 SSH workspace 后任务像“丢了”。
  405. invalidateTaskQueryCacheByScopes([
  406. {
  407. workspacePath: tab.workspacePath,
  408. ...(tab.workspaceIdentity ? { workspaceIdentity: tab.workspaceIdentity } : {}),
  409. },
  410. ]);
  411. if (!isRemoteWorkspace) {
  412. void scanWindowsReservedDeviceNameFiles(baseServices.fileService, tab.workspacePath)
  413. .then((result) => {
  414. if (result.findings.length === 0) {
  415. return;
  416. }
  417. const firstFinding = result.findings[0] ?? tab.workspacePath;
  418. toast(
  419. intl.formatMessage(
  420. { id: "workspaceSidebar.windowsReservedNameRisk" },
  421. { count: result.findings.length, path: firstFinding },
  422. ),
  423. { durationMs: 8_000, variant: "warning" },
  424. );
  425. })
  426. .catch((error: unknown) => {
  427. // Windows 保留设备名扫描只是移除后的兼容风险提示,失败不能影响 workspace 生命周期释放。
  428. logger.debug("[WorkspaceSidebarItem] Windows 保留名风险扫描失败", {
  429. workspaceKey,
  430. error,
  431. });
  432. });
  433. }
  434. }, [
  435. baseServices.fileService,
  436. closeTab,
  437. confirmDialog,
  438. intl,
  439. isExpanded,
  440. isRemoteWorkspace,
  441. tab.id,
  442. tab.workspaceIdentity,
  443. tab.workspacePath,
  444. zcodeTaskService,
  445. ]);
  446. const handleReconnectRemoteWorkspace = useCallback(
  447. (event: MouseEvent<HTMLButtonElement>) => {
  448. event.preventDefault();
  449. event.stopPropagation();
  450. if (!isDisconnectedRemoteWorkspace || isReconnectPending) {
  451. return;
  452. }
  453. void onReconnectRemoteWorkspace(remoteWorkspaceKey);
  454. },
  455. [
  456. isDisconnectedRemoteWorkspace,
  457. isReconnectPending,
  458. onReconnectRemoteWorkspace,
  459. remoteWorkspaceKey,
  460. ],
  461. );
  462. const handleOpenWorkspaceFileTree = useCallback(
  463. (event: MouseEvent<HTMLButtonElement>) => {
  464. event.preventDefault();
  465. event.stopPropagation();
  466. if (isDisconnectedRemoteWorkspace || readOnlyReason || !onOpenFileTree) {
  467. return;
  468. }
  469. onOpenFileTree({
  470. workspacePath: tab.workspacePath,
  471. workspaceName: tab.label,
  472. workspaceIdentity: tab.workspaceIdentity,
  473. workspaceRemoteSessionId: tab.remoteSessionId,
  474. });
  475. },
  476. [
  477. isDisconnectedRemoteWorkspace,
  478. onOpenFileTree,
  479. readOnlyReason,
  480. tab.label,
  481. tab.remoteSessionId,
  482. tab.workspaceIdentity,
  483. tab.workspacePath,
  484. ],
  485. );
  486. // 这些 TaskList 操作以前在 JSX 中每次 render 都创建新闭包。
  487. // 流式事件刷新 workspace 行时,即使任务数据没变,也会穿透 TaskList/TaskListItem 的 memo。
  488. const handleRenameTask = useCallback(
  489. async (taskId: string, title: string) => {
  490. if (readOnlyReason) {
  491. return null;
  492. }
  493. const previousTask = findCurrentTaskItem(taskId);
  494. logger.info("[WorkspaceSidebarItem] rename service call start", {
  495. taskId,
  496. workspacePath: tab.workspacePath,
  497. workspaceIdentity: tab.workspaceIdentity,
  498. previousTitleLength: previousTask?.title.length,
  499. nextTitleLength: title.length,
  500. });
  501. let meta: ZCodeTaskMeta;
  502. try {
  503. meta = await zcodeTaskService.renameTask({
  504. taskId,
  505. workspacePath: tab.workspacePath,
  506. title,
  507. ...(tab.workspaceIdentity ? { workspaceIdentity: tab.workspaceIdentity } : {}),
  508. });
  509. } catch (error) {
  510. logger.error("[WorkspaceSidebarItem] rename service call failed", {
  511. taskId,
  512. workspacePath: tab.workspacePath,
  513. workspaceIdentity: tab.workspaceIdentity,
  514. message: error instanceof Error ? error.message : String(error),
  515. });
  516. throw error;
  517. }
  518. logger.info("[WorkspaceSidebarItem] rename service call resolved", {
  519. taskId,
  520. workspacePath: tab.workspacePath,
  521. workspaceIdentity: tab.workspaceIdentity,
  522. resolvedTitleLength: meta.title.length,
  523. });
  524. upsertOptimisticTaskListItem(tab.workspacePath, meta, tab.workspaceIdentity);
  525. if (tab.workspaceIdentity) {
  526. useRemoteTimelineTaskStore.getState().upsertTask(meta);
  527. }
  528. applyTaskQueryCacheMutation({
  529. previousTask: previousTask ?? meta,
  530. nextTask: meta,
  531. previousState: { pinned: false, archived: false },
  532. nextState: { pinned: false, archived: false },
  533. });
  534. logger.info("[WorkspaceSidebarItem] rename cache mutation applied", {
  535. taskId,
  536. workspacePath: tab.workspacePath,
  537. workspaceIdentity: tab.workspaceIdentity,
  538. });
  539. return meta;
  540. },
  541. [
  542. tab.workspaceIdentity,
  543. tab.workspacePath,
  544. findCurrentTaskItem,
  545. readOnlyReason,
  546. upsertOptimisticTaskListItem,
  547. zcodeTaskService,
  548. ],
  549. );
  550. const handleSetTaskPinned = useCallback(
  551. async (taskId: string, pinned: boolean) => {
  552. if (readOnlyReason) {
  553. return null;
  554. }
  555. const previousTask = findCurrentTaskItem(taskId);
  556. if (previousTask) {
  557. // workspace 内 pin 以前等远端/本地 RPC 返回后才更新全局 pinned 缓存,
  558. // pin 区会先消失再补回来。这里先乐观同步列表成员关系,失败时回滚。
  559. if (tab.workspaceIdentity && pinned) {
  560. useRemotePinnedTaskStore.getState().upsertTask(previousTask);
  561. useRemoteTimelineTaskStore
  562. .getState()
  563. .removeTask(tab.workspacePath, taskId, tab.workspaceIdentity);
  564. }
  565. if (tab.workspaceIdentity && !pinned) {
  566. useRemotePinnedTaskStore
  567. .getState()
  568. .removeTask(tab.workspacePath, taskId, tab.workspaceIdentity);
  569. useRemoteTimelineTaskStore.getState().upsertTask(previousTask);
  570. }
  571. applyTaskQueryCacheMutation({
  572. previousTask,
  573. nextTask: previousTask,
  574. previousState: { pinned: false, archived: false },
  575. nextState: { pinned, archived: false },
  576. });
  577. }
  578. try {
  579. const meta = await zcodeTaskService.setTaskPinned({
  580. taskId,
  581. workspacePath: tab.workspacePath,
  582. pinned,
  583. ...(tab.workspaceIdentity ? { workspaceIdentity: tab.workspaceIdentity } : {}),
  584. });
  585. removeOptimisticTaskListItem(tab.workspacePath, taskId, tab.workspaceIdentity);
  586. if (tab.workspaceIdentity && pinned) {
  587. useRemotePinnedTaskStore.getState().upsertTask(meta);
  588. useRemoteTimelineTaskStore
  589. .getState()
  590. .removeTask(tab.workspacePath, taskId, tab.workspaceIdentity);
  591. }
  592. if (tab.workspaceIdentity && !pinned) {
  593. useRemotePinnedTaskStore
  594. .getState()
  595. .removeTask(tab.workspacePath, taskId, tab.workspaceIdentity);
  596. useRemoteTimelineTaskStore.getState().upsertTask(meta);
  597. }
  598. applyTaskQueryCacheMutation({
  599. previousTask: previousTask ?? meta,
  600. nextTask: meta,
  601. previousState: { pinned, archived: false },
  602. nextState: { pinned, archived: false },
  603. });
  604. return meta;
  605. } catch (error) {
  606. if (previousTask) {
  607. if (tab.workspaceIdentity && pinned) {
  608. useRemotePinnedTaskStore
  609. .getState()
  610. .removeTask(tab.workspacePath, taskId, tab.workspaceIdentity);
  611. useRemoteTimelineTaskStore.getState().upsertTask(previousTask);
  612. }
  613. if (tab.workspaceIdentity && !pinned) {
  614. useRemotePinnedTaskStore.getState().upsertTask(previousTask);
  615. useRemoteTimelineTaskStore
  616. .getState()
  617. .removeTask(tab.workspacePath, taskId, tab.workspaceIdentity);
  618. }
  619. applyTaskQueryCacheMutation({
  620. previousTask,
  621. nextTask: previousTask,
  622. previousState: { pinned, archived: false },
  623. nextState: { pinned: false, archived: false },
  624. });
  625. }
  626. throw error;
  627. }
  628. },
  629. [
  630. removeOptimisticTaskListItem,
  631. readOnlyReason,
  632. tab.workspaceIdentity,
  633. tab.workspacePath,
  634. findCurrentTaskItem,
  635. zcodeTaskService,
  636. ],
  637. );
  638. const handleArchiveTask = useCallback(
  639. async (taskId: string) => {
  640. if (readOnlyReason) {
  641. return null;
  642. }
  643. const previousTask = findCurrentTaskItem(taskId);
  644. const meta = await zcodeTaskService.archiveTask({
  645. taskId,
  646. workspacePath: tab.workspacePath,
  647. ...(tab.workspaceIdentity ? { workspaceIdentity: tab.workspaceIdentity } : {}),
  648. });
  649. removeTaskState(tab.workspacePath, taskId, tab.workspaceIdentity);
  650. if (tab.workspaceIdentity) {
  651. useRemoteTimelineTaskStore
  652. .getState()
  653. .removeTask(tab.workspacePath, taskId, tab.workspaceIdentity);
  654. useRemotePinnedTaskStore
  655. .getState()
  656. .removeTask(tab.workspacePath, taskId, tab.workspaceIdentity);
  657. }
  658. applyTaskQueryCacheMutation({
  659. previousTask: previousTask ?? meta,
  660. nextTask: meta,
  661. previousState: { pinned: false, archived: false },
  662. nextState: { pinned: false, archived: true },
  663. });
  664. return meta;
  665. },
  666. [
  667. removeTaskState,
  668. readOnlyReason,
  669. tab.workspaceIdentity,
  670. tab.workspacePath,
  671. findCurrentTaskItem,
  672. zcodeTaskService,
  673. ],
  674. );
  675. const handleSetTaskUnread = useCallback(
  676. async (taskId: string, unread: boolean) => {
  677. if (readOnlyReason) {
  678. return null;
  679. }
  680. const previousTask = findCurrentTaskItem(taskId);
  681. const meta = await zcodeTaskService.setTaskUnread({
  682. taskId,
  683. workspacePath: tab.workspacePath,
  684. unread,
  685. ...(tab.workspaceIdentity ? { workspaceIdentity: tab.workspaceIdentity } : {}),
  686. });
  687. setTaskUnreadIndicator(tab.workspacePath, taskId, unread, tab.workspaceIdentity);
  688. upsertOptimisticTaskListItem(tab.workspacePath, meta, tab.workspaceIdentity);
  689. if (tab.workspaceIdentity) {
  690. useRemoteTimelineTaskStore.getState().upsertTask(meta);
  691. }
  692. applyTaskQueryCacheMutation({
  693. previousTask: previousTask ?? meta,
  694. nextTask: meta,
  695. previousState: { pinned: false, archived: false },
  696. nextState: { pinned: false, archived: false },
  697. });
  698. return meta;
  699. },
  700. [
  701. setTaskUnreadIndicator,
  702. readOnlyReason,
  703. tab.workspaceIdentity,
  704. tab.workspacePath,
  705. findCurrentTaskItem,
  706. upsertOptimisticTaskListItem,
  707. zcodeTaskService,
  708. ],
  709. );
  710. const handleCopyRemoteWorkspaceError = useCallback(() => {
  711. if (!remoteWorkspaceError || remoteWorkspaceError.trim().length === 0) {
  712. return;
  713. }
  714. navigator.clipboard.writeText(remoteWorkspaceError).then(() => {
  715. setIsRemoteErrorCopied(true);
  716. if (remoteErrorCopyResetRef.current !== null) {
  717. window.clearTimeout(remoteErrorCopyResetRef.current);
  718. }
  719. remoteErrorCopyResetRef.current = window.setTimeout(() => {
  720. setIsRemoteErrorCopied(false);
  721. remoteErrorCopyResetRef.current = null;
  722. }, 1500);
  723. });
  724. }, [remoteWorkspaceError]);
  725. const renderWorkspaceIcon = () => {
  726. // workspace 行之前在 hover/展开时会把目录图标切成箭头,
  727. // 视觉上会多出一层“树形展开控件”的暗示;当前交互只需要保留项目图标本身,
  728. // 这样能减少噪音,也避免用户把它理解成独立的箭头开关。
  729. if (isExpanded && !isDisconnectedRemoteWorkspace) {
  730. return isRemoteWorkspace ? (
  731. <Cloud className="h-4 w-4 text-foreground-subtle" />
  732. ) : isHomeWorkspace ? (
  733. <House className="h-4 w-4 text-foreground-subtle" />
  734. ) : (
  735. <FolderOpen className="h-4 w-4 text-foreground-subtle" />
  736. );
  737. }
  738. return isRemoteWorkspace ? (
  739. <Cloud className="h-4 w-4 text-foreground-subtle" />
  740. ) : isHomeWorkspace ? (
  741. <House className="h-4 w-4 text-foreground-subtle" />
  742. ) : (
  743. <Folder className="h-4 w-4 text-foreground-subtle" />
  744. );
  745. };
  746. const workspaceLabelContent = (
  747. <div className="flex min-w-0 flex-1 items-center gap-2">
  748. <span className="relative flex size-4 shrink-0 items-center justify-center">
  749. {renderWorkspaceIcon()}
  750. </span>
  751. <div className="min-w-0 truncate text-ui-base text-foreground-subtle">{workspaceSidebarLabel}</div>
  752. {!isExpanded && taskListHasUnread ? (
  753. <span
  754. aria-hidden="true"
  755. data-workspace-unread-indicator="true"
  756. className="h-1.5 w-1.5 shrink-0 rounded-full bg-sky-500 dark:bg-sky-400"
  757. />
  758. ) : null}
  759. {!isExpanded && taskListLiveWorkflowCount > 0 ? (
  760. // 工作流运行行的组头汇总:
  761. // 只汇总在跑的 run;已结束未确认的行不上卷。
  762. <span
  763. data-workspace-workflow-indicator="true"
  764. data-count={String(taskListLiveWorkflowCount)}
  765. aria-label={intl.formatMessage(
  766. { id: "taskList.workflowRun.liveCount" },
  767. { count: String(taskListLiveWorkflowCount) },
  768. )}
  769. className="flex shrink-0 items-center gap-1 text-ui-xs leading-none text-foreground-subtle"
  770. >
  771. <span aria-hidden="true" className={cn("size-1.5 rounded-full", STATUS_DOT.running)} />
  772. {taskListLiveWorkflowCount > 1 ? taskListLiveWorkflowCount : null}
  773. </span>
  774. ) : null}
  775. {readOnlyReason ? (
  776. <ControlHintTooltip title={readOnlyReason} side="right" align="center">
  777. <span
  778. role="img"
  779. aria-label={readOnlyReason}
  780. tabIndex={0}
  781. className="flex size-4 shrink-0 items-center justify-center"
  782. >
  783. <CircleAlert className="size-3.5 text-destructive" />
  784. </span>
  785. </ControlHintTooltip>
  786. ) : null}
  787. </div>
  788. );
  789. return (
  790. <li ref={itemRef} style={itemStyle} className="space-y-2">
  791. <Collapsible
  792. className="flex flex-col gap-1"
  793. open={isExpanded && !isDisconnectedRemoteWorkspace}
  794. onOpenChange={handleWorkspaceOpenChange}
  795. >
  796. <BorderBeam
  797. size="line"
  798. colorVariant="colorful"
  799. duration={1.96}
  800. active={shouldShowRemoteConnectingBorderBeam}
  801. borderRadius={8}
  802. >
  803. <div
  804. className={cn(
  805. "group flex items-center gap-2 rounded-lg transition-[background-color,box-shadow]",
  806. isReconnectPending
  807. ? "bg-brand/10 workspace-remote-connecting-breathe"
  808. : isDisconnectedRemoteWorkspace
  809. ? "bg-warning/8"
  810. : null,
  811. // "sticky top-0 z-10", // TODO: 拖拽时让 workspace 项悬浮 不要抹掉
  812. isDragging && "bg-selected shadow-xl",
  813. )}
  814. >
  815. <CollapsibleTrigger asChild>
  816. <div
  817. role="button"
  818. tabIndex={0}
  819. data-skin-row="workspace"
  820. data-testid={testId(TID_WORKSPACE_ITEM, tab.workspacePath)}
  821. className={cn(
  822. buttonVariants({ variant: "ghost", size: "default" }),
  823. /*
  824. * CollapsibleTrigger 会自动注入 aria-expanded。
  825. * 这里复用了 ghost button 变体后,会命中全局 aria-expanded:bg-surface-hover
  826. * 导致 workspace 项一展开就像"被选中"一样出现背景色。
  827. * 局部把 aria-expanded 样式覆盖掉,只保留 hover,避免误导激活态。
  828. * 断连的 remote workspace 不能展开任务列表,因此这里也要禁掉 hover 展开态提示,
  829. * 避免用户看到“可展开”的反馈却点不开,只保留 warning 背景提示当前需要先重连。
  830. */
  831. "flex h-8 min-w-0 flex-1 justify-start gap-2 rounded-lg pl-2.5 pr-1 text-left text-foreground aria-expanded:bg-transparent aria-expanded:text-foreground",
  832. "hover:bg-surface-hover hover:text-foreground",
  833. isDisconnectedRemoteWorkspace &&
  834. "hover:bg-transparent aria-expanded:bg-transparent",
  835. sortableBindings && "cursor-grab active:cursor-grabbing",
  836. )}
  837. onMouseEnter={() => setWorkspaceRowHovered(true)}
  838. onMouseLeave={() => setWorkspaceRowHovered(false)}
  839. onFocusCapture={() => setWorkspaceRowFocusWithin(true)}
  840. onBlurCapture={(event) => {
  841. if (!event.currentTarget.contains(event.relatedTarget as Node | null)) {
  842. setWorkspaceRowFocusWithin(false);
  843. }
  844. }}
  845. {...(sortableBindings?.attributes ?? {})}
  846. {...(sortableBindings?.listeners ?? {})}
  847. >
  848. {sshWorkspaceTooltipDetails ? (
  849. <TooltipProvider>
  850. <Tooltip>
  851. <TooltipTrigger asChild>{workspaceLabelContent}</TooltipTrigger>
  852. <TooltipContent
  853. side="right"
  854. align="start"
  855. sideOffset={6}
  856. className="max-w-80 flex-col items-start gap-2 p-2.5 text-left"
  857. >
  858. <span className="text-ui-sm font-medium text-tooltip-foreground">
  859. {intl.formatMessage({
  860. id: "workspaceSidebar.sshConnectionTitle",
  861. })}
  862. </span>
  863. <dl className="grid w-full grid-cols-[auto_minmax(0,1fr)] gap-x-2 gap-y-1 text-ui-sm/relaxed text-tooltip-foreground">
  864. {sshWorkspaceTooltipDetails.alias ? (
  865. <>
  866. <dt className="font-medium">
  867. {intl.formatMessage({
  868. id: "workspaceSidebar.sshConnectionAlias",
  869. })}
  870. </dt>
  871. <dd className="min-w-0 break-all font-mono">
  872. {sshWorkspaceTooltipDetails.alias}
  873. </dd>
  874. </>
  875. ) : null}
  876. <dt className="font-medium">
  877. {intl.formatMessage({
  878. id: "workspaceSidebar.sshConnectionHost",
  879. })}
  880. </dt>
  881. <dd className="min-w-0 break-all font-mono">
  882. {sshWorkspaceTooltipDetails.hostLabel}
  883. </dd>
  884. <dt className="font-medium">
  885. {intl.formatMessage({
  886. id: "workspaceSidebar.sshConnectionPath",
  887. })}
  888. </dt>
  889. <dd className="min-w-0 break-all font-mono">
  890. {sshWorkspaceTooltipDetails.workspacePath}
  891. </dd>
  892. </dl>
  893. </TooltipContent>
  894. </Tooltip>
  895. </TooltipProvider>
  896. ) : (
  897. workspaceLabelContent
  898. )}
  899. <div className="flex shrink-0 items-center gap-2">
  900. {/* {isRemoteWorkspace && isReconnectPending ? (
  901. <ReconnectingRemoteWorkspaceLogTooltip
  902. logs={reconnectRuntimeLogs}
  903. />
  904. ) : null} */}
  905. <div className="flex shrink-0 items-center gap-1">
  906. {shouldMountWorkspaceRowActions ? (
  907. <DropdownMenu
  908. open={workspaceActionMenuOpen}
  909. onOpenChange={setWorkspaceActionMenuOpen}
  910. >
  911. <ControlHintTooltip
  912. title={intl.formatMessage({ id: "common.more" })}
  913. /* 菜单/重命名弹窗打开期间强制收起 tooltip:select 关菜单后指针
  914. * 仍悬在触发器上,Radix 会按 hover 态把 tooltip 留在原地(「更多」挂着)。
  915. * 弹窗打开条件一并抑制;弹窗关闭后恢复自然悬停行为。 */
  916. open={
  917. workspaceActionMenuOpen || workspaceAliasDialogOpen
  918. ? false
  919. : undefined
  920. }
  921. >
  922. <DropdownMenuTrigger asChild>
  923. <Button
  924. type="button"
  925. variant="ghost"
  926. size="icon-sm"
  927. className="shrink-0 text-foreground-subtle hover:bg-surface-hover hover:text-foreground"
  928. onMouseDown={handleActionMouseDown}
  929. aria-label={intl.formatMessage({ id: "common.more" })}
  930. >
  931. <Ellipsis className="h-3.5 w-3.5" />
  932. </Button>
  933. </DropdownMenuTrigger>
  934. </ControlHintTooltip>
  935. <DropdownMenuContent align="end" onClick={handleActionMenuClick}>
  936. <RemoteSyncMenuItems
  937. canSyncSkills={showRemoteSkillSyncAction}
  938. canSyncMcp={showRemoteSkillSyncAction}
  939. canSyncPlugins={showRemoteSkillSyncAction}
  940. stopMouseDownPropagation
  941. onOpenSkillSync={() => setRemoteSkillSyncOpen(true)}
  942. onOpenMcpSync={() => setRemoteMcpSyncOpen(true)}
  943. onOpenPluginSync={() => setRemotePluginSyncOpen(true)}
  944. />
  945. {onDispatchTasks ? (
  946. <DropdownMenuItem
  947. onSelect={(event) => {
  948. event.preventDefault();
  949. setWorkspaceActionMenuOpen(false);
  950. onDispatchTasks({
  951. workspacePath: tab.workspacePath,
  952. ...(tab.workspaceIdentity
  953. ? { workspaceIdentity: tab.workspaceIdentity }
  954. : {}),
  955. });
  956. }}
  957. >
  958. <ListTodo className="h-3.5 w-3.5" />
  959. {intl.formatMessage({ id: "workspaceSidebar.dispatchTasks" })}
  960. </DropdownMenuItem>
  961. ) : null}
  962. <DropdownMenuItem
  963. onSelect={(event) => {
  964. event.preventDefault();
  965. // 受控菜单不会因 onSelect 自动收起,弹窗打开前先关掉,
  966. // 否则菜单会一直挂在弹窗后面。
  967. setWorkspaceActionMenuOpen(false);
  968. handleOpenWorkspaceAliasDialog();
  969. }}
  970. >
  971. <Pencil className="h-3.5 w-3.5" />
  972. {intl.formatMessage({ id: "workspaceSidebar.renameProject" })}
  973. </DropdownMenuItem>
  974. <DropdownMenuItem
  975. data-testid={testId(TID_WORKSPACE_CLOSE, tab.workspacePath)}
  976. onMouseDown={(event) => {
  977. event.preventDefault();
  978. event.stopPropagation();
  979. }}
  980. onSelect={(event) => {
  981. event.preventDefault();
  982. void handleRemoveWorkspace();
  983. }}
  984. >
  985. <XIcon className="h-3.5 w-3.5" />
  986. {intl.formatMessage({
  987. id: "workspaceSidebar.remove",
  988. })}
  989. </DropdownMenuItem>
  990. </DropdownMenuContent>
  991. </DropdownMenu>
  992. ) : null}
  993. {shouldMountWorkspaceRowActions && showFileTreeAction ? (
  994. <span className="shrink-0">
  995. {/* Bugfix:Project 文件树入口以前单独覆盖 hover:bg-surface-hover,
  996. 与 Pinned / Grouped 的 bg-hover 不一致;三种入口统一复用同一 action。 */}
  997. <TaskRowActionButton
  998. // 该按钮默认继承 ghost 的主前景色,导致同组的三个图标明暗不一致。
  999. className="text-foreground-subtle hover:text-foreground"
  1000. label={intl.formatMessage({
  1001. id: "workspaceSidebar.showFileTree",
  1002. })}
  1003. onClick={handleOpenWorkspaceFileTree}
  1004. showTooltip
  1005. disabledReason={readOnlyReason}
  1006. testId={testId(TID_WORKSPACE_FILE_TREE_BUTTON, tab.workspacePath)}
  1007. >
  1008. <ListTree className="h-3.5 w-3.5" />
  1009. </TaskRowActionButton>
  1010. </span>
  1011. ) : null}
  1012. {showRemoteConnectionErrorNotice ? (
  1013. remoteWorkspaceError ? (
  1014. <TooltipProvider>
  1015. <Tooltip>
  1016. <TooltipTrigger asChild>
  1017. <div
  1018. className="flex size-6 shrink-0 items-center justify-center !text-warning cursor-help"
  1019. aria-label={intl.formatMessage({
  1020. id: "workspaceSidebar.notConnected",
  1021. })}
  1022. >
  1023. <InfoIcon className="h-3.5 w-3.5" />
  1024. </div>
  1025. </TooltipTrigger>
  1026. <TooltipContent
  1027. side="top"
  1028. align="center"
  1029. sideOffset={4}
  1030. className="w-72 max-w-72 items-center gap-2 p-2.5"
  1031. >
  1032. {/*
  1033. * 远端连接失败 tooltip 之前拆成“标题 + 内层卡片”两段结构,
  1034. * 在 sidebar 这种高密度区域里会显得层级过多,像一个迷你弹窗,不够轻。
  1035. * 这里收敛回普通 tooltip 语义:一层浮层里直接放错误正文和复制按钮,
  1036. * 保留可读性与复制能力,同时避免视觉上过度设计。
  1037. */}
  1038. <pre className="max-h-32 min-w-0 flex-1 overflow-auto text-ui-sm/relaxed whitespace-pre-wrap break-words font-mono text-tooltip-foreground">
  1039. {remoteWorkspaceError}
  1040. </pre>
  1041. <Button
  1042. type="button"
  1043. variant="ghost"
  1044. size="icon-md"
  1045. className="mt-0.5 size-6 shrink-0 text-tooltip-foreground/80 hover:bg-tooltip-tag hover:text-tooltip-foreground"
  1046. onClick={(event) => {
  1047. event.preventDefault();
  1048. event.stopPropagation();
  1049. handleCopyRemoteWorkspaceError();
  1050. }}
  1051. title={intl.formatMessage({
  1052. id: isRemoteErrorCopied
  1053. ? "chat.toolCall.copyError.copied"
  1054. : "chat.toolCall.copyError",
  1055. })}
  1056. aria-label={intl.formatMessage({
  1057. id: isRemoteErrorCopied
  1058. ? "chat.toolCall.copyError.copied"
  1059. : "chat.toolCall.copyError",
  1060. })}
  1061. >
  1062. {isRemoteErrorCopied ? (
  1063. <CheckIcon className="size-3" />
  1064. ) : (
  1065. <CopyIcon className="size-3" />
  1066. )}
  1067. </Button>
  1068. </TooltipContent>
  1069. </Tooltip>
  1070. </TooltipProvider>
  1071. ) : (
  1072. <ControlHintTooltip
  1073. title={intl.formatMessage({
  1074. id: "workspaceSidebar.notConnected",
  1075. })}
  1076. >
  1077. <div
  1078. className="flex size-6 shrink-0 items-center justify-center !text-warning"
  1079. aria-label={intl.formatMessage({
  1080. id: "workspaceSidebar.notConnected",
  1081. })}
  1082. >
  1083. <InfoIcon className="h-3.5 w-3.5" />
  1084. </div>
  1085. </ControlHintTooltip>
  1086. )
  1087. ) : null}
  1088. {showReconnectAction ? (
  1089. isReconnectPending ? (
  1090. <ReconnectingRemoteWorkspaceLogTooltip logs={reconnectRuntimeLogs}>
  1091. {/* Bugfix: SSH workspace 重连中时,右侧原本只有 spinning 图标,
  1092. 用户无法在聊天页任务列表里确认连接卡在哪一步。这里复用 SSH dialog 的连接日志 tooltip,
  1093. 保持行内布局稳定,同时把诊断信息放到 hover 浮层里。 */}
  1094. <div
  1095. role="status"
  1096. className={cn(
  1097. buttonVariants({ variant: "ghost", size: "icon-sm" }),
  1098. "shrink-0 text-foreground opacity-100 hover:bg-surface-hover hover:text-foreground",
  1099. )}
  1100. onMouseDown={handleActionMouseDown}
  1101. aria-label={intl.formatMessage({
  1102. id: "workspaceSidebar.connecting",
  1103. })}
  1104. >
  1105. <LoaderCircle className="h-3.5 w-3.5 animate-spin" />
  1106. </div>
  1107. </ReconnectingRemoteWorkspaceLogTooltip>
  1108. ) : (
  1109. <ControlHintTooltip
  1110. title={intl.formatMessage({
  1111. id: "workspaceSidebar.reconnect",
  1112. })}
  1113. side="right"
  1114. align="center"
  1115. >
  1116. <Button
  1117. type="button"
  1118. variant="ghost"
  1119. size="icon-sm"
  1120. className="shrink-0 text-foreground opacity-100 hover:bg-surface-hover hover:text-foreground disabled:opacity-100"
  1121. onMouseDown={handleActionMouseDown}
  1122. onClick={handleReconnectRemoteWorkspace}
  1123. aria-label={intl.formatMessage({
  1124. id: "workspaceSidebar.reconnect",
  1125. })}
  1126. >
  1127. <RefreshCwIcon className="h-3.5 w-3.5" />
  1128. </Button>
  1129. </ControlHintTooltip>
  1130. )
  1131. ) : shouldMountWorkspaceRowActions ? (
  1132. <ControlHintTooltip
  1133. title={readOnlyReason ?? intl.formatMessage({ id: "taskList.newThread" })}
  1134. >
  1135. <Button
  1136. type="button"
  1137. variant="ghost"
  1138. size="icon-sm"
  1139. className="shrink-0 text-foreground-subtle hover:bg-surface-hover hover:text-foreground"
  1140. onMouseDown={handleActionMouseDown}
  1141. onClick={handleCreateThreadClick}
  1142. disabled={Boolean(readOnlyReason)}
  1143. aria-label={intl.formatMessage({
  1144. id: "taskList.newThread",
  1145. })}
  1146. >
  1147. <MessageCirclePlus className="h-3.5 w-3.5" />
  1148. </Button>
  1149. </ControlHintTooltip>
  1150. ) : null}
  1151. </div>
  1152. </div>
  1153. </div>
  1154. </CollapsibleTrigger>
  1155. </div>
  1156. </BorderBeam>
  1157. <CollapsibleContent>
  1158. <TaskList
  1159. workspacePath={tab.workspacePath}
  1160. remoteSessionId={tab.remoteSessionId}
  1161. workspaceIdentity={tab.workspaceIdentity}
  1162. tasks={taskItems}
  1163. pinnedTasks={EMPTY_PINNED_TASKS}
  1164. activeTaskId={isActiveWorkspace ? activeTaskId : null}
  1165. onSelectTask={handleSelectTask}
  1166. showCreateButton={false}
  1167. showFooter={false}
  1168. loading={taskListLoading}
  1169. hasMore={taskListHasMore}
  1170. mobileActiveTaskKey={mobileActiveTaskKey}
  1171. onShowMore={onShowMoreTasks}
  1172. onRenameTask={handleRenameTask}
  1173. onSetTaskPinned={handleSetTaskPinned}
  1174. onArchiveTask={handleArchiveTask}
  1175. onSetTaskUnread={handleSetTaskUnread}
  1176. readOnlyReason={readOnlyReason}
  1177. />
  1178. </CollapsibleContent>
  1179. </Collapsible>
  1180. <RemoteSyncDialogs
  1181. canSyncSkills={showRemoteSkillSyncAction}
  1182. canSyncMcp={showRemoteSkillSyncAction}
  1183. canSyncPlugins={showRemoteSkillSyncAction}
  1184. skillOpen={remoteSkillSyncOpen}
  1185. mcpOpen={remoteMcpSyncOpen}
  1186. pluginOpen={remotePluginSyncOpen}
  1187. onSkillOpenChange={setRemoteSkillSyncOpen}
  1188. onMcpOpenChange={setRemoteMcpSyncOpen}
  1189. onPluginOpenChange={setRemotePluginSyncOpen}
  1190. localSkillSyncService={baseServices.skillSyncService}
  1191. remoteSkillSyncService={services.skillSyncService}
  1192. localMcpSyncService={baseServices.mcpSyncService}
  1193. remoteMcpSyncService={services.mcpSyncService}
  1194. localPluginSyncService={baseServices.pluginSyncService}
  1195. remotePluginSyncService={services.pluginSyncService}
  1196. localZCodeAgentService={baseServices.zcodeAgentService}
  1197. remoteZCodeAgentService={services.zcodeAgentService}
  1198. remoteTarget={tab.remoteTarget}
  1199. skillWorkspacePath={tab.workspacePath}
  1200. mcpWorkspacePath={tab.workspacePath}
  1201. pluginWorkspacePath={tab.workspacePath}
  1202. pluginLocalWorkspacePath={tab.localWorkspacePath}
  1203. mcpLocalWorkspacePath={tab.localWorkspacePath}
  1204. workspaceIdentity={tab.workspaceIdentity}
  1205. onSkillsSynced={async () => {
  1206. await invalidateDeferredDraftSessionForSkillChange({
  1207. zcodeSessionService: services.zcodeSessionService,
  1208. workspacePath: tab.workspacePath,
  1209. workspaceIdentity: tab.workspaceIdentity,
  1210. reason: "sidebar-remote-skill-sync",
  1211. });
  1212. await refreshSharedSkillStoreForWorkspace({
  1213. workspacePath: tab.workspacePath,
  1214. workspaceIdentity: tab.workspaceIdentity,
  1215. skillsService: services.skillsService,
  1216. });
  1217. }}
  1218. onMcpSynced={async () => {
  1219. await useMcpStore
  1220. .getState()
  1221. .ensureLoadedForWorkspace(
  1222. tab.workspacePath,
  1223. services.mcpSyncService,
  1224. tab.workspaceIdentity,
  1225. );
  1226. }}
  1227. onPluginsSynced={async () => {
  1228. await refreshWorkspacePluginCapabilitiesAfterRemoteSync({
  1229. commandsService: services.commandsService,
  1230. mcpSyncService: services.mcpSyncService,
  1231. reason: "sidebar-remote-plugin-sync",
  1232. skillsService: services.skillsService,
  1233. workspaceIdentity: tab.workspaceIdentity,
  1234. workspacePath: tab.workspacePath,
  1235. zcodeAgentService: services.zcodeAgentService,
  1236. zcodeSessionService: services.zcodeSessionService,
  1237. });
  1238. }}
  1239. />
  1240. {/* 项目别名编辑:复用任务重命名对话框(IME Enter 语义已内建),空值即清除别名。 */}
  1241. <TaskRenameDialog
  1242. open={workspaceAliasDialogOpen}
  1243. value={workspaceAliasDraft}
  1244. inputRef={workspaceAliasInputRef}
  1245. intl={intl}
  1246. title={intl.formatMessage({ id: "workspaceSidebar.renameProject" })}
  1247. placeholder={intl.formatMessage({ id: "workspaceSidebar.renameProjectPlaceholder" })}
  1248. onOpenChange={setWorkspaceAliasDialogOpen}
  1249. onChange={setWorkspaceAliasDraft}
  1250. onCancel={() => setWorkspaceAliasDialogOpen(false)}
  1251. onConfirm={handleConfirmWorkspaceAlias}
  1252. />
  1253. </li>
  1254. );
  1255. });
  1256. WorkspaceSidebarItem.displayName = "WorkspaceSidebarItem";