Skip to content

Commit a024b83

Browse files
wesbillmanPinky
andauthored
fix(desktop): refresh channels after access-revoked closure (#7784)
Pinky is updating this PR on Wes’s behalf. ## Summary - Treat exact `CLOSED restricted: channel access revoked` on a known channel-scoped live subscription as a hint to refresh authoritative channel state. - Reuse `useLiveChannelUpdates`’ existing debounced, idle-aware query refresh. Keep terminal retirement, explicit membership denial, and polling unchanged. - Cover archived, unchanged, removed, and failed authoritative results; burst coalescing; irrelevant/stale frames; exact-reason rejection; and unmount cleanup with seven production-path regression cases. The hint does **not** establish archive or membership state. This closes a missed-update recovery gap without changing the relay or blindly retrying subscriptions. Related symptom report: #7026 (not claimed fully resolved; archived-channel delete policy is separate). Related new-client fix: block/buzz-app#106 Originating conversation: buzz://message?channel=cb38cd5a-c920-40a1-b770-e9b89c289476&id=d22c1eed473016cf1f73c889a4cc88f1491ee092cfe3794575f8fea8003aa19e ## Review follow-up and main integration At **`51ec7482ad1e600bd02ea6b9ed265db8a70e7266`**, based on main **`c213d90d5c450e2e579505da4a4145f528ecbcf2`**: - Addressed Jude’s P2: a known channel-scoped live subscription closed with `restricted: not a channel member` stays terminal but must not refresh channels. - Mutation verification: replacing the exact reason predicate with `startsWith("restricted:")` produced **6,588 passes / 1 expected failure**, specifically the new no-refresh assertion (`actual: 1`, `expected: 0`). Restored the exact predicate; the final full suite passed **6,589/6,589**. - Resolved both conflicts with #7790, retaining main’s paced/cancellable subscriptions and this PR’s hint after terminal cleanup/drain cancellation. The fixture advances the production drain with a consistent virtual clock; it does not stub or bypass admission. - Integration crossed the session file’s 1,200-line ceiling (1,207). Extracted only this PR’s exact predicate/listener set into `relayChannelAccessRevocations.ts`, with unchanged session ownership and cleanup. No limit change, new timer, retry policy, or unrelated refactor. Final feature diff: 46 production additions across three files, plus the 333-line regression fixture. - Independent read-only review of the integration and final extraction found no blocking findings. This is not GitHub approval. ## Validation At exact pushed head **`51ec7482ad1e600bd02ea6b9ed265db8a70e7266`**: - Mandatory hooks passed without bypasses: desktop lint/policy checks, TypeScript, repository file-size gate, branch-skew check, and full desktop suite **6,589/6,589**, zero failed/cancelled/skipped. - Working tree clean after push. DCO passed on GitHub. - Fresh hosted CI and Desktop Release Candidate checks are running; prior-head green checks are not evidence for this head. Re-review requested from `jedwards27`; the changes-requested review and required approval remain for the reviewer to update. ## Evidence boundaries - Native IPC is stubbed; the fixture exercises actual subscription creation, raw CLOSED dispatch, mounted hook, authoritative query refresh, and IPC result conversion. It does not exercise native discovery or rendered sidebar behavior. Existing in-flight refresh retention remains source/helper-test coverage rather than a new integrated case. - No native app launch, live archive mutation, or release certification. This fixes a demonstrated recovery mechanism, not proof of the exact original incident ordering. - The initial broad local `just ci` attempt hit a 300-second timeout compiling `buzz-voice`; full local `just ci` remains incomplete. Current delivery uses mandatory path-scoped hooks and fresh hosted CI; no unrelated native/mobile lane was bypassed or claimed rerun locally. --------- Signed-off-by: Pinky <5f5ab050ec58ae208332edd544ebf705221e24c1b86d82a6ca07038a7a8f6ac9@buzz.block.builderlab.xyz> Co-authored-by: Pinky <5f5ab050ec58ae208332edd544ebf705221e24c1b86d82a6ca07038a7a8f6ac9@buzz.block.builderlab.xyz>
1 parent c213d90 commit a024b83

4 files changed

Lines changed: 379 additions & 0 deletions

File tree

Lines changed: 333 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,333 @@
1+
import assert from "node:assert/strict";
2+
import { after, before, test } from "node:test";
3+
import { JSDOM } from "jsdom";
4+
5+
const dom = new JSDOM("<!doctype html><html><body></body></html>", {
6+
url: "http://localhost",
7+
});
8+
before(() => {
9+
Object.assign(globalThis, {
10+
document: dom.window.document,
11+
HTMLElement: dom.window.HTMLElement,
12+
IS_REACT_ACT_ENVIRONMENT: true,
13+
window: dom.window,
14+
localStorage: dom.window.localStorage,
15+
});
16+
});
17+
after(() => dom.window.close());
18+
19+
const rawChannels = ["a", "b"].map((id) => ({
20+
id,
21+
name: id,
22+
channel_type: "stream",
23+
visibility: "private",
24+
description: "",
25+
member_count: 1,
26+
member_pubkeys: ["viewer"],
27+
archived_at: null,
28+
last_message_at: null,
29+
participants: [],
30+
participant_pubkeys: [],
31+
is_member: true,
32+
}));
33+
const revoked = "restricted: channel access revoked";
34+
35+
async function mount() {
36+
const { act, cleanup, renderHook } = await import("@testing-library/react");
37+
const React = await import("react");
38+
const { QueryClient, QueryClientProvider, useQuery } = await import(
39+
"@tanstack/react-query"
40+
);
41+
const { relayClient } = await import("@/shared/api/relayClient");
42+
const { fromRawChannel } = await import("@/shared/api/tauriChannels");
43+
const { channelsQueryKey, refreshChannelsQuery } = await import("./hooks.ts");
44+
const { useLiveChannelUpdates } = await import("./useLiveChannelUpdates.ts");
45+
const original = {
46+
setTimeout: window.setTimeout,
47+
clearTimeout: window.clearTimeout,
48+
internals: window.__TAURI_INTERNALS__,
49+
now: Date.now,
50+
};
51+
const timers = new Map();
52+
let now = Date.now();
53+
Date.now = () => now;
54+
let nextTimer = 0;
55+
window.setTimeout = (fn, ms) => {
56+
timers.set(++nextTimer, { fn, at: now + ms });
57+
return nextTimer;
58+
};
59+
window.clearTimeout = (id) => timers.delete(id);
60+
const sent = [];
61+
const reads = [];
62+
window.__TAURI_INTERNALS__ = {
63+
invoke: async (command, args) => {
64+
if (command === "plugin:websocket|send") {
65+
const frame = JSON.parse(args.message.data);
66+
sent.push(frame);
67+
if (frame[0] === "REQ")
68+
queueMicrotask(() => deliver(["EOSE", frame[1]]));
69+
return;
70+
}
71+
if (command === "get_channels") {
72+
return new Promise((resolve, reject) =>
73+
reads.push({ args, resolve, reject }),
74+
);
75+
}
76+
assert.fail(`Unexpected IPC command: ${command}`);
77+
},
78+
};
79+
// Stub only native transport, not subscription creation or CLOSED dispatch.
80+
relayClient.wsId = 7;
81+
const deliver = (frame, generation = relayClient.connectionGeneration) =>
82+
relayClient.handleWsMessage(JSON.stringify(frame), generation);
83+
const queryClient = new QueryClient({
84+
defaultOptions: { queries: { retry: false, gcTime: Infinity } },
85+
});
86+
const hook = renderHook(
87+
() => {
88+
const query = useQuery({
89+
queryKey: channelsQueryKey,
90+
queryFn: () =>
91+
refreshChannelsQuery({
92+
queryClient,
93+
initialSnapshotPair: null,
94+
relayUrl: null,
95+
ownerPubkey: null,
96+
}),
97+
initialData: rawChannels.map(fromRawChannel),
98+
staleTime: Infinity,
99+
});
100+
useLiveChannelUpdates(query.data, null);
101+
return query;
102+
},
103+
{
104+
wrapper: ({ children }) =>
105+
React.createElement(
106+
QueryClientProvider,
107+
{ client: queryClient },
108+
children,
109+
),
110+
},
111+
);
112+
const settle = () =>
113+
act(async () => {
114+
await new Promise((resolve) => setTimeout(resolve, 0));
115+
});
116+
const tick = async (ms) => {
117+
await act(async () => {
118+
const target = now + ms;
119+
let fired = 0;
120+
for (;;) {
121+
const next = [...timers]
122+
.filter(([, timer]) => timer.at <= target)
123+
.sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
124+
if (!next) break;
125+
assert.ok(++fired < 1000, "timer loop must make progress");
126+
now = next[1].at;
127+
timers.delete(next[0]);
128+
next[1].fn();
129+
await new Promise((resolve) => setTimeout(resolve, 0));
130+
}
131+
now = target;
132+
});
133+
await settle();
134+
};
135+
await settle();
136+
// Admit both subscriptions through the production drain before testing CLOSED.
137+
await tick(500);
138+
assert.equal(sent.filter(([type]) => type === "REQ").length, 2);
139+
const ids = sent.filter(([type]) => type === "REQ").map(([, id]) => id);
140+
return {
141+
reads,
142+
sent,
143+
ids,
144+
timers,
145+
relayClient,
146+
queryClient,
147+
channelsQueryKey,
148+
state: () => queryClient.getQueryState(channelsQueryKey),
149+
data: () => queryClient.getQueryData(channelsQueryKey),
150+
close: (id = ids[0], reason = revoked, generation) =>
151+
act(async () => {
152+
await deliver(["CLOSED", id, reason], generation);
153+
}),
154+
tick,
155+
async respond(channels = rawChannels) {
156+
assert.equal(
157+
reads.length,
158+
1,
159+
"one authoritative refresh must be pending",
160+
);
161+
await act(async () =>
162+
reads[0].resolve({ hash: "fresh", channels, last_messages: {} }),
163+
);
164+
await settle();
165+
},
166+
async fail() {
167+
assert.equal(
168+
reads.length,
169+
1,
170+
"one authoritative refresh must be pending",
171+
);
172+
await act(async () => reads[0].reject(new Error("fixture offline")));
173+
await settle();
174+
},
175+
unmount: hook.unmount,
176+
restore() {
177+
hook.unmount();
178+
cleanup();
179+
queryClient.clear();
180+
// Avoid a native disconnect command; clear the real session's listeners/state.
181+
relayClient.wsId = null;
182+
relayClient.disconnect();
183+
window.setTimeout = original.setTimeout;
184+
window.clearTimeout = original.clearTimeout;
185+
window.__TAURI_INTERNALS__ = original.internals;
186+
Date.now = original.now;
187+
},
188+
};
189+
}
190+
191+
for (const outcome of ["archived", "unchanged", "removed", "failed"]) {
192+
test(`CLOSED refreshes authoritative channel state: ${outcome}`, async () => {
193+
const h = await mount();
194+
try {
195+
await h.close();
196+
await h.close(); // duplicate frame is not a second hint
197+
await h.close(h.ids[1]); // a second channel shares the debounce
198+
assert.equal(
199+
h.relayClient.subscriptions.size,
200+
0,
201+
"terminal subscriptions stay removed",
202+
);
203+
assert.equal(h.reads.length, 0);
204+
assert.ok(
205+
h
206+
.data()
207+
.every((channel) => channel.archivedAt === null && channel.isMember),
208+
);
209+
await h.tick(499);
210+
assert.equal(h.reads.length, 0);
211+
await h.tick(1);
212+
assert.equal(
213+
h.reads.length,
214+
1,
215+
"burst coalesces into one query without waiting for polling",
216+
);
217+
assert.equal(h.data().length, 2, "CLOSED alone cannot remove membership");
218+
if (outcome === "failed") {
219+
await h.fail();
220+
assert.equal(h.state().status, "error");
221+
assert.equal(h.data().length, 2);
222+
assert.ok(
223+
h
224+
.data()
225+
.every(
226+
(channel) => channel.archivedAt === null && channel.isMember,
227+
),
228+
);
229+
} else {
230+
await h.respond(
231+
outcome === "archived"
232+
? [
233+
{ ...rawChannels[0], archived_at: "2026-09-21T15:36:31Z" },
234+
rawChannels[1],
235+
]
236+
: outcome === "removed"
237+
? rawChannels.slice(1)
238+
: rawChannels,
239+
);
240+
assert.deepEqual(
241+
h.data().map((channel) => channel.id),
242+
outcome === "removed" ? ["b"] : ["a", "b"],
243+
);
244+
assert.equal(
245+
h.data().find((channel) => channel.id === "a")?.archivedAt,
246+
outcome === "archived"
247+
? "2026-09-21T15:36:31Z"
248+
: outcome === "removed"
249+
? undefined
250+
: null,
251+
);
252+
}
253+
await h.tick(30_000);
254+
assert.equal(
255+
h.reads.length,
256+
1,
257+
"refresh failure or unchanged state must not loop",
258+
);
259+
assert.equal(
260+
h.sent.filter(([type]) => type === "REQ").length,
261+
2,
262+
"no terminal resubscribe",
263+
);
264+
} finally {
265+
h.restore();
266+
}
267+
});
268+
}
269+
270+
test("unknown, non-channel, unrelated and old-generation CLOSED do not refresh channels", async () => {
271+
const h = await mount();
272+
try {
273+
await h.close("unknown");
274+
await h.close(h.ids[0], revoked, h.relayClient.connectionGeneration - 1);
275+
await h.close(h.ids[0], "invalid: bad filter");
276+
const dispose = await h.relayClient.subscribeLive(
277+
{ kinds: [0], limit: 1 },
278+
() => {},
279+
);
280+
const globalId = h.sent.at(-1)[1];
281+
await h.close(globalId);
282+
await dispose();
283+
await h.tick(500);
284+
assert.equal(h.reads.length, 0);
285+
assert.equal(h.relayClient.subscriptions.size, 1);
286+
} finally {
287+
h.restore();
288+
}
289+
});
290+
291+
test("a different restricted CLOSED reason does not refresh channels", async () => {
292+
const h = await mount();
293+
try {
294+
await h.close(h.ids[0], "restricted: not a channel member");
295+
assert.equal(
296+
h.relayClient.subscriptions.has(h.ids[0]),
297+
false,
298+
"the known channel subscription is still terminal",
299+
);
300+
await h.tick(500);
301+
assert.equal(
302+
h.reads.length,
303+
0,
304+
"only the exact revocation reason refreshes",
305+
);
306+
} finally {
307+
h.restore();
308+
}
309+
});
310+
311+
test("unmount cancels queued invalidation and removes its session listener", async () => {
312+
const h = await mount();
313+
try {
314+
await h.close();
315+
h.unmount();
316+
await h.tick(500);
317+
assert.equal(h.reads.length, 0);
318+
const dispose = await h.relayClient.subscribeLive(
319+
{ kinds: [9], "#h": ["later"], limit: 1 },
320+
() => {},
321+
);
322+
await h.close(h.sent.at(-1)[1]);
323+
await h.tick(500);
324+
assert.equal(
325+
h.timers.size,
326+
0,
327+
"unmounted listener must not schedule another invalidation",
328+
);
329+
await dispose();
330+
} finally {
331+
h.restore();
332+
}
333+
});

‎desktop/src/features/channels/useLiveChannelUpdates.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,14 @@ export function useLiveChannelUpdates(
372372
});
373373
}, [queryClient]);
374374

