Repository navigation
feat: confirm a draft session and publish its share code - #33
Conversation
Adds POST /sessions/:sessionId/confirm. The owner publishes a reviewed draft: the session moves to `open` and gets an 8-character code drawn from an alphabet without look-alike glyphs, retried against the unique index when it collides. Confirming is refused while the draft has no lines or still holds a line below the confidence threshold.
Characterization tests over the integration suite. The draft is seeded with the total the AI read off the receipt, while `totalCents` is then kept by adding and subtracting line deltas — so the gap the draft is born with survives every edit, the delete clamp moves it on its own, and confirm publishes it unchecked. They assert today's behaviour, not the wanted one. The ones that flip when the accumulator goes are the ones naming the gap.
The check compared the line items against `totalCents`, but the API moves that total by the same delta as every line edit, so a draft that was born out of balance could never be brought back into it. The warning had no way to clear and the confirm button stayed disabled for good. Removed here so the balance rule can be rebuilt on an API that keeps the printed total fixed.
`totalCents` was seeded with the total the AI read off the receipt and then kept as a running tally of the line edits, so it moved by the same delta as the lines it was supposed to be reconciled against. A draft born out of balance stayed out of balance by exactly that amount: no sequence of edits could close the gap, and the delete clamp moved it on its own once the total ran below zero. The total now means one thing — what the receipt says — and stays put while the owner reviews. Confirm is the gate: it refuses to publish until the items add up to it exactly, so nothing reaches the split with a total the lines disagree with. Adds PATCH /sessions/:sessionId for the other half of the reconciliation: when the AI misread the printed total, the owner corrects the target instead of being locked out of confirming.
The re-exports were in no particular order, so every new schema landed wherever the last one did. Alphabetical from here on.
The view declared `status` as a bare string while the schema has always restricted it to draft/open/closed, so the generated API types told clients nothing about the values they can expect. It now reuses the `STATUS` tuple the Mongoose schema is built from, which also retires the `Status` alias nothing was importing.
`totalCents` means what the receipt printed, and confirm refuses to publish until the items add up to it. That leaves the owner stuck whenever there is no printed total to reconcile against — a hand-written bill, a total the AI could not read — with no way out but typing the sum themselves and retyping it after every edit. A session now records where its total comes from. `totalSource: 'items'` hands it over: the total adopts the current line sum and is recomputed on every add, edit and delete, so the gap confirm checks stays closed by construction. Typing a total takes the reins back, and asking for both in the same patch is a 409 instead of a silent winner. Existing and new drafts default to 'receipt', so nothing changes until the owner asks for it. The patch body only accepts 'items': going back to a fixed total means sending the number it should be.
Bun treats the trailing argument as a path filter, so a bare `test` also matched the unit specs colocated under `src/**/__test__`. Anchoring it to `test/` keeps the two targets from overlapping.
Without the `await` the assertion resolved after the test had already finished, so the spec passed no matter what `confirmSession` rejected with.
A duplicate-key error raised on any other index must reach the module handler untouched rather than burn a code-generation attempt.
Scripts `crypto.getRandomValues` so two confirms draw the same code, then checks both ends of the retry loop against Mongo: the second session publishes with a fresh code, and when every attempt collides the session stays a draft with the taken code still owned by the first.
Replace the placeholder confirm button with a real mutation against POST /sessions/:id/confirm, seeding the response into the session query so the screen reacts to the published share code.
The API already refuses every edit once a session leaves the draft status, so keep the review screen from showing an editor the server would reject.
There was a problem hiding this comment.
ℹ️ No blocking issues. One correctness edge inline, plus a scope question about where confirm leaves the owner.
Reviewed changes — full review of all 18 commits on feat/join-session, covering the API confirm/patch endpoints, the totalSource rework, and the review-screen UI.
POST /sessions/:sessionId/confirm— owner-only; gates on draft status, non-empty items, no item below the confidence threshold, and an exact items-vs-receipt total match, then flips toopenand assigns a share code.- Share code generation — 8 characters from a 32-char unambiguous alphabet via
crypto.getRandomValues, written optimistically and redrawn on acode-scoped duplicate-key error up to 5 times. The alphabet is exactly 32 long sobyte % 32is unbiased. totalSourceon the session — replaces the old accumulator that mutatedtotalCentson every line-item write.'receipt'freezes the total;'items'recomputes it from the lines on every write.PATCH /sessions/:sessionId— owner-only, draft-only edits tomerchant,date,totalCents,totalSource, with a409when a fixed total andtotalSource: 'items'arrive together.- Review screen — the confirm button is wired to the real endpoint, a dialog edits the receipt total, a button hands the total to the items, and a confirmed session redirects to
/s/:code. - Client tolerance removed —
receiptTotals.matchestightened from ±2 cents to exact, matching the server so the UI can't offer a confirm the server refuses. test:integrationscoped totest/— astestit also matchedsrc/**/__test__, running the unit specs twice under the integration target.
The tests are the strongest part of this PR. session-code-collision.spec.ts scripts crypto.getRandomValues to force a real collision against a real unique index and asserts against the stored document rather than the response; session-totals.spec.ts measures storedTotals from the raw collection. These would fail if the behavior they claim to pin regressed.
ℹ️ Confirming is a one-way door onto a placeholder page
/s/$code is still a stub — "The guest flow for session {code} is coming soon." At the same time this PR makes the review route redirect every non-draft session there, and every mutating session endpoint already 409s on non-draft. So the moment an owner clicks Confirm & create link, they can no longer view the receipt, edit a line, delete the session, or copy a share link, and there is no un-confirm path. The code is only readable as prose on the stub.
That may well be the intended increment — but it's worth deciding deliberately rather than by accident, since it's reachable by a real user the moment this merges.
Technical details
# Confirm publishes into a UI dead end
## Affected sites
- `apps/web/src/app/routes/sessions.$sessionId.review.tsx:46-52` — redirects any
non-draft session to `/s/$code`, so the owner loses the review screen the
instant confirm succeeds.
- `apps/web/src/app/routes/s.$code.tsx:8-20` — the redirect target is a
placeholder with no session data, no share-link affordance, and no way back.
- `apps/api/src/modules/session/service.ts:151-152, 172-173, 195-196, 223-224` —
every edit path refuses a non-draft session, and there is no endpoint that
returns a session to `draft`.
## Required outcome
- A decision, not necessarily a code change: either confirm stays unreachable
until the guest flow lands, or a confirmed session gives the owner something
usable — at minimum the share URL in a copyable form.
## Open questions for the human
- Is landing on the placeholder acceptable for this increment, or should the
confirm button be gated until `/s/:code` renders a real session?
- Should the owner be able to reopen or delete a published session? Right now
`deleteSession` has no draft guard, but it is only reachable from the review
screen the redirect takes away.ℹ️ Nitpicks
LOW_CONFIDENCE_THRESHOLDis now defined in two places —apps/api/src/modules/session/service.ts:19andapps/web/src/features/session/line-item/components/line-item-row.tsx:6. Both are0.7today, but if they drift the UI enables Confirm & create link and the server answers409 Some items still need review, which no client code renders.isDuplicateKeyErrortreatskeyPattern === undefinedas a match, so acode-scoped call would retry on any duplicate-key error that arrives without akeyPattern. MongoDB always includeskeyPatternon an E11000, so that branch only widens the retry for a case that can't occur —code === 11000 && key !== undefined && keyPattern?.[key] !== undefinedwould say what's meant.t.String({ format: 'date' })is genuinely enforced (Elysia 1.4.29 registers thedateformat on import and rejects anythingnew Date()can't parse), but its regex also accepts slash forms like07/07/2026, whichnew Datereads as MM/DD. Latent only — no client sendsdateyet.
Claude Opus | 𝕏
Both sides gated on 0.7 from their own copy. If they drifted, the review screen would enable Confirm & create link while the server answered 409 Some items still need review, which no client renders.
Confirm read the session, set status and code on the hydrated document and saved it. That save emits a $set keyed on _id alone — the schema sets no optimisticConcurrency, so mongoose adds no __v predicate — and two concurrent confirms both went through, the second overwriting the first. The caller that lost held a code that was no longer stored. The publish is now a findOneAndUpdate conditioned on status: 'draft'. No match means someone else published first, which is the same 409 the route already declares, so the response contract is unchanged. A duplicate key on code still means a collision, so the redraw loop carries over. isDuplicateKeyError counted a missing keyPattern as a match, which would have retried on any duplicate arriving without one. Mongo always sends it, so the branch only widened the retry for a case that cannot happen.
There was a problem hiding this comment.
Note
ℹ️ Both prior findings are resolved. One nitpick inline; nothing blocking.
Reviewed changes — delta since the last pullfrog review at 6bc383e:
05119bfmovesLOW_CONFIDENCE_THRESHOLDintolibs/shared-types/src/lib/confidence.tsand imports it from both apps, so the api gate and the "Check this" badge can no longer drift apart. The file is dependency-free, and@repo/shared-typeswas already the established api↔web seam (OBJECT_ID_PATTERN,SUPPORTED_IMAGE_MIME_TYPES), so it stays browser-safe.d98f959replaces the read-modify-write publish with a compare-and-swap:Session.findOneAndUpdate({ _id, status: 'draft' }, { $set: { status: 'open', code } }),null→409. This is exactly the fix suggested on the prior review; thread replied to and resolved.- Same commit tightens
isDuplicateKeyErrorto require bothcode === 11000andkeyPattern[key], so an unrelated duplicate can no longer be swallowed by the retry loop.
What I verified rather than assumed:
- Moving off
session.save()drops no middleware.apps/api/src/schemas/declares nopre/posthooks, no plugins, virtuals, statics or methods, andauthPlugindoesn't mutate the hydrated session — so there are no pending in-memory writes for the$setto lose.returnDocument: 'after'is valid in the installed mongoose 9.9.1. - The retry loop is actually reachable. The tightened predicate only fires if the driver error carries a top-level
keyPattern. Traced it:findAndModifyfails as a single top-level command (nowriteErrorsbatch array), the driver copies the whole raw reply ontoMongoServerError, and mongoose's_transformDuplicateKeyErrorreturns the error untouched because this schema declares its constraint viasessionSchema.index(...)rather than aunique:path with a custom message.session-code-collision.spec.tsthen pins this empirically against realmongo:7.0, so a regression here fails CI rather than silently disabling retries. - The tests are load-bearing.
session-confirm-concurrency.spec.tsruns a genuinePromise.allrace and asserts[200, 409]plus that the winner's code is the one stored; the unit tests pin the CAS filter shape and that a duplicate without akeyPatternbubbles up instead of retrying.session-totals.spec.tsmeasures the stored document rather than the response view, and its comment at L381-384 documents why thetotalSourcebody is at.Literal('items')rather than the full enum — worth keeping, sincet.UnionEnum's injecteddefaultis exactly the kind of thing a later "simplification" would reintroduce.
Local run of bun nx run-many -t test tsc:typecheck lint --skip-nx-cache is green. test:integration needs a Docker socket and can't run in this sandbox — CI covers it.
Claude Opus | 𝕏
The cache was only written on success, and the query defaults hold a session for a minute without refetching on focus. A tab that confirmed a session already published elsewhere got the error toast and went on rendering the draft with the button live, recoverable only by reloading. Invalidating on error refetches; the review route's existing non-draft guard then carries the tab to the share link.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — delta since the last pullfrog review at d98f959, a single commit.
5205959closes the stale-cache-after-409gap —useConfirmSessionnow invalidatesgetSessionQueryOptions(sessionId).queryKeyin anonErrorhandler, alongside the existingonSuccesssetQueryData. This is the prior review's nitpick implemented as suggested; that thread is replied to and resolved.
What I verified rather than assumed:
- The caller's handler is not swallowed and cannot be clobbered.
onErroris destructured out ofmutationConfigthe same wayonSuccessalready was, so the trailing...restConfigspread no longer carries anonErrorthat would overwrite the wrapper, andonError?.(error, ...args)still forwards.MutationConfigis a plainUseMutationOptions, so no type surface changed. - The recovery path actually terminates somewhere useful. After the invalidate the refetch lands,
sessions.$sessionId.review.tsx:46-52seesstatus !== 'draft'and<Navigate>s to/s/$code— so the compare-and-swap loser leaves the draft screen instead of sitting on an enabled Confirm button. Firing on every error rather than only409is the right call here: a refetch is cheap, and the query defaults already setretry: false, so an offline client won't loop.
bun nx run-many -t tsc:typecheck lint -p web --skip-nx-cache is green; the delta is web-only. test:integration needs a Docker socket and can't run in this sandbox — CI covers it.
The guest-flow scope question from the initial review (confirming redirects to the /s/:code stub, with no un-confirm path) is unchanged and still a decision for you, not a code finding.
Claude Opus | 𝕏
|
This feat is for confirming a session |

Lets the session owner finish a draft: fix up the receipt total, then confirm the
session so it gets a shareable code.
Confirming a session
New
POST /sessions/:sessionId/confirm(owner-only). It flips adraftsessionto
openand assigns a public share code. Confirming is refused with a409when the session has no line items, when any item is still below the
low-confidence threshold, or when the line items do not add up to the receipt
total — the same three conditions the review screen already surfaces.
The code is 8 characters from a Crockford-style alphabet (no
I,O,0,1)drawn from
crypto.getRandomValues. Rather than checking for a free code beforewriting, it relies on the unique index: save, and on a duplicate-key error on
coderetry with a fresh one, up to 5 times. Any other write error propagatesuntouched. Exhausting the attempts logs and returns a
500— at 32^8 codes thisshould stay theoretical, but it fails loudly rather than silently reusing a code.
Receipt total vs. items total
Previously
totalCentswas mutated incrementally on every line-item write, sothe receipt total drifted away from what the receipt actually said. The session
now records where its total comes from via a
totalSourcefield (receiptoritems):receipt(the default) — the total is whatever the AI extracted or the ownertyped, and line-item edits leave it alone.
items— the total is recomputed from the line items on every write.New
PATCH /sessions/:sessionId(owner-only, draft-only) editsmerchant,date,totalCentsandtotalSource. SendingtotalCentstogether withtotalSource: 'items'is a409, since the two instructions contradict eachother.
Review screen
The summary now shows the items total next to the receipt total when they
disagree, with the gap and its direction. Two ways out: edit the receipt total in
a dialog, or switch the session to track the items total. Once totals agree, the
items are all reviewed and the session is non-empty, Confirm & create link
becomes available; a confirmed session redirects to
/s/:code.The client-side tolerance of 2 cents is gone — the API compares totals exactly,
so accepting a near-match in the UI would only produce a confirm the server
rejects.
Notes
test:integrationwas scoped totest/— astestit also matchedsrc/**/__test__, so unit specs ran twice under the integration target.unique index, and the totals behaviour lives in
apps/api/test.Testing
bun nx run-many -t lint test typecheck format:check— all greenbun nx test:integration api— 40 pass