diff --git a/app/apps/terminal/connections.ts b/app/apps/terminal/connections.ts new file mode 100644 index 00000000..aeb1fec8 --- /dev/null +++ b/app/apps/terminal/connections.ts @@ -0,0 +1,100 @@ +import { getStringSetting, setStringSetting } from "../../native/settings-store"; + +/** + * Terminal-app connection registry: the g2mirror hosts the app knows about, + * stored as JSON under one settings key so every isolate sees the same list + * and change notifications ride the ordinary settings-store channel. + * + * A connection is entered as a g2mirror:// connection string (the same form + * g2mirror-view accepts): g2mirror://@[:port] for plain + * websockets (default port 8737), g2mirrors://... for TLS (default 443). + */ + +export const TERMINAL_CONNECTIONS_KEY = "terminal.connections"; + +export type TerminalConnection = { + /** Stable id, assigned at add time; windows and clients key off this. */ + id: string; + /** The g2mirror:// connection string as entered. */ + url: string; + /** + * server_name from the last successful init handshake; null before the + * first success. Display name falls back to the connection string's + * host[:port] (never the token). + */ + serverName: string | null; + /** Auto-connect while the Terminal app is open. Toggled by Connect/Disconnect. */ + enabled: boolean; +}; + +export type ParsedConnectionString = { + secure: boolean; + host: string; + port: number; + authToken: string; +}; + +/** + * Parse a g2mirror://token@host[:port] connection string (g2mirrors:// for + * TLS). Returns null if the string doesn't have that shape. + */ +export function parseConnectionString(url: string): ParsedConnectionString | null { + const match = /^(g2mirrors?):\/\/([^@\s/]+)@(\[[^\]\s]+\]|[^:/@\s]+)(?::(\d+))?\/?$/.exec(url.trim()); + if (!match) return null; + const secure = match[1] === "g2mirrors"; + let authToken = match[2]!; + try { + authToken = decodeURIComponent(authToken); + } catch { + // Not valid percent-encoding; use the raw token. + } + const host = match[3]!; + const port = match[4] ? parseInt(match[4], 10) : secure ? 443 : 8737; + if (!(port >= 1 && port <= 65535)) return null; + return { secure, host, port, authToken }; +} + +/** The host[:port] part of a connection string; "" if it doesn't parse. */ +export function connectionStringHostLabel(url: string): string { + const parsed = parseConnectionString(url); + if (!parsed) return ""; + const defaultPort = parsed.secure ? 443 : 8737; + return parsed.port === defaultPort ? parsed.host : `${parsed.host}:${parsed.port}`; +} + +/** Human label for a connection: cached server name, else its host[:port]. */ +export function connectionDisplayName(connection: TerminalConnection): string { + return connection.serverName || connectionStringHostLabel(connection.url) || connection.url; +} + +export function loadConnections(): TerminalConnection[] { + const raw = getStringSetting(TERMINAL_CONNECTIONS_KEY, ""); + if (!raw) return []; + try { + const parsed = JSON.parse(raw); + if (!Array.isArray(parsed)) return []; + return parsed + .map((item: any): TerminalConnection => ({ + id: String(item?.id ?? ""), + url: String(item?.url ?? ""), + serverName: typeof item?.serverName === "string" && item.serverName ? item.serverName : null, + enabled: item?.enabled !== false, + })) + .filter((connection) => connection.id.length > 0 && connection.url.length > 0); + } catch { + return []; + } +} + +export function saveConnections(connections: TerminalConnection[]): void { + setStringSetting(TERMINAL_CONNECTIONS_KEY, JSON.stringify(connections)); +} + +/** Apply `update` to the stored connection with this id (no-op if gone). */ +export function updateConnection(id: string, update: Partial>): void { + const connections = loadConnections(); + const connection = connections.find((candidate) => candidate.id === id); + if (!connection) return; + Object.assign(connection, update); + saveConnections(connections); +} diff --git a/app/apps/terminal/terminal-app.worker.ts b/app/apps/terminal/terminal-app.worker.ts index ed464ffe..3156c61d 100644 --- a/app/apps/terminal/terminal-app.worker.ts +++ b/app/apps/terminal/terminal-app.worker.ts @@ -1,12 +1,22 @@ /** * Terminal app, hosted in its own worker thread. Window model: - * - "terminal:hub": the window opened from the launcher; shows connection - * status and the list of live g2mirror sessions. One control websocket - * backs it and also carries unsolicited bell/title notifications. + * - "terminal:hub": the window opened from the launcher; shows the list of + * live g2mirror sessions across every connected host (grouped by host when + * more than one is connected), and hosts the Manage Connections section + * where g2mirror:// connections are added, removed, and toggled. * - "terminal:view:N": opened by selecting a session in the hub; each has * its own websocket connection (the protocol allows one attached session * per connection) and its own xterm emulator. * + * Connections are g2mirror://@[:port] strings (g2mirrors:// for + * TLS), stored as JSON in the settings store (see connections.ts). Each + * enabled connection gets a control websocket that backs the session list and + * carries unsolicited bell/title notifications; control connections live as + * long as the worker so bells keep flowing even if the hub window is closed. + * The host's server_name (from the init reply) is cached per connection and + * used as its display name, falling back to the connection string's + * host[:port] before the first successful handshake. + * * Bells for a session with an open, non-foregrounded view window set that * window's sidebar attention flag (cleared by the host on foregrounding). * Frames are painted here and submitted directly to the Java compositor from @@ -28,19 +38,27 @@ import * as frameTimings from "../../native/frame-timings"; import { GESTURE_DOUBLE_CLICK } from "../../ui/gestures"; import { G2MirrorClient, + type G2MirrorClientOptions, type G2MirrorSession, type G2MirrorState, } from "../../native/g2mirror-client"; import { onSettingsStoreChanged } from "../../native/settings-store"; import { clamp } from "../../util/numeric-util"; import { - terminalAuthTokenSetting, terminalAutoReconnectSetting, - terminalHostSetting, terminalLaunchPresetsSetting, - terminalPortSetting, + terminalNewConnectionSetting, terminalWakeOnBellSetting, } from "../../ui/dashboard-settings"; +import { + connectionDisplayName, + loadConnections, + parseConnectionString, + saveConnections, + TERMINAL_CONNECTIONS_KEY, + updateConnection, + type TerminalConnection, +} from "./connections"; import { TerminalEmulator } from "./terminal-emulator"; import type { DashboardInputEvent } from "../../ui/layers"; import { @@ -64,7 +82,7 @@ const terminalFont = getFont("terminus12"); const CELL_WIDTH = 6; const CELL_HEIGHT = 12; // Grid of a session view window (full-height); also declared on the control -// connection so sessions launched from presets come up at view size. +// connections so sessions launched from presets come up at view size. const VIEW_VIEWPORT = appViewportSize("max"); const VIEW_GRID = { cols: Math.floor(VIEW_VIEWPORT.width / CELL_WIDTH), @@ -77,6 +95,9 @@ const HISTORY_PAGE = 200; // Auto-reconnect backoff: doubles per failed attempt, resets on success. const RECONNECT_MIN_DELAY_MS = 1_000; const RECONNECT_MAX_DELAY_MS = 60_000; +// Storage key of terminalNewConnectionSetting (the Add-connection draft the +// phone text editor types into); its changes just repaint the add screen. +const NEW_CONNECTION_DRAFT_KEY = "terminal.newConnectionDraft"; type BaseWindow = { windowId: string; @@ -99,21 +120,33 @@ type BaseWindow = { menu: WindowMenu | null; }; +/** + * What the hub window is showing: the session list, the Manage Connections + * section, or the Add-connection screen (type the g2mirror:// string on the + * phone, click to save). + */ +type HubMode = "sessions" | "connections" | "add"; + type HubWindow = BaseWindow & { kind: "hub"; + mode: HubMode; selectedIndex: number; scrollRow: number; /** - * Session sockets in display order, captured when the window last became - * visible so the list doesn't reshuffle under the user while it's open. - * Cleared on foreground/screen-on; orderedSessions() rebuilds it lazily, - * sorting by recency and appending sessions that appear while visible. + * Session recency keys in display order, captured when the window last + * became visible so the list doesn't reshuffle under the user while it's + * open. Cleared on foreground/screen-on; orderedSessions() rebuilds it + * lazily, sorting by recency and appending sessions that appear while + * visible. */ sessionOrder: string[]; + /** Parse-failure message shown on the Add-connection screen. */ + addError: string; }; type ViewWindow = BaseWindow & { kind: "view"; + connectionId: string; socket: string; label: string; /** Sidebar-icon character (">3"); "" if every glyph was taken at open time. */ @@ -147,8 +180,17 @@ type ViewWindow = BaseWindow & { type TerminalWindow = HubWindow | ViewWindow; +type PendingView = { + connectionId: string; + socket: string; + label: string; + glyph: string; + /** Client options captured when the view was requested from a live control. */ + options: G2MirrorClientOptions; +}; + const windows = new Map(); -const pendingViews = new Map(); +const pendingViews = new Map(); // The view an assistant tool acts on when the terminal isn't foregrounded: // the last view to be foregrounded or receive input. let activeViewId: string | null = null; @@ -163,7 +205,7 @@ let nextViewSerial = 1; const TERMINAL_TOOLS: ToolSpec[] = [ { name: "list_sessions", - description: "List the live g2mirror terminal sessions the glasses can see.", + description: "List the live g2mirror terminal sessions the glasses can see, across every connected host.", inputSchema: { type: "object", properties: {}, additionalProperties: false }, availability: "open", }, @@ -188,18 +230,22 @@ const TERMINAL_TOOLS: ToolSpec[] = [ { name: "list_launch_presets", description: - "List the named launch presets that can start a new terminal session on the host machine (for launch_session).", + "List the named launch presets that can start a new terminal session on a host machine (for launch_session).", inputSchema: { type: "object", properties: {}, additionalProperties: false }, availability: "open", }, { name: "launch_session", description: - "Start a new terminal session on the host machine from a named launch preset (see list_launch_presets) and open a window viewing it.", + "Start a new terminal session on a connected host machine from a named launch preset (see list_launch_presets) and open a window viewing it.", inputSchema: { type: "object", properties: { preset: { type: "string", description: "Name of the launch preset to start." }, + host: { + type: "string", + description: "Which host to launch on (server name), when more than one is connected.", + }, }, required: ["preset"], additionalProperties: false, @@ -210,21 +256,37 @@ const TERMINAL_TOOLS: ToolSpec[] = [ ]; let screenOn = true; -// Control connection: session listing for the hub, plus unsolicited -// bell/title notifications for every monitored terminal. Lives as long as -// the worker so bells keep flowing even if the hub window is closed. -let controlClient: G2MirrorClient | null = null; -let controlState: G2MirrorState | null = null; -let controlUnsubscribers: Array<() => void> = []; -let controlReconnectTimer: ReturnType | null = null; -let controlReconnectDelayMs = RECONNECT_MIN_DELAY_MS; +/** + * One record per configured connection: the stored config plus the live + * control client (session listing for the hub, unsolicited bell/title + * notifications). `client` is null while the connection is disabled or the + * config doesn't parse. + */ +type ControlConnection = { + config: TerminalConnection; + client: G2MirrorClient | null; + state: G2MirrorState | null; + unsubscribers: Array<() => void>; + reconnectTimer: ReturnType | null; + reconnectDelayMs: number; + sessionsSeeded: boolean; +}; -// When each session (by socket) last "updated", unix epoch ms: bells, title -// changes, and terminal output from open views. Sessions first seen in the -// initial list after (re)connect are seeded from their last bell, since we -// weren't watching; ones appearing later were just created, so they get "now". +// Keyed by connection id; iteration order mirrors the stored list (rebuilt by +// syncControlsFromSettings). Populated once the app is first opened. +const controls = new Map(); +let controlsInitialized = false; + +// When each session last "updated", unix epoch ms: bells, title changes, and +// terminal output from open views. Keys are recencyKey(connectionId, socket). +// Sessions first seen in the initial list after (re)connect are seeded from +// their last bell, since we weren't watching; ones appearing later were just +// created, so they get "now". const sessionRecency = new Map(); -let controlSessionsSeeded = false; + +function recencyKey(connectionId: string, socket: string): string { + return `${connectionId}\n${socket}`; +} function post(message: WorkerAppReply): void { global.postMessage(message); @@ -251,11 +313,16 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { } case "text-input": { const window = windows.get(message.windowId); - // Only attached view windows have a terminal to type into. submitInput - // appends Enter ("\r") after a wrapper-side pause so paste-detecting - // apps (e.g. Claude Code) submit instead of inserting a newline. + // Attached view windows type into their terminal. The hub accepts text + // only on the Add-connection screen, where it fills the draft (voice + // input as an alternative to the phone keyboard). submitInput appends + // Enter ("\r") after a wrapper-side pause so paste-detecting apps + // (e.g. Claude Code) submit instead of inserting a newline. if (window && window.kind === "view") { window.client.submitInput(message.text); + } else if (window && window.kind === "hub" && window.mode === "add") { + terminalNewConnectionSetting.set(message.text); + scheduleRender(window); } break; } @@ -307,29 +374,41 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { } }; -// Restart the control connection when the g2mirror settings change (edited -// in the dashboard's Settings menu, which lives in the main isolate). +// React to setting changes (connections edited here or in another isolate, +// toggles edited in the Settings app, the Add-connection draft typed on the +// phone). onSettingsStoreChanged((key) => { if (!key.startsWith("terminal.")) return; - // Settings that don't affect the connection; no reconnect needed. - if (key === "terminal.launchPresets" || key === "terminal.wakeOnBell") return; - if (key === "terminal.autoReconnect") { - if (!terminalAutoReconnectSetting.get()) { - cancelPendingReconnects(); - } else if (windows.size > 0 && (controlState?.phase ?? "idle") === "failed") { - startControlClient(); - } - return; - } - // (Re)start only once the app has actually been opened. - if (controlClient || windows.size > 0) { - startControlClient(); + switch (key) { + case TERMINAL_CONNECTIONS_KEY: + // Only once the app has actually been opened. + if (controlsInitialized) syncControlsFromSettings(); + renderHubWindows(); + return; + case NEW_CONNECTION_DRAFT_KEY: + // Live keystrokes from the phone editor; repaint the add screen. + renderHubWindows(); + return; + case "terminal.autoReconnect": + if (!terminalAutoReconnectSetting.get()) { + cancelPendingReconnects(); + } else if (windows.size > 0) { + for (const control of controls.values()) { + if ((control.state?.phase ?? "idle") === "failed") scheduleControlReconnect(control); + } + } + return; + default: + // launchPresets, wakeOnBell: no connection impact. + return; } }); /** Cancel scheduled retries (auto-reconnect turned off); stale views stay marked. */ function cancelPendingReconnects(): void { - cancelControlReconnect(); + for (const control of controls.values()) { + cancelControlReconnect(control); + } for (const window of windows.values()) { if (window.kind === "view" && window.reconnectTimer) { clearTimeout(window.reconnectTimer); @@ -359,14 +438,16 @@ function openWindow(windowId: string, surfaceId: string, viewport: { width: numb renderScheduled: false, lastSubmittedFingerprint: "", menu: null, + mode: "sessions", selectedIndex: 0, scrollRow: 0, sessionOrder: [], + addError: "", }); // The hub carries the app's assistant tools; declare them once it exists. post({ type: "set-tools", windowId, tools: TERMINAL_TOOLS }); - if (!controlClient) { - startControlClient(); + if (!controlsInitialized) { + syncControlsFromSettings(); } } @@ -383,127 +464,207 @@ function closeWindow(windowId: string): void { } window.client.stop(); } + if (window.kind === "hub" && window.mode === "add") { + // Window closed mid-add: shut the phone editor down. + endAddConnection(window); + } windows.delete(windowId); // Auto-reconnect only runs while at least one terminal window is open. - if (windows.size === 0) cancelControlReconnect(); + if (windows.size === 0) { + for (const control of controls.values()) { + cancelControlReconnect(control); + } + } if (activeViewId === windowId) activeViewId = null; if (window.kind === "view") { renderHubWindows(); } } -function clientOptions() { +/** Client options for a connection string; null if the string doesn't parse. */ +function clientOptionsFor(connection: TerminalConnection): G2MirrorClientOptions | null { + const parsed = parseConnectionString(connection.url); + if (!parsed) return null; return { - host: terminalHostSetting.get().trim(), - port: parseInt(terminalPortSetting.get(), 10) || 8737, - authToken: terminalAuthTokenSetting.get(), + ...parsed, deviceName: DEVICE_NAME, cols: VIEW_GRID.cols, rows: VIEW_GRID.rows, }; } -function startControlClient(): void { - stopControlClient(); - const options = clientOptions(); - if (!options.host) { - controlState = null; - renderHubWindows(); +/** + * Reconcile the live control clients with the stored connection list: start + * enabled connections, stop disabled or removed ones, restart ones whose + * connection string changed. Called on first open and whenever the stored + * list changes (including our own edits). Rebuilds the map in stored order so + * UI iteration matches the list the user manages. + */ +function syncControlsFromSettings(): void { + controlsInitialized = true; + const stored = loadConnections(); + const storedIds = new Set(stored.map((connection) => connection.id)); + for (const [id, control] of Array.from(controls)) { + if (!storedIds.has(id)) { + stopControl(control); + controls.delete(id); + } + } + const previous = new Map(controls); + controls.clear(); + for (const connection of stored) { + let control = previous.get(connection.id); + if (!control) { + control = { + config: connection, + client: null, + state: null, + unsubscribers: [], + reconnectTimer: null, + reconnectDelayMs: RECONNECT_MIN_DELAY_MS, + sessionsSeeded: false, + }; + } + const urlChanged = control.config.url !== connection.url; + control.config = connection; + controls.set(connection.id, control); + if (connection.enabled && (urlChanged || !control.client)) { + startControl(control); + } else if (!connection.enabled && control.client) { + stopControl(control); + } + } + renderHubWindows(); +} + +function startControl(control: ControlConnection): void { + stopControl(control); + const options = clientOptionsFor(control.config); + if (!options) { + control.state = null; return; } const client = new G2MirrorClient(options); - controlClient = client; - controlState = client.state(); - controlSessionsSeeded = false; - controlUnsubscribers.push( + const connectionId = control.config.id; + control.client = client; + control.state = client.state(); + control.sessionsSeeded = false; + control.unsubscribers.push( client.onStateChange((state) => { - noteSessionListRecency(state); - controlState = state; - if (state.phase === "connected") controlReconnectDelayMs = RECONNECT_MIN_DELAY_MS; - if (state.phase === "failed") scheduleControlReconnect(); + // Only the current client speaks for the control (stopControl clears + // listeners, but a stop() emits synchronously before that). + if (control.client !== client) return; + noteSessionListRecency(control, state); + control.state = state; + if (state.phase === "connected") { + control.reconnectDelayMs = RECONNECT_MIN_DELAY_MS; + maybeCacheServerName(control, state.serverName); + } + if (state.phase === "failed") scheduleControlReconnect(control); renderHubWindows(); }), client.onBell((socket, lastBellAtMs) => { - routeBell(socket, lastBellAtMs); + routeBell(connectionId, socket, lastBellAtMs); }), client.onTitle((socket) => { - noteSessionUpdated(socket); + noteSessionUpdated(connectionId, socket); }), ); client.start(); } -function noteSessionUpdated(socket: string): void { - sessionRecency.set(socket, Date.now()); +function stopControl(control: ControlConnection): void { + cancelControlReconnect(control); + for (const unsubscribe of control.unsubscribers.splice(0)) { + unsubscribe(); + } + control.client?.stop(); + control.client = null; + control.state = null; } -function noteSessionListRecency(state: G2MirrorState): void { +/** + * A successful handshake reported the host's server_name; cache it on the + * stored connection so the hub can name the host even while disconnected. + * The resulting settings change re-runs syncControlsFromSettings, which sees + * an unchanged url and leaves the live client alone. + */ +function maybeCacheServerName(control: ControlConnection, serverName: string): void { + if (!serverName || control.config.serverName === serverName) return; + control.config.serverName = serverName; + updateConnection(control.config.id, { serverName }); +} + +function noteSessionUpdated(connectionId: string, socket: string): void { + sessionRecency.set(recencyKey(connectionId, socket), Date.now()); +} + +function noteSessionListRecency(control: ControlConnection, state: G2MirrorState): void { + const connectionId = control.config.id; for (const session of state.sessions) { - const known = sessionRecency.get(session.socket); + const key = recencyKey(connectionId, session.socket); + const known = sessionRecency.get(key); if (known === undefined) { sessionRecency.set( - session.socket, - Math.max(session.lastBellAt ?? 0, controlSessionsSeeded ? Date.now() : 0), + key, + Math.max(session.lastBellAt ?? 0, control.sessionsSeeded ? Date.now() : 0), ); } else if ((session.lastBellAt ?? 0) > known) { // A bell rang while we weren't connected to hear it (the live bell // message would have advanced the recency); deliver it late so the // missed attention flag / wake still happens. - routeBell(session.socket, session.lastBellAt!); + routeBell(connectionId, session.socket, session.lastBellAt!); } } - if (state.sessions.length) controlSessionsSeeded = true; -} - -function stopControlClient(): void { - cancelControlReconnect(); - for (const unsubscribe of controlUnsubscribers.splice(0)) { - unsubscribe(); - } - controlClient?.stop(); - controlClient = null; - controlState = null; + if (state.sessions.length) control.sessionsSeeded = true; } /** - * Retry the control connection after a backoff delay. The delay doubles per + * Retry a control connection after a backoff delay. The delay doubles per * scheduled attempt and resets when a connection reaches "connected" (or on * a manual Connect). No-op when auto-reconnect is off, no terminal window is - * open, or no host is configured. + * open, or the connection was disabled/removed meanwhile. */ -function scheduleControlReconnect(): void { - if (controlReconnectTimer) return; +function scheduleControlReconnect(control: ControlConnection): void { + if (control.reconnectTimer) return; if (!terminalAutoReconnectSetting.get()) return; if (windows.size === 0) return; - if (!terminalHostSetting.get().trim()) return; - const delayMs = controlReconnectDelayMs; - controlReconnectDelayMs = Math.min(controlReconnectDelayMs * 2, RECONNECT_MAX_DELAY_MS); - controlReconnectTimer = setTimeout(() => { - controlReconnectTimer = null; + if (!control.config.enabled) return; + const delayMs = control.reconnectDelayMs; + control.reconnectDelayMs = Math.min(control.reconnectDelayMs * 2, RECONNECT_MAX_DELAY_MS); + control.reconnectTimer = setTimeout(() => { + control.reconnectTimer = null; if (!terminalAutoReconnectSetting.get() || windows.size === 0) return; - if ((controlState?.phase ?? "idle") === "failed") startControlClient(); + if (controls.get(control.config.id) !== control || !control.config.enabled) return; + if ((control.state?.phase ?? "idle") === "failed") startControl(control); }, delayMs); } -function cancelControlReconnect(): void { - if (controlReconnectTimer) { - clearTimeout(controlReconnectTimer); - controlReconnectTimer = null; +function cancelControlReconnect(control: ControlConnection): void { + if (control.reconnectTimer) { + clearTimeout(control.reconnectTimer); + control.reconnectTimer = null; } } -function routeBell(socket: string, lastBellAtMs: number): void { - const known = sessionRecency.get(socket) ?? 0; - if (lastBellAtMs > known) sessionRecency.set(socket, lastBellAtMs); +function routeBell(connectionId: string, socket: string, lastBellAtMs: number): void { + const key = recencyKey(connectionId, socket); + const known = sessionRecency.get(key) ?? 0; + if (lastBellAtMs > known) sessionRecency.set(key, lastBellAtMs); for (const window of windows.values()) { - if (window.kind === "view" && window.socket === socket && !window.foreground) { + if ( + window.kind === "view" && + window.connectionId === connectionId && + window.socket === socket && + !window.foreground + ) { post({ type: "set-attention", windowId: window.windowId, attention: true }); } } if (terminalWakeOnBellSetting.get()) { // Wake to the belling session's view window, or the hub if it has none. // The shell drops the message unless the glasses are actually asleep. - const viewId = viewWindowIdForSocket(socket); + const viewId = viewWindowIdForSocket(connectionId, socket); const hubId = [...windows.values()].find((window) => window.kind === "hub")?.windowId ?? null; const target = viewId ?? hubId; if (target) post({ type: "wake-window", windowId: target }); @@ -520,12 +681,12 @@ function createViewWindow( windowId: string, surfaceId: string, viewport: { width: number; height: number }, - view: { socket: string; label: string; glyph: string }, + view: PendingView, ): ViewWindow { - const { socket, label, glyph } = view; + const { connectionId, socket, label, glyph } = view; const gridCols = Math.floor(viewport.width / CELL_WIDTH); const gridRows = Math.floor(viewport.height / CELL_HEIGHT); - const client = new G2MirrorClient({ ...clientOptions(), cols: gridCols, rows: gridRows }); + const client = new G2MirrorClient({ ...view.options, cols: gridCols, rows: gridRows }); const window: ViewWindow = { kind: "view", windowId, @@ -539,6 +700,7 @@ function createViewWindow( renderScheduled: false, lastSubmittedFingerprint: "", menu: null, + connectionId, socket, label, glyph, @@ -594,7 +756,7 @@ function createViewWindow( window.emulator.reset(); } window.receivedData = true; - noteSessionUpdated(window.socket); + noteSessionUpdated(window.connectionId, window.socket); window.emulator.write(data, () => scheduleRender(window)); }), client.onSessionDetached((reason) => { @@ -666,6 +828,14 @@ function windowMenu(window: TerminalWindow): WindowMenu { return window.menu; } +/** Controls currently connected (handshake accepted), in stored order. */ +function connectedControls(): ControlConnection[] { + return [...controls.values()].filter((control) => { + const phase = control.state?.phase; + return phase === "connected" || phase === "attached"; + }); +} + function windowMenuItems(window: TerminalWindow): MenuItem[] { const items: MenuItem[] = [ { @@ -677,28 +847,24 @@ function windowMenuItems(window: TerminalWindow): MenuItem[] { }, ]; if (window.kind === "hub") { - const phase = controlState?.phase; - if (phase === "connected" || phase === "attached") { + const connected = connectedControls(); + const multiHost = connected.length > 1; + for (const control of connected) { for (const preset of launchPresetNames()) { + const label = multiHost + ? `Launch ${preset} @ ${connectionDisplayName(control.config)}` + : `Launch ${preset}`; items.push({ - label: `Launch ${preset}`, + label, onSelect: (ctx) => { ctx.stack.pop(); - launchAndOpenView(preset).catch((error) => { + launchAndOpenView(control, preset).catch((error) => { // The hub status line also shows the server's error message. console.warn(`terminal launch ${preset} failed: ${error}`); }); }, }); } - items.push({ - label: "Disconnect", - onSelect: (ctx) => { - ctx.stack.pop(); - stopControlClient(); - renderHubWindows(); - }, - }); } } else { if (window.client.state().phase === "failed") { @@ -752,6 +918,18 @@ function handleInput(window: TerminalWindow, event: DashboardInputEvent, frameId return; } if (event.type === "double-click") { + // Inside the hub's sub-sections, double-click backs out one level; at the + // top level (and in views) it yields focus to the sidebar as everywhere. + if (window.kind === "hub" && window.mode === "add") { + cancelAddConnection(window); + renderAndSubmit(window, frameId); + return; + } + if (window.kind === "hub" && window.mode === "connections") { + setHubMode(window, "sessions"); + renderAndSubmit(window, frameId); + return; + } frameTimings.finishFrame(frameId, "discarded: terminal yielded focus"); post({ type: "yield-focus", windowId: window.windowId }); return; @@ -814,85 +992,295 @@ function applyHistoryReply(window: ViewWindow, reply: { start: number; oldest: n type HubItem = { label: string; + /** Group heading (host name): drawn differently and skipped by selection. */ + heading?: boolean; onSelect?: () => void; }; +/** Switch the hub between its sections, resetting selection state. */ +function setHubMode(window: HubWindow, mode: HubMode): void { + window.mode = mode; + window.selectedIndex = 0; + window.scrollRow = 0; + window.addError = ""; +} + /** - * The control connection's sessions in this hub window's display order: + * One control connection's sessions in this hub window's display order: * most-recently-updated first as of when the window became visible, with * sessions that appeared since then at the end. The captured order lives in - * window.sessionOrder (cleared when the window becomes visible) so the list - * doesn't reshuffle while the user is looking at it. + * window.sessionOrder (cleared when the window becomes visible; keys are + * connection-scoped) so the list doesn't reshuffle while the user is looking + * at it. */ -function orderedSessions(window: HubWindow): G2MirrorSession[] { - const sessions = controlState?.sessions ?? []; +function orderedSessions(window: HubWindow, control: ControlConnection): G2MirrorSession[] { + const connectionId = control.config.id; + const sessions = control.state?.sessions ?? []; const position = new Map(); - for (const socket of window.sessionOrder) { - if (!position.has(socket)) position.set(socket, position.size); + for (const key of window.sessionOrder) { + if (!position.has(key)) position.set(key, position.size); } const fresh = sessions - .filter((session) => !position.has(session.socket)) - .sort((a, b) => (sessionRecency.get(b.socket) ?? 0) - (sessionRecency.get(a.socket) ?? 0)); + .filter((session) => !position.has(recencyKey(connectionId, session.socket))) + .sort( + (a, b) => + (sessionRecency.get(recencyKey(connectionId, b.socket)) ?? 0) - + (sessionRecency.get(recencyKey(connectionId, a.socket)) ?? 0), + ); for (const session of fresh) { - position.set(session.socket, position.size); - window.sessionOrder.push(session.socket); + const key = recencyKey(connectionId, session.socket); + position.set(key, position.size); + window.sessionOrder.push(key); } - return sessions.slice().sort((a, b) => position.get(a.socket)! - position.get(b.socket)!); + return sessions + .slice() + .sort( + (a, b) => + position.get(recencyKey(connectionId, a.socket))! - position.get(recencyKey(connectionId, b.socket))!, + ); } function hubItems(window: HubWindow): HubItem[] { - const items: HubItem[] = []; - const state = controlState; - const phase = state?.phase ?? "idle"; + return window.mode === "connections" ? hubConnectionItems(window) : hubSessionItems(window); +} - if (phase === "connected" || phase === "attached") { - for (const session of orderedSessions(window)) { - const openWindowId = viewWindowIdForSocket(session.socket); +function hubSessionItems(window: HubWindow): HubItem[] { + const items: HubItem[] = [ + { + label: "Manage Connections", + onSelect: () => setHubMode(window, "connections"), + }, + ]; + const connected = connectedControls(); + const multiHost = connected.length > 1; + for (const control of connected) { + if (multiHost) { + items.push({ label: connectionDisplayName(control.config), heading: true }); + } + const sessions = orderedSessions(window, control); + for (const session of sessions) { + const openWindowId = viewWindowIdForSocket(control.config.id, session.socket); items.push({ label: openWindowId ? `${sessionLabel(session)} [open]` : sessionLabel(session), onSelect: () => { - const windowId = viewWindowIdForSocket(session.socket); + const windowId = viewWindowIdForSocket(control.config.id, session.socket); if (windowId) { post({ type: "focus-window", windowId }); } else { - openViewWindowFor(session); + openViewWindowFor(control, session); } }, }); } - if (!state?.sessions.length) { + if (!sessions.length) { items.push({ - label: "(no live sessions; run g2mirror )", - onSelect: () => controlClient?.listSessions(), + label: multiHost ? "(no live sessions)" : "(no live sessions; run g2mirror )", + onSelect: () => control.client?.listSessions(), }); } } - if (phase === "idle" || phase === "failed") { + // Disconnected/failed connections get a one-click Connect shortcut here; + // full management (remove, add) lives in Manage Connections. + for (const control of controls.values()) { + if (connected.includes(control)) continue; + if (control.config.enabled && control.state?.phase === "connecting") continue; items.push({ - label: terminalHostSetting.get().trim() ? "Connect" : "Connect (host not set)", - onSelect: () => { - // Manual connect: retry now and start the backoff schedule over. - controlReconnectDelayMs = RECONNECT_MIN_DELAY_MS; - startControlClient(); - }, + label: `Connect ${connectionDisplayName(control.config)}`, + onSelect: () => connectControl(control), }); } return items; } +function hubConnectionItems(window: HubWindow): HubItem[] { + const items: HubItem[] = []; + for (const control of controls.values()) { + items.push({ + label: `${connectionDisplayName(control.config)} (${controlStatusWord(control)})`, + onSelect: () => openConnectionActions(window, control), + }); + } + items.push( + { + label: "Add connection", + onSelect: () => beginAddConnection(window), + }, + { + label: "Done", + onSelect: () => setHubMode(window, "sessions"), + }, + ); + return items; +} + +function controlStatusWord(control: ControlConnection): string { + if (!control.config.enabled) return "off"; + switch (control.state?.phase) { + case "connected": + case "attached": + return "connected"; + case "connecting": + return "connecting"; + case "failed": + return control.reconnectTimer ? "retrying" : "failed"; + default: + return clientOptionsFor(control.config) ? "off" : "bad connection string"; + } +} + +/** Per-connection action menu (reuses the window-menu machinery). */ +function openConnectionActions(window: HubWindow, control: ControlConnection): void { + const name = connectionDisplayName(control.config); + const items: MenuItem[] = [ + control.config.enabled + ? { + label: "Disconnect", + onSelect: (ctx) => { + ctx.stack.pop(); + disconnectControl(control); + }, + } + : { + label: "Connect", + onSelect: (ctx) => { + ctx.stack.pop(); + connectControl(control); + }, + }, + { + label: `Remove ${name}`, + onSelect: (ctx) => { + ctx.stack.pop(); + removeControl(control); + }, + }, + { + label: "Cancel", + onSelect: (ctx) => { + ctx.stack.pop(); + }, + }, + ]; + windowMenu(window).open(items); +} + +/** Enable and (re)connect now; also the manual retry path, so reset backoff. */ +function connectControl(control: ControlConnection): void { + control.reconnectDelayMs = RECONNECT_MIN_DELAY_MS; + if (!control.config.enabled) { + control.config.enabled = true; + updateConnection(control.config.id, { enabled: true }); + } + startControl(control); + renderHubWindows(); +} + +function disconnectControl(control: ControlConnection): void { + control.config.enabled = false; + updateConnection(control.config.id, { enabled: false }); + stopControl(control); + renderHubWindows(); +} + +function removeControl(control: ControlConnection): void { + stopControl(control); + controls.delete(control.config.id); + saveConnections(loadConnections().filter((connection) => connection.id !== control.config.id)); + renderHubWindows(); +} + +/** + * Enter the Add-connection screen: clear the draft and ask the shell to open + * the phone text editor on it. The user types (or voice-inputs) the + * g2mirror:// string, then clicks to save or double-clicks to cancel. + */ +function beginAddConnection(window: HubWindow): void { + terminalNewConnectionSetting.set(""); + setHubMode(window, "add"); + post({ type: "start-text-setting-edit", settingId: terminalNewConnectionSetting.id }); +} + +function saveAddConnection(window: HubWindow): void { + const url = terminalNewConnectionSetting.get(); + if (!parseConnectionString(url)) { + window.addError = url + ? "Not a g2mirror://token@host connection string." + : "Enter a g2mirror:// connection string first."; + scheduleRender(window); + return; + } + const connections = loadConnections(); + connections.push({ id: `c${Date.now()}`, url, serverName: null, enabled: true }); + saveConnections(connections); + endAddConnection(window); + setHubMode(window, "connections"); + // Start it immediately rather than waiting for the settings-change tick. + syncControlsFromSettings(); +} + +function cancelAddConnection(window: HubWindow): void { + endAddConnection(window); + setHubMode(window, "connections"); +} + +/** Common teardown for leaving the add screen: clear draft, close phone editor. */ +function endAddConnection(window: HubWindow): void { + window.addError = ""; + terminalNewConnectionSetting.set(""); + post({ type: "end-text-setting-edit" }); +} + +/** Move the hub selection to the next selectable item in `direction`. */ +function moveHubSelection(window: HubWindow, items: HubItem[], direction: -1 | 1): void { + let index = window.selectedIndex + direction; + while (index >= 0 && index < items.length && !items[index]!.onSelect) { + index += direction; + } + if (index >= 0 && index < items.length) { + window.selectedIndex = index; + } +} + +/** Clamp the selection into range and off heading rows (prefer moving down). */ +function clampHubSelection(window: HubWindow, items: HubItem[]): void { + if (!items.length) { + window.selectedIndex = 0; + return; + } + let index = Math.max(0, Math.min(window.selectedIndex, items.length - 1)); + if (!items[index]!.onSelect) { + let forward = index; + while (forward < items.length && !items[forward]!.onSelect) forward++; + let backward = index; + while (backward >= 0 && !items[backward]!.onSelect) backward--; + index = forward < items.length ? forward : Math.max(0, backward); + } + window.selectedIndex = index; +} + function handleHubInput(window: HubWindow, event: DashboardInputEvent, frameId: number): void { + if (window.mode === "add") { + if (event.type === "click") { + saveAddConnection(window); + renderAndSubmit(window, frameId); + return; + } + frameTimings.finishFrame(frameId, "discarded: terminal add-connection ignored input"); + return; + } const items = hubItems(window); + clampHubSelection(window, items); switch (event.type) { case "scroll-up": - window.selectedIndex = Math.max(0, window.selectedIndex - 1); + moveHubSelection(window, items, -1); renderAndSubmit(window, frameId); return; case "scroll-down": - window.selectedIndex = Math.min(items.length - 1, window.selectedIndex + 1); + moveHubSelection(window, items, 1); renderAndSubmit(window, frameId); return; case "click": { - const item = items[Math.max(0, Math.min(window.selectedIndex, items.length - 1))]; + const item = items[window.selectedIndex]; item?.onSelect?.(); renderAndSubmit(window, frameId); return; @@ -908,18 +1296,20 @@ function handleHubInput(window: HubWindow, event: DashboardInputEvent, frameId: * Includes views that were requested but whose surface hasn't opened yet, so * a quick double-select can't spawn two windows for one session. */ -function viewWindowIdForSocket(socket: string): string | null { +function viewWindowIdForSocket(connectionId: string, socket: string): string | null { for (const window of windows.values()) { - if (window.kind === "view" && window.socket === socket) return window.windowId; + if (window.kind === "view" && window.connectionId === connectionId && window.socket === socket) { + return window.windowId; + } } for (const [windowId, pending] of pendingViews) { - if (pending.socket === socket) return windowId; + if (pending.connectionId === connectionId && pending.socket === socket) return windowId; } return null; } -function openViewWindowFor(session: G2MirrorSession): void { - openViewWindow(session.socket, sessionLabel(session)); +function openViewWindowFor(control: ControlConnection, session: G2MirrorSession): void { + openViewWindow(control, session.socket, sessionLabel(session)); } /** @@ -939,10 +1329,12 @@ function allocateViewGlyph(): string { return ""; } -function openViewWindow(socket: string, label: string): void { +function openViewWindow(control: ControlConnection, socket: string, label: string): void { + const options = clientOptionsFor(control.config); + if (!options) return; const windowId = `terminal:view:${nextViewSerial++}`; const glyph = allocateViewGlyph(); - pendingViews.set(windowId, { socket, label, glyph }); + pendingViews.set(windowId, { connectionId: control.config.id, socket, label, glyph, options }); post({ type: "open-window-request", windowId, @@ -967,11 +1359,11 @@ function launchPresetNames(): string[] { return names; } -/** Launch a preset on the server and open a view window on the new session. */ -async function launchAndOpenView(preset: string): Promise { - if (!controlClient) throw new Error("Not connected to the g2mirror server."); - const socket = await controlClient.launchSession(preset); - openViewWindow(socket, preset); +/** Launch a preset on a host and open a view window on the new session. */ +async function launchAndOpenView(control: ControlConnection, preset: string): Promise { + if (!control.client) throw new Error("Not connected to the g2mirror server."); + const socket = await control.client.launchSession(preset); + openViewWindow(control, socket, preset); return socket; } @@ -987,32 +1379,40 @@ function paintContent(window: TerminalWindow): GrayImage { } function paintHub(window: HubWindow): GrayImage { + if (window.mode === "add") { + return paintAddConnection(window); + } const image = new GrayImage(window.viewportWidth, window.viewportHeight, 0); // No border box: the shell chrome (top bar + sidebar) already frames the app. - image.drawText(terminalFont, 18, 10, "Terminal", 220); - image.drawText(terminalFont, 24, 30, hubStatusLine(), 170); + image.drawText(terminalFont, 18, 10, window.mode === "connections" ? "Terminal - Connections" : "Terminal", 220); + image.drawText(terminalFont, 24, 30, hubStatusLine(window), 170); let listTop = 52; - if (!terminalHostSetting.get().trim()) { - image.drawText(terminalFont, 24, 46, "Set host in Settings > Terminal, see:", 150); + if (window.mode === "sessions" && controls.size === 0) { + image.drawText(terminalFont, 24, 46, "Add a g2mirror:// connection to get started, see:", 150); image.drawText(terminalFont, 24, 60, "https://github.com/jimrandomh/g2mirror", 190); listTop += 28; } const items = hubItems(window); - window.selectedIndex = Math.max(0, Math.min(window.selectedIndex, items.length - 1)); + clampHubSelection(window, items); const visibleRowCount = Math.max(1, ((window.viewportHeight - 30 - listTop) / HUB_ROW_HEIGHT) | 0); window.scrollRow = scrollToKeepSelectionVisible(window.scrollRow, window.selectedIndex, visibleRowCount, items.length); const lastVisibleRow = Math.min(items.length, window.scrollRow + visibleRowCount); for (let index = window.scrollRow; index < lastVisibleRow; index++) { const y = listTop + (index - window.scrollRow) * HUB_ROW_HEIGHT; + const item = items[index]!; + if (item.heading) { + image.drawText(terminalFont, 20, y + 2, item.label, 140); + continue; + } const selected = index === window.selectedIndex; if (selected) { // Match the shell convention: fill only when this window has focus, so // an outline-only selection signals the sidebar owns input. drawSelectionHighlight(image, 20, y - 2, window.viewportWidth - 40, HUB_ROW_HEIGHT - 1, window.focused, 8); } - image.drawText(terminalFont, 32, y + 2, items[index]!.label, selected ? 255 : 200); + image.drawText(terminalFont, 32, y + 2, item.label, selected ? 255 : 200); } if (items.length > visibleRowCount) { drawListScrollbar( @@ -1030,12 +1430,39 @@ function paintHub(window: HubWindow): GrayImage { return image; } -function hubStatusLine(): string { - if (!terminalHostSetting.get().trim()) { - return "No host configured."; +function paintAddConnection(window: HubWindow): GrayImage { + const image = new GrayImage(window.viewportWidth, window.viewportHeight, 0); + image.drawText(terminalFont, 18, 10, "Add connection", 220); + image.drawText(terminalFont, 24, 34, "Type the g2mirror://token@host string in the", 170); + image.drawText(terminalFont, 24, 48, "phone app (or use voice input from the menu).", 170); + const draft = terminalNewConnectionSetting.get(); + image.drawText(terminalFont, 24, 76, truncateLabel(draft || "(empty)", 52), 220); + if (window.addError) { + image.drawText(terminalFont, 24, 96, window.addError, 150); } - const status = controlState?.status ?? "Not connected."; - return controlReconnectTimer ? `${status} Retrying...` : status; + image.drawText(terminalFont, 24, window.viewportHeight - 24, `click save ${GESTURE_DOUBLE_CLICK} cancel`, 110); + return image; +} + +function truncateLabel(text: string, maxLength: number): string { + return text.length <= maxLength ? text : `${text.slice(0, Math.max(0, maxLength - 3))}...`; +} + +function hubStatusLine(window: HubWindow): string { + if (window.mode === "connections") { + return "Select a connection to connect, disconnect, or remove."; + } + if (controls.size === 0) { + return "No connections configured."; + } + const anyRetrying = [...controls.values()].some((control) => control.reconnectTimer); + if (controls.size === 1) { + const control = [...controls.values()][0]!; + const status = control.config.enabled ? (control.state?.status ?? "Not connected.") : "Disconnected."; + return anyRetrying ? `${status} Retrying...` : status; + } + const summary = `${connectedControls().length} of ${controls.size} hosts connected.`; + return anyRetrying ? `${summary} Retrying...` : summary; } function paintView(window: ViewWindow): GrayImage { @@ -1179,25 +1606,62 @@ function toolListLaunchPresets(): ToolResult { return { ok: true, content: presets.map((preset) => `- ${preset}`).join("\n") }; } +/** + * Pick the host a launch_session call targets: by (partial) server-name match + * when `host` is given, else the sole connected host; ambiguity is an error + * listing the choices. + */ +function resolveLaunchControl(host: string): ControlConnection | { error: string } { + const connected = connectedControls(); + if (!connected.length) return { error: "Not connected to any g2mirror server." }; + if (host) { + const matches = connected.filter((control) => + connectionDisplayName(control.config).toLowerCase().includes(host.toLowerCase()), + ); + if (matches.length === 1) return matches[0]!; + return { + error: `Host "${host}" ${matches.length ? "is ambiguous among" : "does not match any of"}: ${connected + .map((control) => connectionDisplayName(control.config)) + .join(", ")}`, + }; + } + if (connected.length === 1) return connected[0]!; + return { + error: `Multiple hosts connected; pass host: ${connected + .map((control) => connectionDisplayName(control.config)) + .join(", ")}`, + }; +} + async function toolLaunchSession(args: any): Promise { const preset = String(args?.preset ?? "").trim(); if (!preset) return { ok: false, error: "launch_session requires a preset name." }; - const phase = controlState?.phase; - if (phase !== "connected" && phase !== "attached") { - return { ok: false, error: "Not connected to the g2mirror server." }; - } - const socket = await launchAndOpenView(preset); + const control = resolveLaunchControl(String(args?.host ?? "").trim()); + if ("error" in control) return { ok: false, error: control.error }; + const socket = await launchAndOpenView(control, preset); return { ok: true, content: `Launched "${preset}" (session ${socket}) and opened a window viewing it.` }; } function toolListSessions(): ToolResult { - const sessions = controlState?.sessions ?? []; - if (!sessions.length) { - return { ok: true, content: "No live terminal sessions (run g2mirror on the host)." }; + const connected = connectedControls(); + const multiHost = connected.length > 1; + const lines: string[] = []; + for (const control of connected) { + const sessions = control.state?.sessions ?? []; + if (multiHost) { + lines.push(`${connectionDisplayName(control.config)}:`); + } + for (const session of sessions) { + const open = viewWindowIdForSocket(control.config.id, session.socket) ? " [open]" : ""; + lines.push(`- ${sessionLabel(session)}${open}`); + } + if (!sessions.length && multiHost) { + lines.push("- (no live sessions)"); + } + } + if (!lines.length) { + return { ok: true, content: "No live terminal sessions (run g2mirror on a host)." }; } - const lines = sessions.map( - (session) => `- ${sessionLabel(session)}${viewWindowIdForSocket(session.socket) ? " [open]" : ""}`, - ); return { ok: true, content: lines.join("\n") }; } diff --git a/app/g2/dashboard-controller.ts b/app/g2/dashboard-controller.ts index d233eef8..f0b2e26e 100644 --- a/app/g2/dashboard-controller.ts +++ b/app/g2/dashboard-controller.ts @@ -32,7 +32,7 @@ import { type InProcessAppOptions, type InProcessWindow } from "../ui/shell/in-p import { loadPersistedOpenApps, savePersistedOpenApps } from "../ui/shell/open-apps-persistence"; import { appViewportRect, type WindowHeightMode } from "../ui/shell/geometry"; import { type LayerActions } from "../ui/layers"; -import { assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, brightnessSetting, brightnessSettingToLevel, elevenLabsApiKeySetting, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, verticalPositionSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings"; +import { assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, brightnessSetting, brightnessSettingToLevel, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, verticalPositionSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings"; import { isIgnoringBatteryOptimizations, requestIgnoreBatteryOptimizations } from "../native/battery-optimization"; type ConnectionPhase = "disconnected" | "connecting" | "connected" | "charging" | "disconnecting"; @@ -1395,6 +1395,15 @@ class DashboardController { this.appendLog(`settings launch failed: ${this.formatError(error)}`); }); }, + startTextSettingEdit: (settingId) => { + const setting = getStringSettingById(settingId); + if (setting) { + this.startTextSettingEdit(setting); + } else { + this.appendLog(`worker requested edit of unknown setting ${settingId}`); + } + }, + endTextSettingEdit: () => this.endTextSettingEdit(), }); this.appHosts.set(appId, host); return host; diff --git a/app/native/g2mirror-client.ts b/app/native/g2mirror-client.ts index 60281ffd..c9ec9a78 100644 --- a/app/native/g2mirror-client.ts +++ b/app/native/g2mirror-client.ts @@ -41,6 +41,12 @@ export type G2MirrorState = { status: string; sessions: G2MirrorSession[]; attachedCommand: string; + /** + * server_name from the init success reply: a human-readable name for the + * machine the server runs on. "" until the handshake succeeds (or when an + * older server omits the field). + */ + serverName: string; }; /** A page of archived scrollback lines (see PROTOCOL.md "Scrollback history"). */ @@ -56,6 +62,8 @@ export type G2MirrorHistoryReply = { }; export type G2MirrorClientOptions = { + /** TLS (g2mirrors:// → wss) vs plain (g2mirror:// → ws). */ + secure: boolean; host: string; port: number; authToken: string; @@ -73,6 +81,7 @@ export class G2MirrorClient { private status = "Not connected."; private sessions: G2MirrorSession[] = []; private attachedCommand = ""; + private serverName = ""; // Scrollback archive extent: `historyNext` is the splice point (index of the // next line to be archived), `historyOldest` the oldest retained index. private historyNext = 0; @@ -104,6 +113,7 @@ export class G2MirrorClient { status: this.status, sessions: this.sessions.slice(), attachedCommand: this.attachedCommand, + serverName: this.serverName, }; } @@ -143,7 +153,7 @@ export class G2MirrorClient { start(): void { if (this.ws) return; this.stopped = false; - const url = `ws://${this.options.host}:${this.options.port}`; + const url = `${this.options.secure ? "wss" : "ws"}://${this.options.host}:${this.options.port}`; this.setState("connecting", `Connecting to ${this.options.host}:${this.options.port}...`); this.listenerProxy = new com.faceclaw.app.FaceclawWebSocketListener({ onOpen: () => { @@ -312,6 +322,9 @@ export class G2MirrorClient { switch (message.type) { case "init": + if (typeof message.server_name === "string" && message.server_name) { + this.serverName = message.server_name; + } this.setState("connected", "Connected."); this.listSessions(); this.ensureListRefreshTimer(); diff --git a/app/ui/dashboard-settings.ts b/app/ui/dashboard-settings.ts index 333c04d2..cdec5563 100644 --- a/app/ui/dashboard-settings.ts +++ b/app/ui/dashboard-settings.ts @@ -170,6 +170,15 @@ type ConfigSettingStringOptions = ConfigSettingOptions string; }; +// Every string setting by id, so isolates that can only pass an id over a +// message channel (e.g. a worker app requesting the phone text editor) can be +// resolved back to the setting instance on the main thread. +const stringSettingsById = new Map(); + +export function getStringSettingById(id: string): ConfigSettingString | null { + return stringSettingsById.get(id) ?? null; +} + export class ConfigSettingString extends ConfigSetting { readonly editorTitle: string; readonly glassesEditTitle: string; @@ -180,6 +189,7 @@ export class ConfigSettingString extends ConfigSett this.editorTitle = options.editorTitle ?? options.label; this.glassesEditTitle = options.glassesEditTitle ?? `Edit ${options.label}`; this.normalizer = options.normalize ?? ((value) => value ?? ""); + stringSettingsById.set(this.id, this); } get(): string { @@ -487,34 +497,21 @@ export const mapboxApiKeySetting = new ConfigSettingString({ description: "Mapbox public token (pk. prefix), used by the Navigate app for maps, geocoding, and directions.", }); -export const terminalHostSetting = new ConfigSettingString({ - id: "terminal-host", - label: "Host", - storageKey: "terminal.host", +/** + * Staging buffer for the Terminal app's "Add connection" flow: the worker + * asks the shell to open the phone text editor on this setting, the user + * types the g2mirror:// connection string there, and the worker reads (and + * clears) the draft when the user confirms on the glasses. Deliberately not + * listed in the Settings app; connections are managed inside the Terminal app. + */ +export const terminalNewConnectionSetting = new ConfigSettingString({ + id: "terminal-new-connection", + label: "New connection", + storageKey: "terminal.newConnectionDraft", defaultValue: "", - editorTitle: "g2mirror host (tailscale IP)", - glassesEditTitle: "Edit terminal host", - description: "Hostname or IP address (e.g. a Tailscale address) of the machine running g2mirror, for the Terminal app.", -}); - -export const terminalPortSetting = new ConfigSettingString({ - id: "terminal-port", - label: "Port", - storageKey: "terminal.port", - defaultValue: "8737", - editorTitle: "g2mirror port", - glassesEditTitle: "Edit terminal port", - description: "TCP port the g2mirror server listens on. The default is 8737.", -}); - -export const terminalAuthTokenSetting = new ConfigSettingString({ - id: "terminal-auth-token", - label: "Auth token", - storageKey: "terminal.authToken", - defaultValue: "", - editorTitle: "g2mirror auth token", - glassesEditTitle: "Edit terminal auth token", - description: "Shared secret that must match the g2mirror server's configured auth token.", + editorTitle: "g2mirror connection string (g2mirror://token@host)", + glassesEditTitle: "Add connection", + normalize: (value) => (value ?? "").replace(/[\x00-\x1f]+/g, "").trim(), }); export const terminalLaunchPresetsSetting = new ConfigSettingString({ diff --git a/app/ui/dashboard/settings-menus.ts b/app/ui/dashboard/settings-menus.ts index 2f16fa93..fc73e7fd 100644 --- a/app/ui/dashboard/settings-menus.ts +++ b/app/ui/dashboard/settings-menus.ts @@ -37,11 +37,8 @@ import { lockScreenEnabledSetting, saveVoiceRecordingsSetting, suspendEvenHubWhenScreenOffSetting, - terminalAuthTokenSetting, terminalAutoReconnectSetting, - terminalHostSetting, terminalLaunchPresetsSetting, - terminalPortSetting, terminalWakeOnBellSetting, textSettingMenuItem, timeFormatSetting, @@ -119,10 +116,9 @@ function settingsSections(): SettingsSection[] { }, { label: "Terminal", + // Connections (g2mirror:// strings) are managed inside the Terminal + // app's Manage Connections section, not here. items: [ - textSettingMenuItem(terminalHostSetting), - textSettingMenuItem(terminalPortSetting), - textSettingMenuItem(terminalAuthTokenSetting), textSettingMenuItem(terminalLaunchPresetsSetting), toggleSettingMenuItem(terminalAutoReconnectSetting), toggleSettingMenuItem(terminalWakeOnBellSetting), diff --git a/app/ui/shell/worker-window.ts b/app/ui/shell/worker-window.ts index 45d9c49f..85ae72c5 100644 --- a/app/ui/shell/worker-window.ts +++ b/app/ui/shell/worker-window.ts @@ -67,6 +67,17 @@ export type WorkerAppReply = type: "open-settings"; section?: string; } + | { + /** + * Open the phone app's text editor on a string setting (by id, resolved + * on the main thread). The worker paints its own "type on the phone" + * UI and watches the setting for changes; it must post + * end-text-setting-edit when its flow finishes. + */ + type: "start-text-setting-edit"; + settingId: string; + } + | { type: "end-text-setting-edit" } | { /** * Set or clear the app's top-bar tray icon. Pixels ride the JSON @@ -117,6 +128,10 @@ export type WorkerAppHostOptions = { requestShellRender: () => void; /** Open or focus the Settings app, optionally selecting a section. */ openSettings: (section?: string) => void; + /** Open the phone app's text editor on a string setting (by id). */ + startTextSettingEdit: (settingId: string) => void; + /** Close the phone text editor opened by startTextSettingEdit. */ + endTextSettingEdit: () => void; }; /** @@ -200,6 +215,12 @@ export class WorkerAppHost { case "open-settings": this.options.openSettings(message.section); break; + case "start-text-setting-edit": + this.options.startTextSettingEdit(message.settingId); + break; + case "end-text-setting-edit": + this.options.endTextSettingEdit(); + break; case "set-tray-icon": { let icon: GrayImage | null = null; if (message.icon) {