fix(desktop): bound startup request bursts and recover quota refusals (#7790)

Prepared by Brain on Wes’s behalf.

## Summary

Reduce startup request amplification and let quota-refused background
work recover without changing relay quotas or bypassing the existing
Send gate.

- Coalesce nest regeneration into one worker plus the latest pending
generation. Keep the stale-write fence; bound the archive read so an old
workspace cannot strand newer work.
- Claim pending channel subscriptions before awaiting setup; cancel
removed/unmounted entries and preserve still-owned subscriptions across
reconnect handoff.
- Recheck extended cooldown deadlines before retry dispatch; distinguish
an explicit zero-second hint from a missing hint.
- Recover native finite/unread queries within their original caller
deadline and a three-retry budget, preserving verified unique events,
complete filters and terminal errors.
- Pace renderer initial/live-CLOSED REQs at one per 250ms: visible
channel and explicitly interactive TTS/read-state/observer owners first,
then live-only auxiliaries, then background history. Publication and
finite queries bypass this queue. Reconnect replay now promotes explicit
interactive owners alongside the visible channel with stable
registration-order ties; its existing capped batches and cooldown remain
intact.

**Scope at `867495426`:** 39 source/test files, including 15 production
files (+665/-235) and 24 test/fixture files. The diagnostic recorder,
HTTP instrumentation, trace launcher and raw captures are deliberately
excluded. No profile reset, grouping, quota increase or new global
scheduler.

## Before / after evidence

These are observations from instrumented, human-operated development
Tauri/Vite runs against a production relay, plus explicitly identified
controlled regressions—not a packaged-release startup benchmark.

| Measurement | Before | After | Evidence boundary |
| --- | --- | --- | --- |
| Archive snapshot requests (kind 13535) | 290 | 3 | Recorder-only
baseline → nest-only intermediate candidate; unequal 67.436s / 39.273s
captures and hydration differences |
| Archive responses: HTTP 200 / 429 | 277 / 13 | 3 / 0 | Same
baseline/nest-only captures; not a claim that all quota pressure
disappeared |
| Successful archive responses’ advertised content-length sum |
21,208,505 bytes | 229,695 bytes | Header values, not actual transferred
bytes |
| 154-channel StrictMode replay | 308 REQs | 154 REQs | Controlled real
React hook → real session → mocked Tauri transport regression |
| Add one channel while 154 setups are pending | 309 REQs | 155 REQs |
Same production-boundary regression; ordinary mount remains 154 → 154 |
| Broad renderer request burst / spacing | 110 broad REQs within
10.766ms in pre-drain capture | 250.061ms minimum / 252.131ms median
between broad REQ writes in final longer capture | Different attended
runs; pacing rather than a universal request-rate cap |
| Native unread query outcomes | Baseline: 8 EOSE / 146 quota CLOSED out
of 154 queries | Final longer run: all 156 observed queries reach EOSE;
eight refused queries each recover after two refusals | Different
runs/workloads; query completion, not badge rendering |

### Timing metrics

| Observation | Measured value |
| --- | ---: |
| Baseline’s two accepted chat EVENT socket writes → positive OK |
173.340ms / 85.556ms |
| Nest-only intermediate candidate’s two accepted writes → positive OK |
277.854ms / 78.775ms |
| Final candidate, short run, accepted chat writes → positive OK |
80.636ms / 77.506ms |
| Final candidate, longer run, accepted chat writes → positive OK |
120.712ms / 86.895ms |
| Last initial EOSE among 163 observed broad channel registrations,
longer run | 64.550s after trace start |
| Last EOSE among 156 observed native unread queries, longer run |
73.972s after trace start |
| Native retry waits after 3s then 0s hints, longer run |
3000.7–3002.8ms, then 2001.5–2002.6ms |
| Renderer finite-query retry after a 2s hint, longer run | 2061.365ms |

Both Sends in each final run were accepted, with no recorded negative
OK. Every quota-refused query in the longer run subsequently completed
the same query. Its two Sends happened early (17.878s and 21.655s), not
near the end. These small samples do not support a percentage latency
improvement.

**Tradeoffs and limits**
- 296 background subscriptions imply about 74s of paced registration
before extra cooldowns/high-priority work. The longer capture observed
163 registrations; it did not independently enumerate the expected
membership set or record a queue-empty marker.
- This is not a global 4-REQ/s cap: finite queries, native requests and
reconnect replay are outside the drain and still share relay quota.
Quota refusals recover rather than disappear.
- Socket-write → OK starts after composer submission and any publisher
gate wait. No click-to-visible, launch-to-usable or badge-paint latency
is claimed.
- Native EOSE is not proof of command return, classification, React
state application or visible unread badges. Existing per-channel kinds,
since floors, limits, h-less routing, unread lease/scope guard and
eight-query concurrency remain intact.
- The attended measurements belong to the instrumented candidate, not a
fresh release run of this fixes-only commit. At the initial packaging
checkpoint (`1bf3d060`), eighteen of twenty files were byte-identical;
the other two removed diagnostic gate calls and isolated the nest test’s
temporary paths. The subsequent interactive priority/reconnect and
readiness fixes have controlled hook/session/browser evidence, not
another attended voice/performance run.

### Evidence provenance (captures retained locally, not uploaded)

| Capture | SHA-256 |
| --- | --- |
| Baseline `STARTUP_20260921T194814Z_98811.jsonl` |
`f4f0a89ad9aea91084bd6a7432510488166de4cbc906600d88c26d557f380994` |
| Nest-only `STARTUP_20260921T202610Z_28642.jsonl` |
`ce517b02a3f717c36d96b36bb8616e8fa80b03b12b356bacfd40475925ea3f3e` |
| Final short `STARTUP_20260922T013628Z_13506.jsonl` |
`bfea6f3cf80cd7b7e4e676632a3df2f16271fade5bfa0edec72b7bcbbe7839ff` |
| Final longer `STARTUP_20260922T014637Z_15846.jsonl` |
`f4abece613d108c4c2fe3cb808e633a0486bdc9993ca92323822dc00c3fae6ec` |

Final instrumented build fingerprint:
`b0b4fc27d793c3e643f4e10289b5afdb4620ee2e13a8b33fa0595dd3417fd5ca`. All
observed dropped-record counters in these final captures were zero.
Source manifests and offline correlation analyses are retained locally;
no raw captures, profile data or agent sessions are part of this PR.

## Validation

Current head: `86749542657a60abdfe82eed5cc576d3e162fe5d`, based on
`77729abfb692b25a0f4ec4a69add86af2e32c0dd`.

Review follow-ups:
- `8842dbd8`: explicit interactive TTS admission using the existing
main-window owner, independent of companion/timeline selection.
Real-hook/session/IPC coverage with 296 cold owners proves initial and
CLOSED priority, unchanged filters/cooldown/pacing, background progress
and deduplicated speech.
- `8cb088106`: reconnect preserves interactive priority even with no
visible channel. Stable ordering among foreground ties; real
hook/session reconnect regressions cover cooldown, capped batching, all
297 owners, deduplication and unmount cancellation. Independent reviewer
mutation restored the prior replay implementation, failed both reconnect
rows, then passed the restored candidate.
- `68e76d7c`: read-state and observer reuse interactive priority. Stop
and ModelPicker wait on the existing observer owner inside send
callbacks, after installing result listeners/deadlines. No new owner,
timer or scheduler; inherited CLOSED/fallback/error semantics remain,
rather than a new strict EOSE guarantee. The real Stop panel browser
probe holds observer IPC across the click and checks
observer-before-control order and correlated outcome. ModelPicker
component ordering is source-reviewed only.
- Mock live admission now replays matching stored history with
per-filter time/limit constraints, deduplication, untagged auxiliary
channel fallback and authoritative explicit h-tags. Kind-specific
fixture admission waits and retry-resolving hover actions fix
startup-dependent test setup without weakening event/badge assertions.
- `48e9c0dad` and `867495426`: steady-state scroll-prepend setup
observes live admission, subsequent head dispatch, successful/idle query
completion and initial bottom geometry. Phase-2 genuine-growth and ≤32px
anchor assertions are unchanged. This isolates steady-state prepending:
it **does not fix or certify production early-scroll/head-reset
behavior**.

Current validation:
- Normal push hooks at `867495426`: **6,582/6,582 renderer tests**, zero
failed/skipped/cancelled; lint/static checks, typecheck and differential
file-size gate passed. Native source is unchanged from the earlier
checkpoint; no new native run is claimed for these renderer/test
follow-ups.
- E2E build passed at `48e9c0dad` plus the exact subsequently committed
test-only delta (spec blob `469be2eed868c677ba80b859cc871208000fee60`).
The completed affected-smoke run passed **153/153** across
agent-control, badge, entity links, messaging, profile status and scroll
history; the full scroll file additionally passed twice (**36/36**). No
full CI-smoke pass is claimed from this six-file local run.
- Pinky independently reviewed production and test follow-ups, including
the final scroll spec blob `469be2eed868c677ba80b859cc871208000fee60`,
with no blocking finding. Review is source evidence, not an independent
test run.
- **Not merge-ready:** new-head required CI must complete, exact-range
security review requires authorization, and GitHub currently reports
REVIEW_REQUIRED; fresh exact-head reviewer approval is still needed. No
approval, dismissal or merge performed. No new packaged/native audio,
launch-to-usable or badge-paint observation is claimed.

Initial fixes-only checkpoint validation
(`1bf3d06024d284a63326fdd353baced0842aeb81`):

- Pre-commit formatting hooks passed; worktree clean.
- Renderer package hooks: 6,570 tests passed, zero
failed/skipped/cancelled; lint/static checks, TypeScript and
differential file-size gate passed.
- Native package hook passed: default and mesh-enabled all-target
Clippy, then the complete native workspace test suite. App library:
3,222 passed / 0 failed / 19 ignored; terminal/integration suites
passed. The real nest trigger/stalled-body test passed on macOS.
- Independent whole-change source review: no blocking findings at this
commit; all 20 file hashes matched the committed blobs and
review/validation manifests.
- Regression coverage includes real hook/session cancellation,
StrictMode/membership re-entry, reconnect ownership, extended/zero
cooldowns, burst pacing, auxiliary readiness (including EOSE before IPC
settles), native socket refusal/retry/deadline/cancellation, unread
fetch/classification and real nest trigger/HTTP/file persistence.
- Earlier isolated renderer mutations that started readiness before
enqueue or removed auxiliary priority each failed the real presence
regression; restored controls passed. No native mutation claim.
- Nest fixture uses explicit app-data/nest paths instead of assuming
Windows known-folder APIs obey HOME/APPDATA. Windows runtime execution
is not claimed; CI/build results remain separate.

Originating conversation:
buzz://message?channel=46ced308-71df-495d-a144-4ebf08334703&id=bc43c3422a3b0b2141268d0fa149b898421c824992b662aed8b73c4eee50404f

No approval or merge recommendation is implied by opening this PR.

---------

Signed-off-by: Brain <1a02c72794dcd0f07058a353bc3a81f4028b8c77c92c87fce6d5c8b85970a20b@buzz.block.builderlab.xyz>
Co-authored-by: Brain <1a02c72794dcd0f07058a353bc3a81f4028b8c77c92c87fce6d5c8b85970a20b@buzz.block.builderlab.xyz>
This commit is contained in:
Wes
2026-09-22 11:31:44 -07:00
committed by GitHub
parent 7881447c19
commit c213d90d5c
49 changed files with 4265 additions and 387 deletions

View File

@@ -10,7 +10,7 @@ import { subscribeToAgentObserverFrames } from "./observerRelay.ts";
// network drop never re-delivers and the active-agents badge never appears.
test("subscribeToAgentObserverFrames requests a replay-capable limit with a since window", () => {
const calls = [];
mock.method(relayClient, "subscribeLive", (filter) => {
mock.method(relayClient, "subscribeInteractive", (filter) => {
calls.push(filter);
return () => {};
});
@@ -44,7 +44,7 @@ test("subscribeToAgentObserverFrames since is at least 300s before now", () => {
mock.method(Date, "now", () => FIXED_NOW_MS);
const calls = [];
mock.method(relayClient, "subscribeLive", (filter) => {
mock.method(relayClient, "subscribeInteractive", (filter) => {
calls.push(filter);
return () => {};
});

View File

@@ -15,7 +15,8 @@ export function subscribeToAgentObserverFrames(
ownerPubkey: string,
onEvent: (event: RelayEvent) => void,
) {
return relayClient.subscribeLive(
// Ephemeral control results must not wait behind cold channel history.
return relayClient.subscribeInteractive(
{
kinds: [KIND_AGENT_OBSERVER_FRAME],
"#p": [ownerPubkey],

View File

@@ -0,0 +1,539 @@
// Exercise the production session from live registration/refusal through actual IPC dispatch.
// The IPC transport and clock are fake; no native app or external relay is used.
import assert from "node:assert/strict";
import { after, beforeEach, afterEach, test } from "node:test";
const originalNow = Date.now;
const originalWindow = globalThis.window;
let now = 0;
let nextTimerId = 1;
const timers = new Map();
const writes = [];
const clients = [];
let onSend;
globalThis.window = {
setTimeout(fn, ms) {
const id = nextTimerId++;
timers.set(id, { fn, at: now + ms });
return id;
},
clearTimeout(id) {
timers.delete(id);
},
__TAURI_INTERNALS__: {
async invoke(command, args) {
if (command === "plugin:websocket|send") {
writes.push({
socket: args.id,
frame: JSON.parse(args.message.data),
at: now,
});
await onSend?.(writes.at(-1));
return;
}
if (command === "plugin:websocket|disconnect") return;
assert.fail(`unexpected IPC: ${command}`);
},
},
};
Date.now = () => now;
const { RelayClient } = await import("./relayClientSession.ts");
const { resetRateLimitGate } = await import("./relayRateLimitGate.ts");
const { openPresenceSubscription } = await import(
"./presenceRelaySubscription.ts"
);
beforeEach(() => {
resetRateLimitGate();
now = 0;
timers.clear();
writes.length = 0;
onSend = undefined;
});
afterEach(() => {
for (const client of clients.splice(0)) client.disconnect();
resetRateLimitGate();
assert.equal(
timers.size,
0,
"subscriptions and gate must release their timers",
);
});
after(() => {
Date.now = originalNow;
globalThis.window = originalWindow;
});
async function flush() {
for (let i = 0; i < 20; i++) await Promise.resolve();
}
async function tickTo(target) {
assert.ok(target >= now);
let fired = 0;
for (;;) {
const next = [...timers]
.filter(([, timer]) => timer.at <= target)
.sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
if (!next) break;
assert.ok(++fired < 1000, "timer loop must make progress");
now = next[1].at;
timers.delete(next[0]);
next[1].fn();
await flush();
}
now = target;
await flush();
}
function deliver(client, frame) {
return client.handleWsMessage(
{ type: "Text", data: JSON.stringify(frame) },
client.connectionGeneration,
);
}
function frames(op) {
return writes.filter((write) => write.frame[0] === op);
}
function session() {
const client = new RelayClient();
client.wsId = 7;
clients.push(client);
return client;
}
function start(client, count) {
return Array.from({ length: count }, (_, i) => {
const filter = {
kinds: [9, 5, 7],
"#h": [`channel-${i}`],
since: 123,
limit: 1000,
};
const controller = new AbortController();
const ready = [];
const promise = client.subscribeLive(
filter,
() => {},
(r) => ready.push(r),
250,
controller.signal,
);
void promise.catch(() => {});
return { filter, controller, ready, promise };
});
}
test("cold setup drains at most one live REQ per 250ms, prioritizes visible channel and preserves every filter", async () => {
const client = session();
const entries = start(client, 296);
await flush();
assert.equal(frames("REQ").length, 1, "startup must not dump 296 REQs");
assert.deepEqual(
entries[295].ready,
[],
"queued setup is not yet a readiness timeout",
);
client.setVisibleChannelId("channel-295");
await tickTo(250);
assert.deepEqual(frames("REQ")[1].frame[2], entries[295].filter);
await tickTo(73750);
assert.equal(frames("REQ").length, 296);
const requests = frames("REQ");
for (let i = 1; i < requests.length; i++)
assert.ok(requests[i].at - requests[i - 1].at >= 250);
assert.deepEqual(
new Set(requests.map((r) => JSON.stringify(r.frame[2]))),
new Set(entries.map((e) => JSON.stringify(e.filter))),
);
for (const { frame } of requests) await deliver(client, ["EOSE", frame[1]]);
await Promise.all(entries.map((e) => e.promise));
});
test("observer control-result subscription takes the next paced slot ahead of cold channels", async () => {
const { relayClient: client } = await import("./relayClient.ts");
const { subscribeToAgentObserverFrames } = await import("./observerRelay.ts");
client.wsId = 7;
clients.push(client);
start(client, 296);
await flush();
const received = [];
const pending = subscribeToAgentObserverFrames("owner", (event) =>
received.push(event),
);
void pending.catch(() => {});
await tickTo(249);
assert.equal(frames("REQ").length, 1, "observer priority must retain pacing");
await tickTo(250);
const request = frames("REQ")[1].frame;
assert.deepEqual(request[2], {
kinds: [24200],
"#p": ["owner"],
limit: 1000,
since: -300,
});
const result = { id: "result", kind: 24200, tags: [["p", "owner"]] };
await deliver(client, ["EVENT", request[1], result]);
await deliver(client, ["EOSE", request[1]]);
const dispose = await pending;
assert.deepEqual(
received,
[result],
"ephemeral control results reach the admitted consumer",
);
await dispose();
await tickTo(266); // Flush the session's existing event batch timer.
});
test("read-state initialization takes the next paced slot ahead of cold channels", async () => {
const { ReadStateManager } = await import(
"../../features/channels/readState/readStateManager.ts"
);
const { KIND_READ_STATE } = await import("../constants/kinds.ts");
const previousDocument = globalThis.document;
const previousStorage = globalThis.localStorage;
const store = new Map();
const events = new EventTarget();
Object.assign(window, {
localStorage: {
getItem: (key) => store.get(key) ?? null,
setItem: (key, value) => store.set(key, value),
removeItem: (key) => store.delete(key),
},
addEventListener: events.addEventListener.bind(events),
removeEventListener: events.removeEventListener.bind(events),
});
globalThis.localStorage = window.localStorage;
globalThis.document = new EventTarget();
const client = session();
const background = start(client, 296);
await flush();
onSend = async ({ frame }) => {
if (frame[0] === "REQ") await deliver(client, ["EOSE", frame[1]]);
};
const pubkey = "a".repeat(64);
const manager = new ReadStateManager(pubkey, client);
let ready = false;
const initialized = manager.initialize().then(() => {
ready = true;
});
try {
await tickTo(249);
assert.equal(
ready,
false,
"initialization must retain its live readiness gate",
);
assert.equal(
frames("REQ").filter(({ frame }) => frame[1].startsWith("live-")).length,
1,
);
await tickTo(250);
assert.equal(
ready,
true,
"unread UI must not wait behind 295 cold channels",
);
await initialized;
const live = frames("REQ").filter(({ frame }) =>
frame[1].startsWith("live-"),
);
assert.equal(live.length, 2);
assert.equal(
live[1].at,
250,
"read-state must retain ordinary request pacing",
);
assert.deepEqual(live[1].frame[2], {
kinds: [KIND_READ_STATE],
authors: [pubkey],
"#t": ["read-state"],
limit: 500,
});
} finally {
manager.destroy();
for (const entry of background) entry.controller.abort();
client.disconnect();
await initialized;
globalThis.document = previousDocument;
globalThis.localStorage = previousStorage;
delete window.localStorage;
delete window.addEventListener;
delete window.removeEventListener;
}
});
test("125 refused live subscriptions cannot stampede beside a publish when cooldown releases", async () => {
const client = session();
const entries = start(client, 125);
await flush();
await tickTo(31250);
const initial = frames("REQ");
assert.equal(initial.length, 125);
for (const { frame } of initial) await deliver(client, ["EOSE", frame[1]]);
await Promise.all(entries.map((e) => e.promise));
for (const { frame } of initial)
await deliver(client, [
"CLOSED",
frame[1],
"rate-limited: quota exceeded; retry in 4s",
]);
const event = { id: "a".repeat(64), kind: 9 };
const published = client.publishEvent(event, "timeout", "send failed");
void published.catch(() => {});
await tickTo(35250);
assert.ok(
frames("REQ").length <= 126,
"only one retry may join Send at gate release",
);
assert.equal(
frames("EVENT").length,
1,
"Send must not await the live backlog",
);
await deliver(client, ["OK", event.id, true, ""]);
assert.equal(await published, event);
await tickTo(66250);
assert.equal(frames("REQ").length, 250);
const retries = frames("REQ").slice(125);
assert.deepEqual(
retries.map((r) => r.frame.slice(1)),
initial.map((r) => r.frame.slice(1)),
);
for (let i = 1; i < retries.length; i++)
assert.ok(retries[i].at - retries[i - 1].at >= 250);
});
test("presence waits beyond its 5s budget behind the gate, then EOSE before IPC settles succeeds", async () => {
const client = session();
const background = start(client, 32);
await flush();
await deliver(client, [
"NOTICE",
"rate-limited: quota exceeded; retry in 6s",
]);
let outcome = "pending";
const presence = openPresenceSubscription(
["a".repeat(64)],
() => {},
client.subscribeLive.bind(client),
);
presence.then(
() => {
outcome = "ready";
},
() => {
outcome = "failed";
},
);
await flush();
await tickTo(5999);
assert.equal(outcome, "pending");
const presenceEntry = [...client.subscriptions].find(
([, sub]) => sub.filter.limit === 0,
);
assert.ok(presenceEntry, "presence remains owned while queued");
assert.equal(frames("REQ").length, 1);
const sent = Promise.withResolvers();
onSend = async ({ frame }) => {
if (frame[0] !== "REQ" || frame[1] !== presenceEntry[0]) return;
await deliver(client, ["EOSE", frame[1]]);
await sent.promise;
};
try {
await tickTo(6000);
assert.equal(
frames("REQ")[1].frame[1],
presenceEntry[0],
"limit:0 outranks the background backlog",
);
await tickTo(12000);
assert.equal(outcome, "pending", "setup still awaits transport completion");
sent.resolve();
await flush();
const dispose = await presence;
assert.equal(
outcome,
"ready",
"queued time must not consume presence readiness",
);
assert.ok(client.subscriptions.has(presenceEntry[0]));
await dispose();
} finally {
sent.resolve();
for (const entry of background) entry.controller.abort();
}
});
test("a later gate extension pauses an active drain without changing filters or counting another retry", async () => {
const client = session();
const entries = start(client, 4);
await flush();
await tickTo(750);
const initial = frames("REQ");
for (const { frame } of initial) await deliver(client, ["EOSE", frame[1]]);
await Promise.all(entries.map((e) => e.promise));
for (const { frame } of initial)
await deliver(client, ["CLOSED", frame[1], "error: temporary failure"]);
await tickTo(1750);
assert.equal(frames("REQ").length, 5);
await tickTo(1800);
await deliver(client, [
"NOTICE",
"rate-limited: quota exceeded; retry in 4s",
]);
await tickTo(3000);
await deliver(client, [
"NOTICE",
"rate-limited: quota exceeded; retry in 4s",
]);
await tickTo(6999);
assert.equal(frames("REQ").length, 5);
for (const { frame } of initial)
assert.equal(client.subscriptions.get(frame[1]).closedRetryAttempt, 1);
await tickTo(7500);
assert.deepEqual(
frames("REQ")
.slice(4)
.map((r) => r.at),
[1750, 7000, 7250, 7500],
);
assert.deepEqual(
frames("REQ")
.slice(4)
.map((r) => r.frame),
initial.map((r) => r.frame),
);
});
for (const stop of ["abort", "terminal CLOSED", "workspace switch"]) {
test(`${stop} retires queued cold setup without a later REQ`, async () => {
const client = session();
const entries = start(client, 2);
await flush();
const [id] = [...client.subscriptions].find(
([, sub]) => sub.filter["#h"][0] === "channel-1",
);
if (stop === "abort") entries[1].controller.abort();
if (stop === "terminal CLOSED")
await deliver(client, ["CLOSED", id, "restricted: denied"]);
if (stop === "workspace switch") {
client.disconnect();
client.wsId = 8;
}
const result = await Promise.allSettled([entries[1].promise]);
assert.equal(
result[0].status,
stop === "terminal CLOSED" ? "fulfilled" : "rejected",
);
assert.ok(!client.subscriptions.has(id));
await tickTo(60000);
assert.equal(frames("REQ").length, 1);
assert.ok(!writes.some((w) => w.socket === 8));
});
}
for (const stop of [
"dispose",
"EOSE",
"EVENT",
"terminal CLOSED",
"workspace switch",
]) {
test(`${stop} cancels a retry already queued in the drain`, async () => {
const client = session();
const entries = start(client, 2);
await flush();
await tickTo(250);
const initial = frames("REQ");
for (const { frame } of initial) await deliver(client, ["EOSE", frame[1]]);
const disposers = await Promise.all(entries.map((e) => e.promise));
for (const { frame } of initial)
await deliver(client, ["CLOSED", frame[1], "error: temporary failure"]);
await tickTo(1250);
assert.equal(frames("REQ").length, 3);
const id = initial[1].frame[1];
if (stop === "dispose") await disposers[1]();
if (stop === "EOSE") await deliver(client, ["EOSE", id]);
if (stop === "EVENT")
await deliver(client, [
"EVENT",
id,
{ id: "recovered", kind: 9, created_at: 123 },
]);
if (stop === "terminal CLOSED")
await deliver(client, ["CLOSED", id, "restricted: denied"]);
if (stop === "workspace switch") {
client.disconnect();
client.wsId = 8;
}
await tickTo(60000);
assert.equal(frames("REQ").length, 3);
assert.ok(!writes.some((w) => w.socket === 8));
});
}
for (const stage of ["setup", "CLOSED retry"]) {
test(`reconnect takes over queued ${stage} without a second drain dispatch`, async () => {
const client = session();
const entries = start(client, 3);
await flush();
if (stage === "CLOSED retry") {
await tickTo(500);
for (const { frame } of frames("REQ"))
await deliver(client, ["EOSE", frame[1]]);
await Promise.all(entries.map((e) => e.promise));
for (const { frame } of frames("REQ"))
await deliver(client, ["CLOSED", frame[1], "error: temporary failure"]);
await tickTo(1500);
assert.equal(frames("REQ").length, 4);
}
const originalIds = [...client.subscriptions.keys()];
client.resetConnection(new Error("socket lost"));
// Only connection establishment is fake; ownership/reset and replay are production.
window.clearTimeout(client.reconnectTimeout);
client.reconnectTimeout = null;
entries[2].controller.abort();
client.wsId = 8;
await client.replayLiveSubscriptions();
client.reconnectWaiters.settle();
await flush();
await tickTo(now + 60000);
const replay = frames("REQ").filter((w) => w.socket === 8);
assert.deepEqual(
replay.map((w) => w.frame[1]),
originalIds.slice(0, 2),
);
assert.deepEqual(
replay.map((w) => w.frame[2]),
entries.slice(0, 2).map((e) => e.filter),
);
await Promise.allSettled(entries.map((e) => e.promise));
});
}
test("finite history and its CLOSED retry bypass a live backlog without consuming queued response budget", async () => {
const client = session();
start(client, 296);
await flush();
const filter = { kinds: [7], "#e": ["message"], limit: 1000 };
const history = client.fetchEvents(filter);
void history.catch(() => {});
await flush();
const initial = frames("REQ").find((w) => w.frame[1].startsWith("history-"));
assert.ok(initial);
assert.equal(initial.at, 0);
await deliver(client, [
"CLOSED",
initial.frame[1],
"rate-limited: quota exceeded; retry in 4s",
]);
await tickTo(4000);
const retry = frames("REQ").filter((w) =>
w.frame[1].startsWith("history-"),
)[1];
assert.ok(retry, "history retry is not queued behind 295 live entries");
assert.equal(retry.at, 4000);
assert.deepEqual(retry.frame[2], filter);
await deliver(client, ["EOSE", retry.frame[1]]);
assert.deepEqual(await history, []);
});

View File

@@ -0,0 +1,496 @@
// Exercise real subscribeLive -> inbound CLOSED -> retry timer -> Tauri send.
// The IPC transport and clock are fake; no native app or external relay is used.
import assert from "node:assert/strict";
import { after, beforeEach, afterEach, test } from "node:test";
const originalNow = Date.now;
const originalWindow = globalThis.window;
let now = 0;
let nextTimerId = 1;
const timers = new Map();
const writes = [];
const clients = [];
let onSend;
globalThis.window = {
setTimeout(fn, ms) {
const id = nextTimerId++;
timers.set(id, { fn, at: now + ms });
return id;
},
clearTimeout(id) {
timers.delete(id);
},
__TAURI_INTERNALS__: {
async invoke(command, args) {
if (command === "plugin:websocket|send") {
writes.push({
socket: args.id,
frame: JSON.parse(args.message.data),
at: now,
});
await onSend?.(writes.at(-1));
return;
}
if (command === "plugin:websocket|disconnect") return;
assert.fail(`unexpected IPC: ${command}`);
},
},
};
Date.now = () => now;
const { RelayClient } = await import("./relayClientSession.ts");
const { resetRateLimitGate, isRateLimited } = await import(
"./relayRateLimitGate.ts"
);
beforeEach(() => {
resetRateLimitGate();
now = 0;
timers.clear();
writes.length = 0;
onSend = undefined;
});
afterEach(() => {
for (const client of clients.splice(0)) client.disconnect();
resetRateLimitGate();
assert.equal(
timers.size,
0,
"subscriptions and gate must release their timers",
);
});
after(() => {
Date.now = originalNow;
globalThis.window = originalWindow;
});
async function flush() {
for (let i = 0; i < 20; i++) await Promise.resolve();
}
async function tickTo(target) {
assert.ok(target >= now);
let fired = 0;
for (;;) {
const next = [...timers]
.filter(([, timer]) => timer.at <= target)
.sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
if (!next) break;
assert.ok(++fired < 1000, "timer loop must make progress");
now = next[1].at;
timers.delete(next[0]);
next[1].fn();
await flush();
}
now = target;
await flush();
}
function deliver(client, frame) {
return client.handleWsMessage(
{ type: "Text", data: JSON.stringify(frame) },
client.connectionGeneration,
);
}
function frames(op) {
return writes.filter((write) => write.frame[0] === op);
}
async function liveChannels(count = 1) {
const client = new RelayClient();
client.wsId = 7; // Already authenticated; subscribe and dispatch remain real.
clients.push(client);
const filters = Array.from({ length: count }, (_, i) => ({
kinds: [9, 5, 7],
"#h": [`channel-${i}`],
since: 123,
limit: 1000,
}));
const ready = filters.map((filter) => client.subscribeLive(filter, () => {}));
for (const pending of ready) void pending.catch(() => {});
await flush();
await tickTo(now + (count - 1) * 250);
const initial = frames("REQ").slice(-count);
assert.equal(initial.length, count);
for (const { frame } of initial) await deliver(client, ["EOSE", frame[1]]);
const disposers = await Promise.all(ready);
return {
client,
filters,
ids: initial.map(({ frame }) => frame[1]),
disposers,
};
}
async function refuse(client, id) {
await deliver(client, [
"CLOSED",
id,
"rate-limited: quota exceeded; retry in 4s",
]);
}
async function extend(client, seconds) {
await deliver(client, [
"NOTICE",
`rate-limited: quota exceeded; retry in ${seconds}s`,
]);
}
test("154 real live retries and a publish respect a repeatedly extended cooldown", async () => {
const { client, ids, filters } = await liveChannels(154);
const base = now;
for (const id of ids) await refuse(client, id);
const event = { id: "a".repeat(64), kind: 9 };
const published = client.publishEvent(event, "timeout", "send failed");
// Cleanup disconnects on an assertion failure; don't leak its rejection.
void published.catch(() => {});
await tickTo(base + 1000);
await extend(client, 10); // Original retries wake at 4s; gate now ends at 11s.
await tickTo(base + 4000);
assert.equal(frames("REQ").length, 154, "no retry through an extended gate");
assert.equal(frames("EVENT").length, 0);
assert.equal(
client.pendingEvents.size,
0,
"publish budget starts after gate",
);
for (const id of ids) {
assert.equal(client.subscriptions.get(id).closedRetryAttempt, 1);
}
await tickTo(base + 5000);
await extend(client, 10); // Extend again while the replacement timers sleep.
await tickTo(base + 11000);
assert.equal(frames("REQ").length, 154);
assert.equal(frames("EVENT").length, 0);
await tickTo(base + 14999);
assert.equal(frames("REQ").length, 154);
await tickTo(base + 15000);
assert.equal(isRateLimited(), false);
assert.equal(
frames("REQ").length,
155,
"only one live subscription retries alongside Send",
);
assert.equal(frames("EVENT").length, 1);
await deliver(client, ["OK", event.id, true, ""]);
assert.equal(await published, event);
await tickTo(base + 15000 + 153 * 250);
assert.equal(
frames("REQ").length,
308,
"each live subscription retries once",
);
assert.deepEqual(
frames("REQ")
.slice(154)
.map(({ frame }) => frame.slice(1)),
ids.map((id, i) => [id, filters[i]]),
"retry preserves coverage/filter and ID",
);
assert.ok(
frames("REQ")
.slice(154)
.every(({ at }, i) => at === base + 15000 + i * 250),
);
for (const id of ids) await deliver(client, ["EOSE", id]);
await tickTo(base + 60000);
assert.equal(frames("REQ").length, 308, "EOSE leaves no extra retry");
});
for (const stop of ["dispose", "EOSE", "terminal CLOSED", "workspace switch"]) {
test(`${stop} cancels a live retry re-armed behind the cooldown`, async () => {
const {
client,
ids: [id],
disposers: [dispose],
} = await liveChannels();
await refuse(client, id);
await tickTo(1000);
await extend(client, 10);
await tickTo(4000);
assert.equal(frames("REQ").length, 1, "retry must still be pending");
if (stop === "dispose") await dispose();
if (stop === "EOSE") await deliver(client, ["EOSE", id]);
if (stop === "terminal CLOSED")
await deliver(client, ["CLOSED", id, "restricted: denied"]);
if (stop === "workspace switch") {
client.disconnect();
resetRateLimitGate();
client.wsId = 8;
}
await tickTo(60000);
assert.equal(frames("REQ").length, 1, "retired retry must not send");
assert.ok(!writes.some(({ socket }) => socket === 8));
});
}
test("a non-quota live retry also respects a later shared cooldown", async () => {
const {
client,
ids: [id],
} = await liveChannels();
await deliver(client, ["CLOSED", id, "error: temporary failure"]);
await tickTo(500);
await extend(client, 4);
await tickTo(1000);
assert.equal(frames("REQ").length, 1);
await tickTo(4500);
assert.equal(frames("REQ").length, 2);
await deliver(client, ["EOSE", id]);
});
async function historyRequest() {
const client = new RelayClient();
client.wsId = 7;
clients.push(client);
const filter = { kinds: [7], "#e": ["target"], since: 123, limit: 10000 };
const history = client.fetchEvents(filter);
void history.catch(() => {});
await flush();
const id = frames("REQ").at(-1).frame[1];
return { client, history, filter, id };
}
function historyId(client) {
return [...client.subscriptions].find(([, sub]) => sub.mode === "history")[0];
}
test("history retry and Send respect extended deadlines without consuming response budget", async () => {
const { client, history, filter, id } = await historyRequest();
const partial = { id: "partial", kind: 7, created_at: 10, tags: [] };
await deliver(client, ["EVENT", id, partial]);
await refuse(client, id);
const retryId = historyId(client);
const subscription = client.subscriptions.get(retryId);
const event = { id: "b".repeat(64), kind: 9 };
const published = client.publishEvent(event, "timeout", "send failed");
void published.catch(() => {});
await tickTo(1000);
await extend(client, 30); // Wait exceeds the normal 25s response timeout.
await tickTo(4000);
assert.equal(
frames("REQ").length,
1,
"history cannot retry through extended gate",
);
await tickTo(5000);
await extend(client, 30); // deadline now 35s, not 31s.
await tickTo(31000);
assert.equal(frames("REQ").length, 1);
assert.equal(client.subscriptions.get(retryId), subscription);
assert.equal(subscription.closedRetryAttempt, 1, "waiting is not an attempt");
assert.equal(frames("EVENT").length, 0);
assert.equal(client.pendingEvents.size, 0);
await tickTo(34999);
assert.equal(frames("REQ").length, 1);
await tickTo(35000);
assert.deepEqual(frames("REQ").at(-1).frame, ["REQ", retryId, filter]);
assert.equal(frames("REQ").at(-1).at, 35000);
assert.equal(frames("EVENT").length, 1);
await tickTo(40000); // Plenty of response budget left after the long wait.
await deliver(client, ["EOSE", retryId]);
assert.deepEqual(await history, [partial]);
await deliver(client, ["OK", event.id, true, ""]);
assert.equal(await published, event);
});
for (const stop of ["workspace switch", "terminal CLOSED", "EOSE"]) {
test(`${stop} cancels history retry re-armed behind the gate`, async () => {
const { client, history, id } = await historyRequest();
await refuse(client, id);
await tickTo(1000);
await extend(client, 10);
await tickTo(4000);
assert.equal(frames("REQ").length, 1);
const retryId = historyId(client);
if (stop === "workspace switch") {
client.disconnect();
resetRateLimitGate();
client.wsId = 8;
await assert.rejects(history, /community switch/);
} else if (stop === "terminal CLOSED") {
await deliver(client, ["CLOSED", retryId, "restricted: denied"]);
await assert.rejects(history, /restricted/);
} else {
await deliver(client, ["EOSE", retryId]);
assert.deepEqual(await history, []);
}
await tickTo(60000);
assert.equal(frames("REQ").length, 1);
assert.ok(!writes.some(({ socket }) => socket === 8));
});
}
test("zero-second history refusal does not hold Send for the missing-hint default", async () => {
const { client, history, id } = await historyRequest();
await deliver(client, [
"CLOSED",
id,
"rate-limited: quota exceeded; retry in 0s",
]);
const event = { id: "c".repeat(64), kind: 9 };
const published = client.publishEvent(event, "timeout", "send failed");
void published.catch(() => {});
await tickTo(0);
assert.equal(isRateLimited(), false);
assert.equal(frames("REQ").length, 2);
assert.equal(frames("EVENT").length, 1);
await deliver(client, ["EOSE", historyId(client)]);
assert.deepEqual(await history, []);
await deliver(client, ["OK", event.id, true, ""]);
assert.equal(await published, event);
});
test("repeated zero-second history refusals exhaust the existing three-retry budget", async () => {
const { client, history, id } = await historyRequest();
onSend = ({ frame }) =>
frame[0] === "REQ"
? deliver(client, [
"CLOSED",
frame[1],
"rate-limited: quota exceeded; retry in 0s",
])
: undefined;
await deliver(client, [
"CLOSED",
id,
"rate-limited: quota exceeded; retry in 0s",
]);
await tickTo(0);
assert.equal(
frames("REQ").length,
4,
"initial request plus three retries, not an infinite loop",
);
await assert.rejects(history, /quota exceeded/);
assert.equal(client.subscriptions.size, 0);
assert.equal(timers.size, 0);
});
test("immediate retry EOSE settles history without leaving an op-timeout", async () => {
const { client, history, id } = await historyRequest();
onSend = ({ frame }) =>
frame[0] === "REQ" ? deliver(client, ["EOSE", frame[1]]) : undefined;
await refuse(client, id);
await tickTo(4000);
assert.deepEqual(await history, []);
assert.equal(
timers.size,
0,
"response can arrive before the send promise settles",
);
});
test("history response timeout starts at admitted retry dispatch and sends CLOSE", async () => {
const { client, history, id } = await historyRequest();
await refuse(client, id);
await tickTo(1000);
await extend(client, 30);
await tickTo(31000);
const retryId = historyId(client);
assert.equal(frames("REQ").at(-1).at, 31000);
await tickTo(55999);
assert.ok(client.subscriptions.has(retryId));
await tickTo(56000);
await assert.rejects(history, /closed the history/);
assert.ok(frames("CLOSE").some(({ frame }) => frame[1] === retryId));
assert.equal(client.subscriptions.size, 0);
});
test("late failed history send cannot cancel the next rotated retry", async () => {
const { client, history, id } = await historyRequest();
let rejectOldSend;
onSend = ({ frame }) =>
frame[0] === "REQ"
? new Promise((_, reject) => {
rejectOldSend = reject;
})
: undefined;
await refuse(client, id);
await tickTo(4000);
const oldId = historyId(client);
await refuse(client, oldId);
const nextId = historyId(client);
const nextSub = client.subscriptions.get(nextId);
const nextTimer = nextSub.timeout;
onSend = undefined;
rejectOldSend(new Error("late old IPC failure"));
await flush();
assert.equal(client.subscriptions.get(nextId), nextSub);
assert.ok(
timers.has(nextTimer),
"late failure must not clear the next retry timer",
);
assert.equal(
client.connectionGeneration,
0,
"retired send must not reset socket",
);
await tickTo(8000);
assert.equal(frames("REQ").length, 3);
assert.equal(frames("REQ").at(-1).frame[1], nextId);
await deliver(client, ["EOSE", nextId]);
assert.deepEqual(await history, []);
});
test("zero-second live refusals retain existing exponential retry backoff", async () => {
const {
client,
ids: [id],
} = await liveChannels();
onSend = ({ frame }) =>
frame[0] === "REQ"
? deliver(client, [
"CLOSED",
frame[1],
"rate-limited: quota exceeded; retry in 0s",
])
: undefined;
await deliver(client, [
"CLOSED",
id,
"rate-limited: quota exceeded; retry in 0s",
]);
await tickTo(999);
assert.equal(frames("REQ").length, 1);
await tickTo(1000);
assert.equal(frames("REQ").length, 2);
await tickTo(3000);
assert.equal(frames("REQ").length, 3);
await tickTo(7000);
assert.equal(frames("REQ").length, 4);
assert.equal(isRateLimited(), false);
await deliver(client, ["EOSE", id]);
});
test("zero-second negative OK remains a publish error, not successful acceptance", async () => {
const { client } = await liveChannels();
const event = { id: "d".repeat(64), kind: 9 };
const published = client.publishEvent(event, "timeout", "send failed");
void published.catch(() => {});
await flush();
await deliver(client, [
"OK",
event.id,
false,
"rate-limited: quota exceeded; retry in 0s",
]);
await assert.rejects(published, /quota exceeded/);
assert.equal(
frames("EVENT").length,
1,
"no automatic uncertain publish replay",
);
assert.equal(isRateLimited(), false);
});
test("zero hint on a history retry preserves another operation's active deadline", async () => {
const { client, history, id } = await historyRequest();
await extend(client, 4);
await tickTo(3000);
await deliver(client, [
"CLOSED",
id,
"rate-limited: quota exceeded; retry in 0s",
]);
await tickTo(3999);
assert.equal(frames("REQ").length, 1);
await tickTo(4000);
assert.equal(frames("REQ").length, 2);
await deliver(client, ["EOSE", historyId(client)]);
assert.deepEqual(await history, []);
});

View File

@@ -0,0 +1,408 @@
// Exercise actual session cancellation at the IPC boundary, including in-flight sends.
// The IPC transport and clock are fake; no native app or external relay is used.
import assert from "node:assert/strict";
import { getEventListeners } from "node:events";
import { after, beforeEach, afterEach, test } from "node:test";
const originalNow = Date.now;
const originalWindow = globalThis.window;
let now = 0;
let nextTimerId = 1;
const timers = new Map();
const writes = [];
const clients = [];
let sendHook = async () => {};
globalThis.window = {
setTimeout(fn, ms) {
const id = nextTimerId++;
timers.set(id, { fn, at: now + ms });
return id;
},
clearTimeout(id) {
timers.delete(id);
},
__TAURI_INTERNALS__: {
async invoke(command, args) {
if (command === "plugin:websocket|send") {
writes.push({
socket: args.id,
frame: JSON.parse(args.message.data),
at: now,
});
return sendHook(args, JSON.parse(args.message.data));
}
if (command === "plugin:websocket|disconnect") return;
assert.fail(`unexpected IPC: ${command}`);
},
},
};
Date.now = () => now;
const { RelayClient } = await import("./relayClientSession.ts");
const { resetRateLimitGate, isRateLimited } = await import(
"./relayRateLimitGate.ts"
);
beforeEach(() => {
resetRateLimitGate();
now = 0;
timers.clear();
writes.length = 0;
sendHook = async () => {};
});
afterEach(() => {
for (const client of clients.splice(0)) client.disconnect();
resetRateLimitGate();
assert.equal(
timers.size,
0,
"subscriptions and gate must release their timers",
);
});
after(() => {
Date.now = originalNow;
globalThis.window = originalWindow;
});
async function flush() {
for (let i = 0; i < 20; i++) await Promise.resolve();
}
async function tickTo(target) {
assert.ok(target >= now);
let fired = 0;
for (;;) {
const next = [...timers]
.filter(([, timer]) => timer.at <= target)
.sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
if (!next) break;
assert.ok(++fired < 1000, "timer loop must make progress");
now = next[1].at;
timers.delete(next[0]);
next[1].fn();
await flush();
}
now = target;
await flush();
}
function deliver(client, frame) {
return client.handleWsMessage(
{ type: "Text", data: JSON.stringify(frame) },
client.connectionGeneration,
);
}
function frames(op) {
return writes.filter((write) => write.frame[0] === op);
}
const filter = { kinds: [9], "#h": ["channel"], since: 123, limit: 1000 };
function setup() {
const client = new RelayClient();
client.wsId = 7;
clients.push(client);
const controller = new AbortController();
let outcome = "pending";
const readiness = [];
const events = [];
const start = () => {
const pending = client.subscribeLive(
filter,
(e) => events.push(e),
(r) => readiness.push(r),
250,
controller.signal,
);
pending.then(
() => {
outcome = "ready";
},
(e) => {
outcome = e.name;
},
);
return pending;
};
return {
client,
controller,
start,
readiness,
events,
outcome: () => outcome,
};
}
for (const stop of ["abort", "disconnect"]) {
test(`${stop} settles setup while connection is pending, without late registration`, async () => {
const h = setup();
const connection = Promise.withResolvers();
h.client.connectPromise = connection.promise;
h.start();
if (stop === "abort") h.controller.abort();
else h.client.disconnect();
await flush();
try {
assert.notEqual(h.outcome(), "pending");
h.client.wsId = 8;
connection.resolve(h.client.connectionGeneration);
await flush();
assert.equal(frames("REQ").length, 0);
assert.equal(h.client.subscriptions.size, 0);
} finally {
connection.resolve(h.client.connectionGeneration);
h.client.connectPromise = null;
await flush();
}
});
}
test("abort during an in-flight REQ suppresses delivery and closes again after send settles", async () => {
const h = setup();
const send = Promise.withResolvers();
sendHook = async (_args, f) => {
if (f[0] === "REQ") await send.promise;
};
h.start();
await flush();
const id = frames("REQ")[0].frame[1];
h.controller.abort();
await flush();
try {
assert.equal(h.client.subscriptions.size, 0);
assert.equal(h.outcome(), "AbortError");
const before = frames("CLOSE").length;
assert.ok(before > 0);
await deliver(h.client, [
"EVENT",
id,
{ id: "event", kind: 9, created_at: 1 },
]);
await deliver(h.client, ["EOSE", id]);
assert.equal(h.events.length, 0);
send.resolve();
await flush();
assert.ok(
frames("CLOSE").length > before,
"post-flight close preserves wire order",
);
assert.equal(h.client.wsId, 7);
assert.deepEqual(h.readiness, []);
} finally {
send.resolve();
await flush();
}
});
for (const stage of ["first send", "reconnect wait", "retry send"]) {
test(`cancellation at ${stage} cannot reset or resurrect the replacement socket`, async () => {
const h = setup();
const first = Promise.withResolvers();
const retry = Promise.withResolvers();
let attempts = 0;
sendHook = async (_args, f) => {
if (f[0] !== "REQ") return;
await (++attempts === 1 ? first.promise : retry.promise);
};
h.start();
await flush();
try {
if (stage === "first send") {
h.controller.abort();
first.reject(new Error("late IPC error"));
await flush();
assert.equal(h.client.wsId, 7);
assert.equal(h.client.reconnectTimeout, null);
} else {
first.reject(new Error("socket lost"));
await flush();
assert.notEqual(h.client.reconnectTimeout, null);
if (stage === "reconnect wait") h.controller.abort();
// Resolve the existing reconnect waiter: only transport establishment is fake.
window.clearTimeout(h.client.reconnectTimeout);
h.client.reconnectTimeout = null;
h.client.wsId = 8;
h.client.reconnectWaiters.settle();
await flush();
if (stage === "retry send") {
assert.equal(attempts, 2);
h.controller.abort();
retry.reject(new Error("late retry IPC error"));
await flush();
} else assert.equal(attempts, 1);
assert.equal(h.client.wsId, 8);
}
assert.equal(h.client.subscriptions.size, 0);
assert.equal(h.outcome(), "AbortError");
} finally {
first.resolve();
retry.resolve();
await flush();
}
});
}
for (const finish of ["EOSE", "timeout", "terminal CLOSED", "disconnect"]) {
test(`${finish} settles readiness once and cleans up cancellation`, async () => {
const h = setup();
h.start();
await flush();
const id = frames("REQ")[0].frame[1];
if (finish === "EOSE") {
await deliver(h.client, ["EOSE", id]);
await deliver(h.client, ["EOSE", id]);
}
if (finish === "timeout") await tickTo(250);
if (finish === "terminal CLOSED")
await deliver(h.client, ["CLOSED", id, "restricted: denied"]);
if (finish === "disconnect") h.client.disconnect();
await flush();
assert.notEqual(h.outcome(), "pending");
assert.ok(h.readiness.length <= 1);
assert.equal(timers.size, 0);
h.controller.abort();
await flush();
assert.equal(h.client.subscriptions.size, 0);
});
}
for (const stop of ["abort", "disconnect"]) {
test(`${stop} cancels an actual CLOSED retry while its send is in flight`, async () => {
const h = setup();
const started = h.start();
await flush();
const id = frames("REQ")[0].frame[1];
await deliver(h.client, ["EOSE", id]);
await started;
await deliver(h.client, ["CLOSED", id, "error: temporary failure"]);
const retry = Promise.withResolvers();
sendHook = async (_args, f) => {
if (f[0] === "REQ") await retry.promise;
};
await tickTo(1000);
assert.equal(frames("REQ").length, 2);
if (stop === "abort") h.controller.abort();
else {
h.client.disconnect();
h.client.wsId = 8;
}
retry.reject(new Error("late CLOSED retry failure"));
await flush();
await tickTo(60000);
assert.equal(frames("REQ").length, 2);
assert.equal(h.client.wsId, stop === "abort" ? 7 : 8);
assert.equal(h.client.subscriptions.size, 0);
assert.equal(timers.size, 0);
});
}
for (const stop of ["abort", "dispose", "terminal CLOSED", "disconnect"]) {
test(`${stop} releases caller and session abort listeners after EOSE`, async () => {
const h = setup();
const sessionSignal = h.client.liveSessionAbort.signal;
const started = h.start();
await flush();
const id = frames("REQ")[0].frame[1];
await deliver(h.client, ["EOSE", id]);
const dispose = await started;
assert.equal(
getEventListeners(h.controller.signal, "abort").length,
1,
"live cancellation remains armed after readiness",
);
if (stop === "abort") h.controller.abort();
if (stop === "dispose") await dispose();
if (stop === "terminal CLOSED")
await deliver(h.client, ["CLOSED", id, "restricted: denied"]);
if (stop === "disconnect") h.client.disconnect();
await flush();
assert.equal(getEventListeners(h.controller.signal, "abort").length, 0);
assert.equal(getEventListeners(sessionSignal, "abort").length, 0);
assert.equal(timers.size, 0);
});
}
test("workspace switch during in-flight setup cannot close or reset the new socket", async () => {
const h = setup();
const send = Promise.withResolvers();
sendHook = async (_args, f) => {
if (f[0] === "REQ") await send.promise;
};
h.start();
await flush();
h.client.disconnect();
h.client.wsId = 8;
send.reject(new Error("old workspace send failed"));
await flush();
assert.equal(h.outcome(), "AbortError");
assert.equal(h.client.wsId, 8);
assert.ok(writes.every((w) => w.socket === 7));
assert.equal(h.client.subscriptions.size, 0);
assert.equal(timers.size, 0);
});
test("late old-socket failure preserves a still-owned live entry restored by replay", async () => {
const h = setup();
const first = Promise.withResolvers();
let requests = 0;
sendHook = async (_args, f) => {
if (f[0] === "REQ" && ++requests === 1) await first.promise;
};
h.start();
await flush();
const id = frames("REQ")[0].frame[1];
const entry = h.client.subscriptions.get(id);
h.client.resetConnection(new Error("socket closed during setup"));
window.clearTimeout(h.client.reconnectTimeout);
h.client.reconnectTimeout = null;
h.client.wsId = 8;
await h.client.replayLiveSubscriptions();
assert.equal(frames("REQ").length, 2);
assert.equal(frames("REQ")[1].frame[1], id);
first.reject(new Error("late old-socket IPC failure"));
await flush();
assert.equal(h.outcome(), "ready");
assert.equal(h.client.subscriptions.get(id), entry);
assert.equal(frames("CLOSE").length, 0);
assert.equal(h.client.wsId, 8);
assert.equal(frames("REQ").length, 2, "replay, not fresh setup");
});
test("late retry-send failure preserves an entry handed to another reconnect", async () => {
const h = setup();
const retry = Promise.withResolvers();
let requests = 0;
sendHook = async (_args, f) => {
if (f[0] !== "REQ") return;
if (++requests === 1) throw new Error("first socket failed");
if (requests === 2) await retry.promise;
};
h.start();
await flush();
window.clearTimeout(h.client.reconnectTimeout);
h.client.reconnectTimeout = null;
h.client.wsId = 8;
h.client.reconnectWaiters.settle();
await flush();
assert.equal(requests, 2);
const id = frames("REQ")[0].frame[1];
const entry = h.client.subscriptions.get(id);
h.client.resetConnection(new Error("retry socket closed"));
window.clearTimeout(h.client.reconnectTimeout);
h.client.reconnectTimeout = null;
h.client.wsId = 9;
await h.client.replayLiveSubscriptions();
retry.reject(new Error("late retry-socket failure"));
await flush();
assert.equal(h.outcome(), "ready");
assert.equal(h.client.subscriptions.get(id), entry);
assert.equal(frames("CLOSE").length, 0);
assert.equal(h.client.wsId, 9);
});
test("a failed reconnect attempt still rejects setup rather than claiming a successful handoff", async () => {
const h = setup();
sendHook = async (_args, f) => {
if (f[0] === "REQ") throw new Error("socket failed");
};
h.start();
await flush();
window.clearTimeout(h.client.reconnectTimeout);
h.client.reconnectTimeout = null;
h.client.reconnectWaiters.settle(new Error("authentication failed"));
await flush();
assert.equal(h.outcome(), "Error");
assert.equal(h.client.subscriptions.size, 0);
assert.equal(frames("REQ").length, 1);
assert.equal(timers.size, 0);
});

View File

@@ -37,6 +37,7 @@ import {
} from "@/shared/api/relayClosedRecovery";
import { getChannelReconnectRepairEvents } from "@/shared/api/channelReconnectRepair";
import { replayLiveSubscriptions } from "@/shared/api/relayReconnectReplay";
import { RelayLiveReqDrain } from "./relayLiveReqDrain";
import { publishSessionEvent } from "@/shared/api/relayEventPublisher";
import { activateRateLimitIfSignalled } from "@/shared/api/relayRateLimitGate";
import {
@@ -84,6 +85,7 @@ export class RelayClient {
private keepAliveRequested = false;
private authRequest: RelayAuthRequest | null = null;
private subscriptions = new Map<string, RelaySubscription>();
private liveReqDrain = new RelayLiveReqDrain();
private pendingEvents = new Map<string, PendingEvent>();
private eventBuffer: SubscriptionEventBufferItem[] = [];
private flushTimeout: number | null = null;
@@ -93,6 +95,7 @@ export class RelayClient {
private onMessageChannel: Channel<unknown> | null = null;
private connectionGeneration = 0;
private sessionEpoch = 0;
private liveSessionAbort = new AbortController();
private stabilityTimer: number | null = null;
private visibleChannelId: string | null = null;
private authOkTracker = new AuthOkTracker();
@@ -123,7 +126,10 @@ export class RelayClient {
}
this.stallWatchdog.stop();
this.sessionEpoch++;
this.liveSessionAbort.abort();
this.liveSessionAbort = new AbortController();
this.connectionGeneration++;
this.liveReqDrain.reset();
this.keepAliveRequested = false;
this.relayUrl = null;
this.hasConnectedOnce = false;
@@ -153,6 +159,7 @@ export class RelayClient {
sub.reject(error);
} else {
clearClosedRetry(sub);
sub.onRemoved?.();
}
this.subscriptions.delete(subId);
}
@@ -409,9 +416,25 @@ export class RelayClient {
onEvent: (event: RelayEvent) => void,
onReady?: (readiness: LiveSubscriptionReadiness) => void,
readinessTimeoutMs?: number,
signal?: AbortSignal,
) {
return this.subscribe(filter, onEvent, onReady, readinessTimeoutMs);
return this.subscribe(filter, onEvent, onReady, readinessTimeoutMs, signal);
}
/** Prioritize an interactive live consumer without changing its replay filter or pacing. */
async subscribeInteractive(
filter: RelaySubscriptionFilter,
onEvent: (event: RelayEvent) => void,
) {
return this.subscribe(
filter,
onEvent,
undefined,
undefined,
undefined,
"interactive",
);
}
async preconnect() {
// Explicit re-engagement (reconnect card / community switch): clears the
// terminal latch and AUTH rejection streak, and bypasses backoff once.
@@ -589,52 +612,88 @@ export class RelayClient {
onEvent: (event: RelayEvent) => void,
onReady?: (readiness: LiveSubscriptionReadiness) => void,
readinessTimeoutMs = 250,
signal?: AbortSignal,
priority?: "interactive",
) {
await this.ensureConnected();
const epoch = this.sessionEpoch;
const sessionSignal = this.liveSessionAbort.signal;
signal?.throwIfAborted();
const subId = `live-${crypto.randomUUID()}`;
let resolveReady = (_readiness: LiveSubscriptionReadiness) => {};
const ready = new Promise<void>((resolve) => {
resolveReady = (readiness) => {
window.clearTimeout(fallbackTimeout);
onReady?.(readiness);
resolve();
};
});
const fallbackTimeout = window.setTimeout(
() => resolveReady("timeout"),
readinessTimeoutMs,
);
this.subscriptions.set(subId, {
let fallbackTimeout: number | undefined;
let settleReady = () => {};
const onRemoved = () => {
signal?.removeEventListener("abort", abort);
sessionSignal.removeEventListener("abort", abort);
window.clearTimeout(fallbackTimeout);
settleReady();
};
const subscription: Extract<RelaySubscription, { mode: "live" }> = {
mode: "live",
filter,
priority,
onEvent,
resolveReady,
});
try {
await this.sendRawWithReconnectRetry(
["REQ", subId, filter],
"Failed to restore relay subscription.",
);
} catch (error) {
window.clearTimeout(fallbackTimeout);
onRemoved,
};
const dispose = async () => {
if (this.subscriptions.get(subId) !== subscription) return;
this.subscriptions.delete(subId);
this.liveReqDrain.cancel(subId);
clearClosedRetry(subscription);
onRemoved();
// Workspace teardown closes its socket; never send on its replacement.
if (epoch === this.sessionEpoch) await this.closeSubscription(subId);
};
let rejectCancelled = (_error: Error) => {};
const cancelled = new Promise<never>((_resolve, reject) => {
rejectCancelled = reject;
});
const abort = () => {
rejectCancelled(
new DOMException("Live subscription cancelled.", "AbortError"),
);
void dispose().catch(() => {});
onRemoved();
};
signal?.addEventListener("abort", abort, { once: true });
sessionSignal.addEventListener("abort", abort, { once: true });
try {
await Promise.race([this.ensureConnected(), cancelled]);
signal?.throwIfAborted();
sessionSignal.throwIfAborted();
const ready = new Promise<void>((resolve) => {
settleReady = resolve;
});
let readySettled = false;
subscription.resolveReady = (readiness) => {
if (readySettled) return;
readySettled = true;
window.clearTimeout(fallbackTimeout);
onReady?.(readiness);
settleReady();
};
this.subscriptions.set(subId, subscription);
await Promise.race([
this.sendRawWithReconnectRetry(
["REQ", subId, filter],
"Failed to restore relay subscription.",
() => {
if (readySettled) return;
window.clearTimeout(fallbackTimeout);
fallbackTimeout = window.setTimeout(
() => subscription.resolveReady?.("timeout"),
readinessTimeoutMs,
);
},
),
cancelled,
]);
await Promise.race([ready, cancelled]);
return dispose;
} catch (error) {
await dispose().catch(() => {});
onRemoved();
throw error;
}
await ready;
return async () => {
const active = this.subscriptions.get(subId);
if (active?.mode !== "live") {
return;
}
this.subscriptions.delete(subId);
clearClosedRetry(active);
await this.closeSubscription(subId);
};
}
private async sendRaw(payload: unknown[]) {
@@ -678,18 +737,83 @@ export class RelayClient {
private async sendRawWithReconnectRetry(
payload: unknown[],
fallbackMessage: string,
onDispatch?: () => void,
) {
const epoch = this.sessionEpoch;
const subId = payload[1] as string;
const subscription = this.subscriptions.get(subId);
const isOwned = () =>
subscription !== undefined &&
epoch === this.sessionEpoch &&
this.subscriptions.get(subId) === subscription;
const checkOwned = () => {
if (!isOwned())
throw new DOMException("Relay subscription retired.", "AbortError");
};
let generation = this.connectionGeneration;
const send = async () => {
checkOwned();
generation = this.connectionGeneration;
try {
onDispatch?.();
await this.sendRawForGeneration(payload, generation);
} finally {
// A dispatched REQ cannot be unsent. Converge to CLOSE on that socket,
// without touching a replacement workspace or connection.
if (
!isOwned() &&
epoch === this.sessionEpoch &&
generation === this.connectionGeneration
) {
await this.closeSubscription(subId).catch(() => {});
}
}
};
const dispatch = () => {
const queuedGeneration = this.connectionGeneration;
return subscription?.mode === "live"
? this.liveReqDrain.run(
subId,
() => isOwned() && queuedGeneration === this.connectionGeneration,
() =>
subscription.priority === "interactive" ||
(this.visibleChannelId !== null &&
subscription.filter["#h"]?.includes(this.visibleChannelId) ===
true)
? 0
: subscription.filter.limit === 0
? 1
: 2,
send,
)
: send();
};
try {
await this.sendRaw(payload);
await dispatch();
} catch (error) {
checkOwned(); // Cancellation is not a socket failure and must not reconnect.
if (generation !== this.connectionGeneration) {
// Live entries survive reset and belong to the new connection's replay.
// A late old-socket failure must not tear down that retained ownership.
if (subscription?.mode === "live") return;
throw error;
}
const normalizedError = this.recoverFromSocketFailure(
error,
fallbackMessage,
);
let retryGeneration: number | null = null;
try {
await this.ensureConnected();
await this.sendRaw(payload);
checkOwned();
retryGeneration = this.connectionGeneration;
await dispatch();
} catch (retryError) {
checkOwned();
if (generation !== this.connectionGeneration) {
if (retryGeneration !== null && subscription?.mode === "live") return;
throw retryError;
}
throw this.recoverFromSocketFailure(
retryError,
normalizedError.message,
@@ -800,6 +924,7 @@ export class RelayClient {
),
closeSubscription: (subId) => this.closeSubscription(subId),
});
if (!this.subscriptions.has(rest[0])) this.liveReqDrain.cancel(rest[0]);
return;
}
@@ -839,6 +964,7 @@ export class RelayClient {
}
if (!prepareSubscriptionEvent(subscription, event)) return;
this.liveReqDrain.cancel(subId);
this.eventBuffer.push({ subId, event, generation });
this.flushTimeout ??= window.setTimeout(
() => this.flushEventBuffer(),
@@ -855,6 +981,7 @@ export class RelayClient {
}
private handleEose(subId: string, generation: number) {
this.liveReqDrain.cancel(subId);
this.flushEventBuffer(); // Deliver preceding EVENT frames before EOSE.
handleSubscriptionEose({
subscriptions: this.subscriptions,
@@ -991,6 +1118,7 @@ export class RelayClient {
this.onMessageChannel = null;
this.stallWatchdog.stop();
this.connectionGeneration++;
this.liveReqDrain.reset();
if (this.stabilityTimer !== null) {
window.clearTimeout(this.stabilityTimer);
this.stabilityTimer = null;

View File

@@ -73,8 +73,12 @@ export type LiveSubscriptionReadiness = "eose" | "closed" | "timeout";
type LiveSubscription = {
mode: "live";
filter: RelaySubscriptionFilter;
/** Client-side admission only; interactive consumers still obey cooldown/pacing. */
priority?: "interactive";
onEvent: (event: RelayEvent) => void;
resolveReady?: (readiness: LiveSubscriptionReadiness) => void;
/** Release readiness/cancellation listeners when this entry is retired. */
onRemoved?: () => void;
lastSeenCreatedAt?: number;
/**
* Lower bound of a reconnect backfill window that has not yet completed.

View File

@@ -56,39 +56,45 @@ export function handleRelayClosed({
const attempt = subscription.closedRetryAttempt ?? 0;
if (attempt < 3) {
subscription.closedRetryAttempt = attempt + 1;
// Clear the existing op-timeout so it doesn't fire while waiting for
// the rate-limit window. The setTimeout delay covers this interval.
// The same cancellable timeout owns admission waiting and, only once
// dispatched, the response budget. A later hint can extend the gate.
window.clearTimeout(subscription.timeout);
const hintMs = (hintSeconds ?? 10) * 1_000;
const delayMs = Math.max(rateLimitRemainingMs() || hintMs, hintMs);
// Re-register under a new id so the old subId can be evicted cleanly.
// Accumulated events are preserved on the subscription object.
const newSubId = `history-${crypto.randomUUID()}`;
subscriptions.delete(subId);
subscriptions.set(newSubId, subscription);
// Use the rate-limit delay as the new timeout budget so the
// subscription is not left open indefinitely while waiting.
subscription.timeout = window.setTimeout(() => {
if (!subscriptions.has(newSubId)) return; // cancelled while waiting
void sendReq(newSubId, subscription.filter).catch(() => {
subscriptions.delete(newSubId);
subscription.reject(
new Error(message || "Relay closed the history subscription."),
const isOwned = () => subscriptions.get(newSubId) === subscription;
const retryWhenAdmitted = () => {
if (!isOwned()) return;
const remainingMs = rateLimitRemainingMs();
if (remainingMs > 0) {
subscription.timeout = window.setTimeout(
retryWhenAdmitted,
remainingMs,
);
});
// Set a new op-timeout for the retry REQ so the subscription
// cannot hang indefinitely if the relay stops responding.
return;
}
// Arm before transport: EOSE/CLOSED may arrive before send settles.
subscription.timeout = window.setTimeout(() => {
if (!isOwned()) return;
subscriptions.delete(newSubId);
// History promise is already being rejected below; swallow any
// IPC/socket error from the CLOSE send so it does not surface as
// an unhandled rejection on a path that has no live error handler.
closeSubscription?.(newSubId)?.catch(() => {});
subscription.reject(
new Error("Relay closed the history subscription."),
);
}, subscription.timeoutMs);
}, delayMs);
void sendReq(newSubId, subscription.filter).catch(() => {
if (!isOwned()) return;
window.clearTimeout(subscription.timeout);
subscriptions.delete(newSubId);
subscription.reject(
new Error(message || "Relay closed the history subscription."),
);
});
};
subscription.timeout = window.setTimeout(
retryWhenAdmitted,
rateLimitRemainingMs(),
);
return;
}
}
@@ -132,6 +138,8 @@ function recoverLiveSubscriptionFromClosed({
// Auth/access/filter failure — permanently remove the subscription so it
// doesn't silently loop.
subscriptions.delete(subId);
clearClosedRetry(subscription);
subscription.onRemoved?.();
return;
}
@@ -158,9 +166,20 @@ function recoverLiveSubscriptionFromClosed({
}
subscription.closedRetryAttempt = attempt + 1;
subscription.closedRetryTimeout = window.setTimeout(() => {
const retryWhenAdmitted = () => {
subscription.closedRetryTimeout = undefined;
if (subscriptions.get(subId) !== subscription) return;
// A later quota hint can extend the shared gate after this retry was
// scheduled. Keep the existing cancellable timer owner while waiting;
// postponement is not another failed attempt and must not grow backoff.
const remainingMs = rateLimitRemainingMs();
if (remainingMs > 0) {
subscription.closedRetryTimeout = window.setTimeout(
retryWhenAdmitted,
remainingMs,
);
return;
}
void sendReq(subId, subscription.filter).catch((error) => {
if (subscriptions.get(subId) !== subscription) return;
console.error("Failed to restore closed relay subscription", error);
@@ -172,7 +191,11 @@ function recoverLiveSubscriptionFromClosed({
sendReq,
});
});
}, delayMs);
};
subscription.closedRetryTimeout = window.setTimeout(
retryWhenAdmitted,
delayMs,
);
}
export function prepareSubscriptionEvent(

View File

@@ -0,0 +1,82 @@
import { rateLimitRemainingMs } from "./relayRateLimitGate";
// Deliberately below the relay's default total WS allowance: other request
// families and publications share that budget. This is pacing, not a quota guarantee.
const LIVE_REQ_INTERVAL_MS = 250;
type PendingReq = {
current: () => boolean;
priority: () => number;
send: () => Promise<void>;
resolve: () => void;
reject: (error: unknown) => void;
promise: Promise<void>;
};
/** Session-owned cold/live-retry drain; entries are bounded by owned subscriptions. */
export class RelayLiveReqDrain {
private pending = new Map<string, PendingReq>();
private timer: number | undefined;
private nextAt = 0;
run(
id: string,
current: () => boolean,
priority: () => number,
send: () => Promise<void>,
): Promise<void> {
const existing = this.pending.get(id);
if (existing) return existing.promise;
let resolve = () => {};
let reject = (_error: unknown) => {};
const promise = new Promise<void>((ok, fail) => {
resolve = ok;
reject = fail;
});
this.pending.set(id, { current, priority, send, promise, resolve, reject });
this.drain();
return promise;
}
cancel(id: string) {
const entry = this.pending.get(id);
this.pending.delete(id);
entry?.resolve();
if (this.pending.size === 0) {
window.clearTimeout(this.timer);
this.timer = undefined;
}
}
reset() {
for (const id of this.pending.keys()) this.cancel(id);
this.nextAt = 0;
}
private drain = () => {
window.clearTimeout(this.timer);
this.timer = undefined;
for (const [id, entry] of this.pending) {
if (!entry.current()) this.cancel(id);
}
if (this.pending.size === 0) return;
const delay = Math.max(this.nextAt - Date.now(), rateLimitRemainingMs());
if (delay > 0) {
this.timer = window.setTimeout(this.drain, delay);
return;
}
const entries = [...this.pending];
const selected = entries.sort(
(a, b) => a[1].priority() - b[1].priority(),
)[0];
if (!selected) return;
const [id, entry] = selected;
this.pending.delete(id);
this.nextAt = Date.now() + LIVE_REQ_INTERVAL_MS;
// send checks ownership again immediately before IPC. Do not await its
// outcome here: publications and independent subscriptions must keep moving.
void entry.send().then(entry.resolve, entry.reject);
if (this.pending.size > 0) {
this.timer = window.setTimeout(this.drain, LIVE_REQ_INTERVAL_MS);
}
};
}

View File

@@ -132,13 +132,34 @@ test("null hint uses 10s default", () => {
assert.equal(isRateLimited(), false);
});
test("zero hint uses 10s default (0s gate would be swallowed)", () => {
test("explicit zero hint adds no cooldown or timer", async () => {
reset(0);
assert.equal(
parseRateLimitHint("rate-limited: quota exceeded; retry in 0s"),
0,
);
activateRateLimit(0);
tickTo(9_999);
assert.equal(isRateLimited(), true);
tickTo(10_001);
assert.equal(isRateLimited(), false);
assert.equal(pendingTimers.size, 0);
await waitForRateLimit();
});
test("explicit zero neither shortens nor extends another active deadline", async () => {
reset(0);
activateRateLimit(4);
let settled = false;
const waiting = waitForRateLimit().then(() => {
settled = true;
});
setFakeNow(3000);
activateRateLimit(0);
assert.equal(rateLimitRemainingMs(), 1000);
assert.equal(pendingTimers.size, 1);
await Promise.resolve();
assert.equal(settled, false);
tickTo(4000);
await waiting;
assert.equal(settled, true);
});
test("negative hint uses 10s default", () => {

View File

@@ -44,13 +44,14 @@ export function parseRateLimitHint(msg: string): number | null {
*
* If the gate is already active, the expiry is pushed forward to the maximum of
* the existing expiry and the new hint — overlapping hints never shrink the
* window. Non-positive or absent hints use the 10-second default; a 0s gate
* would resolve immediately and swallow the signal.
* window. An explicit zero adds no hold; it is not a missing hint and does not
* clear an existing deadline. Negative or absent hints use the 10-second default.
*
* Note: buzz-acp uses a 5s no-hint default; desktop deliberately uses 10s here
* for a wider back-off window on degraded connections.
*/
export function activateRateLimit(retryInSeconds: number | null): void {
if (retryInSeconds === 0) return;
const durationMs =
(retryInSeconds != null && retryInSeconds > 0
? Math.min(retryInSeconds, MAX_HINT_SECONDS)

View File

@@ -278,22 +278,20 @@ export async function replayLiveSubscriptions({
};
});
// Sort the visible channel's subscriptions first so the user sees their
// active channel recover before others on degraded networks.
if (visibleChannelId !== null) {
replayRequests.sort((a, b) => {
const aVis =
(a.subscription.filter["#h"] as string[] | undefined)?.includes(
visibleChannelId,
) ?? false;
const bVis =
(b.subscription.filter["#h"] as string[] | undefined)?.includes(
visibleChannelId,
) ?? false;
if (aVis === bVis) return 0;
return aVis ? -1 : 1;
});
}
// Visible timeline and interactive consumers (including off-screen huddle
// speech) recover before cold work. Stable sort preserves registration order
// within each tier, including ties between visible and interactive owners.
const isForeground = (
subscription: Extract<RelaySubscription, { mode: "live" }>,
) =>
subscription.priority === "interactive" ||
(visibleChannelId !== null &&
(subscription.filter["#h"]?.includes(visibleChannelId) ?? false));
replayRequests.sort(
(a, b) =>
Number(isForeground(b.subscription)) -
Number(isForeground(a.subscription)),
);
// Send live REQs in capped batches with inter-batch delays to avoid
// triggering per-pubkey admission control on degraded/recovering connections.