fix(desktop): fence each mention wake by identity, not plan key

A cancelled wake could resurrect itself and start a local agent a full
second early. The preflight fenced its timer continuation with
activePlanKeyRef, a string, and expressed cancellation by nulling it. But
plan keys are deliberately reusable -- the same relay, signer, channel,
and agent set produce the same string, which is exactly what makes the
"same plan, don't re-arm" early return work. Reusing the key as a
lifetime fence conflated the same intent with the same window, so a key
that legitimately came back made a dead continuation look live.

The sequence: an arming's hold matures and its getManagedAgentsByPubkey
lookup suspends; the draft trims to a bare mention, so the
substantive-text gate lapses and cancellation nulls the key; the draft
regains substantive text and re-arms an identical key for a fresh second;
the lookup resolves, both post-await checks compare equal strings, and
the dead arming starts the agent roughly a second early. Mention
removal/re-add and channel navigation away and back are the same shape.
Both the documented guarantee on MENTION_WAKE_GATE_HOLD_MS and the
checked-in gate-lapse contract say this cannot happen.

Give each arming an object identity and fence on that. armedRef holds the
live ArmedWake; the continuation compares by reference, which cannot ABA
by construction. The two comparison styles against that ref are now
deliberate and commented: identity asks "is this arming still the live
one", value asks "is the live window already for this plan" -- the latter
must stay a key comparison, since it is what lets continued typing extend
the hold rather than restart it. The beforeLookup/beforeWake plan checks
stay too; they answer the separate question of whether the live draft
still satisfies the gates.

Three regression tests suspend the managed-agent lookup mid-flight and
cover each cancellation path back to an identical key: the substantive-
text gate, the "@"-free short-circuit, and channel navigation. Each
asserts zero starts on resolve and then one start after a fresh hold, so
they pin a fence rather than a mute. Mutating the identity check back to
key equality fails exactly those three and no others.

Behavior is otherwise unchanged: 12/12 unit tests and all 73 mentions E2E
specs pass, including the wake-before-send journey.

Signed-off-by: Matt Toohey <contact@matttoohey.com>
This commit is contained in:
Matt Toohey
2026-08-27 14:47:21 +10:00
parent 55a70521d0
commit 5189c468e1
2 changed files with 168 additions and 11 deletions

View File

