fix(sidebar): harden sidebar-sync durability, LWW, and mixed-fleet residual

Close the pass-3 review blocker and Carl's four P1s on the channel
sections/sort/stars/mutes relay sync, all in the sidebar lib:

- Gate the legacy-consumed marker on a proven v2 transfer. writeOwnOutbox
  now returns whether the fresh key's setItem succeeded; the whole-blob
  hooks write the marker only when durable, so a quota failure leaves the
  legacy record replayable instead of silently suppressing the only copy.
- Reconnect wakes the existing pending edit (retryPendingPublish) rather
  than re-queueing via publish*(), which reset the frozen baseline and
  published a stale edit over an advanced remote.
- Merge lanes clear an own outbox only after an authoritative retained-head
  fetch proves the head subsumes the attempted store; a bare EVENT OK on a
  superseded NIP-33 write no longer drops the loser's durable click.
- An unreadable/unsupported pre-publish head retains the pending edit and
  retries rather than overwriting state the client could not inspect.
- Document the accepted mixed-fleet residual (a same-second old-build click
  reads rev 0 and loses to an earlier new-build rev, healing on the next
  later-second click) and pin it with a test; no protocol change.

Regressions added for each item, mutation-verified where the fix lives in
the hook.

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
This commit is contained in:
Duncan
2026-08-27 13:21:22 -04:00
parent 3712e6fb2c
commit 6078943f3b
20 changed files with 1403 additions and 82 deletions

View File

