import { useRemoteConnectionProgress, RemoteConnectionMinimizedProgress, summarizeRemoteConnectionProgress, } from "@/remote-connection-flow/ui/RemoteConnectionProgress.js"; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, } from "@/components/ui/dialog.js"; import { useOptionalPlatform } from "@/hooks/usePlatform.js"; import { DesktopCommandIds, ZCODE_VERSION } from "@zcode/shared"; /* eslint-disable max-lines -- Source/Profile/迁移三类管理操作共享同一 Host 快照和错误状态。 */ import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { ArrowUpRight, ChevronDown, ChevronRight, Ellipsis, FileWarning, Folder, ListTree, LoaderCircle, Pencil, Plus, Power, RotateCw, Server, Box, TerminalSquare, Copy, Trash2, Unplug, Wrench, } from "lucide-react"; import { resolveWorkspaceKey } from "@zcode/shared"; import type { ConnectionProfile, AppSettings, SourceServerManagementSnapshot, SourceServerMigrationReport, SourceServerRecord, SourceServerWorkspaceHistoryEntry, } from "@zcode/shared"; import type { ISourceServerManagementService } from "@zcode/services"; import { getPathLeaf } from "@/lib/path.js"; import { toast } from "@/components/ui/toast.js"; import { getSourceServerManagementErrorMessage } from "@/lib/sourceServerManagementError.js"; import { Button } from "@/components/ui/button.js"; import { Switch } from "@/components/ui/switch.js"; import { cn } from "@/components/lib/utils.js"; import { useConfirmDialog } from "@/hooks/useConfirmDialog.js"; import { useSourceServerManagementSnapshot } from "@/hooks/useSourceServerManagementSnapshot.js"; import { useSourceServerOperationLogs } from "@/hooks/useSourceServerOperationLogs.js"; import { useZCodeIntl } from "@/i18n/IntlProvider.js"; import { SourceServerMigrationReportPanel } from "@/settings/SourceServerMigrationReportPanel.js"; import { resolveSourceServerUpdatePercent, SourceServerLogList, SourceServerUpdateActivity, } from "@/settings/SourceServerUpdateActivity.js"; import { SourceServerDeviceRow, type SourceServerDeviceRowProgress, } from "@/settings/SourceServerDeviceRow.js"; import { matchesSourceServerDeviceSearch, reconcileSourceServerDeviceOrder, } from "@/settings/sourceServerDeviceList.js"; import { SettingsSearchInput } from "@/settings/SettingsSearchInput.js"; import { formatRemoteConnectionError } from "@/lib/remoteConnectionPresentation.js"; import { resolveRemoteConnectionPresentation, getRemoteDevicePresentationInput, classifyRemoteConnectionError, type RemoteConnectionPresentation, } from "@/lib/remoteConnectionPresentation.js"; import { sourceServerUpdatePreferences, sourceServerUpdateKey, useDeferredSourceServerUpdates, } from "@/lib/sourceServerUpdatePreferences.js"; import { getRemoteServiceLifecycleDescription, getSourceServerForceUpdateDescription, getSourceServerDowngradeConfirmation, getSourceServerReinstallConfirmation, isSourceServerCredentialsRequiredError, readSourceServerRunningTasksForConfirmation, resolveSourceServerLifecycleActionAvailability, resolveSourceServerReinstallAvailability, runSourceServerUpdate, } from "@/lib/sourceServerUpdateAction.js"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu.js"; import { EditConnectionProfileDialog } from "@/remote-connection/EditConnectionProfileDialog.js"; import { formatConnectionProfileTarget, RemoteConnectionKindTag, RemoteConnectionStatusTag, } from "@/remote-connection/RemoteConnectionTags.js"; import type { WorkspaceTabState } from "@/store/tabStore.js"; import { getWorkspaceSourceServerId } from "@/conversation-workspace-target/sourceIdentity.js"; import { buildRemoteWorkspaceProjection } from "@/remote/remoteWorkspaceProjection.js"; function formatTimestamp(timestamp: number, locale: string): string { return new Date(timestamp).toLocaleString(locale, { dateStyle: "medium", timeStyle: "short", }); } function formatRelativeTimestamp( timestamp: number, locale: string, formatMessage: (descriptor: { id: string }, values?: Record) => string, ): string { const elapsed = Math.max(0, Date.now() - timestamp); if (elapsed < 60_000) return formatMessage({ id: "common.justNow" }); if (elapsed < 60 * 60_000) { return formatMessage({ id: "common.minutesAgo" }, { count: Math.floor(elapsed / 60_000) }); } if (elapsed < 24 * 60 * 60_000) { return formatMessage({ id: "common.hoursAgo" }, { count: Math.floor(elapsed / (60 * 60_000)) }); } if (elapsed < 48 * 60 * 60_000) return formatMessage({ id: "common.yesterday" }); return new Date(timestamp).toLocaleDateString(locale, { month: "short", day: "numeric", }); } export function getProjectCount( snapshot: SourceServerManagementSnapshot, sourceServerId: string, remoteConversationWorkspaceBySourceServerId?: AppSettings["remoteConversationWorkspaceBySourceServerId"], ): number { return new Set( snapshot.workspaceHistory .filter( (entry) => entry.sourceServerId === sourceServerId && remoteConversationWorkspaceBySourceServerId?.[sourceServerId]?.workspacePath !== entry.workspacePath, ) .map((entry) => resolveWorkspaceKey(entry)), ).size; } const COLLAPSED_PROJECT_COUNT = 3; /** 设备行在后台连接等用户处理、或后台连接进行中时显示的状态(RDUX-13 进度展示)。 */ const BACKGROUND_WAITING_PRESENTATION = resolveRemoteConnectionPresentation({ state: "pending" }); const BACKGROUND_CONNECTING_PRESENTATION = resolveRemoteConnectionPresentation({ state: "connecting", }); function getProjectDisplayName(server: SourceServerRecord, workspacePath: string): string { return ( server.declaredWorkspaces?.find((item) => item.workspacePath === workspacePath)?.label ?? getPathLeaf(workspacePath) ); } function toggleSetItem(current: ReadonlySet, item: string): Set { const next = new Set(current); if (next.has(item)) next.delete(item); else next.add(item); return next; } /** * 失败详情要打开的连接:优先 Host failed 终态;其次是保持未连接但留有原因的连接 * (例如停止远端服务失败,Host 按自己选择的路由写入原因,Renderer 不知道是哪条连接)。 */ function findSourceErrorProfile( snapshot: SourceServerManagementSnapshot | null | undefined, sourceServerId: string, ): ConnectionProfile | undefined { const states = snapshot?.states.filter((state) => state.sourceServerId === sourceServerId) ?? []; const state = states.find((candidate) => candidate.state === "failed") ?? states .filter((candidate) => candidate.error || candidate.errorCode) .sort((left, right) => right.updatedAt - left.updatedAt)[0]; return snapshot?.profiles.find((profile) => profile.profileId === state?.profileId); } /** * 设备卡「更多」中的远端服务生命周期操作(RDLC-01)。可用状态、危险确认、同设备互斥与提示规则两者共用; * 只有停止使用 destructive 菜单项。顺序即菜单顺序:重启在停止之前。 */ const REMOTE_SERVICE_LIFECYCLE_ACTIONS = { restart: { label: "settings.source.restartRemoteService", title: "settings.source.restartRemoteServiceTitle", completedToast: "sourceServer.restartCompletedToast", failedToast: "sourceServer.restartFailedToast", intent: "source-server-restart", icon: RotateCw, variant: "default", }, stop: { label: "settings.source.stopRemoteService", title: "settings.source.stopRemoteServiceTitle", completedToast: "sourceServer.stopCompletedToast", failedToast: "sourceServer.stopFailedToast", intent: "source-server-stop", icon: Power, variant: "destructive", }, } as const; type RemoteServiceLifecycleAction = keyof typeof REMOTE_SERVICE_LIFECYCLE_ACTIONS; const REMOTE_SERVICE_LIFECYCLE_ACTION_ORDER: readonly RemoteServiceLifecycleAction[] = [ "restart", "stop", ]; function profileOperationScope(profile: ConnectionProfile): string { return profile.sourceServerId ? `source:${profile.sourceServerId}` : `profile:${profile.profileId}`; } export function SourceServerManagementPanel({ management, targetSourceServerId, targetSourceServerDetails = false, onTargetSourceServerFocused, onCreateConnection, onConnectProfile, onDisconnectSource, onShowInSidebar, onOpenProject, onShowUpdateDetails, workspaceTabs = [], settings, onUpdateSettings, hideProjectDeviceNames = false, onHideProjectDeviceNamesChange, }: { management: ISourceServerManagementService; targetSourceServerId?: string; targetSourceServerDetails?: boolean; onTargetSourceServerFocused?: () => void; onCreateConnection?: () => void; /** 用户点击连接时交给 Root 的全局弹窗,以 preferredProfileId 直达第 4 步。 */ onConnectProfile?: (profileId: string) => Promise | void; /** 用户断开设备时交给 Root 的统一 RemoteWorkspaceController。 */ onDisconnectSource?: (sourceServerId: string) => Promise; /** 「在侧边栏中显示」菜单项:返回工作区主界面(侧边栏设备分组所在处)。 */ onShowInSidebar?: (sourceServerId: string) => void; onOpenProject?: (sourceServerId: string, path: string, profileId?: string) => Promise; onShowUpdateDetails?: (sourceServerId: string) => void; workspaceTabs?: WorkspaceTabState[]; /** 「新任务」按钮(原型 L763):激活该设备已打开的 workspace tab 并开新草稿。 */ /** 有已打开 workspace tab 的设备 id 集合;「新任务」仅对这些设备渲染。 */ settings?: Pick< AppSettings, "remoteStartupAutoReconnectEnabled" | "remoteConversationWorkspaceBySourceServerId" > | null; onUpdateSettings?: (patch: Partial) => Promise | void; hideProjectDeviceNames?: boolean; onHideProjectDeviceNamesChange?: (hidden: boolean) => void; }) { const background = useRemoteConnectionProgress(); const { intl, locale } = useZCodeIntl(); const confirmDialog = useConfirmDialog(); const platform = useOptionalPlatform(); const deferredUpdates = useDeferredSourceServerUpdates(); const [startupAutoReconnect, setStartupAutoReconnect] = useState( settings?.remoteStartupAutoReconnectEnabled ?? true, ); useEffect(() => { setStartupAutoReconnect(settings?.remoteStartupAutoReconnectEnabled ?? true); }, [settings?.remoteStartupAutoReconnectEnabled]); const [editingConnection, setEditingConnection] = useState<{ profile: ConnectionProfile; server?: SourceServerRecord; focusField?: "host" | "auth"; } | null>(null); const [errorDetailsProfile, setErrorDetailsProfile] = useState(null); const [expandedSavedConnectionSources, setExpandedSavedConnectionSources] = useState>( new Set(), ); const [expandedProjectSources, setExpandedProjectSources] = useState>(new Set()); // 设备列表的展示状态(RDUX-13):只在面板内存中,面板重挂即重置,不写回 Host。 const [expandedDevices, setExpandedDevices] = useState>(new Set()); const [highlightedSourceServerId, setHighlightedSourceServerId] = useState(null); const [deviceSearch, setDeviceSearch] = useState(""); const [deviceOrder, setDeviceOrder] = useState(null); const [pendingFocusSourceServerId, setPendingFocusSourceServerId] = useState(null); const deviceTogglesRef = useRef(new Map()); // 用户操作任一行(展开或收起)都结束定位高亮;不使用定时器清除。 const toggleDevice = useCallback((sourceServerId: string) => { setExpandedDevices((current) => toggleSetItem(current, sourceServerId)); setHighlightedSourceServerId(null); }, []); // 只记录用户手动切换过的日志展开状态;未切换时由设备是否失败决定默认值。 const [logExpansionBySource, setLogExpansionBySource] = useState>( new Map(), ); // 这里只拥有面板操作的防重状态;业务状态与快照版本仍由 Host 和快照 hook 负责。 const operationsRef = useRef(new Map()); const [busyOperations, setBusyOperations] = useState>( new Map(), ); const busyScopes = new Set([...busyOperations.values()].flat()); if (background?.sourceServerId) busyScopes.add(`source:${background.sourceServerId}`); else if (background?.profileId) busyScopes.add(`profile:${background.profileId}`); const hasBusyScope = useCallback( (scope: string) => [...operationsRef.current.values()].some((scopes) => scopes.includes(scope)), [], ); const mountedRef = useRef(true); useEffect(() => { mountedRef.current = true; return () => { mountedRef.current = false; }; }, []); // 相对时间必须随时钟更新,不能依赖连接事件才重绘。 const [, setClockTick] = useState(0); useEffect(() => { const timer = setInterval(() => setClockTick((tick) => tick + 1), 60_000); return () => clearInterval(timer); }, []); const [error, setError] = useState(null); const [migrationReports, setMigrationReports] = useState< Record >({}); const { snapshot, ready, applySnapshot, refresh: refreshSnapshot, } = useSourceServerManagementSnapshot(management, { onError: (cause) => setError(getSourceServerManagementErrorMessage(cause, intl.formatMessage)), }); const focusedTargetRef = useRef(undefined); // 定位意图(RDUX-13):快照就绪且目标设备存在时,清空搜索、只展开目标行并持续高亮; // 聚焦与滚动等目标行渲染后再执行。 useEffect(() => { if (!targetSourceServerId) { focusedTargetRef.current = undefined; return; } const targetKey = `${targetSourceServerId}:${targetSourceServerDetails}`; if (!ready || focusedTargetRef.current === targetKey) return; if (!snapshot?.servers.some((server) => server.sourceServerId === targetSourceServerId)) return; setDeviceSearch(""); setExpandedDevices(new Set([targetSourceServerId])); setHighlightedSourceServerId(targetSourceServerId); setPendingFocusSourceServerId(targetSourceServerId); const failedProfile = findSourceErrorProfile(snapshot, targetSourceServerId); if (targetSourceServerDetails && failedProfile) setErrorDetailsProfile(failedProfile); focusedTargetRef.current = targetKey; onTargetSourceServerFocused?.(); }, [ ready, snapshot, targetSourceServerId, targetSourceServerDetails, onTargetSourceServerFocused, ]); const { logsByProfileId } = useSourceServerOperationLogs( management, snapshot?.profiles.map((profile) => profile.profileId), ); const projection = useMemo( () => buildRemoteWorkspaceProjection({ managementSnapshot: snapshot, tabs: [], remoteConversationWorkspaceBySourceServerId: settings?.remoteConversationWorkspaceBySourceServerId, }), [snapshot, settings?.remoteConversationWorkspaceBySourceServerId], ); const refresh = useCallback(async () => { refreshSnapshot(); }, [refreshSnapshot]); const stateByProfile = useMemo( () => new Map(snapshot?.states.map((state) => [state.profileId, state]) ?? []), [snapshot?.states], ); // 失败提示的“查看详情”在操作结束后才点击,需要读取届时最新的 Host 快照。 const snapshotRef = useRef(snapshot); useEffect(() => { snapshotRef.current = snapshot; }, [snapshot]); const run = useCallback( async ( key: string, operation: () => Promise, scopes: readonly string[] = [key], ) => { // 同设备的不同连接互斥;无关设备和日志查看独立,不用全局锁阻塞长时间更新。 if (operationsRef.current.has(key) || scopes.some(hasBusyScope)) return; operationsRef.current.set(key, scopes); setBusyOperations(new Map(operationsRef.current)); setError(null); try { const nextSnapshot = await operation(); if (nextSnapshot) applySnapshot(nextSnapshot); else refreshSnapshot(); } catch (cause) { setError(getSourceServerManagementErrorMessage(cause, intl.formatMessage)); } finally { operationsRef.current.delete(key); setBusyOperations(new Map(operationsRef.current)); } }, [applySnapshot, refreshSnapshot, intl, hasBusyScope], ); /** 设备操作失败提示;凭据不可静默取得时与内联错误共用补充凭据文案,不提供无内容的详情。 */ const showOperationFailureToast = useCallback( ( cause: unknown, messageId: string, source: string, sourceServerId: string | undefined, openDetails: () => void, ) => { if (isSourceServerCredentialsRequiredError(cause)) { toast(getSourceServerManagementErrorMessage(cause, intl.formatMessage), { variant: "warning", }); return; } toast(intl.formatMessage({ id: messageId }, { source }), { variant: "warning", actionLabel: intl.formatMessage({ id: "remote.action.details" }), onAction: () => { // 操作可跨面板生命周期完成,不能让全局 toast 捕获已卸载组件的 setter。 if (mountedRef.current) openDetails(); else if (sourceServerId) onShowUpdateDetails?.(sourceServerId); }, }); }, [intl, onShowUpdateDetails], ); const removeProfile = useCallback( async (profile: ConnectionProfile) => { if (!management) return; const confirmed = await confirmDialog({ title: intl.formatMessage({ id: "settings.source.removeProfileTitle" }), description: intl.formatMessage( { id: "settings.source.removeProfileDescription" }, { name: profile.displayName ?? profile.transport }, ), confirmLabel: intl.formatMessage({ id: "settings.source.removeProfile", }), confirmVariant: "destructive", }); if (!confirmed) return; await run(`remove:${profile.profileId}`, () => management.removeProfile(profile.profileId), [ profileOperationScope(profile), ]); }, [confirmDialog, intl, management, run], ); const removeSourceServer = useCallback( async (server: SourceServerRecord) => { if (hasBusyScope(`source:${server.sourceServerId}`)) return; const affectedProjects = workspaceTabs.filter( (tab) => getWorkspaceSourceServerId(tab, { workspaceHistory: snapshot?.workspaceHistory }) === server.sourceServerId, ); const projectNotice = affectedProjects.length > 0 ? intl.formatMessage( { id: "settings.source.removeOpenProjects" }, { projects: affectedProjects .map((tab) => `${tab.label} (${tab.workspacePath})`) .join("\n"), }, ) : intl.formatMessage({ id: "settings.source.noOpenProjects" }); const confirmed = await confirmDialog({ title: intl.formatMessage({ id: "settings.source.removeSourceServer", }), description: intl.formatMessage( { id: "settings.source.removeSourceServerDescription" }, { name: server.displayName }, ) + "\n\n" + projectNotice, confirmLabel: intl.formatMessage({ id: "settings.source.removeSourceServer", }), confirmVariant: "destructive", }); if (!confirmed) return; await run( `remove-source:${server.sourceServerId}`, () => management.removeSourceServer(server.sourceServerId), [`source:${server.sourceServerId}`], ); }, [confirmDialog, intl, management, run, snapshot?.workspaceHistory, workspaceTabs, hasBusyScope], ); const loadMigrationReport = useCallback( async (sourceServerId: string) => { if (!management) return; await run(`report:${sourceServerId}`, async () => { const report = await management.getMigrationReport(sourceServerId); setMigrationReports((current) => ({ ...current, [sourceServerId]: report })); }); }, [management, run], ); const toggleMigrationReport = useCallback( (sourceServerId: string) => { if (migrationReports[sourceServerId]) { setMigrationReports((current) => { const next = { ...current }; delete next[sourceServerId]; return next; }); return; } void loadMigrationReport(sourceServerId); }, [loadMigrationReport, migrationReports], ); const runMigrationOperation = useCallback( async ( key: string, sourceServerId: string, operation: () => Promise, ) => { await run(key, async () => { const report = await operation(); setMigrationReports((current) => ({ ...current, [sourceServerId]: report })); }, [`source:${sourceServerId}`]); }, [run], ); const updateProfile = useCallback( async ( profile: ConnectionProfile, allowDowngrade = false, // RDRI-01:重新安装复用同一更新链,只替换提示文案与设备名称。 feedback: { source?: string; completedToast?: string; failedToast?: string } = {}, ) => { const source = feedback.source ?? profile.displayName ?? profile.transport; await run( `update:${profile.profileId}`, async () => { let next: SourceServerManagementSnapshot | null; try { next = await runSourceServerUpdate({ management, profileId: profile.profileId, allowDowngrade, confirmForce: async () => await confirmDialog({ title: intl.formatMessage({ id: "settings.source.forceUpdateTitle", }), description: await getSourceServerForceUpdateDescription( management, profile.profileId, (id) => intl.formatMessage({ id }), ), confirmLabel: intl.formatMessage({ id: "settings.source.forceUpdate", }), confirmVariant: "destructive", }), }); } catch (cause) { showOperationFailureToast( cause, feedback.failedToast ?? "sourceServer.updateFailedToast", source, profile.sourceServerId, () => setErrorDetailsProfile(profile), ); throw cause; } if (next) toast( intl.formatMessage( { id: feedback.completedToast ?? "sourceServer.updateCompletedToast" }, { source }, ), { variant: "source-server-update" }, ); return next ?? undefined; }, [profileOperationScope(profile)], ); }, [confirmDialog, intl, management, run, showOperationFailureToast], ); /** * 重新安装远端服务(RDRI-01):普通确认后复用更新链,把本机版本 archive 重新装到远端;损坏的同版本 * release 由远端安装器整体替换。运行中任务守卫与强制确认沿用更新,不另起 Host 操作。 */ const reinstallRemoteService = useCallback( async (server: SourceServerRecord, profile: ConnectionProfile) => { const confirmed = await confirmDialog( getSourceServerReinstallConfirmation({ source: server.displayName, version: ZCODE_VERSION, formatMessage: intl.formatMessage, }), ); if (!confirmed) return; await updateProfile(profile, false, { source: server.displayName, completedToast: "sourceServer.reinstallCompletedToast", failedToast: "sourceServer.reinstallFailedToast", }); }, [confirmDialog, intl, updateProfile], ); /** * 重启 / 停止远端服务(RDLC-01):先按设备读取运行中任务,再弹危险确认,确认后交给 Host。重启期间 * 设备显示连接中,完成后自动连接;停止由 Host 先断开、再停远端服务,设备保持未连接。 * 读取、确认与执行处于同一个 `source:` 互斥内:读取期间菜单项禁用,不能重复触发, * 读取结束到确认之间也不会插入同设备的其他操作。 */ const runRemoteServiceLifecycle = useCallback( async (server: SourceServerRecord, action: RemoteServiceLifecycleAction) => { const copy = REMOTE_SERVICE_LIFECYCLE_ACTIONS[action]; await run( `${action}:${server.sourceServerId}`, async () => { try { // 读取只在凭据不可静默取得时抛出:此时不打开确认,由下方 catch 给出与更新相同的补充凭据提示。 const runningTasks = await readSourceServerRunningTasksForConfirmation( management, server.sourceServerId, ); const confirmed = await confirmDialog({ title: intl.formatMessage({ id: copy.title }), description: getRemoteServiceLifecycleDescription({ action, runningTasks, startupAutoReconnect, formatMessage: (id) => intl.formatMessage({ id }), }), confirmLabel: intl.formatMessage({ id: copy.label }), confirmVariant: "destructive", intent: copy.intent, scrollableDescription: true, }); if (!confirmed) return; const next = action === "restart" ? await management.restartSource(server.sourceServerId) : await management.stopSource(server.sourceServerId); toast(intl.formatMessage({ id: copy.completedToast }, { source: server.displayName })); return next; } catch (cause) { showOperationFailureToast( cause, copy.failedToast, server.displayName, server.sourceServerId, () => { const profile = findSourceErrorProfile(snapshotRef.current, server.sourceServerId) ?? snapshotRef.current?.profiles.find( (candidate) => candidate.profileId === server.preferredProfileId, ); if (profile) setErrorDetailsProfile(profile); }, ); throw cause; } }, [`source:${server.sourceServerId}`], ); }, [confirmDialog, intl, management, run, showOperationFailureToast, startupAutoReconnect], ); const servers = snapshot?.servers ?? []; const profiles = snapshot?.profiles ?? []; const activeProfiles = profiles.filter((profile) => profile.lifecycleState !== "retired"); const retiredProfiles = profiles.filter((profile) => profile.lifecycleState === "retired"); const unboundProfiles = activeProfiles.filter((profile) => !profile.sourceServerId); // 最近使用排序只在快照首次就绪时计算一次;之后只插入新设备、删除已移除设备(RDUX-13)。 const deviceRecency = servers.map((server) => ({ sourceServerId: server.sourceServerId, online: resolveRemoteConnectionPresentation( getRemoteDevicePresentationInput(snapshot, server.sourceServerId), ).status === "online", lastUsedAt: Math.max( server.lastOnlineAt ?? 0, ...(projection.devices .find((candidate) => candidate.sourceServerId === server.sourceServerId) ?.knownProjects.map((project) => project.lastOpenedAt) ?? []), ), })); const nextDeviceOrder = ready ? reconcileSourceServerDeviceOrder(deviceOrder, deviceRecency) : deviceOrder; // 渲染期派生:顺序变化时立即更新;没有变化时 reconcile 返回原引用,不会循环渲染。 if (nextDeviceOrder !== deviceOrder) setDeviceOrder(nextDeviceOrder); const serverById = new Map(servers.map((server) => [server.sourceServerId, server])); const visibleServers = (nextDeviceOrder ?? []) .map((sourceServerId) => serverById.get(sourceServerId)) .filter((server) => server !== undefined) .filter((server) => { const device = projection.devices.find( (candidate) => candidate.sourceServerId === server.sourceServerId, ); return matchesSourceServerDeviceSearch(deviceSearch, [ server.displayName, server.hostname, ...(device?.profiles ?? []).map((profile) => formatConnectionProfileTarget(profile)), ...(device?.knownProjects ?? []).map((project) => getProjectDisplayName(server, project.workspacePath), ), ]); }); useEffect(() => { if (!pendingFocusSourceServerId) return; const toggle = deviceTogglesRef.current.get(pendingFocusSourceServerId); if (!toggle) return; toggle.scrollIntoView({ block: "center" }); toggle.focus({ preventScroll: true }); setPendingFocusSourceServerId(null); }, [pendingFocusSourceServerId, nextDeviceOrder, deviceSearch]); const renderIdentityConfirmation = (profile: ConnectionProfile, size: "sm" | "xs") => ( ); const handleProfileAction = ( profile: ConnectionProfile, presentation: RemoteConnectionPresentation, server?: SourceServerRecord, ) => { if ( !["security", "details"].includes(presentation.primaryAction) && hasBusyScope(profileOperationScope(profile)) ) return; switch (presentation.primaryAction) { case "update-desktop": void run("desktop-update", async () => { await platform?.executeDesktopCommand(DesktopCommandIds.CheckForUpdates); }); return; case "update-server": void updateProfile(profile); return; case "disconnect": if (profile.sourceServerId && onDisconnectSource) void run( `disconnect:${profile.sourceServerId}`, () => onDisconnectSource(profile.sourceServerId!), [profileOperationScope(profile)], ); return; case "credentials": case "edit-auth": setEditingConnection({ profile, server, focusField: "auth" }); return; case "edit-host": setEditingConnection({ profile, server, focusField: "host" }); return; case "security": case "details": setErrorDetailsProfile(profile); return; case "none": return; default: void run( `connect:${profile.profileId}`, async () => { await onConnectProfile?.(profile.profileId); }, [profileOperationScope(profile)], ); } }; const renderProfile = (profile: ConnectionProfile, server?: SourceServerRecord) => { const state = stateByProfile.get(profile.profileId); const isOnline = state?.state === "online"; const identityChangePending = state?.state === "identity-change-pending"; const profileName = profile.displayName ?? profile.transport; const presentation = resolveRemoteConnectionPresentation({ ...state, target: profile.target }); const mutationBusy = busyScopes.has(profileOperationScope(profile)) || presentation.status === "connecting"; const actionBusy = mutationBusy && !["security", "details"].includes(presentation.primaryAction); const devicePresentation = server ? resolveRemoteConnectionPresentation( getRemoteDevicePresentationInput(snapshot, server.sourceServerId), ) : null; const connectionErrorText = presentation.reason && devicePresentation?.profileId !== profile.profileId ? intl.formatMessage({ id: presentation.reason.titleId }, presentation.reason.values) : null; return (
{!server ? : null} {profileName} {formatConnectionProfileTarget(profile)} {server?.preferredProfileId === profile.profileId ? ( {intl.formatMessage({ id: "settings.source.defaultProfile" })} ) : null} {connectionErrorText ? ( {connectionErrorText} ) : profile.lastConnectedAt ? ( {intl.formatMessage( { id: "settings.source.lastConnected" }, { time: formatRelativeTimestamp( profile.lastConnectedAt, locale, intl.formatMessage, ), }, )} ) : null} {!isOnline && !identityChangePending ? ( ) : null} {identityChangePending ? renderIdentityConfirmation(profile, "xs") : null} {server && server.preferredProfileId !== profile.profileId ? ( ) : null}
); }; return (
0}>

