Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/3733-accepted-snapshot-revision.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain-ui-server": minor
---

A stale draft save can no longer bring back a snapshot whose send the host already accepted (#3733). When an acceptance releases a snapshot and keeps the draft (a newer revision exists, or the draft changed chats), the draft now moves to a new revision. A tab or device that read the draft before the acceptance used to save its old list under its `If-Match`, and the sent snapshot came back as a new `dispatched` one: it took a slot of the chat's ten and its files went back to `outgoing`. That save is now `409 DRAFT_CONFLICT` with `current`, as the `If-Match` contract already allows. The single-slot `outgoing` write follows the same rule.
16 changes: 15 additions & 1 deletion docs/decisions/chat-attachments.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,19 @@ replacing #3153's single slot:
draft still holding other snapshots keeps the row at the next revision with
an empty composer instead of a tombstone. A `DELETE` that would drop a held
or unconfirmed snapshot is `409 DRAFT_OUTGOING_PENDING`.
- **A release is a revision (#3733).** An acceptance that releases a snapshot
moves the draft to a new revision even when it keeps the draft (a newer
revision exists, or the draft changed chats). Before this a tab that read
the draft earlier could still save under its `If-Match`, and the snapshot
it listed came back as a new `dispatched` one holding a slot. Now that save
is 409 `DRAFT_CONFLICT` with `current`. The other rule the issue offered,
refusing a new snapshot whose `requestId` is in `session_draft_sends`, was
not taken: that table records only first messages, not sends into an
existing chat (`resumed`), and keeps the last eight per draft, so it cannot
say which requests were accepted. The revision rule needs no new record,
covers every acceptance path and is the conflict the `If-Match` contract
already promises. A tab sending its own snapshot holds its saves until the
answer, so only a tab or device that was already behind sees the conflict.
- **The composer keeps its envelope.** An upload's per-draft count now covers
the current revision and unbound uploads only. A snapshot's files are
checked against the per-message envelope when a save lists it, and stay in
Expand Down Expand Up @@ -326,7 +339,8 @@ originals, on a host that advertises `composerFiles`:
without the limit, keeps the tab-local path, because a snapshot cannot hold
an inline image.
- **Acceptance drops it here at once.** The host releases an accepted
snapshot in place, without a revision (#3733). So the client removes it
snapshot in place, and a stale list saved over it is a conflict (#3733).
So the client removes it
from both its list and its copy of the host's before the next save, and
holds a draft's saves while one of its sends is pending. When other
snapshots remain, the host keeps the row at the next revision with an
Expand Down
8 changes: 7 additions & 1 deletion docs/http-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -1178,7 +1178,13 @@ absent keeps it. Under the save's `If-Match` and `Idempotency-Key`:
cannot be left out (400 `DRAFT_INVALID`); nothing is evicted, merged or
overwritten. Accepting the message whose `requestId` a snapshot carries
releases that snapshot alone, its files moving to the conversation in the
acceptance transaction.
acceptance transaction. An acceptance that releases a snapshot always moves
the draft to a new revision, whether it consumes the draft or keeps it
(#3733). A save from a tab or device that read the draft before the
acceptance still lists the sent snapshot, so it is 409 `DRAFT_CONFLICT`
with `current`, which no longer holds that snapshot. It never recreates the
snapshot as a new one, holds a slot again or gives its files back to
`outgoing`. The single-slot `outgoing` write follows the same rule.

Every snapshot's files stay referenced, charged to the draft sub-limit and the
pool, and each snapshot is checked against the per-message envelope. When an
Expand Down
3 changes: 3 additions & 0 deletions docs/integration-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,9 @@ when the chat is full; a delete that would drop a held or unconfirmed one is
the new 409 `DRAFT_OUTGOING_PENDING`. `Draft.outgoing` and the single-slot
write keep their shape and meaning for one held or unconfirmed send. The save
body bound rises from 512 KiB to 4,390,912 bytes to carry ten snapshot texts.
An acceptance that releases a snapshot moves the draft to a new revision even
when it keeps the draft, so a save that still lists the sent snapshot is 409
`DRAFT_CONFLICT` with `current` rather than recreating it (#3733).
See [the wire component](integration-contract/wire.md#composer-file-attachments-additive-0450-3153)
and [the HTTP API](http-api.md#outgoing-snapshot-list-additive-0450-3588).

Expand Down
4 changes: 2 additions & 2 deletions packages/ui-react/src/lib/draft-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,8 @@ export function createDraftClient(root: BrainUiServices, options: DraftClientOpt
if (d.deviceOnly || d.conflict) return false;
if (d.failure && d.failure.kind !== "unsaved") return false;
if (d.bind) return true;
// A snapshot's send is out: acceptance releases it without a revision,
// so a save made meanwhile could list it again (#3733). It waits.
// A snapshot's send is out: a save made meanwhile would list it again,
// and the host would refuse it once the acceptance releases it (#3733). It waits.
if (sendingSnapshot(d.draftId)) return false;
if (!hasContent(d) && !holdsSnapshots(d)) return (d.host !== null || d.uncertain) && !held(d.draftId);
return d.host === null || d.host.edit !== d.edit;
Expand Down
5 changes: 2 additions & 3 deletions packages/ui-react/src/stores/draft-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -838,9 +838,8 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s
// that session's now, whatever view the reader has moved on to.
const session = d.deviceConflict && send.sessionId !== null ? d.sessionId : d.sessionId ?? acceptedSessionId ?? null;
if (send.snapshotId || draftSnapshots(d).some((x) => x.requestId === requestId)) {
// The host released this snapshot with the acceptance, in place and
// without a revision: it leaves both lists now, so no later save
// names it again (#3733).
// The host released this snapshot with the acceptance, in place: it
// leaves both lists now, so no later save names it again (#3733).
const release = <T extends { requestId: string }>(list: T[] | undefined) => list?.filter((x) => x.requestId !== requestId);
const host = d.host ? { ...d.host, ...(d.host.snapshots ? { snapshots: release(d.host.snapshots)! } : {}) } : null;
const consumedHere = send.draftRef !== null && send.draftRef.draftId === d.draftId && d.host?.revision === send.draftRef.revision;
Expand Down
25 changes: 19 additions & 6 deletions packages/ui-server/src/drafts/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -818,8 +818,9 @@ export function createDraftStore(
// Only the accepted request's snapshot is released; the others stay.
const settled = readDraft(draftId);
const kept = settled && input.requestId ? snapshotsOf(settled).filter((s) => s.requestId !== input.requestId) : null;
if (settled && kept && kept.length !== snapshotsOf(settled).length) {
setRefs(db, "outgoing", draftId, snapshotFiles(kept), at);
const released = Boolean(settled && kept && kept.length !== snapshotsOf(settled).length);
if (released) {
setRefs(db, "outgoing", draftId, snapshotFiles(kept!), at);
db.prepare("UPDATE session_drafts SET outgoing_snapshots = ? WHERE draft_id = ?").run(JSON.stringify(kept), draftId);
}
if (!input.resumed && input.requestId) {
Expand All @@ -834,16 +835,28 @@ export function createDraftStore(
).run(draftId);
}
const row = readDraft(draftId);
if (!row || row.deleted_at !== null || retired(row.session_id) || retired(input.sessionId)) return "kept";
// A released snapshot changes the stored list, so a kept draft moves
// to the next revision with it: a tab that still lists the sent
// snapshot gets 409 DRAFT_CONFLICT with this list, and cannot save it
// back as a new dispatched one (#3733).
const keep = (): "kept" => {
if (released && row && row.deleted_at === null)
db.prepare("UPDATE session_drafts SET revision = ?, updated_at = ?, updated_by = ? WHERE draft_id = ?")
.run(row.revision + 1, at, input.principalId, draftId);
return "kept";
};
if (!row || row.deleted_at !== null || retired(row.session_id) || retired(input.sessionId)) return keep();
const source = input.resumed ? input.sessionId : input.sourceSessionId ?? null;
if (row.session_id !== source) return "kept";
if (row.session_id !== source) return keep();
if (row.revision !== revision) {
// Edits made after submission stay with the same chat when its first
// real task names it. Version the ownership move for concurrent saves.
if (input.sourceSessionId && !input.resumed && input.requestId)
if (input.sourceSessionId && !input.resumed && input.requestId) {
db.prepare("UPDATE session_drafts SET session_id=?,revision=?,updated_at=?,updated_by=? WHERE draft_id=?")
.run(input.sessionId,row.revision+1,at,input.principalId,draftId);
return "kept";
return "kept";
}
return keep();
}
const remaining = snapshotsOf(row);
if (remaining.length > 0) {
Expand Down
5 changes: 3 additions & 2 deletions packages/ui-server/tests/attachment-ownership.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,11 +216,12 @@ test("saved file bindings and the outgoing snapshot survive a restart; acceptanc
expect(store.list(owner).drafts[0]).toMatchObject({ fileCount: 1 });

// The held send is accepted against revision 1: the snapshot's file moves to
// the conversation, the snapshot clears, and the newer revision stays.
// the conversation, the snapshot clears, and the newer edits stay, at the
// next revision so no save of revision 2 lists the snapshot again (#3733).
clock += 1_000;
expect(store.accept({ draftRef: { draftId: "draft-ithaca", revision: 1 }, sessionId: "voyage-1", resumed: false, requestId: "request-fees", principalId: owner, fileIds: [sent.fileId] })).toBe("kept");
const after = store.get(owner, "draft-ithaca");
expect(after).toMatchObject({ revision: 2, text: "And the crew?" });
expect(after).toMatchObject({ revision: 3, text: "And the crew?" });
expect(after).not.toHaveProperty("outgoing");
expect(store.attachmentRef(sent.fileId, "message", "voyage-1")).toBe(true);
expect(store.attachmentRef(sent.fileId, "outgoing", "draft-ithaca")).toBe(false);
Expand Down
36 changes: 36 additions & 0 deletions packages/ui-server/tests/draft-snapshots.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,3 +266,39 @@ test("two devices at nine snapshots save at the same moment: exactly one is admi
const total = (t.app.db.query("SELECT SUM(json_array_length(outgoing_snapshots)) AS n FROM session_drafts WHERE session_id = 'voyage-ithaca'").get() as { n: number }).n;
expect(total).toBe(10);
});

test("a stale save cannot bring back a snapshot whose send the host accepted with the draft kept (#3733)", () => {
const f = fixture();
const fees = storeOriginal(f.dir, f.store, f.owner, "draft-ithaca", "harbour-fees.txt", "Two oxen\n");
const stale = [f.snapshot(1, "dispatched", [fees.fileId]), f.snapshot(2, "held")];
const sent = f.save("draft-ithaca", { snapshots: stale });
// The phone types on after sending: a newer revision exists, so the
// acceptance keeps the draft and releases only the accepted snapshot.
const typed = f.save("draft-ithaca", { text: "And the crew?", snapshots: stale });
const live = () => (f.db.query("SELECT COALESCE(SUM(json_array_length(outgoing_snapshots)), 0) AS n FROM session_drafts WHERE session_id = 'voyage-ithaca' AND deleted_at IS NULL").get() as { n: number }).n;
expect(f.store.accept({ draftRef: { draftId: "draft-ithaca", revision: sent }, sessionId: "voyage-ithaca", resumed: true, requestId: "request-1", principalId: f.owner, fileIds: [fees.fileId] })).toBe("kept");
expect(live()).toBe(1);
// A tab that read the draft before the acceptance still lists the sent
// snapshot. Its save under the revision it holds is a conflict that carries
// the current list, not a new dispatched snapshot.
const conflict = f.refuse(() => f.save("draft-ithaca", { text: "And the crew? All of them.", snapshots: stale }));
expect(conflict.status).toBe(409);
expect(conflict.body).toMatchObject({ error: "DRAFT_CONFLICT", current: { text: "And the crew?" } });
const current = (conflict.body as { current: Draft }).current;
expect(current.revision).toBeGreaterThan(typed);
expect(current.snapshots?.map((s) => s.requestId)).toEqual(["request-2"]);
// The single-slot write is refused the same way.
expect(f.refuse(() => f.save("draft-ithaca", { outgoing: { requestId: "request-1", text: "Message 1 to Ithaca", fileIds: [fees.fileId], state: "dispatched" } })).body)
.toMatchObject({ error: "DRAFT_CONFLICT" });
// Nothing came back: no snapshot names the request, the chat's count is
// unchanged, and the sent file is the message's, not outgoing.
const after = f.store.get(f.owner, "draft-ithaca");
expect(after.revision).toBe(current.revision);
expect(after.snapshots?.some((s) => s.requestId === "request-1")).toBe(false);
expect(live()).toBe(1);
expect(f.store.attachmentRef(fees.fileId, "outgoing", "draft-ithaca")).toBe(false);
expect(f.store.attachmentRef(fees.fileId, "message", "voyage-ithaca")).toBe(true);
// Saving from the current revision goes on as usual.
f.revisions.set("draft-ithaca", current.revision);
f.save("draft-ithaca", { text: "And the crew? All of them.", snapshots: [f.snapshot(2, "held")] });
});
Loading