diff --git a/desktop/src/features/messages/ui/useMentionWakePreflight.test.mjs b/desktop/src/features/messages/ui/useMentionWakePreflight.test.mjs index c93af47026..6bab7b6e99 100644 --- a/desktop/src/features/messages/ui/useMentionWakePreflight.test.mjs +++ b/desktop/src/features/messages/ui/useMentionWakePreflight.test.mjs @@ -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; diff --git a/desktop/src/features/messages/ui/useMentionWakePreflight.ts b/desktop/src/features/messages/ui/useMentionWakePreflight.ts index 31074da681..de82a3f652 100644 --- a/desktop/src/features/messages/ui/useMentionWakePreflight.ts +++ b/desktop/src/features/messages/ui/useMentionWakePreflight.ts @@ -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; }) { const timerRef = React.useRef | null>(null); - const activePlanKeyRef = React.useRef(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(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;