{intl.formatMessage({ id: "settings.remoteDevicesDescription" })}

{error ? (

{error}

) : null}
{onCreateConnection && (!ready || profiles.length > 0 || servers.length > 0) ? ( ) : null}
{background && !servers.some((server) => server.sourceServerId === background.sourceServerId) && !unboundProfiles.some((profile) => profile.profileId === background.profileId) ? (

{intl.formatMessage({ id: "settings.source.unfinishedConnections" })}

) : null} {!ready && !error ? (

) : null}
{servers.length > 0 ? (

{intl.formatMessage({ id: "settings.source.devicesHeading" })} {servers.length}

setDeviceSearch(event.target.value)} onClear={() => setDeviceSearch("")} clearLabel={intl.formatMessage({ id: "settings.search.clear" })} placeholder={intl.formatMessage({ id: "settings.source.searchPlaceholder" })} aria-label={intl.formatMessage({ id: "settings.source.searchPlaceholder" })} />
) : null} {servers.length > 0 ? (
{visibleServers.length === 0 ? (

{intl.formatMessage( { id: "settings.source.searchEmpty" }, { query: deviceSearch.trim() }, )}

) : null} {visibleServers.map((server) => { const device = projection.devices.find( (candidate) => candidate.sourceServerId === server.sourceServerId, ); const serverProfiles = device?.profiles ?? []; const preferredProfile = serverProfiles.find((profile) => profile.profileId === server.preferredProfileId) ?? serverProfiles[0]; // 旧 Source 在确认前仍可能是 uninstalled;恢复入口不能藏在安装状态或首选线路折叠后面。 const pendingIdentityProfiles = serverProfiles.filter( (profile) => stateByProfile.get(profile.profileId)?.state === "identity-change-pending", ); const identityChangeProfile = pendingIdentityProfiles.find((profile) => profile === preferredProfile) ?? pendingIdentityProfiles[0]; const currentProfile = serverProfiles.find( (profile) => stateByProfile.get(profile.profileId)?.state === "online", ); const displayedProfile = currentProfile ?? preferredProfile; const ConnectionIcon = displayedProfile?.transport === "docker" ? Box : displayedProfile?.transport === "wsl" ? TerminalSquare : Server; // 同一项目可能有多条历史(不同连接),保留最近一次,并按最近打开倒序展示。 const latestProjectByKey = new Map(); for (const project of device?.knownProjects ?? []) { const key = resolveWorkspaceKey(project); const existing = latestProjectByKey.get(key); if (!existing || project.lastOpenedAt >= existing.lastOpenedAt) latestProjectByKey.set(key, project); } const projects = [...latestProjectByKey.values()].sort( (left, right) => right.lastOpenedAt - left.lastOpenedAt, ); const projectsExpanded = expandedProjectSources.has(server.sourceServerId); const visibleProjects = projectsExpanded ? projects : projects.slice(0, COLLAPSED_PROJECT_COUNT); const openedProjectPaths = new Set( workspaceTabs .filter( (tab) => getWorkspaceSourceServerId(tab, { workspaceHistory: snapshot?.workspaceHistory, }) === server.sourceServerId, ) .map((tab) => tab.workspacePath), ); const otherProfiles = displayedProfile ? serverProfiles.filter( (profile) => profile !== displayedProfile && !pendingIdentityProfiles.includes(profile), ) : []; const online = device?.aggregatedStatus === "online"; const migrationReport = migrationReports[server.sourceServerId]; const migrationCount = snapshot?.migrationCounts.find( (count) => count.sourceServerId === server.sourceServerId, ); const showServerLines = server.installState !== "uninstalled"; const pendingMigrationCount = showServerLines && migrationCount?.status === "available" ? migrationCount.failedPathCount + migrationCount.abandonedPathCount : 0; // 覆盖可更新/必须升级/更新中/更新失败四态:更新中不再携带 updateAvailability,也要选中。 const profileStates = serverProfiles .map((profile) => stateByProfile.get(profile.profileId)) .filter((state) => state !== undefined); const presentation = resolveRemoteConnectionPresentation( getRemoteDevicePresentationInput(snapshot, server.sourceServerId), ); const actionProfile = serverProfiles.find((profile) => profile.profileId === presentation.profileId) ?? preferredProfile; const deviceBusy = busyScopes.has(`source:${server.sourceServerId}`); const lifecycleAvailability = resolveSourceServerLifecycleActionAvailability({ status: presentation.status, deviceBusy, lastSeenVersion: server.lastSeenVersion, }); const reinstallAvailability = actionProfile ? resolveSourceServerReinstallAvailability({ status: presentation.status, deviceBusy, installState: server.installState, lastSeenVersion: server.lastSeenVersion, localVersion: ZCODE_VERSION, }) : ({ visible: false } as const); const actionBusy = busyOperations.has(`disconnect:${server.sourceServerId}`) || busyOperations.has(`connect:${actionProfile?.profileId}`) || busyOperations.has(`update:${actionProfile?.profileId}`) || (busyOperations.has("desktop-update") && presentation.primaryAction === "update-desktop"); const preferredConnectionErrorText = presentation.reason ? intl.formatMessage( { id: presentation.reason.titleId }, presentation.reason.values, ) : null; const serverState = profileStates.find((state) => state.state === "updating") ?? profileStates.find( (state) => (state.updateAvailability && state.updateAvailability !== "none") || state.state === "updating", ); const updateFailed = serverState?.state === "failed"; const updateKey = sourceServerUpdateKey( server.sourceServerId, serverState?.availableVersion ?? "", ); const showUpdate = serverState && !( serverState.updateAvailability === "available" && serverState.state !== "updating" && deferredUpdates.has(updateKey) ); const updateFailureText = updateFailed && serverState ? formatRemoteConnectionError({ fallback: intl.formatMessage({ id: "settings.source.operationFailed" }), reasonCode: serverState.errorCode, retryable: serverState.retryable, recoveryAttempt: serverState.recoveryAttempt, recoveryLimit: serverState.recoveryLimit, formatMessage: intl.formatMessage, }) : null; const updateExplainsConnectionError = Boolean( showUpdate && serverState?.profileId === presentation.profileId && (serverState?.state === "updating" || (updateFailed && updateFailureText === preferredConnectionErrorText) || (serverState?.updateAvailability === "required" && presentation.reason?.category === "source-server-upgrade-required")), ); const operationLogs = logsByProfileId[serverState?.profileId ?? actionProfile?.profileId ?? ""] ?? []; const showOtherProfiles = showServerLines && otherProfiles.length > 0; const otherProfilesExpanded = showOtherProfiles && expandedSavedConnectionSources.has(server.sourceServerId); // 更新中由更新横幅展示进度与日志,页脚不重复。 const showRecentLog = operationLogs.length > 0 && serverState?.state !== "updating"; const logExpanded = showRecentLog && (logExpansionBySource.get(server.sourceServerId) ?? presentation.status === "failed"); // 进度展示(RDUX-13):折叠时顶边进度线 + 短状态;展开后进度线隐藏,展开区显示完整进度。 const deviceBackground = background?.sourceServerId === server.sourceServerId ? background : null; const backgroundSummary = deviceBackground ? summarizeRemoteConnectionProgress(deviceBackground) : null; let rowPresentation = presentation; let rowProgress: SourceServerDeviceRowProgress | undefined; const backgroundInFlight = backgroundSummary?.progressing === true && !backgroundSummary.waiting && !deviceBackground?.error; if (deviceBackground && !backgroundInFlight) { // Bug 原因:后台连接期间设备操作互斥禁用,而进度块只在展开区。等待输入、已完成、 // 失败或已取消时若沿用 Host 状态,折叠行会显示“已连接”或禁用的“重试”,看不出 // 还要继续或处理;这些状态统一提示需要处理,由用户展开后处理。 rowPresentation = BACKGROUND_WAITING_PRESENTATION; } else if (backgroundInFlight) { rowPresentation = BACKGROUND_CONNECTING_PRESENTATION; rowProgress = { percent: backgroundSummary.percent }; } else if (serverState?.state === "updating") { rowProgress = { percent: resolveSourceServerUpdatePercent(operationLogs) }; } else if (presentation.status === "connecting") { rowProgress = {}; } // 与展开区可选更新横幅同一条件:稍后隐藏,更新中不显示。 const optionalUpdateVersion = showUpdate && serverState && serverState.updateAvailability === "available" && serverState.state !== "updating" ? (serverState.availableVersion?.replace(/^v/i, "") ?? "") : null; const expanded = expandedDevices.has(server.sourceServerId); const showsPrimaryAction = presentation.primaryAction !== "none" && presentation.primaryAction !== "disconnect"; return ( toggleDevice(server.sourceServerId)} toggleRef={(element) => { if (element) deviceTogglesRef.current.set(server.sourceServerId, element); else deviceTogglesRef.current.delete(server.sourceServerId); }} metaTone={pendingMigrationCount > 0 ? "warning" : "muted"} metaTitle={ pendingMigrationCount > 0 ? intl.formatMessage({ id: "settings.source.connectionHistoryNeedsAttention", }) : undefined } meta={ pendingMigrationCount > 0 ? ( <> ); })}
) : null} {unboundProfiles.length > 0 ? (
profile.profileId === background.profileId) ? true : undefined } data-unfinished-connections className="group/unfinished border-t border-border pt-4" > {intl.formatMessage({ id: "settings.source.unfinishedConnections" })} {unboundProfiles.length}
{unboundProfiles.map((profile) => (
{renderProfile(profile)} {background && !background.sourceServerId && background.profileId === profile.profileId ? ( ) : null} {(logsByProfileId[profile.profileId]?.length ?? 0) > 0 ? ( ) : null}
))}
) : null} {retiredProfiles.length > 0 ? (
{intl.formatMessage( { id: "settings.source.retiredProfilesWithCount" }, { count: retiredProfiles.length }, )} {intl.formatMessage({ id: "settings.source.retiredProfilesDescription", })}
{retiredProfiles.map((profile) => (
{profile.displayName ?? profile.transport} {intl.formatMessage({ id: "settings.source.retiredNameSuffix", })} {profile.retiredAt ? `${intl.formatMessage( { id: "settings.source.archivedAt" }, { time: formatRelativeTimestamp( profile.retiredAt, locale, intl.formatMessage, ), }, )} · ${intl.formatMessage({ id: "settings.source.retiredEntryNote", })}` : intl.formatMessage({ id: "settings.source.retiredEntryNote", })}
))}
) : null}

{intl.formatMessage({ id: "settings.source.preferences", })}

{intl.formatMessage({ id: "settings.source.hideProjectDeviceNames" })}

{intl.formatMessage({ id: "settings.source.hideProjectDeviceNamesDescription" })}

{intl.formatMessage({ id: "settings.source.startupAutoReconnect", })}

{intl.formatMessage({ id: "settings.source.startupAutoReconnectDescription", })}

{ const previous = startupAutoReconnect; setStartupAutoReconnect(checked); void run("startup-reconnect", async () => { try { await onUpdateSettings?.({ remoteStartupAutoReconnectEnabled: checked }); } catch (cause) { setStartupAutoReconnect(previous); throw cause; } }); }} aria-label={intl.formatMessage({ id: "settings.source.startupAutoReconnect", })} />
{ready && profiles.length === 0 && servers.length === 0 ? (

{intl.formatMessage({ id: "settings.source.empty" })}

{onCreateConnection ? ( ) : null}
) : null}
{ if (!open) setErrorDetailsProfile(null); }} > {errorDetailsProfile ? (() => { const state = stateByProfile.get(errorDetailsProfile.profileId); const classified = classifyRemoteConnectionError({ errorCode: state?.errorCode, error: state?.error, target: errorDetailsProfile.target, }); return ( <> {intl.formatMessage({ id: classified.titleId })} {intl.formatMessage({ id: classified.reasonId })}
{intl.formatMessage({ id: "remote.error.details" })}
                        {state?.error ?? errorDetailsProfile.lastConnectError}
                      
); })() : null}
{ if (!open) setEditingConnection(null); }} onSaved={refresh} />
); }