Skip to content

Commit a2f6a53

Browse files
kazemek21codex
andcommitted
fix(unread): preserve newer manual intent in captured reads
Fence explicit captured reads against the current saved local journal. Keep retry cuts fixed and expose retained-reply thread reads without advancing a channel or root frontier. Co-authored-by: Codex <[email protected]> Signed-off-by: Kyle Zemek <[email protected]>
1 parent f8acbf4 commit a2f6a53

6 files changed

Lines changed: 760 additions & 51 deletions

File tree

‎docs/buzz-help.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -425,6 +425,9 @@ revokes all of them, and a pairing unused for 30 days expires.
425425
unread evidence is incomplete, or when
426426
read intent or the read evidence needed to locate the boundary changes
427427
elsewhere before it is established.
428+
- **Marking a channel read** keeps the cut from your click when retried. If a newer
429+
manual unread choice was saved in another window while it waited, the read fails
430+
rather than clearing that choice. Mark the channel read again to clear it.
428431
- **Opening a channel or DM** while Buzz is visible and focused clears its sidebar row: the bold name, the mention
429432
dot and the thread dot. Switching away from Buzz pauses this: new messages
430433
can light the row even while that conversation stays selected. The macOS Dock dot follows the rows. Nothing is marked

‎docs/unread.md‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,49 @@ root-tag matches is not seen, and a single deletion event that names several
472472
of the viewer's messages is visible only if all of them are retained. Replies
473473
still require retained evidence of their own.
474474

475+
## Captured explicit reads
476+
477+
`prepareChannelRead(channelId, rootId?)` captures the channel's existing
478+
prefix/time cut and owned local-mark keys once. Invoke its returned function to
479+
save or retry that same intent; a retry does not capture later arrivals or a
480+
new clock cut. The optional root still bounds a DM reader's channel cut; it is
481+
not a narrow thread operation.
482+
483+
`prepareThreadRead(channelId, rootId)` instead captures the retained verified
484+
incoming replies below a retained canonical root. Each captured reply keeps its own
485+
message ID and timestamp. It reads no root, other thread, or subsequently loaded
486+
reply, even one with an older timestamp. It clears the selected thread's local
487+
mark and captured reply marks; independent channel, root-message and other-thread
488+
marks remain. The shared message-unread sidebar hint also remains until channel
489+
open reconciles it: that hint has no subtree ownership, even when this window
490+
has a forced-message overlay. Per-message receipts stay device-local, as with
491+
`markMessageRead`.
492+
Neither operation acquires or disposes a consumer's reading lease or discovers
493+
all historical messages/marks.
494+
495+
Both operations reserve a saved-journal snapshot at preparation, before their
496+
channel queue can wait. Mark all shares one saved revision cut across its selected
497+
channels; the predicates retain only that revision, not copies of the full journal.
498+
The replacing storage transaction checks the *current*
499+
local manual-unread revisions before changing any frontier or local mark. A newer
500+
saved mark among the captured keys rejects the whole save, including marks saved
501+
by another local window. Prepare a new operation to explicitly read that newer
502+
intent. Earlier same-window manual actions already queued at preparation remain
503+
eligible to clear, but only if their saves succeed. A manual save queued behind
504+
the read remains unread when it later commits. An earlier queued save that
505+
overwrites a newer window's same-key mark does not authorize clearing that
506+
intervening intent. This is not a claim of atomicity
507+
between a pending call and its eventual return. Remote unread overrides keep
508+
the existing frontier semantics; this fence does not order identical remote
509+
marker tuples or change automatic observation.
510+
511+
Capture requires initialized read-state storage (`await unread.ensure()` before
512+
preparation). A failed capture rejects every invocation of that operation rather
513+
than moving the snapshot to save time; prepare again after readiness/recovery.
514+
Storage failures retain the cut for retry. Access revoke/regrant, cache clear or
515+
session disposal invalidate captured intent. The thread operation additionally
516+
requires its captured message evidence to remain valid.
517+
475518
## Explicit clearing matrix
476519

