Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Companion: pause the HTTPS address after 30 days with no phone seen; room for a third domain (#4566)
Milind Sonie5e155bdded5
diff --git a/electron/companion-account-service.d.mts b/electron/companion-account-service.d.mtsindex 0314808bf4..6f4c99c84b 100644--- a/electron/companion-account-service.d.mts+++ b/electron/companion-account-service.d.mts@@ -11,6 +11,8 @@ export declare const COMPANION_INSTALLATION_ID_FIELD: string;export declare const COMPANION_INSTALLATION_CREDENTIAL_FIELD: string;export declare const COMPANION_INSTALLATION_EXPIRY_FIELD: string;export declare const COMPANION_ACCOUNT_CLEANUP_PENDING_FIELD: string;+export declare const COMPANION_ENDPOINT_PAUSED_FIELD: string;+export declare const PHONE_UNUSED_RELEASE_MS: number;export type CredentialDocument = Record<string, unknown>;@@ -19,9 +21,11 @@ export declare function resolveCompanionControlPlaneURL(options?: {environment?: NodeJS.ProcessEnv;}): string;export declare function companionAccountCleanupPending(credentials: CredentialDocument): boolean;-/** true while a device is paired or a pairing window is open, false only for- * a cleanly read empty device list, null when that cannot be told. */-export declare function managedEndpointNeed(state: unknown): boolean | null;+/** true while a pairing window is open or a paired device was seen in the+ * last 30 days (or is connected, or has no known last-seen time); "unused"+ * when devices are paired but none was seen for 30 days; false only for a+ * cleanly read empty device list; null when that cannot be told. */+export declare function managedEndpointNeed(state: unknown, now?: number): boolean | "unused" | null;export declare function friendlyCompanionAccountError(error: unknown): string;export interface CompanionAccountState {@@ -30,6 +34,8 @@ export interface CompanionAccountState {email?: string;endpoint?: string;message?: string;+ /** The address was given back after 30 days with no paired phone seen; prepare() brings it back. */+ paused?: true;}export interface CompanionAccountService {@@ -70,7 +76,7 @@ export declare function createCompanionAccountService(options: {firstEndpointCheckMs?: number;/** Hold the address only while something needs it (the desktop app). */onDemand?: boolean;- managedEndpointNeeded?: () => Promise<boolean | null>;+ managedEndpointNeeded?: () => Promise<boolean | "unused" | null>;releaseGraceMs?: number;releaseJitterMs?: number;/** One line per failed setup step: code, HTTP status, request id, retry delay. */diff --git a/electron/companion-account-service.mjs b/electron/companion-account-service.mjsindex 507fa09b4b..ae89f0cc4f 100644--- a/electron/companion-account-service.mjs+++ b/electron/companion-account-service.mjs@@ -11,6 +11,9 @@ import {withManagedCompanionTunnelAccess,withoutManagedCompanionTunnelAccess,} from "./managed-companion-tunnel.mjs";+import { MANAGED_ENDPOINT_PHONES_UNUSED } from "./companion-endpoint-need.mjs";++export { managedEndpointNeed, PHONE_UNUSED_RELEASE_MS } from "./companion-endpoint-need.mjs";export const DEFAULT_COMPANION_CONTROL_PLANE_URL = "https://accounts.openmausbot.com";@@ -23,6 +26,8 @@ export const COMPANION_INSTALLATION_CREDENTIAL_FIELD = "companionInstallationCreexport const COMPANION_INSTALLATION_EXPIRY_FIELD = "companionInstallationCredentialExpiresAt";export const COMPANION_ACCOUNT_CLEANUP_PENDING_FIELD = "companionAccountCleanupPending";export const COMPANION_ENDPOINT_RELEASE_PENDING_FIELD = "companionEndpointReleasePending";+/** The address was given back while phones were paired but unused; the control plane keeps its hostname. */+export const COMPANION_ENDPOINT_PAUSED_FIELD = "companionEndpointPaused";const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;const INSTALLATION_ID = UUID;@@ -80,13 +85,6 @@ export function companionAccountCleanupPending(credentials) {return credentials?.[COMPANION_ACCOUNT_CLEANUP_PENDING_FIELD] === true;}-/** true, false, or null when that cannot be told; only false ever gives an address back. */-export function managedEndpointNeed(state) {- if (!state || typeof state !== "object" || state.enabled !== true || state.error) return null;- if (state.devicesUnreadable === true || !Array.isArray(state.devices)) return null;- return state.devices.length > 0 || Boolean(state.pairing);-}-function storedAccount(credentials) {const email = normalizeAccountEmail(ownString(credentials, COMPANION_ACCOUNT_EMAIL_FIELD));const userId = ownString(credentials, COMPANION_ACCOUNT_USER_ID_FIELD);@@ -117,6 +115,7 @@ function withoutCompanionAccount(credentials) {COMPANION_INSTALLATION_EXPIRY_FIELD,COMPANION_ACCOUNT_CLEANUP_PENDING_FIELD,COMPANION_ENDPOINT_RELEASE_PENDING_FIELD,+ COMPANION_ENDPOINT_PAUSED_FIELD,]) {delete next[field];}@@ -147,6 +146,7 @@ function withProvisionedAccount(credentials, { accountToken, user, installation,};delete next[COMPANION_ACCOUNT_CLEANUP_PENDING_FIELD];delete next[COMPANION_ENDPOINT_RELEASE_PENDING_FIELD];+ delete next[COMPANION_ENDPOINT_PAUSED_FIELD];return next;}@@ -212,8 +212,9 @@ export function friendlyCompanionAccountError(error) {return `${message}${reference}`;}-function publicState({ available, status, email, endpoint, message }) {+function publicState({ available, status, email, endpoint, message, paused }) {const state = { available: Boolean(available), status };+ if (paused === true) state.paused = true;const normalizedEmail = normalizeAccountEmail(email);if (normalizedEmail) state.email = normalizedEmail;const accessEndpoint = (() => {@@ -363,6 +364,7 @@ export function createCompanionAccountService({const account = storedAccount(document);const persistedAccess = managedCompanionTunnelAccess(document);const available = healthy || Boolean(account);+ const paused = Boolean(account) && !persistedAccess && document[COMPANION_ENDPOINT_PAUSED_FIELD] === true;if (!healthy) {return publicState({available,@@ -370,6 +372,7 @@ export function createCompanionAccountService({email: account?.email,endpoint: persistedAccess?.endpoint,message: FRIENDLY_MESSAGES.control_plane_unavailable,+ paused,});}if (@@ -382,11 +385,11 @@ export function createCompanionAccountService({) {phase = null;}- if (phase) return publicState({ available, ...phase });+ if (phase) return publicState({ available, ...phase, paused });if (!account) return publicState({ available, status: "signed-out" });const access = persistedAccess;if (!access) {- if (onDemand) return publicState({ available, status: "ready", email: account.email });+ if (onDemand) return publicState({ available, status: "ready", email: account.email, paused });return publicState({available,status: "error",@@ -765,11 +768,15 @@ export function createCompanionAccountService({const savedAddress = (document) => normalizeManagedCompanionEndpoint(document[MANAGED_COMPANION_ENDPOINT_FIELD]);+ let phonesUnused = false;+ /** "unused" (paired phones, none seen for 30 days) reads as false and is remembered for the release. */const currentNeed = async () => {+ phonesUnused = false;if (requestedRecently()) return true;try {const need = await managedEndpointNeeded();- return typeof need === "boolean" ? need : null;+ phonesUnused = need === MANAGED_ENDPOINT_PHONES_UNUSED;+ return phonesUnused ? false : typeof need === "boolean" ? need : null;} catch {return null;}@@ -792,6 +799,7 @@ export function createCompanionAccountService({/** The connector stops and the address is withdrawn before the DELETE, so nothing can pair to an address being removed. */const releaseAddress = async () => {const need = await currentNeed();+ const pause = phonesUnused;if (need !== false) {if (need) await cancelRelease();return settledState();@@ -822,12 +830,16 @@ export function createCompanionAccountService({return settledState();}}- await updateCredentials((current) => removalPending- ? { ...withoutManagedCompanionTunnelAccess(current), [COMPANION_ENDPOINT_RELEASE_PENDING_FIELD]: true }- : withoutManagedCompanionTunnelAccess(current));+ await updateCredentials((current) => ({+ ...withoutManagedCompanionTunnelAccess(current),+ ...(removalPending ? { [COMPANION_ENDPOINT_RELEASE_PENDING_FIELD]: true } : {}),+ ...(pause ? { [COMPANION_ENDPOINT_PAUSED_FIELD]: true } : {}),+ }));resetAutoRetry();phase = null;- writeLog("companion account: gave the secure address back; no device needs it");+ writeLog(pause+ ? "companion account: gave the secure address back; no paired phone was used in 30 days"+ : "companion account: gave the secure address back; no device needs it");return settledState();};diff --git a/electron/companion-account-service.test.mjs b/electron/companion-account-service.test.mjsindex 21026b8e49..6ca8f4763c 100644--- a/electron/companion-account-service.test.mjs+++ b/electron/companion-account-service.test.mjs@@ -7,6 +7,7 @@ import {COMPANION_ACCOUNT_TOKEN_FIELD,COMPANION_ACCOUNT_USER_ID_FIELD,COMPANION_CLIENT_INSTANCE_FIELD,+ COMPANION_ENDPOINT_PAUSED_FIELD,COMPANION_ENDPOINT_RELEASE_PENDING_FIELD,COMPANION_INSTALLATION_CREDENTIAL_FIELD,COMPANION_INSTALLATION_EXPIRY_FIELD,@@ -14,6 +15,7 @@ import {createCompanionAccountService,friendlyCompanionAccountError,managedEndpointNeed,+ PHONE_UNUSED_RELEASE_MS,resolveCompanionControlPlaneURL,} from "./companion-account-service.mjs";import {@@ -1691,6 +1693,131 @@ describe("Companion account on demand", () => {}});+ it("counts a paired phone as in use until 30 days after it was last seen, and an unknown time as in use", () => {+ const DAY_MS = 24 * HOUR_MS;+ const now = LAUNCH_AT;+ const phone = (lastSeenAt, id = "phone-1") => ({ id, name: "Ada", lastSeenAt });+ const answer = (devices, overrides) => ({ enabled: true, devices, pairing: null, ...overrides });+ expect(PHONE_UNUSED_RELEASE_MS).toBe(30 * DAY_MS);++ expect(managedEndpointNeed(answer([phone(now - DAY_MS)]), now)).toBe(true);+ expect(managedEndpointNeed(answer([phone(now - PHONE_UNUSED_RELEASE_MS + 1)]), now)).toBe(true);+ expect(managedEndpointNeed(answer([phone(now - PHONE_UNUSED_RELEASE_MS)]), now)).toBe(true);+ expect(managedEndpointNeed(answer([phone(now - PHONE_UNUSED_RELEASE_MS - 1)]), now)).toBe("unused");+ expect(managedEndpointNeed(answer([phone(now - 400 * DAY_MS)]), now)).toBe("unused");++ const old = phone(now - 90 * DAY_MS);+ expect(managedEndpointNeed(answer([old, phone(now - DAY_MS, "phone-2")]), now)).toBe(true);+ expect(managedEndpointNeed(answer([old], { connectedDeviceIds: ["phone-1"] }), now)).toBe(true);+ expect(managedEndpointNeed(answer([old], { connectedDeviceIds: ["phone-2"] }), now)).toBe("unused");+ const pairing = { code: "123456", token: `omb_pair_${"a".repeat(43)}`, expiresAt: now };+ expect(managedEndpointNeed(answer([old], { pairing }), now)).toBe(true);+ expect(managedEndpointNeed(answer([]), now)).toBe(false);+ for (const unknown of [undefined, null, 0, -1, Number.NaN, Number.POSITIVE_INFINITY, String(now - 90 * DAY_MS), now + DAY_MS]) {+ expect(managedEndpointNeed(answer([phone(unknown)]), now), String(unknown)).toBe(true);+ }+ for (const unclear of [answer([old], { devicesUnreadable: true }), answer([old], { error: "down" })]) {+ expect(managedEndpointNeed(unclear, now)).toBeNull();+ }+ });++ it("holds the address while a phone was seen in the last 30 days, then gives it back paused", async () => {+ const seenAt = LAUNCH_AT - PHONE_UNUSED_RELEASE_MS + 3 * HOUR_MS;+ const companionState = { enabled: true, devices: [{ id: "phone-1", name: "Ada", lastSeenAt: seenAt }], pairing: null };+ const clock = { now: LAUNCH_AT };+ const f = onDemandFixture({+ managedEndpointNeeded: vi.fn(async () => managedEndpointNeed(companionState, clock.now)),+ now: () => clock.now,+ });++ await f.service.restore();+ while (clock.now < seenAt + PHONE_UNUSED_RELEASE_MS) {+ clock.now += 15 * 60_000;+ await f.watchdog();+ expect(f.store.read(), new Date(clock.now).toISOString()).not.toHaveProperty(MANAGED_COMPANION_RELEASE_AT_FIELD);+ }+ expect(clock.now).toBe(seenAt + PHONE_UNUSED_RELEASE_MS);+ expect(f.store.writes).toHaveLength(0);++ clock.now += 15 * 60_000;+ await f.watchdog();+ const releaseAt = f.store.read()[MANAGED_COMPANION_RELEASE_AT_FIELD];+ expect(releaseAt).toBe(clock.now + 2.5 * HOUR_MS);+ while (clock.now < releaseAt) {+ expect(f.client.deleteEndpoint).not.toHaveBeenCalled();+ clock.now += 15 * 60_000;+ await f.watchdog();+ }+ expect(f.client.deleteEndpoint).toHaveBeenCalledOnce();+ for (const field of ADDRESS_FIELDS) expect(f.store.read()).not.toHaveProperty(field);+ expect(f.store.read()[COMPANION_ENDPOINT_PAUSED_FIELD]).toBe(true);+ expect(f.lines()).toContain("companion account: gave the secure address back; no paired phone was used in 30 days");+ f.service.dispose();+ });++ it("keeps a paused address down until prepare(), which brings the same address back and clears the pause", async () => {+ const ensureEndpoint = vi.fn(async () => ({ endpoint: { url: ENDPOINT }, connectorToken: RECLAIMED_TOKEN }));+ const f = onDemandFixture({+ initial: signedCredentials({ [MANAGED_COMPANION_RELEASE_AT_FIELD]: LAUNCH_AT - 1 }),+ client: readyClient({ ensureEndpoint }),+ });+ f.companion.need = "unused";++ await f.service.restore();+ expect(f.client.deleteEndpoint).toHaveBeenCalledOnce();+ expect(f.store.read()[COMPANION_ENDPOINT_PAUSED_FIELD]).toBe(true);+ await expect(f.service.state()).resolves.toEqual({+ available: true,+ status: "ready",+ email: "[email protected]",+ paused: true,+ });++ // Neither time nor a phone seen again on Wi-Fi brings it back without the page.+ for (const need of ["unused", true, null, false]) {+ f.companion.need = need;+ f.clock.now += 10 * HOUR_MS;+ await f.watchdog();+ }+ expect(ensureEndpoint).not.toHaveBeenCalled();+ expect(f.client.deleteEndpoint).toHaveBeenCalledOnce();++ f.companion.need = "unused";+ await expect(f.service.prepare()).resolves.toEqual({+ available: true,+ status: "ready",+ email: "[email protected]",+ endpoint: ENDPOINT,+ });+ expect(ensureEndpoint).toHaveBeenCalledOnce();+ expect(f.store.read()).toMatchObject({+ [MANAGED_COMPANION_ENDPOINT_FIELD]: ENDPOINT,+ [MANAGED_COMPANION_TOKEN_FIELD]: RECLAIMED_TOKEN,+ });+ expect(f.store.read()).not.toHaveProperty(COMPANION_ENDPOINT_PAUSED_FIELD);+ expect(f.activatePersistedEndpoint).toHaveBeenCalled();++ // Signing out forgets a pause along with the account.+ const paused = onDemandFixture({ initial: { ...signedInWithoutAddress(), [COMPANION_ENDPOINT_PAUSED_FIELD]: true } });+ await expect(paused.service.state()).resolves.toMatchObject({ paused: true });+ await paused.service.signOut();+ expect(paused.store.read()).not.toHaveProperty(COMPANION_ENDPOINT_PAUSED_FIELD);+ f.service.dispose();+ paused.service.dispose();+ });++ it("gives an address back unpaused when nothing is paired, and never pauses on a can't-tell", async () => {+ for (const need of [false, null]) {+ const f = onDemandFixture({ initial: signedCredentials({ [MANAGED_COMPANION_RELEASE_AT_FIELD]: LAUNCH_AT - 1 }) });+ f.companion.need = need;+ await f.service.restore();+ expect(f.client.deleteEndpoint).toHaveBeenCalledTimes(need === false ? 1 : 0);+ expect(f.store.read()).not.toHaveProperty(COMPANION_ENDPOINT_PAUSED_FIELD);+ expect(await f.service.state()).not.toHaveProperty("paused");+ f.service.dispose();+ }+ });+it("says when to try again when HTTPS links are full, retries for the hour, then lets it go", async () => {const ensureEndpoint = vi.fn(async () => {throw new ControlPlaneError("endpoint_capacity", 503, "", 600_000);diff --git a/electron/companion-endpoint-need.mjs b/electron/companion-endpoint-need.mjsnew file mode 100644index 0000000000..4ff9a2cc4a--- /dev/null+++ b/electron/companion-endpoint-need.mjs@@ -0,0 +1,23 @@+// Whether this computer's secure HTTPS address is needed. Each address holds one Cloudflare tunnel from a small+// shared pool, so a phone paired once and never used again must not hold one forever.+export const PHONE_UNUSED_RELEASE_MS = 30 * 24 * 60 * 60_000;++/** Phones are paired but none was seen for 30 days: give the address back, keep it ready to come back. */+export const MANAGED_ENDPOINT_PHONES_UNUSED = "unused";++/** Only a known last-seen time more than 30 days old: a missing one, or one in the future, keeps the phone in use. */+export function phoneUnused(device, now = Date.now()) {+ const seen = device?.lastSeenAt;+ return typeof seen === "number" && Number.isFinite(seen) && seen > 0 && now - seen > PHONE_UNUSED_RELEASE_MS;+}++/** true, false, "unused", or null when that cannot be told; only false or "unused" ever gives an address back. */+export function managedEndpointNeed(state, now = Date.now()) {+ if (!state || typeof state !== "object" || state.enabled !== true || state.error) return null;+ if (state.devicesUnreadable === true || !Array.isArray(state.devices)) return null;+ if (state.pairing) return true;+ if (state.devices.length === 0) return false;+ const connected = new Set(Array.isArray(state.connectedDeviceIds) ? state.connectedDeviceIds : []);+ return state.devices.some((device) => connected.has(device?.id) || !phoneUnused(device, now))+ || MANAGED_ENDPOINT_PHONES_UNUSED;+}diff --git a/electron/desktop-companion-client.mjs b/electron/desktop-companion-client.mjsindex 27fa7079db..ee835c3c8e 100644--- a/electron/desktop-companion-client.mjs+++ b/electron/desktop-companion-client.mjs@@ -41,8 +41,20 @@ const cleanLabel = (value, fallback) => {return label || fallback;};-/** Only the control plane's `c-<32 hex>` names: any other name in those zones never receives a pairing code. Ship a new domain here first. */-const MANAGED_COMPANION_HOSTNAME = /^c-[0-9a-f]{32}\.(?:openmausbot\.com|mausbot\.si)$/;+/** The third Cloudflare account's zone apex, "" until the owner names it. Set it, ship that release, and only then+ * add the control-plane entry with that release as its minAppVersion. */+export const NEXT_MANAGED_COMPANION_HOST_SUFFIX = "";++/** Every zone the control plane makes addresses in, lowercase apex names. Ship a new domain here first. */+export const MANAGED_COMPANION_HOST_SUFFIXES = Object.freeze(+ ["openmausbot.com", "mausbot.si", NEXT_MANAGED_COMPANION_HOST_SUFFIX].filter(Boolean),+);++/** Only the control plane's `c-<32 hex>` names: any other name in those zones never receives a pairing code. */+export function managedCompanionHostname(hostname) {+ const match = /^c-[0-9a-f]{32}\.(.+)$/.exec(String(hostname ?? ""));+ return Boolean(match) && MANAGED_COMPANION_HOST_SUFFIXES.includes(match[1]);+}/** HTTPS, or a Tailscale MagicDNS name (WireGuard protects its HTTP); a LAN IP would put the long-lived bearer on Wi-Fi in plaintext. */export function normalizeDesktopCompanionEndpoint(value) {@@ -60,7 +72,7 @@ export function normalizeDesktopCompanionEndpoint(value) {const hostname = parsed.hostname.toLowerCase();const tailscaleHttp = parsed.protocol === "http:" && hostname.endsWith(".ts.net");const managedHttps =- parsed.protocol === "https:" && MANAGED_COMPANION_HOSTNAME.test(hostname);+ parsed.protocol === "https:" && managedCompanionHostname(hostname);if ((!tailscaleHttp && !managedHttps) ||parsed.username ||diff --git a/electron/desktop-companion-client.test.mjs b/electron/desktop-companion-client.test.mjsindex 8df12958aa..4024c9b493 100644--- a/electron/desktop-companion-client.test.mjs+++ b/electron/desktop-companion-client.test.mjs@@ -6,6 +6,8 @@ import os from "node:os";import path from "node:path";import {DESKTOP_COMPANION_FIELD,+ MANAGED_COMPANION_HOST_SUFFIXES,+ NEXT_MANAGED_COMPANION_HOST_SUFFIX,desktopCompanionAccess,desktopCompanionRendererArguments,desktopCompanionProxyTarget,@@ -104,6 +106,32 @@ describe("desktop companion endpoint", () => {}});+ it("accepts one c-<32 hex> label under each listed domain, and only those", () => {+ // The third domain is a one-line change; until the owner names it, nothing new is accepted.+ expect(NEXT_MANAGED_COMPANION_HOST_SUFFIX).toBe("");+ expect(MANAGED_COMPANION_HOST_SUFFIXES).toEqual(["openmausbot.com", "mausbot.si"]);+ expect(Object.isFrozen(MANAGED_COMPANION_HOST_SUFFIXES)).toBe(true);+ for (const suffix of MANAGED_COMPANION_HOST_SUFFIXES) {+ expect(suffix).toMatch(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/);+ expect(normalizeDesktopCompanionEndpoint(`https://${LABEL}.${suffix}`)).toBe(`https://${LABEL}.${suffix}`);+ expect(normalizeDesktopCompanionEndpoint(`${LABEL.toUpperCase().replace("C-", "c-")}.${suffix}`))+ .toBe(`https://${LABEL}.${suffix}`);+ for (const near of [+ `https://${LABEL}.${suffix}.`,+ `https://${LABEL}.x${suffix}`,+ `https://${LABEL}.sub.${suffix}`,+ `https://${LABEL.slice(0, -1)}g.${suffix}`,+ `https://${LABEL}.${suffix}.example.net`,+ `https://c-.${suffix}`,+ ]) {+ expect(normalizeDesktopCompanionEndpoint(near), near).toBe("");+ }+ }+ for (const unlisted of ["example.net", "openmausbot.net", "mausbot.com", "si", "com", ""]) {+ expect(normalizeDesktopCompanionEndpoint(`https://${LABEL}.${unlisted}`), unlisted).toBe("");+ }+ });+it("validates, adds, and removes the encrypted credential document field", () => {const hostedAccess = { ...access, endpoint: `https://${LABEL}.openmausbot.com` };expect(desktopCompanionAccess({ [DESKTOP_COMPANION_FIELD]: hostedAccess })).toEqual(diff --git a/src/components/CompanionSection.reveal.test.ts b/src/components/CompanionSection.reveal.test.tsindex cef6c4dd92..ac0c13e36a 100644--- a/src/components/CompanionSection.reveal.test.ts+++ b/src/components/CompanionSection.reveal.test.ts@@ -3,7 +3,7 @@ import { renderToStaticMarkup } from "react-dom/server";import { beforeEach, expect, it, vi } from "vitest";// React's hooks are replayed by hand.-const f = vi.hoisted(() => ({ values: [] as unknown[], index: 0, effects: [] as EffectCallback[], revealed: [] as unknown[], state: null as object | null }));+const f = vi.hoisted(() => ({ values: [] as unknown[], index: 0, effects: [] as EffectCallback[], revealed: [] as unknown[], state: null as object | null, account: null as object | null, bridge: null as object | null, accountAct: (() => undefined) as (call: (remote: never) => unknown) => unknown }));vi.mock("react", async (original) => ({...await original<typeof import("react")>(),useRef: (initial: unknown) => { const index = f.index++; if (!(index in f.values)) f.values[index] = { current: initial }; return f.values[index]; },@@ -13,7 +13,8 @@ vi.mock("../lib/phone-pairing", () => ({ revealPhonePairing: (root: unknown) =>vi.mock("@/state/store", () => ({ useStore: () => ({ state: { config: {} } }) }));vi.mock("./PhoneSetupFlow", () => ({companionBridge: () => ({}),- usePhoneSetupController: () => ({ state: f.state, busy: false, accountBusy: false, account: null, accountError: null, error: null, localFallback: false, tailscaleFallback: false, tailscaleAvailable: false, hostedReady: false }),+ companionAccountBridge: () => f.bridge,+ usePhoneSetupController: () => ({ state: f.state, busy: false, accountBusy: false, account: f.account, accountAct: f.accountAct, accountError: null, error: null, localFallback: false, tailscaleFallback: false, tailscaleAvailable: false, hostedReady: false }),PhoneSetupFlowView: () => null,companionAccountActionError: () => null,loadCompanionBridgeState: () => null,@@ -28,7 +29,7 @@ function render(focusRequest: number) {}const flow = () => f.values[0] as { current: unknown };-beforeEach(() => { f.values = []; f.index = 0; f.effects = []; f.revealed = []; f.state = null; });+beforeEach(() => { f.values = []; f.index = 0; f.effects = []; f.revealed = []; f.state = null; f.account = null; f.bridge = null; f.accountAct = () => undefined; });it("waits for the phone flow to be drawn, then reveals it once per request", () => {render(1);@@ -73,3 +74,47 @@ it("reveals again after Settings went elsewhere and came back on a new request",render(1);expect(f.revealed).toEqual([card, card]);});++const PAUSED_LINE = "Paused after 30 days unused. It reconnects when you open this page.";+const unusedPhone = { id: "phone-1", name: "Ada", lastSeenAt: Date.now() - 40 * 24 * 60 * 60_000, cloudDesktopAccess: false };++function visit() {+ f.index = 0; f.effects = [];+ const markup = renderToStaticMarkup(createElement(() => CompanionSection({})));+ // CompanionSection's own effects come first: the reveal, then the resume. Later ones belong to child lists.+ f.effects[1]!();+ return markup;+}++it("brings a paused address back when the page opens, once, and says so under the phone", () => {+ const calls: string[] = [];+ f.bridge = { prepare: () => { calls.push("prepare"); return Promise.resolve({}); }, state: () => { calls.push("state"); return Promise.resolve({}); } };+ f.accountAct = (call) => call(f.bridge as never);+ f.account = { available: true, status: "ready", email: "[email protected]", paused: true };+ f.state = { enabled: true, devices: [unusedPhone], port: 8810 };++ expect(visit()).toContain(PAUSED_LINE);+ expect(calls).toEqual(["prepare"]);+ visit();+ expect(calls).toEqual(["prepare"]);+});++it("asks for no address, and shows no pause, unless the address is paused with a phone paired and Remote access on", () => {+ for (const [account, state] of [+ [{ available: true, status: "ready" }, { enabled: true, devices: [unusedPhone], port: 8810 }],+ [{ available: true, status: "ready", paused: true }, { enabled: true, devices: [], port: 8810 }],+ [{ available: true, status: "ready", paused: true }, { enabled: false, devices: [unusedPhone], port: 8810 }],+ [{ available: true, status: "ready", paused: true }, { enabled: true, devices: [unusedPhone], port: 8810, error: "down" }],+ [{ available: false, status: "signed-out", paused: true }, { enabled: true, devices: [unusedPhone], port: 8810 }],+ ] as const) {+ f.values = [];+ const calls: string[] = [];+ f.bridge = { prepare: () => { calls.push("prepare"); return Promise.resolve({}); } };+ f.accountAct = (call) => call(f.bridge as never);+ f.account = account;+ f.state = state;+ const markup = visit();+ expect(calls, JSON.stringify([account, state])).toEqual([]);+ if (!("paused" in account)) expect(markup).not.toContain(PAUSED_LINE);+ }+});diff --git a/src/components/CompanionSection.tsx b/src/components/CompanionSection.tsxindex 6f557e86ab..f683c09441 100644--- a/src/components/CompanionSection.tsx+++ b/src/components/CompanionSection.tsx@@ -9,9 +9,11 @@ import {Trash2,Wifi,} from "lucide-react";+import type { CompanionAccountState } from "../types/ogb";import {PhoneSetupFlowView,companionAccountActionError,+ companionAccountBridge,companionBridge,loadCompanionBridgeState,shouldHydrateCompanionEmail,@@ -118,6 +120,14 @@ export function deriveCompanionPanelStatus(};}+/** Opening this page is what brings a paused address back: no button. */+export function shouldResumePausedAddress(+ account: CompanionAccountState | null,+ state: Pick<CompanionState, "enabled" | "devices" | "error"> | null,+): boolean {+ return account?.paused === true && account.available && state?.enabled === true && !state.error && state.devices.length > 0;+}+export const relative = (at: number) => {const seconds = Math.round((Date.now() - at) / 1000);if (seconds < 90) return t("remote.time.justNow");@@ -146,6 +156,14 @@ export function CompanionSection({ profileEmail = "", focusRequest = 0 }: { profif (!focusRequest) revealed.current = 0;else if (revealed.current !== focusRequest && revealPhonePairing(pairingFlow.current)) revealed.current = focusRequest;}, [focusRequest, loaded]);+ const resumeAsked = useRef(false);+ const resumePaused = shouldResumePausedAddress(c.account, state);+ const { accountAct } = c;+ useEffect(() => {+ if (!resumePaused || resumeAsked.current || !companionAccountBridge()?.prepare) return;+ resumeAsked.current = true;+ void accountAct((remote) => remote.prepare?.() ?? remote.state());+ }, [resumePaused, accountAct]);const managedPolicy = useStore().state.config?.managedPolicy;const remoteBlocked = managedPolicy?.remoteAccess === false ? t("policy.remoteBlocked", { organization: managedPolicy.organizationName }) : null;const managedBy = managedPolicy?.remoteAccess === false ? t("policy.managedBy", { organization: managedPolicy.organizationName }) : null;@@ -250,6 +268,7 @@ export function CompanionSection({ profileEmail = "", focusRequest = 0 }: { prof<div className="min-w-0 flex-1"><div className="truncate text-[14px] font-medium text-ink">{device.name}</div><div className="text-[12px] text-ink-secondary">{t("remote.devices.lastSeen", { when: relative(device.lastSeenAt) })}</div>+ {c.account?.paused && <div className="text-[12px] text-ink-secondary">{t("remote.devices.paused")}</div>}</div><buttondisabled={c.busy}diff --git a/src/locales/de.json b/src/locales/de.jsonindex 9b10f5c15f..6518fac823 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -1556,6 +1556,7 @@"remote.devices.subtitle": "Verwalte die Geräte, die dieses {app} nutzen dürfen.","remote.devices.empty": "Noch sind keine Geräte gekoppelt.","remote.devices.lastSeen": "Zuletzt gesehen {when}",+ "remote.devices.paused": "Nach 30 Tagen ohne Nutzung pausiert. Es verbindet sich wieder, wenn du diese Seite öffnest.","remote.devices.remove": "{name} entfernen","remote.devices.allowView": "Computeransicht erlauben","remote.devices.allowViewDetail": "Vollständiger interaktiver Zugriff von diesem Gerät.",diff --git a/src/locales/en.json b/src/locales/en.jsonindex c816725a47..eba521b983 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -4454,6 +4454,7 @@"remote.devices.subtitle": "Manage the devices that can use this {app}.","remote.devices.empty": "No devices are paired yet.","remote.devices.lastSeen": "Last seen {when}",+ "remote.devices.paused": "Paused after 30 days unused. It reconnects when you open this page.","remote.devices.remove": "Remove {name}","remote.devices.allowView": "Allow computer view","remote.devices.allowViewDetail": "Full interactive access from this device.",diff --git a/src/locales/es.json b/src/locales/es.jsonindex 0f8de02f27..3836fc784a 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -3497,6 +3497,7 @@"remote.devices.subtitle": "Gestiona los dispositivos que pueden usar este {app}.","remote.devices.empty": "Todavía no hay dispositivos emparejados.","remote.devices.lastSeen": "Visto por última vez {when}",+ "remote.devices.paused": "En pausa tras 30 días sin uso. Se vuelve a conectar cuando abres esta página.","remote.devices.remove": "Quitar {name}","remote.devices.allowView": "Permitir ver el equipo","remote.devices.allowViewDetail": "Acceso interactivo completo desde este dispositivo.",diff --git a/src/locales/fr.json b/src/locales/fr.jsonindex e5e0682604..3f2ac1385b 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -1500,6 +1500,7 @@"remote.devices.subtitle": "Gérez les appareils autorisés à utiliser ce {app}.","remote.devices.empty": "Aucun appareil associé pour l'instant.","remote.devices.lastSeen": "Vu pour la dernière fois {when}",+ "remote.devices.paused": "En pause après 30 jours sans utilisation. Il se reconnecte quand vous ouvrez cette page.","remote.devices.remove": "Retirer {name}","remote.devices.allowView": "Autoriser la vue de l'ordinateur","remote.devices.allowViewDetail": "Accès interactif complet depuis cet appareil.",diff --git a/src/locales/hi.json b/src/locales/hi.jsonindex 890aa8a00f..40ea729f2d 100644--- a/src/locales/hi.json+++ b/src/locales/hi.json@@ -1500,6 +1500,7 @@"remote.devices.subtitle": "इस {app} का उपयोग कर सकने वाले डिवाइस प्रबंधित करें।","remote.devices.empty": "अभी कोई डिवाइस जुड़ा नहीं है।","remote.devices.lastSeen": "आख़िरी बार देखा गया {when}",+ "remote.devices.paused": "30 दिन इस्तेमाल न होने पर रोका गया। यह पेज खोलने पर यह फिर से जुड़ जाता है।","remote.devices.remove": "{name} हटाएँ","remote.devices.allowView": "कंप्यूटर देखने की अनुमति","remote.devices.allowViewDetail": "इस डिवाइस से पूरा इंटरैक्टिव एक्सेस।",diff --git a/src/locales/it.json b/src/locales/it.jsonindex 5d72049127..81576dbac0 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -3749,6 +3749,7 @@"remote.devices.subtitle": "Gestisci i dispositivi che possono usare questo {app}.","remote.devices.empty": "Nessun dispositivo abbinato per ora.","remote.devices.lastSeen": "Visto l'ultima volta {when}",+ "remote.devices.paused": "In pausa dopo 30 giorni di inutilizzo. Si ricollega quando apri questa pagina.","remote.devices.remove": "Rimuovi {name}","remote.devices.allowView": "Consenti la vista del computer","remote.devices.allowViewDetail": "Accesso interattivo completo da questo dispositivo.",diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex 475ac6027c..3c57462125 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -4301,6 +4301,7 @@"remote.devices.subtitle": "この {app} を使えるデバイスを管理します。","remote.devices.empty": "まだペアリング済みのデバイスはありません。","remote.devices.lastSeen": "最後に確認:{when}",+ "remote.devices.paused": "30 日間使われなかったため一時停止中です。このページを開くと再接続されます。","remote.devices.remove": "{name} を削除","remote.devices.allowView": "コンピューター表示を許可","remote.devices.allowViewDetail": "このデバイスからの完全な操作アクセスです。",diff --git a/src/locales/ko.json b/src/locales/ko.jsonindex aba845e535..3a5ae445da 100644--- a/src/locales/ko.json+++ b/src/locales/ko.json@@ -4119,6 +4119,7 @@"remote.devices.subtitle": "이 {app}을(를) 쓸 수 있는 기기를 관리해요.","remote.devices.empty": "아직 페어링된 기기가 없어요.","remote.devices.lastSeen": "마지막 접속 {when}",+ "remote.devices.paused": "30일 동안 사용하지 않아 일시 중지됐어요. 이 페이지를 열면 다시 연결돼요.","remote.devices.remove": "{name} 제거","remote.devices.allowView": "컴퓨터 보기 허용","remote.devices.allowViewDetail": "이 기기에서 완전히 조작할 수 있어요.",diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex 1c4a1aa0bc..00ec3faaa3 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -3814,6 +3814,7 @@"remote.devices.subtitle": "Zarządzaj urządzeniami uprawnionymi do korzystania z aplikacji {app}.","remote.devices.empty": "Nie sparowano jeszcze żadnych urządzeń.","remote.devices.lastSeen": "Ostatnio widziano: {when}",+ "remote.devices.paused": "Wstrzymano po 30 dniach bez użycia. Połączy się ponownie, gdy otworzysz tę stronę.","remote.devices.remove": "Usuń: {name}","remote.devices.allowView": "Zezwól na widok komputera","remote.devices.allowViewDetail": "Pełny interaktywny dostęp z tego urządzenia.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 6590d7359d..010a5410a7 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -4201,6 +4201,7 @@"remote.devices.subtitle": "Gerencie os dispositivos que podem usar esta instalação de {app}.","remote.devices.empty": "Nenhum dispositivo pareado ainda.","remote.devices.lastSeen": "Visto por último {when}",+ "remote.devices.paused": "Pausado após 30 dias sem uso. Ele se reconecta quando você abre esta página.","remote.devices.remove": "Remover {name}","remote.devices.allowView": "Permitir ver o computador","remote.devices.allowViewDetail": "Acesso interativo completo a partir deste dispositivo.",diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex 1a0357f4d9..77d923e89b 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -3870,6 +3870,7 @@"remote.devices.subtitle": "Управляйте устройствами, которые могут использовать этот {app}.","remote.devices.empty": "Сопряжённых устройств пока нет.","remote.devices.lastSeen": "Последняя активность: {when}",+ "remote.devices.paused": "Приостановлено после 30 дней без использования. Подключится снова, когда вы откроете эту страницу.","remote.devices.remove": "Удалить {name}","remote.devices.allowView": "Разрешить просмотр компьютера","remote.devices.allowViewDetail": "Полный интерактивный доступ с этого устройства.",diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex 371e366b4d..a1976958a8 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -3163,6 +3163,7 @@"remote.devices.subtitle": "Bu {app} uygulamasını kullanabilen cihazları yönetin.","remote.devices.empty": "Henüz eşleştirilmiş cihaz yok.","remote.devices.lastSeen": "Son görülme: {when}",+ "remote.devices.paused": "30 gün kullanılmadığı için duraklatıldı. Bu sayfayı açtığınızda yeniden bağlanır.","remote.devices.remove": "{name} cihazını kaldır","remote.devices.allowView": "Bilgisayar görünümüne izin ver","remote.devices.allowViewDetail": "Bu cihazdan tam etkileşimli erişim.",diff --git a/src/locales/uk.json b/src/locales/uk.jsonindex afa02222cb..ed3e03ad58 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -1817,6 +1817,7 @@"remote.devices.subtitle": "Керуйте пристроями, що можуть користуватися цим {app}.","remote.devices.empty": "Прив'язаних пристроїв ще немає.","remote.devices.lastSeen": "Остання поява {when}",+ "remote.devices.paused": "Призупинено після 30 днів без використання. Під'єднається знову, коли ви відкриєте цю сторінку.","remote.devices.remove": "Прибрати {name}","remote.devices.allowView": "Дозволити перегляд комп'ютера","remote.devices.allowViewDetail": "Повний інтерактивний доступ із цього пристрою.",diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex 7ecb675564..b70fe12e33 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -3163,6 +3163,7 @@"remote.devices.subtitle": "Quản lý các thiết bị có thể sử dụng {app} này.","remote.devices.empty": "Chưa có thiết bị nào được ghép nối.","remote.devices.lastSeen": "Hoạt động lần cuối {when}",+ "remote.devices.paused": "Đã tạm dừng sau 30 ngày không dùng. Sẽ kết nối lại khi bạn mở trang này.","remote.devices.remove": "Gỡ {name}","remote.devices.allowView": "Cho phép xem màn hình máy tính","remote.devices.allowViewDetail": "Toàn quyền truy cập tương tác từ thiết bị này.",diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex 055237c6f1..7b907de3b2 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -2683,6 +2683,7 @@"remote.devices.subtitle": "管理可以使用此 {app} 的裝置。","remote.devices.empty": "尚未配對任何裝置。","remote.devices.lastSeen": "上次出現於 {when}",+ "remote.devices.paused": "30 天未使用,已暫停。開啟此頁面時會重新連線。","remote.devices.remove": "移除 {name}","remote.devices.allowView": "允許存取電腦畫面","remote.devices.allowViewDetail": "可從此裝置進行完整的互動式操作。",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex c243403667..72d1f1c2c5 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -4270,6 +4270,7 @@"remote.devices.subtitle": "管理可以使用这个 {app} 的设备。","remote.devices.empty": "还没有配对任何设备。","remote.devices.lastSeen": "最后在线 {when}",+ "remote.devices.paused": "30 天未使用,已暂停。打开此页面时会重新连接。","remote.devices.remove": "移除 {name}","remote.devices.allowView": "允许查看电脑","remote.devices.allowViewDetail": "来自这台设备的完全交互访问。",diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.tsindex c9008b6b8c..c7843c9e4e 100644--- a/src/types/ogb.d.ts+++ b/src/types/ogb.d.ts@@ -500,6 +500,9 @@ export interface CompanionAccountState {email?: string;endpoint?: string;message?: string;+ /** The HTTPS address was given back after 30 days with no paired phone+ * seen. Opening the phone page calls prepare(), which brings it back. */+ paused?: boolean;}export type AndroidUsbDevice = {