Python
Desktop app: a fixed port, 8765, so joined machines survive a restart
Rohit C Prasadf4c50f383773
diff --git a/coworker/server/run.py b/coworker/server/run.pyindex dbc99733..e10bcc04 100644--- a/coworker/server/run.py+++ b/coworker/server/run.py@@ -140,8 +140,8 @@ _ENGINE_LOCK = Nonedef _warn_if_state_shared() -> None:- """The desktop sidecar runs on a random port precisely so it can coexist with- a hand-run `openworker-server` on the same state dir, so this entrypoint only+ """The desktop sidecar can coexist with a hand-run `openworker-server` on the same+ state dir (the app moves to a free port when 8765 is taken), so this entrypoint onlyWARNS about a second engine (statelock.py). `openworker up` refuses outright;set COWORKER_STATE_LOCK=strict to make this server refuse too."""global _ENGINE_LOCK@@ -177,7 +177,7 @@ def main(argv=None) -> None:# Publish the ACTUAL bound port so loopback URLs (the managed-OAuth callback)# target this process, not config.port. The desktop shell runs the sidecar on- # a random free port (to coexist with a hand-run server on 8765), so the+ # port 8765, or a free port when that is taken (a hand-run server), so the# managed-connect redirect must follow the real port, not the 8765 default.os.environ["COWORKER_PORT"] = str(args.port)generated_token_path = _ensure_api_token(args.port)diff --git a/docs/remote-machines.md b/docs/remote-machines.mdindex fda8bfbe..6e735231 100644--- a/docs/remote-machines.md+++ b/docs/remote-machines.md@@ -51,8 +51,9 @@ You should see `controller: not joined` — a fresh, unenrolled machine.## Reachability: how the machine finds your desktop-The machine connects to your desktop app's local server (port 8765). Your-desktop binds to localhost only, so pick one of these:+The machine connects to your desktop app's local server on port 8765. (If 8765+is taken when the app starts, it uses another port and the Add a machine card+shows it.) Your desktop binds to localhost only, so pick one of these:**Option A — Tailscale (recommended).** Install [Tailscale](https://tailscale.com)on both computers. In the desktop app, enable listening on the tailnetdiff --git a/surfaces/gui/src-tauri/src/lib.rs b/surfaces/gui/src-tauri/src/lib.rsindex 5579a9f8..e3e94552 100644--- a/surfaces/gui/src-tauri/src/lib.rs+++ b/surfaces/gui/src-tauri/src/lib.rs@@ -1,8 +1,9 @@//! OpenWorker desktop shell.//!//! Tauri is a thin native window over the existing React SPA. It:-//! 1. picks a free localhost port and starts the Python `openworker-server` as a managed-//! sidecar on that port (so it never clashes with a hand-run server on 8765);+//! 1. starts the Python `openworker-server` as a managed sidecar on localhost port 8765+//! (a fixed port: joined machines and their tunnels keep working across restarts;+//! OPE-212), falling back to a free port only when 8765 is taken;//! 2. injects the sidecar HTTP/WS addresses and per-launch authentication token before the//! SPA loads (single codebase — the browser build still hits 8765);//! 3. lives in the system tray: closing the window hides it (keeps MyHelper + the scheduler@@ -36,11 +37,34 @@ struct ServerProcess(Mutex<Option<Child>>);/// releases the hold (kills `caffeinate` on macOS, clears the execution state on Windows).struct KeepAwake(Mutex<Option<KeepAwakeGuard>>);+/// The port machines are told to reach this app on. Fixed, so a joined machine's stored+/// address and its SSH tunnel survive an app restart (OPE-212: with a random port every+/// restart cut every machine off). The server listens on loopback and needs the launch+/// token on every request, so the port number itself protects nothing.+const DEFAULT_PORT: u16 = 8765;+fn free_port() -> u16 {std::net::TcpListener::bind("127.0.0.1:0").and_then(|l| l.local_addr()).map(|a| a.port())- .unwrap_or(8765)+ .unwrap_or(DEFAULT_PORT)+}++/// 8765 when it is free (or OPENWORKER_PORT, for developers running two copies); otherwise+/// a free port, and the Machines page says so, since tunnels to 8765 then lead nowhere.+fn choose_port() -> u16 {+ if let Some(p) = std::env::var("OPENWORKER_PORT").ok().and_then(|v| v.parse::<u16>().ok()) {+ return p;+ }+ // A restart (an update, a relaunch) can find the previous sidecar still shutting+ // down; give 8765 a few seconds to come free before settling for another port.+ for _ in 0..10 {+ if std::net::TcpListener::bind(("127.0.0.1", DEFAULT_PORT)).is_ok() {+ return DEFAULT_PORT;+ }+ std::thread::sleep(std::time::Duration::from_millis(500));+ }+ free_port()}fn launch_token() -> String {@@ -698,7 +722,7 @@ async fn install_update(}pub fn run() {- let port = free_port();+ let port = choose_port();let api_token = launch_token();let http = format!("http://127.0.0.1:{port}");let ws = format!("ws://127.0.0.1:{port}");diff --git a/surfaces/gui/src/components/MachinesSection.tsx b/surfaces/gui/src/components/MachinesSection.tsxindex 2929d9e4..06629583 100644--- a/surfaces/gui/src/components/MachinesSection.tsx+++ b/surfaces/gui/src/components/MachinesSection.tsx@@ -766,6 +766,13 @@ function AddMachineCard({<>{t("machines.add.ssh_help")}<div className="font-mono mt-1">{`ssh -N -R ${port}:localhost:${port} user@your-vm`}</div>+ {/* OPE-212: the app holds port 8765 so tunnels and joined machines survive a+ restart; only when 8765 was taken at start does it sit elsewhere. */}+ {joinUrl && port !== "8765" && (+ <div className="mt-1 text-warnInk" data-testid="machines-port-note">+ {t("machines.add.port_note", { port })}+ </div>+ )}</>) : (<>diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.jsonindex 97f5fa62..ed2c5653 100644--- a/surfaces/gui/src/locales/en.json+++ b/surfaces/gui/src/locales/en.json@@ -2035,7 +2035,8 @@"expired": "Enrollment window expired.","rearm": "Re-arm","waiting": "Waiting for the machine…",- "token_expires": "token expires in {{countdown}}"+ "token_expires": "token expires in {{countdown}}",+ "port_note": "This Mac's app is on port {{port}} because 8765 was busy when it started. Tunnels and machines set up for 8765 cannot reach it until 8765 is free and the app restarts."},"keys": {"title": "Keys on {{name}}",diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.jsonindex 668c437d..0a967356 100644--- a/surfaces/gui/src/locales/zh.json+++ b/surfaces/gui/src/locales/zh.json@@ -1996,7 +1996,8 @@"expired": "注册窗口已过期。","rearm": "重新开启","waiting": "正在等待机器…",- "token_expires": "令牌将在 {{countdown}} 后过期"+ "token_expires": "令牌将在 {{countdown}} 后过期",+ "port_note": "本机应用当前使用端口 {{port}},因为启动时 8765 被占用。为 8765 设置的隧道和机器在 8765 空出并重启应用前无法连接。"},"keys": {"title": "{{name}} 上的密钥",