375+
React.useEffect(
376+
() =>
377+
relayClient.subscribeToChannelAccessRevocations(
378+
invalidateChannelsDebounced,
379+
),
380+
[invalidateChannelsDebounced],
381+
);
382+
375383
const liveSubsRef = React.useRef(new Map<string, LiveChannelEntry>());
376384

377385
React.useEffect(() => {
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import type { RelaySubscription } from "./relayClientShared";
2+
3+
/** Session-owned hints; CLOSED never establishes archive or membership state. */
4+
export class RelayChannelAccessRevocations {
5+
private listeners = new Set<() => void>();
6+
7+
subscribe(listener: () => void) {
8+
this.listeners.add(listener);
9+
return () => {
10+
this.listeners.delete(listener);
11+
};
12+
}
13+
14+
clear() {
15+
this.listeners.clear();
16+
}
17+
18+
/** Call after terminal cleanup, using the subscription captured before removal. */
19+
notify(subscription: RelaySubscription | undefined, reason: unknown) {
20+
if (
21+
subscription?.mode === "live" &&
22+
(subscription.filter["#h"]?.length ?? 0) > 0 &&
23+
reason === "restricted: channel access revoked"
24+
) {
25+
for (const listener of this.listeners) listener();
26+
}
27+
}
28+
}

0 commit comments

Comments
 (0)