/* eslint-disable max-lines -- workspace 行同时承载折叠、远端状态和快捷操作,先保持同文件收口。 */ import { memo, useCallback, useEffect, useRef, useState, type CSSProperties, type MouseEvent, } from "react"; import { CheckIcon, CircleAlert, Cloud, CopyIcon, Ellipsis, Folder, FolderOpen, House, InfoIcon, ListTree, LoaderCircle, RefreshCwIcon, MessageCirclePlus, XIcon, } from "lucide-react"; import type { useSortable } from "@dnd-kit/sortable"; import { BorderBeam } from "border-beam"; import { STATUS_DOT } from "@/components/workflow-graph/run-status-presentation.js"; import { Button, buttonVariants } from "@/components/ui/button.js"; import { Collapsible, CollapsibleContent, CollapsibleTrigger, } from "@/components/ui/collapsible.js"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu.js"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from "@/components/ui/tooltip.js"; import { ControlHintTooltip } from "@/ControlHintTooltip.js"; import { useZCodeIntl } from "@/i18n/IntlProvider.js"; import { buildWorkspaceSessionKey, formatRemoteWorkspaceDisplayLabel, } from "@/lib/remoteWorkspaceHistory.js"; import { TaskList } from "@/TaskList.js"; import { selectWorkspaceZCodeState, useZCodeSessionStore } from "@/store/zcodeSessionStore.js"; import type { WorkspaceTabState } from "@/store/tabStore.js"; import type { RemoteConnectionLogEntry } from "@/hooks/useRemoteConnectionLogs.js"; import { ReconnectingRemoteWorkspaceLogTooltip } from "@/WorkspaceSidebar/ReconnectingRemoteWorkspaceLogTooltip.js"; import { cn } from "@/components/lib/utils.js"; import { TID_WORKSPACE_CLOSE, TID_WORKSPACE_FILE_TREE_BUTTON, TID_WORKSPACE_ITEM, testId, } from "@zcode/shared"; import type { ZCodeTaskMeta } from "@zcode/shared"; import { useBaseWorkspaceServices, useWorkspaceServices } from "@/hooks/useWorkspaceServices.js"; import { applyTaskQueryCacheMutation, invalidateTaskQueryCacheByScopes, } from "@/store/taskQueryCacheStore.js"; import { useRemotePinnedTaskStore } from "@/store/remotePinnedTaskStore.js"; import { useRemoteTimelineTaskStore } from "@/store/remoteTimelineTaskStore.js"; import { logger } from "@/logger.js"; import { RemoteSyncDialogs, RemoteSyncMenuItems, shouldShowRemoteSyncActions, } from "@/settings/RemoteSyncActions.js"; import { invalidateDeferredDraftSessionForSkillChange } from "@/lib/zcodeDraftSkillInvalidation.js"; import { refreshSharedSkillStoreForWorkspace } from "@/lib/skillStoreRefresh.js"; import { refreshWorkspacePluginCapabilitiesAfterRemoteSync } from "@/lib/remotePluginSyncRefresh.js"; import { useMcpStore } from "@/store/mcpStore.js"; import { TaskRowActionButton } from "@/workspace-grouped-tasks/task-row-action-button.js"; import { releaseWorkspaceRuntimeAfterProjectRemoval } from "@/lib/workspaceRuntimeRelease.js"; import { hasRunningWorkspaceChat, scanWindowsReservedDeviceNameFiles, } from "@/lib/workspaceRemovalSafety.js"; import { useConfirmDialog } from "@/hooks/useConfirmDialog.js"; import { toast } from "@/components/ui/toast.js"; export type SortableBindings = Pick, "attributes" | "listeners">; // workspace 行在流式工具事件期间会因父级刷新而重渲染; // TaskList 如果每次收到新的空数组,会把等价数据误判成变化并连带刷新任务行。 const EMPTY_PINNED_TASKS: ZCodeTaskMeta[] = []; function isHomeWorkspacePath(path: string): boolean { const normalizedPath = path.replace(/\\/g, "/").replace(/\/+$/, ""); return /^(\/Users\/[^/]+|\/home\/[^/]+|[A-Za-z]:\/Users\/[^/]+)$/.test(normalizedPath); } type SshRemoteTarget = Extract, { kind: "ssh" }>; interface SshWorkspaceTooltipDetails { alias: string | null; hostLabel: string; workspacePath: string; } function formatSshRemoteHostLabel(target: SshRemoteTarget): string { const username = target.username.trim(); const host = target.host.trim(); const port = target.port ?? 22; return `${username}@${host}:${port}`; } function getSshWorkspaceTooltipDetails(tab: WorkspaceTabState): SshWorkspaceTooltipDetails | null { if (tab.remoteTarget?.kind !== "ssh") { return null; } return { alias: tab.remoteTarget.sshConfigAlias?.trim() || null, hostLabel: formatSshRemoteHostLabel(tab.remoteTarget), workspacePath: tab.workspacePath, }; } export const WorkspaceSidebarItem = memo(function WorkspaceSidebarItem({ tab, isActiveWorkspace, isExpanded, closeTab, toggleWorkspaceExpanded, onSelectTask, onStartDraftInWorkspace, taskItems, taskListLoading, taskListHasMore, taskListHasUnread = false, taskListLiveWorkflowCount = 0, onShowMoreTasks, reconnectingRemoteWorkspaceKeys, remoteWorkspaceErrorByWorkspaceKey, reconnectingRemoteWorkspaceLogsByWorkspaceKey, onReconnectRemoteWorkspace, onOpenFileTree, itemRef, itemStyle, sortableBindings, isDragging = false, }: { tab: WorkspaceTabState; isActiveWorkspace: boolean; isExpanded: boolean; activateTab: (tabId: string) => void; closeTab: (tabId: string) => void; toggleWorkspaceExpanded: (workspacePath: string) => void; onSelectTask: ( targetWorkspacePath: string, taskId: string, targetWorkspaceIdentity?: string, ) => void; onStartDraftInWorkspace: (targetWorkspacePath: string, targetWorkspaceIdentity?: string) => void; taskItems: ZCodeTaskMeta[]; taskListLoading: boolean; taskListHasMore: boolean; taskListHasUnread?: boolean; /** 组内在跑的工作流 run 数;项目收起时在未读点旁画脉冲灯(>1 带数量)。 */ taskListLiveWorkflowCount?: number; onShowMoreTasks: () => void; reconnectingRemoteWorkspaceKeys: string[]; remoteWorkspaceErrorByWorkspaceKey: Record; reconnectingRemoteWorkspaceLogsByWorkspaceKey: Record; onReconnectRemoteWorkspace: (workspaceKey: string) => Promise; onOpenFileTree?: (target: { workspacePath: string; workspaceName: string; workspaceIdentity?: string; workspaceRemoteSessionId?: string; }) => void; itemRef?: (node: HTMLLIElement | null) => void; itemStyle?: CSSProperties; sortableBindings?: SortableBindings; isDragging?: boolean; }) { const { intl } = useZCodeIntl(); const workspaceZCodeState = useZCodeSessionStore((state) => selectWorkspaceZCodeState(state, tab.workspacePath, tab.workspaceIdentity), ); const activeTaskId = workspaceZCodeState.activeTaskId; const removeTaskState = useZCodeSessionStore((state) => state.removeTaskState); const upsertOptimisticTaskListItem = useZCodeSessionStore( (state) => state.upsertOptimisticTaskListItem, ); const removeOptimisticTaskListItem = useZCodeSessionStore( (state) => state.removeOptimisticTaskListItem, ); const setTaskUnreadIndicator = useZCodeSessionStore((state) => state.setTaskUnreadIndicator); const services = useWorkspaceServices( tab.workspacePath, tab.remoteSessionId, tab.workspaceIdentity, tab.remoteTarget, ); const confirmDialog = useConfirmDialog(); const baseServices = useBaseWorkspaceServices(); const zcodeTaskService = services.zcodeTaskService; const taskItemsRef = useRef(taskItems); taskItemsRef.current = taskItems; const workspaceZCodeStateRef = useRef(workspaceZCodeState); workspaceZCodeStateRef.current = workspaceZCodeState; const findCurrentTaskItem = useCallback((taskId: string) => { // 流式刷新会重建 taskItems 数组,任务操作回调如果直接依赖数组, // 即使任务语义没变也会换引用,继续击穿 TaskListItem 的 memo。 // 用 ref 在调用时读取最新列表,既保持回调稳定,也避免乐观更新拿到过期 meta。 return taskItemsRef.current.find((task) => task.taskId === taskId) ?? null; }, []); const isHomeWorkspace = isHomeWorkspacePath(tab.workspacePath); const readOnlyReason = tab.availability === "unavailable-local-directory" ? intl.formatMessage({ id: "workspaceSidebar.unavailableLocalDirectory" }) : undefined; const remoteWorkspaceKey = buildWorkspaceSessionKey(tab); const isRemoteWorkspace = Boolean( tab.remoteSessionId || tab.remoteTarget || tab.workspaceIdentity, ); const isDisconnectedRemoteWorkspace = Boolean(isRemoteWorkspace && !tab.remoteSessionId); const isReconnectPending = Boolean( isDisconnectedRemoteWorkspace && reconnectingRemoteWorkspaceKeys.includes(remoteWorkspaceKey), ); const remoteWorkspaceError = remoteWorkspaceErrorByWorkspaceKey[remoteWorkspaceKey]; const workspaceSidebarLabel = formatRemoteWorkspaceDisplayLabel(tab.label, tab.remoteTarget); const sshWorkspaceTooltipDetails = getSshWorkspaceTooltipDetails(tab); const reconnectRuntimeLogs = reconnectingRemoteWorkspaceLogsByWorkspaceKey[remoteWorkspaceKey] ?? []; const showRemoteConnectionErrorNotice = Boolean( // 远程项目只要处于“断连”就显示叹号,会把“尚未连接/已断开但无错误”和“真实连接失败”混在一起, // 用户看到列表里的 warning 图标时无法判断是否真有故障。 // 这里收敛成只有存在连接错误正文时才显示叹号,普通未连接状态仅保留重连入口。 isDisconnectedRemoteWorkspace && !isReconnectPending && remoteWorkspaceError?.trim(), ); const showReconnectAction = Boolean(isDisconnectedRemoteWorkspace); const showFileTreeAction = Boolean(onOpenFileTree && !isDisconnectedRemoteWorkspace); const showRemoteSkillSyncAction = shouldShowRemoteSyncActions({ remoteSessionId: tab.remoteSessionId, remoteTarget: tab.remoteTarget, clientMode: "desktop-continuous" as const, hasLocalSourceService: Boolean(baseServices.skillSyncService), }); // 远端工作区在“重连中”时,之前只有轻微背景呼吸效果, // 在侧边栏高密度列表里不够醒目,用户很难快速判断哪个容器仍在连接。 // 这里复用 BorderBeam,只在重连进行中激活,让连接态反馈更清晰, // 同时避免在普通空闲态或断连态误显示为“仍在运行”。 const shouldShowRemoteConnectingBorderBeam = isReconnectPending; const [isRemoteErrorCopied, setIsRemoteErrorCopied] = useState(false); const [remoteSkillSyncOpen, setRemoteSkillSyncOpen] = useState(false); const [remoteMcpSyncOpen, setRemoteMcpSyncOpen] = useState(false); const [remotePluginSyncOpen, setRemotePluginSyncOpen] = useState(false); const [workspaceRowHovered, setWorkspaceRowHovered] = useState(false); const [workspaceRowFocusWithin, setWorkspaceRowFocusWithin] = useState(false); const [workspaceActionMenuOpen, setWorkspaceActionMenuOpen] = useState(false); const [isHoverNone] = useState( () => typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(hover: none)").matches, ); const shouldMountWorkspaceRowActions = // workspace action 以前常驻 DOM,仅靠 opacity 隐藏;相邻 tooltip 会在 // 浮层定位完成前误认隐藏 trigger,短暂显示到错误位置。改为交互时挂载,菜单打开时保活。 workspaceRowHovered || workspaceRowFocusWithin || workspaceActionMenuOpen || isHoverNone; const remoteErrorCopyResetRef = useRef(null); useEffect(() => { return () => { if (remoteErrorCopyResetRef.current !== null) { window.clearTimeout(remoteErrorCopyResetRef.current); } }; }, []); const handleWorkspaceOpenChange = useCallback( (nextOpen: boolean) => { if (isDisconnectedRemoteWorkspace) { return; } // workspace 草稿导航本身会把 workspace 标记为展开。 // 之前在 Collapsible 的 onOpenChange 里无论展开/收起都先激活 workspace, // 收起后的下一次点击会先被激活路径展开,再被 toggleWorkspaceExpanded 反向切回收起, // 表现出来就是"收起后再也打不开"。 // 这里把职责拆开:展开时只走草稿导航;收起时只做 toggle,避免两条状态更新互相抵消。 if (nextOpen) { if (!isExpanded) { // workspace 行表达“打开这个 workspace”,不是恢复它上次选中的 session。 // 统一走上层草稿导航事务,让 workspace identity、group/pane 清理和 draft 聚焦一起收口。 onStartDraftInWorkspace(tab.workspacePath, tab.workspaceIdentity); } } else if (isExpanded) { toggleWorkspaceExpanded(tab.workspacePath); } }, [ isDisconnectedRemoteWorkspace, isExpanded, onStartDraftInWorkspace, tab.workspaceIdentity, tab.workspacePath, toggleWorkspaceExpanded, ], ); const handleSelectTask = useCallback( (taskId: string) => { // 性能优化:上层 handleSelectTask 已经会按 workspacePath 激活 tab。 // 这里重复 activate 会额外触发一轮 tab store 更新,把整列 workspace 行都带着重渲染一次。 onSelectTask(tab.workspacePath, taskId, tab.workspaceIdentity); }, [onSelectTask, tab.workspaceIdentity, tab.workspacePath], ); const handleActionMouseDown = useCallback((event: MouseEvent) => { event.preventDefault(); event.stopPropagation(); }, []); const handleActionMenuClick = useCallback((event: MouseEvent) => { // DropdownMenuContent 虽然通过 Portal 渲染到行外,React 合成 click 仍会沿组件树 // 冒泡到外层 CollapsibleTrigger。收起的 workspace 点“移除”时,会先 closeTab,再被展开回调 // 当成“打开 workspace”重新 addTab,表现为删不掉。菜单层统一截断 click,保留菜单选择与键盘语义。 event.stopPropagation(); }, []); const handleCreateThreadClick = useCallback( (event: MouseEvent) => { event.preventDefault(); event.stopPropagation(); if (readOnlyReason) { return; } onStartDraftInWorkspace(tab.workspacePath, tab.workspaceIdentity); }, [onStartDraftInWorkspace, readOnlyReason, tab.workspaceIdentity, tab.workspacePath], ); const handleRemoveWorkspace = useCallback(async () => { const workspaceKey = tab.workspaceIdentity?.trim() || tab.workspacePath; logger.debug("[WorkspaceSidebarItem] 移除 workspace", { isExpanded, workspaceKey, }); if ( hasRunningWorkspaceChat({ workspaceState: workspaceZCodeStateRef.current, taskItems: taskItemsRef.current, }) ) { const confirmed = await confirmDialog({ title: intl.formatMessage({ id: "workspaceSidebar.removeRunningWorkspace.title" }), description: intl.formatMessage({ id: "workspaceSidebar.removeRunningWorkspace.description", }), confirmLabel: intl.formatMessage({ id: "workspaceSidebar.removeRunningWorkspace.confirm" }), cancelLabel: intl.formatMessage({ id: "common.cancel" }), confirmVariant: "destructive", }); if (!confirmed) { logger.debug("[WorkspaceSidebarItem] 用户取消移除运行中 workspace", { workspaceKey }); return; } } closeTab(tab.id); releaseWorkspaceRuntimeAfterProjectRemoval({ tab: { workspacePath: tab.workspacePath, workspaceIdentity: tab.workspaceIdentity, }, zcodeTaskService, }); // 移除 workspace 只是移除入口和连接历史,不代表用户要隐藏历史任务: // 这里只失效缓存,保留 sqlite 任务索引原状态,避免重连同一 SSH workspace 后任务像“丢了”。 invalidateTaskQueryCacheByScopes([ { workspacePath: tab.workspacePath, ...(tab.workspaceIdentity ? { workspaceIdentity: tab.workspaceIdentity } : {}), }, ]); if (!isRemoteWorkspace) { void scanWindowsReservedDeviceNameFiles(baseServices.fileService, tab.workspacePath) .then((result) => { if (result.findings.length === 0) { return; } const firstFinding = result.findings[0] ?? tab.workspacePath; toast( intl.formatMessage( { id: "workspaceSidebar.windowsReservedNameRisk" }, { count: result.findings.length, path: firstFinding }, ), { durationMs: 8_000, variant: "warning" }, ); }) .catch((error: unknown) => { // Windows 保留设备名扫描只是移除后的兼容风险提示,失败不能影响 workspace 生命周期释放。 logger.debug("[WorkspaceSidebarItem] Windows 保留名风险扫描失败", { workspaceKey, error, }); }); } }, [ baseServices.fileService, closeTab, confirmDialog, intl, isExpanded, isRemoteWorkspace, tab.id, tab.workspaceIdentity, tab.workspacePath, zcodeTaskService, ]); const handleReconnectRemoteWorkspace = useCallback( (event: MouseEvent) => { event.preventDefault(); event.stopPropagation(); if (!isDisconnectedRemoteWorkspace || isReconnectPending) { return; } void onReconnectRemoteWorkspace(remoteWorkspaceKey); }, [ isDisconnectedRemoteWorkspace, isReconnectPending, onReconnectRemoteWorkspace, remoteWorkspaceKey, ], ); const handleOpenWorkspaceFileTree = useCallback( (event: MouseEvent) => { event.preventDefault(); event.stopPropagation(); if (isDisconnectedRemoteWorkspace || readOnlyReason || !onOpenFileTree) { return; } onOpenFileTree({ workspacePath: tab.workspacePath, workspaceName: tab.label, workspaceIdentity: tab.workspaceIdentity, workspaceRemoteSessionId: tab.remoteSessionId, }); }, [ isDisconnectedRemoteWorkspace, onOpenFileTree, readOnlyReason, tab.label, tab.remoteSessionId, tab.workspaceIdentity, tab.workspacePath, ], ); // 这些 TaskList 操作以前在 JSX 中每次 render 都创建新闭包。 // 流式事件刷新 workspace 行时,即使任务数据没变,也会穿透 TaskList/TaskListItem 的 memo。 const handleRenameTask = useCallback( async (taskId: string, title: string) => { if (readOnlyReason) { return null; } const previousTask = findCurrentTaskItem(taskId); logger.info("[WorkspaceSidebarItem] rename service call start", { taskId, workspacePath: tab.workspacePath, workspaceIdentity: tab.workspaceIdentity, previousTitleLength: previousTask?.title.length, nextTitleLength: title.length, }); let meta: ZCodeTaskMeta; try { meta = await zcodeTaskService.renameTask({ taskId, workspacePath: tab.workspacePath, title, ...(tab.workspaceIdentity ? { workspaceIdentity: tab.workspaceIdentity } : {}), }); } catch (error) { logger.error("[WorkspaceSidebarItem] rename service call failed", { taskId, workspacePath: tab.workspacePath, workspaceIdentity: tab.workspaceIdentity, message: error instanceof Error ? error.message : String(error), }); throw error; } logger.info("[WorkspaceSidebarItem] rename service call resolved", { taskId, workspacePath: tab.workspacePath, workspaceIdentity: tab.workspaceIdentity, resolvedTitleLength: meta.title.length, }); upsertOptimisticTaskListItem(tab.workspacePath, meta, tab.workspaceIdentity); if (tab.workspaceIdentity) { useRemoteTimelineTaskStore.getState().upsertTask(meta); } applyTaskQueryCacheMutation({ previousTask: previousTask ?? meta, nextTask: meta, previousState: { pinned: false, archived: false }, nextState: { pinned: false, archived: false }, }); logger.info("[WorkspaceSidebarItem] rename cache mutation applied", { taskId, workspacePath: tab.workspacePath, workspaceIdentity: tab.workspaceIdentity, }); return meta; }, [ tab.workspaceIdentity, tab.workspacePath, findCurrentTaskItem, readOnlyReason, upsertOptimisticTaskListItem, zcodeTaskService, ], ); const handleSetTaskPinned = useCallback( async (taskId: string, pinned: boolean) => { if (readOnlyReason) { return null; } const previousTask = findCurrentTaskItem(taskId); if (previousTask) { // workspace 内 pin 以前等远端/本地 RPC 返回后才更新全局 pinned 缓存, // pin 区会先消失再补回来。这里先乐观同步列表成员关系,失败时回滚。 if (tab.workspaceIdentity && pinned) { useRemotePinnedTaskStore.getState().upsertTask(previousTask); useRemoteTimelineTaskStore .getState() .removeTask(tab.workspacePath, taskId, tab.workspaceIdentity); } if (tab.workspaceIdentity && !pinned) { useRemotePinnedTaskStore .getState() .removeTask(tab.workspacePath, taskId, tab.workspaceIdentity); useRemoteTimelineTaskStore.getState().upsertTask(previousTask); } applyTaskQueryCacheMutation({ previousTask, nextTask: previousTask, previousState: { pinned: false, archived: false }, nextState: { pinned, archived: false }, }); } try { const meta = await zcodeTaskService.setTaskPinned({ taskId, workspacePath: tab.workspacePath, pinned, ...(tab.workspaceIdentity ? { workspaceIdentity: tab.workspaceIdentity } : {}), }); removeOptimisticTaskListItem(tab.workspacePath, taskId, tab.workspaceIdentity); if (tab.workspaceIdentity && pinned) { useRemotePinnedTaskStore.getState().upsertTask(meta); useRemoteTimelineTaskStore .getState() .removeTask(tab.workspacePath, taskId, tab.workspaceIdentity); } if (tab.workspaceIdentity && !pinned) { useRemotePinnedTaskStore .getState() .removeTask(tab.workspacePath, taskId, tab.workspaceIdentity); useRemoteTimelineTaskStore.getState().upsertTask(meta); } applyTaskQueryCacheMutation({ previousTask: previousTask ?? meta, nextTask: meta, previousState: { pinned, archived: false }, nextState: { pinned, archived: false }, }); return meta; } catch (error) { if (previousTask) { if (tab.workspaceIdentity && pinned) { useRemotePinnedTaskStore .getState() .removeTask(tab.workspacePath, taskId, tab.workspaceIdentity); useRemoteTimelineTaskStore.getState().upsertTask(previousTask); } if (tab.workspaceIdentity && !pinned) { useRemotePinnedTaskStore.getState().upsertTask(previousTask); useRemoteTimelineTaskStore .getState() .removeTask(tab.workspacePath, taskId, tab.workspaceIdentity); } applyTaskQueryCacheMutation({ previousTask, nextTask: previousTask, previousState: { pinned, archived: false }, nextState: { pinned: false, archived: false }, }); } throw error; } }, [ removeOptimisticTaskListItem, readOnlyReason, tab.workspaceIdentity, tab.workspacePath, findCurrentTaskItem, zcodeTaskService, ], ); const handleArchiveTask = useCallback( async (taskId: string) => { if (readOnlyReason) { return null; } const previousTask = findCurrentTaskItem(taskId); const meta = await zcodeTaskService.archiveTask({ taskId, workspacePath: tab.workspacePath, ...(tab.workspaceIdentity ? { workspaceIdentity: tab.workspaceIdentity } : {}), }); removeTaskState(tab.workspacePath, taskId, tab.workspaceIdentity); if (tab.workspaceIdentity) { useRemoteTimelineTaskStore .getState() .removeTask(tab.workspacePath, taskId, tab.workspaceIdentity); useRemotePinnedTaskStore .getState() .removeTask(tab.workspacePath, taskId, tab.workspaceIdentity); } applyTaskQueryCacheMutation({ previousTask: previousTask ?? meta, nextTask: meta, previousState: { pinned: false, archived: false }, nextState: { pinned: false, archived: true }, }); return meta; }, [ removeTaskState, readOnlyReason, tab.workspaceIdentity, tab.workspacePath, findCurrentTaskItem, zcodeTaskService, ], ); const handleSetTaskUnread = useCallback( async (taskId: string, unread: boolean) => { if (readOnlyReason) { return null; } const previousTask = findCurrentTaskItem(taskId); const meta = await zcodeTaskService.setTaskUnread({ taskId, workspacePath: tab.workspacePath, unread, ...(tab.workspaceIdentity ? { workspaceIdentity: tab.workspaceIdentity } : {}), }); setTaskUnreadIndicator(tab.workspacePath, taskId, unread, tab.workspaceIdentity); upsertOptimisticTaskListItem(tab.workspacePath, meta, tab.workspaceIdentity); if (tab.workspaceIdentity) { useRemoteTimelineTaskStore.getState().upsertTask(meta); } applyTaskQueryCacheMutation({ previousTask: previousTask ?? meta, nextTask: meta, previousState: { pinned: false, archived: false }, nextState: { pinned: false, archived: false }, }); return meta; }, [ setTaskUnreadIndicator, readOnlyReason, tab.workspaceIdentity, tab.workspacePath, findCurrentTaskItem, upsertOptimisticTaskListItem, zcodeTaskService, ], ); const handleCopyRemoteWorkspaceError = useCallback(() => { if (!remoteWorkspaceError || remoteWorkspaceError.trim().length === 0) { return; } navigator.clipboard.writeText(remoteWorkspaceError).then(() => { setIsRemoteErrorCopied(true); if (remoteErrorCopyResetRef.current !== null) { window.clearTimeout(remoteErrorCopyResetRef.current); } remoteErrorCopyResetRef.current = window.setTimeout(() => { setIsRemoteErrorCopied(false); remoteErrorCopyResetRef.current = null; }, 1500); }); }, [remoteWorkspaceError]); const renderWorkspaceIcon = () => { // workspace 行之前在 hover/展开时会把目录图标切成箭头, // 视觉上会多出一层“树形展开控件”的暗示;当前交互只需要保留项目图标本身, // 这样能减少噪音,也避免用户把它理解成独立的箭头开关。 if (isExpanded && !isDisconnectedRemoteWorkspace) { return isRemoteWorkspace ? ( ) : isHomeWorkspace ? ( ) : ( ); } return isRemoteWorkspace ? ( ) : isHomeWorkspace ? ( ) : ( ); }; const workspaceLabelContent = (
{renderWorkspaceIcon()}
{workspaceSidebarLabel}
{!isExpanded && taskListHasUnread ? (
); return (
  • setWorkspaceRowHovered(true)} onMouseLeave={() => setWorkspaceRowHovered(false)} onFocusCapture={() => setWorkspaceRowFocusWithin(true)} onBlurCapture={(event) => { if (!event.currentTarget.contains(event.relatedTarget as Node | null)) { setWorkspaceRowFocusWithin(false); } }} {...(sortableBindings?.attributes ?? {})} {...(sortableBindings?.listeners ?? {})} > {sshWorkspaceTooltipDetails ? ( {workspaceLabelContent} {intl.formatMessage({ id: "workspaceSidebar.sshConnectionTitle", })}
    {sshWorkspaceTooltipDetails.alias ? ( <>
    {intl.formatMessage({ id: "workspaceSidebar.sshConnectionAlias", })}
    {sshWorkspaceTooltipDetails.alias}
    ) : null}
    {intl.formatMessage({ id: "workspaceSidebar.sshConnectionHost", })}
    {sshWorkspaceTooltipDetails.hostLabel}
    {intl.formatMessage({ id: "workspaceSidebar.sshConnectionPath", })}
    {sshWorkspaceTooltipDetails.workspacePath}
    ) : ( workspaceLabelContent )}
    {/* {isRemoteWorkspace && isReconnectPending ? ( ) : null} */}
    {shouldMountWorkspaceRowActions ? ( setRemoteSkillSyncOpen(true)} onOpenMcpSync={() => setRemoteMcpSyncOpen(true)} onOpenPluginSync={() => setRemotePluginSyncOpen(true)} /> { event.preventDefault(); event.stopPropagation(); }} onSelect={(event) => { event.preventDefault(); void handleRemoveWorkspace(); }} > {intl.formatMessage({ id: "workspaceSidebar.remove", })} ) : null} {shouldMountWorkspaceRowActions && showFileTreeAction ? ( {/* Project 文件树入口以前单独覆盖 hover:bg-surface-hover, 与 Pinned / Grouped 的 bg-hover 不一致;三种入口统一复用同一 action。 */} ) : null} {showRemoteConnectionErrorNotice ? ( remoteWorkspaceError ? (
    {/* * 远端连接失败 tooltip 之前拆成“标题 + 内层卡片”两段结构, * 在 sidebar 这种高密度区域里会显得层级过多,像一个迷你弹窗,不够轻。 * 这里收敛回普通 tooltip 语义:一层浮层里直接放错误正文和复制按钮, * 保留可读性与复制能力,同时避免视觉上过度设计。 */}
                                    {remoteWorkspaceError}
                                  
    ) : (
    ) ) : null} {showReconnectAction ? ( isReconnectPending ? ( {/* SSH workspace 重连中时,右侧原本只有 spinning 图标, 用户无法在聊天页任务列表里确认连接卡在哪一步。这里复用 SSH dialog 的连接日志 tooltip, 保持行内布局稳定,同时把诊断信息放到 hover 浮层里。 */}
    ) : ( ) ) : shouldMountWorkspaceRowActions ? ( ) : null}
    { await invalidateDeferredDraftSessionForSkillChange({ zcodeSessionService: services.zcodeSessionService, workspacePath: tab.workspacePath, workspaceIdentity: tab.workspaceIdentity, reason: "sidebar-remote-skill-sync", }); await refreshSharedSkillStoreForWorkspace({ workspacePath: tab.workspacePath, workspaceIdentity: tab.workspaceIdentity, skillsService: services.skillsService, }); }} onMcpSynced={async () => { await useMcpStore .getState() .ensureLoadedForWorkspace( tab.workspacePath, services.mcpSyncService, tab.workspaceIdentity, ); }} onPluginsSynced={async () => { await refreshWorkspacePluginCapabilitiesAfterRemoteSync({ commandsService: services.commandsService, mcpSyncService: services.mcpSyncService, reason: "sidebar-remote-plugin-sync", skillsService: services.skillsService, workspaceIdentity: tab.workspaceIdentity, workspacePath: tab.workspacePath, zcodeAgentService: services.zcodeAgentService, zcodeSessionService: services.zcodeSessionService, }); }} />
  • ); }); WorkspaceSidebarItem.displayName = "WorkspaceSidebarItem";