Skip to content

Commit c2c3aac

Browse files
matt2eclaude
andcommitted
fix(desktop): bound how stale the publish-boundary mention admission can be
PR #7154 review round 2, point 1 (P2): the publish-boundary revalidation skips when `preparedUpload`, `draft.preparedLinkPreviews`, and `relaySideEffectsRan` are all false, so the pre-side-effect authorization pass stands as the publish answer across whatever separated the two. Those three are an *enumeration* of the awaited steps known to reach the relay, and enumerations rot: a contributor adding an awaited step later must remember to set the boolean, and forgetting fails silent and unsafe — a stale admission publishes and nothing goes red. This branch already hardened one instance of this exact fragility class in cbd43fa, making the access-policy `wrote` signal load-bearing by construction rather than by convention. Measure the gap instead of enumerating its causes: - New `shouldRevalidateMentionsAtPublish` in `useMentionSendFlow.helpers` takes the three named triggers plus `msSinceAdmission` and adds a fourth clause: revalidate when at least `MENTION_ADMISSION_MAX_AGE_MS` (200) elapsed since the admission pass resolved. `completeSend` stamps `performance.now()` at admission and passes the delta at the boundary — monotonic, so a wall-clock step backwards cannot suppress the check. - The named triggers stay: they catch sub-threshold relay writes, which the clock alone would miss. - Cost on the fast path is nil. The measured immediate send is ~5 ms of local IPC between admission and publish (managed-agents cache read, the member short-circuit in readiness, and the no-active-huddle sync, which returns before touching the relay), so the bound never fires and the send keeps its single pass. What it converts is the unenumerated case: a future awaited step, a cold cache, or contention degrades to one extra ~570 ms pass instead of a silently stale publish. Conceding one tail the review write-up did not name and we had not either: `sync_agents_to_active_huddle` takes `AGENT_SYNC_LOCK` *before* its phase check, so a concurrent huddle-enrolling send can hold the "no active huddle" IPC — the leg that reports no relay work — open for hundreds of ms. Rare, but it is a real case where that step is not instant, and it is precisely what a clock catches and an enumeration cannot. Two corrections to the review's narrative, neither changing the fix. The "matching access policy leaves the flag false" combination is unreachable: `applyReusableAgentAccessPolicy` only runs for a non-member (`useEnsureAgentMentionsReady.ts:105-111`), and a non-member that skips the `wrote: true` attach must be in `participants` via `preparedParticipantPubkeys`, which is non-empty only under DM expansion — and that branch already set `relaySideEffectsRan` before readiness ran. And unconditional revalidation was not taken because it re-adds ~570 ms to every send to shrink an uncaught window that is ~600 ms on this branch *and* on `origin/main` (the admission pass's own three sequential relay queries leave its answer ~380 ms stale at resolution; the publish flight adds ~215 ms). Moving admission to the publish boundary was not taken because `admittedMentionPubkeys` gates every relay side effect that must precede the publish — DM participant set, access-policy/attach, the wake queue, huddle enrollment — so a late-only pass would write membership and queue agent wakes for unadmitted agents, the #5681 violation this ordering exists to prevent. Tests: - The requested causal regression, red-on-revert verified: a member relay agent on `general` (readiness short-circuits — no policy read, no attach, no wake), no huddle, no attachments. A new releasable bridge knob `syncAgentsToActiveHuddleDelayMs` holds the huddle-sync IPC open; the spec waits for +1 revalidation, injects the revocation, then releases via `__BUZZ_E2E_RELEASE_HUDDLE_AGENT_SYNCS__()` — injection before release makes the ordering deterministic by construction rather than by timing. It asserts the message publishes, quinn's p tag is stripped, revalidation is +2, and `add_channel_members`, `attach_managed_agent`, `update_managed_agent` and `start_managed_agent` are all unchanged, which is what proves the leg wrote nothing and so fired no named trigger. Neutering the elapsed clause makes it red (p tag present). - The untouched fast-path spec at `mentions.spec.ts:1793` stays at +1 as the over-trigger control: the bound must not fire on unheld sends, or the latency win this branch exists for is gone. - Three unit tests pin the predicate directly: the fast path reuses the admitted set, the bound fires at exactly `MENTION_ADMISSION_MAX_AGE_MS` and not one ms below, and each named trigger still fires on its own inside the bound. The repository file-size gate stays green. Verified: desktop tsc --noEmit, biome check over the touched files (exit 0), desktop unit tests (5909 passed, 0 failed), and the full mentions (89) and channels (88) Playwright smoke suites against a fresh pnpm build:e2e bundle, plus a 3x stress rerun of the new spec. Unrelated, recorded so it is not mistaken for fallout: the `huddle-transcription.spec.ts` "assigns distinct agent voices" spec fails on this branch — it also fails 3/3 with this change stashed and on a clean tree, so it predates this commit. Diagnosing it needs a stable preview server: a stale or dying server on port 4173 produces both phantom failures and phantom passes here. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Matt Toohey <[email protected]>
1 parent b5a24d5 commit c2c3aac

