From 93d98965de6a68ade72c7f291fbaa038ce6c96dc Mon Sep 17 00:00:00 2001 From: James Babcock Date: Sun, 26 Jul 2026 14:31:21 -0700 Subject: [PATCH] Add support for g2mirror lanuch presets to Terminal app --- app/native/g2mirror-client.ts | 64 ++++++++++++++++++++++ app/ui/dashboard-settings.ts | 11 ++++ app/ui/dashboard/settings-menus.ts | 2 + app/workers/terminal-app.worker.ts | 87 ++++++++++++++++++++++++++++-- 4 files changed, 161 insertions(+), 3 deletions(-) diff --git a/app/native/g2mirror-client.ts b/app/native/g2mirror-client.ts index d5d48e37..60281ffd 100644 --- a/app/native/g2mirror-client.ts +++ b/app/native/g2mirror-client.ts @@ -13,6 +13,7 @@ declare const java: any; const PROTOCOL_VERSION = 1; const SESSION_LIST_REFRESH_MS = 3_000; +const LAUNCH_REPLY_TIMEOUT_MS = 10_000; // Wrapper-side pause between submitted text and its trailing "\r". Apps that // infer pasting from bytes arriving in one read (e.g. Claude Code) would // otherwise treat the "\r" as a pasted newline instead of the Enter key. @@ -86,6 +87,14 @@ export class G2MirrorClient { private readonly sessionDetachedListeners = new Set<(reason: string) => void>(); private readonly bellListeners = new Set<(socket: string, lastBellAtMs: number) => void>(); private readonly titleListeners = new Set<(socket: string, title: string) => void>(); + // Launch requests awaiting their reply, oldest first. The server answers + // each `launch` with either `launched` or an `error` whose message starts + // with "launch failed", so replies are matched to requests in order. + private readonly pendingLaunches: Array<{ + resolve: (socket: string) => void; + reject: (error: Error) => void; + timer: ReturnType; + }> = []; constructor(private readonly options: G2MirrorClientOptions) {} @@ -172,6 +181,7 @@ export class G2MirrorClient { stop(): void { this.stopped = true; + this.rejectAllPendingLaunches("client stopped"); this.clearListRefreshTimer(); if (this.ws) { // Best effort: let the wrapped app resize back before we go away. @@ -196,6 +206,32 @@ export class G2MirrorClient { } } + /** + * Start a new detached session from a named server-side launch preset (the + * wire can only pick presets by name, never supply a command line; the + * token needs a launch grant covering the preset). Resolves with the new + * session's socket, which can then be attached like any other session. + */ + launchSession(preset: string): Promise { + return new Promise((resolve, reject) => { + if (this.phase !== "connected" && this.phase !== "attached") { + reject(new Error("Not connected to the g2mirror server.")); + return; + } + const pending = { + resolve, + reject, + timer: setTimeout(() => { + const index = this.pendingLaunches.indexOf(pending); + if (index >= 0) this.pendingLaunches.splice(index, 1); + reject(new Error(`Launch of "${preset}" timed out.`)); + }, LAUNCH_REPLY_TIMEOUT_MS), + }; + this.pendingLaunches.push(pending); + this.send({ type: "launch", command: preset }); + }); + } + connectSession(socket: string): void { if (this.phase !== "connected") return; this.setState(this.phase, "Attaching to session..."); @@ -282,6 +318,9 @@ export class G2MirrorClient { return; case "error": { const errorText = String(message.message ?? "unknown error"); + if (errorText.startsWith("launch failed") && this.pendingLaunches.length) { + this.settlePendingLaunch(null, errorText); + } if (this.phase === "connecting") { // Handshake rejection; the server closes the socket after this. this.setState("failed", `Rejected: ${errorText}`); @@ -327,6 +366,12 @@ export class G2MirrorClient { this.emitState(); return; } + case "launched": { + const socket = String(message.socket ?? ""); + this.settlePendingLaunch(socket, `launch reply carried no socket`); + this.listSessions(); + return; + } case "connect": { // Session accepted us (relayed from the wrapper). this.clearListRefreshTimer(); @@ -398,7 +443,26 @@ export class G2MirrorClient { } } + /** Settle the oldest pending launch: resolve with `socket` if non-empty, else reject. */ + private settlePendingLaunch(socket: string | null, errorText: string): void { + const pending = this.pendingLaunches.shift(); + if (!pending) return; + clearTimeout(pending.timer); + if (socket) { + pending.resolve(socket); + } else { + pending.reject(new Error(errorText)); + } + } + + private rejectAllPendingLaunches(reason: string): void { + while (this.pendingLaunches.length) { + this.settlePendingLaunch(null, reason); + } + } + private handleConnectionLost(statusText: string): void { + this.rejectAllPendingLaunches("connection lost"); this.clearListRefreshTimer(); this.ws = null; this.listenerProxy = null; diff --git a/app/ui/dashboard-settings.ts b/app/ui/dashboard-settings.ts index 62f8a241..ab3329bf 100644 --- a/app/ui/dashboard-settings.ts +++ b/app/ui/dashboard-settings.ts @@ -427,6 +427,17 @@ export const terminalAuthTokenSetting = new ConfigSettingString({ description: "Shared secret that must match the g2mirror server's configured auth token.", }); +export const terminalLaunchPresetsSetting = new ConfigSettingString({ + id: "terminal-launch-presets", + label: "Launch presets", + storageKey: "terminal.launchPresets", + defaultValue: "shell", + editorTitle: "g2mirror launch presets (comma-separated)", + glassesEditTitle: "Edit launch presets", + description: + "Comma-separated names of g2mirror launch presets that can be started from the glasses. Presets are defined in the server's config; the wire protocol has no way to list them, so name them here. The default server config defines \"shell\".", +}); + export const nightscoutSiteUrlSetting = new ConfigSettingString({ id: "nightscout-site-url", label: "Nightscout site URL", diff --git a/app/ui/dashboard/settings-menus.ts b/app/ui/dashboard/settings-menus.ts index 7ce6afcd..2e34d748 100644 --- a/app/ui/dashboard/settings-menus.ts +++ b/app/ui/dashboard/settings-menus.ts @@ -18,6 +18,7 @@ import { suspendEvenHubWhenScreenOffSetting, terminalAuthTokenSetting, terminalHostSetting, + terminalLaunchPresetsSetting, terminalPortSetting, textSettingMenuItem, timeFormatSetting, @@ -81,6 +82,7 @@ function settingsSections(): SettingsSection[] { textSettingMenuItem(terminalHostSetting), textSettingMenuItem(terminalPortSetting), textSettingMenuItem(terminalAuthTokenSetting), + textSettingMenuItem(terminalLaunchPresetsSetting), ], }, { diff --git a/app/workers/terminal-app.worker.ts b/app/workers/terminal-app.worker.ts index d259a620..9d828ddc 100644 --- a/app/workers/terminal-app.worker.ts +++ b/app/workers/terminal-app.worker.ts @@ -27,6 +27,7 @@ import { clamp } from "../util/numeric-util"; import { terminalAuthTokenSetting, terminalHostSetting, + terminalLaunchPresetsSetting, terminalPortSetting, } from "../ui/dashboard-settings"; import { TerminalEmulator } from "../ui/apps/terminal-emulator"; @@ -139,6 +140,28 @@ const TERMINAL_TOOLS: ToolSpec[] = [ inputSchema: { type: "object", properties: {}, additionalProperties: false }, availability: "open", }, + { + name: "list_launch_presets", + description: + "List the named launch presets that can start a new terminal session on the 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.", + inputSchema: { + type: "object", + properties: { + preset: { type: "string", description: "Name of the launch preset to start." }, + }, + required: ["preset"], + additionalProperties: false, + }, + availability: "open", + timeoutMs: 15_000, + }, ]; let viewportWidth = 0; let viewportHeight = 0; @@ -230,6 +253,8 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { // in the dashboard's Settings menu, which lives in the main isolate). onSettingsStoreChanged((key) => { if (!key.startsWith("terminal.")) return; + // The preset list only feeds menus and tool replies; no reconnect needed. + if (key === "terminal.launchPresets") return; if (gridCols > 0) { startControlClient(); } @@ -436,6 +461,18 @@ function windowMenuItems(window: TerminalWindow): MenuItem[] { if (window.kind === "hub") { const phase = controlState?.phase; if (phase === "connected" || phase === "attached") { + for (const preset of launchPresetNames()) { + items.push({ + label: `Launch ${preset}`, + onSelect: (ctx) => { + ctx.stack.pop(); + launchAndOpenView(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) => { @@ -623,12 +660,33 @@ function viewWindowIdForSocket(socket: string): string | null { } function openViewWindowFor(session: G2MirrorSession): void { + openViewWindow(session.socket, sessionLabel(session)); +} + +function openViewWindow(socket: string, label: string): void { const windowId = `terminal:view:${nextViewSerial++}`; - const label = sessionLabel(session); - pendingViews.set(windowId, { socket: session.socket, label }); + pendingViews.set(windowId, { socket, label }); post({ type: "open-window-request", windowId, title: label, iconLetter: "T", icon: "terminal", focus: true }); } +/** Preset names the user listed in Settings > Terminal (the wire protocol has no way to enumerate the server's). */ +function launchPresetNames(): string[] { + const names: string[] = []; + for (const piece of terminalLaunchPresetsSetting.get().split(",")) { + const name = piece.trim(); + if (name && !names.includes(name)) names.push(name); + } + 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); + return socket; +} + function paint(window: TerminalWindow): GrayImage { if (window.menu?.isOpen()) { return window.menu.paint(); @@ -800,7 +858,7 @@ function sessionLabel(session: G2MirrorSession): string { } /** Dispatch an assistant tool-call (unprefixed name) to its handler. */ -function handleTerminalTool(name: string, args: any): ToolResult { +function handleTerminalTool(name: string, args: any): ToolResult | Promise { switch (name) { case "list_sessions": return toolListSessions(); @@ -808,11 +866,34 @@ function handleTerminalTool(name: string, args: any): ToolResult { return toolSendInput(args); case "read_screen": return toolReadScreen(); + case "list_launch_presets": + return toolListLaunchPresets(); + case "launch_session": + return toolLaunchSession(args); default: return { ok: false, error: `Unknown terminal tool: ${name}` }; } } +function toolListLaunchPresets(): ToolResult { + const presets = launchPresetNames(); + if (!presets.length) { + return { ok: true, content: "No launch presets configured (Settings > Terminal > Launch presets)." }; + } + return { ok: true, content: presets.map((preset) => `- ${preset}`).join("\n") }; +} + +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); + return { ok: true, content: `Launched "${preset}" (session ${socket}) and opened a window viewing it.` }; +} + function toolListSessions(): ToolResult { const sessions = controlState?.sessions ?? []; if (!sessions.length) {