SourceServerManagementPanel.tsx 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248
  1. import {
  2. useRemoteConnectionProgress,
  3. RemoteConnectionMinimizedProgress,
  4. summarizeRemoteConnectionProgress,
  5. } from "@/remote-connection-flow/ui/RemoteConnectionProgress.js";
  6. import {
  7. Dialog,
  8. DialogContent,
  9. DialogHeader,
  10. DialogTitle,
  11. DialogDescription,
  12. } from "@/components/ui/dialog.js";
  13. import { useOptionalPlatform } from "@/hooks/usePlatform.js";
  14. import { DesktopCommandIds, ZCODE_VERSION } from "@zcode/shared";
  15. /* eslint-disable max-lines -- Source/Profile/迁移三类管理操作共享同一 Host 快照和错误状态。 */
  16. import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
  17. import {
  18. ArrowUpRight,
  19. ChevronDown,
  20. ChevronRight,
  21. Ellipsis,
  22. FileWarning,
  23. Folder,
  24. ListTree,
  25. LoaderCircle,
  26. Pencil,
  27. Plus,
  28. Power,
  29. RotateCw,
  30. Server,
  31. Box,
  32. TerminalSquare,
  33. Copy,
  34. Trash2,
  35. Unplug,
  36. Wrench,
  37. } from "lucide-react";
  38. import { resolveWorkspaceKey } from "@zcode/shared";
  39. import type {
  40. ConnectionProfile,
  41. AppSettings,
  42. SourceServerManagementSnapshot,
  43. SourceServerMigrationReport,
  44. SourceServerRecord,
  45. SourceServerWorkspaceHistoryEntry,
  46. } from "@zcode/shared";
  47. import type { ISourceServerManagementService } from "@zcode/services";
  48. import { getPathLeaf } from "@/lib/path.js";
  49. import { toast } from "@/components/ui/toast.js";
  50. import { getSourceServerManagementErrorMessage } from "@/lib/sourceServerManagementError.js";
  51. import { Button } from "@/components/ui/button.js";
  52. import { Switch } from "@/components/ui/switch.js";
  53. import { cn } from "@/components/lib/utils.js";
  54. import { useConfirmDialog } from "@/hooks/useConfirmDialog.js";
  55. import { useSourceServerManagementSnapshot } from "@/hooks/useSourceServerManagementSnapshot.js";
  56. import { useSourceServerOperationLogs } from "@/hooks/useSourceServerOperationLogs.js";
  57. import { useZCodeIntl } from "@/i18n/IntlProvider.js";
  58. import { SourceServerMigrationReportPanel } from "@/settings/SourceServerMigrationReportPanel.js";
  59. import {
  60. resolveSourceServerUpdatePercent,
  61. SourceServerLogList,
  62. SourceServerUpdateActivity,
  63. } from "@/settings/SourceServerUpdateActivity.js";
  64. import {
  65. SourceServerDeviceRow,
  66. type SourceServerDeviceRowProgress,
  67. } from "@/settings/SourceServerDeviceRow.js";
  68. import {
  69. matchesSourceServerDeviceSearch,
  70. reconcileSourceServerDeviceOrder,
  71. } from "@/settings/sourceServerDeviceList.js";
  72. import { SettingsSearchInput } from "@/settings/SettingsSearchInput.js";
  73. import { formatRemoteConnectionError } from "@/lib/remoteConnectionPresentation.js";
  74. import {
  75. resolveRemoteConnectionPresentation,
  76. getRemoteDevicePresentationInput,
  77. classifyRemoteConnectionError,
  78. type RemoteConnectionPresentation,
  79. } from "@/lib/remoteConnectionPresentation.js";
  80. import {
  81. sourceServerUpdatePreferences,
  82. sourceServerUpdateKey,
  83. useDeferredSourceServerUpdates,
  84. } from "@/lib/sourceServerUpdatePreferences.js";
  85. import {
  86. getRemoteServiceLifecycleDescription,
  87. getSourceServerForceUpdateDescription,
  88. getSourceServerDowngradeConfirmation,
  89. getSourceServerReinstallConfirmation,
  90. isSourceServerCredentialsRequiredError,
  91. readSourceServerRunningTasksForConfirmation,
  92. resolveSourceServerLifecycleActionAvailability,
  93. resolveSourceServerReinstallAvailability,
  94. runSourceServerUpdate,
  95. } from "@/lib/sourceServerUpdateAction.js";
  96. import {
  97. DropdownMenu,
  98. DropdownMenuContent,
  99. DropdownMenuItem,
  100. DropdownMenuSeparator,
  101. DropdownMenuTrigger,
  102. } from "@/components/ui/dropdown-menu.js";
  103. import { EditConnectionProfileDialog } from "@/remote-connection/EditConnectionProfileDialog.js";
  104. import {
  105. formatConnectionProfileTarget,
  106. RemoteConnectionKindTag,
  107. RemoteConnectionStatusTag,
  108. } from "@/remote-connection/RemoteConnectionTags.js";
  109. import type { WorkspaceTabState } from "@/store/tabStore.js";
  110. import { getWorkspaceSourceServerId } from "@/conversation-workspace-target/sourceIdentity.js";
  111. import { buildRemoteWorkspaceProjection } from "@/remote/remoteWorkspaceProjection.js";
  112. function formatTimestamp(timestamp: number, locale: string): string {
  113. return new Date(timestamp).toLocaleString(locale, {
  114. dateStyle: "medium",
  115. timeStyle: "short",
  116. });
  117. }
  118. function formatRelativeTimestamp(
  119. timestamp: number,
  120. locale: string,
  121. formatMessage: (descriptor: { id: string }, values?: Record<string, string | number>) => string,
  122. ): string {
  123. const elapsed = Math.max(0, Date.now() - timestamp);
  124. if (elapsed < 60_000) return formatMessage({ id: "common.justNow" });
  125. if (elapsed < 60 * 60_000) {
  126. return formatMessage({ id: "common.minutesAgo" }, { count: Math.floor(elapsed / 60_000) });
  127. }
  128. if (elapsed < 24 * 60 * 60_000) {
  129. return formatMessage({ id: "common.hoursAgo" }, { count: Math.floor(elapsed / (60 * 60_000)) });
  130. }
  131. if (elapsed < 48 * 60 * 60_000) return formatMessage({ id: "common.yesterday" });
  132. return new Date(timestamp).toLocaleDateString(locale, {
  133. month: "short",
  134. day: "numeric",
  135. });
  136. }
  137. export function getProjectCount(
  138. snapshot: SourceServerManagementSnapshot,
  139. sourceServerId: string,
  140. remoteConversationWorkspaceBySourceServerId?: AppSettings["remoteConversationWorkspaceBySourceServerId"],
  141. ): number {
  142. return new Set(
  143. snapshot.workspaceHistory
  144. .filter(
  145. (entry) =>
  146. entry.sourceServerId === sourceServerId &&
  147. remoteConversationWorkspaceBySourceServerId?.[sourceServerId]?.workspacePath !==
  148. entry.workspacePath,
  149. )
  150. .map((entry) => resolveWorkspaceKey(entry)),
  151. ).size;
  152. }
  153. const COLLAPSED_PROJECT_COUNT = 3;
  154. /** 设备行在后台连接等用户处理、或后台连接进行中时显示的状态(RDUX-13 进度展示)。 */
  155. const BACKGROUND_WAITING_PRESENTATION = resolveRemoteConnectionPresentation({ state: "pending" });
  156. const BACKGROUND_CONNECTING_PRESENTATION = resolveRemoteConnectionPresentation({
  157. state: "connecting",
  158. });
  159. function getProjectDisplayName(server: SourceServerRecord, workspacePath: string): string {
  160. return (
  161. server.declaredWorkspaces?.find((item) => item.workspacePath === workspacePath)?.label ??
  162. getPathLeaf(workspacePath)
  163. );
  164. }
  165. function toggleSetItem(current: ReadonlySet<string>, item: string): Set<string> {
  166. const next = new Set(current);
  167. if (next.has(item)) next.delete(item);
  168. else next.add(item);
  169. return next;
  170. }
  171. /**
  172. * 失败详情要打开的连接:优先 Host failed 终态;其次是保持未连接但留有原因的连接
  173. * (例如停止远端服务失败,Host 按自己选择的路由写入原因,Renderer 不知道是哪条连接)。
  174. */
  175. function findSourceErrorProfile(
  176. snapshot: SourceServerManagementSnapshot | null | undefined,
  177. sourceServerId: string,
  178. ): ConnectionProfile | undefined {
  179. const states = snapshot?.states.filter((state) => state.sourceServerId === sourceServerId) ?? [];
  180. const state =
  181. states.find((candidate) => candidate.state === "failed") ??
  182. states
  183. .filter((candidate) => candidate.error || candidate.errorCode)
  184. .sort((left, right) => right.updatedAt - left.updatedAt)[0];
  185. return snapshot?.profiles.find((profile) => profile.profileId === state?.profileId);
  186. }
  187. /**
  188. * 设备卡「更多」中的远端服务生命周期操作(RDLC-01)。可用状态、危险确认、同设备互斥与提示规则两者共用;
  189. * 只有停止使用 destructive 菜单项。顺序即菜单顺序:重启在停止之前。
  190. */
  191. const REMOTE_SERVICE_LIFECYCLE_ACTIONS = {
  192. restart: {
  193. label: "settings.source.restartRemoteService",
  194. title: "settings.source.restartRemoteServiceTitle",
  195. completedToast: "sourceServer.restartCompletedToast",
  196. failedToast: "sourceServer.restartFailedToast",
  197. intent: "source-server-restart",
  198. icon: RotateCw,
  199. variant: "default",
  200. },
  201. stop: {
  202. label: "settings.source.stopRemoteService",
  203. title: "settings.source.stopRemoteServiceTitle",
  204. completedToast: "sourceServer.stopCompletedToast",
  205. failedToast: "sourceServer.stopFailedToast",
  206. intent: "source-server-stop",
  207. icon: Power,
  208. variant: "destructive",
  209. },
  210. } as const;
  211. type RemoteServiceLifecycleAction = keyof typeof REMOTE_SERVICE_LIFECYCLE_ACTIONS;
  212. const REMOTE_SERVICE_LIFECYCLE_ACTION_ORDER: readonly RemoteServiceLifecycleAction[] = [
  213. "restart",
  214. "stop",
  215. ];
  216. function profileOperationScope(profile: ConnectionProfile): string {
  217. return profile.sourceServerId
  218. ? `source:${profile.sourceServerId}`
  219. : `profile:${profile.profileId}`;
  220. }
  221. export function SourceServerManagementPanel({
  222. management,
  223. targetSourceServerId,
  224. targetSourceServerDetails = false,
  225. onTargetSourceServerFocused,
  226. onCreateConnection,
  227. onConnectProfile,
  228. onDisconnectSource,
  229. onShowInSidebar,
  230. onOpenProject,
  231. onShowUpdateDetails,
  232. workspaceTabs = [],
  233. settings,
  234. onUpdateSettings,
  235. hideProjectDeviceNames = false,
  236. onHideProjectDeviceNamesChange,
  237. }: {
  238. management: ISourceServerManagementService;
  239. targetSourceServerId?: string;
  240. targetSourceServerDetails?: boolean;
  241. onTargetSourceServerFocused?: () => void;
  242. onCreateConnection?: () => void;
  243. /** 用户点击连接时交给 Root 的全局弹窗,以 preferredProfileId 直达第 4 步。 */
  244. onConnectProfile?: (profileId: string) => Promise<void> | void;
  245. /** 用户断开设备时交给 Root 的统一 RemoteWorkspaceController。 */
  246. onDisconnectSource?: (sourceServerId: string) => Promise<void>;
  247. /** 「在侧边栏中显示」菜单项:返回工作区主界面(侧边栏设备分组所在处)。 */
  248. onShowInSidebar?: (sourceServerId: string) => void;
  249. onOpenProject?: (sourceServerId: string, path: string, profileId?: string) => Promise<void>;
  250. onShowUpdateDetails?: (sourceServerId: string) => void;
  251. workspaceTabs?: WorkspaceTabState[];
  252. /** 「新任务」按钮(原型 L763):激活该设备已打开的 workspace tab 并开新草稿。 */
  253. /** 有已打开 workspace tab 的设备 id 集合;「新任务」仅对这些设备渲染。 */
  254. settings?: Pick<
  255. AppSettings,
  256. "remoteStartupAutoReconnectEnabled" | "remoteConversationWorkspaceBySourceServerId"
  257. > | null;
  258. onUpdateSettings?: (patch: Partial<AppSettings>) => Promise<unknown> | void;
  259. hideProjectDeviceNames?: boolean;
  260. onHideProjectDeviceNamesChange?: (hidden: boolean) => void;
  261. }) {
  262. const background = useRemoteConnectionProgress();
  263. const { intl, locale } = useZCodeIntl();
  264. const confirmDialog = useConfirmDialog();
  265. const platform = useOptionalPlatform();
  266. const deferredUpdates = useDeferredSourceServerUpdates();
  267. const [startupAutoReconnect, setStartupAutoReconnect] = useState(
  268. settings?.remoteStartupAutoReconnectEnabled ?? true,
  269. );
  270. useEffect(() => {
  271. setStartupAutoReconnect(settings?.remoteStartupAutoReconnectEnabled ?? true);
  272. }, [settings?.remoteStartupAutoReconnectEnabled]);
  273. const [editingConnection, setEditingConnection] = useState<{
  274. profile: ConnectionProfile;
  275. server?: SourceServerRecord;
  276. focusField?: "host" | "auth";
  277. } | null>(null);
  278. const [errorDetailsProfile, setErrorDetailsProfile] = useState<ConnectionProfile | null>(null);
  279. const [expandedSavedConnectionSources, setExpandedSavedConnectionSources] = useState<Set<string>>(
  280. new Set(),
  281. );
  282. const [expandedProjectSources, setExpandedProjectSources] = useState<Set<string>>(new Set());
  283. // 设备列表的展示状态(RDUX-13):只在面板内存中,面板重挂即重置,不写回 Host。
  284. const [expandedDevices, setExpandedDevices] = useState<ReadonlySet<string>>(new Set());
  285. const [highlightedSourceServerId, setHighlightedSourceServerId] = useState<string | null>(null);
  286. const [deviceSearch, setDeviceSearch] = useState("");
  287. const [deviceOrder, setDeviceOrder] = useState<readonly string[] | null>(null);
  288. const [pendingFocusSourceServerId, setPendingFocusSourceServerId] = useState<string | null>(null);
  289. const deviceTogglesRef = useRef(new Map<string, HTMLButtonElement>());
  290. // 用户操作任一行(展开或收起)都结束定位高亮;不使用定时器清除。
  291. const toggleDevice = useCallback((sourceServerId: string) => {
  292. setExpandedDevices((current) => toggleSetItem(current, sourceServerId));
  293. setHighlightedSourceServerId(null);
  294. }, []);
  295. // 只记录用户手动切换过的日志展开状态;未切换时由设备是否失败决定默认值。
  296. const [logExpansionBySource, setLogExpansionBySource] = useState<ReadonlyMap<string, boolean>>(
  297. new Map(),
  298. );
  299. // 这里只拥有面板操作的防重状态;业务状态与快照版本仍由 Host 和快照 hook 负责。
  300. const operationsRef = useRef(new Map<string, readonly string[]>());
  301. const [busyOperations, setBusyOperations] = useState<ReadonlyMap<string, readonly string[]>>(
  302. new Map(),
  303. );
  304. const busyScopes = new Set([...busyOperations.values()].flat());
  305. if (background?.sourceServerId) busyScopes.add(`source:${background.sourceServerId}`);
  306. else if (background?.profileId) busyScopes.add(`profile:${background.profileId}`);
  307. const hasBusyScope = useCallback(
  308. (scope: string) => [...operationsRef.current.values()].some((scopes) => scopes.includes(scope)),
  309. [],
  310. );
  311. const mountedRef = useRef(true);
  312. useEffect(() => {
  313. mountedRef.current = true;
  314. return () => {
  315. mountedRef.current = false;
  316. };
  317. }, []);
  318. // 相对时间必须随时钟更新,不能依赖连接事件才重绘。
  319. const [, setClockTick] = useState(0);
  320. useEffect(() => {
  321. const timer = setInterval(() => setClockTick((tick) => tick + 1), 60_000);
  322. return () => clearInterval(timer);
  323. }, []);
  324. const [error, setError] = useState<string | null>(null);
  325. const [migrationReports, setMigrationReports] = useState<
  326. Record<string, SourceServerMigrationReport | undefined>
  327. >({});
  328. const {
  329. snapshot,
  330. ready,
  331. applySnapshot,
  332. refresh: refreshSnapshot,
  333. } = useSourceServerManagementSnapshot(management, {
  334. onError: (cause) => setError(getSourceServerManagementErrorMessage(cause, intl.formatMessage)),
  335. });
  336. const focusedTargetRef = useRef<string | undefined>(undefined);
  337. // 定位意图(RDUX-13):快照就绪且目标设备存在时,清空搜索、只展开目标行并持续高亮;
  338. // 聚焦与滚动等目标行渲染后再执行。
  339. useEffect(() => {
  340. if (!targetSourceServerId) {
  341. focusedTargetRef.current = undefined;
  342. return;
  343. }
  344. const targetKey = `${targetSourceServerId}:${targetSourceServerDetails}`;
  345. if (!ready || focusedTargetRef.current === targetKey) return;
  346. if (!snapshot?.servers.some((server) => server.sourceServerId === targetSourceServerId)) return;
  347. setDeviceSearch("");
  348. setExpandedDevices(new Set([targetSourceServerId]));
  349. setHighlightedSourceServerId(targetSourceServerId);
  350. setPendingFocusSourceServerId(targetSourceServerId);
  351. const failedProfile = findSourceErrorProfile(snapshot, targetSourceServerId);
  352. if (targetSourceServerDetails && failedProfile) setErrorDetailsProfile(failedProfile);
  353. focusedTargetRef.current = targetKey;
  354. onTargetSourceServerFocused?.();
  355. }, [
  356. ready,
  357. snapshot,
  358. targetSourceServerId,
  359. targetSourceServerDetails,
  360. onTargetSourceServerFocused,
  361. ]);
  362. const { logsByProfileId } = useSourceServerOperationLogs(
  363. management,
  364. snapshot?.profiles.map((profile) => profile.profileId),
  365. );
  366. const projection = useMemo(
  367. () =>
  368. buildRemoteWorkspaceProjection({
  369. managementSnapshot: snapshot,
  370. tabs: [],
  371. remoteConversationWorkspaceBySourceServerId:
  372. settings?.remoteConversationWorkspaceBySourceServerId,
  373. }),
  374. [snapshot, settings?.remoteConversationWorkspaceBySourceServerId],
  375. );
  376. const refresh = useCallback(async () => {
  377. refreshSnapshot();
  378. }, [refreshSnapshot]);
  379. const stateByProfile = useMemo(
  380. () => new Map(snapshot?.states.map((state) => [state.profileId, state]) ?? []),
  381. [snapshot?.states],
  382. );
  383. // 失败提示的“查看详情”在操作结束后才点击,需要读取届时最新的 Host 快照。
  384. const snapshotRef = useRef(snapshot);
  385. useEffect(() => {
  386. snapshotRef.current = snapshot;
  387. }, [snapshot]);
  388. const run = useCallback(
  389. async (
  390. key: string,
  391. operation: () => Promise<SourceServerManagementSnapshot | void>,
  392. scopes: readonly string[] = [key],
  393. ) => {
  394. // 同设备的不同连接互斥;无关设备和日志查看独立,不用全局锁阻塞长时间更新。
  395. if (operationsRef.current.has(key) || scopes.some(hasBusyScope)) return;
  396. operationsRef.current.set(key, scopes);
  397. setBusyOperations(new Map(operationsRef.current));
  398. setError(null);
  399. try {
  400. const nextSnapshot = await operation();
  401. if (nextSnapshot) applySnapshot(nextSnapshot);
  402. else refreshSnapshot();
  403. } catch (cause) {
  404. setError(getSourceServerManagementErrorMessage(cause, intl.formatMessage));
  405. } finally {
  406. operationsRef.current.delete(key);
  407. setBusyOperations(new Map(operationsRef.current));
  408. }
  409. },
  410. [applySnapshot, refreshSnapshot, intl, hasBusyScope],
  411. );
  412. /** 设备操作失败提示;凭据不可静默取得时与内联错误共用补充凭据文案,不提供无内容的详情。 */
  413. const showOperationFailureToast = useCallback(
  414. (
  415. cause: unknown,
  416. messageId: string,
  417. source: string,
  418. sourceServerId: string | undefined,
  419. openDetails: () => void,
  420. ) => {
  421. if (isSourceServerCredentialsRequiredError(cause)) {
  422. toast(getSourceServerManagementErrorMessage(cause, intl.formatMessage), {
  423. variant: "warning",
  424. });
  425. return;
  426. }
  427. toast(intl.formatMessage({ id: messageId }, { source }), {
  428. variant: "warning",
  429. actionLabel: intl.formatMessage({ id: "remote.action.details" }),
  430. onAction: () => {
  431. // 操作可跨面板生命周期完成,不能让全局 toast 捕获已卸载组件的 setter。
  432. if (mountedRef.current) openDetails();
  433. else if (sourceServerId) onShowUpdateDetails?.(sourceServerId);
  434. },
  435. });
  436. },
  437. [intl, onShowUpdateDetails],
  438. );
  439. const removeProfile = useCallback(
  440. async (profile: ConnectionProfile) => {
  441. if (!management) return;
  442. const confirmed = await confirmDialog({
  443. title: intl.formatMessage({ id: "settings.source.removeProfileTitle" }),
  444. description: intl.formatMessage(
  445. { id: "settings.source.removeProfileDescription" },
  446. { name: profile.displayName ?? profile.transport },
  447. ),
  448. confirmLabel: intl.formatMessage({
  449. id: "settings.source.removeProfile",
  450. }),
  451. confirmVariant: "destructive",
  452. });
  453. if (!confirmed) return;
  454. await run(`remove:${profile.profileId}`, () => management.removeProfile(profile.profileId), [
  455. profileOperationScope(profile),
  456. ]);
  457. },
  458. [confirmDialog, intl, management, run],
  459. );
  460. const removeSourceServer = useCallback(
  461. async (server: SourceServerRecord) => {
  462. if (hasBusyScope(`source:${server.sourceServerId}`)) return;
  463. const affectedProjects = workspaceTabs.filter(
  464. (tab) =>
  465. getWorkspaceSourceServerId(tab, { workspaceHistory: snapshot?.workspaceHistory }) ===
  466. server.sourceServerId,
  467. );
  468. const projectNotice =
  469. affectedProjects.length > 0
  470. ? intl.formatMessage(
  471. { id: "settings.source.removeOpenProjects" },
  472. {
  473. projects: affectedProjects
  474. .map((tab) => `${tab.label} (${tab.workspacePath})`)
  475. .join("\n"),
  476. },
  477. )
  478. : intl.formatMessage({ id: "settings.source.noOpenProjects" });
  479. const confirmed = await confirmDialog({
  480. title: intl.formatMessage({
  481. id: "settings.source.removeSourceServer",
  482. }),
  483. description:
  484. intl.formatMessage(
  485. { id: "settings.source.removeSourceServerDescription" },
  486. { name: server.displayName },
  487. ) +
  488. "\n\n" +
  489. projectNotice,
  490. confirmLabel: intl.formatMessage({
  491. id: "settings.source.removeSourceServer",
  492. }),
  493. confirmVariant: "destructive",
  494. });
  495. if (!confirmed) return;
  496. await run(
  497. `remove-source:${server.sourceServerId}`,
  498. () => management.removeSourceServer(server.sourceServerId),
  499. [`source:${server.sourceServerId}`],
  500. );
  501. },
  502. [confirmDialog, intl, management, run, snapshot?.workspaceHistory, workspaceTabs, hasBusyScope],
  503. );
  504. const loadMigrationReport = useCallback(
  505. async (sourceServerId: string) => {
  506. if (!management) return;
  507. await run(`report:${sourceServerId}`, async () => {
  508. const report = await management.getMigrationReport(sourceServerId);
  509. setMigrationReports((current) => ({ ...current, [sourceServerId]: report }));
  510. });
  511. },
  512. [management, run],
  513. );
  514. const toggleMigrationReport = useCallback(
  515. (sourceServerId: string) => {
  516. if (migrationReports[sourceServerId]) {
  517. setMigrationReports((current) => {
  518. const next = { ...current };
  519. delete next[sourceServerId];
  520. return next;
  521. });
  522. return;
  523. }
  524. void loadMigrationReport(sourceServerId);
  525. },
  526. [loadMigrationReport, migrationReports],
  527. );
  528. const runMigrationOperation = useCallback(
  529. async (
  530. key: string,
  531. sourceServerId: string,
  532. operation: () => Promise<SourceServerMigrationReport>,
  533. ) => {
  534. await run(key, async () => {
  535. const report = await operation();
  536. setMigrationReports((current) => ({ ...current, [sourceServerId]: report }));
  537. }, [`source:${sourceServerId}`]);
  538. },
  539. [run],
  540. );
  541. const updateProfile = useCallback(
  542. async (
  543. profile: ConnectionProfile,
  544. allowDowngrade = false,
  545. // RDRI-01:重新安装复用同一更新链,只替换提示文案与设备名称。
  546. feedback: { source?: string; completedToast?: string; failedToast?: string } = {},
  547. ) => {
  548. const source = feedback.source ?? profile.displayName ?? profile.transport;
  549. await run(
  550. `update:${profile.profileId}`,
  551. async () => {
  552. let next: SourceServerManagementSnapshot | null;
  553. try {
  554. next = await runSourceServerUpdate({
  555. management,
  556. profileId: profile.profileId,
  557. allowDowngrade,
  558. confirmForce: async () =>
  559. await confirmDialog({
  560. title: intl.formatMessage({
  561. id: "settings.source.forceUpdateTitle",
  562. }),
  563. description: await getSourceServerForceUpdateDescription(
  564. management,
  565. profile.profileId,
  566. (id) => intl.formatMessage({ id }),
  567. ),
  568. confirmLabel: intl.formatMessage({
  569. id: "settings.source.forceUpdate",
  570. }),
  571. confirmVariant: "destructive",
  572. }),
  573. });
  574. } catch (cause) {
  575. showOperationFailureToast(
  576. cause,
  577. feedback.failedToast ?? "sourceServer.updateFailedToast",
  578. source,
  579. profile.sourceServerId,
  580. () => setErrorDetailsProfile(profile),
  581. );
  582. throw cause;
  583. }
  584. if (next)
  585. toast(
  586. intl.formatMessage(
  587. { id: feedback.completedToast ?? "sourceServer.updateCompletedToast" },
  588. { source },
  589. ),
  590. { variant: "source-server-update" },
  591. );
  592. return next ?? undefined;
  593. },
  594. [profileOperationScope(profile)],
  595. );
  596. },
  597. [confirmDialog, intl, management, run, showOperationFailureToast],
  598. );
  599. /**
  600. * 重新安装远端服务(RDRI-01):普通确认后复用更新链,把本机版本 archive 重新装到远端;损坏的同版本
  601. * release 由远端安装器整体替换。运行中任务守卫与强制确认沿用更新,不另起 Host 操作。
  602. */
  603. const reinstallRemoteService = useCallback(
  604. async (server: SourceServerRecord, profile: ConnectionProfile) => {
  605. const confirmed = await confirmDialog(
  606. getSourceServerReinstallConfirmation({
  607. source: server.displayName,
  608. version: ZCODE_VERSION,
  609. formatMessage: intl.formatMessage,
  610. }),
  611. );
  612. if (!confirmed) return;
  613. await updateProfile(profile, false, {
  614. source: server.displayName,
  615. completedToast: "sourceServer.reinstallCompletedToast",
  616. failedToast: "sourceServer.reinstallFailedToast",
  617. });
  618. },
  619. [confirmDialog, intl, updateProfile],
  620. );
  621. /**
  622. * 重启 / 停止远端服务(RDLC-01):先按设备读取运行中任务,再弹危险确认,确认后交给 Host。重启期间
  623. * 设备显示连接中,完成后自动连接;停止由 Host 先断开、再停远端服务,设备保持未连接。
  624. * 读取、确认与执行处于同一个 `source:<id>` 互斥内:读取期间菜单项禁用,不能重复触发,
  625. * 读取结束到确认之间也不会插入同设备的其他操作。
  626. */
  627. const runRemoteServiceLifecycle = useCallback(
  628. async (server: SourceServerRecord, action: RemoteServiceLifecycleAction) => {
  629. const copy = REMOTE_SERVICE_LIFECYCLE_ACTIONS[action];
  630. await run(
  631. `${action}:${server.sourceServerId}`,
  632. async () => {
  633. try {
  634. // 读取只在凭据不可静默取得时抛出:此时不打开确认,由下方 catch 给出与更新相同的补充凭据提示。
  635. const runningTasks = await readSourceServerRunningTasksForConfirmation(
  636. management,
  637. server.sourceServerId,
  638. );
  639. const confirmed = await confirmDialog({
  640. title: intl.formatMessage({ id: copy.title }),
  641. description: getRemoteServiceLifecycleDescription({
  642. action,
  643. runningTasks,
  644. startupAutoReconnect,
  645. formatMessage: (id) => intl.formatMessage({ id }),
  646. }),
  647. confirmLabel: intl.formatMessage({ id: copy.label }),
  648. confirmVariant: "destructive",
  649. intent: copy.intent,
  650. scrollableDescription: true,
  651. });
  652. if (!confirmed) return;
  653. const next =
  654. action === "restart"
  655. ? await management.restartSource(server.sourceServerId)
  656. : await management.stopSource(server.sourceServerId);
  657. toast(intl.formatMessage({ id: copy.completedToast }, { source: server.displayName }));
  658. return next;
  659. } catch (cause) {
  660. showOperationFailureToast(
  661. cause,
  662. copy.failedToast,
  663. server.displayName,
  664. server.sourceServerId,
  665. () => {
  666. const profile =
  667. findSourceErrorProfile(snapshotRef.current, server.sourceServerId) ??
  668. snapshotRef.current?.profiles.find(
  669. (candidate) => candidate.profileId === server.preferredProfileId,
  670. );
  671. if (profile) setErrorDetailsProfile(profile);
  672. },
  673. );
  674. throw cause;
  675. }
  676. },
  677. [`source:${server.sourceServerId}`],
  678. );
  679. },
  680. [confirmDialog, intl, management, run, showOperationFailureToast, startupAutoReconnect],
  681. );
  682. const servers = snapshot?.servers ?? [];
  683. const profiles = snapshot?.profiles ?? [];
  684. const activeProfiles = profiles.filter((profile) => profile.lifecycleState !== "retired");
  685. const retiredProfiles = profiles.filter((profile) => profile.lifecycleState === "retired");
  686. const unboundProfiles = activeProfiles.filter((profile) => !profile.sourceServerId);
  687. // 最近使用排序只在快照首次就绪时计算一次;之后只插入新设备、删除已移除设备(RDUX-13)。
  688. const deviceRecency = servers.map((server) => ({
  689. sourceServerId: server.sourceServerId,
  690. online:
  691. resolveRemoteConnectionPresentation(
  692. getRemoteDevicePresentationInput(snapshot, server.sourceServerId),
  693. ).status === "online",
  694. lastUsedAt: Math.max(
  695. server.lastOnlineAt ?? 0,
  696. ...(projection.devices
  697. .find((candidate) => candidate.sourceServerId === server.sourceServerId)
  698. ?.knownProjects.map((project) => project.lastOpenedAt) ?? []),
  699. ),
  700. }));
  701. const nextDeviceOrder = ready
  702. ? reconcileSourceServerDeviceOrder(deviceOrder, deviceRecency)
  703. : deviceOrder;
  704. // 渲染期派生:顺序变化时立即更新;没有变化时 reconcile 返回原引用,不会循环渲染。
  705. if (nextDeviceOrder !== deviceOrder) setDeviceOrder(nextDeviceOrder);
  706. const serverById = new Map(servers.map((server) => [server.sourceServerId, server]));
  707. const visibleServers = (nextDeviceOrder ?? [])
  708. .map((sourceServerId) => serverById.get(sourceServerId))
  709. .filter((server) => server !== undefined)
  710. .filter((server) => {
  711. const device = projection.devices.find(
  712. (candidate) => candidate.sourceServerId === server.sourceServerId,
  713. );
  714. return matchesSourceServerDeviceSearch(deviceSearch, [
  715. server.displayName,
  716. server.hostname,
  717. ...(device?.profiles ?? []).map((profile) => formatConnectionProfileTarget(profile)),
  718. ...(device?.knownProjects ?? []).map((project) =>
  719. getProjectDisplayName(server, project.workspacePath),
  720. ),
  721. ]);
  722. });
  723. useEffect(() => {
  724. if (!pendingFocusSourceServerId) return;
  725. const toggle = deviceTogglesRef.current.get(pendingFocusSourceServerId);
  726. if (!toggle) return;
  727. toggle.scrollIntoView({ block: "center" });
  728. toggle.focus({ preventScroll: true });
  729. setPendingFocusSourceServerId(null);
  730. }, [pendingFocusSourceServerId, nextDeviceOrder, deviceSearch]);
  731. const renderIdentityConfirmation = (profile: ConnectionProfile, size: "sm" | "xs") => (
  732. <Button
  733. type="button"
  734. variant="outline"
  735. size={size}
  736. disabled={
  737. busyScopes.has(profileOperationScope(profile)) ||
  738. stateByProfile.get(profile.profileId)?.state === "updating"
  739. }
  740. onClick={() =>
  741. void confirmDialog({
  742. title: intl.formatMessage({ id: "settings.source.identityChangeTitle" }),
  743. description: intl.formatMessage({ id: "settings.source.identityChangeDescription" }),
  744. confirmLabel: intl.formatMessage({ id: "settings.source.identityChangeConfirm" }),
  745. }).then((confirmed) =>
  746. confirmed
  747. ? run(
  748. `identity:${profile.profileId}`,
  749. () => management.confirmIdentityChange(profile.profileId),
  750. [profileOperationScope(profile)],
  751. )
  752. : undefined,
  753. )
  754. }
  755. >
  756. {busyOperations.has(`identity:${profile.profileId}`) ? (
  757. <LoaderCircle className="size-3.5 animate-spin" aria-hidden="true" />
  758. ) : null}
  759. {intl.formatMessage({ id: "settings.source.identityChangeConfirm" })}
  760. </Button>
  761. );
  762. const handleProfileAction = (
  763. profile: ConnectionProfile,
  764. presentation: RemoteConnectionPresentation,
  765. server?: SourceServerRecord,
  766. ) => {
  767. if (
  768. !["security", "details"].includes(presentation.primaryAction) &&
  769. hasBusyScope(profileOperationScope(profile))
  770. )
  771. return;
  772. switch (presentation.primaryAction) {
  773. case "update-desktop":
  774. void run("desktop-update", async () => {
  775. await platform?.executeDesktopCommand(DesktopCommandIds.CheckForUpdates);
  776. });
  777. return;
  778. case "update-server":
  779. void updateProfile(profile);
  780. return;
  781. case "disconnect":
  782. if (profile.sourceServerId && onDisconnectSource)
  783. void run(
  784. `disconnect:${profile.sourceServerId}`,
  785. () => onDisconnectSource(profile.sourceServerId!),
  786. [profileOperationScope(profile)],
  787. );
  788. return;
  789. case "credentials":
  790. case "edit-auth":
  791. setEditingConnection({ profile, server, focusField: "auth" });
  792. return;
  793. case "edit-host":
  794. setEditingConnection({ profile, server, focusField: "host" });
  795. return;
  796. case "security":
  797. case "details":
  798. setErrorDetailsProfile(profile);
  799. return;
  800. case "none":
  801. return;
  802. default:
  803. void run(
  804. `connect:${profile.profileId}`,
  805. async () => {
  806. await onConnectProfile?.(profile.profileId);
  807. },
  808. [profileOperationScope(profile)],
  809. );
  810. }
  811. };
  812. const renderProfile = (profile: ConnectionProfile, server?: SourceServerRecord) => {
  813. const state = stateByProfile.get(profile.profileId);
  814. const isOnline = state?.state === "online";
  815. const identityChangePending = state?.state === "identity-change-pending";
  816. const profileName = profile.displayName ?? profile.transport;
  817. const presentation = resolveRemoteConnectionPresentation({ ...state, target: profile.target });
  818. const mutationBusy =
  819. busyScopes.has(profileOperationScope(profile)) || presentation.status === "connecting";
  820. const actionBusy =
  821. mutationBusy && !["security", "details"].includes(presentation.primaryAction);
  822. const devicePresentation = server
  823. ? resolveRemoteConnectionPresentation(
  824. getRemoteDevicePresentationInput(snapshot, server.sourceServerId),
  825. )
  826. : null;
  827. const connectionErrorText =
  828. presentation.reason && devicePresentation?.profileId !== profile.profileId
  829. ? intl.formatMessage({ id: presentation.reason.titleId }, presentation.reason.values)
  830. : null;
  831. return (
  832. <div
  833. key={profile.profileId}
  834. className="group/line -mx-2 flex min-w-0 flex-wrap items-center gap-2.5 rounded-md px-2 py-1.5 hover:bg-hover"
  835. >
  836. <RemoteConnectionKindTag kind={profile.transport} />
  837. {!server ? <RemoteConnectionStatusTag presentation={presentation} /> : null}
  838. <span className="shrink-0 text-ui-base font-medium text-foreground">{profileName}</span>
  839. <span className="min-w-0 truncate font-mono text-ui-sm text-remote-foreground-muted">
  840. {formatConnectionProfileTarget(profile)}
  841. </span>
  842. {server?.preferredProfileId === profile.profileId ? (
  843. <span className="shrink-0 rounded-md bg-tag px-2 py-0.5 text-ui-xs text-remote-foreground-muted">
  844. {intl.formatMessage({ id: "settings.source.defaultProfile" })}
  845. </span>
  846. ) : null}
  847. <span className="ml-auto flex min-w-0 flex-wrap items-center gap-2">
  848. {connectionErrorText ? (
  849. <span
  850. className="max-w-64 truncate text-ui-sm text-destructive-surface-foreground"
  851. title={connectionErrorText}
  852. >
  853. {connectionErrorText}
  854. </span>
  855. ) : profile.lastConnectedAt ? (
  856. <span
  857. className="text-ui-sm text-remote-foreground-muted"
  858. title={formatTimestamp(profile.lastConnectedAt, locale)}
  859. >
  860. {intl.formatMessage(
  861. { id: "settings.source.lastConnected" },
  862. {
  863. time: formatRelativeTimestamp(
  864. profile.lastConnectedAt,
  865. locale,
  866. intl.formatMessage,
  867. ),
  868. },
  869. )}
  870. </span>
  871. ) : null}
  872. {!isOnline && !identityChangePending ? (
  873. <Button
  874. type="button"
  875. variant="outline"
  876. size="xs"
  877. disabled={actionBusy}
  878. onClick={() =>
  879. handleProfileAction(
  880. profile,
  881. resolveRemoteConnectionPresentation({
  882. ...stateByProfile.get(profile.profileId),
  883. target: profile.target,
  884. }),
  885. )
  886. }
  887. >
  888. {intl.formatMessage({
  889. id: resolveRemoteConnectionPresentation({ ...state, target: profile.target })
  890. .actionMessageId,
  891. })}
  892. </Button>
  893. ) : null}
  894. {identityChangePending ? renderIdentityConfirmation(profile, "xs") : null}
  895. <Button
  896. type="button"
  897. variant="ghost"
  898. size="xs"
  899. aria-label={intl.formatMessage({
  900. id: "settings.source.editConnection",
  901. })}
  902. disabled={busyScopes.has(profileOperationScope(profile))}
  903. onClick={() => setEditingConnection({ profile })}
  904. >
  905. <Pencil className="size-3.5" />
  906. {intl.formatMessage({ id: "settings.source.editConnection" })}
  907. </Button>
  908. {server && server.preferredProfileId !== profile.profileId ? (
  909. <Button
  910. type="button"
  911. variant="ghost"
  912. size="xs"
  913. disabled={mutationBusy}
  914. onClick={() =>
  915. void run(
  916. `preferred:${profile.profileId}`,
  917. () => management.setPreferredProfile(server.sourceServerId, profile.profileId),
  918. [profileOperationScope(profile)],
  919. )
  920. }
  921. >
  922. {intl.formatMessage({ id: "settings.source.setDefault" })}
  923. </Button>
  924. ) : null}
  925. <Button
  926. type="button"
  927. variant="ghost"
  928. size="xs"
  929. disabled={mutationBusy}
  930. onClick={() => void removeProfile(profile)}
  931. >
  932. <Trash2 className="size-3.5" />
  933. {intl.formatMessage({ id: "settings.source.removeProfile" })}
  934. </Button>
  935. </span>
  936. </div>
  937. );
  938. };
  939. return (
  940. <div className="flex flex-col gap-4" aria-busy={busyOperations.size > 0}>
  941. <div className="flex flex-wrap items-start justify-between gap-3">
  942. <div className="min-w-0 max-w-xl">
  943. <p className="text-ui-base text-remote-foreground-muted">
  944. {intl.formatMessage({ id: "settings.remoteDevicesDescription" })}
  945. </p>
  946. {error ? (
  947. <p role="alert" className="mt-2 text-ui-base text-destructive">
  948. {error}
  949. </p>
  950. ) : null}
  951. </div>
  952. {onCreateConnection && (!ready || profiles.length > 0 || servers.length > 0) ? (
  953. <Button type="button" size="sm" onClick={onCreateConnection}>
  954. <Plus className="size-3.5" />
  955. {intl.formatMessage({ id: "settings.source.newConnection" })}
  956. </Button>
  957. ) : null}
  958. </div>
  959. {background &&
  960. !servers.some((server) => server.sourceServerId === background.sourceServerId) &&
  961. !unboundProfiles.some((profile) => profile.profileId === background.profileId) ? (
  962. <section
  963. data-unfinished-background-connection
  964. className="rounded-xl border border-card-border bg-card pt-3"
  965. >
  966. <p className="px-4 text-ui-base font-medium">
  967. {intl.formatMessage({ id: "settings.source.unfinishedConnections" })}
  968. </p>
  969. <RemoteConnectionMinimizedProgress {...background} />
  970. </section>
  971. ) : null}
  972. {!ready && !error ? (
  973. <p
  974. role="status"
  975. className="flex items-center gap-2 text-ui-base text-remote-foreground-muted"
  976. >
  977. <LoaderCircle className="size-4 animate-spin" aria-hidden="true" />
  978. {intl.formatMessage({ id: "common.loading" })}
  979. </p>
  980. ) : null}
  981. <div className="min-w-0 space-y-3">
  982. {servers.length > 0 ? (
  983. <div className="flex flex-wrap items-center justify-between gap-2">
  984. <h3 className="flex items-center gap-2 text-ui-base font-medium text-foreground">
  985. {intl.formatMessage({ id: "settings.source.devicesHeading" })}
  986. <span className="text-ui-xs font-normal text-remote-foreground-muted">
  987. {servers.length}
  988. </span>
  989. </h3>
  990. <SettingsSearchInput
  991. containerClassName="w-full max-w-64"
  992. value={deviceSearch}
  993. onChange={(event) => setDeviceSearch(event.target.value)}
  994. onClear={() => setDeviceSearch("")}
  995. clearLabel={intl.formatMessage({ id: "settings.search.clear" })}
  996. placeholder={intl.formatMessage({ id: "settings.source.searchPlaceholder" })}
  997. aria-label={intl.formatMessage({ id: "settings.source.searchPlaceholder" })}
  998. />
  999. </div>
  1000. ) : null}
  1001. {servers.length > 0 ? (
  1002. <div
  1003. data-source-server-device-list
  1004. className="@container/source-server-devices overflow-hidden rounded-xl border border-card-border bg-card"
  1005. >
  1006. {visibleServers.length === 0 ? (
  1007. <p className="px-4 py-6 text-center text-ui-base text-remote-foreground-muted">
  1008. {intl.formatMessage(
  1009. { id: "settings.source.searchEmpty" },
  1010. { query: deviceSearch.trim() },
  1011. )}
  1012. </p>
  1013. ) : null}
  1014. {visibleServers.map((server) => {
  1015. const device = projection.devices.find(
  1016. (candidate) => candidate.sourceServerId === server.sourceServerId,
  1017. );
  1018. const serverProfiles = device?.profiles ?? [];
  1019. const preferredProfile =
  1020. serverProfiles.find((profile) => profile.profileId === server.preferredProfileId) ??
  1021. serverProfiles[0];
  1022. // 旧 Source 在确认前仍可能是 uninstalled;恢复入口不能藏在安装状态或首选线路折叠后面。
  1023. const pendingIdentityProfiles = serverProfiles.filter(
  1024. (profile) =>
  1025. stateByProfile.get(profile.profileId)?.state === "identity-change-pending",
  1026. );
  1027. const identityChangeProfile =
  1028. pendingIdentityProfiles.find((profile) => profile === preferredProfile) ??
  1029. pendingIdentityProfiles[0];
  1030. const currentProfile = serverProfiles.find(
  1031. (profile) => stateByProfile.get(profile.profileId)?.state === "online",
  1032. );
  1033. const displayedProfile = currentProfile ?? preferredProfile;
  1034. const ConnectionIcon =
  1035. displayedProfile?.transport === "docker"
  1036. ? Box
  1037. : displayedProfile?.transport === "wsl"
  1038. ? TerminalSquare
  1039. : Server;
  1040. // 同一项目可能有多条历史(不同连接),保留最近一次,并按最近打开倒序展示。
  1041. const latestProjectByKey = new Map<string, SourceServerWorkspaceHistoryEntry>();
  1042. for (const project of device?.knownProjects ?? []) {
  1043. const key = resolveWorkspaceKey(project);
  1044. const existing = latestProjectByKey.get(key);
  1045. if (!existing || project.lastOpenedAt >= existing.lastOpenedAt)
  1046. latestProjectByKey.set(key, project);
  1047. }
  1048. const projects = [...latestProjectByKey.values()].sort(
  1049. (left, right) => right.lastOpenedAt - left.lastOpenedAt,
  1050. );
  1051. const projectsExpanded = expandedProjectSources.has(server.sourceServerId);
  1052. const visibleProjects = projectsExpanded
  1053. ? projects
  1054. : projects.slice(0, COLLAPSED_PROJECT_COUNT);
  1055. const openedProjectPaths = new Set(
  1056. workspaceTabs
  1057. .filter(
  1058. (tab) =>
  1059. getWorkspaceSourceServerId(tab, {
  1060. workspaceHistory: snapshot?.workspaceHistory,
  1061. }) === server.sourceServerId,
  1062. )
  1063. .map((tab) => tab.workspacePath),
  1064. );
  1065. const otherProfiles = displayedProfile
  1066. ? serverProfiles.filter(
  1067. (profile) =>
  1068. profile !== displayedProfile && !pendingIdentityProfiles.includes(profile),
  1069. )
  1070. : [];
  1071. const online = device?.aggregatedStatus === "online";
  1072. const migrationReport = migrationReports[server.sourceServerId];
  1073. const migrationCount = snapshot?.migrationCounts.find(
  1074. (count) => count.sourceServerId === server.sourceServerId,
  1075. );
  1076. const showServerLines = server.installState !== "uninstalled";
  1077. const pendingMigrationCount =
  1078. showServerLines && migrationCount?.status === "available"
  1079. ? migrationCount.failedPathCount + migrationCount.abandonedPathCount
  1080. : 0;
  1081. // 覆盖可更新/必须升级/更新中/更新失败四态:更新中不再携带 updateAvailability,也要选中。
  1082. const profileStates = serverProfiles
  1083. .map((profile) => stateByProfile.get(profile.profileId))
  1084. .filter((state) => state !== undefined);
  1085. const presentation = resolveRemoteConnectionPresentation(
  1086. getRemoteDevicePresentationInput(snapshot, server.sourceServerId),
  1087. );
  1088. const actionProfile =
  1089. serverProfiles.find((profile) => profile.profileId === presentation.profileId) ??
  1090. preferredProfile;
  1091. const deviceBusy = busyScopes.has(`source:${server.sourceServerId}`);
  1092. const lifecycleAvailability = resolveSourceServerLifecycleActionAvailability({
  1093. status: presentation.status,
  1094. deviceBusy,
  1095. lastSeenVersion: server.lastSeenVersion,
  1096. });
  1097. const reinstallAvailability = actionProfile
  1098. ? resolveSourceServerReinstallAvailability({
  1099. status: presentation.status,
  1100. deviceBusy,
  1101. installState: server.installState,
  1102. lastSeenVersion: server.lastSeenVersion,
  1103. localVersion: ZCODE_VERSION,
  1104. })
  1105. : ({ visible: false } as const);
  1106. const actionBusy =
  1107. busyOperations.has(`disconnect:${server.sourceServerId}`) ||
  1108. busyOperations.has(`connect:${actionProfile?.profileId}`) ||
  1109. busyOperations.has(`update:${actionProfile?.profileId}`) ||
  1110. (busyOperations.has("desktop-update") &&
  1111. presentation.primaryAction === "update-desktop");
  1112. const preferredConnectionErrorText = presentation.reason
  1113. ? intl.formatMessage(
  1114. { id: presentation.reason.titleId },
  1115. presentation.reason.values,
  1116. )
  1117. : null;
  1118. const serverState =
  1119. profileStates.find((state) => state.state === "updating") ??
  1120. profileStates.find(
  1121. (state) =>
  1122. (state.updateAvailability && state.updateAvailability !== "none") ||
  1123. state.state === "updating",
  1124. );
  1125. const updateFailed = serverState?.state === "failed";
  1126. const updateKey = sourceServerUpdateKey(
  1127. server.sourceServerId,
  1128. serverState?.availableVersion ?? "",
  1129. );
  1130. const showUpdate =
  1131. serverState &&
  1132. !(
  1133. serverState.updateAvailability === "available" &&
  1134. serverState.state !== "updating" &&
  1135. deferredUpdates.has(updateKey)
  1136. );
  1137. const updateFailureText =
  1138. updateFailed && serverState
  1139. ? formatRemoteConnectionError({
  1140. fallback: intl.formatMessage({ id: "settings.source.operationFailed" }),
  1141. reasonCode: serverState.errorCode,
  1142. retryable: serverState.retryable,
  1143. recoveryAttempt: serverState.recoveryAttempt,
  1144. recoveryLimit: serverState.recoveryLimit,
  1145. formatMessage: intl.formatMessage,
  1146. })
  1147. : null;
  1148. const updateExplainsConnectionError = Boolean(
  1149. showUpdate &&
  1150. serverState?.profileId === presentation.profileId &&
  1151. (serverState?.state === "updating" ||
  1152. (updateFailed && updateFailureText === preferredConnectionErrorText) ||
  1153. (serverState?.updateAvailability === "required" &&
  1154. presentation.reason?.category === "source-server-upgrade-required")),
  1155. );
  1156. const operationLogs =
  1157. logsByProfileId[serverState?.profileId ?? actionProfile?.profileId ?? ""] ?? [];
  1158. const showOtherProfiles = showServerLines && otherProfiles.length > 0;
  1159. const otherProfilesExpanded =
  1160. showOtherProfiles && expandedSavedConnectionSources.has(server.sourceServerId);
  1161. // 更新中由更新横幅展示进度与日志,页脚不重复。
  1162. const showRecentLog = operationLogs.length > 0 && serverState?.state !== "updating";
  1163. const logExpanded =
  1164. showRecentLog &&
  1165. (logExpansionBySource.get(server.sourceServerId) ??
  1166. presentation.status === "failed");
  1167. // 进度展示(RDUX-13):折叠时顶边进度线 + 短状态;展开后进度线隐藏,展开区显示完整进度。
  1168. const deviceBackground =
  1169. background?.sourceServerId === server.sourceServerId ? background : null;
  1170. const backgroundSummary = deviceBackground
  1171. ? summarizeRemoteConnectionProgress(deviceBackground)
  1172. : null;
  1173. let rowPresentation = presentation;
  1174. let rowProgress: SourceServerDeviceRowProgress | undefined;
  1175. const backgroundInFlight =
  1176. backgroundSummary?.progressing === true &&
  1177. !backgroundSummary.waiting &&
  1178. !deviceBackground?.error;
  1179. if (deviceBackground && !backgroundInFlight) {
  1180. // Bug 原因:后台连接期间设备操作互斥禁用,而进度块只在展开区。等待输入、已完成、
  1181. // 失败或已取消时若沿用 Host 状态,折叠行会显示“已连接”或禁用的“重试”,看不出
  1182. // 还要继续或处理;这些状态统一提示需要处理,由用户展开后处理。
  1183. rowPresentation = BACKGROUND_WAITING_PRESENTATION;
  1184. } else if (backgroundInFlight) {
  1185. rowPresentation = BACKGROUND_CONNECTING_PRESENTATION;
  1186. rowProgress = { percent: backgroundSummary.percent };
  1187. } else if (serverState?.state === "updating") {
  1188. rowProgress = { percent: resolveSourceServerUpdatePercent(operationLogs) };
  1189. } else if (presentation.status === "connecting") {
  1190. rowProgress = {};
  1191. }
  1192. // 与展开区可选更新横幅同一条件:稍后隐藏,更新中不显示。
  1193. const optionalUpdateVersion =
  1194. showUpdate &&
  1195. serverState &&
  1196. serverState.updateAvailability === "available" &&
  1197. serverState.state !== "updating"
  1198. ? (serverState.availableVersion?.replace(/^v/i, "") ?? "")
  1199. : null;
  1200. const expanded = expandedDevices.has(server.sourceServerId);
  1201. const showsPrimaryAction =
  1202. presentation.primaryAction !== "none" &&
  1203. presentation.primaryAction !== "disconnect";
  1204. return (
  1205. <SourceServerDeviceRow
  1206. key={server.sourceServerId}
  1207. sourceServerId={server.sourceServerId}
  1208. name={server.displayName}
  1209. address={
  1210. displayedProfile ? formatConnectionProfileTarget(displayedProfile) : undefined
  1211. }
  1212. icon={ConnectionIcon}
  1213. dimIcon={server.installState === "uninstalled"}
  1214. expanded={expanded}
  1215. highlighted={highlightedSourceServerId === server.sourceServerId}
  1216. progress={rowProgress}
  1217. onToggle={() => toggleDevice(server.sourceServerId)}
  1218. toggleRef={(element) => {
  1219. if (element) deviceTogglesRef.current.set(server.sourceServerId, element);
  1220. else deviceTogglesRef.current.delete(server.sourceServerId);
  1221. }}
  1222. metaTone={pendingMigrationCount > 0 ? "warning" : "muted"}
  1223. metaTitle={
  1224. pendingMigrationCount > 0
  1225. ? intl.formatMessage({
  1226. id: "settings.source.connectionHistoryNeedsAttention",
  1227. })
  1228. : undefined
  1229. }
  1230. meta={
  1231. pendingMigrationCount > 0 ? (
  1232. <>
  1233. <FileWarning className="size-3.5 text-warning" aria-hidden="true" />
  1234. {intl.formatMessage(
  1235. { id: "settings.source.pendingMigrationCount" },
  1236. { count: pendingMigrationCount },
  1237. )}
  1238. </>
  1239. ) : optionalUpdateVersion !== null ? (
  1240. intl.formatMessage(
  1241. { id: "settings.source.updateAvailableVersion" },
  1242. { version: optionalUpdateVersion },
  1243. )
  1244. ) : online ? (
  1245. intl.formatMessage(
  1246. { id: "settings.source.projectCount" },
  1247. { count: projects.length },
  1248. )
  1249. ) : server.lastOnlineAt ? (
  1250. intl.formatMessage(
  1251. { id: "settings.source.lastOnline" },
  1252. {
  1253. time: formatRelativeTimestamp(
  1254. server.lastOnlineAt,
  1255. locale,
  1256. intl.formatMessage,
  1257. ),
  1258. },
  1259. )
  1260. ) : undefined
  1261. }
  1262. status={
  1263. <RemoteConnectionStatusTag
  1264. presentation={rowPresentation}
  1265. compact
  1266. progressPercent={rowProgress?.percent}
  1267. />
  1268. }
  1269. actions={
  1270. <>
  1271. {presentation.primaryAction === "confirm-identity" &&
  1272. identityChangeProfile ? (
  1273. renderIdentityConfirmation(identityChangeProfile, "sm")
  1274. ) : showsPrimaryAction ? (
  1275. <Button
  1276. type="button"
  1277. variant="outline"
  1278. size="sm"
  1279. disabled={
  1280. (deviceBusy &&
  1281. !["security", "details"].includes(presentation.primaryAction)) ||
  1282. actionBusy ||
  1283. presentation.status === "connecting"
  1284. }
  1285. aria-busy={actionBusy}
  1286. onClick={() => {
  1287. if (actionProfile)
  1288. handleProfileAction(actionProfile, presentation, server);
  1289. else onCreateConnection?.();
  1290. }}
  1291. >
  1292. {actionBusy ? (
  1293. <LoaderCircle className="size-3.5 animate-spin" aria-hidden="true" />
  1294. ) : null}
  1295. {intl.formatMessage({
  1296. id:
  1297. server.installState === "uninstalled" &&
  1298. presentation.primaryAction === "install"
  1299. ? "settings.source.reinstallAndConnect"
  1300. : presentation.actionMessageId,
  1301. })}
  1302. </Button>
  1303. ) : null}
  1304. {presentation.primaryAction === "update-desktop" && preferredProfile ? (
  1305. <Button
  1306. type="button"
  1307. variant="ghost"
  1308. size="sm"
  1309. disabled={deviceBusy}
  1310. aria-busy={busyOperations.has(`connect:${preferredProfile.profileId}`)}
  1311. onClick={() =>
  1312. void run(
  1313. `connect:${preferredProfile.profileId}`,
  1314. async () => {
  1315. await onConnectProfile?.(preferredProfile.profileId);
  1316. },
  1317. [profileOperationScope(preferredProfile)],
  1318. )
  1319. }
  1320. >
  1321. {busyOperations.has(`connect:${preferredProfile.profileId}`) ? (
  1322. <LoaderCircle className="size-3.5 animate-spin" aria-hidden="true" />
  1323. ) : null}
  1324. {intl.formatMessage({ id: "remote.action.connect" })}
  1325. </Button>
  1326. ) : null}
  1327. <DropdownMenu>
  1328. <DropdownMenuTrigger asChild>
  1329. <Button
  1330. type="button"
  1331. variant="ghost"
  1332. size="icon-sm"
  1333. aria-label={intl.formatMessage({ id: "common.more" })}
  1334. >
  1335. <Ellipsis className="size-3.5" />
  1336. </Button>
  1337. </DropdownMenuTrigger>
  1338. <DropdownMenuContent
  1339. align="end"
  1340. className="w-max min-w-64 [&_[data-slot=dropdown-menu-item]]:whitespace-nowrap"
  1341. >
  1342. {/* RDUX-13:编辑与已连接设备的断开从行上移入菜单,断开仍不弹确认。 */}
  1343. {displayedProfile ? (
  1344. <DropdownMenuItem
  1345. disabled={deviceBusy}
  1346. onSelect={() =>
  1347. setEditingConnection({ profile: displayedProfile, server })
  1348. }
  1349. >
  1350. <Pencil className="size-3.5" />
  1351. {intl.formatMessage({ id: "settings.source.editConnection" })}
  1352. </DropdownMenuItem>
  1353. ) : null}
  1354. {presentation.primaryAction === "disconnect" && actionProfile ? (
  1355. <DropdownMenuItem
  1356. disabled={deviceBusy || actionBusy}
  1357. onSelect={() =>
  1358. handleProfileAction(actionProfile, presentation, server)
  1359. }
  1360. >
  1361. <Unplug className="size-3.5" />
  1362. <span className="flex min-w-0 flex-col">
  1363. {intl.formatMessage({ id: "remote.action.disconnect" })}
  1364. <span className="text-ui-sm text-remote-foreground-muted">
  1365. {intl.formatMessage({ id: "settings.source.disconnectHint" })}
  1366. </span>
  1367. </span>
  1368. </DropdownMenuItem>
  1369. ) : null}
  1370. {/*
  1371. Bug 原因:「移除全部连接」曾被包在 online 分支里,简化 UI 删掉离线态的
  1372. 「重命名 / 迁移报告」后离线菜单变成空壳,离线设备再无任何移除入口。
  1373. 移除只删本机记录与凭据,Host removeSourceServer 会先幂等断开再删记录,
  1374. 不依赖远端在线;因此对所有已安装状态都渲染,只有「在侧边栏中显示」保留在线条件。
  1375. */}
  1376. {onShowInSidebar &&
  1377. workspaceTabs.some(
  1378. (tab) =>
  1379. getWorkspaceSourceServerId(tab, {
  1380. workspaceHistory: snapshot?.workspaceHistory,
  1381. }) === server.sourceServerId,
  1382. ) ? (
  1383. <DropdownMenuItem
  1384. onSelect={() => onShowInSidebar(server.sourceServerId)}
  1385. >
  1386. <ListTree className="size-3.5" />
  1387. {intl.formatMessage({
  1388. id: "settings.source.showInSidebar",
  1389. })}
  1390. </DropdownMenuItem>
  1391. ) : null}
  1392. {displayedProfile || presentation.primaryAction === "disconnect" ? (
  1393. <DropdownMenuSeparator />
  1394. ) : null}
  1395. <div
  1396. className="max-w-80 space-y-1 px-2 py-2 text-ui-sm text-remote-foreground-muted"
  1397. data-device-info
  1398. >
  1399. {[
  1400. ["version", server.lastSeenVersion],
  1401. ["hostname", server.hostname],
  1402. ["osUser", server.osUser],
  1403. ["deviceId", server.sourceServerId],
  1404. ].map(([key, value]) => (
  1405. <p key={key} className="break-all whitespace-normal">
  1406. <span>
  1407. {intl.formatMessage({ id: `settings.source.info.${key}` })}:{" "}
  1408. </span>
  1409. {value ?? intl.formatMessage({ id: "remote.infoUnavailable" })}
  1410. </p>
  1411. ))}
  1412. </div>
  1413. <DropdownMenuItem
  1414. onSelect={() =>
  1415. void run(`copy:${server.sourceServerId}`, async () => {
  1416. await navigator.clipboard.writeText(server.sourceServerId);
  1417. })
  1418. }
  1419. >
  1420. <Copy className="size-3.5" />
  1421. {intl.formatMessage({ id: "settings.source.copyDeviceId" })}
  1422. </DropdownMenuItem>
  1423. {lifecycleAvailability.visible ? (
  1424. <>
  1425. <DropdownMenuSeparator />
  1426. {REMOTE_SERVICE_LIFECYCLE_ACTION_ORDER.map((action) => {
  1427. const copy = REMOTE_SERVICE_LIFECYCLE_ACTIONS[action];
  1428. const Icon = copy.icon;
  1429. return (
  1430. <Fragment key={action}>
  1431. {/* RDRI-01:重新安装位于重启与停止之间;可用规则独立,不受远端控制命令版本门禁约束。 */}
  1432. {action === "stop" &&
  1433. reinstallAvailability.visible &&
  1434. actionProfile ? (
  1435. <DropdownMenuItem
  1436. data-source-server-lifecycle-action="reinstall"
  1437. disabled={!reinstallAvailability.enabled || actionBusy}
  1438. onSelect={() =>
  1439. void reinstallRemoteService(server, actionProfile)
  1440. }
  1441. >
  1442. <Wrench className="size-3.5" />
  1443. <span className="flex min-w-0 flex-col">
  1444. {intl.formatMessage({
  1445. id: "settings.source.reinstallRemoteService",
  1446. })}
  1447. <span className="text-ui-sm text-remote-foreground-muted">
  1448. {intl.formatMessage({
  1449. id: "settings.source.reinstallRemoteServiceHint",
  1450. })}
  1451. </span>
  1452. </span>
  1453. </DropdownMenuItem>
  1454. ) : null}
  1455. <DropdownMenuItem
  1456. variant={copy.variant}
  1457. data-source-server-lifecycle-action={action}
  1458. disabled={!lifecycleAvailability.enabled}
  1459. onSelect={() =>
  1460. void runRemoteServiceLifecycle(server, action)
  1461. }
  1462. >
  1463. <Icon className="size-3.5" />
  1464. <span className="flex min-w-0 flex-col">
  1465. {intl.formatMessage({ id: copy.label })}
  1466. {/* 禁用菜单项不响应指针,版本提示必须常驻在项内而不是悬停提示。 */}
  1467. {lifecycleAvailability.requiresRemoteUpdate ? (
  1468. <span className="text-ui-sm text-remote-foreground-muted">
  1469. {intl.formatMessage({
  1470. id: "settings.source.remoteServiceUpdateRequired",
  1471. })}
  1472. </span>
  1473. ) : null}
  1474. </span>
  1475. </DropdownMenuItem>
  1476. </Fragment>
  1477. );
  1478. })}
  1479. </>
  1480. ) : null}
  1481. <DropdownMenuSeparator />
  1482. <DropdownMenuItem
  1483. variant="destructive"
  1484. disabled={deviceBusy}
  1485. onSelect={() => void removeSourceServer(server)}
  1486. >
  1487. <Trash2 className="size-3.5" />
  1488. {intl.formatMessage({
  1489. id: "settings.source.removeSourceServer",
  1490. })}
  1491. </DropdownMenuItem>
  1492. </DropdownMenuContent>
  1493. </DropdownMenu>
  1494. </>
  1495. }
  1496. >
  1497. {deviceBackground ? (
  1498. <div className="-mx-4">
  1499. <RemoteConnectionMinimizedProgress {...deviceBackground} />
  1500. </div>
  1501. ) : presentation.status === "connecting" && presentation.recovery ? (
  1502. <div className="rounded-lg bg-progress-surface px-3 py-2 text-ui-base text-progress-surface-foreground">
  1503. {intl.formatMessage(
  1504. { id: presentation.recovery.messageId },
  1505. presentation.recovery.values,
  1506. )}
  1507. </div>
  1508. ) : null}
  1509. <div
  1510. className="flex min-w-0 flex-wrap items-center gap-2 text-ui-sm text-remote-foreground-muted"
  1511. data-device-connection
  1512. >
  1513. {displayedProfile ? (
  1514. <>
  1515. <RemoteConnectionKindTag kind={displayedProfile.transport} />
  1516. <span
  1517. className="min-w-0 truncate font-mono"
  1518. title={formatConnectionProfileTarget(displayedProfile)}
  1519. >
  1520. {formatConnectionProfileTarget(displayedProfile)}
  1521. </span>
  1522. {/* 只有一条连接时“当前 / 默认”没有区分意义,不显示。 */}
  1523. {serverProfiles.length > 1 && currentProfile ? (
  1524. <span className="shrink-0 rounded-md bg-tag px-1.5 py-0.5 text-ui-xs">
  1525. {intl.formatMessage({
  1526. id: "settings.source.currentProfile",
  1527. })}
  1528. </span>
  1529. ) : null}
  1530. {serverProfiles.length > 1 &&
  1531. displayedProfile.profileId === server.preferredProfileId ? (
  1532. <span className="shrink-0 rounded-md bg-tag px-1.5 py-0.5 text-ui-xs">
  1533. {intl.formatMessage({ id: "settings.source.defaultProfile" })}
  1534. </span>
  1535. ) : null}
  1536. {displayedProfile.profileId !== server.preferredProfileId ? (
  1537. <Button
  1538. type="button"
  1539. variant="ghost"
  1540. size="xs"
  1541. disabled={deviceBusy}
  1542. onClick={() =>
  1543. void run(
  1544. `preferred:${displayedProfile.profileId}`,
  1545. () =>
  1546. management.setPreferredProfile(
  1547. server.sourceServerId,
  1548. displayedProfile.profileId,
  1549. ),
  1550. [`source:${server.sourceServerId}`],
  1551. )
  1552. }
  1553. >
  1554. {intl.formatMessage({ id: "settings.source.setDefault" })}
  1555. </Button>
  1556. ) : null}
  1557. </>
  1558. ) : null}
  1559. {server.lastSeenVersion ? (
  1560. <span
  1561. className="shrink-0"
  1562. title={intl.formatMessage({ id: "settings.source.info.version" })}
  1563. >
  1564. {displayedProfile ? "· " : ""}v{server.lastSeenVersion.replace(/^v/i, "")}
  1565. </span>
  1566. ) : null}
  1567. {server.lastOnlineAt && !online ? (
  1568. <span
  1569. className="shrink-0"
  1570. title={formatTimestamp(server.lastOnlineAt, locale)}
  1571. >
  1572. {displayedProfile || server.lastSeenVersion ? "· " : ""}
  1573. {intl.formatMessage(
  1574. { id: "settings.source.lastOnline" },
  1575. {
  1576. time: formatRelativeTimestamp(
  1577. server.lastOnlineAt,
  1578. locale,
  1579. intl.formatMessage,
  1580. ),
  1581. },
  1582. )}
  1583. </span>
  1584. ) : null}
  1585. </div>
  1586. {/* 更新失败只替代同一连接的相同原因,其他连接和可选更新不能吞掉连接错误。 */}
  1587. {preferredConnectionErrorText && !updateExplainsConnectionError ? (
  1588. <div className="flex flex-wrap items-center gap-2 rounded-lg bg-destructive-surface px-3 py-2 text-ui-base text-destructive-surface-foreground">
  1589. <span className="min-w-0 flex-1">{preferredConnectionErrorText}</span>
  1590. {/* RDRI-01:连接失败时就地提供重新安装;与「更多」菜单共用同一可用规则与确认。 */}
  1591. {presentation.status === "failed" &&
  1592. reinstallAvailability.visible &&
  1593. actionProfile ? (
  1594. <Button
  1595. type="button"
  1596. variant="outline"
  1597. size="sm"
  1598. data-source-server-reinstall
  1599. disabled={!reinstallAvailability.enabled || actionBusy}
  1600. onClick={() => void reinstallRemoteService(server, actionProfile)}
  1601. >
  1602. {intl.formatMessage({ id: "settings.source.reinstallRemoteService" })}
  1603. </Button>
  1604. ) : null}
  1605. </div>
  1606. ) : null}
  1607. {showUpdate && serverState ? (
  1608. <div
  1609. className={cn(
  1610. "flex flex-wrap items-center justify-between gap-2 rounded-lg px-3 py-2 text-ui-base",
  1611. presentation.updateNotice.surface,
  1612. presentation.updateNotice.foreground,
  1613. )}
  1614. >
  1615. <span>
  1616. {serverState.state === "updating"
  1617. ? intl.formatMessage({
  1618. id: "settings.source.updateInProgress",
  1619. })
  1620. : updateFailed
  1621. ? updateFailureText
  1622. : serverState.updateAvailability === "required"
  1623. ? intl.formatMessage({
  1624. id: "settings.source.updateRequired",
  1625. })
  1626. : intl.formatMessage(
  1627. { id: "settings.source.updateAvailableVersion" },
  1628. {
  1629. version: serverState.availableVersion?.replace(/^v/i, "") ?? "",
  1630. },
  1631. )}
  1632. </span>
  1633. {serverState.updateAvailability === "available" &&
  1634. serverState.state !== "updating" ? (
  1635. <Button
  1636. type="button"
  1637. variant="ghost"
  1638. size="sm"
  1639. className="ml-auto"
  1640. onClick={() => sourceServerUpdatePreferences.defer(updateKey)}
  1641. >
  1642. {intl.formatMessage({ id: "updateDialog.later" })}
  1643. </Button>
  1644. ) : null}
  1645. {serverState.state !== "updating" &&
  1646. presentation.primaryAction !== "update-server" &&
  1647. presentation.primaryAction !== "update-desktop" ? (
  1648. <Button
  1649. type="button"
  1650. variant="outline"
  1651. size="sm"
  1652. disabled={deviceBusy || busyOperations.has("desktop-update")}
  1653. onClick={() => {
  1654. const profile = serverProfiles.find(
  1655. (candidate) => candidate.profileId === serverState.profileId,
  1656. );
  1657. if (serverState.upgradeTarget === "controller")
  1658. void run("desktop-update", async () => {
  1659. await platform?.executeDesktopCommand(
  1660. DesktopCommandIds.CheckForUpdates,
  1661. );
  1662. });
  1663. else if (profile) void updateProfile(profile);
  1664. }}
  1665. >
  1666. {intl.formatMessage({
  1667. id:
  1668. serverState.upgradeTarget === "controller"
  1669. ? "remote.action.update-desktop"
  1670. : updateFailed
  1671. ? "remote.action.retry"
  1672. : "remote.action.update-server",
  1673. })}
  1674. </Button>
  1675. ) : null}
  1676. {serverState.upgradeTarget === "controller" &&
  1677. serverState.updateAvailability === "required" &&
  1678. serverState.state !== "updating" &&
  1679. serverState.currentVersion ? (
  1680. <Button
  1681. type="button"
  1682. variant="outline"
  1683. size="sm"
  1684. disabled={deviceBusy}
  1685. onClick={() => {
  1686. const profile = serverProfiles.find(
  1687. (candidate) => candidate.profileId === serverState.profileId,
  1688. );
  1689. if (!profile) return;
  1690. void confirmDialog(
  1691. getSourceServerDowngradeConfirmation(serverState, intl.formatMessage),
  1692. ).then((confirmed) =>
  1693. confirmed ? updateProfile(profile, true) : undefined,
  1694. );
  1695. }}
  1696. >
  1697. {intl.formatMessage(
  1698. { id: "remote.action.downgrade-server" },
  1699. { version: serverState.currentVersion.replace(/^v/i, "") },
  1700. )}
  1701. </Button>
  1702. ) : null}
  1703. {serverState.state === "updating" ? (
  1704. <SourceServerUpdateActivity
  1705. active={serverState.state === "updating"}
  1706. logs={operationLogs}
  1707. />
  1708. ) : serverState.currentVersion && serverState.minimumVersion ? (
  1709. <p className="basis-full text-ui-sm opacity-80">
  1710. {intl.formatMessage(
  1711. { id: "settings.source.versionDetails" },
  1712. {
  1713. current: serverState.currentVersion.replace(/^v/i, ""),
  1714. minimum: serverState.minimumVersion.replace(/^v/i, ""),
  1715. },
  1716. )}
  1717. </p>
  1718. ) : null}
  1719. </div>
  1720. ) : null}
  1721. {pendingIdentityProfiles.length > 1 ? (
  1722. <div>
  1723. {pendingIdentityProfiles
  1724. .filter((profile) => profile !== identityChangeProfile)
  1725. .map((profile) => renderProfile(profile, server))}
  1726. </div>
  1727. ) : null}
  1728. <div className="min-w-0" data-device-projects>
  1729. {projects.length === 0 ? (
  1730. <p className="text-ui-sm text-remote-foreground-muted">
  1731. {intl.formatMessage({ id: "settings.source.projectCount" }, { count: 0 })}
  1732. </p>
  1733. ) : (
  1734. <>
  1735. <div className="flex min-w-0 items-center justify-between gap-2">
  1736. <p className="text-ui-sm font-medium text-remote-foreground-muted">
  1737. {intl.formatMessage({ id: "settings.source.recentProjects" })}
  1738. </p>
  1739. {/* Bug 原因:旧实现超出三个只显示不可点击的 +N,其余项目在此处无法打开。 */}
  1740. {projects.length > COLLAPSED_PROJECT_COUNT ? (
  1741. <Button
  1742. type="button"
  1743. variant="ghost"
  1744. size="xs"
  1745. className="text-remote-foreground-muted"
  1746. aria-expanded={projectsExpanded}
  1747. onClick={() =>
  1748. setExpandedProjectSources((current) =>
  1749. toggleSetItem(current, server.sourceServerId),
  1750. )
  1751. }
  1752. >
  1753. {intl.formatMessage(
  1754. {
  1755. id: projectsExpanded
  1756. ? "settings.source.showLessProjects"
  1757. : "settings.source.showAllProjects",
  1758. },
  1759. { count: projects.length },
  1760. )}
  1761. </Button>
  1762. ) : null}
  1763. </div>
  1764. <div className="mt-1 min-w-0">
  1765. {visibleProjects.map((project) => {
  1766. const projectName = getProjectDisplayName(
  1767. server,
  1768. project.workspacePath,
  1769. );
  1770. return (
  1771. <Button
  1772. key={resolveWorkspaceKey(project)}
  1773. data-device-project
  1774. type="button"
  1775. variant="ghost"
  1776. size="sm"
  1777. className="group/project -mx-2 h-auto w-[calc(100%+1rem)] min-w-0 justify-start gap-2 px-2 py-1.5"
  1778. aria-label={projectName}
  1779. title={project.workspacePath}
  1780. disabled={!onOpenProject || deviceBusy}
  1781. onClick={() =>
  1782. void run(
  1783. `open:${resolveWorkspaceKey(project)}`,
  1784. () =>
  1785. onOpenProject?.(
  1786. server.sourceServerId,
  1787. project.workspacePath,
  1788. displayedProfile?.profileId,
  1789. ) ?? Promise.resolve(),
  1790. [`source:${server.sourceServerId}`],
  1791. )
  1792. }
  1793. >
  1794. <Folder className="size-3.5 text-remote-foreground-muted" />
  1795. <span className="max-w-48 shrink-0 truncate text-ui-base font-medium">
  1796. {projectName}
  1797. </span>
  1798. <span className="min-w-0 flex-1 truncate text-left font-mono text-ui-sm text-remote-foreground-muted">
  1799. {project.workspacePath}
  1800. </span>
  1801. {openedProjectPaths.has(project.workspacePath) ? (
  1802. <span className="shrink-0 rounded-md bg-tag px-1.5 py-0.5 text-ui-xs text-remote-foreground-muted">
  1803. {intl.formatMessage({ id: "settings.source.projectOpened" })}
  1804. </span>
  1805. ) : null}
  1806. <span className="shrink-0 text-ui-sm text-remote-foreground-muted">
  1807. {formatRelativeTimestamp(
  1808. project.lastOpenedAt,
  1809. locale,
  1810. intl.formatMessage,
  1811. )}
  1812. </span>
  1813. <ArrowUpRight className="size-3.5 text-remote-foreground-muted opacity-0 group-hover/project:opacity-100 group-focus-visible/project:opacity-100" />
  1814. </Button>
  1815. );
  1816. })}
  1817. </div>
  1818. </>
  1819. )}
  1820. </div>
  1821. {showOtherProfiles || showRecentLog ? (
  1822. <div className="border-t border-border pt-2" data-device-card-footer>
  1823. <div className="flex min-w-0 flex-wrap items-center gap-2">
  1824. {showOtherProfiles ? (
  1825. <Button
  1826. type="button"
  1827. variant="ghost"
  1828. size="sm"
  1829. className="-ml-2 text-remote-foreground-muted"
  1830. aria-label={intl.formatMessage({
  1831. id: "settings.source.otherSavedConnections",
  1832. })}
  1833. aria-expanded={otherProfilesExpanded}
  1834. onClick={() =>
  1835. setExpandedSavedConnectionSources((current) =>
  1836. toggleSetItem(current, server.sourceServerId),
  1837. )
  1838. }
  1839. >
  1840. {otherProfilesExpanded ? (
  1841. <ChevronDown className="size-3.5" />
  1842. ) : (
  1843. <ChevronRight className="size-3.5" />
  1844. )}
  1845. {intl.formatMessage(
  1846. { id: "settings.source.otherSavedConnectionsCount" },
  1847. { count: otherProfiles.length },
  1848. )}
  1849. </Button>
  1850. ) : null}
  1851. {showRecentLog ? (
  1852. <Button
  1853. data-source-server-log-toggle
  1854. type="button"
  1855. variant="ghost"
  1856. size="sm"
  1857. // 只有日志入口时靠左,避免页脚左侧空出一整行。
  1858. className={cn(
  1859. "text-remote-foreground-muted",
  1860. showOtherProfiles ? "-mr-2 ml-auto" : "-ml-2",
  1861. )}
  1862. aria-expanded={logExpanded}
  1863. onClick={() =>
  1864. setLogExpansionBySource((current) =>
  1865. new Map(current).set(server.sourceServerId, !logExpanded),
  1866. )
  1867. }
  1868. >
  1869. <ChevronRight
  1870. className={cn(
  1871. "size-3.5 transition-transform",
  1872. logExpanded && "rotate-90",
  1873. )}
  1874. />
  1875. {intl.formatMessage({ id: "settings.source.recentLog" })}
  1876. </Button>
  1877. ) : null}
  1878. </div>
  1879. {otherProfilesExpanded ? (
  1880. <div className="mt-1 px-2 py-1">
  1881. {otherProfiles.map((profile) => renderProfile(profile, server))}
  1882. </div>
  1883. ) : null}
  1884. {logExpanded ? (
  1885. <div className="mt-1 pb-1">
  1886. <SourceServerLogList logs={operationLogs} />
  1887. </div>
  1888. ) : null}
  1889. </div>
  1890. ) : null}
  1891. {/* 产品边界:迁移账本是内部兼容机制,仅在存在待处理问题时以用户可理解的连接历史提醒暴露。 */}
  1892. {pendingMigrationCount > 0 ? (
  1893. <div className="border-t border-border pt-2">
  1894. <Button
  1895. type="button"
  1896. variant="ghost"
  1897. size="sm"
  1898. className="-ml-2 justify-start text-ui-base text-remote-foreground-muted"
  1899. onClick={() => toggleMigrationReport(server.sourceServerId)}
  1900. >
  1901. {migrationReport ? (
  1902. <ChevronDown className="size-3.5" />
  1903. ) : (
  1904. <ChevronRight className="size-3.5" />
  1905. )}
  1906. <FileWarning className="size-3.5 text-warning" />
  1907. {intl.formatMessage({
  1908. id: "settings.source.connectionHistoryNeedsAttention",
  1909. })}
  1910. <span className="font-medium text-warning-surface-foreground">
  1911. {intl.formatMessage(
  1912. { id: "settings.source.pendingMigrationCount" },
  1913. { count: pendingMigrationCount },
  1914. )}
  1915. </span>
  1916. </Button>
  1917. {migrationReport ? (
  1918. <SourceServerMigrationReportPanel
  1919. report={migrationReport}
  1920. disabled={deviceBusy}
  1921. onAbandon={(workspacePath, migrationId) => {
  1922. void confirmDialog({
  1923. title: intl.formatMessage({
  1924. id: "settings.source.abandonMigrationTitle",
  1925. }),
  1926. description: intl.formatMessage({
  1927. id: "settings.source.abandonMigrationDescription",
  1928. }),
  1929. confirmLabel: intl.formatMessage({
  1930. id: "settings.source.abandonMigration",
  1931. }),
  1932. confirmVariant: "destructive",
  1933. }).then((confirmed) => {
  1934. if (!confirmed) return;
  1935. void runMigrationOperation(
  1936. `abandon:${server.sourceServerId}:${migrationId}`,
  1937. server.sourceServerId,
  1938. () =>
  1939. management.abandonWorkspaceMigration(
  1940. server.sourceServerId,
  1941. workspacePath,
  1942. migrationId,
  1943. ),
  1944. );
  1945. });
  1946. }}
  1947. onRetry={(workspacePath, migrationId) =>
  1948. void runMigrationOperation(
  1949. `retry:${server.sourceServerId}:${migrationId}`,
  1950. server.sourceServerId,
  1951. () =>
  1952. management.retryWorkspaceMigration(
  1953. server.sourceServerId,
  1954. workspacePath,
  1955. migrationId,
  1956. ),
  1957. )
  1958. }
  1959. />
  1960. ) : null}
  1961. </div>
  1962. ) : null}
  1963. </SourceServerDeviceRow>
  1964. );
  1965. })}
  1966. </div>
  1967. ) : null}
  1968. {unboundProfiles.length > 0 ? (
  1969. <details
  1970. open={
  1971. background &&
  1972. !background.sourceServerId &&
  1973. unboundProfiles.some((profile) => profile.profileId === background.profileId)
  1974. ? true
  1975. : undefined
  1976. }
  1977. data-unfinished-connections
  1978. className="group/unfinished border-t border-border pt-4"
  1979. >
  1980. <summary className="flex cursor-pointer list-none items-center gap-2 text-ui-base font-medium">
  1981. <ChevronRight className="size-3.5 transition-transform group-open/unfinished:rotate-90" />
  1982. {intl.formatMessage({ id: "settings.source.unfinishedConnections" })}
  1983. <span className="rounded-md bg-tag px-1.5 py-0.5 text-ui-xs font-normal text-remote-foreground-muted">
  1984. {unboundProfiles.length}
  1985. </span>
  1986. </summary>
  1987. <div className="mt-2 space-y-2">
  1988. {unboundProfiles.map((profile) => (
  1989. <div key={profile.profileId}>
  1990. {renderProfile(profile)}
  1991. {background &&
  1992. !background.sourceServerId &&
  1993. background.profileId === profile.profileId ? (
  1994. <RemoteConnectionMinimizedProgress {...background} />
  1995. ) : null}
  1996. {(logsByProfileId[profile.profileId]?.length ?? 0) > 0 ? (
  1997. <SourceServerUpdateActivity
  1998. active={false}
  1999. recent
  2000. logs={logsByProfileId[profile.profileId] ?? []}
  2001. />
  2002. ) : null}
  2003. </div>
  2004. ))}
  2005. <Button
  2006. type="button"
  2007. variant="outline"
  2008. size="sm"
  2009. disabled={
  2010. busyOperations.has("clear-unfinished") ||
  2011. unboundProfiles.some((profile) => busyScopes.has(profileOperationScope(profile)))
  2012. }
  2013. onClick={() => {
  2014. void confirmDialog({
  2015. title: intl.formatMessage({ id: "settings.source.clearUnfinished" }),
  2016. description: intl.formatMessage({
  2017. id: "settings.source.clearUnfinishedDescription",
  2018. }),
  2019. confirmLabel: intl.formatMessage({ id: "settings.source.clearUnfinished" }),
  2020. confirmVariant: "destructive",
  2021. }).then((confirmed) => {
  2022. if (confirmed)
  2023. void run(
  2024. "clear-unfinished",
  2025. async () => {
  2026. // 清理时复核归属,连接刚成功的设备不能被旧列表误删。
  2027. const latest = await management.getSnapshot();
  2028. for (const profile of latest.profiles) {
  2029. if (!profile.sourceServerId && profile.lifecycleState !== "retired")
  2030. applySnapshot(await management.removeProfile(profile.profileId));
  2031. }
  2032. },
  2033. unboundProfiles.map(profileOperationScope),
  2034. );
  2035. });
  2036. }}
  2037. >
  2038. {intl.formatMessage({ id: "settings.source.clearUnfinished" })}
  2039. </Button>
  2040. </div>
  2041. </details>
  2042. ) : null}
  2043. {retiredProfiles.length > 0 ? (
  2044. <details className="group/retired border-t border-border pt-4">
  2045. <summary className="flex cursor-pointer list-none flex-wrap items-center gap-2 text-ui-base font-medium text-foreground">
  2046. <ChevronRight className="size-3.5 shrink-0 text-remote-foreground-muted transition-transform group-open/retired:rotate-90" />
  2047. {intl.formatMessage(
  2048. { id: "settings.source.retiredProfilesWithCount" },
  2049. { count: retiredProfiles.length },
  2050. )}
  2051. <span className="text-ui-sm font-normal text-remote-foreground-muted">
  2052. {intl.formatMessage({
  2053. id: "settings.source.retiredProfilesDescription",
  2054. })}
  2055. </span>
  2056. </summary>
  2057. <div className="mt-2 space-y-1 pl-6">
  2058. {retiredProfiles.map((profile) => (
  2059. <div
  2060. key={profile.profileId}
  2061. className="flex min-w-0 flex-wrap items-center gap-2 py-1.5 text-remote-foreground-muted"
  2062. >
  2063. <span className="font-mono text-ui-sm">
  2064. {profile.displayName ?? profile.transport}
  2065. {intl.formatMessage({
  2066. id: "settings.source.retiredNameSuffix",
  2067. })}
  2068. </span>
  2069. <span className="text-ui-sm">
  2070. {profile.retiredAt
  2071. ? `${intl.formatMessage(
  2072. { id: "settings.source.archivedAt" },
  2073. {
  2074. time: formatRelativeTimestamp(
  2075. profile.retiredAt,
  2076. locale,
  2077. intl.formatMessage,
  2078. ),
  2079. },
  2080. )} · ${intl.formatMessage({
  2081. id: "settings.source.retiredEntryNote",
  2082. })}`
  2083. : intl.formatMessage({
  2084. id: "settings.source.retiredEntryNote",
  2085. })}
  2086. </span>
  2087. </div>
  2088. ))}
  2089. </div>
  2090. </details>
  2091. ) : null}
  2092. <section className="border-t border-border pt-4">
  2093. <h3 className="text-ui-base font-medium text-foreground">
  2094. {intl.formatMessage({
  2095. id: "settings.source.preferences",
  2096. })}
  2097. </h3>
  2098. <div className="mt-3 space-y-4">
  2099. <div className="flex items-start justify-between gap-3">
  2100. <div>
  2101. <p className="text-ui-base text-foreground">
  2102. {intl.formatMessage({ id: "settings.source.hideProjectDeviceNames" })}
  2103. </p>
  2104. <p className="text-ui-sm text-remote-foreground-muted">
  2105. {intl.formatMessage({ id: "settings.source.hideProjectDeviceNamesDescription" })}
  2106. </p>
  2107. </div>
  2108. <Switch
  2109. data-testid="hide-project-device-names"
  2110. checked={hideProjectDeviceNames}
  2111. disabled={!onHideProjectDeviceNamesChange}
  2112. onCheckedChange={onHideProjectDeviceNamesChange}
  2113. aria-label={intl.formatMessage({ id: "settings.source.hideProjectDeviceNames" })}
  2114. />
  2115. </div>
  2116. <div className="flex items-start justify-between gap-3">
  2117. <div>
  2118. <p className="text-ui-base text-foreground">
  2119. {intl.formatMessage({
  2120. id: "settings.source.startupAutoReconnect",
  2121. })}
  2122. </p>
  2123. <p className="text-ui-sm text-remote-foreground-muted">
  2124. {intl.formatMessage({
  2125. id: "settings.source.startupAutoReconnectDescription",
  2126. })}
  2127. </p>
  2128. </div>
  2129. <Switch
  2130. checked={startupAutoReconnect}
  2131. disabled={busyOperations.has("startup-reconnect") || !onUpdateSettings}
  2132. aria-busy={busyOperations.has("startup-reconnect")}
  2133. onCheckedChange={(checked) => {
  2134. const previous = startupAutoReconnect;
  2135. setStartupAutoReconnect(checked);
  2136. void run("startup-reconnect", async () => {
  2137. try {
  2138. await onUpdateSettings?.({ remoteStartupAutoReconnectEnabled: checked });
  2139. } catch (cause) {
  2140. setStartupAutoReconnect(previous);
  2141. throw cause;
  2142. }
  2143. });
  2144. }}
  2145. aria-label={intl.formatMessage({
  2146. id: "settings.source.startupAutoReconnect",
  2147. })}
  2148. />
  2149. </div>
  2150. </div>
  2151. </section>
  2152. {ready && profiles.length === 0 && servers.length === 0 ? (
  2153. <div className="space-y-3 py-4 text-center text-ui-base text-remote-foreground-muted">
  2154. <p>{intl.formatMessage({ id: "settings.source.empty" })}</p>
  2155. {onCreateConnection ? (
  2156. <Button type="button" size="sm" onClick={onCreateConnection}>
  2157. <Plus className="size-3.5" />
  2158. {intl.formatMessage({ id: "settings.source.newConnection" })}
  2159. </Button>
  2160. ) : null}
  2161. </div>
  2162. ) : null}
  2163. </div>
  2164. <Dialog
  2165. open={Boolean(errorDetailsProfile)}
  2166. onOpenChange={(open) => {
  2167. if (!open) setErrorDetailsProfile(null);
  2168. }}
  2169. >
  2170. <DialogContent>
  2171. {errorDetailsProfile
  2172. ? (() => {
  2173. const state = stateByProfile.get(errorDetailsProfile.profileId);
  2174. const classified = classifyRemoteConnectionError({
  2175. errorCode: state?.errorCode,
  2176. error: state?.error,
  2177. target: errorDetailsProfile.target,
  2178. });
  2179. return (
  2180. <>
  2181. <DialogHeader>
  2182. <DialogTitle>{intl.formatMessage({ id: classified.titleId })}</DialogTitle>
  2183. <DialogDescription>
  2184. {intl.formatMessage({ id: classified.reasonId })}
  2185. </DialogDescription>
  2186. </DialogHeader>
  2187. <details>
  2188. <summary>{intl.formatMessage({ id: "remote.error.details" })}</summary>
  2189. <pre className="whitespace-pre-wrap break-words text-ui-sm">
  2190. {state?.error ?? errorDetailsProfile.lastConnectError}
  2191. </pre>
  2192. </details>
  2193. <SourceServerUpdateActivity
  2194. active={false}
  2195. recent
  2196. logs={logsByProfileId[errorDetailsProfile.profileId] ?? []}
  2197. />
  2198. </>
  2199. );
  2200. })()
  2201. : null}
  2202. </DialogContent>
  2203. </Dialog>
  2204. <EditConnectionProfileDialog
  2205. open={editingConnection !== null}
  2206. profile={editingConnection?.profile ?? null}
  2207. source={editingConnection?.server}
  2208. focusField={editingConnection?.focusField}
  2209. management={management}
  2210. onOpenChange={(open) => {
  2211. if (!open) setEditingConnection(null);
  2212. }}
  2213. onSaved={refresh}
  2214. />
  2215. </div>
  2216. );
  2217. }