6 files changed

Lines changed: 257 additions & 8 deletions

File tree

‎desktop/src/features/messages/ui/useMentionSendFlow.helpers.test.mjs‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,18 @@ import test from "node:test";
44
import {
55
formatMessageSendError,
66
getErrorMessage,
7+
MENTION_ADMISSION_MAX_AGE_MS,
78
mergeMentionRecipients,
9+
shouldRevalidateMentionsAtPublish,
810
} from "./useMentionSendFlow.helpers.ts";
911

12+
const fastPathSend = {
13+
hasDeferredUpload: false,
14+
hasDeferredLinkPreviews: false,
15+
relaySideEffectsRan: false,
16+
msSinceAdmission: 3,
17+
};
18+
1019
test("formatMessageSendError preserves the publication failure", () => {
1120
assert.equal(
1221
formatMessageSendError(new Error("relay rejected voice note")),
@@ -29,6 +38,44 @@ test("getErrorMessage preserves Tauri string errors", () => {
2938
assert.equal(getErrorMessage({}, "Unknown error"), "Unknown error");
3039
});
3140

41+
test("the immediate fast path reuses the admitted mention set", () => {
42+
assert.equal(shouldRevalidateMentionsAtPublish(fastPathSend), false);
43+
});
44+
45+
test("a long gap between admission and publish forces a fresh pass", () => {
46+
// The staleness bound, not any named trigger: none of the enumerated
47+
// relay-touching steps ran, yet the two passes are far enough apart that
48+
// the earlier admission can no longer be assumed current.
49+
assert.equal(
50+
shouldRevalidateMentionsAtPublish({
51+
...fastPathSend,
52+
msSinceAdmission: MENTION_ADMISSION_MAX_AGE_MS,
53+
}),
54+
true,
55+
);
56+
assert.equal(
57+
shouldRevalidateMentionsAtPublish({
58+
...fastPathSend,
59+
msSinceAdmission: MENTION_ADMISSION_MAX_AGE_MS - 1,
60+
}),
61+
false,
62+
);
63+
});
64+
65+
test("each relay-touching trigger forces a fresh pass on its own", () => {
66+
for (const trigger of [
67+
"hasDeferredUpload",
68+
"hasDeferredLinkPreviews",
69+
"relaySideEffectsRan",
70+
]) {
71+
assert.equal(
72+
shouldRevalidateMentionsAtPublish({ ...fastPathSend, [trigger]: true }),
73+
true,
74+
`${trigger} must revalidate even inside the staleness bound`,
75+
);
76+
}
77+
});
78+
3279
test("address-locked agents join explicit mentions without duplicating recipients", () => {
3380
const explicit = ["A".repeat(64), "b".repeat(64)];
3481
const locked = ["a".repeat(64), "C".repeat(64)];

‎desktop/src/features/messages/ui/useMentionSendFlow.helpers.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,49 @@ export function mergeOutgoingTagsWithReferenceMentions(
130130
];
131131
}
132132

133+
/**
134+
* How long the pre-side-effect mention-authorization pass may stand in as the
135+
* publish-boundary answer before the publish re-runs it.
136+
*
137+
* The named triggers in {@link shouldRevalidateMentionsAtPublish} enumerate
138+
* the awaited steps known to reach the relay, and an enumeration rots: a step
139+
* added later that suspends the send for a round-trip would silently publish
140+
* a stale admission, and nothing would fail. Measuring the gap fails the
141+
* other way — an unenumerated suspension, a cold cache, a contended backend
142+
* lock, or an event-loop stall costs one extra pass instead of a stale
143+
* publish. The measured fast path is single-digit milliseconds of local IPC
144+
* with no relay traffic possible, so this bound never fires there.
145+
*/
146+
export const MENTION_ADMISSION_MAX_AGE_MS = 200;
147+
148+
/**
149+
* Whether the publish must re-run mention authorization rather than reuse the
150+
* pre-side-effect pass (#5681): either an awaited step known to reach the
151+
* relay ran in between, or the two are far enough apart that the earlier
152+
* answer can no longer be assumed current.
153+
*
154+
* `msSinceAdmission` must come from a monotonic clock (`performance.now()`),
155+
* not `Date.now()` — a wall-clock step backwards would suppress the check.
156+
*/
157+
export function shouldRevalidateMentionsAtPublish({
158+
hasDeferredUpload,
159+
hasDeferredLinkPreviews,
160+
relaySideEffectsRan,
161+
msSinceAdmission,
162+
}: {
163+
hasDeferredUpload: boolean;
164+
hasDeferredLinkPreviews: boolean;
165+
relaySideEffectsRan: boolean;
166+
msSinceAdmission: number;
167+
}) {
168+
return (
169+
hasDeferredUpload ||
170+
hasDeferredLinkPreviews ||
171+
relaySideEffectsRan ||
172+
msSinceAdmission >= MENTION_ADMISSION_MAX_AGE_MS
173+
);
174+
}
175+
133176
export function getErrorMessage(error: unknown, fallback: string) {
134177
if (error instanceof Error && error.message) return error.message;
135178
if (typeof error === "string" && error.trim()) return error;

‎desktop/src/features/messages/ui/useMentionSendFlow.ts‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ import {
4141
type QueuedAgentWake,
4242
type SendMessageWithMentionFlowInput,
4343
resolvePreviewTags,
44+
shouldRevalidateMentionsAtPublish,
4445
uniqueNormalizedPubkeys,
4546
} from "./useMentionSendFlow.helpers";
4647
import { buildAgentAddressMentionTags } from "@/features/messages/lib/agentAddressMention.mjs";
@@ -380,6 +381,8 @@ export function useMentionSendFlow({
380381
const admittedMentionPubkeys = uniqueNormalizedPubkeys(
381382
await mentions.revalidateMentionPubkeys(mentionPubkeys),
382383
);
384+
// Monotonic stamp for the publish-boundary staleness bound below.
385+
const admittedAtMs = performance.now();
383386
if (isSendCancelled()) return restoreComposerAfterFailure();
384387
if (!isMountedRef.current) return persistPreflightDraft();
385388
const admittedMentionPubkeySet = new Set(admittedMentionPubkeys);
@@ -520,15 +523,20 @@ export function useMentionSendFlow({
520523
// Mention authorization was already established by the pre-side-effect
521524
// pass above. Re-validate at the publish boundary only when something
522525
// separated that pass from this publish — a deferred wait (background
523-
// media upload, link-preview settlement) or an awaited relay side
526+
// media upload, link-preview settlement), an awaited relay side
524527
// effect (DM expansion, membership/access-policy writes, huddle
525-
// enrollment) — since authorization could have been revoked during
526-
// the gap. On the remaining immediate path a second pass would repeat
527-
// the same relay round-trips with the same inputs.
528-
const revalidatedMentionPubkeys =
529-
preparedUpload || draft.preparedLinkPreviews || relaySideEffectsRan
530-
? await mentions.revalidateMentionPubkeys(mentionPubkeys)
531-
: admittedMentionPubkeys;
528+
// enrollment), or simply enough elapsed time that the earlier answer
529+
// is no longer current — since authorization could have been revoked
530+
// during the gap. On the remaining immediate path a second pass would
531+
// repeat the same relay round-trips with the same inputs.
532+
const revalidatedMentionPubkeys = shouldRevalidateMentionsAtPublish({
533+
hasDeferredUpload: preparedUpload != null,
534+
hasDeferredLinkPreviews: draft.preparedLinkPreviews != null,
535+
relaySideEffectsRan,
536+
msSinceAdmission: performance.now() - admittedAtMs,
537+
})
538+
? await mentions.revalidateMentionPubkeys(mentionPubkeys)
539+
: admittedMentionPubkeys;
532540
if (signal?.aborted || isSendCancelled()) return;
533541
const finalTagsWithAgentAddress = [
534542
...finalOutgoingTags,

‎desktop/src/testing/e2eBridge.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,11 @@ type E2eConfig = {
316316
addAgentToHuddleError?: string;
317317
/** Delay an invocation-time huddle snapshot to exercise hydration ordering. */
318318
huddleStateReadDelayMs?: number;
319+
/** Delay (ms) for `sync_agents_to_active_huddle` so e2e tests can hold the
320+
* send path open across a leg that writes nothing to the relay (no active
321+
* huddle) and revoke a mention mid-hold.
322+
* Releasable early via `__BUZZ_E2E_RELEASE_HUDDLE_AGENT_SYNCS__()`. */
323+
syncAgentsToActiveHuddleDelayMs?: number;
319324
/** Delay companion creation to expose the newly-started huddle handoff state. */
320325
openHuddleWindowDelayMs?: number;
321326
/** Delay the native start result after membership arrives in the channel list. */
@@ -1514,6 +1519,10 @@ declare global {
15141519
* armed `startManagedAgentErrors` rejection) without waiting out the
15151520
* delay. Returns the number of holds flushed. */
15161521
__BUZZ_E2E_RELEASE_MANAGED_AGENT_STARTS__?: () => number;
1522+
/** Release every `sync_agents_to_active_huddle` currently held behind
1523+
* `syncAgentsToActiveHuddleDelayMs`, letting it resolve without waiting
1524+
* out the delay. Returns the number of holds flushed. */
1525+
__BUZZ_E2E_RELEASE_HUDDLE_AGENT_SYNCS__?: () => number;
15171526
/** Hold the next channel read until released. */
15181527
__BUZZ_E2E_DEFER_NEXT_CHANNELS_READ__?: () => void;
15191528
/** Disarm the latch and release the held channel read, if any. */
@@ -1651,6 +1660,11 @@ let deferredThreadRepliesQueue: Array<() => void> = [];
16511660
// start across a community round-trip needs the hold long enough to be
16521661
// deterministic AND a way to settle it on demand afterwards.
16531662
let heldManagedAgentStartReleases: Array<() => void> = [];
1663+
// Huddle agent syncs currently held behind `syncAgentsToActiveHuddleDelayMs`,
1664+
// releasable early via `__BUZZ_E2E_RELEASE_HUDDLE_AGENT_SYNCS__()`. The hold
1665+
// must outlast the mid-send mutation a spec injects, then settle on demand
1666+
// rather than on a timer, so the publish never races the injection.
1667+
let heldHuddleAgentSyncReleases: Array<() => void> = [];
16541668
let cancelledMediaUploadIds = new Set<string>();
16551669
let cancelledMediaFetchIds = new Set<string>();
16561670
let mockMediaFetchControllers = new Map<string, AbortController>();
@@ -11540,6 +11554,12 @@ export function maybeInstallE2eTauriMocks() {
1154011554
for (const release of held) release();
1154111555
return held.length;
1154211556
};
11557+
heldHuddleAgentSyncReleases = [];
11558+
window.__BUZZ_E2E_RELEASE_HUDDLE_AGENT_SYNCS__ = () => {
11559+
const held = heldHuddleAgentSyncReleases.splice(0);
11560+
for (const release of held) release();
11561+
return held.length;
11562+
};
1154311563
deferNextChannelsRead = false;
1154411564
deferredChannelsReadResolve = null;
1154511565
window.__BUZZ_E2E_CHANNELS_READ_PENDING__ = 0;
@@ -11974,6 +11994,24 @@ export function maybeInstallE2eTauriMocks() {
1197411994
channelId?: string;
1197511995
agentPubkeys?: string[];
1197611996
};
11997+
const syncDelayMs =
11998+
activeConfig?.mock?.syncAgentsToActiveHuddleDelayMs ?? 0;
11999+
if (syncDelayMs > 0) {
12000+
await new Promise<void>((resolve) => {
12001+
let settled = false;
12002+
const release = () => {
12003+
if (settled) return;
12004+
settled = true;
12005+
window.clearTimeout(timer);
12006+
heldHuddleAgentSyncReleases = heldHuddleAgentSyncReleases.filter(
12007+
(held) => held !== release,
12008+
);
12009+
resolve();
12010+
};
12011+
const timer = window.setTimeout(release, syncDelayMs);
12012+
heldHuddleAgentSyncReleases.push(release);
12013+
});
12014+
}
1197712015
if (
1197812016
!mockHuddle ||
1197912017
!request.channelId ||

‎desktop/tests/e2e/mentions.spec.ts‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2243,6 +2243,115 @@ test("sends that enroll agents into an active huddle revalidate at the publish b
22432243
);
22442244
});
22452245

2246+
test("a send held open by a no-write step still revalidates at the publish boundary", async ({
2247+
page,
2248+
}) => {
2249+
// The three named triggers enumerate the awaited steps known to reach the
2250+
// relay; the staleness bound covers the ones they cannot name. Here the only
2251+
// thing separating the authorization pass from the publish is the huddle
2252+
// sync — which with no active huddle writes nothing and returns
2253+
// `matched_active_huddle: false`, so no named trigger fires — held open long
2254+
// enough for a revocation to land. The p tag must still be stripped.
2255+
await installMockBridge(page, {
2256+
// Released on demand below; long enough that it is never waited out.
2257+
syncAgentsToActiveHuddleDelayMs: 45_000,
2258+
relayAgents: [
2259+
{
2260+
pubkey: ALLOWLIST_RELAY_AGENT_PUBKEY,
2261+
name: "quinn",
2262+
respondTo: "allowlist",
2263+
respondToAllowlist: [MOCK_VIEWER_PUBKEY],
2264+
channelNames: ["general"],
2265+
},
2266+
],
2267+
});
2268+
await page.goto("/");
2269+
await page.getByTestId("channel-general").click();
2270+
// Already a member, so readiness short-circuits: no access-policy read, no
2271+
// membership write, no wake.
2272+
await page.evaluate(
2273+
async ({ channelId, pubkey }) => {
2274+
const invoke = window.__BUZZ_E2E_INVOKE_MOCK_COMMAND__;
2275+
if (!invoke) throw new Error("Mock bridge is not installed.");
2276+
await invoke("add_channel_members", {
2277+
channelId,
2278+
pubkeys: [pubkey],
2279+
role: "bot",
2280+
});
2281+
await window.__BUZZ_E2E_QUERY_CLIENT__?.invalidateQueries({
2282+
queryKey: ["channels"],
2283+
});
2284+
},
2285+
{
2286+
channelId: GENERAL_CHANNEL_ID,
2287+
pubkey: ALLOWLIST_RELAY_AGENT_PUBKEY,
2288+
},
2289+
);
2290+
2291+
const input = page.getByTestId("message-input");
2292+
await input.fill("@quinn");
2293+
const quinnRow = autocomplete(page).locator("button", { hasText: "quinn" });
2294+
await expect(quinnRow).toBeVisible();
2295+
await quinnRow.click();
2296+
await page.keyboard.type("hello");
2297+
await expect(input).toHaveText("@quinn hello");
2298+
2299+
const baselineCommands = await readCommandLog(page);
2300+
await page.getByTestId("send-message").click();
2301+
2302+
// The pre-side-effect pass has admitted quinn; the huddle sync now holds the
2303+
// publish open. Revoke before releasing, so the ordering is deterministic by
2304+
// construction rather than by timing.
2305+
await expect
2306+
.poll(async () =>
2307+
commandCount(await readCommandLog(page), "revalidate_relay_agents"),
2308+
)
2309+
.toBe(commandCount(baselineCommands, "revalidate_relay_agents") + 1);
2310+
await page.evaluate((pubkey) => {
2311+
window.__BUZZ_E2E__.mock ??= {};
2312+
window.__BUZZ_E2E__.mock.relayAgentRevalidationRevokedPubkeys = [pubkey];
2313+
}, ALLOWLIST_RELAY_AGENT_PUBKEY);
2314+
2315+
// The send is parked on the held sync, so this only widens a gap that is
2316+
// already open — it pins the admission-to-publish distance past the
2317+
// staleness bound on any machine.
2318+
await page.waitForTimeout(400);
2319+
await expect
2320+
.poll(() =>
2321+
page.evaluate(
2322+
() => window.__BUZZ_E2E_RELEASE_HUDDLE_AGENT_SYNCS__?.() ?? 0,
2323+
),
2324+
)
2325+
.toBeGreaterThan(0);
2326+
2327+
await expect
2328+
.poll(() => readOutgoingMentionPubkeys(page, "@quinn hello"))
2329+
.not.toBeNull();
2330+
await expect
2331+
.poll(() => readOutgoingMentionPubkeys(page, "@quinn hello"))
2332+
.not.toContain(ALLOWLIST_RELAY_AGENT_PUBKEY);
2333+
2334+
const commands = await readCommandLog(page);
2335+
expect(commandCount(commands, "revalidate_relay_agents")).toBe(
2336+
commandCount(baselineCommands, "revalidate_relay_agents") + 2,
2337+
);
2338+
expect(commandCount(commands, "sync_agents_to_active_huddle")).toBe(
2339+
commandCount(baselineCommands, "sync_agents_to_active_huddle") + 1,
2340+
);
2341+
// The second pass was owed to elapsed time alone: nothing on this leg wrote
2342+
// relay state, which is what makes it invisible to the named triggers.
2343+
for (const command of [
2344+
"add_channel_members",
2345+
"attach_managed_agent",
2346+
"update_managed_agent",
2347+
"start_managed_agent",
2348+
]) {
2349+
expect(commandCount(commands, command)).toBe(
2350+
commandCount(baselineCommands, command),
2351+
);
2352+
}
2353+
});
2354+
22462355
test("selected relay agents are invited as bots before sending", async ({
22472356
page,
22482357
}) => {

‎desktop/tests/helpers/bridge.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,10 @@ type MockBridgeOptions = {
228228
};
229229
/** Delay an invocation-time huddle snapshot to exercise hydration ordering. */
230230
huddleStateReadDelayMs?: number;
231+
/** Delay (ms) for `sync_agents_to_active_huddle` so e2e tests can hold the
232+
* send path open across a leg that writes nothing to the relay.
233+
* Releasable early via `__BUZZ_E2E_RELEASE_HUDDLE_AGENT_SYNCS__()`. */
234+
syncAgentsToActiveHuddleDelayMs?: number;
231235
/** Delay companion creation to expose the newly-started huddle handoff state. */
232236
openHuddleWindowDelayMs?: number;
233237
/** Delay the native start result after membership arrives in the channel list. */

0 commit comments

Comments
 (0)