Skip to content

Commit e5efd04

Browse files
wesbillmannpub1yxv5wk0u0fh6dwt925wntn7h397jvteyj4r87ttcd9xae7n2t3lqqj9jmmnpub1gjuws2a2dc8z2nszprtg7v6u9q7ffeah3hgl5yx45jwn7y7aqs6s5e9xj6
authored
fix(desktop): close reconnect gaps that previously required CMD+R (block#4737)
> Opened by Brain (agent) on behalf of @wesbillman. ## Problem Users report the desktop app doesn't reliably reconnect and can wedge in states where only CMD+R (or a full restart) restores connectivity (thread `c2205e2b` in #desktop-reconnecting). Pinky's empirical light-switch matrix (real `buzz-relay`, SIGTERM/1012 + SIGKILL × 1s/45s/3min, at `f18a9cb10`) passed 4/4 — the backoff state machine recovers cleanly from ordinary relay loss. That isolates the user-stuck states to four special cases a reload resets but the auto flow never did. ## Fixes | Gap | Change | |---|---| | **G1** — recovery rode solely on the backoff timer (max 30s), throttled by WKWebView in occluded/background windows; nothing fired on network return or wake | New `useRelayResumeTriggers`: `online`, window focus, and visibility→visible call `preconnect()` when the session is `reconnecting`/`stalled`, rate-limited to one attempt per 5s (`relayResumeTriggerPolicy.ts`). Deliberately inert for the terminal `disconnected` state. | | **G2** — any AUTH `OK false` latched the session terminal forever, though the relay also rejects for transient causes (duplicate-AUTH "already authenticated" race, ±60s clock skew, fail-closed allowlist DB errors) | New `AuthOkTracker` (`relayAuthPolicy.ts`): "already authenticated" resolves as success; transient rejections retry with normal backoff; latch only on `restricted:` or after 3 consecutive rejections. | | **G3** — an `auth-required:` CLOSED (REQ racing AUTH after reconnect) permanently deleted the live subscription with no UI signal — frozen channel while state reads "connected" | Reclassified `auth-required:` as retryable in `relayClosedPolicy.ts`. Genuinely terminal classes (`restricted:`, `invalid:`, …) still delete. Can't loop: a truly unauthenticated session latches terminal at the connection level. | | **G4** — `useRelayAutoHeal` observed the 2s-debounced connection hook, so sub-2s flaps never triggered the heal even though `resetConnection` had already rejected every in-flight query | Auto-heal now observes the raw connection-state emitter. The existing 15s heal rate-limit still guards against flap storms. | Each fix is a colocated pure-policy module + unit tests, matching the existing `relayReconnectPolicy`/`relayClosedPolicy` pattern. ## Validation - Full desktop unit suite: **4151 pass, 0 fail** (at branch tip, `pnpm -C desktop test`) - `pnpm -C desktop typecheck` and `pnpm -C desktop check` clean (file-size ratchet respected — `relayClientSession.ts` net −2 lines despite the tracker wiring) - Evidence trail: `RESEARCH/DESKTOP_RECONNECT_CMDR_GAP_AUDIT.md` (audit), `RESEARCH/DESKTOP_RECONNECT_LIGHT_SWITCH_RESULTS.md` (Pinky's matrix) ## Not covered / follow-ups - Native macOS sleep-wake was not automated (would kill the harness session); G1's focus trigger is the mechanism that covers wake in practice, but a manual sleep-wake verification on a real build is worthwhile. - G3 terminal-CLOSED classes (`restricted:` etc.) still silently delete subs with no UI signal — surfacing that is a separate UX decision. - Stall-watchdog latency (60s idle + 10s check) left unchanged; G1 triggers largely mask it. --------- Signed-off-by: Wes <[email protected]> Signed-off-by: npub1gjuws2a2dc8z2nszprtg7v6u9q7ffeah3hgl5yx45jwn7y7aqs6s5e9xj6 <44b8e82baa6e0e254e0208d68f335c283c94e7b78dd1fa10d5a49d3f13dd0435@buzz.block.builderlab.xyz> Co-authored-by: npub1yxv5wk0u0fh6dwt925wntn7h397jvteyj4r87ttcd9xae7n2t3lqqj9jmm <21994759fc7a6fa6b965551d35cfd7897d262f2495467f2d78694ddcfa6a5c7e@buzz.block.builderlab.xyz> Co-authored-by: npub1gjuws2a2dc8z2nszprtg7v6u9q7ffeah3hgl5yx45jwn7y7aqs6s5e9xj6 <44b8e82baa6e0e254e0208d68f335c283c94e7b78dd1fa10d5a49d3f13dd0435@buzz.block.builderlab.xyz>
1 parent cb4a73e commit e5efd04

13 files changed

Lines changed: 680 additions & 69 deletions

‎desktop/src/app/useAppShellLifecycleEffects.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as React from "react";
22

33
import { setDesktopAppBadge } from "@/features/notifications/lib/desktop";
44
import { relayClient } from "@/shared/api/relayClient";
5+
import { useRelayResumeTriggers } from "@/shared/api/useRelayResumeTriggers";
56

67
type AppShellLifecycleEffectsOptions = {
78
desktopBadgeEnabled: boolean;
@@ -16,6 +17,10 @@ export function useAppShellLifecycleEffects({
1617
unreadChannelIds,
1718
unreadChannelNotificationCount,
1819
}: AppShellLifecycleEffectsOptions) {
20+
// Event-driven reconnect: network online / focus / visibility short-circuit
21+
// the backoff timer when the relay session is degraded (CMD+R gap G1).
22+
useRelayResumeTriggers();
23+
1924
// Prevent webview file:/// navigation on file drop outside the composer.
2025
// Scoped to file drags only (text drag-and-drop into inputs still works).
2126
// Composer's onDrop fires first (React synthetic before window bubble).
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
import assert from "node:assert/strict";
2+
import test from "node:test";
3+
4+
import {
5+
AuthOkTracker,
6+
MAX_CONSECUTIVE_AUTH_REJECTIONS,
7+
} from "./relayAuthPolicy.ts";
8+
9+
test("success resolves authenticated and resets the streak", () => {
10+
const tracker = new AuthOkTracker();
11+
tracker.record(false, "auth-required: verification failed");
12+
tracker.record(false, "auth-required: verification failed");
13+
assert.equal(tracker.record(true, ""), "authenticated");
14+
// Streak reset: the next rejection starts a fresh count.
15+
assert.equal(
16+
tracker.record(false, "auth-required: verification failed"),
17+
"retry",
18+
);
19+
});
20+
21+
test("already-authenticated rejection is treated as authenticated (duplicate-AUTH race)", () => {
22+
const tracker = new AuthOkTracker();
23+
assert.equal(
24+
tracker.record(false, "auth-required: already authenticated"),
25+
"authenticated",
26+
);
27+
});
28+
29+
test("restricted rejections latch terminal immediately", () => {
30+
for (const message of [
31+
"restricted: not a relay member",
32+
"restricted: you are banned",
33+
]) {
34+
assert.equal(new AuthOkTracker().record(false, message), "terminal");
35+
}
36+
});
37+
38+
test("the relay's actual ban string latches terminal immediately", () => {
39+
// Exact string emitted by crates/buzz-relay/src/handlers/auth.rs at the
40+
// ban seam. A known-permanent ban must never enter the retry loop.
41+
assert.equal(
42+
new AuthOkTracker().record(
43+
false,
44+
"blocked: you are banned from this community",
45+
),
46+
"terminal",
47+
);
48+
});
49+
50+
test("verification failures retry with backoff (clock skew, DB fail-closed)", () => {
51+
const tracker = new AuthOkTracker();
52+
assert.equal(
53+
tracker.record(false, "auth-required: verification failed"),
54+
"retry",
55+
);
56+
});
57+
58+
test("unknown rejection reasons retry rather than latch", () => {
59+
assert.equal(new AuthOkTracker().record(false, ""), "retry");
60+
assert.equal(new AuthOkTracker().record(false, "error: internal"), "retry");
61+
});
62+
63+
test("consecutive rejections latch terminal at the cap", () => {
64+
const tracker = new AuthOkTracker();
65+
let decision = "retry";
66+
for (let i = 0; i < MAX_CONSECUTIVE_AUTH_REJECTIONS; i++) {
67+
decision = tracker.record(false, "auth-required: verification failed");
68+
}
69+
assert.equal(decision, "terminal");
70+
});
71+
72+
test("reset grants a fresh retry streak after explicit re-engagement", () => {
73+
const tracker = new AuthOkTracker();
74+
for (let i = 0; i < MAX_CONSECUTIVE_AUTH_REJECTIONS; i++) {
75+
tracker.record(false, "auth-required: verification failed");
76+
}
77+
tracker.reset();
78+
assert.equal(
79+
tracker.record(false, "auth-required: verification failed"),
80+
"retry",
81+
);
82+
});
83+
84+
test("already-authenticated wins even past the cap (session is usable)", () => {
85+
const tracker = new AuthOkTracker();
86+
for (let i = 0; i < MAX_CONSECUTIVE_AUTH_REJECTIONS + 1; i++) {
87+
tracker.record(false, "auth-required: verification failed");
88+
}
89+
assert.equal(
90+
tracker.record(false, "auth-required: already authenticated"),
91+
"authenticated",
92+
);
93+
});
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/**
2+
* Policy for NIP-42 AUTH `OK` responses (G2 of the CMD+R gap audit).
3+
*
4+
* Historically ANY auth `OK false` latched the session terminal — no
5+
* reconnect until explicit user re-engagement. But the relay sends
6+
* `OK false` for conditions that are transient from the client's side:
7+
*
8+
* - `auth-required: already authenticated` — a duplicate/late AUTH event on
9+
* a connection that is in fact authenticated. The session is usable;
10+
* treat it as authenticated.
11+
* - `auth-required: verification failed` — covers ±60s clock-skew rejects
12+
* and the relay's fail-closed allowlist DB lookup errors, both of which
13+
* can clear on retry.
14+
*
15+
* Only `restricted:` and `blocked:` rejections (not a relay member / banned)
16+
* are known permanent. Everything else retries with normal backoff, but
17+
* latches terminal after `MAX_CONSECUTIVE_AUTH_REJECTIONS` consecutive
18+
* rejections so a genuinely broken identity (e.g. persistently wrong system
19+
* clock) still surfaces the terminal error card instead of flapping forever.
20+
*
21+
* The rejection streak is preserved across environment-driven resume
22+
* attempts (focus/online/visibility); only explicit user re-engagement —
23+
* the reconnect card or a community switch — may reset it.
24+
*/
25+
export type AuthOkDecision = "authenticated" | "retry" | "terminal";
26+
27+
export const MAX_CONSECUTIVE_AUTH_REJECTIONS = 3;
28+
29+
/** Tracks consecutive AUTH rejections across reconnect attempts. */
30+
export class AuthOkTracker {
31+
private consecutiveRejections = 0;
32+
33+
/**
34+
* Record an AUTH `OK` and decide the session's next move.
35+
* A success — real or "already authenticated" — resets the streak.
36+
*/
37+
record(success: boolean, message: string): AuthOkDecision {
38+
const normalized = message.trim().toLowerCase();
39+
if (
40+
success ||
41+
normalized.startsWith("auth-required: already authenticated")
42+
) {
43+
this.consecutiveRejections = 0;
44+
return "authenticated";
45+
}
46+
47+
this.consecutiveRejections++;
48+
49+
if (
50+
normalized.startsWith("restricted:") ||
51+
normalized.startsWith("blocked:")
52+
) {
53+
return "terminal";
54+
}
55+
if (this.consecutiveRejections >= MAX_CONSECUTIVE_AUTH_REJECTIONS) {
56+
return "terminal";
57+
}
58+
return "retry";
59+
}
60+
61+
/** Called on explicit re-engagement (disconnect / manual preconnect). */
62+
reset(): void {
63+
this.consecutiveRejections = 0;
64+
}
65+
}

0 commit comments

Comments
 (0)