perf(desktop): skip re-persisting identical agent prefill snapshots

While a composer sits in prefill state, every identity change of
restoreAddressedAgentMentions (it depends on profiles and
audience.pubkeys) re-runs the restore effect, and
applyRestoredAgentMentions re-persisted the prefill unconditionally.
saveDraftEntry has no same-content short-circuit, so each run cost a
localStorage flush plus a notifySubscribers() broadcast with a fresh
updatedAt, re-rendering Inbox count subscribers for no state change.

persistAgentPrefill now loads the stored record first and returns
without writing when the incoming snapshot is identical: same content,
same channelId, an already-agent-prefill classification, matching
mention refs, and no pending attachments or spoilered URLs (a stored
agent-prefill record always has neither, so any live attachment state
disqualifies the skip and the write proceeds).

Bound by a unit test on the production hook: persisting an identical
prefill snapshot twice notifies zero subscribers and leaves updatedAt
untouched, while a genuinely changed snapshot (grown audience) still
writes, notifies once, and keeps the agent-prefill classification.
Falsified against the disabled skip (fails 2 !== 0 notifications).

Verified: the touched unit test file (22 passing) and the
persistent-agent-audience Playwright suite (37 passing; one
load-flake passed in isolation and on full-suite rerun).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: Matt Toohey <contact@matttoohey.com>
This commit is contained in:
Matt Toohey
2026-09-03 16:03:52 +10:00
parent 053b1ef343
commit 409c0c6b26
2 changed files with 106 additions and 2 deletions

View File

@@ -244,6 +244,7 @@ import {
initDraftStore,
loadDraftEntry,
persistDraftEntry,
subscribeToStore,
} from "../lib/useDrafts.ts";
import {
saveQueuedAttachmentsForDraft,
@@ -970,6 +971,72 @@ test("automatic_prefill_persists_immediately_without_waiting_for_cleanup", async
await handle.unmount();
});
test("repersisting_an_identical_prefill_snapshot_is_a_storage_noop", async () => {
const draftKey = "chan-prefill-noop";
setupStore("pubkey-prefill-noop");
const GROWN_PREFILL_REFS = [
...AGENT_PREFILL_REFS,
{ displayName: "Scout", pubkey: "agent-scout", isAgent: true },
];
let persistAgentPrefill;
const spoileredRef = { current: new Set() };
function HarnessComposer() {
({ persistAgentPrefill } = useDraftPersistLifecycle({
effectiveDraftKey: draftKey,
channelId: draftKey,
loadDraft: loadDraftEntry,
persistDraft: persistDraftEntry,
getMentionRefs: (content) =>
content.includes("@Scout") ? GROWN_PREFILL_REFS : AGENT_PREFILL_REFS,
restoreMentionRefs: () => {},
livePendingImeta: [],
setPendingImeta: () => {},
setContent: () => {},
clearContent: () => {},
setSpoileredAttachmentUrls: () => {},
spoileredAttachmentUrlsRef: spoileredRef,
syncComposerContentFromEditor: () => "@Jitter ",
}));
return null;
}
const handle = await mountStrictMode(HarnessComposer);
persistAgentPrefill("@Jitter ");
const first = loadDraftEntry(draftKey);
assert.equal(first?.entryKind, "agent-prefill");
// ISO timestamps have millisecond precision — space the writes out so an
// updatedAt bump from a non-skipped duplicate persist is observable.
await new Promise((resolve) => setTimeout(resolve, 10));
let notifications = 0;
const unsubscribe = subscribeToStore(() => {
notifications += 1;
});
persistAgentPrefill("@Jitter ");
persistAgentPrefill("@Jitter ");
assert.equal(
notifications,
0,
"re-persisting an identical prefill snapshot must not notify subscribers",
);
assert.equal(
loadDraftEntry(draftKey)?.updatedAt,
first.updatedAt,
"re-persisting an identical prefill snapshot must not bump updatedAt",
);
// A genuinely changed snapshot (audience grew) must still write and notify.
persistAgentPrefill("@Jitter @Scout ");
unsubscribe();
assert.equal(notifications, 1, "a changed prefill snapshot must persist");
const grown = loadDraftEntry(draftKey);
assert.equal(grown?.content, "@Jitter @Scout ");
assert.equal(grown?.entryKind, "agent-prefill");
assert.notEqual(grown?.updatedAt, first.updatedAt);
await handle.unmount();
});
test("authored_edit_promotes_prefill_monotonically_even_if_text_returns", async () => {
const draftKey = "chan-prefill-authored";
setupStore("pubkey-prefill-authored");

View File

@@ -78,7 +78,11 @@ type UseDraftPersistLifecycleResult = {
trackAuthoredContent: (content: string) => void;
/** Begin a fresh automatic address-only composer snapshot. */
resetToAgentPrefill: () => void;
/** Persist an automatic prefill, or clear it after its last mention is removed. */
/**
* Persist an automatic prefill, or clear it after its last mention is
* removed. Re-persisting a snapshot identical to the stored record is a
* no-op (no write, no subscriber broadcast, no updatedAt churn).
*/
persistAgentPrefill: (content: string) => void;
/** Restore the exact classification captured before an attempted send. */
restoreEntryKind: (entryKind: DraftEntryKind) => void;
@@ -91,6 +95,21 @@ function scopedDraftKey(draftKey: string): string {
return `${getDraftStoreScope()}:${draftKey}`;
}
function mentionRefsEqual(
stored: readonly DraftMentionRef[],
next: readonly DraftMentionRef[],
): boolean {
return (
stored.length === next.length &&
stored.every(
(ref, i) =>
ref.displayName === next[i].displayName &&
ref.pubkey === next[i].pubkey &&
ref.isAgent === next[i].isAgent,
)
);
}
/**
* Owns the draft-persist lifecycle for `MessageComposer`.
*
@@ -303,13 +322,30 @@ export function useDraftPersistLifecycle({
return;
}
resetToAgentPrefill();
// Effect-driven callers re-run whenever a collaborator identity changes
// (profile refresh, audience update) without the prefill itself moving.
// saveDraftEntry has no same-content short-circuit — every write flushes
// localStorage and broadcasts a fresh updatedAt to Inbox subscribers —
// so skip the re-persist when the stored snapshot is already identical.
const mentionRefs = getMentionRefs(content);
const stored = loadDraft(effectiveDraftKey);
if (
stored?.entryKind === "agent-prefill" &&
stored.content === content &&
stored.channelId === (channelId ?? effectiveDraftKey) &&
pendingImetaForPersistRef.current.length === 0 &&
spoileredAttachmentUrlsRef.current.size === 0 &&
mentionRefsEqual(stored.mentionRefs ?? [], mentionRefs)
) {
return;
}
persistDraft(
effectiveDraftKey,
content,
channelId ?? effectiveDraftKey,
[...pendingImetaForPersistRef.current],
[...spoileredAttachmentUrlsRef.current],
getMentionRefs(content),
mentionRefs,
"agent-prefill",
);
},
@@ -317,6 +353,7 @@ export function useDraftPersistLifecycle({
channelId,
effectiveDraftKey,
getMentionRefs,
loadDraft,
persistDraft,
resetToAgentPrefill,
spoileredAttachmentUrlsRef,