Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Desktop: retry the phone companion when its launch start fails, and log why (#4072)
Suhanic91b820015f6
diff --git a/electron/companion-autostart.mjs b/electron/companion-autostart.mjsnew file mode 100644index 0000000000..8bd83b7db0--- /dev/null+++ b/electron/companion-autostart.mjs@@ -0,0 +1,43 @@+// The first launch after an update is the slow one on Windows: the new files are scanned and the old companion may+// still hold its ports, so the one start at launch can time out. A paired phone then has no way in until the app is+// restarted by hand, so the launch start tries again a few times, as long as the companion is still wanted.+export const COMPANION_AUTOSTART_RETRY_DELAYS_MS = Object.freeze([5_000, 15_000, 30_000]);++/**+ * Starts the companion, retrying a failed start after each delay while `wanted()` holds. Resolves with the last state;+ * a thrown error (a policy refusal) is never retried.+ */+export async function startCompanionWithRetries({+ start,+ wanted,+ log = () => {},+ delaysMs = COMPANION_AUTOSTART_RETRY_DELAYS_MS,+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),+}) {+ let state = await start();+ for (const [index, delay] of delaysMs.entries()) {+ if (!state?.error) return state;+ log(`companion start failed: ${state.error}; trying again in ${Math.round(delay / 1000)}s (${index + 1} of ${delaysMs.length})`);+ await sleep(delay);+ if (!wanted()) {+ log("companion start retry skipped: the companion is no longer wanted");+ return state;+ }+ state = await start();+ }+ if (state?.error) log(`companion start failed: ${state.error}; giving up until the app restarts`);+ return state;+}++/**+ * The start at launch: waits for `restored` (a saved organisation policy may turn remote access off), then starts with+ * retries. Never rejects: a refusal, or a policy that could not be restored, is logged as a skipped auto-start.+ */+export function autoStartCompanion({ restored, log = () => {}, ...retry }) {+ return Promise.resolve(restored)+ .then(() => startCompanionWithRetries({ log, ...retry }))+ .catch((error) => {+ log(`companion auto-start skipped: ${error?.message ?? error}`);+ return null;+ });+}diff --git a/electron/companion-autostart.node-test.mjs b/electron/companion-autostart.node-test.mjsnew file mode 100644index 0000000000..be8496dc90--- /dev/null+++ b/electron/companion-autostart.node-test.mjs@@ -0,0 +1,120 @@+import assert from "node:assert/strict";+import test from "node:test";++import { autoStartCompanion, COMPANION_AUTOSTART_RETRY_DELAYS_MS, startCompanionWithRetries } from "./companion-autostart.mjs";++const up = { enabled: true };+const timedOut = { enabled: false, error: "the companion did not come up in time" };++function run(states, { wanted = () => true } = {}) {+ const starts = [];+ const slept = [];+ const lines = [];+ const promise = startCompanionWithRetries({+ start: async () => {+ starts.push(starts.length);+ const next = states.shift();+ if (next instanceof Error) throw next;+ return next;+ },+ wanted,+ log: (line) => lines.push(line),+ sleep: async (ms) => { slept.push(ms); },+ });+ return { promise, starts, slept, lines };+}++test("a start that comes up the first time is not retried and logs nothing", async () => {+ const { promise, starts, slept, lines } = run([up]);+ assert.deepEqual(await promise, up);+ assert.equal(starts.length, 1);+ assert.deepEqual(slept, []);+ assert.deepEqual(lines, []);+});++test("a start that times out after an update is tried again and the companion comes up", async () => {+ const { promise, starts, slept, lines } = run([timedOut, timedOut, up]);+ assert.deepEqual(await promise, up);+ assert.equal(starts.length, 3);+ assert.deepEqual(slept, COMPANION_AUTOSTART_RETRY_DELAYS_MS.slice(0, 2));+ assert.deepEqual(lines, [+ "companion start failed: the companion did not come up in time; trying again in 5s (1 of 3)",+ "companion start failed: the companion did not come up in time; trying again in 15s (2 of 3)",+ ]);+});++test("after every retry fails, the last failure is returned and the log says it gave up", async () => {+ const { promise, starts, slept, lines } = run([timedOut, timedOut, timedOut, timedOut]);+ assert.deepEqual(await promise, timedOut);+ assert.equal(starts.length, 1 + COMPANION_AUTOSTART_RETRY_DELAYS_MS.length);+ assert.deepEqual(slept, [...COMPANION_AUTOSTART_RETRY_DELAYS_MS]);+ assert.equal(lines.at(-1), "companion start failed: the companion did not come up in time; giving up until the app restarts");+});++test("a retry waiting while the companion stops being wanted does not start it", async () => {+ let wanted = true;+ const { promise, starts, lines } = run([timedOut, up], { wanted: () => wanted });+ // The person turns the phone off during the first wait.+ wanted = false;+ assert.deepEqual(await promise, timedOut);+ assert.equal(starts.length, 1);+ assert.equal(lines.at(-1), "companion start retry skipped: the companion is no longer wanted");+});++test("a refusal thrown by the start is never retried", async () => {+ const { promise, starts } = run([new Error("remote access is turned off by your organisation")]);+ await assert.rejects(promise, /turned off by your organisation/);+ assert.equal(starts.length, 1);+});++test("the delays grow and stay within a minute", () => {+ const delays = [...COMPANION_AUTOSTART_RETRY_DELAYS_MS];+ assert.deepEqual(delays, [...delays].sort((a, b) => a - b));+ assert.ok(delays.every((ms) => ms > 0 && ms <= 60_000));+ assert.throws(() => COMPANION_AUTOSTART_RETRY_DELAYS_MS.push(1));+});++test("the launch start waits for the organisation policy before the first start", async () => {+ const order = [];+ let restore;+ const restored = new Promise((resolve) => { restore = resolve; });+ const done = autoStartCompanion({+ restored,+ start: async () => { order.push("start"); return up; },+ wanted: () => true,+ sleep: async () => {},+ });+ await new Promise((resolve) => setTimeout(resolve, 10));+ assert.deepEqual(order, []);+ order.push("restored");+ restore();+ assert.deepEqual(await done, up);+ assert.deepEqual(order, ["restored", "start"]);+});++test("the launch start retries a failed start, as startCompanionWithRetries does", async () => {+ const states = [timedOut, up];+ const lines = [];+ const state = await autoStartCompanion({+ start: async () => states.shift(),+ wanted: () => true,+ log: (line) => lines.push(line),+ sleep: async () => {},+ });+ assert.deepEqual(state, up);+ assert.deepEqual(lines, ["companion start failed: the companion did not come up in time; trying again in 5s (1 of 3)"]);+});++test("a refusal or a policy that could not be restored is logged as a skipped auto-start and never rejects", async () => {+ for (const [restored, start] of [+ [undefined, async () => { throw new Error("remote access is turned off by your organisation"); }],+ [Promise.reject(new Error("policy unreadable")), async () => up],+ ]) {+ const lines = [];+ let starts = 0;+ const state = await autoStartCompanion({ restored, start: async () => { starts++; return start(); }, wanted: () => true, log: (line) => lines.push(line) });+ assert.equal(state, null);+ assert.match(lines.at(-1), /^companion auto-start skipped: (remote access is turned off by your organisation|policy unreadable)$/);+ assert.equal(starts, restored ? 0 : 1);+ }+});diff --git a/electron/main.mjs b/electron/main.mjsindex 5ddb872f1d..94ce7d48c6 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -476,6 +476,7 @@ import {startCompanion,stopCompanion,} from "./companion.mjs";+import { autoStartCompanion } from "./companion-autostart.mjs";import { createRoutineWakeHold, rememberRoutineWake, routineWakeSettings } from "./routine-wake.mjs";import { CREDENTIAL_PATCH, credentialSaveError } from "./credential-patch.mjs";@@ -3107,10 +3108,9 @@ app.whenReady().then(async () => {}void cloudAccountStarted.then(() => { cloudSignInRestored = true; void oneHome.kick(); void homeWindow.refresh(); }); void ownHome?.kick();if (!desktopRemoteAccess && serverReady && companionEnabledAtRest() && !oneHome.away() && !ownHome?.away()) {- // Wait until a saved organisation policy is known: it may turn remote access off.- void (managedDesktop?.whenRestored() ?? Promise.resolve())- .then(() => startDesktopCompanion({ waitForHosted: false, remember: false }))- .catch(error => slog(`companion auto-start skipped: ${error?.message ?? error}`));+ // Retries stop once the person turns the phone off, starts it by hand or quits.+ const wanted = () => !desktopShutdownStarted && companionEnabledAtRest() && !companionRunning() && !oneHome.away() && !ownHome?.away();+ void autoStartCompanion({ restored: managedDesktop?.whenRestored(), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }), wanted, log: slog });}setLocalOrigin(rendererOrigin());session.defaultSession.webRequest.onCompleted({ urls: ["https://*/api/*"] }, details => homeWindow.responded(details));