@@ -35,7 +35,7 @@ const OTHER_AGENT = "b".repeat(64);
const fizzRef = { displayName: "Fizz", pubkey: AGENT, isAgent: true };
const localAgentOptions = (contentRef, onStart) => ({
const localAgentOptions = (contentRef, onStart, overrides = {}) => ({
channelId: "general",
contentRef,
enabled: true,
@@ -52,8 +52,32 @@ const localAgentOptions = (contentRef, onStart) => ({
onStart();
return { pubkey: AGENT, status: "running" };
},
...overrides,
});
// Suspends the managed-agent lookup so a matured wake can be held mid-flight,
// which is the window in which a cancelled arming could resurrect itself.
const suspendedLookup = () => {
let resolve;
const lookup = new Promise((r) => {
resolve = r;
});
return {
getManagedAgentsByPubkey: () => lookup,
settle: async () => {
resolve(
new Map([
[
AGENT,
{ pubkey: AGENT, status: "stopped", backend: { type: "local" } },
],
]),
);
await lookup;
},
};
};
test("mention-only composer content is not substantive", () => {
assert.equal(hasSubstantiveNonMentionText("@Fizz ", [fizzRef]), false);
assert.equal(hasSubstantiveNonMentionText("@Fizz hello", [fizzRef]), true);
@@ -188,6 +212,117 @@ test("a lapse in the gates requires a fresh full gate hold", async (t) => {
assert.equal(starts, 1);
});
test("a trimmed-then-retyped draft cannot resurrect the cancelled wake", async (t) => {
t.mock.timers.enable({ apis: ["setTimeout"] });
const { act, renderHook } = await import("@testing-library/react");
const lookup = suspendedLookup();
let starts = 0;
const contentRef = { current: "@Fizz initial" };
const view = renderHook(() =>
useMentionWakePreflight(
localAgentOptions(
contentRef,
() => {
starts += 1;
},
{ getManagedAgentsByPubkey: lookup.getManagedAgentsByPubkey },
),
),
);
// Mature the hold, then park the arming inside its managed-agent lookup.
await act(async () => t.mock.timers.tick(MENTION_WAKE_GATE_HOLD_MS));
// Trimming to the bare mention lapses the substantive-text gate and cancels
// that arming; retyping restores an identical plan key within the same round
// trip. Only the arming's identity separates the dead window from the new one.
contentRef.current = "@Fizz ";
act(() => view.result.current.prepareMentionWake(contentRef.current));
contentRef.current = "@Fizz back again";
act(() => view.result.current.prepareMentionWake(contentRef.current));
await act(async () => t.mock.timers.tick(1));
await act(lookup.settle);
assert.equal(starts, 0);
// The replacement window is still live, so this is a fence, not a mute.
await act(async () => t.mock.timers.tick(MENTION_WAKE_GATE_HOLD_MS));
assert.equal(starts, 1);
});
test("removing and re-adding the mention cannot resurrect the cancelled wake", async (t) => {
t.mock.timers.enable({ apis: ["setTimeout"] });
const { act, renderHook } = await import("@testing-library/react");
const lookup = suspendedLookup();
let starts = 0;
const contentRef = { current: "@Fizz initial" };
const view = renderHook(() =>
useMentionWakePreflight(
localAgentOptions(
contentRef,
() => {
starts += 1;
},
{ getManagedAgentsByPubkey: lookup.getManagedAgentsByPubkey },
),
),
);
await act(async () => t.mock.timers.tick(MENTION_WAKE_GATE_HOLD_MS));
// Same race, reached down the other cancellation path: dropping the mention
// entirely nulls the plan on the "@"-free short-circuit rather than on the
// substantive-text gate.
contentRef.current = "please investigate";
act(() => view.result.current.prepareMentionWake(contentRef.current));
contentRef.current = "@Fizz back again";
act(() => view.result.current.prepareMentionWake(contentRef.current));
await act(async () => t.mock.timers.tick(1));
await act(lookup.settle);
assert.equal(starts, 0);
await act(async () => t.mock.timers.tick(MENTION_WAKE_GATE_HOLD_MS));
assert.equal(starts, 1);
});
test("navigating away and back cannot resurrect the cancelled wake", async (t) => {
t.mock.timers.enable({ apis: ["setTimeout"] });
const { act, renderHook } = await import("@testing-library/react");
const lookup = suspendedLookup();
let starts = 0;
const contentRef = { current: "@Fizz please investigate" };
const view = renderHook(
({ channelId }) =>
useMentionWakePreflight(
localAgentOptions(
contentRef,
() => {
starts += 1;
},
{
channelId,
getManagedAgentsByPubkey: lookup.getManagedAgentsByPubkey,
},
),
),
{ initialProps: { channelId: "general" } },
);
await act(async () => t.mock.timers.tick(MENTION_WAKE_GATE_HOLD_MS));
// The plan key carries the channel, so navigating away cancels the in-flight
// arming and navigating back hands the same key to a new one.
await act(async () => view.rerender({ channelId: "random" }));
await act(async () => view.rerender({ channelId: "general" }));
await act(lookup.settle);
assert.equal(starts, 0);
await act(async () => t.mock.timers.tick(MENTION_WAKE_GATE_HOLD_MS));
assert.equal(starts, 1);
});
test("mention-free drafts skip the mention-ref snapshot entirely", async () => {
const { act, renderHook } = await import("@testing-library/react");
let snapshots = 0;

View File

@@ -42,6 +42,14 @@ type MentionWakePlan = {
pubkeys: string[];
};
/**
* One arming of the wake window. Plan keys are deliberately reusable — the same
* relay, signer, channel, and agent set produce the same string — so a fresh
* object per arming is what distinguishes *this* window from a later one that
* happens to describe the same intent.
*/
type ArmedWake = { key: string };
export function hasSubstantiveNonMentionText(
content: string,
mentionRefs: readonly DraftMentionRef[],
@@ -100,7 +108,17 @@ export function useMentionWakePreflight(options: {
startManagedAgent: (input: ManagedAgentStartInput) => Promise<ManagedAgent>;
}) {
const timerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
const activePlanKeyRef = React.useRef<string | null>(null);
// The currently armed window, or null if none is. Two comparison styles are
// used against it on purpose:
//
// - by identity (`armedRef.current !== armed`) to ask "is this lifetime still
// the live one". Comparing keys here would let a cancelled window resurrect
// itself: cancel nulls the ref, and re-arming an identical plan restores an
// equal key, so a stale continuation would compare equal and fire early.
// - by value (`armedRef.current?.key === plan.key`) to ask "is the live
// window already for this plan", which is what lets continued typing extend
// the hold instead of restarting it.
const armedRef = React.useRef<ArmedWake | null>(null);
// Latest-ref over the whole options object: the stable callbacks below read
// fresh values without a hand-maintained field list that could drift.
const optionsRef = React.useRef(options);
@@ -109,7 +127,7 @@ export function useMentionWakePreflight(options: {
const cancelMentionWake = React.useCallback(() => {
if (timerRef.current !== null) clearTimeout(timerRef.current);
timerRef.current = null;
activePlanKeyRef.current = null;
armedRef.current = null;
}, []);
const currentPlan = React.useCallback((content: string) => {
@@ -167,23 +185,27 @@ export function useMentionWakePreflight(options: {
if (!plan) return cancelMentionWake();
// The gates are still holding for the same plan, so leave the running
// window alone. Re-arming here would turn the interval into a keystroke
// debounce and never fire for an uninterrupted typist.
if (activePlanKeyRef.current === plan.key) return;
// debounce and never fire for an uninterrupted typist. This one compares
// keys, not identity: a live window for an equal plan is the same window.
if (armedRef.current?.key === plan.key) return;
cancelMentionWake();
activePlanKeyRef.current = plan.key;
const armed: ArmedWake = { key: plan.key };
armedRef.current = armed;
timerRef.current = setTimeout(() => {
timerRef.current = null;
void (async () => {
// Re-confirm the gates at fire time and again after the lookup await,
// so the interval is a hold on live draft state rather than a promise
// made once at arming time.
if (activePlanKeyRef.current !== plan.key) return;
// Two questions at each checkpoint, not one. The identity check asks
// whether this arming is still the live one; the plan check asks
// whether the live draft still satisfies the gates. Both must hold, at
// fire time and again after the lookup await, so the interval is a
// hold on live draft state rather than a promise made once at arming.
if (armedRef.current !== armed) return;
const beforeLookup = currentPlan(contentRef.current);
if (beforeLookup?.key !== plan.key) return;
const managedAgents =
await optionsRef.current.getManagedAgentsByPubkey();
if (activePlanKeyRef.current !== plan.key) return;
if (armedRef.current !== armed) return;
const beforeWake = currentPlan(contentRef.current);
if (beforeWake?.key !== plan.key) return;