Skip to content

feat: confirm a draft session and publish its share code - #33

Merged
aek676 merged 21 commits into
mainfrom
feat/join-session
Aug 12, 2026
Merged

aek676 merged 21 commits into
mainfrom
feat/join-session

Conversation

@aek676

@aek676 aek676 commented Aug 12, 2026 •

Copy link
Copy Markdown
Owner

Note: the branch was named feat/join-session by mistake. This PR is about
confirming a session, not joining one. A merged PR's head branch cannot be
renamed, so the title and this description are the ones to go by.

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 a draft session
to open and assigns a public share code. Confirming is refused with a 409
when 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 before
writing, it relies on the unique index: save, and on a duplicate-key error on
code retry with a fresh one, up to 5 times. Any other write error propagates
untouched. Exhausting the attempts logs and returns a 500 — at 32^8 codes this
should stay theoretical, but it fails loudly rather than silently reusing a code.

Receipt total vs. items total

Previously totalCents was mutated incrementally on every line-item write, so
the receipt total drifted away from what the receipt actually said. The session
now records where its total comes from via a totalSource field (receipt or
items):

  • receipt (the default) — the total is whatever the AI extracted or the owner
    typed, 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) edits merchant,
date, totalCents and totalSource. Sending totalCents together with
totalSource: 'items' is a 409, since the two instructions contradict each
other.

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:integration was scoped to test/ — as test it also matched
    src/**/__test__, so unit specs ran twice under the integration target.
  • Integration coverage for the confirm flow, code collisions against a real
    unique index, and the totals behaviour lives in apps/api/test.

Testing

  • bun nx run-many -t lint test typecheck format:check — all green
  • bun nx test:integration api — 40 pass

aek676 added 18 commits August 12, 2026 10:44
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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ 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 to open and assigns a share code.
  • Share code generation — 8 characters from a 32-char unambiguous alphabet via crypto.getRandomValues, written optimistically and redrawn on a code-scoped duplicate-key error up to 5 times. The alphabet is exactly 32 long so byte % 32 is unbiased.
  • totalSource on the session — replaces the old accumulator that mutated totalCents on 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 to merchant, date, totalCents, totalSource, with a 409 when a fixed total and totalSource: '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.matches tightened from ±2 cents to exact, matching the server so the UI can't offer a confirm the server refuses.
  • test:integration scoped to test/ — as test it also matched src/**/__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_THRESHOLD is now defined in two places — apps/api/src/modules/session/service.ts:19 and apps/web/src/features/session/line-item/components/line-item-row.tsx:6. Both are 0.7 today, but if they drift the UI enables Confirm & create link and the server answers 409 Some items still need review, which no client code renders.
  • isDuplicateKeyError treats keyPattern === undefined as a match, so a code-scoped call would retry on any duplicate-key error that arrives without a keyPattern. MongoDB always includes keyPattern on an E11000, so that branch only widens the retry for a case that can't occur — code === 11000 && key !== undefined && keyPattern?.[key] !== undefined would say what's meant.
  • t.String({ format: 'date' }) is genuinely enforced (Elysia 1.4.29 registers the date format on import and rejects anything new Date() can't parse), but its regex also accepts slash forms like 07/07/2026, which new Date reads as MM/DD. Latent only — no client sends date yet.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using Claude Opus | 𝕏

Comment thread apps/api/src/modules/session/service.ts Resolved
aek676 added 2 commits August 12, 2026 23:35
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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

ℹ️ Both prior findings are resolved. One nitpick inline; nothing blocking.

Reviewed changes — delta since the last pullfrog review at 6bc383e:

  • 05119bf moves LOW_CONFIDENCE_THRESHOLD into libs/shared-types/src/lib/confidence.ts and 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-types was already the established api↔web seam (OBJECT_ID_PATTERN, SUPPORTED_IMAGE_MIME_TYPES), so it stays browser-safe.
  • d98f959 replaces 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 isDuplicateKeyError to require both code === 11000 and keyPattern[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 no pre/post hooks, no plugins, virtuals, statics or methods, and authPlugin doesn't mutate the hydrated session — so there are no pending in-memory writes for the $set to 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: findAndModify fails as a single top-level command (no writeErrors batch array), the driver copies the whole raw reply onto MongoServerError, and mongoose's _transformDuplicateKeyError returns the error untouched because this schema declares its constraint via sessionSchema.index(...) rather than a unique: path with a custom message. session-code-collision.spec.ts then pins this empirically against real mongo:7.0, so a regression here fails CI rather than silently disabling retries.
  • The tests are load-bearing. session-confirm-concurrency.spec.ts runs a genuine Promise.all race 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 a keyPattern bubbles up instead of retrying. session-totals.spec.ts measures the stored document rather than the response view, and its comment at L381-384 documents why the totalSource body is a t.Literal('items') rather than the full enum — worth keeping, since t.UnionEnum's injected default is 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes — delta since the last pullfrog review at d98f959, a single commit.

  • 5205959 closes the stale-cache-after-409 gap — useConfirmSession now invalidates getSessionQueryOptions(sessionId).queryKey in an onError handler, alongside the existing onSuccess setQueryData. 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. onError is destructured out of mutationConfig the same way onSuccess already was, so the trailing ...restConfig spread no longer carries an onError that would overwrite the wrapper, and onError?.(error, ...args) still forwards. MutationConfig is a plain UseMutationOptions, so no type surface changed.
  • The recovery path actually terminates somewhere useful. After the invalidate the refetch lands, sessions.$sessionId.review.tsx:46-52 sees status !== '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 only 409 is the right call here: a refetch is cheap, and the query defaults already set retry: 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.

Pullfrog  | View workflow run | Using Claude Opus | 𝕏

@aek676
aek676 merged commit ec6ba41 into main Aug 12, 2026
2 checks passed
@aek676
aek676 deleted the feat/join-session branch August 13, 2026 08:04
@aek676

aek676 commented Aug 13, 2026

Copy link
Copy Markdown
Owner Author

This feat is for confirming a session

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant