WorkspaceSidebarItem.tsx 50 KB

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