Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Always-on home: add a Mac mini (or any spare computer) as your own Cloud
milind-soni3baee1b12376
diff --git a/electron/always-on-home.mjs b/electron/always-on-home.mjsnew file mode 100644index 0000000000..66710afb45--- /dev/null+++ b/electron/always-on-home.mjs@@ -0,0 +1,114 @@+// "Use this computer as an always-on home" (Settings → Phone & devices): one switch for a spare computer, such as a Mac+// mini, that runs the person's bots all day. It turns on what the app already has (Open at login, the updater's quiet+// install, the server supervisor's recovery) and adds one thing of its own: the computer stays awake while it is on+// power. Turning it off undoes only what turning it on changed: a login item the person had set up stays.+import fs from "node:fs";+import path from "node:path";++export const ALWAYS_ON_FILE = "always-on-home.json";+/** Electron's powerSaveBlocker type that keeps the system from idle sleep and lets the display turn off. */+export const ALWAYS_ON_BLOCKER = "prevent-app-suspension";+export const ALWAYS_ON_LOOK_MS = 60_000;+const UPDATES = new Set(["by-itself", "restart", "package", "none"]);++/** The saved switch: `{ v: 1, on, addedLogin }`; anything else reads as off. `addedLogin`: turning it on added the login item. */+export function parseAlwaysOn(value) {+ if (!value || typeof value !== "object" || value.v !== 1) return { v: 1, on: false, addedLogin: false };+ return { v: 1, on: value.on === true, addedLogin: value.on === true && value.addedLogin === true };+}++/**+ * `loginItem`: open-at-login.mjs's item (`available`, `chosen`, `choose`). `blocker`: Electron's powerSaveBlocker.+ * `isOnBattery()`: powerMonitor's word. `updates()`: how an update arrives with nobody at the computer (updater.mjs+ * `unattendedUpdates`). `platform`: process.platform.+ */+export function createAlwaysOnHome({ file, loginItem, blocker, isOnBattery, updates = () => "none", platform = process.platform, log = () => {}, lookMs = ALWAYS_ON_LOOK_MS }) {+ let saved = read();+ let blockerId = null;+ let timer = null;++ function read() {+ try { return parseAlwaysOn(JSON.parse(fs.readFileSync(file, "utf8"))); } catch { return parseAlwaysOn(null); }+ }+ function write(next) {+ saved = next;+ const temporary = `${file}.${process.pid}.tmp`;+ try {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(temporary, JSON.stringify(next));+ fs.renameSync(temporary, file);+ } catch {+ try { fs.unlinkSync(temporary); } catch {}+ }+ }+ const battery = () => { try { return isOnBattery() === true; } catch { return false; } };+ const loginOn = () => { try { return loginItem.chosen() === true; } catch { return false; } };++ function look() {+ const hold = saved.on && !battery();+ if (hold && blockerId === null) {+ blockerId = blocker.start(ALWAYS_ON_BLOCKER);+ log("always-on home: holding this computer awake while it is on power");+ } else if (!hold && blockerId !== null) {+ if (blocker.isStarted(blockerId)) blocker.stop(blockerId);+ blockerId = null;+ log(`always-on home: released the awake hold (${saved.on ? "on battery" : "off"})`);+ }+ }++ function state() {+ const kind = updates();+ return {+ available: loginItem.available() === true,+ on: saved.on,+ platform,+ openAtLogin: loginOn(),+ awake: !saved.on ? "off" : battery() ? "battery" : "holding",+ updates: UPDATES.has(kind) ? kind : "none",+ };+ }++ return {+ state,+ look,+ on: () => saved.on,+ set(on) {+ const want = on === true;+ if (want === saved.on) { look(); return state(); }+ let addedLogin = false;+ try {+ if (want && !loginOn()) { loginItem.choose(true); addedLogin = true; }+ else if (!want && saved.addedLogin && loginOn()) loginItem.choose(false);+ } catch (error) {+ log(`always-on home: login item: ${error?.message ?? error}`);+ }+ write({ v: 1, on: want, addedLogin });+ look();+ return state();+ },+ /** `powerMonitor`: plugging in or unplugging changes the hold at once, not at the next look. */+ start(powerMonitor = null) {+ look();+ if (timer) return;+ for (const event of ["on-ac", "on-battery"]) { try { powerMonitor?.on(event, look); } catch {} }+ timer = setInterval(look, lookMs);+ timer.unref?.();+ },+ stop() {+ if (timer) clearInterval(timer);+ timer = null;+ if (blockerId !== null && blocker.isStarted(blockerId)) blocker.stop(blockerId);+ blockerId = null;+ },+ holding: () => blockerId !== null,+ };+}++/** The switch and Settings' channels for it, on this computer's own page (`guard`). `changed()` redraws what shows Open+ * at login elsewhere (the app menu). Nothing is held until `start()`, once the app is ready. */+export function installAlwaysOnHome({ ipcMain, guard, changed = () => {}, ...options }) {+ const home = createAlwaysOnHome(options);+ ipcMain.handle("always-on-home:state", guard("always-on-home:state", () => home.state()));+ ipcMain.handle("always-on-home:set", guard("always-on-home:set", (_event, on) => { const next = home.set(on === true); changed(); return next; }));+ return home;+}diff --git a/electron/always-on-home.node-test.mjs b/electron/always-on-home.node-test.mjsnew file mode 100644index 0000000000..e5d6787069--- /dev/null+++ b/electron/always-on-home.node-test.mjs@@ -0,0 +1,118 @@+import assert from "node:assert/strict";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import test from "node:test";++import { ALWAYS_ON_BLOCKER, createAlwaysOnHome, installAlwaysOnHome, parseAlwaysOn } from "./always-on-home.mjs";++function fixture(t, { login = false, battery = false, available = true, updates = "by-itself", platform = "darwin" } = {}) {+ const dir = mkdtempSync(path.join(tmpdir(), "omb-always-on-"));+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ const world = { login, battery, chose: [], held: new Set(), started: [], nextId: 1 };+ const loginItem = { available: () => available, chosen: () => world.login, choose: (on) => { world.chose.push(on); world.login = on; } };+ const blocker = {+ start: (type) => { const id = world.nextId++; world.started.push(type); world.held.add(id); return id; },+ stop: (id) => { world.held.delete(id); },+ isStarted: (id) => world.held.has(id),+ };+ const file = path.join(dir, "always-on-home.json");+ const make = () => createAlwaysOnHome({ file, loginItem, blocker, isOnBattery: () => world.battery, updates: () => updates, platform, lookMs: 3_600_000 });+ return { world, file, make, home: make() };+}++test("the saved switch reads only its own shape; anything else is off", () => {+ assert.deepEqual(parseAlwaysOn(null), { v: 1, on: false, addedLogin: false });+ assert.deepEqual(parseAlwaysOn({ v: 2, on: true }), { v: 1, on: false, addedLogin: false });+ assert.deepEqual(parseAlwaysOn({ v: 1, on: "yes", addedLogin: true }), { v: 1, on: false, addedLogin: false });+ assert.deepEqual(parseAlwaysOn({ v: 1, on: true, addedLogin: true }), { v: 1, on: true, addedLogin: true });+});++test("on: opens at login, holds the computer awake on power, and says how updates arrive", (t) => {+ const f = fixture(t);+ assert.deepEqual(f.home.state(), { available: true, on: false, platform: "darwin", openAtLogin: false, awake: "off", updates: "by-itself" });+ const state = f.home.set(true);+ assert.deepEqual(state, { available: true, on: true, platform: "darwin", openAtLogin: true, awake: "holding", updates: "by-itself" });+ assert.deepEqual(f.world.chose, [true]);+ assert.deepEqual(f.world.started, [ALWAYS_ON_BLOCKER]);+ assert.equal(f.home.holding(), true);+ assert.equal(f.home.on(), true);+ assert.deepEqual(JSON.parse(readFileSync(f.file, "utf8")), { v: 1, on: true, addedLogin: true });+ f.home.set(true);+ assert.equal(f.world.started.length, 1, "asking again holds nothing twice");+ f.home.stop();+});++test("on battery the hold lets go, and comes back once the computer is plugged in", (t) => {+ const f = fixture(t);+ f.home.set(true);+ f.world.battery = true;+ f.home.look();+ assert.equal(f.home.holding(), false);+ assert.equal(f.home.state().awake, "battery");+ f.world.battery = false;+ f.home.look();+ assert.equal(f.home.holding(), true);+ f.home.stop();+ assert.equal(f.world.held.size, 0, "stop releases the hold");+});++test("off undoes only what on changed: a login item the person set up stays", (t) => {+ const added = fixture(t);+ added.home.set(true);+ added.home.set(false);+ assert.deepEqual(added.world.chose, [true, false], "the login item the switch added goes");+ assert.equal(added.home.holding(), false);+ assert.equal(added.home.state().awake, "off");++ const theirs = fixture(t, { login: true });+ theirs.home.set(true);+ theirs.home.set(false);+ assert.deepEqual(theirs.world.chose, [], "the person's own login item is never touched");+ assert.equal(theirs.world.login, true);+});++test("the switch survives a restart, and a fresh launch holds the computer awake again", (t) => {+ const f = fixture(t);+ f.home.set(true);+ f.home.stop();+ const again = f.make();+ assert.equal(again.on(), true);+ again.start();+ assert.equal(again.holding(), true);+ again.set(false);+ assert.deepEqual(f.world.chose, [true, false], "what the first launch added is still known after a restart");+ again.stop();+});++test("a damaged file reads as off, and a failing login item still saves the choice", (t) => {+ const f = fixture(t);+ writeFileSync(f.file, "{not json");+ assert.equal(f.make().on(), false);+ const home = createAlwaysOnHome({ file: f.file, loginItem: { available: () => true, chosen: () => false, choose: () => { throw new Error("denied"); } },+ blocker: { start: () => 1, stop: () => {}, isStarted: () => true }, isOnBattery: () => false });+ const state = home.set(true);+ assert.equal(state.on, true);+ assert.equal(state.openAtLogin, false, "Settings then says Open at login is off");+ home.stop();+});++test("an updater that names no way reads as none", (t) => {+ const f = fixture(t, { updates: "sideways", available: false, platform: "linux" });+ assert.deepEqual(f.home.state(), { available: false, on: false, platform: "linux", openAtLogin: false, awake: "off", updates: "none" });+});++test("Settings' channels go through main's guard, and set takes only true as on", async (t) => {+ const f = fixture(t);+ const handlers = new Map(), guarded = [];+ let changed = 0;+ const home = installAlwaysOnHome({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, guard: (channel, handler) => { guarded.push(channel); return handler; },+ changed: () => changed++, file: f.file, loginItem: { available: () => true, chosen: () => f.world.login, choose: (on) => { f.world.login = on; } },+ blocker: { start: () => 1, stop: () => {}, isStarted: () => false }, isOnBattery: () => false });+ assert.deepEqual(guarded, ["always-on-home:state", "always-on-home:set"]);+ assert.equal((await handlers.get("always-on-home:set")({}, "true")).on, false, "a string is not a yes");+ assert.equal((await handlers.get("always-on-home:set")({}, true)).on, true);+ assert.equal((await handlers.get("always-on-home:state")({})).on, true);+ assert.equal(changed, 2);+ home.stop();+});diff --git a/electron/bridge-contract.json b/electron/bridge-contract.jsonindex 0b8899bfad..e2f4db5fd7 100644--- a/electron/bridge-contract.json+++ b/electron/bridge-contract.json@@ -4,6 +4,9 @@"0.1.136"],"paths": [+ "alwaysOnHome",+ "alwaysOnHome.set",+ "alwaysOnHome.state","androidDevice","androidDevice.frame","androidDevice.input",diff --git a/electron/cloud-rail.mjs b/electron/cloud-rail.mjsindex 6f1fbd1757..2f9bd7bd3a 100644--- a/electron/cloud-rail.mjs+++ b/electron/cloud-rail.mjs@@ -206,8 +206,9 @@ export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, besconst client = account();return { outcome: client?.hideCloud ? (await client.hideCloud(place.cloudId)).outcome : "unsupported" };});- // Make … my home, from a circle's menu: only a server main listed with it, by main's own word for it.- listed("workspaces:make-home", (_event, id) => {+ // Make … my home, from a circle's menu or Settings → Phone & devices on this computer's own page (`trusted`): only a server+ // main listed with it, by main's own word for it.+ handle("workspaces:make-home", (_event, id) => {const place = places().find(entry => entry.id === plain(id) && entry.makeHome);if (!place || !makeHome) throw new Error(t("native.home.notAvailable"));return makeHome(place.id);diff --git a/electron/cloud-rail.node-test.mjs b/electron/cloud-rail.node-test.mjsindex 79d3b60523..a53127bc72 100644--- a/electron/cloud-rail.node-test.mjs+++ b/electron/cloud-rail.node-test.mjs@@ -326,7 +326,7 @@ test("Remove from list from a circle's menu: only the rail's own page, only a ciassert.deepEqual(making.opened, ["cloud:c-b"], "its own screen, never a saved place or an address");});-test("Make … my home: only on a server connected by hand that main offers it for, from the rail's own page, by main's own word for it", async () => {+test("Make … my home: only on a server connected by hand that main offers it for, from the rail's or this computer's own page, by main's own word for it", async () => {const offered = new Set(["vps"]), made = [];const r = rail({ places: () => railPlaces({ saved: saved("home", [{ id: "box", kind: "remote", name: "Box", origin: "https://box.example.test" }]), home: HOME, mine: HOME, state: session(),offers: entry => offered.has(entry.id) || entry.id === "home" || entry.id === "a" || entry.id === "acme" }), makeHome: id => { made.push(id); return { started: true }; } });@@ -339,7 +339,10 @@ test("Make … my home: only on a server connected by hand that main offers it fassert.deepEqual(made, ["vps"]);offered.clear();assert.throws(() => r.call("workspaces:make-home", "vps"), /can't be your bots' home/, "no longer offered: refused");+ offered.add("vps");r.w.lists = false;+ assert.deepEqual(await r.call("workspaces:make-home", "vps"), { started: true }, "this computer's own page (Settings → Phone & devices)");+ r.w.trusted = false;assert.throws(() => r.call("workspaces:make-home", "vps"), /only available/, "any other page: refused");assert.throws(() => rail().call("workspaces:make-home", "vps"), /can't be your bots' home/, "a main that offers it nowhere");});diff --git a/electron/main.mjs b/electron/main.mjsindex 0696e1b7af..b1234039b7 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -13,7 +13,7 @@ import { installTalk, isTalkPanel } from "./talk-main.mjs";import { openBlankTerminal } from "./terminal-launch.mjs";import { linuxDisablesGpu, SOFTWARE_RENDERING_ARG } from "./linux-gpu.mjs";import { pasteMenuItem } from "./paste-menu-item.mjs";-import { attachUpdaterWindow, startUpdater, registerUpdaterIpc, sendUpdaterState, reopenedOutOfSight, quietSignals } from "./updater.mjs";+import { attachUpdaterWindow, startUpdater, registerUpdaterIpc, sendUpdaterState, reopenedOutOfSight, quietSignals, unattendedUpdates } from "./updater.mjs"; import { installAlwaysOnHome } from "./always-on-home.mjs";import {appendDesktopCrashRecord,buildDiagnosticsReport,@@ -297,7 +297,7 @@ const desktopLaunchId = randomUUID();const companionMutationToken = randomBytes(32).toString("base64url");const serverSupervisor = createServerSupervisor({restart: () => startServerOn(SERVER_PORT),- stop: stopUtilityServer,+ stop: stopUtilityServer, keepTrying: () => alwaysOnHome.on(),onReady(proc) {serverProc = proc;serverReady = true;@@ -1456,7 +1456,7 @@ function reconnectCloud(origin) {return signInCloudSession({ origin, mine: other ? origin : myCloud(), pair: () => ensureCloudAccount().pairHome(other?.id ?? null), fetch: (...args) => session.defaultSession.fetch(...args) });}const loginItem = createOpenAtLogin({ app, file: path.join(app.getPath("userData"), "open-at-login.json"), home: os.homedir() });-installOpenAtLogin({ ipcMain, guard: localOrHome, loginItem, changed: refreshApplicationMenu });+installOpenAtLogin({ ipcMain, guard: localOrHome, loginItem, changed: refreshApplicationMenu }); const alwaysOnHome = installAlwaysOnHome({ ipcMain, guard: localOnly, loginItem, changed: refreshApplicationMenu, file: path.join(app.getPath("userData"), "always-on-home.json"), blocker: powerSaveBlocker, isOnBattery: () => powerMonitor.isOnBatteryPower(), updates: unattendedUpdates, log: slog });let hiddenStart = false;async function openCloudSettings() {@@ -3070,7 +3070,7 @@ app.whenReady().then(async () => {slog("skipping connected-apps registration: the credential store was unreadable this launch");}checkInManagedComposio();- startUpdater(quietSignals({ powerMonitor, window: () => mainWindow, lastInput: oneHome.lastInput, local: localServerRequest, place: () => homeWindow.placeOrigin(), cloudFetch: (...args) => session.defaultSession.fetch(...args), asleep: origin => homeWindow.asleepAt(origin), busy: () => ((oneHome.oneHome.busy() || ownHome?.busy()) && "move") || (computerSharing?.busy() && "lending") || (talk.busy() && "talk") || (companyBackupController || companyRestoreCommitting ? "backup" : null) }));+ startUpdater(quietSignals({ powerMonitor, window: () => mainWindow, lastInput: oneHome.lastInput, local: localServerRequest, place: () => homeWindow.placeOrigin(), cloudFetch: (...args) => session.defaultSession.fetch(...args), asleep: origin => homeWindow.asleepAt(origin), busy: () => ((oneHome.oneHome.busy() || ownHome?.busy()) && "move") || (computerSharing?.busy() && "lending") || (talk.busy() && "talk") || (companyBackupController || companyRestoreCommitting ? "backup" : null) })); alwaysOnHome.start(powerMonitor);refreshApplicationMenu();openWindowForLink = () => {if (!mainWindow || mainWindow.isDestroyed()) createWindow({ deferNavigation: homeWindow.current().kind !== "computer" });@@ -3084,7 +3084,7 @@ app.whenReady().then(async () => {const allWindowsClosedQuit = createAllWindowsClosedQuit({app,- allWindows: () => appWindows(), stayOpen: () => hiddenStart,+ allWindows: () => appWindows(), stayOpen: () => hiddenStart || alwaysOnHome.on(),});// The embedded CUA daemon's async cleanup cannot run after the host exits, so the first quit waits for it (capped).diff --git a/electron/preload.cjs b/electron/preload.cjsindex 8330723f07..fac80adac3 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -436,6 +436,10 @@ const bridge = {openHtmlInBrowser: (source, name) => invokeWithPlainError("desktop:open-html", source, name),// This app's own logs folder (server.log, desktop-crashes.log, updater.log); the page names no path.openLogsFolder: () => ipcRenderer.invoke("desktop:open-logs"),+ alwaysOnHome: {+ state: () => ipcRenderer.invoke("always-on-home:state"),+ set: on => ipcRenderer.invoke("always-on-home:set", on === true),+ },openAtLogin: {state: () => ipcRenderer.invoke("open-at-login:state"),set: on => on !== true || isLocalPage || navigator.userActivation?.isActive === truediff --git a/electron/server-supervisor.mjs b/electron/server-supervisor.mjsindex 3454df0c17..c0f2687440 100644--- a/electron/server-supervisor.mjs+++ b/electron/server-supervisor.mjs@@ -1,4 +1,5 @@-// Owns one child, including while its health probe is pending; recovery retries the established port.+// Owns one child, including while its health probe is pending; recovery retries the established port. `keepTrying()`:+// the computer is an always-on home, so a spent budget waits `longRetryMs` and starts over instead of giving up.export function createServerSupervisor({restart,stop,@@ -8,6 +9,8 @@ export function createServerSupervisor({log = () => {},retryDelaysMs = [1_000, 2_000, 4_000],stableUptimeMs = 60_000,+ keepTrying = () => false,+ longRetryMs = 5 * 60_000,now = () => performance.now(),}) {let current = null;@@ -29,12 +32,18 @@ export function createServerSupervisor({function schedule() {if (stopped || paused) return;- if (attempts === retryDelaysMs.length) {+ let delay;+ if (attempts < retryDelaysMs.length) {+ delay = retryDelaysMs[attempts++];+ log(`server recovery attempt ${attempts}/${retryDelaysMs.length} in ${delay}ms`);+ } else if (keepTrying()) {+ attempts = 0;+ delay = longRetryMs;+ log(`server recovery: always-on home, trying again in ${delay}ms`);+ } else {onExhausted();return;}- const delay = retryDelaysMs[attempts++];- log(`server recovery attempt ${attempts}/${retryDelaysMs.length} in ${delay}ms`);timer = setTimeout(async () => {timer = null;if (paused) return;diff --git a/electron/server-supervisor.node-test.mjs b/electron/server-supervisor.node-test.mjsindex fba7384efc..6ee77a91b6 100644--- a/electron/server-supervisor.node-test.mjs+++ b/electron/server-supervisor.node-test.mjs@@ -77,6 +77,30 @@ test("crash clears readiness immediately, backs off, and exhausts a bounded budgassert.equal(f.children.length, 4);});+test("an always-on home never gives up: a spent budget waits the long delay and starts over, with no dialog", async (t) => {+ let home = true;+ const f = fixture(t, { keepTrying: () => home, longRetryMs: 500 });+ const crash = () => f.children.at(-1).emit("exit", 1);+ f.supervisor.ready(f.spawn());+ for (const delay of [10, 20, 40]) { crash(); await f.tick(delay); }+ assert.equal(f.children.length, 4);+ crash();+ await f.tick(499);+ assert.equal(f.children.length, 4, "the long wait, not a fourth quick try");+ assert.equal(f.events.some(([kind]) => kind === "exhausted"), false);+ await f.tick(1);+ assert.equal(f.children.length, 5);+ crash();+ await f.tick(10);+ assert.equal(f.children.length, 6, "after the long wait the quick tries start over");+ home = false;+ for (const delay of [20, 40]) { crash(); await f.tick(delay); }+ crash();+ assert.deepEqual(f.events.at(-1), ["exhausted"], "turned off: the budget ends as before");+ await f.tick(1000);+ assert.equal(f.children.length, 8);+});+test("only a stable ready uptime resets the recovery budget", async (t) => {const f = fixture(t);f.supervisor.ready(f.spawn());diff --git a/electron/updater.mjs b/electron/updater.mjsindex 5000bb9889..02665809f3 100644--- a/electron/updater.mjs+++ b/electron/updater.mjs@@ -175,6 +175,14 @@ export function registerUpdaterIpc({ pageAllowed: allowed, serverPage = () => nu}));}+/** How an update reaches this computer with nobody at it: installed at a quiet moment ("by-itself"), on the person's+ * Restart ("restart"), through their package manager ("package"), or not at all from this app ("none"). */+export function unattendedUpdates() {+ if (!updaterCoordinator) return "none";+ if (quiet) return "by-itself";+ return state.installMode === "handoff" ? "package" : "restart";+}+// macOS keeps the process (and updater) alive after its window closes, so each new window is retargeted here.export function attachUpdaterWindow(mainWindow) {win = mainWindow;diff --git a/shared/settings-places.ts b/shared/settings-places.tsindex 5ee0872cb3..d026ba183e 100644--- a/shared/settings-places.ts+++ b/shared/settings-places.ts@@ -36,6 +36,8 @@ export const SETTINGS_PLACES = [{"id":"relay","path":"Settings → Phone & devices → How your phone reaches this computer → Anywhere, through MausBot","words":["anywhere","relay","away"],"only":"the desktop app, on this computer's own page"},{"id":"keep-awake","path":"Settings → Phone & devices → How your phone reaches this computer → Keep this computer awake","words":["sleep","awake","overnight","scheduled"],"only":"the desktop app, on this computer's own page"},{"id":"wake-automations","path":"Automations, in the sidebar","words":["keep this computer awake for scheduled automations","awake"]},+ {"id":"always-on","path":"Settings → Phone & devices → Always-on home → Use this computer as an always-on home","words":["always on","always-on","home server","spare computer","mac mini","mini","server at home","run all day","24/7","open at login","awake"],"only":"the desktop app, on this computer's own page"},+ {"id":"add-always-on","path":"Settings → Phone & devices → Always-on home → Add a Mac mini or other always-on computer","words":["add a mac mini","add mac mini","add a computer","add always-on computer","mac mini","mini","home server","spare computer","move my bots"],"only":"the desktop app, on this computer's own page"},{"id":"other-computers","path":"Settings → Phone & devices → Your other computers","words":["tailscale","other computers","another computer","other computer","my other computer","computer","computers","laptop","desktop","mac","pc","share","tailnet","connect to a server"],"only":"the desktop app, on this computer's own page"},{"id":"tailscale","path":"Settings → Phone & devices → How your phone reaches this computer → More ways in","words":["tailscale","https","tailnet"],"advanced":true,"only":"the desktop app, on this computer's own page"},{"id":"domain","path":"Settings → (the place's own name, at the top) → Address","words":["domain","dns","https","custom domain"],"advanced":true,"only":"a Cloud's or server's own page"},diff --git a/src/components/AlwaysOnHomeSection.dom.test.ts b/src/components/AlwaysOnHomeSection.dom.test.tsnew file mode 100644index 0000000000..cb1e80ed0d--- /dev/null+++ b/src/components/AlwaysOnHomeSection.dom.test.ts@@ -0,0 +1,189 @@+// @vitest-environment happy-dom+// The section against a fake preload bridge: the switch on the spare computer, and adding one from the main computer.+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { setLocale } from "@/lib/i18n";+import type { CompanionState, PhoneSetupController } from "./PhoneSetupFlow";++const sessions = vi.hoisted(() => ({ list: [] as unknown[] }));+vi.mock("@/state/store", () => ({ useStore: () => ({ state: { config: {} } }), api: async () => ({ sessions: sessions.list }) }));+vi.mock("./PlaceAddSheet", async () => {+ const { createElement: h } = await import("react");+ return {+ RailSheet: ({ children }: { children: unknown }) => h("div", { "data-rail-sheet": "" }, children as never),+ OwnServerLink: () => h("div", { "data-own-server-link": "" }),+ };+});++const { AlwaysOnHomeSection, alwaysOnLines, homeStatusLine, systemSettingLines } = await import("./AlwaysOnHomeSection");++const off = { on: false, since: null };+const companionState = (devices = 0, computers = false): CompanionState => ({+ enabled: true, keepAwake: false, port: 8810, pairing: null,+ devices: Array.from({ length: devices }, (_, index) => ({ id: `p${index}`, name: `Phone ${index}`, createdAt: 1, lastSeenAt: 1, cloudDesktopAccess: false })),+ routes: { wifi: { on: true, since: 1 }, relay: off, tailscale: computers ? { on: true, since: 1, name: "mini", computers: true } : off, https: off } as CompanionState["routes"],+});+const home = (over: Partial<AlwaysOnHomeState> = {}): AlwaysOnHomeState =>+ ({ available: true, on: false, platform: "darwin", openAtLogin: false, awake: "off", updates: "by-itself", ...over });++let host: HTMLDivElement;+let root: Root;+const $ = <T extends Element = HTMLElement>(selector: string) => document.querySelector<T>(selector);+const text = () => host.textContent ?? "";++beforeEach(() => {+ setLocale("en");+ sessions.list = [];+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});+afterEach(() => {+ flushSync(() => root.unmount());+ host.remove();+ delete (globalThis as { ogb?: unknown }).ogb;+});++type Act = (call: (companion: unknown) => Promise<CompanionState>) => Promise<CompanionState>;+function render(state: CompanionState, { act = vi.fn<Act>(async () => state), onAddPhone = vi.fn() } = {}) {+ const c = { busy: false, accountBusy: false, act } as unknown as PhoneSetupController;+ flushSync(() => root.render(createElement(AlwaysOnHomeSection, { c, state, onAddPhone })));+ return { act, onAddPhone };+}++describe("what the switch says it did", () => {+ it("one line for each part, from main's own state", () => {+ expect(alwaysOnLines(home({ on: true, openAtLogin: true, awake: "holding" })).map((line) => [line.key, line.good])).toEqual([+ ["alwaysOn.login.on", true], ["alwaysOn.awake.on", true], ["alwaysOn.updates.byItself", true], ["alwaysOn.windowClosed", true], ["alwaysOn.restarts", true],+ ]);+ expect(alwaysOnLines(home({ on: true, awake: "battery", updates: "package", available: false })).map((line) => line.key)).toEqual([+ "alwaysOn.login.unavailable", "alwaysOn.awake.battery", "alwaysOn.updates.package", "alwaysOn.windowClosed", "alwaysOn.restarts",+ ]);+ });++ it("names the Mac's own settings on a Mac only", () => {+ expect(systemSettingLines("darwin")).toHaveLength(4);+ expect(systemSettingLines("win32")).toEqual([]);+ expect(systemSettingLines("linux")).toEqual([]);+ });++ it("the status line counts what reaches it", () => {+ expect(homeStatusLine(0)).toBe("Home is on · nothing paired yet");+ expect(homeStatusLine(1)).toBe("Home is on · reachable from 1 device");+ expect(homeStatusLine(2)).toBe("Home is on · reachable from 2 devices");+ });+});++describe("on the spare computer", () => {+ it("one switch turns it on; then what it did, the status, the next step and the Mac's own settings", async () => {+ let saved = home();+ const set = vi.fn(async (on: boolean) => (saved = home({ on, openAtLogin: on, awake: on ? "holding" : "off" })));+ (globalThis as { ogb?: unknown }).ogb = { platform: "darwin", alwaysOnHome: { state: vi.fn(async () => saved), set } };+ sessions.list = [{ id: "laptop" }];+ const { onAddPhone } = render(companionState(1));+ await vi.waitFor(() => expect($("[data-always-on-switch] [role=switch]")).not.toBeNull());+ expect(text()).toContain("Use this Mac as an always-on home");+ expect($("[data-always-on-details]")).toBeNull();+ flushSync(() => $<HTMLButtonElement>("[data-always-on-switch] [role=switch]")!.click());+ await vi.waitFor(() => expect($("[data-always-on-details]")).not.toBeNull());+ expect(set).toHaveBeenCalledWith(true);+ expect(text()).toContain("Opens at login");+ expect(text()).toContain("Stays awake while plugged in");+ expect(text()).toContain("Installs updates by itself when nobody is using it");+ expect(text()).toContain("Starts its server again if it stops");+ await vi.waitFor(() => expect($("[data-always-on-status]")?.textContent).toBe("Home is on · reachable from 2 devices"));+ expect($("[data-always-on-system]")?.textContent).toContain("System Settings → Energy");+ expect($("[data-always-on-system]")?.textContent).toContain("Automatically log in as");+ expect($("[data-always-on-system]")?.textContent).toContain("Accessibility and Screen Recording");+ expect($("[data-always-on-steps]"), "a home doesn't offer adding another").toBeNull();+ flushSync(() => $<HTMLButtonElement>("[data-always-on-add-phone]")!.click());+ expect(onAddPhone).toHaveBeenCalledOnce();+ });++ it("Add your other computer turns on Your other computers in one tap; once on, it points at Pair a computer", async () => {+ (globalThis as { ogb?: unknown }).ogb = { platform: "darwin", alwaysOnHome: { state: async () => home({ on: true, openAtLogin: true, awake: "holding" }), set: vi.fn() } };+ const setTailscaleComputers = vi.fn(async () => companionState(0, true));+ const { act } = render(companionState(0), { act: vi.fn<Act>(async (call) => call({ setTailscaleComputers, state: vi.fn() })) });+ await vi.waitFor(() => expect($("[data-always-on-add-computer]")).not.toBeNull());+ flushSync(() => $<HTMLButtonElement>("[data-always-on-add-computer]")!.click());+ await vi.waitFor(() => expect(setTailscaleComputers).toHaveBeenCalledWith(true));+ expect(act).toHaveBeenCalledOnce();+ render(companionState(0, true));+ await vi.waitFor(() => expect($("[data-always-on-add-computer]")).toBeNull());+ expect(text()).toContain("choose Pair a computer under Your other computers");+ });++ it("on Windows the Mac's settings are left out, and a Linux package's updates say where they come from", async () => {+ (globalThis as { ogb?: unknown }).ogb = { platform: "linux", alwaysOnHome: { state: async () => home({ on: true, platform: "linux", openAtLogin: true, awake: "holding", updates: "package" }), set: vi.fn() } };+ render(companionState(0));+ await vi.waitFor(() => expect($("[data-always-on-details]")).not.toBeNull());+ expect(text()).toContain("Use this computer as an always-on home");+ expect(text()).toContain("Updates come through your package manager");+ expect($("[data-always-on-system]")).toBeNull();+ });+});++describe("on the main computer", () => {+ const environments = (servers: Array<{ id: string; name: string; origin?: string; home?: boolean; kind?: "local" | "remote" }>, status: unknown[] = []) => ({+ state: vi.fn(async () => ({ localOrigin: "http://127.0.0.1:8799", remote: false, packaged: true, activeId: "local", environments: servers })),+ status: vi.fn(async () => status),+ switch: vi.fn(async () => {}),+ onStatus: () => () => {},+ });++ it("walks through adding one: the steps, Connect opens the existing pairing sheet", async () => {+ const env = environments([{ id: "local", name: "This computer", kind: "local" }]);+ (globalThis as { ogb?: unknown }).ogb = { platform: "darwin", environments: env, workspaces: { probe: vi.fn(), makeHome: vi.fn() } };+ render(companionState(0));+ await vi.waitFor(() => expect($("[data-settings-disclosure=add-always-on] button")).not.toBeNull());+ expect(text()).toContain("Add a Mac mini or other always-on computer");+ flushSync(() => $<HTMLButtonElement>("[data-settings-disclosure=add-always-on] button")!.click());+ expect($("[data-always-on-steps]")?.textContent).toContain("Use this Mac as an always-on home");+ expect($("[data-always-on-steps]")?.textContent).toContain("Tailscale");+ flushSync(() => $<HTMLButtonElement>("[data-always-on-connect]")!.click());+ expect($("[data-rail-sheet] [data-own-server-link]")).not.toBeNull();+ });++ it("once added: how it is doing, Open its bots, and Move my bots there after a plain confirm", async () => {+ const env = environments([+ { id: "local", name: "This computer", kind: "local" },+ { id: "cloud", name: "My Cloud", kind: "remote", origin: "https://cloud.example.test", home: true },+ { id: "mini", name: "Mac mini", kind: "remote", origin: "http://mini.tail1234.ts.net:8799" },+ ], [{ id: "mini", state: "connected", since: 1, version: "0.1.166", behind: false, install: null }]);+ const makeHome = vi.fn(async () => ({ started: true }));+ (globalThis as { ogb?: unknown }).ogb = { platform: "darwin", environments: env, workspaces: { probe: vi.fn(), makeHome, places: vi.fn(async () => ({ places: [], add: {} })) } };+ render(companionState(0));+ await vi.waitFor(() => expect($("[data-always-on-computer=mini]")).not.toBeNull());+ expect($("[data-always-on-computer=cloud]"), "My Cloud is not a computer added by hand").toBeNull();+ await vi.waitFor(() => expect($("[data-always-on-health]")?.textContent).toBe("Online"));+ expect(text()).toContain("Mac mini has its own circle at the left edge of the window");+ expect(text()).toContain("Bots there use its screen, browser and files");+ flushSync(() => $<HTMLButtonElement>("[data-always-on-open]")!.click());+ expect(env.switch).toHaveBeenCalledWith("mini");+ flushSync(() => $<HTMLButtonElement>("[data-always-on-move]")!.click());+ expect(makeHome, "nothing moves before the confirm").not.toHaveBeenCalled();+ expect(text()).toContain("Moves this computer's bots, chats, memory and routines to Mac mini");+ flushSync(() => $<HTMLButtonElement>("[data-always-on-move-yes]")!.click());+ await vi.waitFor(() => expect(makeHome).toHaveBeenCalledWith("mini"));+ });++ it("says main's own words when it can't move there", async () => {+ const env = environments([{ id: "mini", name: "Mac mini", kind: "remote", origin: "http://mini.tail1234.ts.net:8799" }]);+ const makeHome = vi.fn(async () => { throw new Error("This server can't be your bots' home."); });+ (globalThis as { ogb?: unknown }).ogb = { platform: "darwin", environments: env, workspaces: { probe: vi.fn(), makeHome, places: vi.fn(async () => ({ places: [], add: {} })) } };+ render(companionState(0));+ await vi.waitFor(() => expect($("[data-always-on-move]")).not.toBeNull());+ flushSync(() => $<HTMLButtonElement>("[data-always-on-move]")!.click());+ flushSync(() => $<HTMLButtonElement>("[data-always-on-move-yes]")!.click());+ await vi.waitFor(() => expect($("[role=alert]")?.textContent).toBe("This server can't be your bots' home."));+ });++ it("nothing at all where neither part can run (an older app, or a browser)", () => {+ (globalThis as { ogb?: unknown }).ogb = {};+ render(companionState(0));+ expect(host.innerHTML).toBe("");+ });+});diff --git a/src/components/AlwaysOnHomeSection.tsx b/src/components/AlwaysOnHomeSection.tsxnew file mode 100644index 0000000000..a4b0ca5aca--- /dev/null+++ b/src/components/AlwaysOnHomeSection.tsx@@ -0,0 +1,230 @@+// Settings → Phone & devices → Always-on home: a spare computer (a Mac mini, say) as the person's own Cloud at home. On+// that computer, one switch makes it one; on their main computer, the steps to add it and what it then does for them.+import { useEffect, useState } from "react";+import { Check } from "lucide-react";+import { productName } from "@/lib/brand";+import { t } from "@/lib/i18n";+import { makeHome } from "@/lib/places";+import { api } from "@/state/store";+import type { LocaleKey } from "@/locales";+import type { ServerStatus } from "../../electron/server-status.mjs";+import type { CompanionState, PhoneSetupController } from "./PhoneSetupFlow";+import { OwnServerLink, RailSheet } from "./PlaceAddSheet";+import { byHand, type SavedServer } from "./ServerList";+import { SettingRow, SettingsFoldRow, SettingsGroup, SettingsRows, Switch } from "./SettingsPrimitives";++type Line = { key: LocaleKey; good: boolean };++const UPDATE_LINE = {+ "by-itself": "alwaysOn.updates.byItself",+ restart: "alwaysOn.updates.restart",+ package: "alwaysOn.updates.package",+ none: "alwaysOn.updates.none",+} as const satisfies Record<AlwaysOnHomeState["updates"], LocaleKey>;++/** What the switch turned on, one line each, as main reads it now. */+export function alwaysOnLines(state: AlwaysOnHomeState): Line[] {+ return [+ { key: state.openAtLogin ? "alwaysOn.login.on" : state.available ? "alwaysOn.login.off" : "alwaysOn.login.unavailable", good: state.openAtLogin },+ { key: state.awake === "holding" ? "alwaysOn.awake.on" : "alwaysOn.awake.battery", good: state.awake === "holding" },+ { key: UPDATE_LINE[state.updates], good: state.updates === "by-itself" },+ { key: "alwaysOn.windowClosed", good: true },+ { key: "alwaysOn.restarts", good: true },+ ];+}++/** What only the computer's own settings can do, in their own names: a Mac's, shown on a Mac only. */+export function systemSettingLines(platform: string): LocaleKey[] {+ return platform === "darwin" ? ["alwaysOn.mac.power", "alwaysOn.mac.login", "alwaysOn.mac.locked", "alwaysOn.mac.permissions"] : [];+}++/** "Home is on · reachable from 2 devices", or "Home is on · nothing paired yet". */+export function homeStatusLine(devices: number): string {+ if (devices <= 0) return t("alwaysOn.status.none");+ return devices === 1 ? t("alwaysOn.status.one") : t("alwaysOn.status.many", { count: devices });+}++/** Phones paired with this computer, and other computers and browsers signed in to it with a pairing code. */+function usePairedCount(state: CompanionState, on: boolean): number {+ const [signedIn, setSignedIn] = useState(0);+ useEffect(() => {+ if (!on) return;+ let alive = true;+ void api("/api/auth/sessions").then((body) => { if (alive) setSignedIn(Array.isArray(body?.sessions) ? body.sessions.length : 0); }).catch(() => {});+ return () => { alive = false; };+ }, [on]);+ return state.devices.length + signedIn;+}++const ogb = () => (typeof window === "undefined" ? undefined : window.ogb);+const isMac = () => ogb()?.platform === "darwin";++/** On the spare computer: one switch, what it did, and the next step (pair a phone, then another computer). */+function ThisComputerHome({ home, setHome, c, state, onAddPhone }: {+ home: AlwaysOnHomeState; setHome: (next: AlwaysOnHomeState) => void; c: PhoneSetupController; state: CompanionState; onAddPhone: () => void;+}) {+ const [busy, setBusy] = useState(false);+ const [failed, setFailed] = useState(false);+ const paired = usePairedCount(state, home.on);+ const set = (on: boolean) => {+ const bridge = ogb()?.alwaysOnHome;+ if (!bridge) return;+ setBusy(true); setFailed(false);+ void bridge.set(on).then(setHome, () => setFailed(true)).finally(() => setBusy(false));+ };+ const title = t(isMac() ? "alwaysOn.titleMac" : "alwaysOn.title");+ const computersOn = state.routes?.tailscale?.on === true && state.routes.tailscale.computers === true;+ return (+ <>+ <SettingRow title={title} subtitle={t("alwaysOn.line")}+ message={failed ? <span role="alert" className="text-danger">{t("alwaysOn.failed")}</span>+ : home.on ? <span data-always-on-status="" aria-live="polite">{homeStatusLine(paired)}</span> : undefined}>+ <span data-always-on-switch="" className="contents">+ <Switch checked={home.on} disabled={busy} aria-label={title} onClick={() => set(!home.on)} />+ </span>+ </SettingRow>+ {home.on && <AlwaysOnDetails home={home} c={c} onAddPhone={onAddPhone} canAddComputer={!computersOn} />}+ </>+ );+}++function AlwaysOnDetails({ home, c, onAddPhone, canAddComputer }: { home: AlwaysOnHomeState; c: PhoneSetupController; onAddPhone: () => void; canAddComputer: boolean }) {+ const system = systemSettingLines(home.platform);+ return (+ <div data-always-on-details="" className="flex flex-col gap-3 px-4 py-3">+ <ul className="flex flex-col gap-1 text-[13px] leading-[18px]">+ {alwaysOnLines(home).map((line) => (+ <li key={line.key} data-always-on-line={line.key} className={line.good ? "flex gap-1.5 text-ink" : "flex gap-1.5 text-ink-secondary"}>+ {line.good ? <Check size={14} aria-hidden="true" className="mt-0.5 shrink-0 text-ink-secondary" /> : <span aria-hidden="true" className="w-3.5 shrink-0" />}+ <span>{t(line.key, { app: productName() })}</span>+ </li>+ ))}+ </ul>+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-[13px] leading-[18px] text-ink">{t("alwaysOn.next")}</span>+ <button type="button" className="ui-button ui-button-primary" data-always-on-add-phone="" disabled={c.busy} onClick={onAddPhone}>{t("alwaysOn.addPhone")}</button>+ {canAddComputer && (+ <button type="button" className="ui-button" data-always-on-add-computer="" disabled={c.busy}+ onClick={() => void c.act((companion) => companion.setTailscaleComputers?.(true) ?? companion.state())}>{t("alwaysOn.addComputer")}</button>+ )}+ </div>+ {!canAddComputer && <p className="text-[12px] leading-4 text-ink-secondary">{t("alwaysOn.addComputerOn")}</p>}+ {system.length > 0 && (+ <ul data-always-on-system="" className="flex list-disc flex-col gap-1 pl-4 text-[12px] leading-4 text-ink-secondary">+ {system.map((key) => <li key={key}>{t(key, { app: productName() })}</li>)}+ </ul>+ )}+ </div>+ );+}++/** The servers saved by hand on this computer, read again whenever the Connect sheet closes. */+function useSavedServers(version: number): { servers: SavedServer[]; status: ServerStatus[] } {+ const environments = ogb()?.environments;+ const [servers, setServers] = useState<SavedServer[]>([]);+ const [status, setStatus] = useState<ServerStatus[]>([]);+ useEffect(() => {+ if (!environments) return;+ let alive = true;+ const read = () => {+ void environments.state().then((saved) => { if (alive) setServers(saved.environments.filter(byHand)); }).catch(() => {});+ void environments.status?.().then((rows) => { if (alive) setStatus(rows); }).catch(() => {});+ };+ read();+ const off = environments.onStatus?.(read);+ return () => { alive = false; off?.(); };+ }, [environments, version]);+ return { servers, status };+}++/** One computer added here: how it is doing, and one tap each for what it can do. */+function AddedComputer({ server, status }: { server: SavedServer; status: ServerStatus | undefined }) {+ const [confirming, setConfirming] = useState(false);+ const [moving, setMoving] = useState(false);+ const [said, setSaid] = useState<string | null>(null);+ const move = () => {+ setMoving(true); setSaid(null);+ void makeHome(server.id).then((outcome) => {+ setMoving(false);+ if (outcome === true) setConfirming(false); else setSaid(outcome);+ });+ };+ const health = !status || status.state === "checking" ? t("alwaysOn.added.checking")+ : status.state === "connected" ? t("alwaysOn.added.online") : t("alwaysOn.added.offline");+ return (+ <div data-always-on-computer={server.id} className="flex flex-col gap-2 px-4 py-3">+ <div className="flex flex-wrap items-center gap-3">+ <div className="min-w-0 flex-1">+ <div className="truncate text-[14px] leading-5 text-ink">{server.name}</div>+ <div data-always-on-health={status?.state ?? "checking"} className="text-[12px] leading-4 text-ink-secondary">{health}</div>+ </div>+ <button type="button" className="ui-button" data-always-on-open="" onClick={() => void ogb()?.environments?.switch(server.id)}>{t("alwaysOn.added.open")}</button>+ {!confirming && <button type="button" className="ui-button" data-always-on-move="" onClick={() => setConfirming(true)}>{t("alwaysOn.added.move")}</button>}+ </div>+ {confirming && (+ <div role="group" aria-label={t("rail.makeHome", { name: server.name })} className="flex flex-col gap-2 rounded-lg bg-inset px-3 py-2.5">+ <p className="text-[13px] leading-[18px] text-ink">{t("rail.makeHomeSub", { name: server.name })}</p>+ <div className="flex flex-wrap gap-2">+ <button type="button" className="ui-button ui-button-primary" data-always-on-move-yes="" disabled={moving} aria-busy={moving || undefined} onClick={move}>{t("rail.makeHome", { name: server.name })}</button>+ <button type="button" className="ui-button" disabled={moving} onClick={() => { setConfirming(false); setSaid(null); }}>{t("common.cancel")}</button>+ </div>+ {said && <p role="alert" className="text-[12px] leading-4 text-danger">{said}</p>}+ </div>+ )}+ <ul className="flex list-disc flex-col gap-1 pl-4 text-[12px] leading-4 text-ink-secondary">+ <li>{t("alwaysOn.added.sidebar", { name: server.name })}</li>+ <li>{t("alwaysOn.added.keepRunning", { name: server.name })}</li>+ <li>{t("alwaysOn.added.screen", { app: productName() })}</li>+ </ul>+ </div>+ );+}++/** On the person's main computer: the steps to add a spare computer, then each one added and what it can do. */+function AddAlwaysOnComputer() {+ const [asked, setOpen] = useState<boolean | null>(null);+ const [connecting, setConnecting] = useState(false);+ const [version, setVersion] = useState(0);+ const { servers, status } = useSavedServers(version);+ const title = t("alwaysOn.add.title");+ const open = asked ?? servers.length > 0;+ return (+ <>+ <SettingsFoldRow id="add-always-on" title={title} subtitle={t("alwaysOn.add.line")} open={open} onToggle={() => setOpen(!open)}>+ <ol data-always-on-steps="" className="flex list-decimal flex-col gap-2 px-4 py-3 pl-8 text-[13px] leading-[18px] text-ink">+ <li>{t("alwaysOn.add.step1", { app: productName() })}</li>+ <li>{t("alwaysOn.add.step2")}</li>+ <li className="flex flex-wrap items-center gap-3">+ <span>{t("alwaysOn.add.step3")}</span>+ <button type="button" className="ui-button ui-button-primary" data-always-on-connect="" onClick={() => setConnecting(true)}>{t("alwaysOn.add.connect")}</button>+ </li>+ </ol>+ {servers.map((server) => <AddedComputer key={server.id} server={server} status={status.find((row) => row.id === server.id)} />)}+ </SettingsFoldRow>+ {connecting && <RailSheet focusKey="connect" onClose={() => { setConnecting(false); setVersion((n) => n + 1); }}>+ <OwnServerLink onBack={null} onConnected={() => { setConnecting(false); setVersion((n) => n + 1); }} />+ </RailSheet>}+ </>+ );+}++/** The section: this computer as a home, and adding another computer as one. The second is left out while this one is a home. */+export function AlwaysOnHomeSection({ c, state, onAddPhone }: { c: PhoneSetupController; state: CompanionState; onAddPhone: () => void }) {+ const bridge = ogb()?.alwaysOnHome;+ const [home, setHome] = useState<AlwaysOnHomeState | null>(null);+ useEffect(() => {+ let alive = true;+ void bridge?.state().then((next) => { if (alive) setHome(next); }).catch(() => {});+ return () => { alive = false; };+ }, [bridge]);+ const addHere = Boolean(ogb()?.environments && ogb()?.workspaces?.probe);+ if (!home && !addHere) return null;+ return (+ <SettingsGroup label={t("alwaysOn.section")} block="always-on" description={t("alwaysOn.sectionLine")}>+ <SettingsRows>+ {home && <ThisComputerHome home={home} setHome={setHome} c={c} state={state} onAddPhone={onAddPhone} />}+ {addHere && !home?.on && <AddAlwaysOnComputer />}+ </SettingsRows>+ </SettingsGroup>+ );+}diff --git a/src/components/PhoneDevicesSection.reveal.test.ts b/src/components/PhoneDevicesSection.reveal.test.tsindex 01ab757cbb..f76ae6cde6 100644--- a/src/components/PhoneDevicesSection.reveal.test.ts+++ b/src/components/PhoneDevicesSection.reveal.test.ts@@ -9,7 +9,7 @@ vi.mock("react", async (original) => ({useRef: (initial: unknown) => { const index = f.index++; if (!(index in f.values)) f.values[index] = { current: initial }; return f.values[index]; },useEffect: (effect: EffectCallback) => { f.effects.push(effect); },}));-vi.mock("../lib/phone-pairing", () => ({ takePairOnOpen: () => false, revealPhonePairing: (root: unknown) => { if (!root) return false; f.revealed.push(root); return true; } }));+vi.mock("../lib/phone-pairing", async (original) => ({ ...await original<typeof import("../lib/phone-pairing")>(), takePairOnOpen: () => false, revealPhonePairing: (root: unknown) => { if (!root) return false; f.revealed.push(root); return true; } }));vi.mock("@/state/store", () => ({ useStore: () => ({ state: { config: {} } }) }));vi.mock("./PhoneSetupFlow", () => ({companionBridge: () => ({}),diff --git a/src/components/PhoneDevicesSection.tsx b/src/components/PhoneDevicesSection.tsxindex 6f1928bee8..c689949fb6 100644--- a/src/components/PhoneDevicesSection.tsx+++ b/src/components/PhoneDevicesSection.tsx@@ -22,6 +22,7 @@ import { showTunnelRetiredNotice } from "../lib/phone-link";import { PhonesList } from "./PhonesList";import { PairedPhones } from "./PairedPhones";import { TailnetComputers } from "./TailnetComputers";+import { AlwaysOnHomeSection } from "./AlwaysOnHomeSection";import { RemoteAccessCheckRow } from "./RemoteAccessCheck";import { LearnMore, SettingRow, SettingsFoldRow, SettingsGroup, SettingsLinkRow, SettingsRows, Switch } from "./SettingsPrimitives";import { Layer } from "./Layer";@@ -473,6 +474,8 @@ export function PhoneDevicesSection({ profileEmail = "", focusRequest = 0, simpl</SettingsGroup>)}+ <AlwaysOnHomeSection c={c} state={state} onAddPhone={() => { if (!remoteBlocked) setPairing("device"); }} />+{!reachOpen ? (<SettingsGroup block="reach" footnote={t("phone.reach.foot")}><SettingsRows>diff --git a/src/components/ServerList.tsx b/src/components/ServerList.tsxindex 2c1e9174ee..230af4c7dc 100644--- a/src/components/ServerList.tsx+++ b/src/components/ServerList.tsx@@ -13,12 +13,15 @@ import { PlaceBadge } from "./settings/SettingsNav";type Saved = Awaited<ReturnType<NonNullable<NonNullable<Window["ogb"]>["environments"]>["state"]>>;type Entry = Saved["environments"][number];+/** One place saved on this computer, as Settings reads it. */+export type SavedServer = Entry;type Sheet = { address: string; locked: boolean; title: string } | null;/** A saved server of the person's own (this desktop is its admin), and how lending this computer to it is. */export type OwnServerSharing = { id: string; enabled: boolean; connected: boolean; paused: boolean };const TRANSPORT = { https: "servers.transport.https", tailscale: "servers.transport.tailscale", "private-http": "servers.transport.privateHttp", loopback: "servers.transport.loopback" } as const;-const byHand = (entry: Entry) => entry.kind !== "local" && Boolean(entry.origin) && !entry.home && !entry.cloud && !("team" in entry && entry.team);+/** A server the person connected by hand: not This computer, My Cloud, another Cloud of theirs or a team's. */+export const byHand = (entry: Entry) => entry.kind !== "local" && Boolean(entry.origin) && !entry.home && !entry.cloud && !("team" in entry && entry.team);const clock = (ms: number) => new Date(ms).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });/** The update command that fits how the server was installed, pinned to this app's version. */diff --git a/src/components/settings/settings-index.ts b/src/components/settings/settings-index.tsindex ce3dd9ab1d..875adb9087 100644--- a/src/components/settings/settings-index.ts+++ b/src/components/settings/settings-index.ts@@ -179,6 +179,10 @@ export const SETTINGS_INDEX: readonly SettingsIndexEntry[] = [{ id: "relay", page: "phone", anchor: "reach", labelKey: "devices.route.relay", sectionKey: "phone.reach.title", when: hereOnly, synonyms: ["anywhere", "relay", "away"] },{ id: "keep-awake", page: "phone", anchor: "reach", labelKey: "remote.keepAwake", sectionKey: "phone.reach.title", when: hereOnly, synonyms: ["sleep", "awake", "overnight", "scheduled"] },{ id: "wake-automations", page: "phone", labelKey: "settings.search.wakeAutomations", jump: "automations", when: hereOnly, topFor: ["sleep", "overnight", "scheduled"], synonyms: ["awake"] },+ { id: "always-on", page: "phone", anchor: "always-on", labelKey: "alwaysOn.title", sectionKey: "alwaysOn.section", when: hereOnly,+ topFor: ["always on", "always-on", "home server", "spare computer", "mac mini"], synonyms: ["mini", "server at home", "run all day", "24/7", "open at login", "awake"] },+ { id: "add-always-on", page: "phone", anchor: "always-on", labelKey: "alwaysOn.add.title", sectionKey: "alwaysOn.section", when: hereOnly,+ topFor: ["add a mac mini", "add mac mini", "add a computer", "add always-on computer"], synonyms: ["mac mini", "mini", "home server", "spare computer", "move my bots"] },{ id: "other-computers", page: "phone", anchor: "computers", labelKey: "devices.computers.title", when: hereOnly, topFor: ["tailscale", "other computers", "another computer", "other computer", "my other computer"],synonyms: ["computer", "computers", "laptop", "desktop", "mac", "pc", "share", "tailnet", "connect to a server"] },{ id: "tailscale", page: "phone", anchor: "reach", labelKey: "devices.moreWays", sectionKey: "phone.reach.title", when: hereOnly, advanced: true, synonyms: ["tailscale", "https", "tailnet"] },diff --git a/src/locales/de.json b/src/locales/de.jsonindex 474ad685b1..3c88a562db 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -4010,5 +4010,8 @@"server.rooms.linkedEnded": "{place} hat sich 30 Tage lang nicht verbunden, deshalb wurde die Verbindung dorthin beendet. Nicht mehr in diesem Raum: {bots}.","room.members.far.place": "auf {place}","room.members.far.off": "Verbindung ist aus",- "room.members.far.missing": "Nicht mehr verfügbar"+ "room.members.far.missing": "Nicht mehr verfügbar",+ "alwaysOn.section": "Immer eingeschaltetes Zuhause",+ "alwaysOn.title": "Diesen Computer als immer eingeschaltetes Zuhause nutzen",+ "alwaysOn.add.title": "Einen Mac mini oder anderen immer eingeschalteten Computer hinzufügen"}diff --git a/src/locales/en.json b/src/locales/en.jsonindex 3cd4ae1bec..b4544a09d8 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -10992,5 +10992,47 @@"templateImport.notATemplate": "This isn't a template. Choose another one.","sidebar.addDepartment": "Add department","sidebar.import": "Import…",- "team.shareDepartment": "Share"+ "team.shareDepartment": "Share",+ "alwaysOn.section": "Always-on home",+ "alwaysOn.sectionLine": "A spare computer, like a Mac mini, that runs your bots all day: your own Cloud at home, reachable from your laptop and phone.",+ "alwaysOn.titleMac": "Use this Mac as an always-on home",+ "alwaysOn.title": "Use this computer as an always-on home",+ "alwaysOn.line": "Opens at login, stays awake while plugged in, updates itself and starts its server again if it stops.",+ "alwaysOn.failed": "Could not change this. Try again.",+ "alwaysOn.login.on": "Opens at login",+ "alwaysOn.login.off": "Open at login is off. Turn it on in Login Items in your system's settings.",+ "alwaysOn.login.unavailable": "Open at login works only in the installed app.",+ "alwaysOn.awake.on": "Stays awake while plugged in",+ "alwaysOn.awake.battery": "On battery now: it sleeps as usual until it's plugged in",+ "alwaysOn.updates.byItself": "Installs updates by itself when nobody is using it",+ "alwaysOn.updates.restart": "Updates wait for you to choose Restart in {app}",+ "alwaysOn.updates.package": "Updates come through your package manager",+ "alwaysOn.updates.none": "This copy of {app} doesn't update itself",+ "alwaysOn.restarts": "Starts its server again if it stops, as often as it takes",+ "alwaysOn.status.none": "Home is on · nothing paired yet",+ "alwaysOn.status.one": "Home is on · reachable from 1 device",+ "alwaysOn.status.many": "Home is on · reachable from {count} devices",+ "alwaysOn.next": "Next:",+ "alwaysOn.addPhone": "Add your phone",+ "alwaysOn.addComputer": "Add your other computer",+ "alwaysOn.addComputerOn": "To add your other computer, choose Pair a computer under Your other computers below.",+ "alwaysOn.mac.power": "After a power cut: System Settings → Energy → Start up when power is connected: Always (on older macOS, Start up automatically after a power failure).",+ "alwaysOn.mac.login": "To start without anyone signing in: System Settings → Users & Groups → Automatically log in as. macOS offers it only while FileVault is off.",+ "alwaysOn.mac.locked": "Bots can't use the screen while it's locked. Locking is set in System Settings → Lock Screen.",+ "alwaysOn.mac.permissions": "For bots to use its screen, allow {app} under Accessibility and Screen Recording in System Settings → Privacy & Security.",+ "alwaysOn.add.title": "Add a Mac mini or other always-on computer",+ "alwaysOn.add.line": "Your bots keep running there while this computer sleeps or travels.",+ "alwaysOn.add.step1": "On that computer, install {app}, open Settings → Phone & devices and turn on Use this Mac as an always-on home.",+ "alwaysOn.add.step2": "There, turn on Your other computers and choose Pair a computer. Both computers need Tailscale, signed in to the same account.",+ "alwaysOn.add.step3": "Here, paste the link it shows.",+ "alwaysOn.add.connect": "Connect to it",+ "alwaysOn.added.checking": "Checking…",+ "alwaysOn.added.online": "Online",+ "alwaysOn.added.offline": "Can't reach it right now",+ "alwaysOn.added.open": "Open its bots",+ "alwaysOn.added.move": "Move my bots there",+ "alwaysOn.added.sidebar": "{name} has its own circle at the left edge of the window: click it to open its bots.",+ "alwaysOn.added.keepRunning": "Move my bots there moves this computer's bots, chats, memory and routines to {name}, so they keep running while this computer is off.",+ "alwaysOn.added.screen": "Bots there use its screen, browser and files, once {app} is allowed to use that computer.",+ "alwaysOn.windowClosed": "Keeps running when its window is closed"}diff --git a/src/locales/es.json b/src/locales/es.jsonindex 2bc84006c6..3991dd9c35 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -6392,5 +6392,8 @@"remote.tailscale.needsApproval": "Este ordenador espera la aprobación en tu red de Tailscale. Apruébalo en la consola de administración de Tailscale y vuelve a intentarlo.","together.switch.title": "Este equipo y My Cloud juntos","together.switch.line": "Desactivado de forma predeterminada. Los bots del Cloud y los de este equipo aparecen en una sola lista, y cada uno se abre donde está.",- "together.switch.failed": "No se pudo guardar. Inténtalo de nuevo."+ "together.switch.failed": "No se pudo guardar. Inténtalo de nuevo.",+ "alwaysOn.section": "Casa siempre encendida",+ "alwaysOn.title": "Usar este ordenador como casa siempre encendida",+ "alwaysOn.add.title": "Añadir un Mac mini u otro ordenador siempre encendido"}diff --git a/src/locales/fr.json b/src/locales/fr.jsonindex 6f78654fac..4bd78ff6f0 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -3796,5 +3796,8 @@"remote.tailscale.needsApproval": "Cet ordinateur attend d'être approuvé sur votre réseau Tailscale. Approuvez-le dans la console d'administration Tailscale, puis réessayez.","together.switch.title": "Cet ordinateur et Mon Cloud ensemble","together.switch.line": "Désactivé par défaut. Les bots du Cloud et ceux de cet ordinateur s'affichent dans une seule liste, et chacun s'ouvre là où il se trouve.",- "together.switch.failed": "Impossible d'enregistrer. Réessayez."+ "together.switch.failed": "Impossible d'enregistrer. Réessayez.",+ "alwaysOn.section": "Maison toujours allumée",+ "alwaysOn.title": "Utiliser cet ordinateur comme maison toujours allumée",+ "alwaysOn.add.title": "Ajouter un Mac mini ou un autre ordinateur toujours allumé"}diff --git a/src/locales/hi.json b/src/locales/hi.jsonindex e14db2b7f7..0123ced278 100644--- a/src/locales/hi.json+++ b/src/locales/hi.json@@ -3650,5 +3650,8 @@"remote.tailscale.needsApproval": "यह कंप्यूटर आपके Tailscale नेटवर्क पर मंज़ूरी का इंतज़ार कर रहा है। Tailscale एडमिन कंसोल में इसे मंज़ूर करें, फिर दोबारा कोशिश करें।","together.switch.title": "यही कंप्यूटर और मेरा क्लाउड एक साथ","together.switch.line": "डिफ़ॉल्ट रूप से बंद। क्लाउड के बॉट और इस कंप्यूटर के बॉट एक ही सूची में दिखते हैं, और हर बॉट वहीं खुलता है जहाँ वह है।",- "together.switch.failed": "इसे सहेजा नहीं जा सका। फिर से कोशिश करें।"+ "together.switch.failed": "इसे सहेजा नहीं जा सका। फिर से कोशिश करें।",+ "alwaysOn.section": "हमेशा चालू घर",+ "alwaysOn.title": "इस कंप्यूटर को हमेशा चालू घर की तरह इस्तेमाल करें",+ "alwaysOn.add.title": "Mac mini या कोई और हमेशा चालू कंप्यूटर जोड़ें"}diff --git a/src/locales/it.json b/src/locales/it.jsonindex 44c992df81..9e6fcee492 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -6966,5 +6966,8 @@"remote.tailscale.needsApproval": "Questo computer è in attesa di approvazione sulla tua rete Tailscale. Approvalo nella console di amministrazione di Tailscale, poi riprova.","together.switch.title": "Questo computer e Il mio Cloud insieme","together.switch.line": "Disattivato per impostazione predefinita. I bot del Cloud e quelli di questo computer compaiono in un unico elenco, e ognuno si apre dove si trova.",- "together.switch.failed": "Non è stato possibile salvare. Riprova."+ "together.switch.failed": "Non è stato possibile salvare. Riprova.",+ "alwaysOn.section": "Casa sempre accesa",+ "alwaysOn.title": "Usa questo computer come casa sempre accesa",+ "alwaysOn.add.title": "Aggiungi un Mac mini o un altro computer sempre acceso"}diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex 9743408d2e..3bb8158f14 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -7938,5 +7938,8 @@"remote.tailscale.needsApproval": "このコンピューターは Tailscale ネットワークでの承認を待っています。Tailscale の管理コンソールで承認してから、もう一度お試しください。","together.switch.title": "このコンピューターと My Cloud をまとめる","together.switch.line": "既定ではオフです。Cloud のボットとこのコンピューターのボットを 1 つの一覧に表示し、それぞれがある場所で開きます。",- "together.switch.failed": "保存できませんでした。もう一度お試しください。"+ "together.switch.failed": "保存できませんでした。もう一度お試しください。",+ "alwaysOn.section": "常時オンの拠点",+ "alwaysOn.title": "このコンピュータを常時オンの拠点として使う",+ "alwaysOn.add.title": "Mac mini などの常時オンのコンピュータを追加"}diff --git a/src/locales/ko.json b/src/locales/ko.jsonindex f8cdd2515c..8661e29e42 100644--- a/src/locales/ko.json+++ b/src/locales/ko.json@@ -7631,5 +7631,8 @@"remote.tailscale.needsApproval": "이 컴퓨터는 Tailscale 네트워크에서 승인을 기다리고 있습니다. Tailscale 관리 콘솔에서 승인한 다음 다시 시도하세요.","together.switch.title": "이 컴퓨터와 내 클라우드 함께 보기","together.switch.line": "기본값은 꺼짐입니다. 클라우드의 봇과 이 컴퓨터의 봇이 하나의 목록에 표시되며, 각 봇은 자기가 있는 곳에서 열립니다.",- "together.switch.failed": "저장하지 못했습니다. 다시 시도하세요."+ "together.switch.failed": "저장하지 못했습니다. 다시 시도하세요.",+ "alwaysOn.section": "항상 켜진 홈",+ "alwaysOn.title": "이 컴퓨터를 항상 켜진 홈으로 사용",+ "alwaysOn.add.title": "Mac mini 또는 다른 항상 켜진 컴퓨터 추가"}diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex 890dbc48b2..f01866444b 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -7100,5 +7100,8 @@"remote.tailscale.needsApproval": "Ten komputer czeka na zatwierdzenie w Twojej sieci Tailscale. Zatwierdź go w konsoli administracyjnej Tailscale, a potem spróbuj ponownie.","together.switch.title": "Ten komputer i My Cloud razem","together.switch.line": "Domyślnie wyłączone. Boty z Cloud i boty z tego komputera są na jednej liście, a każdy otwiera się tam, gdzie działa.",- "together.switch.failed": "Nie udało się zapisać. Spróbuj ponownie."+ "together.switch.failed": "Nie udało się zapisać. Spróbuj ponownie.",+ "alwaysOn.section": "Zawsze włączony dom",+ "alwaysOn.title": "Używaj tego komputera jako zawsze włączonego domu",+ "alwaysOn.add.title": "Dodaj Maca mini lub inny zawsze włączony komputer"}diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex d1ec2b17d6..351ef9f411 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -10992,5 +10992,47 @@"templateImport.notATemplate": "Isto não é um modelo. Escolha outro.","sidebar.addDepartment": "Adicionar equipe","sidebar.import": "Importar…",- "team.shareDepartment": "Compartilhar"+ "team.shareDepartment": "Compartilhar",+ "alwaysOn.section": "Casa sempre ligada",+ "alwaysOn.sectionLine": "Um computador sobrando, como um Mac mini, que roda seus bots o dia todo: sua própria Cloud em casa, acessível do seu notebook e do seu celular.",+ "alwaysOn.titleMac": "Usar este Mac como casa sempre ligada",+ "alwaysOn.title": "Usar este computador como casa sempre ligada",+ "alwaysOn.line": "Abre ao iniciar a sessão, fica acordado enquanto está na tomada, se atualiza sozinho e reinicia o servidor se ele parar.",+ "alwaysOn.failed": "Não foi possível mudar isso. Tente de novo.",+ "alwaysOn.login.on": "Abre ao iniciar a sessão",+ "alwaysOn.login.off": "Abrir ao iniciar a sessão está desligado. Ative em Itens de Início nos ajustes do sistema.",+ "alwaysOn.login.unavailable": "Abrir ao iniciar a sessão só funciona no app instalado.",+ "alwaysOn.awake.on": "Fica acordado enquanto está na tomada",+ "alwaysOn.awake.battery": "Na bateria agora: dorme normalmente até ser ligado na tomada",+ "alwaysOn.updates.byItself": "Instala atualizações sozinho quando ninguém está usando",+ "alwaysOn.updates.restart": "As atualizações esperam você escolher Reiniciar no {app}",+ "alwaysOn.updates.package": "As atualizações chegam pelo seu gerenciador de pacotes",+ "alwaysOn.updates.none": "Esta cópia do {app} não se atualiza sozinha",+ "alwaysOn.restarts": "Reinicia o servidor se ele parar, quantas vezes for preciso",+ "alwaysOn.status.none": "Casa ligada · nada pareado ainda",+ "alwaysOn.status.one": "Casa ligada · acessível de 1 dispositivo",+ "alwaysOn.status.many": "Casa ligada · acessível de {count} dispositivos",+ "alwaysOn.next": "Próximo passo:",+ "alwaysOn.addPhone": "Adicionar seu celular",+ "alwaysOn.addComputer": "Adicionar seu outro computador",+ "alwaysOn.addComputerOn": "Para adicionar seu outro computador, escolha Parear um computador em Seus outros computadores, abaixo.",+ "alwaysOn.mac.power": "Depois de uma queda de energia: Ajustes do Sistema → Energia → Iniciar quando conectado à energia: Sempre (em versões mais antigas do macOS, Iniciar automaticamente após falta de energia).",+ "alwaysOn.mac.login": "Para iniciar sem ninguém entrar na sessão: Ajustes do Sistema → Usuários e Grupos → Iniciar sessão automaticamente como. O macOS só oferece isso com o FileVault desligado.",+ "alwaysOn.mac.locked": "Os bots não podem usar a tela enquanto ela está bloqueada. O bloqueio é ajustado em Ajustes do Sistema → Tela Bloqueada.",+ "alwaysOn.mac.permissions": "Para os bots usarem a tela, permita o {app} em Acessibilidade e Gravação de Tela em Ajustes do Sistema → Privacidade e Segurança.",+ "alwaysOn.add.title": "Adicionar um Mac mini ou outro computador sempre ligado",+ "alwaysOn.add.line": "Seus bots continuam rodando lá enquanto este computador dorme ou viaja.",+ "alwaysOn.add.step1": "Naquele computador, instale o {app}, abra Configurações → Celular e dispositivos e ative Usar este Mac como casa sempre ligada.",+ "alwaysOn.add.step2": "Lá, ative Seus outros computadores e escolha Parear um computador. Os dois computadores precisam do Tailscale, conectado à mesma conta.",+ "alwaysOn.add.step3": "Aqui, cole o link que ele mostra.",+ "alwaysOn.add.connect": "Conectar",+ "alwaysOn.added.checking": "Verificando…",+ "alwaysOn.added.online": "Online",+ "alwaysOn.added.offline": "Não dá para alcançá-lo agora",+ "alwaysOn.added.open": "Abrir os bots dele",+ "alwaysOn.added.move": "Mover meus bots para lá",+ "alwaysOn.added.sidebar": "{name} tem seu próprio círculo na borda esquerda da janela: clique nele para abrir os bots dele.",+ "alwaysOn.added.keepRunning": "Mover meus bots para lá leva os bots, conversas, memória e rotinas deste computador para {name}, para que continuem rodando enquanto este computador está desligado.",+ "alwaysOn.added.screen": "Os bots de lá usam a tela, o navegador e os arquivos daquele computador, depois que o {app} tiver permissão para usá-lo.",+ "alwaysOn.windowClosed": "Continua rodando quando a janela é fechada"}diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex a9ff1c91ce..089e6448dc 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -7154,5 +7154,8 @@"remote.tailscale.needsApproval": "Этот компьютер ждёт одобрения в вашей сети Tailscale. Одобрите его в консоли администратора Tailscale, затем попробуйте снова.","together.switch.title": "Этот компьютер и Моё облако вместе","together.switch.line": "По умолчанию выключено. Боты из облака и боты этого компьютера показаны в одном списке, и каждый открывается там, где он находится.",- "together.switch.failed": "Не удалось сохранить. Попробуйте ещё раз."+ "together.switch.failed": "Не удалось сохранить. Попробуйте ещё раз.",+ "alwaysOn.section": "Всегда включённый дом",+ "alwaysOn.title": "Использовать этот компьютер как всегда включённый дом",+ "alwaysOn.add.title": "Добавить Mac mini или другой всегда включённый компьютер"}diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex 827c40b2e3..562c8cf886 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -5892,5 +5892,8 @@"remote.tailscale.needsApproval": "Bu bilgisayar Tailscale ağınızda onay bekliyor. Tailscale yönetici konsolunda onaylayın, ardından tekrar deneyin.","together.switch.title": "Bu bilgisayar ve Cloud'um birlikte","together.switch.line": "Varsayılan olarak kapalı. Cloud'daki botlar ile bu bilgisayardaki botlar tek listede görünür ve her biri bulunduğu yerde açılır.",- "together.switch.failed": "Kaydedilemedi. Yeniden deneyin."+ "together.switch.failed": "Kaydedilemedi. Yeniden deneyin.",+ "alwaysOn.section": "Her zaman açık ev",+ "alwaysOn.title": "Bu bilgisayarı her zaman açık ev olarak kullan",+ "alwaysOn.add.title": "Mac mini veya her zaman açık başka bir bilgisayar ekle"}diff --git a/src/locales/uk.json b/src/locales/uk.jsonindex 7009669e87..198ccc9519 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -4070,5 +4070,8 @@"remote.tailscale.needsApproval": "Цей комп’ютер чекає на схвалення у вашій мережі Tailscale. Схваліть його в консолі адміністратора Tailscale, потім спробуйте ще раз.","together.switch.title": "Цей комп'ютер і Моя хмара разом","together.switch.line": "Типово вимкнено. Боти з хмари й боти цього комп'ютера показані в одному списку, і кожен відкривається там, де він є.",- "together.switch.failed": "Не вдалося зберегти. Спробуйте ще раз."+ "together.switch.failed": "Не вдалося зберегти. Спробуйте ще раз.",+ "alwaysOn.section": "Завжди увімкнений дім",+ "alwaysOn.title": "Використовувати цей комп’ютер як завжди увімкнений дім",+ "alwaysOn.add.title": "Додати Mac mini або інший завжди увімкнений комп’ютер"}diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex 91e686dad6..b503486096 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -5892,5 +5892,8 @@"remote.tailscale.needsApproval": "Máy tính này đang chờ được phê duyệt trên mạng Tailscale của bạn. Hãy phê duyệt trong bảng điều khiển quản trị Tailscale, rồi thử lại.","together.switch.title": "Máy tính này và My Cloud cùng nhau","together.switch.line": "Mặc định là tắt. Bot trên Cloud và bot trên máy tính này hiện trong một danh sách, và mỗi bot mở ở nơi nó đang ở.",- "together.switch.failed": "Không lưu được. Hãy thử lại."+ "together.switch.failed": "Không lưu được. Hãy thử lại.",+ "alwaysOn.section": "Nhà luôn bật",+ "alwaysOn.title": "Dùng máy tính này làm nhà luôn bật",+ "alwaysOn.add.title": "Thêm Mac mini hoặc máy tính luôn bật khác"}diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex ec5b260e4e..9bcd92324b 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -10166,5 +10166,8 @@"remote.tailscale.needsApproval": "這台電腦正在等待你的 Tailscale 網路核准。請在 Tailscale 管理主控台中核准它,然後再試一次。","together.switch.title": "這台電腦和 My Cloud 合在一起","together.switch.line": "預設為關閉。Cloud 上的機器人和這台電腦上的機器人顯示在同一個清單中,各自在所在的位置開啟。",- "together.switch.failed": "無法儲存。請再試一次。"+ "together.switch.failed": "無法儲存。請再試一次。",+ "alwaysOn.section": "常開的家",+ "alwaysOn.title": "將這台電腦當作常開的家",+ "alwaysOn.add.title": "加入 Mac mini 或其他常開的電腦"}diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex 24e2bba039..448fae8930 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -10062,5 +10062,8 @@"server.rooms.linkedEnded": "{place} 已有 30 天没有连接,与它的连接已结束。已不在这个群组聊天中:{bots}。","room.members.far.place": "位于 {place}","room.members.far.off": "连接已关闭",- "room.members.far.missing": "已不可用"+ "room.members.far.missing": "已不可用",+ "alwaysOn.section": "常开的家",+ "alwaysOn.title": "将这台电脑用作常开的家",+ "alwaysOn.add.title": "添加 Mac mini 或其他常开的电脑"}diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.tsindex 686380e4b2..238d133a2c 100644--- a/src/types/ogb.d.ts+++ b/src/types/ogb.d.ts@@ -107,6 +107,16 @@ const __APP_VERSION__: string;at: number | null;onBattery: boolean;}+ /** Use this computer as an always-on home, as main reads it now. `available`: a packaged app, where Open at login works.+ * `awake`: held awake on power, let sleep on battery, or off. `updates`: how an update arrives with nobody at the computer. */+ interface AlwaysOnHomeState {+ available: boolean;+ on: boolean;+ platform: string;+ openAtLogin: boolean;+ awake: "holding" | "battery" | "off";+ updates: "by-itself" | "restart" | "package" | "none";+ }interface DesktopRemoteClientState {active: boolean;endpoint?: string;@@ -450,6 +460,8 @@ const __APP_VERSION__: string;openLogsFolder?(): Promise<{ folder: string; opened: boolean; error?: string }>;/** This app's own login item, which opens the window. `available`: false in a build that cannot add one. */openAtLogin?: { state(): Promise<{ available: boolean; on: boolean }>; set(on: boolean): Promise<{ available: boolean; on: boolean }> };+ /** Use this computer as an always-on home (this computer's own page only). Absent on an older app. */+ alwaysOnHome?: { state(): Promise<AlwaysOnHomeState>; set(on: boolean): Promise<AlwaysOnHomeState> };/** Saved keys this launch could not read (this app's own page only). `reset` asks the person, moves the unreadable* file aside and restarts; it resolves "cancelled" when they say no, "quitting" (doing nothing) when the app began* to quit while they decided, "failed" (after telling them) when the file could not be moved, and "readable"