Terminal connection string management, multi-host
This commit is contained in:
1 parent
6f45888627
commit
6df7e9bc81
7 files changed
+825
-225
No files matched your search
@@ -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://<token>@<host>[: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<Omit<TerminalConnection, "id">>): void {
|
||||
const connections = loadConnections();
|
||||
const connection = connections.find((candidate) => candidate.id === id);
|
||||
if (!connection) return;
|
||||
Object.assign(connection, update);
|
||||
saveConnections(connections);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -170,6 +170,15 @@ type ConfigSettingStringOptions<TId extends string> = ConfigSettingOptions<strin
|
||||
normalize?: (value: string | null | undefined) => 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<string, ConfigSettingString>();
|
||||
|
||||
export function getStringSettingById(id: string): ConfigSettingString | null {
|
||||
return stringSettingsById.get(id) ?? null;
|
||||
}
|
||||
|
||||
export class ConfigSettingString<TId extends string = string> extends ConfigSetting<string, TId> {
|
||||
readonly editorTitle: string;
|
||||
readonly glassesEditTitle: string;
|
||||
@@ -180,6 +189,7 @@ export class ConfigSettingString<TId extends string = string> 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({
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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) {
|
||||
|
||||
Reference in new issue
Block a user