Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Phone & devices: step-by-step connection check, relay reconnect timing and hello watchdog (#5928)

Milind Soni05318b58097d
diff --git a/NOTICE b/NOTICE
index 6667b96457..59ef3af0af 100644
--- a/NOTICE
+++ b/NOTICE
@@ -29,6 +29,11 @@ The updatable model manifest (server/model-manifest/) adapts the model manifest
cache and schema of an MIT-licensed project, Copyright 2026 T3 Tools Inc., used
under the MIT License (third_party/t3-code/LICENSE).
+The remote access diagnosis (src/lib/remote-access-diagnosis.ts) adapts the
+connection diagnosis model (packages/client-runtime/src/connection/diagnosis.ts)
+of an MIT-licensed project, Copyright 2026 T3 Tools Inc., used under the MIT
+License (third_party/t3-code/LICENSE).
+
Prompt-cache keep-warm (server/cache-keepwarm.ts and
server/drivers/claude-keepwarm.ts) ports the design of Cache Tax,
https://github.com/karanb192/claude-code-mods, Copyright (c) 2026 Karan
diff --git a/companion/src/control.ts b/companion/src/control.ts
index ce9f4bdf5e..c796325cd5 100644
--- a/companion/src/control.ts
+++ b/companion/src/control.ts
@@ -51,6 +51,8 @@ export interface E2EStatus {
enabled: boolean;
relay: "connected" | "connecting" | "off";
node: string | null;
+ /** Why the relay's control socket is not connected; null once the relay acknowledged it. */
+ relayProblem?: "no_answer" | "token_refused" | "busy" | "unreachable" | "replaced" | null;
/** What the pairing QR carries as `e2e`. */
descriptor: E2EDescriptor | null;
}
diff --git a/companion/src/e2e/README.md b/companion/src/e2e/README.md
index e768053cf0..ff81c9ce5a 100644
--- a/companion/src/e2e/README.md
+++ b/companion/src/e2e/README.md
@@ -228,7 +228,7 @@ This uses the yamux wire format (`hashicorp/yamux` spec): a 12-byte header of `v
| Dir | Message | Meaning |
|---|---|---|
| host→relay | `{"t":"auth","v":1,"token":"<relay token>"}` | First message. Sent again to refresh before `exp`. Must keep the same `hid` |
-| relay→host | `{"t":"hello","v":1,"node":"relay1","sessionsMax":16}` | Auth accepted |
+| relay→host | `{"t":"hello","v":1,"node":"relay1","sessionsMax":16}` | Auth accepted. Every later `auth` on the same socket is acknowledged with `hello` too, which the host uses as a liveness check |
| host→relay | `{"t":"admit","set":["<b64u SHA256(adm)>",…]}` | The full replacement admission set, at most 32 entries. Required within 5 s of `hello`, and again on every pair, revoke, restriction change, or pairing window open or close. Sessions whose `adm` leaves the set are closed with 4404 |
| relay→host | `{"t":"open","sid":"<b64u 16 bytes>"}` | A phone is waiting. The host must open a data socket within 10 s |
| relay→host | `{"t":"restarting","reconnectInMs":0,"tryForMs":15000}` | Deploy or shutdown. Reconnect after `reconnectInMs + random(0, tryForMs)` |
@@ -284,7 +284,10 @@ own the `sid`, and a `sid` is single-use with a 10 s life. The relay then splice
| yamux ping | Every 20 s; dead if no answer in 10 s |
| Relay WebSocket ping (to every socket it owns) | Every 20 s; dead if no pong in 10 s |
| Phone direct attempt timeout / relay attempt timeout | 5 s / 10 s |
-| Host reconnect after loss | Immediate, then 1, 2, 4 … 60 s with ±20% jitter |
+| Host reconnect after loss | Immediate, then 1, 2, 4 … 60 s with ±20% jitter. The count resets only after a control socket has stayed connected 30 s, so a relay that accepts and then drops the socket at once is not redialled in a loop. After 4429, at least 30 s |
+| Host waits for `hello` | 15 s after dialling; then the socket is dropped and the next node dialled with the backoff above |
+| Host liveness check | Every 2 min ±20% while connected, and when the network changes: an `auth` with the current token, answered by `hello` within 10 s, or the socket is dropped and dialled again with the backoff above, after at least a random 0–5 s |
+| Host on a network change while not connected | After a failed or silent dial, dial now (the backoff count stays). A wait the relay asked for (4429, 4503, `restarting`) or a wait for a token is kept |
| Host reconnect after `restarting` / 4503 | `reconnectInMs + random(0, tryForMs)`; default random 1–15 s |
| Sleep detection (desktop) | A wall-clock jump of more than 5 s against the monotonic clock, checked every 2 s, or Electron `powerMonitor` `resume`: redial now |
| Host returns to its first node | While on a later node, try the first every 10 min ±2 min. Move when it accepts: open the new control socket, then close the old one |
diff --git a/companion/src/e2e/relay-client.ts b/companion/src/e2e/relay-client.ts
index 8ac1cc01fe..e779d772ba 100644
--- a/companion/src/e2e/relay-client.ts
+++ b/companion/src/e2e/relay-client.ts
@@ -5,15 +5,34 @@ import type { RecordTransport } from "./session.ts";
export const RELAY_PROTOCOL = "omb-relay.v1";
export type RelayStatus = "connected" | "connecting" | "off";
+/** Why the control socket is not connected, in words the desktop's diagnosis maps: no hello in time ("no_answer"), the
+ * token refused (4401), the relay busy or restarting (4429, 4503, `restarting`), the socket failed or closed
+ * ("unreachable"), or another socket for this computer took over (4409). */
+export type RelayProblem = "no_answer" | "token_refused" | "busy" | "unreachable" | "replaced";
-const BACKOFF_MS = [0, 1_000, 2_000, 4_000, 8_000, 16_000, 32_000, 60_000];
+/** README section 10: 4429 means back off at least this long. */
+const LIMITED_MIN_MS = 30_000;
const DEFAULT_TIMING = {
+ /** Reconnect delays by failure count (± a fifth); the last repeats. */
+ backoffMs: [0, 1_000, 2_000, 4_000, 8_000, 16_000, 32_000, 60_000],
/** While on a later node, how often to try the first one again (± a fifth). */
firstNodeRetryMs: 10 * 60_000,
sleepCheckMs: 2_000,
sleepJumpMs: 5_000,
/** The pairing window expires on its own; the admission set is rechecked this often. */
admissionCheckMs: 5_000,
+ /** The backoff count resets only once a control socket has stayed connected this long. */
+ stableAfterMs: 30_000,
+ /** A dialled control socket with no `hello` by then is dropped and dialled again with backoff. */
+ helloTimeoutMs: 15_000,
+ /** A connected socket is asked to answer (a token refresh, which the relay acknowledges with `hello`) this often
+ * (± a fifth), and on every `checkAlive()`. */
+ livenessEveryMs: 2 * 60_000,
+ /** A liveness check unanswered this long means the socket is dead: it is dropped and dialled again with backoff. */
+ livenessTimeoutMs: 10_000,
+ /** That redial waits a random part of this at least, so the hosts a stalled node drops at once don't all redial at
+ * once. */
+ redialSpreadMs: 5_000,
};
export interface SessionSink {
@@ -57,12 +76,17 @@ export class RelayClient {
#controlNode = 0;
#probe: WebSocket | null = null;
#status: RelayStatus = "off";
+ #problem: RelayProblem | null = null;
#attempt = 0;
#stopped = true;
#awaitingToken = false;
#lastAdmit = "";
#retryTimer: ReturnType<typeof setTimeout> | null = null;
+ #retryIndex = 0;
#firstNodeTimer: ReturnType<typeof setTimeout> | null = null;
+ #stableTimer: ReturnType<typeof setTimeout> | null = null;
+ #ackTimer: ReturnType<typeof setTimeout> | null = null;
+ #livenessTimer: ReturnType<typeof setTimeout> | null = null;
#intervals: Array<ReturnType<typeof setInterval>> = [];
constructor(options: RelayClientOptions) {
@@ -81,9 +105,15 @@ export class RelayClient {
return this.#status === "connected" ? this.#nodes[this.#controlNode] ?? null : null;
}
+ /** The last reason the control socket dropped or failed to connect; null once the relay acknowledged it. */
+ get problem(): RelayProblem | null {
+ return this.#status === "off" && this.#problem !== "replaced" ? null : this.#problem;
+ }
+
start(): void {
if (!this.#stopped) return;
this.#stopped = false;
+ this.#problem = null;
this.#setStatus("connecting");
this.#connect(0);
let wall = Date.now();
@@ -129,7 +159,7 @@ export class RelayClient {
if (this.#status === "connected") this.#control?.send(JSON.stringify({ t: "auth", v: 1, token }));
}
- /** After sleep, a network change or a resume: drop the control socket and dial the first node now. */
+ /** After sleep or a resume: drop the control socket and dial the first node now. */
redial(): void {
if (this.#stopped) return;
this.#clearTimers();
@@ -141,6 +171,18 @@ export class RelayClient {
this.#connect(0);
}
+ /** The network changed. A connected socket must answer a liveness check or it is dialled again; a socket waiting out
+ * its backoff after a failed or silent dial dials now, keeping its backoff count. A wait the relay asked for (4429,
+ * 4503, `restarting`) and one for a token are kept. */
+ checkAlive(): void {
+ if (this.#stopped || this.#awaitingToken) return;
+ if (this.#status === "connected") return this.#probeLiveness();
+ if (!this.#retryTimer || (this.#problem !== "unreachable" && this.#problem !== "no_answer")) return;
+ clearTimeout(this.#retryTimer);
+ this.#retryTimer = null;
+ this.#connect(this.#retryIndex);
+ }
+
/** Sends the full set whenever it differs from the last one sent. */
refreshAdmission(force = false): void {
if (this.#status !== "connected" || !this.#control) return;
@@ -165,6 +207,58 @@ export class RelayClient {
for (const timer of [this.#retryTimer, this.#firstNodeTimer]) if (timer) clearTimeout(timer);
this.#retryTimer = null;
this.#firstNodeTimer = null;
+ this.#clearSocketTimers();
+ }
+
+ #clearSocketTimers(): void {
+ for (const timer of [this.#stableTimer, this.#ackTimer, this.#livenessTimer]) if (timer) clearTimeout(timer);
+ this.#stableTimer = null;
+ this.#ackTimer = null;
+ this.#livenessTimer = null;
+ }
+
+ #timer(callback: () => void, ms: number): ReturnType<typeof setTimeout> {
+ const timer = setTimeout(callback, ms);
+ timer.unref?.();
+ return timer;
+ }
+
+ /** The relay acknowledges a token refresh on a live socket with `hello`; silence means the socket is dead. */
+ #probeLiveness(): void {
+ const socket = this.#control;
+ if (!socket || this.#ackTimer || socket.readyState !== WebSocket.OPEN) return;
+ socket.send(JSON.stringify({ t: "auth", v: 1, token: this.#token }));
+ this.#ackTimer = this.#timer(() => this.#unanswered(socket), this.#timing.livenessTimeoutMs);
+ }
+
+ #scheduleLiveness(): void {
+ if (this.#livenessTimer) clearTimeout(this.#livenessTimer);
+ this.#livenessTimer = this.#timer(() => {
+ this.#livenessTimer = null;
+ this.#probeLiveness();
+ }, jitter(this.#timing.livenessEveryMs, this.#random));
+ }
+
+ /** A control socket that never said `hello`, or stopped answering: dropped without waiting for its close, and
+ * dialled again once, with backoff. */
+ #unanswered(socket: WebSocket): void {
+ this.#ackTimer = null;
+ if (socket !== this.#control || this.#stopped) return;
+ const wasConnected = this.#status === "connected";
+ this.#control = null;
+ this.#clearSocketTimers();
+ socket.close(1000);
+ this.#problem = "no_answer";
+ this.#setStatus("connecting");
+ if (wasConnected) this.#backOff(this.#controlNode, this.#random() * this.#timing.redialSpreadMs);
+ else this.#backOff(this.#controlNode + 1);
+ }
+
+ #backOff(index: number, atLeastMs = 0): void {
+ const ladder = this.#timing.backoffMs;
+ const delay = jitter(ladder[Math.min(this.#attempt, ladder.length - 1)], this.#random);
+ this.#attempt += 1;
+ this.#retry(index, Math.max(atLeastMs, delay));
}
#connect(index: number, probe = false): void {
@@ -172,7 +266,12 @@ export class RelayClient {
const nodeIndex = index % this.#nodes.length;
const socket = new WebSocket(this.#url(this.#nodes[nodeIndex], "/v1/host"), [RELAY_PROTOCOL]);
if (probe) this.#probe = socket;
- else this.#control = socket;
+ else {
+ this.#control = socket;
+ this.#controlNode = nodeIndex;
+ this.#clearSocketTimers();
+ this.#ackTimer = this.#timer(() => this.#unanswered(socket), this.#timing.helloTimeoutMs);
+ }
socket.onopen = () => socket.send(JSON.stringify({ t: "auth", v: 1, token: this.#token }));
socket.onmessage = (event: MessageEvent) => {
if (typeof event.data !== "string") return;
@@ -190,6 +289,11 @@ export class RelayClient {
#onControlMessage(socket: WebSocket, nodeIndex: number, message: ControlMessage): void {
if (message.t === "hello") {
+ if (socket === this.#control && this.#status === "connected") {
+ if (this.#ackTimer) clearTimeout(this.#ackTimer);
+ this.#ackTimer = null;
+ return this.#scheduleLiveness();
+ }
if (socket === this.#probe) {
// Back on the first node: the new socket first, then the old one goes.
this.#probe = null;
@@ -199,11 +303,17 @@ export class RelayClient {
}
if (socket !== this.#control) return;
this.#controlNode = nodeIndex;
- this.#attempt = 0;
+ this.#clearSocketTimers();
+ this.#stableTimer = this.#timer(() => {
+ this.#stableTimer = null;
+ this.#attempt = 0;
+ }, this.#timing.stableAfterMs);
+ this.#problem = null;
this.#lastAdmit = "";
this.#setStatus("connected");
this.refreshAdmission(true);
this.#scheduleFirstNode();
+ this.#scheduleLiveness();
return;
}
if (socket !== this.#control) return;
@@ -213,7 +323,10 @@ export class RelayClient {
if (message.t === "restarting") {
const wait = (Number(message.reconnectInMs) || 0) + this.#random() * (Number(message.tryForMs) || 15_000);
this.#control = null;
+ this.#clearSocketTimers();
socket.close(1000);
+ this.#problem = "busy";
+ this.#setStatus("connecting");
this.#retry(nodeIndex + 1, Math.min(wait, 60_000));
}
}
@@ -225,8 +338,14 @@ export class RelayClient {
}
if (socket !== this.#control || this.#stopped) return;
this.#control = null;
- if (code === 4409) return this.stop();
+ this.#clearSocketTimers();
+ if (code === 4409) {
+ this.stop();
+ this.#problem = "replaced";
+ return;
+ }
const wasConnected = this.#status === "connected";
+ this.#problem = code === 4401 ? "token_refused" : code === 4503 || code === 4429 ? "busy" : "unreachable";
this.#setStatus("connecting");
if (code === 4401) {
this.#awaitingToken = true;
@@ -242,14 +361,13 @@ export class RelayClient {
}
return this.#retry(nodeIndex + 1, Math.min(retryInMs, 60_000) + this.#random() * 1_000);
}
- const delay = jitter(BACKOFF_MS[Math.min(this.#attempt, BACKOFF_MS.length - 1)], this.#random);
- this.#attempt += 1;
- this.#retry(wasConnected ? nodeIndex : nodeIndex + 1, delay);
+ this.#backOff(wasConnected ? nodeIndex : nodeIndex + 1, code === 4429 ? LIMITED_MIN_MS : 0);
}
#retry(index: number, delayMs: number): void {
if (this.#stopped) return;
if (this.#retryTimer) clearTimeout(this.#retryTimer);
+ this.#retryIndex = index;
this.#retryTimer = setTimeout(() => {
this.#retryTimer = null;
this.#connect(index);
diff --git a/companion/src/index.ts b/companion/src/index.ts
index 198d9ce0ed..02f7d13875 100755
--- a/companion/src/index.ts
+++ b/companion/src/index.ts
@@ -130,8 +130,9 @@ const relayBaseUrl = relayBaseUrlOverride(process.env.OMB_COMPANION_RELAY_URL);
const watcher = createAddressWatcher({
addresses: advertisableAddresses,
name: machineName,
- advertise: () => mdns.advertise(service()),
- withdraw: () => mdns.stop(),
+ // Called when the address set (or the name) changes: a relay socket that crossed networks may be dead without knowing it.
+ advertise: () => (relay?.checkAlive(), mdns.advertise(service())),
+ withdraw: () => (relay?.checkAlive(), mdns.stop()),
log: (line) => console.log(`bonjour: ${line}`),
// On a Mac a failed join is not papered over by the default-route
// membership, so a join that fails while an interface settles is retried.
@@ -263,7 +264,7 @@ const control = createControlServer({
void watcher.check();
return true;
},
- e2e: () => ({ enabled: e2e.enabled, relay: relay?.status ?? "off", node: relay?.node ?? null, descriptor: e2e.descriptor(null) }),
+ e2e: () => ({ enabled: e2e.enabled, relay: relay?.status ?? "off", node: relay?.node ?? null, relayProblem: relay?.problem ?? null, descriptor: e2e.descriptor(null) }),
liveRoutes: () => e2e.routes(),
// The phone hears where it may connect from inside its session first. Narrowed, the relay keeps it a moment so that
// lands, then refuses it (4404) and its relay sessions close; direct ones stay. Widened, it is admitted before it hears.
diff --git a/companion/test/e2e/fake-relay.ts b/companion/test/e2e/fake-relay.ts
index 8facdaa96e..4cb3caaa89 100644
--- a/companion/test/e2e/fake-relay.ts
+++ b/companion/test/e2e/fake-relay.ts
@@ -32,6 +32,10 @@ export interface FakeRelay {
closes: Array<{ kind: string; code: number }>;
/** Token refreshes accepted on a live control socket. */
refreshes: number;
+ /** Plays a relay whose sockets open but never answer: no `hello`, to an auth or a refresh. */
+ silent: boolean;
+ /** Refuses every token refresh on a live control socket (4401), as for an expired token. */
+ refuseRefresh: boolean;
/** Plays a malicious relay on every session spliced from now on; null passes bytes through. */
tamper: FakeRelayOptions["tamper"] | null;
admitted(hid: string): Set<string>;
@@ -48,7 +52,7 @@ const toBuffer = (data: RawData): Buffer => (Array.isArray(data) ? Buffer.concat
export async function startFakeRelay(options: FakeRelayOptions): Promise<FakeRelay> {
const hosts = new Map<string, Host>();
- const relay = { refreshes: 0, tamper: options.tamper ?? null } as FakeRelay;
+ const relay = { refreshes: 0, silent: false, refuseRefresh: false, tamper: options.tamper ?? null } as FakeRelay;
const closes: FakeRelay["closes"] = [];
const server = createServer((_req, res) => res.writeHead(404).end());
const wss = new WebSocketServer({
@@ -101,6 +105,7 @@ export async function startFakeRelay(options: FakeRelayOptions): Promise<FakeRel
const hostControl = (socket: WebSocket) =>
onFirst(socket, "host", (message) => {
+ if (relay.silent) return;
if (message.t !== "auth" || typeof message.token !== "string") return close(socket, "host", 4400);
const verified = verifyRelayToken(message.token, options.keys, now());
if (!verified.ok) return close(socket, "host", 4401);
@@ -115,8 +120,11 @@ export async function startFakeRelay(options: FakeRelayOptions): Promise<FakeRel
const next = JSON.parse(toBuffer(raw).toString("utf8")) as Record<string, unknown>;
if (next.t === "auth") {
const refreshed = typeof next.token === "string" ? verifyRelayToken(next.token, options.keys, now(), hid) : null;
- if (!refreshed?.ok) close(socket, "host", 4401);
- else relay.refreshes += 1;
+ if (!refreshed?.ok || relay.refuseRefresh) close(socket, "host", 4401);
+ else if (!relay.silent) {
+ relay.refreshes += 1;
+ socket.send(JSON.stringify({ t: "hello", v: 1, node: "relay1", sessionsMax: 16 }));
+ }
} else if (next.t === "admit" && Array.isArray(next.set) && next.set.length <= 32) {
host.set = new Set(next.set as string[]);
for (const session of host.sessions) {
diff --git a/companion/test/e2e/relay-client.test.ts b/companion/test/e2e/relay-client.test.ts
index 79329b89a2..42657705f1 100644
--- a/companion/test/e2e/relay-client.test.ts
+++ b/companion/test/e2e/relay-client.test.ts
@@ -1,6 +1,6 @@
import { createHash, generateKeyPairSync, randomBytes } from "node:crypto";
import { afterEach, describe, expect, it, vi } from "vitest";
-import { WebSocket } from "ws";
+import { WebSocket, WebSocketServer } from "ws";
import { b64u, ed25519RawPublicKey, mintRelayToken } from "../../src/e2e/credentials.ts";
import { RelayClient, type RelayClientOptions } from "../../src/e2e/relay-client.ts";
@@ -34,7 +34,29 @@ async function relayAt(port?: number): Promise<FakeRelay> {
return relay;
}
-function client(relays: Record<string, FakeRelay>, overrides: Partial<RelayClientOptions> = {}) {
+/** A relay that answers each control socket's auth with `script`: how many sockets it saw is the dial count. */
+async function scriptedRelay(script: (socket: WebSocket) => void): Promise<{ url: string; dials: () => number }> {
+ const server = new WebSocketServer({ port: 0, host: "127.0.0.1", handleProtocols: () => "omb-relay.v1" });
+ await new Promise((resolve) => server.once("listening", resolve));
+ let dials = 0;
+ server.on("connection", (socket) => {
+ dials += 1;
+ socket.once("message", () => script(socket));
+ });
+ cleanup.push(() => new Promise((resolve) => {
+ for (const socket of server.clients) socket.terminate();
+ server.close(resolve);
+ }));
+ const { port } = server.address() as { port: number };
+ return { url: `ws://127.0.0.1:${port}`, dials: () => dials };
+}
+
+/** For waits on something that must happen: a runner several times slower than a laptop only stretches them. */
+const SLOW = 15_000;
+const hello = JSON.stringify({ t: "hello", v: 1, node: "relay1", sessionsMax: 16 });
+const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+function client(relays: Record<string, Pick<FakeRelay, "url">>, overrides: Partial<RelayClientOptions> = {}) {
const statuses: string[] = [];
const rejected: number[] = [];
const instance = new RelayClient({
@@ -106,7 +128,10 @@ describe("the relay client", () => {
instance.start();
await waitFor(() => instance.status === "connected");
relay.restart();
- await waitFor(() => statuses.filter((status) => status.startsWith("connected")).length === 2, 5_000);
+ await waitFor(() => instance.problem === "busy", SLOW);
+ expect(instance.status).toBe("connecting");
+ await waitFor(() => statuses.filter((status) => status.startsWith("connected")).length === 2, SLOW);
+ expect(statuses.map((status) => status.split("@")[0])).toEqual(["connecting", "connected", "connecting", "connected"]);
});
it("fails over to the next node, then moves back to the first when it returns", async () => {
@@ -160,4 +185,123 @@ describe("the relay client", () => {
expect(accepted).toHaveLength(1);
phone.close();
});
+
+ it("does not redial in a loop a relay that accepts and drops the socket at once", async () => {
+ const relay = await scriptedRelay((socket) => {
+ socket.send(hello);
+ socket.close(1011);
+ });
+ // Immediate, then a minute: a count that reset on every hello would redial at once, over and over.
+ const { instance } = client({ "relay1.openmausbot.com": relay }, { timing: { backoffMs: [0, 60_000] } });
+ instance.start();
+ await waitFor(() => relay.dials() === 2, SLOW);
+ await waitFor(() => instance.problem === "unreachable", SLOW);
+ await pause(500);
+ expect(relay.dials()).toBe(2);
+ });
+
+ it("resets the backoff once a socket has stayed connected long enough", async () => {
+ const relay = await scriptedRelay((socket) => {
+ socket.send(hello);
+ setTimeout(() => socket.close(1011), 1_000);
+ });
+ // Without the reset, the second drop would wait a minute.
+ const { instance } = client({ "relay1.openmausbot.com": relay }, { timing: { stableAfterMs: 50, backoffMs: [0, 60_000] } });
+ instance.start();
+ await waitFor(() => relay.dials() >= 4, SLOW);
+ });
+
+ it("drops a socket that never says hello and dials the next node", async () => {
+ const silent = await relayAt();
+ silent.silent = true;
+ const second = await relayAt();
+ const { instance } = client({ "relay1.openmausbot.com": silent, "relay2.openmausbot.com": second }, { timing: { helloTimeoutMs: 1_000 } });
+ instance.start();
+ await waitFor(() => instance.node === "relay2.openmausbot.com", SLOW);
+ expect(instance.problem).toBeNull();
+ await waitFor(() => second.admitted(hid).size === 2, SLOW);
+ });
+
+ it("keeps a connected socket that answers its liveness check", async () => {
+ const relay = await relayAt();
+ const { instance } = client({ "relay1.openmausbot.com": relay }, { timing: { livenessTimeoutMs: 5_000 } });
+ instance.start();
+ await waitFor(() => instance.status === "connected", SLOW);
+ const socket = relay.hosts.get(hid)!.control;
+ instance.checkAlive();
+ await waitFor(() => relay.refreshes === 1, SLOW);
+ expect(instance.status).toBe("connected");
+ expect(relay.hosts.get(hid)?.control).toBe(socket);
+ expect(relay.closes).toEqual([]);
+ });
+
+ it("dials again, once and with backoff, when a connected socket stops answering", async () => {
+ const relay = await relayAt();
+ const { instance, statuses } = client({ "relay1.openmausbot.com": relay }, { timing: { livenessTimeoutMs: 200, redialSpreadMs: 600 } });
+ instance.start();
+ await waitFor(() => instance.status === "connected", SLOW);
+ relay.silent = true;
+ instance.checkAlive();
+ await waitFor(() => instance.problem === "no_answer", SLOW);
+ const droppedAt = Date.now();
+ relay.silent = false;
+ await waitFor(() => statuses.filter((status) => status.startsWith("connected")).length === 2, SLOW);
+ // Not at once, though the backoff count is at its first step: a random part of the spread (here half of 600 ms).
+ // A lower bound only: a slow runner makes it longer, never shorter.
+ expect(Date.now() - droppedAt).toBeGreaterThanOrEqual(250);
+ expect(instance.problem).toBeNull();
+ });
+
+ it("waits for a new token when the relay answers a liveness check with 4401", async () => {
+ const relay = await relayAt();
+ const { instance, rejected } = client({ "relay1.openmausbot.com": relay });
+ instance.start();
+ await waitFor(() => instance.status === "connected", SLOW);
+ relay.refuseRefresh = true;
+ instance.checkAlive();
+ await waitFor(() => rejected.length === 1, SLOW);
+ expect(instance.status).toBe("connecting");
+ expect(instance.problem).toBe("token_refused");
+ instance.checkAlive();
+ await pause(200);
+ expect(rejected).toHaveLength(1);
+ });
+
+ it("checks liveness on its own while connected", async () => {
+ const relay = await relayAt();
+ const { instance } = client({ "relay1.openmausbot.com": relay }, { timing: { livenessEveryMs: 100 } });
+ instance.start();
+ await waitFor(() => relay.refreshes >= 2, SLOW);
+ expect(instance.status).toBe("connected");
+ });
+
+ it("waits at least 30 s after the relay's rate limit (4429)", async () => {
+ const relay = await scriptedRelay((socket) => socket.close(4429));
+ const { instance } = client({ "relay1.openmausbot.com": relay });
+ instance.start();
+ await waitFor(() => instance.problem === "busy", SLOW);
+ await pause(500);
+ expect(relay.dials()).toBe(1);
+ });
+
+ it("on a network change after a failed dial, dials now instead of waiting out its backoff", async () => {
+ const relay = await scriptedRelay((socket) => socket.close(1011));
+ // The backoff after the first failure is 30 s, so a second dial within the wait below can only be the shortcut.
+ const { instance } = client({ "relay1.openmausbot.com": relay }, { timing: { backoffMs: [30_000] } });
+ instance.start();
+ await waitFor(() => instance.problem === "unreachable", SLOW);
+ expect(relay.dials()).toBe(1);
+ instance.checkAlive();
+ await waitFor(() => relay.dials() === 2, SLOW);
+ });
+
+ it("on a network change keeps a wait the relay asked for (4429)", async () => {
+ const relay = await scriptedRelay((socket) => socket.close(4429));
+ const { instance } = client({ "relay1.openmausbot.com": relay });
+ instance.start();
+ await waitFor(() => instance.problem === "busy", SLOW);
+ instance.checkAlive();
+ await pause(500);
+ expect(relay.dials()).toBe(1);
+ });
});
diff --git a/electron/companion-account-documents.mjs b/electron/companion-account-documents.mjs
index 995f0fbf2d..cc32e05103 100644
--- a/electron/companion-account-documents.mjs
+++ b/electron/companion-account-documents.mjs
@@ -126,8 +126,21 @@ export function withAuthenticatedAccount(
return next;
}
-export function publicState({ available, status, email, endpoint, message, paused, tunnelRetired }) {
+const PROBLEMS = new Set(["unconfigured", "unreachable", "sign_in", "busy", "limit", "update", "address", "failed"]);
+const PROBLEM_OF = {
+ control_plane_unavailable: "unreachable", network_unavailable: "unreachable",
+ unauthorized: "sign_in", forbidden: "sign_in", signed_out: "sign_in", invalid_otp: "sign_in", otp_expired: "sign_in", invalid_email: "sign_in",
+ rate_limited: "busy", credential_rotation_rate_limited: "busy", endpoint_rate_limited: "busy", endpoint_busy: "busy", endpoint_capacity: "busy",
+ installation_limit_reached: "limit", update_required: "update",
+};
+
+/** A control-plane error code as one of the renderer's few problem words; the code itself stays in the main process. */
+export const accountProblem = (code) => PROBLEM_OF[code] ?? "failed";
+
+/** `problem` is one fixed word for the renderer's diagnosis, never a message or a control-plane code. */
+export function publicState({ available, status, email, endpoint, message, paused, tunnelRetired, problem }) {
const state = { available: Boolean(available), status };
+ if (PROBLEMS.has(problem)) state.problem = problem;
if (paused === true) state.paused = true;
if (tunnelRetired === true) state.tunnelRetired = true;
const normalizedEmail = normalizeAccountEmail(email);
diff --git a/electron/companion-account-service.d.mts b/electron/companion-account-service.d.mts
index 2e70fcc620..3564a043ee 100644
--- a/electron/companion-account-service.d.mts
+++ b/electron/companion-account-service.d.mts
@@ -42,6 +42,8 @@ export interface CompanionAccountState {
/** The secure address was ended for old phone apps: a phone that has not used the encrypted connection must be
* updated and paired again. */
tunnelRetired?: true;
+ /** What failed, as one fixed word for the renderer's diagnosis: never a message or a control-plane code. */
+ problem?: "unconfigured" | "unreachable" | "sign_in" | "busy" | "limit" | "update" | "address" | "failed";
}
export interface CompanionAccountService {
diff --git a/electron/companion-account-service.mjs b/electron/companion-account-service.mjs
index a612a01771..cd1a474511 100644
--- a/electron/companion-account-service.mjs
+++ b/electron/companion-account-service.mjs
@@ -17,7 +17,7 @@ import {
COMPANION_ENDPOINT_RELEASE_PENDING_FIELD,
COMPANION_TUNNEL_RETIRED_FIELD,
COMPANION_TUNNEL_WAITING_FIELD,
- UUID,
+ UUID, accountProblem,
companionAccountCleanupPending,
companionTunnelRetired,
ownString,
@@ -233,7 +233,7 @@ export function createCompanionAccountService({
return publicState({
available: false,
status: "signed-out",
- message: FRIENDLY_MESSAGES.control_plane_unavailable,
+ message: FRIENDLY_MESSAGES.control_plane_unavailable, problem: "unconfigured",
});
}
const document = credentials();
@@ -247,7 +247,7 @@ export function createCompanionAccountService({
status: account ? "error" : "signed-out",
email: account?.email,
endpoint: persistedAccess?.endpoint,
- message: FRIENDLY_MESSAGES.control_plane_unavailable,
+ message: FRIENDLY_MESSAGES.control_plane_unavailable, problem: "unreachable",
paused,
tunnelRetired,
});
@@ -271,7 +271,7 @@ export function createCompanionAccountService({
available,
status: "error",
email: account.email,
- message: "This computer still needs a secure address. Try again; local pairing continues to work.",
+ message: "This computer still needs a secure address. Try again; local pairing continues to work.", problem: "address",
});
}
const connection = managedConnectionState?.() ?? {};
@@ -291,7 +291,7 @@ export function createCompanionAccountService({
status: "error",
email: account.email,
endpoint: access.endpoint,
- message: "The secure connection needs attention. Local pairing still works.",
+ message: "The secure connection needs attention. Local pairing still works.", problem: "address",
});
}
}
@@ -498,7 +498,7 @@ export function createCompanionAccountService({
status: "error",
email: user.email,
endpoint: endpoint.endpoint.url,
- message: "The address is ready, but this app could not start its secure connection. Local pairing still works.",
+ message: "The address is ready, but this app could not start its secure connection. Local pairing still works.", problem: "address",
};
}
return settledState();
@@ -529,6 +529,7 @@ export function createCompanionAccountService({
: "error",
email,
message,
+ problem: accountProblem(error instanceof ControlPlaneError ? error.code : ""),
};
return message;
};
diff --git a/electron/companion-account-service.test.mjs b/electron/companion-account-service.test.mjs
index c92bf6f1e7..13969077bc 100644
--- a/electron/companion-account-service.test.mjs
+++ b/electron/companion-account-service.test.mjs
@@ -144,6 +144,11 @@ describe("Companion account service", () => {
});
});
+ it("tells a build with no control plane apart from one that can't reach it", async () => {
+ const { service } = serviceFixture({ client: null });
+ await expect(service.state()).resolves.toMatchObject({ available: false, status: "signed-out", problem: "unconfigured" });
+ });
+
it("hides account onboarding until the configured control plane is healthy", async () => {
const client = readyClient({
health: vi.fn(async () => {
@@ -176,6 +181,7 @@ describe("Companion account service", () => {
endpoint: ENDPOINT,
message: "Secure access is not available right now. Local pairing still works.",
+ problem: "unreachable",
});
expect(store.writes).toHaveLength(0);
});
@@ -309,6 +315,7 @@ describe("Companion account service", () => {
});
expect(JSON.stringify(await service.state())).not.toContain("invalid_otp");
+ expect((await service.state()).problem).toBe("sign_in");
});
it("handles an expired account session without deleting recovery credentials", async () => {
diff --git a/electron/companion-e2e.mjs b/electron/companion-e2e.mjs
index 79471e6894..2c91397627 100644
--- a/electron/companion-e2e.mjs
+++ b/electron/companion-e2e.mjs
@@ -63,6 +63,7 @@ export function createCompanionE2E({
void ensureIdentity().then(sync, (error) => log(`e2e: connection key unavailable: ${error?.message ?? error}`));
},
log,
+ wakeAfterSignInFailure: true,
});
async function reconcile() {
@@ -80,6 +81,10 @@ export function createCompanionE2E({
get publicKey() {
return identity?.publicKey ?? null;
},
+ /** The relay token's state and last failure code, for the renderer's diagnosis: never the token. */
+ get relayToken() {
+ return tokens.status;
+ },
/** For a new sidecar: null while the encrypted connection is off. */
message: () => (identity ? companionE2EMessage(identity, tokens.grant) : null),
start() {
diff --git a/electron/companion-e2e.test.mjs b/electron/companion-e2e.test.mjs
index 68b768e500..5aa52924b2 100644
--- a/electron/companion-e2e.test.mjs
+++ b/electron/companion-e2e.test.mjs
@@ -101,6 +101,79 @@ describe("relay tokens", () => {
await service.refreshNow();
expect(grants).toEqual([grant(), null]);
expect([...timers.pending.values()][0].milliseconds).toBe(30 * 60_000);
+ expect(service.status).toEqual({ state: "failed", code: "unavailable" });
+ service.stop();
+ expect(service.status).toEqual({ state: "off", code: null });
+ });
+
+ it("after a sign-in failure, wait for a wake-up, with only an hourly fallback", async () => {
+ const timers = manualTimers();
+ const answers = [
+ () => Promise.reject(Object.assign(new Error("signed out"), { code: "signed_out" })),
+ () => Promise.reject(Object.assign(new Error("expired"), { status: 401 })),
+ () => grant(),
+ ];
+ const fetchGrant = vi.fn(async () => answers.shift()());
+ const service = createRelayTokenService({ fetchGrant, onGrant: () => {}, ...timers, now: () => 0, random: () => 0.5, wakeAfterSignInFailure: true });
+ service.start();
+ await new Promise((resolve) => setImmediate(resolve));
+ expect([...timers.pending.values()].map((timer) => timer.milliseconds)).toEqual([60 * 60_000]);
+ expect(service.status).toEqual({ state: "waiting", code: "sign_in" });
+ await timers.fireAll();
+ expect(fetchGrant).toHaveBeenCalledTimes(2);
+ expect([...timers.pending.values()].map((timer) => timer.milliseconds)).toEqual([60 * 60_000]);
+ expect(service.status).toEqual({ state: "waiting", code: "sign_in" });
+ await service.refreshNow();
+ expect(service.status).toEqual({ state: "ready", code: null });
+ expect(fetchGrant).toHaveBeenCalledTimes(3);
+ service.stop();
+ });
+
+ it("asks again once a request in flight settles, when a wake-up arrived during it", async () => {
+ const timers = manualTimers();
+ let answerOld;
+ const answers = [
+ () => new Promise((_resolve, reject) => {
+ answerOld = () => reject(Object.assign(new Error("old credential"), { status: 401 }));
+ }),
+ () => grant(),
+ ];
+ const fetchGrant = vi.fn(async () => answers.shift()());
+ const service = createRelayTokenService({ fetchGrant, onGrant: () => {}, ...timers, now: () => 0, random: () => 0.5, wakeAfterSignInFailure: true });
+ service.start();
+ await new Promise((resolve) => setImmediate(resolve));
+ const woken = service.refreshNow();
+ answerOld();
+ await woken;
+ expect(fetchGrant).toHaveBeenCalledTimes(2);
+ expect(service.status).toEqual({ state: "ready", code: null });
+ service.stop();
+ });
+
+ it("without the wake-up option, a sign-in failure still asks again after half an hour", async () => {
+ const timers = manualTimers();
+ const service = createRelayTokenService({
+ fetchGrant: async () => Promise.reject(Object.assign(new Error("signed out"), { code: "signed_out" })),
+ onGrant: () => {}, ...timers, now: () => 0, random: () => 0.5,
+ });
+ service.start();
+ await new Promise((resolve) => setImmediate(resolve));
+ expect([...timers.pending.values()][0].milliseconds).toBe(30 * 60_000);
+ service.stop();
+ });
+
+ it("reports only a fixed word: never a token, a server message or its code", async () => {
+ const timers = manualTimers();
+ const answers = [
+ () => Promise.reject(Object.assign(new Error("eyJ2IjoxfQ.c2lnbmF0dXJl leaked"), { code: "Bearer omb_install_secret" })),
+ () => Promise.reject(Object.assign(new Error("busy"), { code: "rate_limited", status: 429 })),
+ ];
+ const service = createRelayTokenService({ fetchGrant: async () => answers.shift()(), onGrant: () => {}, ...timers, now: () => 0, random: () => 0.5 });
+ service.start();
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(service.status).toEqual({ state: "failed", code: "failed" });
+ await service.refreshNow();
+ expect(service.status).toEqual({ state: "failed", code: "busy" });
service.stop();
});
});
diff --git a/electron/main.mjs b/electron/main.mjs
index ab0c4a53b7..f60fde77c4 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -569,7 +569,7 @@ function publicManagedCompanionState() {
function decorateDesktopCompanionState(state) {
syncCompanionKeepAwake(state.enabled && !state.error, state.keepAwake === true);
- return { ...state, managedConnection: publicManagedCompanionState(), tailnetShare: tailnetShare.state() };
+ return { ...state, managedConnection: publicManagedCompanionState(), tailnetShare: tailnetShare.state(), relayToken: companionE2E?.relayToken ?? null };
}
async function desktopCompanionState() {
diff --git a/electron/relay-token.d.mts b/electron/relay-token.d.mts
index 5d27c7e8c1..1cf4da6d80 100644
--- a/electron/relay-token.d.mts
+++ b/electron/relay-token.d.mts
@@ -9,9 +9,15 @@ export interface RelayGrant {
export declare function validRelayGrant(payload: unknown): RelayGrant | null;
+export interface RelayTokenStatus {
+ state: "off" | "fetching" | "ready" | "failed" | "waiting";
+ code: "unavailable" | "sign_in" | "busy" | "unreachable" | "failed" | null;
+}
+
export interface RelayTokenService {
readonly grant: RelayGrant | null;
readonly running: boolean;
+ readonly status: RelayTokenStatus;
start(): void;
stop(): void;
refreshNow(): Promise<void>;
@@ -25,4 +31,6 @@ export declare function createRelayTokenService(options: {
now?: () => number;
random?: () => number;
log?: (line: string) => void;
+ /** A signed-out or refused (401) answer waits for `refreshNow` instead of asking again every 30 minutes. */
+ wakeAfterSignInFailure?: boolean;
}): RelayTokenService;
diff --git a/electron/relay-token.mjs b/electron/relay-token.mjs
index 89cb2d06f9..b124baf97a 100644
--- a/electron/relay-token.mjs
+++ b/electron/relay-token.mjs
@@ -3,12 +3,26 @@
* failed refresh; the relay keeps spliced sessions through an expired control socket anyway. */
const MINUTE_MS = 60_000;
const UNAVAILABLE_RETRY_MS = 30 * MINUTE_MS;
+/** After a sign-in failure the wake-ups (a new credential, pairing, resume) do the work; this bounds a 401 that came from
+ * a control-plane fault, not the credential. An hour is the healthy refresh cadence, so a computer with a dead
+ * credential asks no more often than a working one does. */
+const SIGN_IN_FALLBACK_MS = 60 * MINUTE_MS;
const BACKOFF_MS = [MINUTE_MS, 2 * MINUTE_MS, 4 * MINUTE_MS, 8 * MINUTE_MS, 16 * MINUTE_MS, 32 * MINUTE_MS, 60 * MINUTE_MS];
const MIN_REFRESH_MS = MINUTE_MS;
const RELAY_HOST = /^relay[1-9][0-9]?\.openmausbot\.com$/;
const HOST_ID = /^[A-Za-z0-9_-]{22}$/;
const TOKEN = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
+/** A failure as one of a few fixed words for the desktop's diagnosis: never a message, a server's text or its code. */
+function failureWord(error) {
+ const code = error?.code;
+ if (code === "relay_unavailable") return "unavailable";
+ if (code === "signed_out" || error?.status === 401) return "sign_in";
+ if (code === "rate_limited" || error?.status === 429) return "busy";
+ if (code === "network_unavailable" || code === "control_plane_unavailable") return "unreachable";
+ return "failed";
+}
+
const defaultSetTimer = (callback, milliseconds) => {
const timer = setTimeout(callback, milliseconds);
timer.unref?.();
@@ -34,12 +48,16 @@ export function createRelayTokenService({
now = Date.now,
random = Math.random,
log = () => {},
+ wakeAfterSignInFailure = false,
}) {
let running = false;
let grant = null;
let timer = null;
let failures = 0;
let inFlight = null;
+ let followUp = null;
+ let lastCode = null;
+ let waiting = false;
const jitter = (milliseconds) => Math.round(milliseconds * (0.8 + 0.4 * random()));
const schedule = (milliseconds) => {
@@ -57,16 +75,21 @@ export function createRelayTokenService({
const next = validRelayGrant(await fetchGrant());
if (!next) throw Object.assign(new Error("invalid relay grant"), { code: "invalid_response" });
failures = 0;
+ lastCode = null;
+ waiting = false;
if (!running) return;
publish(next);
schedule(Math.max(MIN_REFRESH_MS, next.refreshAfter - now()));
} catch (error) {
if (!running) return;
const code = error?.code ?? "";
- if (code === "relay_unavailable" || code === "signed_out" || error?.status === 401) {
+ lastCode = failureWord(error);
+ const signIn = code === "signed_out" || error?.status === 401;
+ if (code === "relay_unavailable" || signIn) {
log(`relay token ${code || "refused"}`);
publish(null);
- return schedule(jitter(UNAVAILABLE_RETRY_MS));
+ waiting = signIn && wakeAfterSignInFailure;
+ return schedule(jitter(waiting ? SIGN_IN_FALLBACK_MS : UNAVAILABLE_RETRY_MS));
}
if (grant && grant.expiresAt <= now()) publish(null);
const retryAfter = Number.isSafeInteger(error?.retryAfterMs) ? error.retryAfterMs : 0;
@@ -90,6 +113,12 @@ export function createRelayTokenService({
get running() {
return running;
},
+ /** For the desktop's diagnosis: "waiting" means a sign-in failure that waits for a sign-in, a new credential or a
+ * wake from sleep (`refreshNow`), or at most about an hour. `code` is one fixed word, never the token or a server's message. */
+ get status() {
+ const state = !running ? "off" : grant ? "ready" : waiting ? "waiting" : lastCode ? "failed" : "fetching";
+ return { state, code: running ? lastCode : null };
+ },
start() {
if (running) return;
running = true;
@@ -99,14 +128,22 @@ export function createRelayTokenService({
running = false;
if (timer) clearTimer(timer);
timer = null;
+ lastCode = null;
+ waiting = false;
publish(null);
},
- /** The relay said 4401, or the computer woke up. */
+ /** The relay said 4401, the computer woke up, or a sign-in or credential changed. A request already on its way may
+ * carry the old credential, so a wake-up during it asks again once it settles. */
refreshNow() {
if (!running) return Promise.resolve();
if (timer) clearTimer(timer);
timer = null;
- return refresh();
+ if (!inFlight) return refresh();
+ followUp ??= inFlight.then(() => {
+ followUp = null;
+ return running ? refresh() : undefined;
+ });
+ return followUp;
},
};
}
diff --git a/src/components/PhoneDevicesSection.tsx b/src/components/PhoneDevicesSection.tsx
index 9c2df627da..bd5484f2d6 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 { RemoteAccessCheckRow } from "./RemoteAccessCheck";
import { LearnMore, SettingRow, SettingsFoldRow, SettingsGroup, SettingsLinkRow, SettingsRows, Switch } from "./SettingsPrimitives";
import { Layer } from "./Layer";
import { DialogTitle } from "./settings/SettingsDialog";
@@ -480,6 +481,7 @@ export function PhoneDevicesSection({ profileEmail = "", focusRequest = 0, simpl
<Switch checked={state.keepAwake} aria-label={t("remote.keepAwakeAria")} disabled={c.busy || !anyRoute}
onClick={() => void c.act((companion) => companion.keepAwake(!state.keepAwake))} />
</SettingRow>
+ <RemoteAccessCheckRow account={c.account} state={state} />
{moreWays && (
<SettingsFoldRow id="more-ways" title={t("devices.moreWays")} open={moreOpen} onToggle={() => setMoreOpen(!moreOpen)}>
<SettingRow title="Tailscale" subtitle={<>{t("remote.tailscaleSwitch.short", { app: productName() })}{" "}<LearnMore href={TAILSCALE_HELP} /></>}
diff --git a/src/components/PhoneSetupFlow.onDemand.test.ts b/src/components/PhoneSetupFlow.onDemand.test.ts
index 5ba04cff4c..e3bc4d74a3 100644
--- a/src/components/PhoneSetupFlow.onDemand.test.ts
+++ b/src/components/PhoneSetupFlow.onDemand.test.ts
@@ -176,6 +176,9 @@ describe("pairing on a computer that holds no HTTPS address yet", () => {
fake.finishPrepare("full");
await vi.waitFor(() => expect(text()).toContain(FULL));
expect(text()).toContain("Secure access needs attention");
+ expect(host.querySelector('[data-step="account"]')?.getAttribute("data-result")).toBe("failed");
+ expect(button("Copy diagnostics")).not.toBeNull();
+ expect(host.querySelector("[data-remote-access-check]")?.textContent).not.toContain("[email protected]");
expect(button("Try secure access again")).not.toBeNull();
expect(button("Pair on this Wi-Fi instead")).not.toBeNull();
expect(button("Pair using Tailscale")).toBeNull();
diff --git a/src/components/PhoneSetupFlow.tsx b/src/components/PhoneSetupFlow.tsx
index 656b71357c..fe2be8eba2 100644
--- a/src/components/PhoneSetupFlow.tsx
+++ b/src/components/PhoneSetupFlow.tsx
@@ -9,6 +9,7 @@ import {
useState,
} from "react";
import { t } from "@/lib/i18n";
+import { PairingFailureCheck } from "./RemoteAccessCheck";
import {
ArrowLeft,
Check,
@@ -896,10 +897,7 @@ export function PhoneSetupFlowView({ controller }: { controller: PhoneSetupContr
<h2 className="mt-3 text-[18px] font-semibold text-ink">
{unavailable || failed ? t("phone.signIn.attention") : t("phone.signIn.title")}
</h2>
- <p
- role={c.setupTimedOut ? "alert" : undefined}
- className="mt-1 text-[13px] leading-relaxed text-ink-secondary"
- >
+ <p role={c.setupTimedOut ? "alert" : undefined} className="mt-1 text-[13px] leading-relaxed text-ink-secondary">
{unavailable
? t("phone.signIn.unavailable")
: c.setupTimedOut
@@ -908,6 +906,7 @@ export function PhoneSetupFlowView({ controller }: { controller: PhoneSetupContr
? c.account?.message ?? t("phone.signIn.failed")
: t("phone.signIn.emailPrompt")}
</p>
+ {(unavailable || failed) && <PairingFailureCheck account={c.account} state={c.state} setupTimedOut={c.setupTimedOut} />}
{!unavailable && !failed && (
<div className="mt-5 flex flex-col gap-3">
diff --git a/src/components/RemoteAccessCheck.test.ts b/src/components/RemoteAccessCheck.test.ts
new file mode 100644
index 0000000000..4febc750fc
--- /dev/null
+++ b/src/components/RemoteAccessCheck.test.ts
@@ -0,0 +1,74 @@
+// @vitest-environment happy-dom
+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";
+
+const copied: string[] = [];
+vi.mock("@/lib/copy-text", () => ({
+ copyText: vi.fn(async (text: string) => {
+ copied.push(text);
+ return "copied";
+ }),
+}));
+
+import { setLocale } from "@/lib/i18n";
+import type { CompanionState } from "@/lib/companion-types";
+import type { CompanionAccountState } from "../types/ogb";
+import { PairingFailureCheck, RemoteAccessCheckRow } from "./RemoteAccessCheck";
+
+const state: CompanionState = {
+ enabled: true,
+ keepAwake: false,
+ port: 8810,
+ devices: [{ id: "device-secret-id", name: "Ana's iPhone", createdAt: 1, lastSeenAt: 1, cloudDesktopAccess: false }],
+ pairing: { code: "482913", token: "omb_pair_secret", expiresAt: 1 },
+ lan: "192.168.1.34",
+ endpoints: [{ url: "http://192.168.1.34:8810", kind: "lan", priority: 0 }, { url: "https://c-opaque.openmausbot.com", kind: "hosted", priority: 1 }],
+ routes: { wifi: { on: true, since: 1 }, relay: { on: true, since: 1 }, tailscale: { on: false, since: null }, https: { on: false, since: null } },
+ e2e: { enabled: true, relay: "connecting", node: null, relayProblem: "no_answer", descriptor: null },
+ relayToken: { state: "ready", code: null },
+};
+const account: CompanionAccountState = { available: true, status: "ready", email: "[email protected]", endpoint: "https://c-opaque.openmausbot.com" };
+
+let host: HTMLDivElement;
+let root: Root;
+beforeEach(() => {
+ setLocale("en");
+ copied.length = 0;
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(() => {
+ flushSync(() => root.unmount());
+ host.remove();
+});
+
+const button = (label: string) => [...host.querySelectorAll("button")].find((node) => node.textContent?.includes(label)) ?? null;
+
+describe("the connection check", () => {
+ it("in Settings, shows the headline closed, and the steps and Copy diagnostics open", async () => {
+ flushSync(() => root.render(createElement(RemoteAccessCheckRow, { account, state })));
+ expect(host.querySelector("[data-remote-access-headline]")?.textContent).toBe("MausBot Relay didn't answer.");
+ expect(host.querySelector("[data-remote-access-check]")).toBeNull();
+ flushSync(() => button("Connection check")!.click());
+ const steps = [...host.querySelectorAll("[data-step]")].map((node) => `${node.getAttribute("data-step")}=${node.getAttribute("data-result")}`);
+ expect(steps).toEqual(["computer=ok", "account=ok", "relay=failed", "route=ok"]);
+ flushSync(() => button("Copy diagnostics")!.click());
+ await vi.waitFor(() => expect(host.textContent).toContain("Copied"));
+ expect(copied).toHaveLength(1);
+ for (const secret of ["[email protected]", "c-opaque", "192.168.1.34", "482913", "omb_pair_secret", "device-secret-id", "Ana's iPhone"]) {
+ expect(copied[0]).not.toContain(secret);
+ expect(host.textContent).not.toContain(secret);
+ }
+ });
+
+ it("under the pairing screen's failure message, lists the steps without a second headline", () => {
+ flushSync(() => root.render(createElement(PairingFailureCheck, { account: { available: false, status: "signed-out" }, state, setupTimedOut: false })));
+ expect(host.querySelector("[data-remote-access-headline]")).toBeNull();
+ expect(host.querySelector('[data-step="account"]')?.getAttribute("data-result")).toBe("failed");
+ expect(host.textContent).toContain("This computer can't reach MausBot right now.");
+ expect(button("Copy diagnostics")).not.toBeNull();
+ });
+});
diff --git a/src/components/RemoteAccessCheck.tsx b/src/components/RemoteAccessCheck.tsx
new file mode 100644
index 0000000000..d6c79b996f
--- /dev/null
+++ b/src/components/RemoteAccessCheck.tsx
@@ -0,0 +1,83 @@
+import { useState } from "react";
+import { Check, Circle, X } from "lucide-react";
+
+import { desktopAppVersion } from "@/lib/app-links";
+import { cn } from "@/lib/cn";
+import { copyText } from "@/lib/copy-text";
+import { t } from "@/lib/i18n";
+import {
+ diagnoseRemoteAccess,
+ remoteAccessDiagnosisText,
+ remoteAccessStepMark,
+ type RemoteAccessDiagnosis,
+ type RemoteAccessFacts,
+} from "@/lib/remote-access-diagnosis";
+import type { CompanionAccountState } from "../types/ogb";
+import type { CompanionState } from "@/lib/companion-types";
+import { SettingsFoldRow } from "./SettingsPrimitives";
+
+const ICON = { ok: Check, failed: X, unchecked: Circle } as const;
+
+export function remoteAccessFacts(account: CompanionAccountState | null, state: CompanionState | null, setupTimedOut = false, accountWanted = false): RemoteAccessFacts {
+ return { account, companion: state, setupTimedOut, appVersion: desktopAppVersion(), accountWanted };
+}
+
+/** The steps, what to try, and Copy diagnostics: shown under a failure message and in Settings, never on its own. */
+export function RemoteAccessSteps({ diagnosis, className }: { diagnosis: RemoteAccessDiagnosis; className?: string }) {
+ const [copied, setCopied] = useState<"idle" | "copied" | "failed">("idle");
+ const copy = async () => {
+ const result = await copyText(remoteAccessDiagnosisText(diagnosis));
+ if (result !== "empty") setCopied(result);
+ };
+ return (
+ <div className={cn("flex flex-col gap-3 text-left", className)} data-remote-access-check="">
+ <ol className="flex flex-col gap-2">
+ {diagnosis.steps.map((step) => {
+ const Icon = ICON[step.result];
+ return (
+ <li key={step.id} data-step={step.id} data-result={step.result} className="flex items-start gap-2.5">
+ <Icon size={14} aria-hidden="true" className={cn("mt-[3px] shrink-0", step.result === "ok" ? "text-success" : step.result === "failed" ? "text-danger" : "text-ink-tertiary")} />
+ <span className="flex min-w-0 flex-col">
+ <span className="text-[13px] leading-[18px] text-ink">
+ {step.label}<span className="sr-only">{`: ${remoteAccessStepMark(step.result)}`}</span>
+ </span>
+ <span className="text-[12px] leading-4 text-ink-secondary">{step.reason}</span>
+ </span>
+ </li>
+ );
+ })}
+ </ol>
+ {diagnosis.next.length > 0 && (
+ <div className="flex flex-col gap-1">
+ <span className="text-[12px] font-medium leading-4 text-ink-secondary">{t("remote.diagnosis.nextTitle")}</span>
+ <ul className="flex list-disc flex-col gap-1 ps-4 text-[12px] leading-4 text-ink-secondary">
+ {diagnosis.next.map((line) => <li key={line}>{line}</li>)}
+ </ul>
+ </div>
+ )}
+ <div className="flex flex-wrap items-center gap-2">
+ <button type="button" className="ui-button" data-copy-diagnostics="" onClick={() => void copy()}>{t("remote.diagnosis.copy")}</button>
+ <span role="status" className="text-[12px] leading-4 text-ink-secondary">
+ {copied === "copied" ? t("remote.diagnosis.copied") : copied === "failed" ? t("common.copyFailed") : t("remote.diagnosis.copyNote")}
+ </span>
+ </div>
+ </div>
+ );
+}
+
+/** Under the pairing screen's failure message: the same model as Settings, without a second headline. */
+export function PairingFailureCheck({ account, state, setupTimedOut }: { account: CompanionAccountState | null; state: CompanionState | null; setupTimedOut: boolean }) {
+ return <RemoteAccessSteps className="mt-4" diagnosis={diagnoseRemoteAccess(remoteAccessFacts(account, state, setupTimedOut, true))} />;
+}
+
+/** Settings → Phone & devices: a closed row whose value is the headline; open, the steps. */
+export function RemoteAccessCheckRow({ account, state }: { account: CompanionAccountState | null; state: CompanionState }) {
+ const [open, setOpen] = useState(false);
+ const diagnosis = diagnoseRemoteAccess(remoteAccessFacts(account, state));
+ return (
+ <SettingsFoldRow id="connection-check" title={t("remote.diagnosis.title")} subtitle={t("remote.diagnosis.subtitle")} open={open} onToggle={() => setOpen(!open)}
+ value={<span data-remote-access-headline="" className={cn("max-w-[16rem] truncate", diagnosis.failed && "text-danger")}>{diagnosis.headline}</span>}>
+ <div className="px-4 py-3"><RemoteAccessSteps diagnosis={diagnosis} /></div>
+ </SettingsFoldRow>
+ );
+}
diff --git a/src/lib/companion-types.ts b/src/lib/companion-types.ts
index 403e5d6def..448f43f002 100644
--- a/src/lib/companion-types.ts
+++ b/src/lib/companion-types.ts
@@ -56,7 +56,16 @@ export interface CompanionState {
/** Windows has that network down as Public, where its firewall drops a phone's connection. */
publicNetwork?: string;
/** The end-to-end connection; absent or `enabled: false` until this computer serves it. */
- e2e?: { enabled: boolean; relay: "connected" | "connecting" | "off"; node: string | null; descriptor: PairingE2EDescriptor | null };
+ e2e?: {
+ enabled: boolean;
+ relay: "connected" | "connecting" | "off";
+ node: string | null;
+ /** Why the relay connection is not up; null once the relay acknowledged this computer. Absent on older builds. */
+ relayProblem?: "no_answer" | "token_refused" | "busy" | "unreachable" | "replaced" | null;
+ descriptor: PairingE2EDescriptor | null;
+ };
+ /** The relay access token's state and last failure code (never the token). Absent on older builds. */
+ relayToken?: { state: "off" | "fetching" | "ready" | "failed" | "waiting"; code: "unavailable" | "sign_in" | "busy" | "unreachable" | "failed" | null } | null;
error?: string;
}
diff --git a/src/lib/remote-access-diagnosis.test.ts b/src/lib/remote-access-diagnosis.test.ts
new file mode 100644
index 0000000000..7f533e2773
--- /dev/null
+++ b/src/lib/remote-access-diagnosis.test.ts
@@ -0,0 +1,188 @@
+import { describe, expect, it } from "vitest";
+
+import { diagnoseRemoteAccess, remoteAccessDiagnosisText, type RemoteAccessFacts } from "./remote-access-diagnosis";
+
+type Companion = NonNullable<RemoteAccessFacts["companion"]>;
+type Account = NonNullable<RemoteAccessFacts["account"]>;
+
+const route = (on: boolean, name?: string) => ({ on, since: on ? 1 : null, ...(name ? { name } : {}) });
+
+const companion = (overrides: Partial<Companion> = {}): Companion => ({
+ enabled: true,
+ port: 8810,
+ devices: [],
+ routes: { wifi: route(true), relay: route(true), tailscale: route(false), https: route(false) },
+ endpoints: [{ url: "http://192.168.1.23:8810", kind: "lan", priority: 0 }],
+ e2e: { enabled: true, relay: "connected", node: "relay1.openmausbot.com", relayProblem: null, descriptor: null },
+ relayToken: { state: "ready", code: null },
+ ...overrides,
+});
+
+const signedIn: Account = { available: true, status: "ready" };
+
+const results = (facts: RemoteAccessFacts) => Object.fromEntries(diagnoseRemoteAccess(facts).steps.map((step) => [step.id, step.result]));
+
+describe("the remote access diagnosis", () => {
+ it("passes every step when the relay confirmed this computer", () => {
+ const diagnosis = diagnoseRemoteAccess({ account: signedIn, companion: companion() });
+ expect(results({ account: signedIn, companion: companion() })).toEqual({ computer: "ok", account: "ok", relay: "ok", route: "ok" });
+ expect(diagnosis.failed).toBe(false);
+ expect(diagnosis.headline).toBe("Your phone can reach this computer from anywhere.");
+ expect(diagnosis.steps.map((step) => step.label)).toEqual(["This computer", "MausBot account", "MausBot Relay", "Your phone's way in"]);
+ });
+
+ it("stops at this computer when the phone link is off, and checks nothing after it", () => {
+ const diagnosis = diagnoseRemoteAccess({ account: signedIn, companion: companion({ enabled: false }) });
+ expect(diagnosis.steps.map((step) => step.result)).toEqual(["failed", "unchecked", "unchecked", "unchecked"]);
+ expect(diagnosis.headline).toBe("The phone link is off.");
+ expect(diagnosis.next).toEqual(["Turn on Same Wi-Fi or Anywhere, through MausBot."]);
+ });
+
+ it("names the account when MausBot can't be reached, and still finds Same Wi-Fi working", () => {
+ const facts = { account: { available: false, status: "signed-out" as const, problem: "unreachable" as const }, companion: companion({ e2e: { enabled: false, relay: "off", node: null, descriptor: null }, relayToken: { state: "failed", code: "unreachable" } }) };
+ const diagnosis = diagnoseRemoteAccess(facts);
+ expect(results(facts)).toEqual({ computer: "ok", account: "failed", relay: "unchecked", route: "ok" });
+ expect(diagnosis.headline).toBe("This computer can't reach MausBot right now.");
+ expect(diagnosis.next[0]).toMatch(/internet connection/);
+ expect(diagnosis.steps[2].reason).toBe("Needs the MausBot account first.");
+ });
+
+ it("asks to sign in when signed out, or when the relay refused this computer's sign-in", () => {
+ expect(diagnoseRemoteAccess({ account: { available: true, status: "signed-out" }, companion: companion() }).headline).toBe("Not signed in.");
+ const refused = diagnoseRemoteAccess({ account: signedIn, companion: companion({ relayToken: { state: "waiting", code: "sign_in" }, e2e: { enabled: true, relay: "off", node: null, descriptor: null } }) });
+ expect(refused.headline).toBe("This computer's sign-in was not accepted.");
+ expect(refused.next).toEqual(["MausBot asks again on its own within the hour, or as soon as you pair a phone."]);
+ });
+
+ it("maps the account's control-plane codes to plain reasons", () => {
+ const reason = (problem: Account["problem"]) => diagnoseRemoteAccess({ account: { available: true, status: "error", problem }, companion: companion() }).headline;
+ expect(reason("sign_in")).toBe("Your sign-in expired.");
+ expect(reason("busy")).toBe("MausBot is busy right now.");
+ expect(reason("limit")).toBe("This account has reached its computer limit.");
+ expect(reason("update")).toBe("This version of MausBot is too old to connect.");
+ expect(reason("failed")).toBe("Signing in didn't finish.");
+ });
+
+ it("names the relay when it is off for this computer, busy, silent, or taken over", () => {
+ const relayFailure = (overrides: Partial<Companion>) => diagnoseRemoteAccess({ account: signedIn, companion: companion(overrides) });
+ const off = { enabled: true, relay: "connecting" as const, node: null, descriptor: null };
+ expect(relayFailure({ relayToken: { state: "failed", code: "unavailable" }, e2e: { ...off, relay: "off" } }).headline).toBe("MausBot Relay isn't available for this computer right now.");
+ expect(relayFailure({ relayToken: { state: "failed", code: "busy" }, e2e: { ...off, relay: "off" } }).headline).toBe("MausBot Relay is busy.");
+ const silent = relayFailure({ e2e: { ...off, relayProblem: "no_answer" } });
+ expect(silent.headline).toBe("MausBot Relay didn't answer.");
+ expect(silent.next).toHaveLength(2);
+ expect(relayFailure({ e2e: { ...off, relayProblem: "unreachable" } }).headline).toBe("This computer can't reach MausBot Relay.");
+ expect(relayFailure({ e2e: { ...off, relayProblem: "busy" } }).headline).toBe("MausBot Relay is busy.");
+ expect(relayFailure({ e2e: { ...off, relay: "off", relayProblem: "replaced" } }).headline).toBe("Another copy of MausBot took over this computer's relay connection.");
+ });
+
+ it("reads a relay still connecting, or renewing its access, as not checked rather than failed", () => {
+ for (const relayProblem of [null, "token_refused"] as const) {
+ const facts = { account: signedIn, companion: companion({ e2e: { enabled: true, relay: "connecting", node: null, relayProblem, descriptor: null } }) };
+ expect(results(facts).relay).toBe("unchecked");
+ expect(diagnoseRemoteAccess(facts).failed).toBe(false);
+ expect(diagnoseRemoteAccess(facts).headline).toBe("Your phone can reach this computer on the same Wi-Fi.");
+ }
+ });
+
+ it("does not treat Anywhere being off as a failure", () => {
+ const facts = { account: signedIn, companion: companion({ routes: { wifi: route(true), relay: route(false), tailscale: route(false), https: route(false) } }) };
+ expect(results(facts)).toEqual({ computer: "ok", account: "unchecked", relay: "unchecked", route: "ok" });
+ expect(diagnoseRemoteAccess(facts).steps[2].reason).toBe("Not used: Anywhere is off.");
+ });
+
+ it("does not ask a person using only Same Wi-Fi or Tailscale to sign in, unless pairing asks for the account", () => {
+ const wifiOnly = companion({ routes: { wifi: route(true), relay: route(false), tailscale: route(true, "mac.tailnet.ts.net"), https: route(false) } });
+ for (const account of [{ available: true, status: "signed-out" as const }, { available: false, status: "signed-out" as const, problem: "unreachable" as const }]) {
+ const diagnosis = diagnoseRemoteAccess({ account, companion: wifiOnly });
+ expect(diagnosis.steps[1]).toMatchObject({ result: "unchecked", reason: "Not needed for Same Wi-Fi or Tailscale." });
+ expect(diagnosis.failed).toBe(false);
+ expect(diagnosis.headline).toBe("Your phone can reach this computer on the same Wi-Fi.");
+ }
+ const pairing = diagnoseRemoteAccess({ account: { available: true, status: "signed-out" }, companion: wifiOnly, accountWanted: true });
+ expect(pairing.headline).toBe("Not signed in.");
+ });
+
+ it("reads a build with no control plane as not set up, not as a failure", () => {
+ const diagnosis = diagnoseRemoteAccess({ account: { available: false, status: "signed-out", problem: "unconfigured" }, companion: companion({ e2e: { enabled: false, relay: "off", node: null, descriptor: null }, relayToken: { state: "off", code: null } }), accountWanted: true });
+ expect(diagnosis.steps[1]).toMatchObject({ result: "unchecked", reason: "Not set up in this build of MausBot." });
+ expect(diagnosis.failed).toBe(false);
+ expect(remoteAccessDiagnosisText(diagnosis)).toContain("account: unavailable (unconfigured)");
+ });
+
+ it("reads a relay idle by design, with no phone needing it, as not checked", () => {
+ const facts = { account: signedIn, companion: companion({ e2e: { enabled: true, relay: "off", node: null, relayProblem: null, descriptor: null }, relayToken: { state: "off", code: null } }) };
+ expect(diagnoseRemoteAccess(facts).steps[2]).toMatchObject({ result: "unchecked", reason: "Starts when a phone needs it." });
+ expect(diagnoseRemoteAccess(facts).failed).toBe(false);
+ });
+
+ it("keeps a connected relay ok while MausBot's service can't be reached", () => {
+ const facts = { account: { available: false, status: "error" as const, problem: "unreachable" as const }, companion: companion() };
+ expect(results(facts)).toEqual({ computer: "ok", account: "failed", relay: "ok", route: "ok" });
+ });
+
+ it("names the phone's way in when Wi-Fi has no address, nothing is on, or only a failing HTTPS address is", () => {
+ const routes = (wifi: boolean, relay: boolean, https = false) => ({ wifi: route(wifi), relay: route(relay), tailscale: route(false), https: route(https) });
+ const noAddress = { endpoints: [], routes: routes(true, false) };
+ expect(diagnoseRemoteAccess({ account: signedIn, companion: companion(noAddress) }).headline).toBe("This computer isn't on a Wi-Fi network.");
+ expect(diagnoseRemoteAccess({ account: signedIn, companion: companion({ routes: routes(false, false) }) }).headline).toBe("No way in is on.");
+ const https = diagnoseRemoteAccess({ account: { available: true, status: "error", problem: "address" }, companion: companion({ endpoints: [], routes: routes(false, false, true) }) });
+ expect(https.steps.map((step) => step.result)).toEqual(["ok", "ok", "unchecked", "failed"]);
+ expect(https.headline).toBe("The HTTPS address isn't working.");
+ const tailnet = { account: signedIn, companion: companion({ endpoints: [], routes: { wifi: route(false), relay: route(false), tailscale: route(true, "mac.tailnet.ts.net"), https: route(false) } }) };
+ expect(results(tailnet).route).toBe("ok");
+ });
+
+ it("copies the steps, what to try and the facts as one block", () => {
+ const diagnosis = diagnoseRemoteAccess({ account: signedIn, companion: companion({ e2e: { enabled: true, relay: "connecting", node: null, relayProblem: "no_answer", descriptor: null } }), setupTimedOut: true, appVersion: "0.1.158" });
+ const text = remoteAccessDiagnosisText(diagnosis);
+ expect(text.split("\n")[0]).toBe("MausBot remote access: MausBot Relay didn't answer.");
+ expect(text).toContain("MausBot Relay: failed · MausBot Relay didn't answer.");
+ expect(text).toContain("This computer: ok · The phone link is on.");
+ expect(text).toContain("- A VPN or firewall on this computer can block MausBot Relay.");
+ expect(text).toContain("app: 0.1.158");
+ expect(text).toContain("relay: connecting (no_answer)");
+ expect(text).toContain("ways_on: wifi,relay");
+ expect(text).toContain("setup: timed_out");
+ });
+
+ it("never copies an email, address, hostname, IP, pairing code, token, key or device name", () => {
+ const secrets = [
+ "[email protected]", "c-0123abcd", "mausbot.si", "192.168.1.23", "100.64.0.9", "mac.tailnet.ts.net", "mac.local",
+ "482913", "pairtoken_secret", "PUBKEY_secret", "hhash_secret", "eyJ2IjoxfQ", "omb_install_secret", "req_8f3a",
+ "device-secret-id", "Ana's iPhone", "Bearer", "relay9.example.com", "openmausbot.com",
+ ];
+ const account = {
+ available: true, status: "error", email: "[email protected]", endpoint: "https://c-0123abcd.mausbot.si",
+ message: "Could not finish. Reference: req_8f3a.", problem: "Bearer omb_install_secret",
+ } as unknown as Account;
+ const leaky = {
+ ...companion(),
+ addresses: ["192.168.1.23", "100.64.0.9"], lan: "192.168.1.23", tailscale: "100.64.0.9", tailnetName: "mac.tailnet.ts.net",
+ hosts: ["mac.local", "mac.tailnet.ts.net"], discovery: { advertising: true, name: "mac.local" },
+ endpoints: [
+ { url: "http://192.168.1.23:8810", kind: "lan", priority: 0 },
+ { url: "https://c-0123abcd.mausbot.si", kind: "hosted", priority: 1 },
+ { url: "http://mac.tailnet.ts.net:8810", kind: "tailnet", priority: 2 },
+ ],
+ routes: { wifi: route(true), relay: route(true), tailscale: route(true, "mac.tailnet.ts.net"), https: route(true) },
+ pairing: { code: "482913", token: "pairtoken_secret", expiresAt: 1 },
+ devices: [{ id: "device-secret-id", name: "Ana's iPhone", createdAt: 1, lastSeenAt: 1, cloudDesktopAccess: false }],
+ e2e: { enabled: true, relay: "connecting", node: "relay9.example.com", relayProblem: "no_answer", descriptor: { v: 1, k: "PUBKEY_secret", h: "hhash_secret", r: ["relay1.openmausbot.com"] } },
+ relayToken: { state: "failed", code: "eyJ2IjoxfQ.c2lnbmF0dXJl" },
+ error: undefined,
+ } as unknown as Companion;
+ const variants: RemoteAccessFacts[] = [
+ { account, companion: leaky, appVersion: "eyJ2IjoxfQ.c2lnbmF0dXJl" },
+ { account: { ...account, available: false }, companion: leaky },
+ { account, companion: { ...leaky, e2e: { ...leaky.e2e!, relay: "connected" } } },
+ { account, companion: { ...leaky, enabled: false } },
+ { account, companion: { ...leaky, error: "Failed to bind 192.168.1.23:8810 for [email protected]" } },
+ { account: null, companion: null },
+ ];
+ for (const facts of variants) {
+ const text = remoteAccessDiagnosisText(diagnoseRemoteAccess(facts));
+ for (const secret of secrets) expect(text, `${secret} in:\n${text}`).not.toContain(secret);
+ }
+ });
+});
diff --git a/src/lib/remote-access-diagnosis.ts b/src/lib/remote-access-diagnosis.ts
new file mode 100644
index 0000000000..0df49bb947
--- /dev/null
+++ b/src/lib/remote-access-diagnosis.ts
@@ -0,0 +1,233 @@
+// Adapted from packages/client-runtime/src/connection/diagnosis.ts at commit abc0fde5, MIT License, Copyright (c) 2026
+// T3 Tools Inc. (full text in third_party/t3-code/LICENSE); modified: the steps are this computer's own (phone link,
+// account, relay, the phone's way in) read from the state the desktop already holds, every line is localised, and the
+// copied text carries only fixed words and codes.
+import type { CompanionAccountState } from "../types/ogb";
+import { companionPairingRoute, type CompanionPairingRouteSource } from "./companion-pairing";
+import type { CompanionState } from "./companion-types";
+import { t } from "./i18n";
+
+export type RemoteAccessStepId = "computer" | "account" | "relay" | "route";
+export type RemoteAccessStepResult = "ok" | "failed" | "unchecked";
+
+export interface RemoteAccessStep {
+ id: RemoteAccessStepId;
+ label: string;
+ result: RemoteAccessStepResult;
+ reason: string;
+}
+
+export interface RemoteAccessDiagnosis {
+ /** The first failed step's reason, or how it stands when nothing failed. */
+ headline: string;
+ steps: RemoteAccessStep[];
+ /** What the person can do, for the first failed step. */
+ next: string[];
+ /** For the copied text only: fixed keys, and values that are codes, counts, yes/no or a version. */
+ facts: Array<[string, string]>;
+ failed: boolean;
+}
+
+export interface RemoteAccessFacts {
+ account: Pick<CompanionAccountState, "available" | "status" | "problem"> | null;
+ companion: (CompanionPairingRouteSource & Pick<CompanionState, "enabled" | "error" | "routes" | "e2e" | "devices" | "relayToken">) | null;
+ setupTimedOut?: boolean;
+ appVersion?: string | null;
+ /** The account is needed even with Anywhere and the HTTPS address off: the pairing screen is asking for it. */
+ accountWanted?: boolean;
+}
+
+type Problem = { reason: string; next: string[] };
+type AccountProblem = NonNullable<CompanionAccountState["problem"]>;
+
+const VERSION = /^\d{1,4}\.\d{1,4}\.\d{1,6}(?:-[0-9A-Za-z.]{1,32})?$/;
+const RELAY_NODE = /^(relay[1-9][0-9]?)\.openmausbot\.com$/;
+const ACCOUNT_PROBLEMS: ReadonlySet<string> = new Set<AccountProblem>(["unconfigured", "unreachable", "sign_in", "busy", "limit", "update", "address", "failed"]);
+const TOKEN_CODES: ReadonlySet<string> = new Set(["unavailable", "sign_in", "busy", "unreachable", "failed"]);
+const RELAY_PROBLEMS: ReadonlySet<string> = new Set(["no_answer", "token_refused", "busy", "unreachable", "replaced"]);
+
+const known = (value: unknown, words: ReadonlySet<string>): string | null => (typeof value === "string" && words.has(value) ? value : null);
+
+function accountProblem(problem: string | null): Problem {
+ switch (problem) {
+ case "unreachable":
+ return { reason: t("remote.diagnosis.account.unreachable"), next: [t("remote.diagnosis.next.internet")] };
+ case "sign_in":
+ return { reason: t("remote.diagnosis.account.expired"), next: [t("remote.diagnosis.next.signIn")] };
+ case "busy":
+ return { reason: t("remote.diagnosis.account.busy"), next: [t("remote.diagnosis.next.wait")] };
+ case "limit":
+ return { reason: t("remote.diagnosis.account.limit"), next: [t("remote.diagnosis.next.removeComputer")] };
+ case "update":
+ return { reason: t("remote.diagnosis.account.update"), next: [t("remote.diagnosis.next.update")] };
+ default:
+ return { reason: t("remote.diagnosis.account.failed"), next: [t("remote.diagnosis.next.retry"), t("remote.diagnosis.next.support")] };
+ }
+}
+
+const hasWifiAddress = (companion: NonNullable<RemoteAccessFacts["companion"]>) => companionPairingRoute(companion, "local") !== null;
+
+interface Evaluated {
+ result: RemoteAccessStepResult;
+ reason: string;
+ next?: string[];
+}
+
+function computerStep(companion: RemoteAccessFacts["companion"]): Evaluated {
+ if (!companion) return { result: "unchecked", reason: t("remote.diagnosis.notChecked") };
+ if (companion.error) return { result: "failed", reason: t("remote.diagnosis.computer.failed"), next: [t("remote.diagnosis.next.restart")] };
+ if (!companion.enabled) return { result: "failed", reason: t("remote.diagnosis.computer.off"), next: [t("remote.diagnosis.next.turnOn")] };
+ return { result: "ok", reason: t("remote.diagnosis.computer.on") };
+}
+
+function accountStep(facts: RemoteAccessFacts): Evaluated {
+ const { account, companion } = facts;
+ if (!account) return { result: "unchecked", reason: t("remote.diagnosis.notChecked") };
+ const problem = known(account.problem, ACCOUNT_PROBLEMS);
+ if (problem === "unconfigured") return { result: "unchecked", reason: t("remote.diagnosis.account.unconfigured") };
+ const used = companion?.routes?.relay?.on === true || companion?.routes?.https?.on === true;
+ if (!used && !facts.accountWanted) return { result: "unchecked", reason: t("remote.diagnosis.account.notNeeded") };
+ if (!account.available) return { result: "failed", ...accountProblem(problem ?? "unreachable") };
+ if (account.status === "signed-out") {
+ return { result: "failed", reason: t("remote.diagnosis.account.signedOut"), next: [t("remote.diagnosis.next.signIn")] };
+ }
+ if (account.status === "connecting") return { result: "unchecked", reason: t("remote.diagnosis.connecting") };
+ // A failing HTTPS address is not the account's failure: the phone's way in reports it.
+ if (account.status === "error" && problem !== "address") {
+ return { result: "failed", ...accountProblem(problem) };
+ }
+ if (companion?.relayToken?.state === "waiting") {
+ return { result: "failed", reason: t("remote.diagnosis.account.credential"), next: [t("remote.diagnosis.next.askAgain")] };
+ }
+ return { result: "ok", reason: t("remote.diagnosis.account.signedIn") };
+}
+
+function relayStep(facts: RemoteAccessFacts, accountResult: RemoteAccessStepResult): Evaluated {
+ const companion = facts.companion;
+ if (!companion || companion.routes?.relay?.on !== true) return { result: "unchecked", reason: t("remote.diagnosis.relay.off") };
+ const e2e = companion.e2e;
+ if (e2e?.enabled === true && e2e.relay === "connected") return { result: "ok", reason: t("remote.diagnosis.relay.connected") };
+ if (accountResult === "failed") return { result: "unchecked", reason: t("remote.diagnosis.relay.needsAccount") };
+ if (e2e?.relayProblem === "replaced") {
+ return { result: "failed", reason: t("remote.diagnosis.relay.replaced"), next: [t("remote.diagnosis.next.otherCopy")] };
+ }
+ const token = companion.relayToken;
+ const tokenCode = known(token?.code, TOKEN_CODES);
+ if (token?.state === "off") return { result: "unchecked", reason: t("remote.diagnosis.relay.idle") };
+ if (token?.state === "failed") {
+ if (tokenCode === "unavailable") {
+ return { result: "failed", reason: t("remote.diagnosis.relay.unavailable"), next: [t("remote.diagnosis.next.useWifi")] };
+ }
+ if (tokenCode === "busy") {
+ return { result: "failed", reason: t("remote.diagnosis.relay.busy"), next: [t("remote.diagnosis.next.wait")] };
+ }
+ if (tokenCode === "unreachable") {
+ return { result: "failed", reason: t("remote.diagnosis.account.unreachable"), next: [t("remote.diagnosis.next.internet")] };
+ }
+ return { result: "failed", reason: t("remote.diagnosis.relay.noAccess"), next: [t("remote.diagnosis.next.wait"), t("remote.diagnosis.next.support")] };
+ }
+ if (e2e?.enabled !== true || token?.state === "fetching") return { result: "unchecked", reason: t("remote.diagnosis.connecting") };
+ switch (e2e.relayProblem) {
+ case "no_answer":
+ return { result: "failed", reason: t("remote.diagnosis.relay.noAnswer"), next: [t("remote.diagnosis.next.internet"), t("remote.diagnosis.next.vpn")] };
+ case "unreachable":
+ return { result: "failed", reason: t("remote.diagnosis.relay.unreachable"), next: [t("remote.diagnosis.next.internet"), t("remote.diagnosis.next.vpn")] };
+ case "busy":
+ return { result: "failed", reason: t("remote.diagnosis.relay.busy"), next: [t("remote.diagnosis.next.wait")] };
+ default:
+ return { result: "unchecked", reason: t("remote.diagnosis.connecting") };
+ }
+}
+
+function routeStep(facts: RemoteAccessFacts, relay: RemoteAccessStepResult): Evaluated {
+ const companion = facts.companion;
+ if (!companion?.enabled || companion.error) return { result: "unchecked", reason: t("remote.diagnosis.notChecked") };
+ if (relay === "ok") return { result: "ok", reason: t("remote.diagnosis.route.anywhere") };
+ const on = (route: "wifi" | "relay" | "tailscale" | "https") => companion.routes?.[route]?.on === true;
+ if (on("wifi") && hasWifiAddress(companion)) return { result: "ok", reason: t("remote.diagnosis.route.wifi") };
+ if (on("tailscale") && companion.routes?.tailscale?.name) return { result: "ok", reason: t("remote.diagnosis.route.tailscale") };
+ if (on("https") && facts.account?.problem === "address") {
+ return { result: "failed", reason: t("remote.diagnosis.route.https"), next: [t("remote.diagnosis.next.retry"), t("remote.diagnosis.next.useWifi")] };
+ }
+ if (on("wifi")) return { result: "failed", reason: t("remote.diagnosis.route.noWifi"), next: [t("remote.diagnosis.next.joinWifi")] };
+ if (on("relay")) {
+ return relay === "unchecked"
+ ? { result: "unchecked", reason: t("remote.diagnosis.connecting") }
+ : { result: "failed", reason: t("remote.diagnosis.route.none"), next: [t("remote.diagnosis.next.useWifi")] };
+ }
+ return { result: "failed", reason: t("remote.diagnosis.route.off"), next: [t("remote.diagnosis.next.turnOn")] };
+}
+
+const ROUTES = ["wifi", "relay", "tailscale", "https"] as const;
+
+function factsOf(facts: RemoteAccessFacts): Array<[string, string]> {
+ const { account, companion } = facts;
+ const out: Array<[string, string]> = [];
+ const add = (key: string, value: string | null | undefined) => {
+ if (value) out.push([key, value]);
+ };
+ add("app", typeof facts.appVersion === "string" && VERSION.test(facts.appVersion) ? facts.appVersion : null);
+ if (account) {
+ const status = known(account.status, new Set(["signed-out", "connecting", "ready", "error"])) ?? "unknown";
+ const problem = known(account.problem, ACCOUNT_PROBLEMS);
+ add("account", `${account.available ? status : "unavailable"}${problem ? ` (${problem})` : ""}`);
+ }
+ if (companion) {
+ add("phone_link", companion.error ? "error" : companion.enabled ? "on" : "off");
+ add("ways_on", ROUTES.filter((route) => companion.routes?.[route]?.on === true).join(",") || "none");
+ add("wifi_address", hasWifiAddress(companion) ? "yes" : "no");
+ add("encrypted", companion.e2e?.enabled === true ? "on" : "off");
+ const relay = companion.e2e?.relay;
+ const node = companion.e2e?.node?.match(RELAY_NODE)?.[1] ?? null;
+ const problem = known(companion.e2e?.relayProblem, RELAY_PROBLEMS);
+ if (relay === "connected" || relay === "connecting" || relay === "off") add("relay", `${relay}${node ? ` ${node}` : ""}${problem ? ` (${problem})` : ""}`);
+ const token = companion.relayToken;
+ const tokenState = known(token?.state, new Set(["off", "fetching", "ready", "failed", "waiting"]));
+ const tokenCode = known(token?.code, TOKEN_CODES);
+ if (tokenState) add("relay_access", `${tokenState}${tokenCode ? ` (${tokenCode})` : ""}`);
+ add("paired", String(Array.isArray(companion.devices) ? Math.min(companion.devices.length, 100) : 0));
+ }
+ if (facts.setupTimedOut) add("setup", "timed_out");
+ return out;
+}
+
+/** Where this computer's remote access stands, step by step, from the state the desktop already has. */
+export function diagnoseRemoteAccess(facts: RemoteAccessFacts): RemoteAccessDiagnosis {
+ const computer = computerStep(facts.companion);
+ const account = computer.result === "failed" ? { result: "unchecked" as const, reason: t("remote.diagnosis.notChecked") } : accountStep(facts);
+ const relay = computer.result === "failed" ? { result: "unchecked" as const, reason: t("remote.diagnosis.notChecked") } : relayStep(facts, account.result);
+ const route = routeStep(facts, relay.result);
+ const evaluated: Array<[RemoteAccessStepId, string, Evaluated]> = [
+ ["computer", t("remote.diagnosis.step.computer"), computer],
+ ["account", t("remote.diagnosis.step.account"), account],
+ ["relay", t("remote.diagnosis.step.relay"), relay],
+ ["route", t("remote.diagnosis.step.route"), route],
+ ];
+ const steps = evaluated.map(([id, label, step]): RemoteAccessStep => ({ id, label, result: step.result, reason: step.reason }));
+ const first = evaluated.find(([, , step]) => step.result === "failed")?.[2];
+ const waiting = steps.some((step) => step.result === "unchecked" && step.id !== "relay");
+ return {
+ headline: first?.reason ?? (route.result === "ok" ? route.reason : waiting ? t("remote.diagnosis.connecting") : t("remote.diagnosis.allClear")),
+ steps,
+ next: first?.next ?? [],
+ facts: factsOf(facts),
+ failed: Boolean(first),
+ };
+}
+
+const MARK = { ok: "remote.diagnosis.mark.ok", failed: "remote.diagnosis.mark.failed", unchecked: "remote.diagnosis.mark.unchecked" } as const;
+
+export const remoteAccessStepMark = (result: RemoteAccessStepResult): string => t(MARK[result]);
+
+/** One plain-text block to paste into a support message. It holds the localised lines above and the facts, nothing
+ * else: no email, address, token, pairing code or key. */
+export function remoteAccessDiagnosisText(diagnosis: RemoteAccessDiagnosis): string {
+ return [
+ t("remote.diagnosis.copyTitle", { headline: diagnosis.headline }),
+ "",
+ ...diagnosis.steps.map((step) => `${step.label}: ${remoteAccessStepMark(step.result)} · ${step.reason}`),
+ ...(diagnosis.next.length ? ["", ...diagnosis.next.map((line) => `- ${line}`)] : []),
+ "",
+ ...diagnosis.facts.map(([key, value]) => `${key}: ${value}`),
+ ].join("\n");
+}
diff --git a/src/locales/en.json b/src/locales/en.json
index 8092039b03..62365ccb51 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -10317,6 +10317,68 @@
"remote.e2e.anywhere": "Reachable from anywhere · end-to-end encrypted",
"remote.e2e.connecting": "Connecting to MausBot Relay…",
"remote.e2e.local": "On this Wi-Fi and Tailscale · end-to-end encrypted",
+ "remote.diagnosis.title": "Connection check",
+ "remote.diagnosis.subtitle": "Each step between your phone and this computer, and what to try.",
+ "remote.diagnosis.copy": "Copy diagnostics",
+ "remote.diagnosis.copied": "Copied",
+ "remote.diagnosis.copyNote": "Holds no email, address, code or key.",
+ "remote.diagnosis.nextTitle": "What you can do",
+ "remote.diagnosis.copyTitle": "{app} remote access: {headline}",
+ "remote.diagnosis.mark.ok": "ok",
+ "remote.diagnosis.mark.failed": "failed",
+ "remote.diagnosis.mark.unchecked": "not checked",
+ "remote.diagnosis.step.computer": "This computer",
+ "remote.diagnosis.step.account": "{app} account",
+ "remote.diagnosis.step.relay": "{app} Relay",
+ "remote.diagnosis.step.route": "Your phone's way in",
+ "remote.diagnosis.notChecked": "Not checked yet.",
+ "remote.diagnosis.connecting": "Connecting…",
+ "remote.diagnosis.allClear": "Everything that is on works.",
+ "remote.diagnosis.computer.on": "The phone link is on.",
+ "remote.diagnosis.computer.off": "The phone link is off.",
+ "remote.diagnosis.computer.failed": "The phone link on this computer didn't start.",
+ "remote.diagnosis.account.signedIn": "Signed in.",
+ "remote.diagnosis.account.signedOut": "Not signed in.",
+ "remote.diagnosis.account.unreachable": "This computer can't reach {app} right now.",
+ "remote.diagnosis.account.expired": "Your sign-in expired.",
+ "remote.diagnosis.account.busy": "{app} is busy right now.",
+ "remote.diagnosis.account.limit": "This account has reached its computer limit.",
+ "remote.diagnosis.account.update": "This version of {app} is too old to connect.",
+ "remote.diagnosis.account.credential": "This computer's sign-in was not accepted.",
+ "remote.diagnosis.account.failed": "Signing in didn't finish.",
+ "remote.diagnosis.account.unconfigured": "Not set up in this build of {app}.",
+ "remote.diagnosis.account.notNeeded": "Not needed for Same Wi-Fi or Tailscale.",
+ "remote.diagnosis.relay.idle": "Starts when a phone needs it.",
+ "remote.diagnosis.next.askAgain": "{app} asks again on its own within the hour, or as soon as you pair a phone.",
+ "remote.diagnosis.relay.off": "Not used: Anywhere is off.",
+ "remote.diagnosis.relay.needsAccount": "Needs the {app} account first.",
+ "remote.diagnosis.relay.connected": "Connected. The relay confirmed this computer.",
+ "remote.diagnosis.relay.unavailable": "{app} Relay isn't available for this computer right now.",
+ "remote.diagnosis.relay.busy": "{app} Relay is busy.",
+ "remote.diagnosis.relay.noAccess": "This computer couldn't get access to the relay.",
+ "remote.diagnosis.relay.noAnswer": "{app} Relay didn't answer.",
+ "remote.diagnosis.relay.unreachable": "This computer can't reach {app} Relay.",
+ "remote.diagnosis.relay.replaced": "Another copy of {app} took over this computer's relay connection.",
+ "remote.diagnosis.route.anywhere": "Your phone can reach this computer from anywhere.",
+ "remote.diagnosis.route.wifi": "Your phone can reach this computer on the same Wi-Fi.",
+ "remote.diagnosis.route.tailscale": "Your phone can reach this computer on your tailnet.",
+ "remote.diagnosis.route.https": "The HTTPS address isn't working.",
+ "remote.diagnosis.route.noWifi": "This computer isn't on a Wi-Fi network.",
+ "remote.diagnosis.route.none": "No way in works yet.",
+ "remote.diagnosis.route.off": "No way in is on.",
+ "remote.diagnosis.next.internet": "Check this computer's internet connection. {app} tries again on its own.",
+ "remote.diagnosis.next.vpn": "A VPN or firewall on this computer can block {app} Relay.",
+ "remote.diagnosis.next.signIn": "Sign in again.",
+ "remote.diagnosis.next.wait": "Wait a few minutes. {app} tries again on its own.",
+ "remote.diagnosis.next.removeComputer": "Remove a computer you no longer use from your account, then try again.",
+ "remote.diagnosis.next.update": "Update {app}, then try again.",
+ "remote.diagnosis.next.retry": "Try again.",
+ "remote.diagnosis.next.support": "If it keeps failing, copy the diagnostics and send them to support.",
+ "remote.diagnosis.next.restart": "Quit {app} and open it again.",
+ "remote.diagnosis.next.turnOn": "Turn on Same Wi-Fi or Anywhere, through {app}.",
+ "remote.diagnosis.next.useWifi": "Same Wi-Fi still works: pair on this Wi-Fi for now.",
+ "remote.diagnosis.next.joinWifi": "Connect this computer to Wi-Fi.",
+ "remote.diagnosis.next.otherCopy": "Quit the other copy of {app}, then turn Anywhere off and on.",
"serverError.mailbox.outgoingFields": "Check the outgoing server: a name like mail.example.com, a port from 1 to 65535, and SSL/TLS or STARTTLS.",
"server.meetings.card.title": "Meeting notes",
"server.meetings.card.starting": "Getting the cloud computer ready…",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index afc6f0f2d3..f8ddd885cf 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -10268,6 +10268,68 @@
"remote.e2e.anywhere": "Acessível de qualquer lugar · criptografia de ponta a ponta",
"remote.e2e.connecting": "Conectando ao MausBot Relay…",
"remote.e2e.local": "Neste Wi-Fi e Tailscale · criptografia de ponta a ponta",
+ "remote.diagnosis.title": "Verificação da conexão",
+ "remote.diagnosis.subtitle": "Cada etapa entre seu celular e este computador, e o que tentar.",
+ "remote.diagnosis.copy": "Copiar diagnóstico",
+ "remote.diagnosis.copied": "Copiado",
+ "remote.diagnosis.copyNote": "Não inclui e-mail, endereço, código nem chave.",
+ "remote.diagnosis.nextTitle": "O que você pode fazer",
+ "remote.diagnosis.copyTitle": "Acesso remoto do {app}: {headline}",
+ "remote.diagnosis.mark.ok": "ok",
+ "remote.diagnosis.mark.failed": "falhou",
+ "remote.diagnosis.mark.unchecked": "não verificado",
+ "remote.diagnosis.step.computer": "Este computador",
+ "remote.diagnosis.step.account": "Conta do {app}",
+ "remote.diagnosis.step.relay": "{app} Relay",
+ "remote.diagnosis.step.route": "Como seu celular chega aqui",
+ "remote.diagnosis.notChecked": "Ainda não verificado.",
+ "remote.diagnosis.connecting": "Conectando…",
+ "remote.diagnosis.allClear": "Tudo o que está ligado funciona.",
+ "remote.diagnosis.computer.on": "A conexão com o celular está ligada.",
+ "remote.diagnosis.computer.off": "A conexão com o celular está desligada.",
+ "remote.diagnosis.computer.failed": "A conexão com o celular não iniciou neste computador.",
+ "remote.diagnosis.account.signedIn": "Login feito.",
+ "remote.diagnosis.account.signedOut": "Sem login.",
+ "remote.diagnosis.account.unreachable": "Este computador não consegue acessar o {app} agora.",
+ "remote.diagnosis.account.expired": "Seu login expirou.",
+ "remote.diagnosis.account.busy": "O {app} está ocupado agora.",
+ "remote.diagnosis.account.limit": "Esta conta chegou ao limite de computadores.",
+ "remote.diagnosis.account.update": "Esta versão do {app} é antiga demais para conectar.",
+ "remote.diagnosis.account.credential": "O login deste computador não foi aceito.",
+ "remote.diagnosis.account.failed": "O login não terminou.",
+ "remote.diagnosis.account.unconfigured": "Não configurado nesta versão do {app}.",
+ "remote.diagnosis.account.notNeeded": "Não é necessário para Mesmo Wi-Fi nem Tailscale.",
+ "remote.diagnosis.relay.idle": "Começa quando um celular precisar.",
+ "remote.diagnosis.next.askAgain": "O {app} tenta de novo sozinho em até uma hora, ou assim que você parear um celular.",
+ "remote.diagnosis.relay.off": "Não usado: De qualquer lugar está desligado.",
+ "remote.diagnosis.relay.needsAccount": "Precisa primeiro da conta do {app}.",
+ "remote.diagnosis.relay.connected": "Conectado. O relay confirmou este computador.",
+ "remote.diagnosis.relay.unavailable": "O {app} Relay não está disponível para este computador agora.",
+ "remote.diagnosis.relay.busy": "O {app} Relay está ocupado.",
+ "remote.diagnosis.relay.noAccess": "Este computador não conseguiu acesso ao relay.",
+ "remote.diagnosis.relay.noAnswer": "O {app} Relay não respondeu.",
+ "remote.diagnosis.relay.unreachable": "Este computador não consegue acessar o {app} Relay.",
+ "remote.diagnosis.relay.replaced": "Outra cópia do {app} assumiu a conexão deste computador com o relay.",
+ "remote.diagnosis.route.anywhere": "Seu celular consegue acessar este computador de qualquer lugar.",
+ "remote.diagnosis.route.wifi": "Seu celular consegue acessar este computador no mesmo Wi-Fi.",
+ "remote.diagnosis.route.tailscale": "Seu celular consegue acessar este computador pela sua tailnet.",
+ "remote.diagnosis.route.https": "O endereço HTTPS não está funcionando.",
+ "remote.diagnosis.route.noWifi": "Este computador não está em uma rede Wi-Fi.",
+ "remote.diagnosis.route.none": "Nenhuma forma de acesso funciona ainda.",
+ "remote.diagnosis.route.off": "Nenhuma forma de acesso está ligada.",
+ "remote.diagnosis.next.internet": "Verifique a conexão com a internet deste computador. O {app} tenta novamente sozinho.",
+ "remote.diagnosis.next.vpn": "Uma VPN ou um firewall neste computador pode bloquear o {app} Relay.",
+ "remote.diagnosis.next.signIn": "Faça login novamente.",
+ "remote.diagnosis.next.wait": "Aguarde alguns minutos. O {app} tenta novamente sozinho.",
+ "remote.diagnosis.next.removeComputer": "Remova da sua conta um computador que você não usa mais e tente novamente.",
+ "remote.diagnosis.next.update": "Atualize o {app} e tente novamente.",
+ "remote.diagnosis.next.retry": "Tente novamente.",
+ "remote.diagnosis.next.support": "Se continuar falhando, copie o diagnóstico e envie para o suporte.",
+ "remote.diagnosis.next.restart": "Feche o {app} e abra de novo.",
+ "remote.diagnosis.next.turnOn": "Ligue Mesmo Wi-Fi ou De qualquer lugar, pelo {app}.",
+ "remote.diagnosis.next.useWifi": "Mesmo Wi-Fi continua funcionando: por enquanto, pareie nesta rede Wi-Fi.",
+ "remote.diagnosis.next.joinWifi": "Conecte este computador a uma rede Wi-Fi.",
+ "remote.diagnosis.next.otherCopy": "Feche a outra cópia do {app} e depois desligue e ligue De qualquer lugar.",
"serverError.mailbox.outgoingFields": "Confira o servidor de saída: um nome como mail.example.com, uma porta de 1 a 65535 e SSL/TLS ou STARTTLS.",
"server.meetings.card.title": "Notas da reunião",
"server.meetings.card.starting": "Preparando o computador na nuvem…",
diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.ts
index bdf266223b..371daebab1 100644
--- a/src/types/ogb.d.ts
+++ b/src/types/ogb.d.ts
@@ -551,6 +551,8 @@ export interface CompanionAccountState {
/** The secure address was ended for old phone apps: a phone that has not used the encrypted connection must be
* updated and paired again. */
tunnelRetired?: boolean;
+ /** What failed, as one fixed word for the connection diagnosis. Absent on older builds. */
+ problem?: "unconfigured" | "unreachable" | "sign_in" | "busy" | "limit" | "update" | "address" | "failed";
}
export type AndroidUsbDevice = {