| 1 | import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type Dispatch, type SetStateAction } from "react"; |
| 2 | import { Plus, Server, Square, XCircle } from "lucide-react"; |
| 3 | |
| 4 | import { app, onRemoteTabOpened, onRemoteTabUpdated } from "../lib/bridge"; |
| 5 | import { runtimeStateStore, selectRuntime, type RuntimeProjection } from "../lib/runtimeStateStore"; |
| 6 | import type { Translator } from "../lib/i18n"; |
| 7 | import type { ProjectNode, RemoteServerView, RemoteSessionView, RemoteTabRefView } from "../lib/types"; |
| 8 | import type { ToastContextValue } from "../lib/toast"; |
| 9 | import { loadRemoteSessionCache, removeRemoteSessionCache, saveRemoteSessionCache } from "../lib/remoteSessionCache"; |
| 10 | import { useRemoteNavigationCommand } from "../lib/remoteNavigationCommands"; |
| 11 | import { publishNavigationIntent } from "../lib/useNavigationIntentFence"; |
| 12 | import { useRemoteStore, waitForRemoteConnection } from "../store/remote"; |
| 13 | import type { ContextMenuItem } from "./ContextMenu"; |
| 14 | |
| 15 | export function remoteProjectKey(ref: RemoteTabRefView): string { |
| 16 | return `${ref.hostId}\u0000${ref.workspace}`; |
| 17 | } |
| 18 | |
| 19 | // Canonical remote sessions may not have a legacy transcript path. Use the |
| 20 | // immutable session ID first so React keys, topic IDs, and action lookups do |
| 21 | // not collapse a canonical row into a path-only or blank row. |
| 22 | export function remoteSessionIdentity(row: Pick<RemoteSessionView, "sessionId" | "path" | "name">): string { |
| 23 | return row.sessionId?.trim() || row.path?.trim() || row.name?.trim() || "new"; |
| 24 | } |
| 25 | |
| 26 | // Mutations still use the historical bridge argument named `name`, but that |
| 27 | // argument is an identity token, not the visible title. Canonical rows must |
| 28 | // use sessionId; legacy rows retain their stable basename. |
| 29 | export function remoteSessionActionIdentity(remote: Pick<RemoteSessionView, "sessionId" | "name" | "path">): string { |
| 30 | // Keep the legacy name fallback for old Serve rows, but never fall back to |
| 31 | // path: the synthetic current row may have a path while still being a |
| 32 | // blank, non-catalogued session. |
| 33 | const legacyIdentity = remote.name || remote.sessionId || ""; |
| 34 | const explicit = remote.sessionId?.trim() || legacyIdentity.trim(); |
| 35 | if (explicit) return explicit; |
| 36 | const route = remote.path?.trim() || ""; |
| 37 | return route.startsWith("session-id:") ? route.slice("session-id:".length).trim() : ""; |
| 38 | } |
| 39 | |
| 40 | // A remote session cannot be trashed while it is the serve's current row, or |
| 41 | // before it has an identity the delete call can name. |
| 42 | export function remoteSessionArchiveBlocked( |
| 43 | remote: (Pick<RemoteSessionView, "sessionId" | "name" | "path"> & { current?: boolean }) | undefined, |
| 44 | ): boolean { |
| 45 | return Boolean(remote && (remote.current || !remoteSessionActionIdentity(remote))); |
| 46 | } |
| 47 | |
| 48 | export function remoteSessionLabel(row: Pick<RemoteSessionView, "sessionId" | "name" | "title">, t: Translator): string { |
| 49 | const title = row.title?.trim(); |
| 50 | if (title) return title; |
| 51 | // Canonical rows use `name` as an identity compatibility field, which is |
| 52 | // the opaque session ID. Never expose that ID as the visible topic label. |
| 53 | if (row.sessionId?.trim()) return t("projectTree.newTopic"); |
| 54 | return row.name?.trim() || t("projectTree.newTopic"); |
| 55 | } |
| 56 | |
| 57 | export function useRemoteRuntimeTree(tree: ProjectNode[], sessions: Record<string, RemoteSessionView[]>, t: Translator) { |
| 58 | const runtime = useSyncExternalStore(runtimeStateStore.subscribe, runtimeStateStore.getSnapshot); |
| 59 | const failed = useSyncExternalStore(runtimeStateStore.subscribe, runtimeStateStore.getFailed); |
| 60 | return useMemo(() => mergeRemoteSessionsIntoTree(tree, sessions, t, runtime, failed), [tree, sessions, t, runtime, failed]); |
| 61 | } |
| 62 | |
| 63 | export function activeRemoteProjectAncestorKeys( |
| 64 | nodes: ProjectNode[], |
| 65 | activeRemote: RemoteTabRefView, |
| 66 | nodeKey: (node: ProjectNode, index: number) => string, |
| 67 | ): string[] { |
| 68 | const activeKey = remoteProjectKey(activeRemote); |
| 69 | return nodes.flatMap((node, index) => node.remote && remoteProjectKey(node.remote) === activeKey ? [nodeKey(node, index)] : []); |
| 70 | } |
| 71 | |
| 72 | export function remoteServeBadgeState(view?: RemoteServerView, busy = false): string { |
| 73 | if (busy) return "serve-busy"; |
| 74 | if (view?.state === "ready") return "serve-ready"; |
| 75 | if (view?.state === "error") return "serve-error"; |
| 76 | if (!view || view.state === "stopped") return "serve-idle"; |
| 77 | return "serve-busy"; |
| 78 | } |
| 79 | |
| 80 | export function mergeRemoteSessionsIntoTree( |
| 81 | tree: ProjectNode[], |
| 82 | sessions: Record<string, RemoteSessionView[]>, |
| 83 | t: Translator, |
| 84 | runtime?: RuntimeProjection, |
| 85 | failed = false, |
| 86 | ): ProjectNode[] { |
| 87 | return tree.map((node) => { |
| 88 | if (!node.remote) return node; |
| 89 | const rows = sessions[remoteProjectKey(node.remote)] ?? []; |
| 90 | const remoteChildren = rows.map((row): ProjectNode => { |
| 91 | const identity = remoteSessionIdentity(row); |
| 92 | const session = runtime?.sessions.find(session => session.hostId === node.remote!.hostId && session.workspaceRoot === node.remote!.workspace && ( |
| 93 | row.sessionId ? session.sessionId === row.sessionId : session.sessionPath === row.path |
| 94 | )); |
| 95 | const state = selectRuntime(session, failed); |
| 96 | const status = state.unknown ? "unknown" : state.known && state.kind !== "idle" && state.kind !== "legacy" ? state.kind : undefined; |
| 97 | return ({ |
| 98 | key: `remote-session-${node.remote!.hostId}-${node.remote!.workspace}-${identity}`, |
| 99 | kind: "topic", |
| 100 | label: remoteSessionLabel(row, t), |
| 101 | root: node.remote!.workspace, |
| 102 | topicId: `${node.remote!.hostId}\u0000${node.remote!.workspace}\u0000${identity}`, |
| 103 | sessionPath: row.path, |
| 104 | turns: row.turns, |
| 105 | resultSequence: row.resultSequence, |
| 106 | turnsState: row.resultSequence === undefined ? undefined : row.metadataReady ? "ready" : "pending", |
| 107 | running: state.known ? state.unknown ? false : Boolean(state.running || session!.state.pendingPrompt || session!.state.backgroundJobs) : row.running, |
| 108 | status: status as ProjectNode["status"], |
| 109 | lastActivityAt: row.lastActivityAt, |
| 110 | pinned: row.pinned, |
| 111 | remoteSession: { hostId: node.remote!.hostId, workspace: node.remote!.workspace, name: row.name, path: row.path, sessionId: row.sessionId, title: row.title, current: row.current }, |
| 112 | children: [], |
| 113 | }); |
| 114 | }); |
| 115 | return { ...node, children: [...remoteChildren, ...(node.children ?? [])] }; |
| 116 | }); |
| 117 | } |
| 118 | |
| 119 | export function useRemoteSessionActions( |
| 120 | sessions: Record<string, RemoteSessionView[]>, |
| 121 | refresh: () => void, |
| 122 | reportError: (error: unknown) => void, |
| 123 | ) { |
| 124 | const index = useMemo(() => { |
| 125 | const next = new Map<string, { hostId: string; workspace: string; name: string; path?: string; sessionId?: string; writable: boolean }>(); |
| 126 | for (const [groupKey, rows] of Object.entries(sessions)) { |
| 127 | const [hostId, workspace] = groupKey.split("\u0000"); |
| 128 | for (const row of rows) { |
| 129 | // A canonical row is identified exactly by its sessionId; only legacy |
| 130 | // rows fall back to name identity, where duplicate names stay |
| 131 | // ambiguous and mutations must refuse rather than hit the wrong row. |
| 132 | const writable = Boolean(row.sessionId?.trim()) || rows.filter((candidate) => candidate.name === row.name).length === 1; |
| 133 | next.set(`${hostId}\u0000${workspace}\u0000${remoteSessionIdentity(row)}`, { |
| 134 | hostId, workspace, name: row.name, path: row.path, sessionId: row.sessionId, writable, |
| 135 | }); |
| 136 | } |
| 137 | } |
| 138 | return next; |
| 139 | }, [sessions]); |
| 140 | const resolve = useCallback((topicId: string) => index.get(topicId), [index]); |
| 141 | const mutate = useCallback(async ( |
| 142 | topicId: string, |
| 143 | action: (remote: { hostId: string; workspace: string; name: string; path?: string; sessionId?: string }) => Promise<unknown>, |
| 144 | ) => { |
| 145 | const remote = index.get(topicId); |
| 146 | if (!remote) return false; |
| 147 | if (!remote.writable) throw new Error("This remote service cannot identify that session precisely. Upgrade the remote Reasonix service before changing it."); |
| 148 | // The synthesized current blank session intentionally has an empty name. |
| 149 | // Its rename/pin/delete bindings still own that row and must decide whether |
| 150 | // the requested mutation is supported; never report success without |
| 151 | // invoking the backend action. |
| 152 | await action(remote); |
| 153 | refresh(); |
| 154 | return true; |
| 155 | }, [index, refresh]); |
| 156 | const remove = useCallback(async (topicId: string, local: () => Promise<unknown>) => { |
| 157 | try { |
| 158 | if (await mutate(topicId, (remote) => { |
| 159 | const identity = remoteSessionActionIdentity(remote); |
| 160 | // A blank, not-yet-catalogued session has no identity the Serve can |
| 161 | // delete; the deterministic "name required" rejection would only |
| 162 | // surface as a broken trash action. |
| 163 | if (!identity) return Promise.resolve(); |
| 164 | return app.DeleteRemoteProjectSession(remote.hostId, remote.workspace, identity); |
| 165 | })) return; |
| 166 | await local(); |
| 167 | } catch (error) { |
| 168 | reportError(error); |
| 169 | } |
| 170 | }, [mutate, reportError]); |
| 171 | return { resolve, mutate, remove }; |
| 172 | } |
| 173 | |
| 174 | export function openRemoteSessionNode( |
| 175 | remote: { hostId: string; workspace: string; name: string; path?: string; sessionId?: string; title?: string } | undefined, |
| 176 | open: (ref: RemoteTabRefView, opts?: { sessionName?: string; sessionPath?: string; sessionId?: string; sessionTitle?: string; focus?: boolean }) => Promise<void>, |
| 177 | ): boolean { |
| 178 | if (!remote) return false; |
| 179 | void open(remote, remote.name || remote.path || remote.sessionId |
| 180 | ? { sessionName: remote.name, sessionPath: remote.path, sessionId: remote.sessionId, sessionTitle: remote.title } |
| 181 | : { focus: true }); |
| 182 | return true; |
| 183 | } |
| 184 | |
| 185 | export async function renameRemoteProjectTitle(root: string, title: string): Promise<boolean> { |
| 186 | if (!root.startsWith("remote-project:")) return false; |
| 187 | const identity = root.slice("remote-project:".length); |
| 188 | const separator = identity.indexOf(":"); |
| 189 | if (separator < 1) throw new Error("invalid remote project identity"); |
| 190 | await app.SetRemoteProjectTitle(identity.slice(0, separator), identity.slice(separator + 1), title); |
| 191 | return true; |
| 192 | } |
| 193 | |
| 194 | export function useRemoteProjectGroups( |
| 195 | projects: Array<{ key?: string; remote?: RemoteTabRefView }>, |
| 196 | showToast: ToastContextValue["showToast"], |
| 197 | expanded: Set<string>, |
| 198 | query: string, |
| 199 | ) { |
| 200 | const navigateRemote = useRemoteNavigationCommand(); |
| 201 | const statuses = useRemoteStore((state) => state.statuses); |
| 202 | const servers = useRemoteStore((state) => state.servers); |
| 203 | const [sessions, setSessions] = useState<Record<string, RemoteSessionView[]>>({}); |
| 204 | const [groupBusy, setGroupBusy] = useState<Record<string, boolean>>({}); |
| 205 | const [groupError, setGroupError] = useState<Record<string, string>>({}); |
| 206 | const sessionLoads = useRef(new Map<string, number>()); |
| 207 | const sessionLoadGenerations = useRef(new Map<string, number>()); |
| 208 | const eligibleSessionKeys = useRef(new Set<string>()); |
| 209 | const groupBusyRef = useRef(new Set<string>()); |
| 210 | const nextLoad = useRef(0); |
| 211 | const opening = useRef(new Set<string>()); |
| 212 | const [revision, setRevision] = useState(0); |
| 213 | const groupKeys = useMemo( |
| 214 | () => projects.flatMap((project) => project.remote ? [remoteProjectKey(project.remote)] : []), |
| 215 | [projects], |
| 216 | ); |
| 217 | |
| 218 | const acceptRemoteSessionRows = useCallback((key: string, rows: RemoteSessionView[]) => { |
| 219 | saveRemoteSessionCache(key, rows); |
| 220 | setSessions((current) => ({ ...current, [key]: rows })); |
| 221 | // A passive refresh can recover after an explicit ensure failed. Once an |
| 222 | // authoritative listing succeeds, the old connection error no longer |
| 223 | // describes this group (including when the successful result is empty). |
| 224 | setGroupError((current) => current[key] ? { ...current, [key]: "" } : current); |
| 225 | }, []); |
| 226 | |
| 227 | const recordRemoteSessionLoadError = useCallback((key: string, error: unknown) => { |
| 228 | // Passive refreshes must not turn a transient Serve failure into an |
| 229 | // authoritative empty listing. Keep the last successful rows/cache while |
| 230 | // surfacing a retry when the group has no rows to render. |
| 231 | setGroupError((current) => ({ |
| 232 | ...current, |
| 233 | [key]: error instanceof Error ? error.message : String(error), |
| 234 | })); |
| 235 | }, []); |
| 236 | |
| 237 | const openRemoteProject = useCallback(async ( |
| 238 | ref: RemoteTabRefView, |
| 239 | opts?: { newSession?: boolean; sessionName?: string; sessionPath?: string; sessionId?: string; sessionTitle?: string; focus?: boolean }, |
| 240 | ) => { |
| 241 | const key = remoteProjectKey(ref); |
| 242 | if (opening.current.has(key)) return; |
| 243 | opening.current.add(key); |
| 244 | try { |
| 245 | const outcome = await navigateRemote(ref, |
| 246 | opts?.focus ? {} : opts?.sessionName || opts?.sessionPath || opts?.sessionId |
| 247 | ? { sessionName: opts.sessionName, sessionPath: opts.sessionPath, sessionId: opts.sessionId, sessionTitle: opts.sessionTitle } |
| 248 | : { newSession: true }); |
| 249 | if (outcome.status === "cancelled") return; |
| 250 | if (outcome.status === "failed") throw outcome.error; |
| 251 | if (!opts?.focus) setRevision((current) => current + 1); |
| 252 | } catch (error) { |
| 253 | showToast(error instanceof Error ? error.message : String(error), "error"); |
| 254 | } finally { |
| 255 | opening.current.delete(key); |
| 256 | } |
| 257 | }, [navigateRemote, showToast]); |
| 258 | |
| 259 | const ensureRemoteGroupSessions = useCallback(async (hostId: string, workspace: string) => { |
| 260 | const key = `${hostId}\u0000${workspace}`; |
| 261 | if (groupBusyRef.current.has(key)) return; |
| 262 | groupBusyRef.current.add(key); |
| 263 | setGroupBusy((current) => ({ ...current, [key]: true })); |
| 264 | setGroupError((current) => ({ ...current, [key]: "" })); |
| 265 | // Explicit ensures and passive listings share one last-start-wins order. |
| 266 | // In particular, a passive request that began before this cold start must |
| 267 | // not be allowed to overwrite the authoritative rows returned here. |
| 268 | const load = ++nextLoad.current; |
| 269 | sessionLoads.current.set(key, load); |
| 270 | sessionLoadGenerations.current.set(key, load); |
| 271 | try { |
| 272 | const rows = await app.EnsureRemoteProjectSessions(hostId, workspace); |
| 273 | if (sessionLoadGenerations.current.get(key) !== load) return; |
| 274 | acceptRemoteSessionRows(key, rows); |
| 275 | void app.RemoteServerStatus(hostId, workspace).then((view) => useRemoteStore.getState().setServer(view)).catch(() => {}); |
| 276 | } catch (error) { |
| 277 | if (sessionLoadGenerations.current.get(key) !== load) return; |
| 278 | recordRemoteSessionLoadError(key, error); |
| 279 | } finally { |
| 280 | if (sessionLoads.current.get(key) === load) sessionLoads.current.delete(key); |
| 281 | groupBusyRef.current.delete(key); |
| 282 | setGroupBusy((current) => ({ ...current, [key]: false })); |
| 283 | } |
| 284 | }, [acceptRemoteSessionRows, recordRemoteSessionLoadError]); |
| 285 | |
| 286 | const openRemoteWindow = useCallback(async (ref: RemoteTabRefView) => { |
| 287 | try { |
| 288 | const state = statuses[ref.hostId]?.state; |
| 289 | if (state !== "connected" && state !== "degraded") { |
| 290 | await app.ConnectRemoteHost(ref.hostId); |
| 291 | await waitForRemoteConnection(ref.hostId); |
| 292 | } |
| 293 | await publishNavigationIntent("remote-workspace"); |
| 294 | await app.OpenRemoteWorkspace(ref.hostId, ref.workspace); |
| 295 | } catch (error) { |
| 296 | showToast(error instanceof Error ? error.message : String(error), "error"); |
| 297 | } |
| 298 | }, [showToast, statuses]); |
| 299 | |
| 300 | useEffect(() => onRemoteTabOpened(() => setRevision((current) => current + 1)), []); |
| 301 | |
| 302 | const refreshRemoteGroup = useCallback((meta: { remote: RemoteTabRefView }) => { |
| 303 | const key = remoteProjectKey(meta.remote); |
| 304 | if (!groupKeys.includes(key) || !eligibleSessionKeys.current.has(key)) return; |
| 305 | const load = ++nextLoad.current; |
| 306 | sessionLoads.current.set(key, load); |
| 307 | sessionLoadGenerations.current.set(key, load); |
| 308 | void app.RemoteProjectSessions(meta.remote.hostId, meta.remote.workspace) |
| 309 | .then((rows) => { |
| 310 | if (sessionLoadGenerations.current.get(key) === load && eligibleSessionKeys.current.has(key)) { |
| 311 | acceptRemoteSessionRows(key, rows); |
| 312 | } |
| 313 | }) |
| 314 | .catch((error) => { |
| 315 | if (sessionLoadGenerations.current.get(key) === load && eligibleSessionKeys.current.has(key)) { |
| 316 | recordRemoteSessionLoadError(key, error); |
| 317 | } |
| 318 | }) |
| 319 | .finally(() => { |
| 320 | if (sessionLoads.current.get(key) === load) sessionLoads.current.delete(key); |
| 321 | }); |
| 322 | }, [acceptRemoteSessionRows, groupKeys, recordRemoteSessionLoadError]); |
| 323 | |
| 324 | useEffect(() => onRemoteTabUpdated((meta) => { |
| 325 | if (!meta.remote) return; |
| 326 | // V1 runtimes invalidate their own session below, independently of the |
| 327 | // tab's foreground running flag. Older services retain metadata refreshes. |
| 328 | if (runtimeStateStore.getSnapshot()?.sessions.some(session => session.tabId === meta.id && session.state.schemaVersion === 1)) return; |
| 329 | refreshRemoteGroup({ remote: meta.remote }); |
| 330 | }), [refreshRemoteGroup]); |
| 331 | |
| 332 | useEffect(() => { |
| 333 | let previous = runtimeStateStore.getSnapshot(); |
| 334 | let disposed = false; |
| 335 | let queued = false; |
| 336 | const pending = new Map<string, RemoteTabRefView>(); |
| 337 | const index = (snapshot: RuntimeProjection | undefined) => new Map(snapshot?.sessions |
| 338 | .filter(session => session.remote && session.hostId && session.state.schemaVersion === 1) |
| 339 | .map(session => [`${session.hostId}\0${session.workspaceRoot}\0${session.sessionId || session.sessionPath}`, session])); |
| 340 | const off = runtimeStateStore.subscribe(() => { |
| 341 | const next = runtimeStateStore.getSnapshot(); |
| 342 | if (next === previous || runtimeStateStore.getFailed()) return; |
| 343 | const before = index(previous), after = index(next); |
| 344 | previous = next; |
| 345 | const invalidate = (session: NonNullable<RuntimeProjection>["sessions"][number]) => { |
| 346 | const ref = { hostId: session.hostId!, workspace: session.workspaceRoot }; |
| 347 | pending.set(remoteProjectKey(ref), ref); |
| 348 | }; |
| 349 | for (const [key, session] of after) { |
| 350 | const old = before.get(key); |
| 351 | if (selectRuntime(session).kind === "idle" && (!old || selectRuntime(old).kind !== "idle" |
| 352 | || old.state.runtimeEpoch !== session.state.runtimeEpoch |
| 353 | || old.state.turnEventSeq !== session.state.turnEventSeq |
| 354 | || old.state.durableEventSeq !== session.state.durableEventSeq)) invalidate(session); |
| 355 | } |
| 356 | // A detached runtime can retire before its terminal SSE arrives. Its |
| 357 | // catalog result remains authoritative after the runtime disappears. |
| 358 | for (const [key, session] of before) if (!after.has(key)) invalidate(session); |
| 359 | if (pending.size === 0 || queued) return; |
| 360 | queued = true; |
| 361 | queueMicrotask(() => { |
| 362 | queued = false; |
| 363 | if (disposed) return; |
| 364 | for (const remote of pending.values()) refreshRemoteGroup({ remote }); |
| 365 | pending.clear(); |
| 366 | }); |
| 367 | }); |
| 368 | return () => { disposed = true; off(); }; |
| 369 | }, [refreshRemoteGroup]); |
| 370 | |
| 371 | // A cold catalog may need a rebuild after the terminal event. Retry that |
| 372 | // metadata briefly without turning an incomplete zero into a read baseline. |
| 373 | const metadataRetries = useRef(new Map<string, number>()); |
| 374 | useEffect(() => { |
| 375 | const timers: ReturnType<typeof setTimeout>[] = []; |
| 376 | for (const [key, rows] of Object.entries(sessions)) { |
| 377 | if (!rows.some(row => row.resultSequence !== undefined && !row.metadataReady)) { |
| 378 | metadataRetries.current.delete(key); |
| 379 | continue; |
| 380 | } |
| 381 | if (!eligibleSessionKeys.current.has(key) || (metadataRetries.current.get(key) ?? 0) >= 5) continue; |
| 382 | timers.push(setTimeout(() => { |
| 383 | metadataRetries.current.set(key, (metadataRetries.current.get(key) ?? 0) + 1); |
| 384 | const [hostId, workspace] = key.split("\0"); |
| 385 | refreshRemoteGroup({ remote: { hostId, workspace } }); |
| 386 | }, 1000)); |
| 387 | } |
| 388 | return () => timers.forEach(clearTimeout); |
| 389 | }, [sessions, refreshRemoteGroup]); |
| 390 | |
| 391 | useEffect(() => { |
| 392 | const seeded: Record<string, RemoteSessionView[]> = {}; |
| 393 | for (const key of groupKeys) { |
| 394 | const rows = loadRemoteSessionCache(key); |
| 395 | if (rows.length > 0) seeded[key] = rows; |
| 396 | } |
| 397 | if (Object.keys(seeded).length > 0) { |
| 398 | setSessions((current) => ({ ...seeded, ...current })); |
| 399 | } |
| 400 | }, [groupKeys]); |
| 401 | |
| 402 | useEffect(() => { |
| 403 | void app.RemoteConnectionStatuses() |
| 404 | .then((rows) => useRemoteStore.getState().hydrateStatuses(rows ?? [])) |
| 405 | .catch(() => {}); |
| 406 | }, []); |
| 407 | |
| 408 | useEffect(() => { |
| 409 | for (const key of groupKeys) { |
| 410 | const [hostId, workspace] = key.split("\u0000"); |
| 411 | void app.RemoteServerStatus(hostId, workspace) |
| 412 | .then((view) => useRemoteStore.getState().setServer(view)) |
| 413 | .catch(() => {}); |
| 414 | } |
| 415 | }, [groupKeys]); |
| 416 | |
| 417 | useEffect(() => { |
| 418 | const searchable = query.trim() !== ""; |
| 419 | const eligible = new Set(groupKeys.filter((key) => { |
| 420 | const state = statuses[key.split("\u0000")[0]]?.state; |
| 421 | if (state !== "connected" && state !== "degraded") return false; |
| 422 | const project = projects.find((item) => item.remote && remoteProjectKey(item.remote) === key); |
| 423 | return searchable || Boolean(project?.key && expanded.has(project.key)); |
| 424 | })); |
| 425 | eligibleSessionKeys.current = eligible; |
| 426 | for (const key of sessionLoads.current.keys()) { |
| 427 | if (!eligible.has(key)) sessionLoads.current.delete(key); |
| 428 | } |
| 429 | const retained = new Set(groupKeys); |
| 430 | for (const key of sessionLoadGenerations.current.keys()) { |
| 431 | if (!retained.has(key)) sessionLoadGenerations.current.delete(key); |
| 432 | } |
| 433 | setSessions((current) => { |
| 434 | if (Object.keys(current).every((key) => retained.has(key))) return current; |
| 435 | const next = Object.fromEntries(Object.entries(current).filter(([key]) => retained.has(key))); |
| 436 | return next; |
| 437 | }); |
| 438 | for (const key of eligible) { |
| 439 | if (sessionLoads.current.has(key)) continue; |
| 440 | const [hostId, workspace] = key.split("\u0000"); |
| 441 | const load = ++nextLoad.current; |
| 442 | sessionLoads.current.set(key, load); |
| 443 | sessionLoadGenerations.current.set(key, load); |
| 444 | void app.RemoteProjectSessions(hostId, workspace) |
| 445 | .then((rows) => { |
| 446 | if (sessionLoadGenerations.current.get(key) === load && eligibleSessionKeys.current.has(key)) { |
| 447 | acceptRemoteSessionRows(key, rows); |
| 448 | } |
| 449 | }) |
| 450 | .catch((error) => { |
| 451 | if (sessionLoadGenerations.current.get(key) === load && eligibleSessionKeys.current.has(key)) { |
| 452 | recordRemoteSessionLoadError(key, error); |
| 453 | } |
| 454 | }) |
| 455 | .finally(() => { |
| 456 | if (sessionLoads.current.get(key) === load) sessionLoads.current.delete(key); |
| 457 | }); |
| 458 | } |
| 459 | }, [acceptRemoteSessionRows, expanded, groupKeys, projects, query, recordRemoteSessionLoadError, revision, statuses]); |
| 460 | |
| 461 | return { |
| 462 | openRemoteProject, |
| 463 | openRemoteWindow, |
| 464 | remoteSessions: sessions, |
| 465 | remoteGroupBusy: groupBusy, |
| 466 | remoteGroupError: groupError, |
| 467 | ensureRemoteGroupSessions, |
| 468 | setRemoteSessions: setSessions, |
| 469 | remoteServers: servers, |
| 470 | refreshRemoteSessions: () => setRevision((current) => current + 1), |
| 471 | }; |
| 472 | } |
| 473 | |
| 474 | export function RemoteProjectEmptyState({ |
| 475 | busy, error, ready, isExpanded, depth, t, onEnsure, |
| 476 | }: { |
| 477 | busy: boolean; |
| 478 | error: string; |
| 479 | ready: boolean; |
| 480 | isExpanded: boolean; |
| 481 | depth: number; |
| 482 | t: Translator; |
| 483 | onEnsure: () => void; |
| 484 | }) { |
| 485 | const inner = busy ? ( |
| 486 | <div className="project-tree__skeleton" style={{ paddingLeft: 14 + (depth + 1) * 16 }} aria-hidden="true"> |
| 487 | <span className="project-tree__skeleton-bar" /> |
| 488 | <span className="project-tree__skeleton-bar project-tree__skeleton-bar--short" /> |
| 489 | <span className="project-tree__skeleton-bar" /> |
| 490 | <span className="project-tree__skeleton-bar project-tree__skeleton-bar--short" /> |
| 491 | </div> |
| 492 | ) : error || !ready ? ( |
| 493 | <button |
| 494 | type="button" |
| 495 | className={`project-tree__remote-status${error ? " project-tree__remote-status--error" : ""}`} |
| 496 | style={{ paddingLeft: 14 + (depth + 1) * 16 }} |
| 497 | onClick={onEnsure} |
| 498 | > |
| 499 | {error ? t("projectTree.remoteConnectFailed") : t("projectTree.remoteConnect")} |
| 500 | </button> |
| 501 | ) : null; |
| 502 | if (!inner) return null; |
| 503 | return ( |
| 504 | <div className={`project-tree__children${isExpanded ? " project-tree__children--expanded" : ""}`}> |
| 505 | <div className="project-tree__children-inner">{inner}</div> |
| 506 | </div> |
| 507 | ); |
| 508 | } |
| 509 | |
| 510 | interface RemoteMenuOptions { |
| 511 | ref: RemoteTabRefView; |
| 512 | t: Translator; |
| 513 | closeMenu: () => void; |
| 514 | openRemoteProject: (ref: RemoteTabRefView, opts?: { newSession?: boolean; sessionName?: string; sessionPath?: string; sessionId?: string; sessionTitle?: string; focus?: boolean }) => Promise<void>; |
| 515 | openRemoteWindow: (ref: RemoteTabRefView) => Promise<void>; |
| 516 | setRemoteSessions: Dispatch<SetStateAction<Record<string, RemoteSessionView[]>>>; |
| 517 | refresh: () => Promise<void>; |
| 518 | showToast: ToastContextValue["showToast"]; |
| 519 | } |
| 520 | |
| 521 | export function buildRemoteProjectMenuItems(options: RemoteMenuOptions): ContextMenuItem[] { |
| 522 | const { ref, t, closeMenu, openRemoteProject, openRemoteWindow, setRemoteSessions, refresh, showToast } = options; |
| 523 | const report = (error: unknown) => showToast(error instanceof Error ? error.message : String(error), "error"); |
| 524 | return [ |
| 525 | { |
| 526 | key: "remote-new-session", icon: <Plus size={13} />, label: t("projectTree.newTopic"), |
| 527 | onSelect: () => { closeMenu(); void openRemoteProject(ref, { newSession: true }); }, |
| 528 | }, |
| 529 | { |
| 530 | key: "remote-open-window", icon: <Server size={13} />, label: t("projectTree.remoteOpenWindow"), |
| 531 | onSelect: () => { closeMenu(); void openRemoteWindow(ref); }, |
| 532 | }, |
| 533 | { |
| 534 | key: "remote-stop-server", icon: <Square size={13} />, label: t("projectTree.remoteStopServer"), |
| 535 | onSelect: () => { closeMenu(); void app.StopRemoteServer(ref.hostId, ref.workspace).catch(report); }, |
| 536 | }, |
| 537 | { |
| 538 | key: "remote-unpin", icon: <XCircle size={13} />, label: t("projectTree.remoteUnpin"), |
| 539 | onSelect: () => { |
| 540 | closeMenu(); |
| 541 | void app.RemoveRemoteProject(ref.hostId, ref.workspace).then(() => { |
| 542 | removeRemoteSessionCache(remoteProjectKey(ref)); |
| 543 | setRemoteSessions((current) => { |
| 544 | const next = { ...current }; |
| 545 | delete next[remoteProjectKey(ref)]; |
| 546 | return next; |
| 547 | }); |
| 548 | void refresh(); |
| 549 | }).catch(report); |
| 550 | }, |
| 551 | }, |
| 552 | ]; |
| 553 | } |
| 554 |