477520
| Intent | Durable frontier | Local manual-unread clears |

‎src/features/relay/read-state.test.ts‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,92 @@ function holdUpdate(f: ReturnType<typeof fixture>, afterCommit = false) {
178178
};
179179
}
180180
describe("durable read-state owner", () => {
181+
it.each(
182+
["room", "thread:root", "msg:reply"].flatMap((key) =>
183+
[false, true].map((intervening) => ({ key, intervening })),
184+
),
185+
)(
186+
"older queued saves preserve intervening intent: $key ($intervening)",
187+
async ({ key, intervening }) => {
188+
const f = fixture();
189+
const owner = f.make();
190+
const second = f.make();
191+
await Promise.all([owner.ready, second.ready]);
192+
let release = () => {};
193+
const held = new Promise<void>((resolve) => {
194+
release = resolve;
195+
});
196+
const enqueue = async (save: () => ReturnType<typeof owner.read>) => {
197+
await held;
198+
return save();
199+
};
200+
const marks = [
201+
owner.markLocalUnread(key, () => true, enqueue),
202+
owner.markLocalUnread(key, () => true, enqueue),
203+
];
204+
const fence = owner.captureLocalUnread([key]);
205+
try {
206+
if (intervening) await second.markLocalUnread(key, () => true);
207+
release();
208+
await Promise.all(marks);
209+
const saved = f.journal();
210+
const read = owner.read(
211+
"room",
212+
20,
213+
() => true,
214+
true,
215+
[key],
216+
undefined,
217+
fence,
218+
);
219+
if (intervening) {
220+
await expect(read).rejects.toThrow("Reading observation expired");
221+
expect(f.journal()).toEqual(saved);
222+
} else {
223+
await expect(read).resolves.toMatchObject({ durability: "saved" });
224+
expect(f.journal()?.localUnread[key]).toBeUndefined();
225+
expect(f.journal()?.state.frontiers.room).toBe(20);
226+
}
227+
} finally {
228+
release();
229+
await Promise.allSettled(marks);
230+
}
231+
},
232+
);
233+
234+
it("a failed older local mark cannot authorize a newer window's revision", async () => {
235+
const f = fixture();
236+
const owner = f.make();
237+
const second = f.make();
238+
await Promise.all([owner.ready, second.ready]);
239+
const heldMark = holdUpdate(f);
240+
const mark = expect(
241+
owner.markLocalUnread("room", () => true),
242+
).rejects.toThrow("disk full");
243+
await heldMark.started;
244+
const fence = owner.captureLocalUnread(["room"]);
245+
const heldRead = holdUpdate(f);
246+
const read = expect(
247+
owner.read("room", 20, () => true, true, ["room"], undefined, fence),
248+
).rejects.toThrow();
249+
try {
250+
// Exercise a failed callback that calculated a revision but never saved it.
251+
heldMark.fail(true);
252+
heldMark.release();
253+
await mark;
254+
await heldRead.started;
255+
await second.markLocalUnread("room", () => true);
256+
const saved = f.journal();
257+
heldRead.release();
258+
await read;
259+
expect(f.journal()).toEqual(saved);
260+
expect(f.journal()?.state.frontiers).toEqual({});
261+
} finally {
262+
heldMark.release();
263+
heldRead.release();
264+
}
265+
});
266+
181267
it("saves intent and exact signed event before publishing, then confirms the coordinate", async () => {
182268
const f = fixture();
183269
const owner = f.make();

‎src/features/relay/read-state.ts‎

Lines changed: 105 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,55 @@ export function createReadState({
238238
* so a fence on local intent sees other windows' saves, not this cache.
239239
*/
240240
type Validity = (current: ReadJournal) => boolean;
241+
type LocalUnreadAttempt = {
242+
key: string;
243+
saved?: { revision: number; previous: number };
244+
};
245+
const pendingLocalUnread = new Set<LocalUnreadAttempt>();
246+
type LocalUnreadFence = Promise<{ valid: Validity } | { error: unknown }>;
247+
function captureLocalUnreadRevision() {
248+
return new Promise<ReadJournal | undefined>((resolve) =>
249+
resolve(storage.capture()),
250+
).then(
251+
(captured) => ({ revision: captured?.revision ?? 0 }),
252+
(error: unknown) => ({ error }),
253+
);
254+
}
255+
function captureLocalUnread(
256+
keys: readonly string[],
257+
cut?: ReturnType<typeof captureLocalUnreadRevision>,
258+
): LocalUnreadFence {
259+
// Reserve at the click, not when a channel's queue eventually runs. Older
260+
// queued local actions are allowed only after their save actually succeeds.
261+
const older = [...pendingLocalUnread].filter(({ key }) =>
262+
keys.includes(key),
263+
);
264+
return (cut ?? captureLocalUnreadRevision()).then((captured) => {
265+
if ("error" in captured) return captured;
266+
return {
267+
valid: (current: ReadJournal) =>
268+
keys.every((key) => {
269+
let revision = current.localUnread[key] ?? 0;
270+
// An older queued save may overwrite a newer window's mark. Only
271+
// follow successful older saves back to the captured journal cut.
272+
while (revision > captured.revision) {
273+
const saved = older.find(
274+
(attempt) =>
275+
attempt.key === key && attempt.saved?.revision === revision,
276+
)?.saved;
277+
if (!saved) return false;
278+
revision = saved.previous;
279+
}
280+
return true;
281+
}),
282+
};
283+
});
284+
}
285+
async function capturedValidity(valid: Validity, fence: LocalUnreadFence) {
286+
const captured = await fence;
287+
if ("error" in captured) throw captured.error;
288+
return (current: ReadJournal) => valid(current) && captured.valid(current);
289+
}
241290
function queue<T>(job: () => Promise<T>): Promise<T> {
242291
const next = work.then(job);
243292
work = next.catch(() => {});
@@ -817,6 +866,8 @@ export function createReadState({
817866
valid: Validity,
818867
clearLocalKeys: readonly string[] = [key],
819868
observedFrontier?: (state: ReadState) => number | undefined,
869+
fence?: LocalUnreadFence,
870+
localUnreadAttempt?: LocalUnreadAttempt,
820871
): Promise<ReadMutationResult> {
821872
const automatic =
822873
key.startsWith("msg:") && timestamp !== undefined && unread === undefined;
@@ -867,8 +918,12 @@ export function createReadState({
867918
),
868919
);
869920
}
921+
const currentValid = fence
922+
? await capturedValidity(valid, fence)
923+
: valid;
924+
let previousLocalUnread = 0;
870925
const saved = await save((current) => {
871-
if (!valid(current)) throw new ObservationExpired();
926+
if (!currentValid(current)) throw new ObservationExpired();
872927
if (
873928
!contextId(key) ||
874929
(timestamp !== undefined && !uint32(timestamp))
@@ -903,6 +958,7 @@ export function createReadState({
903958
recent,
904959
);
905960
const localUnread = { ...current.localUnread };
961+
previousLocalUnread = localUnread[key] ?? 0;
906962
// Automatic observations do not clear explicit local manual-unread intent.
907963
if (unread === false)
908964
for (const clearKey of clearLocalKeys) delete localUnread[clearKey];
@@ -976,6 +1032,11 @@ export function createReadState({
9761032
: current.acceptedRevision,
9771033
};
9781034
});
1035+
if (localUnreadAttempt)
1036+
localUnreadAttempt.saved = {
1037+
revision: saved.revision,
1038+
previous: previousLocalUnread,
1039+
};
9791040
if (automaticRead) automaticRead.status = "saved";
9801041
health({
9811042
status: capability === "frontier-sync" ? "pending" : "local",
@@ -1275,6 +1336,8 @@ export function createReadState({
12751336
}
12761337
return {
12771338
ready,
1339+
captureLocalUnread,
1340+
captureLocalUnreadRevision,
12781341
snapshot: () => snapshot,
12791342
/** Markers may be missing: a snapshot read is still owed. */
12801343
owed: () => observationOwed,
@@ -1324,6 +1387,7 @@ export function createReadState({
13241387
clearLocalKeys?: readonly string[],
13251388
/** Verified observation ancestry, evaluated only inside the fenced transaction. */
13261389
observedFrontier?: (state: ReadState) => number | undefined,
1390+
fence?: LocalUnreadFence,
13271391
) =>
13281392
mutate(
13291393
key,
@@ -1332,9 +1396,14 @@ export function createReadState({
13321396
valid,
13331397
clearLocalKeys,
13341398
observedFrontier,
1399+
fence,
13351400
),
1336-
clearLocalUnread: (key: string, keys: readonly string[], valid: Validity) =>
1337-
mutate(key, undefined, false, valid, keys),
1401+
clearLocalUnread: (
1402+
key: string,
1403+
keys: readonly string[],
1404+
valid: Validity,
1405+
fence?: LocalUnreadFence,
1406+
) => mutate(key, undefined, false, valid, keys, undefined, fence),
13381407
/** Atomic explicit subtree read; local-only hosts clear intent without
13391408
* fabricating frontiers. A `quiet` save (a row's `seen:` marks) reads
13401409
* nothing, so it is counted apart from unread intent (`intentRevision`). */
@@ -1348,14 +1417,19 @@ export function createReadState({
13481417
clearForce: string | undefined,
13491418
valid: Validity,
13501419
quiet = false,
1420+
fence?: LocalUnreadFence,
1421+
clearLocalKeys: readonly string[] = [],
13511422
) =>
13521423
queue(async () => {
13531424
await ready;
13541425
if (!journal)
13551426
throw new Error("Saved read state unavailable; retry storage first");
13561427
try {
1428+
const currentValid = fence
1429+
? await capturedValidity(valid, fence)
1430+
: valid;
13571431
const saved = await save((current) => {
1358-
if (!valid(current)) throw new ObservationExpired();
1432+
if (!currentValid(current)) throw new ObservationExpired();
13591433
if (
13601434
messages.some(
13611435
({ key, timestamp }) => !contextId(key) || !uint32(timestamp),
@@ -1384,6 +1458,7 @@ export function createReadState({
13841458
delete localUnread[key];
13851459
}
13861460
if (clearForce) delete localUnread[clearForce];
1461+
for (const key of clearLocalKeys) delete localUnread[key];
13871462
const kept = Object.keys(frontiers).length
13881463
? retainMarks(
13891464
current,
@@ -1437,8 +1512,32 @@ export function createReadState({
14371512
throw error;
14381513
}
14391514
}),
1440-
markLocalUnread: (key: string, valid: () => boolean) =>
1441-
mutate(key, undefined, true, valid),
1515+
async markLocalUnread(
1516+
key: string,
1517+
valid: () => boolean,
1518+
enqueue: (
1519+
save: () => Promise<ReadMutationResult>,
1520+
) => Promise<ReadMutationResult> = (save) => save(),
1521+
) {
1522+
const attempt: LocalUnreadAttempt = { key };
1523+
pendingLocalUnread.add(attempt);
1524+
try {
1525+
return await enqueue(() =>
1526+
mutate(
1527+
key,
1528+
undefined,
1529+
true,
1530+
valid,
1531+
undefined,
1532+
undefined,
1533+
undefined,
1534+
attempt,
1535+
),
1536+
);
1537+
} finally {
1538+
pendingLocalUnread.delete(attempt);
1539+
}
1540+
},
14421541
accept(events: readonly RelayEvent[]) {
14431542
if (
14441543
closed ||

0 commit comments

Comments
 (0)