refactor(site/src/pages/AgentsPage): move the desktop connection into a class (#32695)

This commit is contained in:
Danielle Maywood authored and GitHub committed 2026-12-01 11:14:31 +00:00
1 parent 820ba68826
commit 429dae8936
6 files changed
+558 -527

No files matched your search

@@ -27,7 +27,6 @@ import { useZoomShortcuts } from "../hooks/useZoomShortcuts";
export default function DesktopPopoutPage() {
const { agentId } = useParams() as { agentId: string };
const [scaleMode, setScaleMode] = useState<ScaleMode>("fit");
const [isControlling, setIsControlling] = useState(false);
// The pop-out renders outside the chat page, so it resolves the
@@ -48,13 +47,19 @@ export default function DesktopPopoutPage() {
// Same gating as DesktopPanel: dial only while the agent is connected
// so a stopped workspace tears the session down and a restarted one
// reconnects on its own.
const { status, reconnect, attach } = useDesktopConnection({
chatId: agentId,
activated:
workspace !== undefined &&
isDesktopReachable(workspace.latest_build.status, workspaceAgent?.status),
scaleViewport: scaleMode === "fit",
});
const { status, reconnect, attach, scaleViewport, setScaleViewport } =
useDesktopConnection({
chatId: agentId,
activated:
workspace !== undefined &&
isDesktopReachable(
workspace.latest_build.status,
workspaceAgent?.status,
),
initialScaleViewport: true,
});
const scaleMode: ScaleMode = scaleViewport ? "fit" : "native";
const setScaleMode = (mode: ScaleMode) => setScaleViewport(mode === "fit");
// BroadcastChannel for parent window communication.
useEffect(() => {
@@ -22,10 +22,10 @@ export const Idle: Story = {
connectionOverride: {
status: "idle",
hasConnected: false,
scaleViewport: false,
setScaleViewport: fn(),
reconnect: fn(),
attach: fn(),
rfb: null,
remoteClipboardText: null,
},
},
};
@@ -43,10 +43,10 @@ export const Connected: Story = {
connectionOverride: {
status: "connected",
hasConnected: true,
scaleViewport: false,
setScaleViewport: fn(),
reconnect: fn(),
attach: fn(),
rfb: null,
remoteClipboardText: null,
},
},
};
@@ -60,10 +60,10 @@ export const Disconnected: Story = {
connectionOverride: {
status: "disconnected",
hasConnected: true,
scaleViewport: false,
setScaleViewport: fn(),
reconnect: fn(),
attach: fn(),
rfb: null,
remoteClipboardText: null,
},
},
};
@@ -77,10 +77,10 @@ export const ErrorState: Story = {
connectionOverride: {
status: "error",
hasConnected: false,
scaleViewport: false,
setScaleViewport: fn(),
reconnect: fn(),
attach: fn(),
rfb: null,
remoteClipboardText: null,
},
},
};
@@ -51,20 +51,25 @@ export const DesktopPanel: React.FC<DesktopPanelProps> = ({
setIsControlling(false);
}
const [scaleMode, setScaleMode] = useState<ScaleMode>("fit");
const [isPoppedOut, setIsPoppedOut] = useState(false);
// Gating the connection on the live workspace watch tears the session
// down when the workspace stops and dials again as soon as the agent
// reconnects, without manual retries.
const { status, reconnect, attach } = useDesktopConnection({
chatId: isPoppedOut ? undefined : chatId,
activated:
activated &&
!isPoppedOut &&
isDesktopReachable(workspace.latest_build.status, workspaceAgent?.status),
scaleViewport: scaleMode === "fit",
});
const { status, reconnect, attach, scaleViewport, setScaleViewport } =
useDesktopConnection({
chatId: isPoppedOut ? undefined : chatId,
activated:
activated &&
!isPoppedOut &&
isDesktopReachable(
workspace.latest_build.status,
workspaceAgent?.status,
),
initialScaleViewport: true,
});
const scaleMode: ScaleMode = scaleViewport ? "fit" : "native";
const setScaleMode = (mode: ScaleMode) => setScaleViewport(mode === "fit");
useZoomShortcuts(setScaleMode, isActive);
@@ -124,7 +124,6 @@ describe("useDesktopConnection", () => {
expect(result.current.status).toBe("idle");
expect(result.current.hasConnected).toBe(false);
expect(result.current.rfb).toBeNull();
expect(mockWatchChatDesktop).not.toHaveBeenCalled();
});
@@ -148,7 +147,7 @@ describe("useDesktopConnection", () => {
useDesktopConnection({
chatId: "chat-1",
activated: true,
scaleViewport: true,
initialScaleViewport: true,
}),
);
const rfb = getLastRFBInstance();
@@ -158,22 +157,20 @@ describe("useDesktopConnection", () => {
});
it("syncs scaleViewport changes to the RFB instance", () => {
const { rerender } = renderHook(
({ scaleViewport }) =>
useDesktopConnection({
chatId: "chat-1",
activated: true,
scaleViewport,
}),
{ initialProps: { scaleViewport: true } },
const { result } = renderHook(() =>
useDesktopConnection({
chatId: "chat-1",
activated: true,
initialScaleViewport: true,
}),
);
const rfb = getLastRFBInstance();
expect(rfb.scaleViewport).toBe(true);
rerender({ scaleViewport: false });
act(() => result.current.setScaleViewport(false));
expect(rfb.scaleViewport).toBe(false);
rerender({ scaleViewport: true });
act(() => result.current.setScaleViewport(true));
expect(rfb.scaleViewport).toBe(true);
});
@@ -398,8 +395,8 @@ describe("useDesktopConnection", () => {
expect(mockWatchChatDesktop).toHaveBeenCalledTimes(1);
});
it("stores remote clipboard text when the server sends it", async () => {
const { result } = renderHook(() =>
it("copies remote clipboard text to the local clipboard", async () => {
renderHook(() =>
useDesktopConnection({ chatId: "chat-1", activated: true }),
);
@@ -407,7 +404,6 @@ describe("useDesktopConnection", () => {
act(() => rfb.simulateEvent("connect"));
act(() => rfb.simulateEvent("clipboard", { text: "from remote" }));
expect(result.current.remoteClipboardText).toBe("from remote");
await vi.waitFor(() => {
expect(mockClipboardWriteText).toHaveBeenCalledWith("from remote");
});
@@ -740,12 +736,14 @@ describe("useDesktopConnection", () => {
act(() => rfb.simulateEvent("disconnect", { clean: false }));
expect(result.current.status).toBe("error");
// User clicks Reconnect.
// User switches to fit mode, then clicks Reconnect.
act(() => result.current.setScaleViewport(true));
mockWatchChatDesktop.mockClear();
act(() => result.current.reconnect());
expect(mockWatchChatDesktop).toHaveBeenCalledWith("chat-1");
expect(result.current.status).toBe("connecting");
expect(getLastRFBInstance().scaleViewport).toBe(true);
} finally {
vi.useRealTimers();
}
@@ -892,7 +890,7 @@ describe("useDesktopConnection", () => {
useDesktopConnection({
chatId: "chat-1",
activated: true,
scaleViewport: true,
initialScaleViewport: true,
}),
);
const rfb = getLastRFBInstance();
@@ -1,21 +1,19 @@
import RFB from "@novnc/novnc/lib/rfb";
import { useEffect, useRef, useState } from "react";
import { watchChatDesktop } from "#/api/api";
import { useEffect, useState, useSyncExternalStore } from "react";
import { toast } from "#/components/Toaster/toast";
import { useClipboard } from "#/hooks/useClipboard";
export type DesktopConnectionStatus =
| "idle"
| "connecting"
| "connected"
| "disconnected"
| "error";
import {
DesktopConnection,
type DesktopConnectionStatus,
} from "../utils/desktopConnection";
export type { DesktopConnectionStatus } from "../utils/desktopConnection";
type UseDesktopConnectionOptions = {
chatId: string | undefined;
/** When false the hook stays dormant, no WebSocket, no RFB. */
activated: boolean;
/** When true the viewport is scaled to fit the container. Default: false (native 100%). */
scaleViewport?: boolean;
/** Whether the viewport starts scaled to fit the container. Default: false (native 100%). */
initialScaleViewport?: boolean;
};
export type UseDesktopConnectionResult = {
@@ -23,6 +21,10 @@ export type UseDesktopConnectionResult = {
status: DesktopConnectionStatus;
/** Whether the connection has ever been established. */
hasConnected: boolean;
/** Whether the viewport is scaled to fit the container. */
scaleViewport: boolean;
/** Scales the viewport to fit the container, or shows it at 100%. */
setScaleViewport: (scaleViewport: boolean) => void;
/**
* Tear down the current connection and start a fresh one.
* Used by the "Reconnect" button after an error.
@@ -35,92 +37,20 @@ export type UseDesktopConnectionResult = {
* without reconnecting.
*/
attach: (container: HTMLElement) => void;
/** Latest text received from the remote desktop clipboard. */
remoteClipboardText: string | null;
/** The underlying RFB instance, if connected. */
rfb: RFB | null;
};
const MAX_BACKOFF_MS = 30_000;
const MAX_RECONNECT_ATTEMPTS = 10;
const STABLE_CONNECTION_MS = 3_000;
const CONNECT_TIMEOUT_MS = 30_000;
// X11 keysym values sent to the remote desktop via the RFB
// protocol. Full list: https://www.cl.cam.ac.uk/~mgk25/ucs/keysymdef.h
const XK_Control_L = 0xffe3; // Left Control modifier.
const XK_Control_R = 0xffe4; // Right Control modifier.
const XK_Meta_L = 0xffeb; // Left Meta (Cmd on macOS) modifier.
const XK_Meta_R = 0xffec; // Right Meta modifier.
const XK_c = 0x0063; // Latin lowercase 'c'.
const XK_v = 0x0076; // Latin lowercase 'v'.
const XK_x = 0x0078; // Latin lowercase 'x'.
const XK_Shift_L = 0xffe1; // Left Shift modifier.
const XK_Shift_R = 0xffe2; // Right Shift modifier.
const isPasteShortcut = (event: KeyboardEvent): boolean => {
const key = event.key.toLowerCase();
return (
(key === "v" && (event.ctrlKey || event.metaKey) && !event.altKey) ||
(key === "insert" && event.shiftKey && !event.ctrlKey && !event.metaKey)
);
};
// Detect Cmd+C on macOS so we can remap it to Ctrl+C on the
// remote desktop. Plain Ctrl+C already travels through noVNC
// correctly, so we only need to intercept the Meta variant.
const isMacCopyShortcut = (event: KeyboardEvent): boolean => {
const key = event.key.toLowerCase();
return key === "c" && event.metaKey && !event.ctrlKey && !event.altKey;
};
// Detect Cmd+X on macOS — same remapping rationale as copy.
const isMacCutShortcut = (event: KeyboardEvent): boolean => {
const key = event.key.toLowerCase();
return key === "x" && event.metaKey && !event.ctrlKey && !event.altKey;
};
export function useDesktopConnection({
chatId,
activated,
scaleViewport = false,
initialScaleViewport = false,
}: UseDesktopConnectionOptions): UseDesktopConnectionResult {
const [status, setStatus] = useState<DesktopConnectionStatus>("idle");
const [hasConnected, setHasConnected] = useState(false);
const [remoteClipboardText, setRemoteClipboardText] = useState<string | null>(
null,
const [connection] = useState(
() => new DesktopConnection(initialScaleViewport),
);
// rfbRef provides synchronous access for cleanup and event
// handlers. rfbInstance (state) provides reactivity so consumers
// re-render when the RFB instance changes.
const [rfbInstance, setRfbInstance] = useState<RFB | null>(null);
const rfbRef = useRef<RFB | null>(null);
const offscreenContainerRef = useRef<HTMLElement | null>(null);
const reconnectAttemptRef = useRef(0);
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const reconnectStableTimerRef = useRef<ReturnType<typeof setTimeout> | null>(
null,
const { status, hasConnected, scaleViewport } = useSyncExternalStore(
connection.subscribe,
connection.getSnapshot,
);
const connectTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Monotonically increasing counter. Incremented at the start of
// every doConnect() and inside the cleanup. Event handlers
// capture the current value and bail when it no longer matches,
// which prevents async noVNC callbacks from a previous session
// (e.g. a phantom "disconnect" event fired after cleanupRfb)
// from scheduling unwanted reconnect timers.
const generationRef = useRef(0);
// Populated by the lifecycle effect so reconnect() can tear
// down and restart the connection from outside the effect.
// Cleared on cleanup so calls after unmount are no-ops.
const restartRef = useRef<(() => void) | null>(null);
const reconnect = () => {
restartRef.current?.();
};
const { copyToClipboard: syncRemoteClipboardToLocal } = useClipboard({
onError: () => {
toast.error(
@@ -129,408 +59,21 @@ export function useDesktopConnection({
},
});
const attach = (container: HTMLElement) => {
const screen = offscreenContainerRef.current;
if (screen && screen.parentElement !== container) {
container.appendChild(screen);
}
};
// Single lifecycle effect that owns the entire connection.
// Connects on mount, tears down on unmount, and resets when
// chatId changes.
//
// All connection logic (doConnect, cleanupRfb, timer helpers)
// is defined inside the effect so the dependency array only
// contains primitives. This avoids any reliance on the React
// Compiler for function identity stability.
useEffect(() => {
let visibilityObserver: ResizeObserver | null = null;
setRemoteClipboardText(null);
let clipboardKeyListener: ((event: KeyboardEvent) => void) | null = null;
let clipboardKeyUpListener: ((event: KeyboardEvent) => void) | null = null;
const removeClipboardKeyListener = () => {
const screen = offscreenContainerRef.current;
if (screen && clipboardKeyListener) {
screen.removeEventListener("keydown", clipboardKeyListener, true);
clipboardKeyListener = null;
}
if (screen && clipboardKeyUpListener) {
screen.removeEventListener("keyup", clipboardKeyUpListener, true);
clipboardKeyUpListener = null;
}
};
const cleanupRfb = () => {
removeClipboardKeyListener();
if (rfbRef.current) {
try {
rfbRef.current.disconnect();
} catch {
// Ignore errors during disconnect.
}
rfbRef.current = null;
setRfbInstance(null);
}
};
const clearAllTimers = () => {
if (reconnectTimerRef.current !== null) {
clearTimeout(reconnectTimerRef.current);
reconnectTimerRef.current = null;
}
if (reconnectStableTimerRef.current !== null) {
clearTimeout(reconnectStableTimerRef.current);
reconnectStableTimerRef.current = null;
}
if (connectTimeoutRef.current !== null) {
clearTimeout(connectTimeoutRef.current);
connectTimeoutRef.current = null;
}
};
const teardown = () => {
generationRef.current++;
clearAllTimers();
cleanupRfb();
if (offscreenContainerRef.current?.parentElement) {
offscreenContainerRef.current.remove();
}
offscreenContainerRef.current = null;
reconnectAttemptRef.current = 0;
visibilityObserver?.disconnect();
visibilityObserver = null;
};
const doConnect = () => {
if (!chatId) {
return;
}
// Bump the generation so any in-flight async callbacks
// from the previous RFB session become stale.
generationRef.current++;
const gen = generationRef.current;
clearAllTimers();
cleanupRfb();
visibilityObserver?.disconnect();
visibilityObserver = null;
setStatus("connecting");
// Remove the previous offscreen container from the DOM
// so reconnect cycles don't leak detached divs.
if (offscreenContainerRef.current?.parentElement) {
offscreenContainerRef.current.remove();
}
// Temporary offscreen container for the RFB canvas;
// moved into the visible panel by `attach()`.
offscreenContainerRef.current = document.createElement("div");
offscreenContainerRef.current.style.width = "100%";
offscreenContainerRef.current.style.height = "100%";
offscreenContainerRef.current.style.position = "relative";
offscreenContainerRef.current.style.overflow = "hidden";
const socket = watchChatDesktop(chatId);
try {
const rfb = new RFB(offscreenContainerRef.current, socket, {
shared: true,
});
rfb.scaleViewport = false;
rfb.resizeSession = false;
rfb.focusOnClick = true;
// Override the noVNC default background (rgb(40,40,40))
// so the letterbox margins match the app surface color
// in both light and dark themes.
const surfaceHsl = getComputedStyle(document.documentElement)
.getPropertyValue("--surface-secondary")
.trim();
if (surfaceHsl) {
rfb.background = `hsl(${surfaceHsl})`;
}
// Per-session flags scoped to this RFB instance.
// NOT refs — each doConnect() gets fresh copies so
// state from a previous session cannot leak.
let sessionConnected = false;
let securityFailed = false;
rfb.addEventListener("clipboard", (event) => {
const text = event.detail.text ?? "";
if (gen !== generationRef.current || !sessionConnected) {
return;
}
setRemoteClipboardText(text);
syncRemoteClipboardToLocal(text).catch((err) => {
console.error("Failed to sync remote clipboard to local:", err);
});
});
// Capture-phase keydown on the container fires before
// noVNC's own handlers on the canvas. This lets us
// intercept clipboard shortcuts before noVNC swallows
// them without any hidden-textarea focus tricks.
// Track which keys were intercepted on keydown so
// the corresponding keyup events can be suppressed.
const interceptedKeys = new Set<string>();
clipboardKeyListener = (event) => {
if (gen !== generationRef.current) {
return;
}
if (!sessionConnected) {
return;
}
// Remap Cmd+C / Cmd+X on macOS to Ctrl+C / Ctrl+X
// on the remote desktop. Release the stale Meta
// modifier first because its keydown already reached
// the remote before we could intercept it.
if (isMacCopyShortcut(event) || isMacCutShortcut(event)) {
const targetKeysym = isMacCopyShortcut(event) ? XK_c : XK_x;
const keyName = isMacCopyShortcut(event) ? "KeyC" : "KeyX";
event.preventDefault();
event.stopPropagation();
interceptedKeys.add(event.code);
rfb.sendKey(XK_Meta_L, "MetaLeft", false);
rfb.sendKey(XK_Meta_R, "MetaRight", false);
rfb.sendKey(XK_Control_L, "ControlLeft", true);
rfb.sendKey(targetKeysym, keyName, true);
rfb.sendKey(targetKeysym, keyName, false);
rfb.sendKey(XK_Control_L, "ControlLeft", false);
return;
}
if (!isPasteShortcut(event)) {
return;
}
event.preventDefault();
event.stopPropagation();
interceptedKeys.add(event.code);
const doPaste = async () => {
// Check clipboard permission state before
// attempting readText(). This lets us show a
// clear message when permission is denied
// instead of silently hanging.
try {
const permStatus = await navigator.permissions.query({
name: "clipboard-read" as PermissionName,
});
if (permStatus.state === "denied") {
toast.error(
"Clipboard permission denied. Allow clipboard access in your browser settings to paste.",
);
return;
}
} catch {
// permissions.query may not support
// clipboard-read in all browsers.
// Continue with readText anyway.
}
const text = await navigator.clipboard.readText();
if (!text) {
return;
}
if (gen !== generationRef.current) {
return;
}
rfb.clipboardPasteFrom(text);
rfb.sendKey(XK_Shift_L, "ShiftLeft", false);
rfb.sendKey(XK_Shift_R, "ShiftRight", false);
rfb.sendKey(XK_Meta_L, "MetaLeft", false);
rfb.sendKey(XK_Meta_R, "MetaRight", false);
rfb.sendKey(XK_Control_L, "ControlLeft", false);
rfb.sendKey(XK_Control_R, "ControlRight", false);
rfb.sendKey(XK_Control_L, "ControlLeft", true);
rfb.sendKey(XK_v, "KeyV", true);
rfb.sendKey(XK_v, "KeyV", false);
rfb.sendKey(XK_Control_L, "ControlLeft", false);
};
doPaste().catch((err) => {
console.error("Paste into remote desktop failed:", err);
});
};
clipboardKeyUpListener = (event) => {
if (interceptedKeys.has(event.code)) {
interceptedKeys.delete(event.code);
event.preventDefault();
event.stopPropagation();
}
};
offscreenContainerRef.current.addEventListener(
"keydown",
clipboardKeyListener,
true,
);
offscreenContainerRef.current.addEventListener(
"keyup",
clipboardKeyUpListener,
true,
);
// Fail if the VNC handshake doesn't complete within
// a reasonable window. Bump the generation before
// cleanupRfb() so the resulting noVNC "disconnect"
// event is treated as stale and doesn't redundantly
// set status to "error".
connectTimeoutRef.current = setTimeout(() => {
if (gen !== generationRef.current) return;
if (!sessionConnected) {
generationRef.current++;
cleanupRfb();
setStatus("error");
}
}, CONNECT_TIMEOUT_MS);
rfb.addEventListener("connect", () => {
if (gen !== generationRef.current) return;
sessionConnected = true;
if (connectTimeoutRef.current !== null) {
clearTimeout(connectTimeoutRef.current);
connectTimeoutRef.current = null;
}
setStatus("connected");
setHasConnected(true);
// Only reset the reconnect counter after the
// connection has been stable for a minimum
// duration. This prevents infinite reconnect
// loops when the VNC handshake succeeds but the
// connection drops immediately.
// No gen check needed — clearAllTimers()
// always cancels this before a new session.
reconnectStableTimerRef.current = setTimeout(() => {
reconnectAttemptRef.current = 0;
}, STABLE_CONNECTION_MS);
});
rfb.addEventListener("disconnect", () => {
if (gen !== generationRef.current) return;
if (reconnectStableTimerRef.current !== null) {
clearTimeout(reconnectStableTimerRef.current);
reconnectStableTimerRef.current = null;
}
if (connectTimeoutRef.current !== null) {
clearTimeout(connectTimeoutRef.current);
connectTimeoutRef.current = null;
}
rfbRef.current = null;
setRfbInstance(null);
// Security failures are terminal — the
// securityfailure handler already moved to
// "error". noVNC fires disconnect after
// securityfailure; ignore it so we don't
// accidentally schedule a retry.
if (securityFailed) {
return;
}
// Only retry if THIS session's VNC handshake
// completed. A previous session having connected
// is irrelevant — the desktop may have become
// permanently unavailable.
if (!sessionConnected) {
setStatus("error");
return;
}
const attempt = reconnectAttemptRef.current;
if (attempt >= MAX_RECONNECT_ATTEMPTS) {
setStatus("error");
return;
}
setStatus("disconnected");
const delay = Math.min(1000 * 2 ** attempt, MAX_BACKOFF_MS);
reconnectAttemptRef.current = attempt + 1;
reconnectTimerRef.current = setTimeout(doConnect, delay);
});
rfb.addEventListener("securityfailure", () => {
if (gen !== generationRef.current) return;
securityFailed = true;
rfbRef.current = null;
setRfbInstance(null);
setStatus("error");
});
rfbRef.current = rfb;
setRfbInstance(rfb);
// Work around a noVNC rendering bug: when an ancestor
// hides this container (display: none), the canvas
// shrinks to 0×0. When the container becomes visible
// again, noVNC may skip rescaling because it believes
// the viewport size hasn't changed. Re-assigning
// scaleViewport forces a fresh scale pass
// regardless.
let prevContainerW = 0;
let prevContainerH = 0;
visibilityObserver = new ResizeObserver((entries) => {
const entry = entries[0];
if (!entry) return;
if (gen !== generationRef.current) return;
const { width, height } = entry.contentRect;
const wasHidden = prevContainerW === 0 && prevContainerH === 0;
const isVisible = width > 0 && height > 0;
prevContainerW = width;
prevContainerH = height;
if (wasHidden && isVisible && rfbRef.current) {
// Re-assign the current value to force noVNC to
// recalculate the viewport. The setter triggers an
// internal rescale regardless of whether the value
// actually changed.
const current = rfbRef.current.scaleViewport;
rfbRef.current.scaleViewport = current;
}
});
visibilityObserver.observe(offscreenContainerRef.current);
} catch {
socket.close();
setStatus("error");
}
};
// Expose a restart handle for the Reconnect button.
restartRef.current = () => {
teardown();
doConnect();
};
if (activated) {
doConnect();
if (!activated || !chatId) {
return;
}
return () => {
restartRef.current = null;
teardown();
setStatus("idle");
setHasConnected(false);
};
}, [activated, chatId, syncRemoteClipboardToLocal]);
useEffect(() => {
if (rfbInstance && rfbRef.current) {
rfbRef.current.scaleViewport = scaleViewport;
}
}, [rfbInstance, scaleViewport]);
connection.open(chatId, syncRemoteClipboardToLocal);
return connection.close;
}, [connection, activated, chatId, syncRemoteClipboardToLocal]);
return {
status,
hasConnected,
reconnect,
attach,
remoteClipboardText,
rfb: rfbInstance,
scaleViewport,
setScaleViewport: connection.setScaleViewport,
reconnect: connection.reconnect,
attach: connection.attach,
};
}
@@ -0,0 +1,480 @@
import RFB from "@novnc/novnc/lib/rfb";
import { watchChatDesktop } from "#/api/api";
import { toast } from "#/components/Toaster/toast";
export type DesktopConnectionStatus =
| "idle"
| "connecting"
| "connected"
| "disconnected"
| "error";
type DesktopConnectionSnapshot = {
readonly status: DesktopConnectionStatus;
/** Whether a session of the current chat has ever connected. */
readonly hasConnected: boolean;
/** Whether the remote screen is scaled to fit its container. */
readonly scaleViewport: boolean;
};
const MAX_BACKOFF_MS = 30_000;
const MAX_RECONNECT_ATTEMPTS = 10;
const STABLE_CONNECTION_MS = 3_000;
const CONNECT_TIMEOUT_MS = 30_000;
// X11 keysym values sent to the remote desktop via the RFB
// protocol. Full list: https://www.cl.cam.ac.uk/~mgk25/ucs/keysymdef.h
const XK_Control_L = 0xffe3; // Left Control modifier.
const XK_Control_R = 0xffe4; // Right Control modifier.
const XK_Meta_L = 0xffeb; // Left Meta (Cmd on macOS) modifier.
const XK_Meta_R = 0xffec; // Right Meta modifier.
const XK_c = 0x0063; // Latin lowercase 'c'.
const XK_v = 0x0076; // Latin lowercase 'v'.
const XK_x = 0x0078; // Latin lowercase 'x'.
const XK_Shift_L = 0xffe1; // Left Shift modifier.
const XK_Shift_R = 0xffe2; // Right Shift modifier.
const isPasteShortcut = (event: KeyboardEvent): boolean => {
const key = event.key.toLowerCase();
return (
(key === "v" && (event.ctrlKey || event.metaKey) && !event.altKey) ||
(key === "insert" && event.shiftKey && !event.ctrlKey && !event.metaKey)
);
};
// Detect Cmd+C on macOS so we can remap it to Ctrl+C on the
// remote desktop. Plain Ctrl+C already travels through noVNC
// correctly, so we only need to intercept the Meta variant.
const isMacCopyShortcut = (event: KeyboardEvent): boolean => {
const key = event.key.toLowerCase();
return key === "c" && event.metaKey && !event.ctrlKey && !event.altKey;
};
// Detect Cmd+X on macOS, remapped for the same reason as copy.
const isMacCutShortcut = (event: KeyboardEvent): boolean => {
const key = event.key.toLowerCase();
return key === "x" && event.metaKey && !event.ctrlKey && !event.altKey;
};
/**
* A noVNC connection to a chat's desktop. After a dropped session it
* reconnects with exponential backoff. Settings apply to the current
* session and every later one. Status changes are published to
* subscribers, in the shape `useSyncExternalStore` reads.
*/
export class DesktopConnection {
private snapshot: DesktopConnectionSnapshot;
private readonly listeners = new Set<() => void>();
private chatId: string | undefined;
private onRemoteClipboard: (text: string) => Promise<unknown> = () =>
Promise.resolve();
private rfb: RFB | null = null;
// Offscreen container for the RFB canvas; moved into the visible
// panel by `attach()`.
private screen: HTMLElement | null = null;
private visibilityObserver: ResizeObserver | null = null;
private removeClipboardKeyListeners: (() => void) | null = null;
private reconnectAttempt = 0;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectStableTimer: ReturnType<typeof setTimeout> | null = null;
private connectTimeout: ReturnType<typeof setTimeout> | null = null;
// Incremented at the start of every session and on teardown. Event
// handlers capture the current value and bail when it no longer
// matches, which prevents async noVNC callbacks from a previous
// session (e.g. a phantom "disconnect" event fired after cleanupRfb)
// from scheduling unwanted reconnect timers.
private generation = 0;
constructor(scaleViewport: boolean) {
this.snapshot = { status: "idle", hasConnected: false, scaleViewport };
}
subscribe = (listener: () => void): (() => void) => {
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
};
getSnapshot = (): DesktopConnectionSnapshot => this.snapshot;
/** Connects to the chat's desktop, replacing any current session. */
open = (
chatId: string,
onRemoteClipboard: (text: string) => Promise<unknown>,
) => {
this.teardown();
this.chatId = chatId;
this.onRemoteClipboard = onRemoteClipboard;
this.connect();
};
/** Ends the session and stops reconnecting. */
close = () => {
this.teardown();
this.chatId = undefined;
this.setSnapshot({ status: "idle", hasConnected: false });
};
/** Starts a fresh session with a reset retry budget. */
reconnect = () => {
if (!this.chatId) {
return;
}
this.teardown();
this.connect();
};
/** Scales the remote screen to fit its container, or shows it at 100%. */
setScaleViewport = (scaleViewport: boolean) => {
this.setSnapshot({ scaleViewport });
if (this.rfb) {
this.rfb.scaleViewport = scaleViewport;
}
};
/**
* Moves the noVNC canvas into a container element without
* reconnecting. Can be called again, e.g. when the tab is reselected.
*/
attach = (container: HTMLElement) => {
if (this.screen && this.screen.parentElement !== container) {
container.appendChild(this.screen);
}
};
private setSnapshot(update: Partial<DesktopConnectionSnapshot>) {
this.snapshot = { ...this.snapshot, ...update };
for (const listener of this.listeners) {
listener();
}
}
private cleanupRfb() {
this.removeClipboardKeyListeners?.();
this.removeClipboardKeyListeners = null;
if (this.rfb) {
try {
this.rfb.disconnect();
} catch {
// Ignore errors during disconnect.
}
this.rfb = null;
}
}
private clearAllTimers() {
if (this.reconnectTimer !== null) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
if (this.reconnectStableTimer !== null) {
clearTimeout(this.reconnectStableTimer);
this.reconnectStableTimer = null;
}
if (this.connectTimeout !== null) {
clearTimeout(this.connectTimeout);
this.connectTimeout = null;
}
}
private teardown() {
this.generation++;
this.clearAllTimers();
this.cleanupRfb();
this.screen?.remove();
this.screen = null;
this.reconnectAttempt = 0;
this.visibilityObserver?.disconnect();
this.visibilityObserver = null;
}
private connect = () => {
const chatId = this.chatId;
if (!chatId) {
return;
}
// Bump the generation so any in-flight async callbacks
// from the previous RFB session become stale.
this.generation++;
const gen = this.generation;
const isStale = () => gen !== this.generation;
this.clearAllTimers();
this.cleanupRfb();
this.visibilityObserver?.disconnect();
this.visibilityObserver = null;
this.setSnapshot({ status: "connecting" });
// Remove the previous container from the DOM so reconnect
// cycles don't leak detached divs.
this.screen?.remove();
const screen = document.createElement("div");
screen.style.width = "100%";
screen.style.height = "100%";
screen.style.position = "relative";
screen.style.overflow = "hidden";
this.screen = screen;
const socket = watchChatDesktop(chatId);
try {
const rfb = new RFB(screen, socket, {
shared: true,
});
rfb.scaleViewport = this.snapshot.scaleViewport;
rfb.resizeSession = false;
rfb.focusOnClick = true;
// Override the noVNC default background (rgb(40,40,40))
// so the letterbox margins match the app surface color
// in both light and dark themes.
const surfaceHsl = getComputedStyle(document.documentElement)
.getPropertyValue("--surface-secondary")
.trim();
if (surfaceHsl) {
rfb.background = `hsl(${surfaceHsl})`;
}
// Per-session flags scoped to this RFB instance, so state
// from a previous session cannot leak.
let sessionConnected = false;
let securityFailed = false;
rfb.addEventListener("clipboard", (event) => {
const text = event.detail.text ?? "";
if (isStale() || !sessionConnected) {
return;
}
this.onRemoteClipboard(text).catch((err) => {
console.error("Failed to sync remote clipboard to local:", err);
});
});
// Capture-phase keydown on the container fires before
// noVNC's own handlers on the canvas. This lets us
// intercept clipboard shortcuts before noVNC swallows
// them without any hidden-textarea focus tricks.
// Track which keys were intercepted on keydown so
// the corresponding keyup events can be suppressed.
const interceptedKeys = new Set<string>();
const clipboardKeyListener = (event: KeyboardEvent) => {
if (isStale()) {
return;
}
if (!sessionConnected) {
return;
}
// Remap Cmd+C / Cmd+X on macOS to Ctrl+C / Ctrl+X
// on the remote desktop. Release the stale Meta
// modifier first because its keydown already reached
// the remote before we could intercept it.
if (isMacCopyShortcut(event) || isMacCutShortcut(event)) {
const targetKeysym = isMacCopyShortcut(event) ? XK_c : XK_x;
const keyName = isMacCopyShortcut(event) ? "KeyC" : "KeyX";
event.preventDefault();
event.stopPropagation();
interceptedKeys.add(event.code);
rfb.sendKey(XK_Meta_L, "MetaLeft", false);
rfb.sendKey(XK_Meta_R, "MetaRight", false);
rfb.sendKey(XK_Control_L, "ControlLeft", true);
rfb.sendKey(targetKeysym, keyName, true);
rfb.sendKey(targetKeysym, keyName, false);
rfb.sendKey(XK_Control_L, "ControlLeft", false);
return;
}
if (!isPasteShortcut(event)) {
return;
}
event.preventDefault();
event.stopPropagation();
interceptedKeys.add(event.code);
const doPaste = async () => {
// Check clipboard permission state before
// attempting readText(). This lets us show a
// clear message when permission is denied
// instead of silently hanging.
try {
const permStatus = await navigator.permissions.query({
name: "clipboard-read" as PermissionName,
});
if (permStatus.state === "denied") {
toast.error(
"Clipboard permission denied. Allow clipboard access in your browser settings to paste.",
);
return;
}
} catch {
// permissions.query may not support
// clipboard-read in all browsers.
// Continue with readText anyway.
}
const text = await navigator.clipboard.readText();
if (!text) {
return;
}
if (isStale()) {
return;
}
rfb.clipboardPasteFrom(text);
rfb.sendKey(XK_Shift_L, "ShiftLeft", false);
rfb.sendKey(XK_Shift_R, "ShiftRight", false);
rfb.sendKey(XK_Meta_L, "MetaLeft", false);
rfb.sendKey(XK_Meta_R, "MetaRight", false);
rfb.sendKey(XK_Control_L, "ControlLeft", false);
rfb.sendKey(XK_Control_R, "ControlRight", false);
rfb.sendKey(XK_Control_L, "ControlLeft", true);
rfb.sendKey(XK_v, "KeyV", true);
rfb.sendKey(XK_v, "KeyV", false);
rfb.sendKey(XK_Control_L, "ControlLeft", false);
};
doPaste().catch((err) => {
console.error("Paste into remote desktop failed:", err);
});
};
const clipboardKeyUpListener = (event: KeyboardEvent) => {
if (interceptedKeys.has(event.code)) {
interceptedKeys.delete(event.code);
event.preventDefault();
event.stopPropagation();
}
};
screen.addEventListener("keydown", clipboardKeyListener, true);
screen.addEventListener("keyup", clipboardKeyUpListener, true);
this.removeClipboardKeyListeners = () => {
screen.removeEventListener("keydown", clipboardKeyListener, true);
screen.removeEventListener("keyup", clipboardKeyUpListener, true);
};
// Fail if the VNC handshake doesn't complete within
// a reasonable window. Bump the generation before
// cleanupRfb() so the resulting noVNC "disconnect"
// event is treated as stale and doesn't redundantly
// set status to "error".
this.connectTimeout = setTimeout(() => {
if (isStale()) return;
if (!sessionConnected) {
this.generation++;
this.cleanupRfb();
this.setSnapshot({ status: "error" });
}
}, CONNECT_TIMEOUT_MS);
rfb.addEventListener("connect", () => {
if (isStale()) return;
sessionConnected = true;
if (this.connectTimeout !== null) {
clearTimeout(this.connectTimeout);
this.connectTimeout = null;
}
this.setSnapshot({ status: "connected", hasConnected: true });
// Only reset the reconnect counter after the
// connection has been stable for a minimum
// duration. This prevents infinite reconnect
// loops when the VNC handshake succeeds but the
// connection drops immediately.
// No gen check needed: clearAllTimers()
// always cancels this before a new session.
this.reconnectStableTimer = setTimeout(() => {
this.reconnectAttempt = 0;
}, STABLE_CONNECTION_MS);
});
rfb.addEventListener("disconnect", () => {
if (isStale()) return;
if (this.reconnectStableTimer !== null) {
clearTimeout(this.reconnectStableTimer);
this.reconnectStableTimer = null;
}
if (this.connectTimeout !== null) {
clearTimeout(this.connectTimeout);
this.connectTimeout = null;
}
this.rfb = null;
// Security failures are terminal: the
// securityfailure handler already moved to
// "error". noVNC fires disconnect after
// securityfailure; ignore it so we don't
// accidentally schedule a retry.
if (securityFailed) {
return;
}
// Only retry if THIS session's VNC handshake
// completed. A previous session having connected
// is irrelevant; the desktop may have become
// permanently unavailable.
if (!sessionConnected) {
this.setSnapshot({ status: "error" });
return;
}
const attempt = this.reconnectAttempt;
if (attempt >= MAX_RECONNECT_ATTEMPTS) {
this.setSnapshot({ status: "error" });
return;
}
this.setSnapshot({ status: "disconnected" });
const delay = Math.min(1000 * 2 ** attempt, MAX_BACKOFF_MS);
this.reconnectAttempt = attempt + 1;
this.reconnectTimer = setTimeout(this.connect, delay);
});
rfb.addEventListener("securityfailure", () => {
if (isStale()) return;
securityFailed = true;
this.rfb = null;
this.setSnapshot({ status: "error" });
});
this.rfb = rfb;
// Work around a noVNC rendering bug: when an ancestor
// hides this container (display: none), the canvas
// shrinks to 0×0. When the container becomes visible
// again, noVNC may skip rescaling because it believes
// the viewport size hasn't changed. Re-assigning
// scaleViewport forces a fresh scale pass
// regardless.
let prevContainerW = 0;
let prevContainerH = 0;
this.visibilityObserver = new ResizeObserver((entries) => {
const entry = entries[0];
if (!entry) return;
if (isStale()) return;
const { width, height } = entry.contentRect;
const wasHidden = prevContainerW === 0 && prevContainerH === 0;
const isVisible = width > 0 && height > 0;
prevContainerW = width;
prevContainerH = height;
if (wasHidden && isVisible && this.rfb) {
// Re-assign the current value to force noVNC to
// recalculate the viewport. The setter triggers an
// internal rescale regardless of whether the value
// actually changed.
const current = this.rfb.scaleViewport;
this.rfb.scaleViewport = current;
}
});
this.visibilityObserver.observe(screen);
} catch {
socket.close();
this.setSnapshot({ status: "error" });
}
};
}