@@ -156,6 +156,31 @@ test("mergeStores: equal updatedAt AND equal rev → muted=true wins (leaf)", ()
assert.deepEqual(result.channels.c, E(true, 100, 3));
});
test("mergeStores: same-second old-build click (rev 0) loses to an earlier new-build rev, heals next second", () => {
// ACCEPTED MIXED-FLEET RESIDUAL (Carl P1 #5). A new build wrote {muted:true,
// rev:2} at second 100; an old build then UNMUTES in the SAME second — old
// builds mint no rev, so its click reads rev:0. It loses the same-second tie
// to the earlier rev-2 entry: the later intent is suppressed until a
// strictly-later second carries it on the primary updatedAt key. This pins the
// current deterministic outcome; it is not a regression to fix here.
const newBuildMute = S(E(true, 100, 2));
const oldBuildUnmuteSameSecond = S(E(false, 100, 0));
assert.deepEqual(
mergeStores(newBuildMute, oldBuildUnmuteSameSecond).channels.c,
E(true, 100, 2),
"the earlier new-build rev-2 mute wins the same-second tie — old click's unmute is lost",
);
// The same old-build unmute one second later wins outright on updatedAt: the
// residual self-heals the moment the user clicks again in a later second.
const oldBuildUnmuteNextSecond = S(E(false, 101, 0));
assert.deepEqual(
mergeStores(newBuildMute, oldBuildUnmuteNextSecond).channels.c,
E(false, 101, 0),
"a strictly-later-second old-build unmute wins — the residual is transient",
);
});
test("mergeStores: unmute with higher updatedAt overrides mute", () => {
const result = mergeStores(S(E(true, 100, 9)), S(E(false, 999, 1)));
assert.deepEqual(result.channels.c, E(false, 999, 1));

View File

@@ -162,9 +162,21 @@ export function writeChannelMutesStore(
* `updatedAt` is primary so a strictly-later edit — from any build, whether it
* carries `rev` or (older build) reads `rev: 0` — wins outright. `rev` breaks
* only a same-second `updatedAt` tie: the ambiguous integer-second window the
* clock cannot resolve, where a click that minted `rev = maxSeen + 1` dominates
* any same-second state it observed. On a full tie (equal `updatedAt` AND equal
* `rev`) `true` wins as the deterministic leaf.
* clock cannot resolve, where a NEW-build click that minted `rev = maxSeen + 1`
* dominates same-second state it observed. On a full tie (equal `updatedAt` AND
* equal `rev`) `true` wins as the deterministic leaf.
*
* ACCEPTED MIXED-FLEET RESIDUAL (Carl P1 #5, no protocol change): an OLD build
* mints no `rev`, so its click reads `rev: 0`. A later old-build click that
* lands in the SAME integer second as an earlier new-build write carrying
* `rev >= 1` therefore loses that same-second tie — the old click's intent is
* suppressed until the user clicks again in a strictly-later second, when the
* primary `updatedAt` key carries it. This is bounded (one integer second,
* old-build writer only, self-heals on the next later-second click) and is no
* worse than the shipped LWW behavior; closing it would need a version
* migration we deliberately do not build. `mergeStores: same-second old-build
* click (rev 0) loses to an earlier new-build rev, heals next second` pins the
* exact current outcome.
*/
export function mergeStores(
a: ChannelMuteStore,

View File

@@ -7,6 +7,7 @@ import { ChannelMuteSyncManager } from "./channelMutesSync.ts";
import {
installFakeWindow,
installTauriMock,
installEchoTauri,
makeFakeWindow,
} from "./sidebarSyncTestHelpers.mjs";
@@ -159,19 +160,27 @@ test("destroy: is safe to call with no pending publish", () => {
// generation CAS in discardPending lets A's success null out B's pending+outbox.
test("A-in-flight → B-click → A-succeeds: B stays pending and B publishes", async () => {
let releaseFirst = null;
const publishedContents = [];
mock.method(relayClient, "fetchEvents", () => Promise.resolve([]));
mock.method(relayClient, "publishEvent", () => {
if (releaseFirst === null && publishedContents.length === 0) {
let publishCount = 0;
let storedHead = [];
mock.method(relayClient, "fetchEvents", () => Promise.resolve(storedHead));
mock.method(relayClient, "publishEvent", (event) => {
publishCount++;
if (publishCount === 1) {
// A reaches the relay; hold its ACK open until the test releases it, then
// record it as the retained head.
return new Promise((res) => {
releaseFirst = res;
releaseFirst = () => {
storedHead = [event];
res();
};
});
}
storedHead = [event];
return Promise.resolve();
});
const t = makeMultiTimerWindow();
const restore = installFakeWindow(t.win);
const tauri = installTauriMock("{}");
const tauri = installEchoTauri("pk-ab");
try {
const manager = new ChannelMuteSyncManager("pk-ab", RELAY);
const storeA = makeStore({ a: E(true, 100, 1) });
@@ -203,7 +212,9 @@ test("A-in-flight → B-click → A-succeeds: B stays pending and B publishes",
"older A completion leaves B outbox",
);
// B's own debounce fires and B reaches the relay (published) with no kick.
// B's own debounce fires and B reaches the relay with no kick; the
// post-publish retained-head fetch reads B's own write back and confirms
// subsumption, so B's outbox clears.
const capturedBefore = tauri.capturedPlaintext();
await t.fireDelay(2000);
for (let i = 0; i < 50; i++) await Promise.resolve();
@@ -215,7 +226,7 @@ test("A-in-flight → B-click → A-succeeds: B stays pending and B publishes",
assert.equal(
manager.getPendingMuteStore(),
null,
"B cleared after publish",
"B cleared after confirmed publish",
);
assert.equal(
readChannelMutesOutbox("pk-ab", RELAY),
@@ -235,19 +246,21 @@ test("A-in-flight → B-click → A-succeeds: B stays pending and B publishes",
test("A-in-flight → B-click → A-fails: B remains pending and B publishes", async () => {
let rejectFirst = null;
let publishCount = 0;
mock.method(relayClient, "fetchEvents", () => Promise.resolve([]));
mock.method(relayClient, "publishEvent", () => {
let storedHead = [];
mock.method(relayClient, "fetchEvents", () => Promise.resolve(storedHead));
mock.method(relayClient, "publishEvent", (event) => {
publishCount++;
if (publishCount === 1) {
return new Promise((_res, rej) => {
rejectFirst = () => rej(new Error("socket error"));
});
}
storedHead = [event];
return Promise.resolve();
});
const t = makeMultiTimerWindow();
const restore = installFakeWindow(t.win);
const tauri = installTauriMock("{}");
const tauri = installEchoTauri("pk-abfail");
try {
const manager = new ChannelMuteSyncManager("pk-abfail", RELAY);
manager.publishMutes(makeStore({ a: E(true, 100, 1) }));
@@ -268,7 +281,8 @@ test("A-in-flight → B-click → A-fails: B remains pending and B publishes", a
"B outbox intact after A's failure",
);
// B's debounce fires and B publishes successfully.
// B's debounce fires and B publishes successfully; the retained-head fetch
// confirms B's own write and clears it.
await t.fireDelay(2000);
for (let i = 0; i < 50; i++) await Promise.resolve();
const captured = tauri.capturedPlaintext();
@@ -290,15 +304,17 @@ test("A-in-flight → B-click → A-fails: B remains pending and B publishes", a
// edit stranded (Will's "make another change to kick it" symptom).
test("failed publish schedules a bounded-backoff retry and keeps the pending edit", async () => {
let publishCount = 0;
mock.method(relayClient, "fetchEvents", () => Promise.resolve([]));
mock.method(relayClient, "publishEvent", () => {
let storedHead = [];
mock.method(relayClient, "fetchEvents", () => Promise.resolve(storedHead));
mock.method(relayClient, "publishEvent", (event) => {
publishCount++;
if (publishCount === 1) return Promise.reject(new Error("timeout"));
storedHead = [event];
return Promise.resolve();
});
const t = makeMultiTimerWindow();
const restore = installFakeWindow(t.win);
const tauri = installTauriMock("{}");
const tauri = installEchoTauri("pk-retry");
try {
const manager = new ChannelMuteSyncManager("pk-retry", RELAY);
manager.publishMutes(makeStore({ a: E(true, 100, 1) }));
@@ -309,7 +325,8 @@ test("failed publish schedules a bounded-backoff retry and keeps the pending edi
);
assert.ok(t.hasDelay(2000), "a retry timer at RETRY_BASE_MS is scheduled");
// The retry fires and the second publish succeeds → pending cleared.
// The retry fires and the second publish succeeds; the retained-head fetch
// confirms the write → pending cleared.
await t.fireDelay(2000);
for (let i = 0; i < 50; i++) await Promise.resolve();
assert.equal(publishCount, 2, "retry re-published");
@@ -326,6 +343,72 @@ test("failed publish schedules a bounded-backoff retry and keeps the pending edi
}
});
// ─── Retention confirmation (Carl P1): OK is not proof of retention ───────────
// The relay OKs a superseded NIP-33 write as a no-op, so two windows racing
// distinct blobs from the same head can both get OK while only one is retained.
// The loser must NOT clear its durable outbox on OK alone: it fetches the
// authoritative retained head and clears only when that head subsumes its
// write. A retained head carrying a peer's distinct blob does not subsume the
// loser's click, so the outbox is kept and a retry is scheduled.
// Mutation: clearing on OK alone (dropping confirmRetainedHeadSubsumes) would
// null the pending edit here and lose the click.
test("publish OK but a peer blob is retained: loser keeps its outbox and retries", async () => {
let publishCount = 0;
// The retained head is a peer window's distinct blob from the same base —
// it does NOT contain our channel `a`, so it cannot subsume our write.
let storedHead = [];
mock.method(relayClient, "fetchEvents", () => Promise.resolve(storedHead));
const tauri = installEchoTauri("pk-loser");
mock.method(relayClient, "publishEvent", (event) => {
publishCount++;
if (publishCount === 1) {
// Our write is OK'd by the relay but immediately superseded: the retained
// head is the peer's blob for a different channel, minted through the same
// echo seam so it decrypts.
storedHead = [tauri.mintHead(makeStore({ z: E(true, 200, 5) }), 100)];
return Promise.resolve();
}
// The retry (which max-merges the peer head in) is retained.
storedHead = [event];
return Promise.resolve();
});
const t = makeMultiTimerWindow();
const restore = installFakeWindow(t.win);
try {
const manager = new ChannelMuteSyncManager("pk-loser", RELAY);
manager.publishMutes(makeStore({ a: E(true, 100, 1) }));
await t.fireDelay(2000); // publish OK, but peer blob is what's retained
for (let i = 0; i < 50; i++) await Promise.resolve();
assert.ok(
manager.getPendingMuteStore() !== null,
"unconfirmed publish keeps the pending edit",
);
assert.ok(
readChannelMutesOutbox("pk-loser", RELAY),
"loser keeps its durable outbox — OK is not proof of retention",
);
assert.ok(t.hasDelay(2000), "a retry is scheduled");
// The retry re-publishes the max-merge of our click and the peer head; this
// time it is retained (subsumes our `a`) and the outbox clears.
await t.fireDelay(2000);
for (let i = 0; i < 50; i++) await Promise.resolve();
assert.equal(publishCount, 2, "loser retried");
assert.equal(
manager.getPendingMuteStore(),
null,
"pending cleared once the retained head subsumes our click",
);
manager.destroy();
} finally {
tauri.restore();
restore();
mock.reset();
}
});
// ─── Boot seed-publish guard (the revert-fix regression suite) ─────────────────
test("revert-fix: fetch failed (error) does not trigger seed-publish via bootstrap", async () => {

View File

@@ -8,6 +8,7 @@ import type { RelayEvent } from "@/shared/api/types";
import { KIND_CHANNEL_MUTES } from "@/shared/constants/kinds";
import {
clearChannelMutesOutbox,
isMutesStoreSubsumedBy,
mergeStores,
parseMutePayload,
writeChannelMutesOutbox,
@@ -231,6 +232,41 @@ export class ChannelMuteSyncManager {
}
}
/**
* After a publish OK, fetch the authoritative retained head and report whether
* it subsumes the store we attempted to write. The relay returns OK for a
* superseded NIP-33 write as a no-op, so two windows racing distinct blobs
* from the same head can both get OK while only one blob is retained (Carl
* P1). Only a retained head that subsumes our store proves our click is
* durable on the relay; otherwise the outbox must be kept and retried.
*
* A failed/absent/undecryptable fetch cannot prove subsumption and returns
* false, so the durable click is retained and retried rather than dropped.
* Records the fetched head and observes it so a subsequent merge/retry folds
* the retained blob in.
*/
private async confirmRetainedHeadSubsumes(
store: ChannelMuteStore,
): Promise<boolean> {
try {
const events = await relayClient.fetchEvents({
kinds: [KIND_CHANNEL_MUTES],
authors: [this.pubkey],
"#d": [D_TAG],
limit: 1,
});
if (events.length === 0 || events[0].pubkey !== this.pubkey) return false;
const event = events[0];
this.recordRemoteHead(event.created_at);
const remote = await decryptAndParse(event);
if (!remote) return false;
this.observe(remote.store);
return isMutesStoreSubsumedBy(store, remote.store);
} catch {
return false;
}
}
private isIdenticalToLastPublished(store: ChannelMuteStore): boolean {
if (!this.lastPublishedStore) return false;
const lastKeys = Object.keys(this.lastPublishedStore.channels);
@@ -321,6 +357,20 @@ export class ChannelMuteSyncManager {
);
this.recordRemoteHead(event.created_at);
this.observe(merged);
// A publish OK is NOT proof of retention: the relay OKs a superseded
// NIP-33 write as a no-op, so a peer window racing a distinct blob from
// the same head can win retention while ours is silently dropped (Carl
// P1). Fetch the authoritative retained head and clear the durable outbox
// only when it subsumes what we wrote. If it does not (or the fetch
// could not prove it), keep the outbox and retry so the click is never
// lost; the retry's pre-publish max-merge folds the retained blob in.
if (this.destroyed) return;
const confirmed = await this.confirmRetainedHeadSubsumes(merged);
if (this.destroyed) return;
if (!confirmed) {
this.scheduleRetry(gen);
return;
}
// Only claim this store as the published head if it is still the current
// edit; a newer edit queued mid-flight owns lastPublishedStore now.
if (gen === this.pendingGeneration) {

View File

@@ -216,14 +216,15 @@ function legacyOutboxKey(pubkey: string, relayUrl: string): string {
* synchronously on every edit as a single unconditional `setItem` (no shared-
* key read-modify-write); resumed on next mount so an edit made <2s before
* quit/community-switch is never dropped. `queuedAt` stamps the write so resume
* replays only the newest queued blob (whole-blob LWW).
* replays only the newest queued blob (whole-blob LWW). Returns whether the
* intent is now durably held in this window's own v2 key (see `writeOwnOutbox`).
*/
export function writeChannelSectionsOutbox(
pubkey: string,
store: ChannelSectionStore,
relayUrl: string,
): void {
writeOwnOutbox(
): boolean {
return writeOwnOutbox(
OUTBOX_KEY_PREFIX,
pubkey,
relayUrl,

View File

@@ -334,6 +334,108 @@ test("timestamp clamp: published createdAt stays inside the relay future window"
}
});
// ─── Unreadable head: retain, never overwrite (Carl P1) ───────────────────────
// A pre-publish head event exists but cannot be decrypted (transient keychain
// fault, future NIP-44 scheme). We cannot inspect it to decide adopt-or-publish,
// so publishing our blob over it would blindly clobber authoritative state.
// Fix: `retain` — keep the durable pending edit and retry, never publish.
// Mutation: reverting `retain` to `publish` fires publishEvent and drops the
// head's unread state.
test("unreadable head (decrypt failure) retains the pending edit and retries, never publishing", async () => {
mock.method(relayClient, "fetchEvents", () =>
Promise.resolve([
{
pubkey: "pk-undec",
content: "bad-cipher",
created_at: 500,
id: "evt-undec",
},
]),
);
const publishCalls = [];
mock.method(relayClient, "publishEvent", (...args) => {
publishCalls.push(args);
return Promise.resolve();
});
const fw = makeFakeWindow();
const restore = installFakeWindow(fw);
const tauri = installTauriMock("{}");
try {
const manager = new ChannelSectionSyncManager("pk-undec", RELAY);
manager.publishSections(
makeSectionsStore([{ id: "s1", name: "Work", order: 0 }]),
);
fw._fireTimer();
await new Promise((r) => setTimeout(r, 20));
assert.equal(
publishCalls.length,
0,
"must not publish over a head we could not read",
);
assert.ok(
manager.getPendingStore() !== null,
"unreadable head must retain the pending edit",
);
assert.ok(
readChannelSectionsOutbox("pk-undec", RELAY) !== null,
"durable outbox must survive an unreadable head",
);
assert.ok(fw._hasTimer(), "a retry must be scheduled");
} finally {
tauri.restore();
restore();
mock.reset();
}
});
// A malformed payload that decrypts to non-JSON is equally unreadable:
// `decryptAndParse` throws in `JSON.parse` and returns null, so the manager
// must `retain`, not overwrite.
test("malformed (non-JSON) head payload retains the pending edit, never publishing", async () => {
mock.method(relayClient, "fetchEvents", () =>
Promise.resolve([
{
pubkey: "pk-badver",
content: "good-cipher",
created_at: 500,
id: "evt-badver",
},
]),
);
const publishCalls = [];
mock.method(relayClient, "publishEvent", (...args) => {
publishCalls.push(args);
return Promise.resolve();
});
const fw = makeFakeWindow();
const restore = installFakeWindow(fw);
// Decrypts cleanly but the plaintext is not JSON — parsing throws.
const tauri = installTauriMock("not-json{");
try {
const manager = new ChannelSectionSyncManager("pk-badver", RELAY);
manager.publishSections(
makeSectionsStore([{ id: "s1", name: "Work", order: 0 }]),
);
fw._fireTimer();
await new Promise((r) => setTimeout(r, 20));
assert.equal(
publishCalls.length,
0,
"must not publish over a head whose payload we could not parse",
);
assert.ok(
manager.getPendingStore() !== null,
"malformed head must retain the pending edit",
);
assert.ok(fw._hasTimer(), "a retry must be scheduled");
} finally {
tauri.restore();
restore();
mock.reset();
}
});
// 5. live-sub: undecryptable event on live path records head before decrypt
// Mutation test: removing recordRemoteHead before decrypt in the live callback
// leaves watermark at 0 after a live event.

View File

@@ -45,10 +45,17 @@ export type RemoteSections = {
* LWW and must be discarded in favour of the remote store so UI
* and relay converge (see the fix-2 design note). The manager
* hands the remote back to the hook and never publishes.
* - `retain` — a head event exists but could not be decrypted/parsed (future
* schema, transient keychain/decrypt fault, malformed payload).
* The client cannot inspect it to decide adopt-or-publish, so
* overwriting it would be blind data loss (Carl P1). Keep the
* durable pending edit and retry rather than clobber authoritative
* state the client could not read.
*/
type PublishDecision =
| { kind: "publish"; store: ChannelSectionStore }
| { kind: "adopt"; remote: RemoteSections };
| { kind: "adopt"; remote: RemoteSections }
| { kind: "retain" };
/**
* The canonical remote head as it stood when an edit was queued. The pre-publish
@@ -234,6 +241,22 @@ export class ChannelSectionSyncManager {
return this.pendingStore;
}
/**
* Re-drive the CURRENT pending edit's publish immediately without opening a
* new generation — used by the reconnect handler. Calling the public
* `publishSections()` there would bump the generation and reset
* `publishBaseline` to the just-fetched head, so a remote that won LWW while
* the edit was pending would be published over instead of adopted (Carl P1).
* Waking the existing generation keeps the frozen baseline, so the debounced
* cycle's pre-publish check still adopts a genuinely-advanced remote. No-op
* when nothing is pending.
*/
retryPendingPublish(): void {
if (this.pendingStore === null) return;
this.cancelPendingPublish();
this.startCycle();
}
/** True while an unpublished local edit is queued (debouncing or retrying). */
hasPendingEdit(): boolean {
return this.pendingStore !== null;
@@ -274,7 +297,7 @@ export class ChannelSectionSyncManager {
clearChannelSectionsOutbox(this.pubkey, this.relayUrl);
}
publishSections(store: ChannelSectionStore): void {
publishSections(store: ChannelSectionStore): boolean {
this.pendingStore = store;
++this.pendingGeneration;
// Freeze the canonical head this edit is racing against at queue time. The
@@ -291,8 +314,14 @@ export class ChannelSectionSyncManager {
// survives teardown and resumes on next mount (durable outbox). This
// window's own key is the only one written — a single unconditional
// setItem, never a shared-key read-modify-write; `queuedAt` stamps it so
// resume replays only the newest queued blob (whole-blob LWW).
writeChannelSectionsOutbox(this.pubkey, store, this.relayUrl);
// resume replays only the newest queued blob (whole-blob LWW). The returned
// flag reports whether the intent is now durably held, so a legacy replay
// can gate its consumption marker on a proven transfer.
const durable = writeChannelSectionsOutbox(
this.pubkey,
store,
this.relayUrl,
);
if (this.debounceTimer !== null) {
window.clearTimeout(this.debounceTimer);
}
@@ -306,6 +335,7 @@ export class ChannelSectionSyncManager {
this.debounceTimer = null;
this.startCycle();
}, DEBOUNCE_MS);
return durable;
}
/**
@@ -355,7 +385,11 @@ export class ChannelSectionSyncManager {
// Record the head after decrypt attempt so the watermark/head-tuple
// advance even for an undecryptable payload.
this.recordRemoteHead(event.created_at, event.id);
if (!remote) return { kind: "publish", store };
// A head event exists but we could not read it (future schema, transient
// decrypt fault, malformed payload). We cannot decide adopt-or-publish
// against state we cannot inspect, so retain the pending edit and retry
// rather than blindly overwrite authoritative state (Carl P1).
if (!remote) return { kind: "retain" };
// Sections use whole-blob LWW. Compare the fetched head against the
// baseline frozen when this edit was queued — NOT the live watermark,
// which a passive live event during debounce may already have advanced to
@@ -445,6 +479,12 @@ export class ChannelSectionSyncManager {
this.adoptRemote(decision.remote, gen);
return;
}
if (decision.kind === "retain") {
// Head exists but is unreadable — keep the durable pending edit and
// retry with backoff rather than overwrite state we could not inspect.
this.scheduleRetry(gen);
return;
}
const merged = decision.store;
if (this.isIdenticalToLastPublished(merged)) {
this.discardPending(gen);

View File

@@ -160,8 +160,8 @@ export function writeChannelSortOutbox(
pubkey: string,
store: ChannelSortStore,
relayUrl: string,
): void {
writeOwnOutbox(
): boolean {
return writeOwnOutbox(
OUTBOX_KEY_PREFIX,
pubkey,
relayUrl,

View File

@@ -252,12 +252,13 @@ test("timestamp clamp: published createdAt stays inside the relay future window"
let call = 0;
mock.method(relayClient, "fetchEvents", () => {
call++;
// First call primes lastRemoteCreatedAt to farFutureHead (undecryptable so
// no adopt); pre-publish call returns created_at=0 so the local edit wins.
// First call primes lastRemoteCreatedAt to farFutureHead; the pre-publish
// call returns a decryptable head at created_at=0 so the local edit wins
// LWW and publishes (an undecryptable head would now `retain`, not publish).
return Promise.resolve([
{
pubkey: "pk-clamp",
content: "bad-cipher",
content: "good-cipher",
created_at: call === 1 ? farFutureHead : 0,
id: "evt-clamp",
},
@@ -289,6 +290,179 @@ test("timestamp clamp: published createdAt stays inside the relay future window"
}
});
// ─── Unreadable head: retain, never overwrite (Carl P1) ───────────────────────
// A pre-publish head event exists but cannot be decrypted (transient keychain
// fault, future NIP-44 scheme). We cannot inspect it to decide adopt-or-publish,
// so publishing our blob over it would blindly clobber authoritative state.
// Fix: `retain` — keep the durable pending edit and retry, never publish.
// Mutation: reverting `retain` to `publish` fires publishEvent and drops the
// head's unread state.
test("unreadable head (decrypt failure) retains the pending edit and retries, never publishing", async () => {
mock.method(relayClient, "fetchEvents", () =>
Promise.resolve([
{
pubkey: "pk-undec",
content: "bad-cipher",
created_at: 500,
id: "evt-undec",
},
]),
);
const publishCalls = [];
mock.method(relayClient, "publishEvent", (...args) => {
publishCalls.push(args);
return Promise.resolve();
});
const fw = makeFakeWindow();
const restore = installFakeWindow(fw);
const tauri = installTauriMock("{}");
try {
const manager = new ChannelSortSyncManager("pk-undec", RELAY);
manager.publishSortPrefs(makeStore({ channels: "recent" }));
fw._fireTimer();
await new Promise((r) => setTimeout(r, 20));
assert.equal(
publishCalls.length,
0,
"must not publish over a head we could not read",
);
assert.ok(
manager.getPendingStore() !== null,
"unreadable head must retain the pending edit",
);
assert.ok(
readChannelSortOutbox("pk-undec", RELAY) !== null,
"durable outbox must survive an unreadable head",
);
assert.ok(fw._hasTimer(), "a retry must be scheduled");
} finally {
tauri.restore();
restore();
mock.reset();
}
});
// An unsupported/unparseable payload version is equally unreadable: it decrypts
// but `parseChannelSortPayload` rejects it, so the manager must `retain`, not
// overwrite.
test("unsupported head payload version retains the pending edit, never publishing", async () => {
mock.method(relayClient, "fetchEvents", () =>
Promise.resolve([
{
pubkey: "pk-badver",
content: "good-cipher",
created_at: 500,
id: "evt-badver",
},
]),
);
const publishCalls = [];
mock.method(relayClient, "publishEvent", (...args) => {
publishCalls.push(args);
return Promise.resolve();
});
const fw = makeFakeWindow();
const restore = installFakeWindow(fw);
// Decrypts cleanly but carries a future schema version the parser rejects.
const tauri = installTauriMock(JSON.stringify({ version: 2, groups: {} }));
try {
const manager = new ChannelSortSyncManager("pk-badver", RELAY);
manager.publishSortPrefs(makeStore({ channels: "recent" }));
fw._fireTimer();
await new Promise((r) => setTimeout(r, 20));
assert.equal(
publishCalls.length,
0,
"must not publish over a head whose payload version we do not support",
);
assert.ok(
manager.getPendingStore() !== null,
"unsupported head must retain the pending edit",
);
assert.ok(fw._hasTimer(), "a retry must be scheduled");
} finally {
tauri.restore();
restore();
mock.reset();
}
});
// ─── Reconnect keeps the frozen baseline (Carl P1) ────────────────────────────
// The reconnect handler re-drives a pending edit through retryPendingPublish(),
// NOT the public publishSortPrefs(). A remote that advanced while the edit was
// pending must be adopted on reconnect, not published over: retryPendingPublish
// keeps the generation and the baseline frozen at queue time, so the pre-publish
// check still sees the head as advanced and adopts. Mutation: reverting the
// reconnect handler to publishSortPrefs(pending) resets the baseline to the
// just-fetched head, so the pre-publish check sees no advancement and publishes
// the stale edit over the remote (adopt never fires, publishEvent does).
test("reconnect adopts a remote that advanced while the edit was pending, never publishing over it", async () => {
const REMOTE_KEY = "remote-group-won-lww";
let call = 0;
// call 1: prime lastRemoteHead to the baseline head (created_at 100).
// call 2+: the remote has since advanced to 200 (reconnect fetch + pre-publish
// fetch both see the advanced head).
mock.method(relayClient, "fetchEvents", () => {
call++;
return Promise.resolve([
{
pubkey: "pk-recon",
content: "good-cipher",
created_at: call === 1 ? 100 : 200,
id: call === 1 ? "evt-100" : "evt-200",
},
]);
});
const publishCalls = [];
mock.method(relayClient, "publishEvent", (...args) => {
publishCalls.push(args);
return Promise.resolve();
});
const fw = makeFakeWindow();
const restore = installFakeWindow(fw);
const tauri = installTauriMock(
JSON.stringify({ version: 1, groups: { [REMOTE_KEY]: "recent" } }),
);
try {
const manager = new ChannelSortSyncManager("pk-recon", RELAY);
const adopted = [];
manager.setOnRemoteAdopted((r) => adopted.push(r));
// Prime the baseline: the head stood at created_at 100 when the edit began.
await manager.fetchRemoteSortPrefs();
manager.publishSortPrefs(makeStore({ "local-group": "recent" }));
// Reconnect fires: the hook re-fetches (head now 200) then wakes the
// existing generation via retryPendingPublish — WITHOUT bumping generation
// or resetting the frozen baseline.
await manager.fetchRemoteSortPrefs();
manager.retryPendingPublish();
fw._fireTimer();
await new Promise((r) => setTimeout(r, 20));
assert.equal(
publishCalls.length,
0,
"must adopt the advanced remote, never publish the stale edit over it",
);
assert.equal(adopted.length, 1, "the advanced remote must be adopted");
assert.ok(
REMOTE_KEY in adopted[0].store.groups,
"adopted store must be the remote content that won LWW",
);
assert.equal(
manager.getPendingStore(),
null,
"the losing pending edit must be cleared on adopt",
);
} finally {
tauri.restore();
restore();
mock.reset();
}
});
// ─── Durable lane: outbox resume, retry, and cross-generation safety ──────────
// 5. Durable outbox resume: an edit made <2s before quit (destroy inside the

View File

@@ -44,10 +44,17 @@ export type RemoteSortPrefs = {
* and must be discarded in favour of the remote store so UI and
* relay converge. The manager hands the remote back to the hook
* and never publishes.
* - `retain` — a head event exists but could not be decrypted/parsed (future
* schema, transient keychain/decrypt fault, malformed payload).
* The client cannot inspect it to decide adopt-or-publish, so
* overwriting it would be blind data loss (Carl P1). Keep the
* durable pending edit and retry rather than clobber authoritative
* state the client could not read.
*/
type PublishDecision =
| { kind: "publish"; store: ChannelSortStore }
| { kind: "adopt"; remote: RemoteSortPrefs };
| { kind: "adopt"; remote: RemoteSortPrefs }
| { kind: "retain" };
/**
* The canonical remote head as it stood when an edit was queued. The pre-publish
@@ -232,6 +239,22 @@ export class ChannelSortSyncManager {
return this.pendingStore;
}
/**
* Re-drive the CURRENT pending edit's publish immediately without opening a
* new generation — used by the reconnect handler. Calling the public
* `publishSortPrefs()` there would bump the generation and reset
* `publishBaseline` to the just-fetched head, so a remote that won LWW while
* the edit was pending would be published over instead of adopted (Carl P1).
* Waking the existing generation keeps the frozen baseline, so the debounced
* cycle's pre-publish check still adopts a genuinely-advanced remote. No-op
* when nothing is pending.
*/
retryPendingPublish(): void {
if (this.pendingStore === null) return;
this.cancelPendingPublish();
this.startCycle();
}
/** True while an unpublished local edit is queued (debouncing or retrying). */
hasPendingEdit(): boolean {
return this.pendingStore !== null;
@@ -270,7 +293,7 @@ export class ChannelSortSyncManager {
clearChannelSortOutbox(this.pubkey, this.relayUrl);
}
publishSortPrefs(store: ChannelSortStore): void {
publishSortPrefs(store: ChannelSortStore): boolean {
this.pendingStore = store;
++this.pendingGeneration;
// Freeze the canonical head this edit is racing against at queue time so a
@@ -285,8 +308,10 @@ export class ChannelSortSyncManager {
// survives teardown and resumes on next mount (durable outbox). This
// window's own key is the only one written — a single unconditional
// setItem, never a shared-key read-modify-write; `queuedAt` stamps it so
// resume replays only the newest queued blob (whole-blob LWW).
writeChannelSortOutbox(this.pubkey, store, this.relayUrl);
// resume replays only the newest queued blob (whole-blob LWW). The returned
// flag reports whether the intent is now durably held, so a legacy replay
// can gate its consumption marker on a proven transfer.
const durable = writeChannelSortOutbox(this.pubkey, store, this.relayUrl);
if (this.debounceTimer !== null) {
window.clearTimeout(this.debounceTimer);
}
@@ -300,6 +325,7 @@ export class ChannelSortSyncManager {
this.debounceTimer = null;
this.startCycle();
}, DEBOUNCE_MS);
return durable;
}
/**
@@ -343,7 +369,11 @@ export class ChannelSortSyncManager {
// Record the head after decrypt attempt so the watermark/head-tuple
// advance even for an undecryptable payload.
this.recordRemoteHead(event.created_at, event.id);
if (!remote) return { kind: "publish", store };
// A head event exists but we could not read it (future schema, transient
// decrypt fault, malformed payload). We cannot decide adopt-or-publish
// against state we cannot inspect, so retain the pending edit and retry
// rather than blindly overwrite authoritative state (Carl P1).
if (!remote) return { kind: "retain" };
// Sort prefs use whole-blob LWW. Compare the fetched head against the
// baseline frozen when this edit was queued — NOT the live watermark. If
// the canonical head advanced since the edit began, the local edit lost
@@ -412,6 +442,12 @@ export class ChannelSortSyncManager {
this.adoptRemote(decision.remote, gen);
return;
}
if (decision.kind === "retain") {
// Head exists but is unreadable — keep the durable pending edit and
// retry with backoff rather than overwrite state we could not inspect.
this.scheduleRetry(gen);
return;
}
const merged = decision.store;
if (this.isIdenticalToLastPublished(merged)) {
this.discardPending(gen);

View File

@@ -156,6 +156,31 @@ test("mergeStores: equal updatedAt AND equal rev → starred=true wins (leaf)",
assert.deepEqual(result.channels.c, E(true, 100, 3));
});
test("mergeStores: same-second old-build click (rev 0) loses to an earlier new-build rev, heals next second", () => {
// ACCEPTED MIXED-FLEET RESIDUAL (Carl P1 #5). A new build wrote {starred:true,
// rev:2} at second 100; an old build then UNSTARS in the SAME second — old
// builds mint no rev, so its click reads rev:0. It loses the same-second tie
// to the earlier rev-2 entry: the later intent is suppressed until a
// strictly-later second carries it on the primary updatedAt key. This pins the
// current deterministic outcome; it is not a regression to fix here.
const newBuildStar = S(E(true, 100, 2));
const oldBuildUnstarSameSecond = S(E(false, 100, 0));
assert.deepEqual(
mergeStores(newBuildStar, oldBuildUnstarSameSecond).channels.c,
E(true, 100, 2),
"the earlier new-build rev-2 star wins the same-second tie — old click's unstar is lost",
);
// The same old-build unstar one second later wins outright on updatedAt: the
// residual self-heals the moment the user clicks again in a later second.
const oldBuildUnstarNextSecond = S(E(false, 101, 0));
assert.deepEqual(
mergeStores(newBuildStar, oldBuildUnstarNextSecond).channels.c,
E(false, 101, 0),
"a strictly-later-second old-build unstar wins — the residual is transient",
);
});
test("mergeStores: unstar with higher updatedAt overrides star", () => {
const result = mergeStores(S(E(true, 100, 9)), S(E(false, 999, 1)));
assert.deepEqual(result.channels.c, E(false, 999, 1));

View File

@@ -162,9 +162,21 @@ export function writeChannelStarsStore(
* `updatedAt` is primary so a strictly-later edit — from any build, whether it
* carries `rev` or (older build) reads `rev: 0` — wins outright. `rev` breaks
* only a same-second `updatedAt` tie: the ambiguous integer-second window the
* clock cannot resolve, where a click that minted `rev = maxSeen + 1` dominates
* any same-second state it observed. On a full tie (equal `updatedAt` AND equal
* `rev`) `true` wins as the deterministic leaf.
* clock cannot resolve, where a NEW-build click that minted `rev = maxSeen + 1`
* dominates same-second state it observed. On a full tie (equal `updatedAt` AND
* equal `rev`) `true` wins as the deterministic leaf.
*
* ACCEPTED MIXED-FLEET RESIDUAL (Carl P1 #5, no protocol change): an OLD build
* mints no `rev`, so its click reads `rev: 0`. A later old-build click that
* lands in the SAME integer second as an earlier new-build write carrying
* `rev >= 1` therefore loses that same-second tie — the old click's intent is
* suppressed until the user clicks again in a strictly-later second, when the
* primary `updatedAt` key carries it. This is bounded (one integer second,
* old-build writer only, self-heals on the next later-second click) and is no
* worse than the shipped LWW behavior; closing it would need a version
* migration we deliberately do not build. `mergeStores: same-second old-build
* click (rev 0) loses to an earlier new-build rev, heals next second` pins the
* exact current outcome.
*/
export function mergeStores(
a: ChannelStarStore,

View File

@@ -7,6 +7,7 @@ import { ChannelStarSyncManager } from "./channelStarsSync.ts";
import {
installFakeWindow,
installTauriMock,
installEchoTauri,
makeFakeWindow,
} from "./sidebarSyncTestHelpers.mjs";
@@ -159,19 +160,27 @@ test("destroy: is safe to call with no pending publish", () => {
// generation CAS in discardPending lets A's success null out B's pending+outbox.
test("A-in-flight → B-click → A-succeeds: B stays pending and B publishes", async () => {
let releaseFirst = null;
const publishedContents = [];
mock.method(relayClient, "fetchEvents", () => Promise.resolve([]));
mock.method(relayClient, "publishEvent", () => {
if (releaseFirst === null && publishedContents.length === 0) {
let publishCount = 0;
let storedHead = [];
mock.method(relayClient, "fetchEvents", () => Promise.resolve(storedHead));
mock.method(relayClient, "publishEvent", (event) => {
publishCount++;
if (publishCount === 1) {
// A reaches the relay; hold its ACK open until the test releases it, then
// record it as the retained head.
return new Promise((res) => {
releaseFirst = res;
releaseFirst = () => {
storedHead = [event];
res();
};
});
}
storedHead = [event];
return Promise.resolve();
});
const t = makeMultiTimerWindow();
const restore = installFakeWindow(t.win);
const tauri = installTauriMock("{}");
const tauri = installEchoTauri("pk-ab");
try {
const manager = new ChannelStarSyncManager("pk-ab", RELAY);
const storeA = makeStore({ a: E(true, 100, 1) });
@@ -203,7 +212,9 @@ test("A-in-flight → B-click → A-succeeds: B stays pending and B publishes",
"older A completion leaves B outbox",
);
// B's own debounce fires and B reaches the relay (published) with no kick.
// B's own debounce fires and B reaches the relay with no kick; the
// post-publish retained-head fetch reads B's own write back and confirms
// subsumption, so B's outbox clears.
const capturedBefore = tauri.capturedPlaintext();
await t.fireDelay(2000);
for (let i = 0; i < 50; i++) await Promise.resolve();
@@ -215,7 +226,7 @@ test("A-in-flight → B-click → A-succeeds: B stays pending and B publishes",
assert.equal(
manager.getPendingStarStore(),
null,
"B cleared after publish",
"B cleared after confirmed publish",
);
assert.equal(
readChannelStarsOutbox("pk-ab", RELAY),
@@ -235,19 +246,21 @@ test("A-in-flight → B-click → A-succeeds: B stays pending and B publishes",
test("A-in-flight → B-click → A-fails: B remains pending and B publishes", async () => {
let rejectFirst = null;
let publishCount = 0;
mock.method(relayClient, "fetchEvents", () => Promise.resolve([]));
mock.method(relayClient, "publishEvent", () => {
let storedHead = [];
mock.method(relayClient, "fetchEvents", () => Promise.resolve(storedHead));
mock.method(relayClient, "publishEvent", (event) => {
publishCount++;
if (publishCount === 1) {
return new Promise((_res, rej) => {
rejectFirst = () => rej(new Error("socket error"));
});
}
storedHead = [event];
return Promise.resolve();
});
const t = makeMultiTimerWindow();
const restore = installFakeWindow(t.win);
const tauri = installTauriMock("{}");
const tauri = installEchoTauri("pk-abfail");
try {
const manager = new ChannelStarSyncManager("pk-abfail", RELAY);
manager.publishStars(makeStore({ a: E(true, 100, 1) }));
@@ -268,7 +281,8 @@ test("A-in-flight → B-click → A-fails: B remains pending and B publishes", a
"B outbox intact after A's failure",
);
// B's debounce fires and B publishes successfully.
// B's debounce fires and B publishes successfully; the retained-head fetch
// confirms B's own write and clears it.
await t.fireDelay(2000);
for (let i = 0; i < 50; i++) await Promise.resolve();
const captured = tauri.capturedPlaintext();
@@ -290,15 +304,17 @@ test("A-in-flight → B-click → A-fails: B remains pending and B publishes", a
// edit stranded (Will's "make another change to kick it" symptom).
test("failed publish schedules a bounded-backoff retry and keeps the pending edit", async () => {
let publishCount = 0;
mock.method(relayClient, "fetchEvents", () => Promise.resolve([]));
mock.method(relayClient, "publishEvent", () => {
let storedHead = [];
mock.method(relayClient, "fetchEvents", () => Promise.resolve(storedHead));
mock.method(relayClient, "publishEvent", (event) => {
publishCount++;
if (publishCount === 1) return Promise.reject(new Error("timeout"));
storedHead = [event];
return Promise.resolve();
});
const t = makeMultiTimerWindow();
const restore = installFakeWindow(t.win);
const tauri = installTauriMock("{}");
const tauri = installEchoTauri("pk-retry");
try {
const manager = new ChannelStarSyncManager("pk-retry", RELAY);
manager.publishStars(makeStore({ a: E(true, 100, 1) }));
@@ -309,7 +325,8 @@ test("failed publish schedules a bounded-backoff retry and keeps the pending edi
);
assert.ok(t.hasDelay(2000), "a retry timer at RETRY_BASE_MS is scheduled");
// The retry fires and the second publish succeeds → pending cleared.
// The retry fires and the second publish succeeds; the retained-head fetch
// confirms the write → pending cleared.
await t.fireDelay(2000);
for (let i = 0; i < 50; i++) await Promise.resolve();
assert.equal(publishCount, 2, "retry re-published");
@@ -326,6 +343,72 @@ test("failed publish schedules a bounded-backoff retry and keeps the pending edi
}
});
// ─── Retention confirmation (Carl P1): OK is not proof of retention ───────────
// The relay OKs a superseded NIP-33 write as a no-op, so two windows racing
// distinct blobs from the same head can both get OK while only one is retained.
// The loser must NOT clear its durable outbox on OK alone: it fetches the
// authoritative retained head and clears only when that head subsumes its
// write. A retained head carrying a peer's distinct blob does not subsume the
// loser's click, so the outbox is kept and a retry is scheduled.
// Mutation: clearing on OK alone (dropping confirmRetainedHeadSubsumes) would
// null the pending edit here and lose the click.
test("publish OK but a peer blob is retained: loser keeps its outbox and retries", async () => {
let publishCount = 0;
// The retained head is a peer window's distinct blob from the same base —
// it does NOT contain our channel `a`, so it cannot subsume our write.
let storedHead = [];
mock.method(relayClient, "fetchEvents", () => Promise.resolve(storedHead));
const tauri = installEchoTauri("pk-loser");
mock.method(relayClient, "publishEvent", (event) => {
publishCount++;
if (publishCount === 1) {
// Our write is OK'd by the relay but immediately superseded: the retained
// head is the peer's blob for a different channel, minted through the same
// echo seam so it decrypts.
storedHead = [tauri.mintHead(makeStore({ z: E(true, 200, 5) }), 100)];
return Promise.resolve();
}
// The retry (which max-merges the peer head in) is retained.
storedHead = [event];
return Promise.resolve();
});
const t = makeMultiTimerWindow();
const restore = installFakeWindow(t.win);
try {
const manager = new ChannelStarSyncManager("pk-loser", RELAY);
manager.publishStars(makeStore({ a: E(true, 100, 1) }));
await t.fireDelay(2000); // publish OK, but peer blob is what's retained
for (let i = 0; i < 50; i++) await Promise.resolve();
assert.ok(
manager.getPendingStarStore() !== null,
"unconfirmed publish keeps the pending edit",
);
assert.ok(
readChannelStarsOutbox("pk-loser", RELAY),
"loser keeps its durable outbox — OK is not proof of retention",
);
assert.ok(t.hasDelay(2000), "a retry is scheduled");
// The retry re-publishes the max-merge of our click and the peer head; this
// time it is retained (subsumes our `a`) and the outbox clears.
await t.fireDelay(2000);
for (let i = 0; i < 50; i++) await Promise.resolve();
assert.equal(publishCount, 2, "loser retried");
assert.equal(
manager.getPendingStarStore(),
null,
"pending cleared once the retained head subsumes our click",
);
manager.destroy();
} finally {
tauri.restore();
restore();
mock.reset();
}
});
// ─── Boot seed-publish guard (the revert-fix regression suite) ─────────────────
test("revert-fix: fetch failed (error) does not trigger seed-publish via bootstrap", async () => {

View File

@@ -8,6 +8,7 @@ import type { RelayEvent } from "@/shared/api/types";
import { KIND_CHANNEL_STARS } from "@/shared/constants/kinds";
import {
clearChannelStarsOutbox,
isStarsStoreSubsumedBy,
mergeStores,
parseStarPayload,
writeChannelStarsOutbox,
@@ -231,6 +232,41 @@ export class ChannelStarSyncManager {
}
}
/**
* After a publish OK, fetch the authoritative retained head and report whether
* it subsumes the store we attempted to write. The relay returns OK for a
* superseded NIP-33 write as a no-op, so two windows racing distinct blobs
* from the same head can both get OK while only one blob is retained (Carl
* P1). Only a retained head that subsumes our store proves our click is
* durable on the relay; otherwise the outbox must be kept and retried.
*
* A failed/absent/undecryptable fetch cannot prove subsumption and returns
* false, so the durable click is retained and retried rather than dropped.
* Records the fetched head and observes it so a subsequent merge/retry folds
* the retained blob in.
*/
private async confirmRetainedHeadSubsumes(
store: ChannelStarStore,
): Promise<boolean> {
try {
const events = await relayClient.fetchEvents({
kinds: [KIND_CHANNEL_STARS],
authors: [this.pubkey],
"#d": [D_TAG],
limit: 1,
});
if (events.length === 0 || events[0].pubkey !== this.pubkey) return false;
const event = events[0];
this.recordRemoteHead(event.created_at);
const remote = await decryptAndParse(event);
if (!remote) return false;
this.observe(remote.store);
return isStarsStoreSubsumedBy(store, remote.store);
} catch {
return false;
}
}
private isIdenticalToLastPublished(store: ChannelStarStore): boolean {
if (!this.lastPublishedStore) return false;
const lastKeys = Object.keys(this.lastPublishedStore.channels);
@@ -321,6 +357,20 @@ export class ChannelStarSyncManager {
);
this.recordRemoteHead(event.created_at);
this.observe(merged);
// A publish OK is NOT proof of retention: the relay OKs a superseded
// NIP-33 write as a no-op, so a peer window racing a distinct blob from
// the same head can win retention while ours is silently dropped (Carl
// P1). Fetch the authoritative retained head and clear the durable outbox
// only when it subsumes what we wrote. If it does not (or the fetch
// could not prove it), keep the outbox and retry so the click is never
// lost; the retry's pre-publish max-merge folds the retained blob in.
if (this.destroyed) return;
const confirmed = await this.confirmRetainedHeadSubsumes(merged);
if (this.destroyed) return;
if (!confirmed) {
this.scheduleRetry(gen);
return;
}
// Only claim this store as the published head if it is still the current
// edit; a newer edit queued mid-flight owns lastPublishedStore now.
if (gen === this.pendingGeneration) {

View File

@@ -49,6 +49,73 @@ export function installFakeWindow(fw) {
};
}
// A faithful crypto seam for merge-lane retention-confirmation tests: encrypt
// maps each plaintext to a unique ciphertext, decrypt recovers it, and
// sign_event stamps the manager's `pubkey` and echoes the ciphertext as
// `content`. A published event therefore round-trips through a later fetch —
// modelling the relay retaining our own write so the post-publish subsumption
// check can read it back. `pubkey` must equal the manager's pubkey so the
// `events[0].pubkey === this.pubkey` guard passes.
export function installEchoTauri(pubkey) {
const orig = globalThis.window?.__TAURI_INTERNALS__;
if (typeof globalThis.window === "undefined") globalThis.window = {};
const cipherToPlain = new Map();
let seq = 0;
let captured = null;
globalThis.window.__TAURI_INTERNALS__ = {
invoke: (cmd, args) => {
if (cmd === "nip44_encrypt_to_self") {
captured = args?.plaintext ?? null;
const ct = `ct-${seq++}`;
cipherToPlain.set(ct, args?.plaintext ?? "");
return Promise.resolve(ct);
}
if (cmd === "nip44_decrypt_from_self") {
const pt = cipherToPlain.get(args?.ciphertext);
if (pt === undefined)
return Promise.reject(new Error("decrypt failed"));
return Promise.resolve(pt);
}
if (cmd === "sign_event")
return Promise.resolve(
JSON.stringify({
id: `evt-${seq}`,
pubkey,
content: args?.content ?? "",
created_at: args?.createdAt ?? 0,
kind: args?.kind ?? 0,
tags: args?.tags ?? [],
sig: "s",
}),
);
return Promise.reject(new Error(`unmocked: ${cmd}`));
},
};
return {
restore: () => {
if (orig !== undefined) globalThis.window.__TAURI_INTERNALS__ = orig;
else delete globalThis.window.__TAURI_INTERNALS__;
},
capturedPlaintext: () => captured,
// Mint a decryptable relay event for an arbitrary store payload — models a
// peer window's retained head. Registers its ciphertext in the same map the
// decrypt path reads, so the manager decrypts it back to `store`.
mintHead: (store, createdAt = 0) => {
const ct = `ct-peer-${seq++}`;
cipherToPlain.set(ct, JSON.stringify(store));
return {
id: `peer-${seq}`,
pubkey,
content: ct,
created_at: createdAt,
kind: 0,
tags: [],
sig: "s",
};
},
};
}
export function installTauriMock(goodCipherPayload) {
const orig = globalThis.window?.__TAURI_INTERNALS__;
if (typeof globalThis.window === "undefined") globalThis.window = {};

View File

@@ -245,6 +245,14 @@ function parseEnvelope<T>(
* of a proven-stale foreign key can never race a rewrite. Best-effort: the
* in-memory pending edit still drives this session's publish even if the
* persisted copy could not be written.
*
* Returns whether the fresh key's `setItem` succeeded — i.e. whether the intent
* is now durably held in this window's own v2 key. A whole-blob legacy replay
* gates its consumption marker on this: the marker may be written only once the
* transfer is durable, so a `setItem` failure (quota) leaves the legacy record
* replayable on a later boot rather than silently consumed. A failure to drop
* this window's superseded keys does NOT falsify durability of the fresh key,
* so it does not lower the return value.
*/
export function writeOwnOutbox(
prefix: string,
@@ -252,21 +260,30 @@ export function writeOwnOutbox(
relayUrl: string,
store: unknown,
nowSecs: number = Math.floor(Date.now() / 1_000),
): void {
): boolean {
const base = ownKeyBase(prefix, pubkey, relayUrl);
let key: string;
try {
const key = nextOwnKey(base);
key = nextOwnKey(base);
window.localStorage.setItem(
key,
JSON.stringify({ store, queuedAt: nowSecs }),
);
// Drop this window's now-superseded own keys (all but the one just written).
} catch {
// The fresh key could not be persisted — the intent is NOT durably held.
return false;
}
// The fresh key is durable. Best-effort drop of this window's now-superseded
// own keys (all but the one just written); a failure here only leaves a stale
// own key that the next publish/boot re-evaluates.
try {
for (const k of ownKeys(base)) {
if (k !== key) window.localStorage.removeItem(k);
}
} catch {
// Best-effort durability.
// Ignore — durability of the fresh key already holds.
}
return true;
}
/** Remove all of this window's own outbox keys (its edit published or a no-op). */

View File

@@ -275,3 +275,270 @@ test("equal-timestamp tie-break applies the lower event id (relay canonical winn
window.__TAURI_INTERNALS__ = origTauri;
}
});
// Carl P1-sections regression: on reconnect the hook must wake the EXISTING
// pending edit (retryPendingPublish) rather than re-queue it via
// publishSections(). A re-queue bumps the generation and resets the frozen
// publishBaseline to the just-fetched head, so a remote that won whole-blob LWW
// while the edit was pending would be published over instead of adopted. Here
// the head advances (100 → 200) while a local edit is pending; on reconnect the
// advanced remote must be adopted (the losing local section dropped) and NOTHING
// published. Reverting the reconnect handler to publishSections(pending) resets
// the baseline and publishes the stale edit.
test("reconnect adopts a remote that advanced while the edit was pending, never publishing over it", async () => {
const { act, cleanup, renderHook } = await import("@testing-library/react");
const { relayClient } = await import("@/shared/api/relayClient");
const { useChannelSections } = await import("./useChannelSections.ts");
const origFetch = relayClient.fetchEvents;
const origLive = relayClient.subscribeLive;
const origReconnect = relayClient.subscribeToReconnects;
const origPublish = relayClient.publishEvent;
const origTauri = window.__TAURI_INTERNALS__;
let reconnect = null;
// A single mutable head; bumped to created_at 200 (a remote that won LWW)
// right before the reconnect fires.
let head = {
pubkey: "pk-sec-recon",
content: "remote-cipher",
created_at: 100,
id: "evt-100",
};
const publishCalls = [];
relayClient.fetchEvents = async () => [head];
relayClient.subscribeLive = async () => async () => {};
relayClient.subscribeToReconnects = (cb) => {
reconnect = cb;
return () => {};
};
relayClient.publishEvent = async (...args) => {
publishCalls.push(args);
};
window.__TAURI_INTERNALS__ = {
invoke: (cmd) => {
// The head decrypts to a remote store with a single "remote" section.
if (cmd === "nip44_decrypt_from_self")
return Promise.resolve(
JSON.stringify({
version: 1,
sections: [{ id: "remote", name: "Remote", order: 0 }],
assignments: {},
}),
);
if (cmd === "nip44_encrypt_to_self") return Promise.resolve("ct");
if (cmd === "sign_event")
return Promise.resolve(
JSON.stringify({
id: "signed",
pubkey: "pk-sec-recon",
content: "ct",
created_at: 0,
kind: 30078,
tags: [],
sig: "s",
}),
);
return Promise.reject(new Error(`unmocked ${cmd}`));
},
};
const pubkey = "pk-sec-recon";
const relayUrl = "wss://r.recon";
let hook = null;
try {
await act(async () => {
hook = renderHook(() => useChannelSections(pubkey, relayUrl));
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
});
assert.ok(reconnect, "reconnect handler installed");
// Local edit while the head stands at created_at 100 — the baseline the
// edit is frozen against.
await act(async () => {
hook.result.current.createSection("Local");
});
assert.ok(
hook.result.current.sections.some((s) => s.name === "Local"),
"optimistic local section applied",
);
// The remote advances to created_at 200 (a peer won LWW), then reconnect
// fires: the hook re-fetches and wakes the existing generation.
head = {
pubkey: "pk-sec-recon",
content: "remote-cipher",
created_at: 200,
id: "evt-200",
};
await act(async () => {
reconnect();
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
});
assert.equal(
publishCalls.length,
0,
"must adopt the advanced remote on reconnect, never publish the stale edit over it",
);
// On adopt the whole-blob store is replaced by the remote (only a "remote"
// section), so the losing local edit is dropped. Under the mutation
// (re-queue) the pending edit is never adopted away and "Local" survives.
assert.deepEqual(
hook.result.current.sections.map((s) => s.id),
["remote"],
"the losing local edit must be adopted away by the advanced remote",
);
hook.unmount();
} finally {
cleanup();
relayClient.fetchEvents = origFetch;
relayClient.subscribeLive = origLive;
relayClient.subscribeToReconnects = origReconnect;
relayClient.publishEvent = origPublish;
window.__TAURI_INTERNALS__ = origTauri;
}
});
// Thufir pass-3 regression (sections lane): a legacy replay whose durability
// transfer into this window's own v2 key fails (quota) must NOT write the
// consumed marker. Otherwise the marker permanently suppresses the only copy of
// the legacy edit on every later boot — silent loss of exactly the durability
// this PR guarantees. The hook now gates markLegacyConsumed on the `durable`
// flag publishSections() returns; removing that guard writes the marker
// unconditionally and this test goes red.
test("legacy replay whose v2 transfer fails (quota) does not write the consumed marker", async () => {
const { act, cleanup, renderHook } = await import("@testing-library/react");
const { relayClient } = await import("@/shared/api/relayClient");
const { useChannelSections } = await import("./useChannelSections.ts");
const { readChannelSectionsOutbox } = await import(
"./channelSectionsStorage.ts"
);
const { normalizeRelayUrl } = await import("@/shared/lib/normalizeRelayUrl");
const origFetch = relayClient.fetchEvents;
const origLive = relayClient.subscribeLive;
const origReconnect = relayClient.subscribeToReconnects;
const origPublish = relayClient.publishEvent;
const origTauri = window.__TAURI_INTERNALS__;
const origLocalStorage = window.localStorage;
const pubkey = "pk-sec-quota";
const relayUrl = "wss://r.sec-quota";
const scope = `${pubkey}:${encodeURIComponent(normalizeRelayUrl(relayUrl))}`;
const legacyKey = `buzz-channel-sections-outbox.v1:${scope}`;
const v2Prefix = `buzz-channel-sections-outbox.v1:${scope}:`; // nonce/seq suffix
const legacyRaw = JSON.stringify({
store: {
version: 1,
sections: [{ id: "legacy", name: "Legacy", order: 0 }],
assignments: {},
},
queuedAt: 0,
});
// A backing localStorage that throws on any v2 outbox write (the quota
// failure), while allowing the legacy read, the marker write, and applied
// state through — so the ONLY failure is the durability transfer.
const map = new Map([[legacyKey, legacyRaw]]);
const throwingStorage = {
getItem: (k) => (map.has(k) ? map.get(k) : null),
setItem: (k, v) => {
if (k.startsWith(v2Prefix)) throw new Error("QuotaExceededError");
map.set(k, String(v));
},
removeItem: (k) => map.delete(k),
clear: () => map.clear(),
get length() {
return map.size;
},
key: (i) => [...map.keys()][i] ?? null,
};
const head = null;
relayClient.fetchEvents = async () => (head ? [head] : []);
relayClient.subscribeLive = async () => async () => {};
relayClient.subscribeToReconnects = () => () => {};
relayClient.publishEvent = async () => {};
window.__TAURI_INTERNALS__ = {
invoke: (cmd) => {
if (cmd === "nip44_encrypt_to_self") return Promise.resolve("ct");
if (cmd === "sign_event")
return Promise.resolve(
JSON.stringify({
id: "signed",
pubkey,
content: "ct",
created_at: 0,
kind: 30078,
tags: [],
sig: "s",
}),
);
return Promise.reject(new Error(`unmocked ${cmd}`));
},
};
let hook = null;
try {
// Seed a prior watermark so bootstrap holds (no first-sync seed) and the
// legacy blob is the sole outbox record resumed.
Object.defineProperty(window, "localStorage", {
value: throwingStorage,
configurable: true,
});
window.localStorage.setItem(
`buzz-sync-watermark.v1:channel-sections:${pubkey}:${encodeURIComponent(
normalizeRelayUrl(relayUrl),
)}`,
"1700000000",
);
await act(async () => {
hook = renderHook(() => useChannelSections(pubkey, relayUrl));
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
});
// The marker must NOT have been written: the v2 transfer threw.
const markerWritten = [...map.keys()].some((k) =>
k.includes("-legacy-consumed:"),
);
assert.equal(
markerWritten,
false,
"consumed marker must not be written after a failed v2 transfer",
);
// The legacy blob is still enumerated as replayable — not silently lost.
const resumed = readChannelSectionsOutbox(pubkey, relayUrl);
assert.ok(resumed !== null, "legacy blob must remain replayable");
assert.equal(
resumed.store.sections[0]?.id,
"legacy",
"the exact legacy intent survives for a later boot",
);
assert.ok(
resumed.legacyRawToConsume !== null,
"legacy record still reports itself for consumption on a later boot",
);
hook.unmount();
} finally {
cleanup();
Object.defineProperty(window, "localStorage", {
value: origLocalStorage,
configurable: true,
});
relayClient.fetchEvents = origFetch;
relayClient.subscribeLive = origLive;
relayClient.subscribeToReconnects = origReconnect;
relayClient.publishEvent = origPublish;
window.__TAURI_INTERNALS__ = origTauri;
}
});

View File

@@ -155,13 +155,17 @@ export function useChannelSections(
const outbox = readChannelSectionsOutbox(pubkey, relayUrl);
if (outbox) {
// publishSections synchronously copies the intent into this window's
// own v2 key, so marking the legacy blob consumed afterward can never
// lose it: a crash before the marker write replays the legacy blob once
// more, a crash after resumes it from the v2 key. The marker is what
// stops the never-deleted legacy key republishing above the head every
// boot (Thufir pass-2 resurrection finding).
managerRef.current?.publishSections(outbox.store);
if (outbox.legacyRawToConsume !== null) {
// own v2 key and returns whether that transfer is durable. Mark the
// legacy blob consumed ONLY when it is: a `setItem` failure (quota)
// returns false, so the marker is not written and the legacy record
// stays replayable on a later boot rather than being silently
// suppressed (Thufir pass-3 finding). A crash between a durable
// transfer and the marker write replays the legacy blob once more, a
// crash after resumes it from the v2 key. The marker is what stops the
// never-deleted legacy key republishing above the head every boot
// (Thufir pass-2 resurrection finding).
const durable = managerRef.current?.publishSections(outbox.store);
if (durable && outbox.legacyRawToConsume !== null) {
markChannelSectionsLegacyConsumed(
pubkey,
relayUrl,
@@ -270,10 +274,13 @@ export function useChannelSections(
if (result.status === "found") {
setStore(applyRemote(result.data));
}
const pending = managerRef.current?.getPendingStore();
if (pending) {
managerRef.current?.publishSections(pending);
}
// Wake the existing pending edit's cycle rather than re-queueing it via
// publishSections(): a re-queue would bump the generation and reset the
// frozen publishBaseline to the just-fetched head, so a remote that won
// LWW while the edit was pending would be published over instead of
// adopted (Carl P1). retryPendingPublish keeps the baseline, so the
// pre-publish check still adopts a genuinely-advanced remote.
managerRef.current?.retryPendingPublish();
});
});
return () => {

View File

@@ -228,3 +228,266 @@ test("equal-timestamp tie-break applies the lower event id (relay canonical winn
window.__TAURI_INTERNALS__ = origTauri;
}
});
// Carl P1-sort regression: on reconnect the hook must wake the EXISTING pending
// edit (retryPendingPublish) rather than re-queue it via publishSortPrefs().
// A re-queue bumps the generation and resets the frozen publishBaseline to the
// just-fetched head, so a remote that won whole-blob LWW while the edit was
// pending would be published over instead of adopted. Here the head advances
// (100 → 200) while a local edit is pending; on reconnect the advanced remote
// must be adopted and NOTHING published. Reverting the reconnect handler to
// publishSortPrefs(pending) resets the baseline and publishes the stale edit.
test("reconnect adopts a remote that advanced while the edit was pending, never publishing over it", async () => {
const { act, cleanup, renderHook } = await import("@testing-library/react");
const { relayClient } = await import("@/shared/api/relayClient");
const { useChannelSortPreference } = await import(
"./useChannelSortPreference.ts"
);
const origFetch = relayClient.fetchEvents;
const origLive = relayClient.subscribeLive;
const origReconnect = relayClient.subscribeToReconnects;
const origPublish = relayClient.publishEvent;
const origTauri = window.__TAURI_INTERNALS__;
let reconnect = null;
// A single mutable head the fetch returns; bumped to created_at 200 (a remote
// that won LWW) right before the reconnect fires.
let head = {
pubkey: "pk-sort-recon",
content: "remote-cipher",
created_at: 100,
id: "evt-100",
};
const publishCalls = [];
relayClient.fetchEvents = async () => [head];
relayClient.subscribeLive = async () => async () => {};
relayClient.subscribeToReconnects = (cb) => {
reconnect = cb;
return () => {};
};
relayClient.publishEvent = async (...args) => {
publishCalls.push(args);
};
window.__TAURI_INTERNALS__ = {
invoke: (cmd) => {
// The head decrypts to a remote store setting `remote-group`.
if (cmd === "nip44_decrypt_from_self")
return Promise.resolve(
JSON.stringify({ version: 1, groups: { "remote-group": "recent" } }),
);
if (cmd === "nip44_encrypt_to_self") return Promise.resolve("ct");
if (cmd === "sign_event")
return Promise.resolve(
JSON.stringify({
id: "signed",
pubkey: "pk-sort-recon",
content: "ct",
created_at: 0,
kind: 30078,
tags: [],
sig: "s",
}),
);
return Promise.reject(new Error(`unmocked ${cmd}`));
},
};
const pubkey = "pk-sort-recon";
const relayUrl = "wss://r.recon";
let hook = null;
try {
await act(async () => {
hook = renderHook(() => useChannelSortPreference(pubkey, relayUrl));
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
});
assert.ok(reconnect, "reconnect handler installed");
// Local edit while the head stands at created_at 100 — the baseline the
// edit is frozen against.
await act(async () => {
hook.result.current.setSortModeFor("channels", "recent");
});
// The remote advances to created_at 200 (a peer won LWW), then reconnect
// fires: the hook re-fetches and wakes the existing generation.
head = {
pubkey: "pk-sort-recon",
content: "remote-cipher",
created_at: 200,
id: "evt-200",
};
await act(async () => {
reconnect();
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
});
assert.equal(
publishCalls.length,
0,
"must adopt the advanced remote on reconnect, never publish the stale edit over it",
);
// On adopt the whole-blob store is replaced by the remote (which has no
// `channels` entry), so the losing local edit is dropped and `channels`
// reverts to the default. Under the mutation (re-queue) the pending edit is
// never adopted away and `channels` stays "recent".
assert.equal(
hook.result.current.sortModeFor("channels"),
"alpha",
"the losing local edit must be adopted away by the advanced remote",
);
assert.equal(
hook.result.current.sortModeFor("remote-group"),
"recent",
"the advanced remote store must be adopted",
);
hook.unmount();
} finally {
cleanup();
relayClient.fetchEvents = origFetch;
relayClient.subscribeLive = origLive;
relayClient.subscribeToReconnects = origReconnect;
relayClient.publishEvent = origPublish;
window.__TAURI_INTERNALS__ = origTauri;
}
});
// Thufir pass-3 blocker (Carl P1 durability): a legacy (old-build) blob is
// replayed by copying it into this window's own v2 outbox key, then writing a
// "consumed" marker. writeOwnOutbox swallows setItem failures; the hook must
// therefore write the marker ONLY when the v2 transfer actually succeeded.
// Here the v2 outbox setItem throws (quota), so the transfer failed: the marker
// must NOT be written, leaving the legacy blob replayable on a later boot rather
// than silently suppressed. Mutation: writing the marker unconditionally (the
// pre-fix code) consumes the legacy blob after a failed transfer and it is lost.
test("legacy replay whose v2 transfer fails (quota) does not write the consumed marker", async () => {
const { act, cleanup, renderHook } = await import("@testing-library/react");
const { relayClient } = await import("@/shared/api/relayClient");
const { useChannelSortPreference } = await import(
"./useChannelSortPreference.ts"
);
const { readChannelSortOutbox } = await import("./channelSortPreference.ts");
const { normalizeRelayUrl } = await import("@/shared/lib/normalizeRelayUrl");
const origFetch = relayClient.fetchEvents;
const origLive = relayClient.subscribeLive;
const origReconnect = relayClient.subscribeToReconnects;
const origPublish = relayClient.publishEvent;
const origTauri = window.__TAURI_INTERNALS__;
const origLocalStorage = window.localStorage;
const pubkey = "pk-quota";
const relayUrl = "wss://r.quota";
const scope = `${pubkey}:${encodeURIComponent(normalizeRelayUrl(relayUrl))}`;
const legacyKey = `buzz-channel-sort-outbox.v1:${scope}`;
const v2Prefix = `buzz-channel-sort-outbox.v1:${scope}:`; // nonce/seq suffix
const legacyRaw = JSON.stringify({
store: { version: 1, groups: { "legacy-group": "recent" } },
queuedAt: 0,
});
// A backing localStorage that throws on any v2 outbox write (the quota
// failure), while allowing the legacy read, the marker write, and applied
// state through — so the ONLY failure is the durability transfer.
const map = new Map([[legacyKey, legacyRaw]]);
const throwingStorage = {
getItem: (k) => (map.has(k) ? map.get(k) : null),
setItem: (k, v) => {
if (k.startsWith(v2Prefix)) throw new Error("QuotaExceededError");
map.set(k, String(v));
},
removeItem: (k) => map.delete(k),
clear: () => map.clear(),
get length() {
return map.size;
},
key: (i) => [...map.keys()][i] ?? null,
};
const head = null;
relayClient.fetchEvents = async () => (head ? [head] : []);
relayClient.subscribeLive = async () => async () => {};
relayClient.subscribeToReconnects = () => () => {};
relayClient.publishEvent = async () => {};
window.__TAURI_INTERNALS__ = {
invoke: (cmd) => {
if (cmd === "nip44_encrypt_to_self") return Promise.resolve("ct");
if (cmd === "sign_event")
return Promise.resolve(
JSON.stringify({
id: "signed",
pubkey,
content: "ct",
created_at: 0,
kind: 30078,
tags: [],
sig: "s",
}),
);
return Promise.reject(new Error(`unmocked ${cmd}`));
},
};
let hook = null;
try {
// Seed a prior watermark so bootstrap holds (no first-sync seed) and the
// legacy blob is the sole outbox record resumed.
Object.defineProperty(window, "localStorage", {
value: throwingStorage,
configurable: true,
});
window.localStorage.setItem(
`buzz-sync-watermark.v1:channel-sort:${pubkey}:${encodeURIComponent(
normalizeRelayUrl(relayUrl),
)}`,
"1700000000",
);
await act(async () => {
hook = renderHook(() => useChannelSortPreference(pubkey, relayUrl));
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
});
// The marker must NOT have been written: the v2 transfer threw.
const markerWritten = [...map.keys()].some((k) =>
k.includes("-legacy-consumed:"),
);
assert.equal(
markerWritten,
false,
"consumed marker must not be written after a failed v2 transfer",
);
// The legacy blob is still enumerated as replayable — not silently lost.
const resumed = readChannelSortOutbox(pubkey, relayUrl);
assert.ok(resumed !== null, "legacy blob must remain replayable");
assert.equal(
resumed.store.groups["legacy-group"],
"recent",
"the exact legacy intent survives for a later boot",
);
assert.ok(
resumed.legacyRawToConsume !== null,
"legacy record still reports itself for consumption on a later boot",
);
hook.unmount();
} finally {
cleanup();
Object.defineProperty(window, "localStorage", {
value: origLocalStorage,
configurable: true,
});
relayClient.fetchEvents = origFetch;
relayClient.subscribeLive = origLive;
relayClient.subscribeToReconnects = origReconnect;
relayClient.publishEvent = origPublish;
window.__TAURI_INTERNALS__ = origTauri;
}
});

View File

@@ -152,13 +152,17 @@ export function useChannelSortPreference(
const outbox = readChannelSortOutbox(pubkey, relayUrl);
if (outbox) {
// publishSortPrefs synchronously copies the intent into this window's
// own v2 key, so marking the legacy blob consumed afterward can never
// lose it: a crash before the marker write replays the legacy blob once
// more, a crash after resumes it from the v2 key. The marker is what
// stops the never-deleted legacy key republishing above the head every
// boot (Thufir pass-2 resurrection finding).
managerRef.current?.publishSortPrefs(outbox.store);
if (outbox.legacyRawToConsume !== null) {
// own v2 key and returns whether that transfer is durable. Mark the
// legacy blob consumed ONLY when it is: a `setItem` failure (quota)
// returns false, so the marker is not written and the legacy record
// stays replayable on a later boot rather than being silently
// suppressed (Thufir pass-3 finding). A crash between a durable
// transfer and the marker write replays the legacy blob once more, a
// crash after resumes it from the v2 key. The marker is what stops the
// never-deleted legacy key republishing above the head every boot
// (Thufir pass-2 resurrection finding).
const durable = managerRef.current?.publishSortPrefs(outbox.store);
if (durable && outbox.legacyRawToConsume !== null) {
markChannelSortLegacyConsumed(
pubkey,
relayUrl,
@@ -263,10 +267,13 @@ export function useChannelSortPreference(
if (result.status === "found") {
setStore(applyRemote(result.data));
}
const pending = managerRef.current?.getPendingStore();
if (pending) {
managerRef.current?.publishSortPrefs(pending);
}
// Wake the existing pending edit's cycle rather than re-queueing it via
// publishSortPrefs(): a re-queue would bump the generation and reset the
// frozen publishBaseline to the just-fetched head, so a remote that won
// LWW while the edit was pending would be published over instead of
// adopted (Carl P1). retryPendingPublish keeps the baseline, so the
// pre-publish check still adopts a genuinely-advanced remote.
managerRef.current?.retryPendingPublish();
});
});
return () => {