Repository navigation
feat(meditations): give an editor a way to ask for a transcript again - #1011
Conversation
Closes #984. On `main` a `failed` transcript row stayed failed forever and a meditation whose run was lost stayed blank: #968 removed the transcript endpoints, `meditations-editor` holds nothing on `meditation-transcripts`, and `restrictUploadToAdmin` refuses re-uploading the audio — so the only lever left was an administrator deleting the row by hand. Each of the three is right on its own. `POST /api/meditations/:id/transcript` is that lever back, gated on the `meditations: update` an editor already holds, through `requireManagerPermission` — which refuses an API client as a caller, so `requireActiveClient` is deliberately absent. A retry is the delete-and-create pair `syncMeditationTranscript` already runs for a replaced recording; the new row's own afterChange queues the run. A run costs money, so the server decides whether to pay for one (Decision 2). Two bounds: the phase must be retryable — `completed` and a run in flight are refused with 409 — and the existing row must be older than `RETRANSCRIBE_COOLDOWN_MS`, refused with 429 and a `Retry-After`. The cooldown is keyed on the row's own `createdAt`, so it needs no column; it is 10 minutes and must stay at or under `TRANSCRIPTION_STALL_MS`, or a `stalled` row — which is by definition that old — would become permanently unretryable. The unit lane holds that bound. `transcriptPhase` moves out of the tab's `transcriptModel.ts` into `src/lib/meditations/transcriptPhase.ts`, beside `transcriptStall.ts` and zod-free for the reason that module states: the tab is `'use client'`. `transcriptPhaseIsRetryable` joins it, and both sides read it — the endpoint to refuse, the tab to offer — so a button cannot promise what the server will not do. The row's own virtual `status` supplies the phase, which is why the lookup takes no `select`: one would starve that field's afterRead and read every row as `completed`. Both writes are one transaction, opened with Payload's own `initTransaction` and killed on any throw: an endpoint inherits none, so two sequential writes would leave a create that fails with no transcript at all. The delete goes by `where` rather than by id, so the loser of a race deletes nothing and its insert hits the `unique` index on `meditation` — answered as a 409, not the adapter's own 400, since `@payloadcms/drizzle` converts the SQLSTATE to a `ValidationError` and drops the Postgres error. A delete by `where` collects per-document failures instead of throwing, so its `errors` are read rather than discarded; unread, a row that refused to go would be reported as a race. The control is a `RetryTranscript` button inside the notice that says why it is needed. The cooldown renders as the wait rather than a button that only 429s, and no recording hides it in every phase, as the endpoint refuses it in every phase. `useRetryCooldown` gives that moment its own timer for the same reason `useTranscriptPhase` has one: a failed row answers every poll with itself, so the instant the cooldown passes would never reach the screen. A refusal other than a 429 re-reads the row, since a run that finishes past the stall bound leaves the tab holding a notice the server disagrees with. No role grant, no migration, and nothing writes the meditation document, so no version is added. `/api/meditations/{id}/transcript` stays out of `CUSTOM_ENDPOINT_PATHS` — a manager-only action reaches the spec only through an explicit opt-in. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FhKEe64iU3R2GgZb266wEf
`perf-figures-pinned.spec.ts` compares `tests/PERF.md`'s recorded file count against the specs on disk, and it was already red on `main`: the tree carries 216 unit specs and PERF.md recorded 215, so a spec landed without the figure moving with it. Two more here make it 218 / 2825. Counts only. PERF.md states that the file and test counts are the current tree's while every timing belongs to the session its row names, so the 78 s median and the tier targets stand unmeasured by this. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FhKEe64iU3R2GgZb266wEf
… answer The collection's docblock said there is "no second permission to hold, and no endpoint standing in for one". The read half still holds; the write half does not, so it now names `POST /api/meditations/:id/transcript` and that the authority to re-transcribe is the authority to edit the meditation. `docs/rules/access.md`'s hand-rolled-fetch table gains the two the tab makes. The read one was already missing: the tab shipped with #985 and the table never moved. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FhKEe64iU3R2GgZb266wEf
|
🚅 Deployed to the SahajCloud-pr-1011 environment in sahajcloud
1 service not affected by this PR
|
|
🤖 no session running recent dispatchesWritten by the sydevs dispatcher. Sessions never edit this comment. |
Four conflicts, all one figure: the unit lane's pinned file and test counts. #996 re-pinned them for the one spec it added, this branch for the two it adds, so neither side's number describes the merged tree. Recounted off the merged tree instead of taking a side: 219 spec files on disk, 2829 cases in the lane. `perf-figures-pinned.spec.ts` holds PERF.md against the tree and the three consumer docs against PERF.md, so all four files carry the same pair. No timing was re-measured — the lane ran 50 s here, inside the 47-78 s spread already recorded, so the quoted 78 s stands. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_0147tSnnXypdirnAAbr7BcYc
|
Merged Four conflicts, all the same figure: the unit lane's pinned file and test counts, in I took neither side and recounted: 219 files / 2829 cases, confirmed by the lean gate (lint, both typechecks, No timing was re-measured. The lane ran 50 s here, inside the 47–78 s spread already recorded, so the quoted 78 s stands. The body's Test results line still reads 218 / 2825 from before the merge. No code conflicted: #996's 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
The diff is the ticket's shape. One endpoint, one control, two bounds, no role change, no migration. The one joined change, the spec-count re-pin, is named in the body. Contracts are untouched: src/payload-types.ts does not move, so no consumer repo is owed a sync. Simplicity is where it strains. src/lib/meditations/ now holds three single-idea modules, each repeating the same reason for being its own file.
One thing is unproven rather than wrong. The control's visibility rests on filename being a key in form state, and the only precedent in this repo for reading that field goes the other way. Separately, the body's Test results line is stale after the main merge. It reads 218 files / 2825 tests, the branch pins 219 / 2829.
Findings
- should-fix —
RetryTranscript.tsx:39readsfilenamefrom form state.AudioUpload.tsx:61reads it fromuseDocumentInfo(). No test can tell them apart. - consider —
transcriptThrottle.ts:1. Three one-idea modules where one would do.
What was checked
- Ticket #984 line by line against the diff. Every acceptance criterion traces to a case in
meditation-transcription.int.spec.ts, the #701 locale gate over REST included. - Read whole:
transcript.ts,syncMeditationTranscript.ts,MeditationTranscripts/status.ts,filterMeditationsByLocale.ts,MeditationTranscript.tsx. - The deviation from the ticket's Approach holds.
transcriptPhasereads the virtualstatus, the lookup passes noselect, and the int phase cases redden if one is added. - The
overrideAccessmeditation read gives a French-only editor no reachPATCH /api/meditations/:id?locale=frlacks. Meditation locale is a field, andfindByIDnever filtered on it. - Both Preview links answer 200. Not signed in, so the control was not exercised in a browser.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
RetryTranscript read `filename` through `useFormFields`. The key is in form state — Payload's upload base fields declare it `admin.hidden`, not `hidden` or `admin.disabled`, and only the latter two short-circuit form state — but nothing in this repo relies on that, and the mocked tab spec cannot tell a present key from an absent one. `useDocumentInfo().data` is the read `AudioUpload` already makes on this same collection, for the audio player, so the assumption is one shipped code exercises. Both answer the stored filename either way: `<Upload>` writes only the `file` path, so staging or removing a recording moves neither until save. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FevaxC4SrdqHmyo2ZzFQqp
`transcriptStall.ts`, `transcriptPhase.ts` and `transcriptThrottle.ts` each held one constant or function and each restated the same reason for existing: zod-free, apart from `./transcript`, because the Transcript tab is a client component. That reason forces them out of `transcript.ts`, not into three files — they have the same two consumers. `transcriptBounds.ts` states it once. It also puts the ⚠ coupling beside what it couples: the cooldown must stay at or under the stall bound, which until now was asserted in a module that did not hold the other constant. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FevaxC4SrdqHmyo2ZzFQqp
|
Merged
The review body's stale Test results line is corrected in the PR body. Lean gate green: lint, both typechecks, 219 files / 2829 tests. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
|
Addressed the review. The branch was already level with
Gate green: lint, both typechecks, The body's contract and flow now match the branch. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Both sides re-pinned the unit lane's figures, so all four docs `perf-figures-pinned.spec.ts` couples conflicted. Kept main's side throughout — #993 replaced the per-edit row the spec now captures, and taking this branch's table would leave that capture with nothing to match. The counts are re-pinned to the merged tree: 224 files, 2880 tests. PERF.md's "86 of the 222 specs" is left as main wrote it. That denominator belongs to its own measurement, as the 198-file rows beside it do. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01GeyvnxHoLUW1pDfC51s4kt
|
Merged Took main's side in all four. #1009 replaced PERF.md's per-edit row with "Slowest per-edit selection", which the spec now captures; this branch's "Widest per-edit selection" wording would leave that capture matching nothing. Then re-pinned the counts to the merged tree: 224 files, 2880 tests. PERF.md's "86 of the 222 specs" stays as main wrote it. That denominator belongs to its own measurement, like the 198-file rows beside it. Gate green on the merge: lint, typecheck, typecheck:tests, The body's Test results still quote 220 / 2832. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Four conflicts, all the unit-lane counts: tests/PERF.md's `Files / tests` row and the three docs quoting it. Every block is the same sentence on both sides with different numbers, so there was nothing to choose between the prose. The counts are neither side's. Each side had refreshed the row against its own tree — 223 / 2855 here, 224 / 2880 on main — because the merge base carried 222 files and each side added its own specs. perf-figures-pinned counts the files on disk, so the row has to be the merged tree's: measured at 225 / 2892, the lane in 51.87 s. Recorded as a ninth session row in tests/PERF.md, which asks for a new row rather than a replaced one. Main added a third meditation endpoint, POST /api/meditations/:id/transcribe (#984, #1011), which this branch's write scoping does not reach. That is a gap, not a conflict: the endpoint gates on requireManagerPermission, a capability check in the request's locale, then reads and writes with overrideAccess. Raised on the PR rather than resolved here, since closing it is a product call that also touches the Transcript tab's button. Gate green on the merge: lint, both typechecks, 225 files / 2892 tests, prettier clean on the four resolved files, and role-based-access.int.spec.ts 81 passed. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01R2yfaBVaT7HyuB6pBjNsp6
`main` added `transcribeUrl` (#1011) to the same locale-URL inventory this branch removes `submissionActionUrl` from, and #996 re-measured the unit lane. Both sides' intent is kept. - `docs/rules/access.md`: main's two `MeditationTranscript` rows stay, the `SubmissionReview/urls.ts` row goes with the endpoint this branch deletes. The "build the URL in a pure module" list keeps `transcribeUrl` and the spec-pins clause, minus `submissionActionUrl`. - `tests/unit/admin-locale-urls.spec.ts`: main's `transcribeUrl` cases stay, the `submissionActionUrl` block is gone, so the docblock counts four sites and three pinned here. - `tests/PERF.md`, `docs/rules/testing-reqs.md`, `tests/AGENTS.md`: the merged tree measures 224 files / 2886 tests, not either side's figure. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_011e9ab9kznCHJEC3dgtLvjD
#1011 gave `transcriptPhase` a home in `lib/meditations/transcriptBounds.ts`, where `POST /api/meditations/:id/transcribe` refuses from it, while this branch made it take a `JobStageConfig` off `admin.custom`. The reviewer chose the constant (1A), so `main`'s signature and home stand and this branch drops its job-stage phase hunk: `jobStagePhase` is unexported again, the tab reads `useTranscriptPhase(row)`, and the two transcript specs keep `main`'s cases. The stage test stays stated twice, which #986's other two seams do not touch. The two remaining seams land unchanged. `MeditationTranscript` keeps reading its list through `payloadListFetcher`, now beside `main`'s `RetryTranscript`, and the three general config rules replace the two hand-written ones. Doc counts and the per-edit selection figures are the merged tree's. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DdfQKCGoojQ6zf3yAj8gsW
`main` added `POST /api/meditations/:id/transcribe` after this branch opened (#984, #1011). It proves `meditations: update` in `req.locale` and then reads the meditation and writes `meditation-transcripts` with `overrideAccess`, so the access function's `Where` reaches none of it — the grant this branch narrows everywhere else stayed collection-wide at that one door, and a `fr`-only editor could delete an `en` meditation's transcript and buy a new paid run. The handler now compares the row's own language, before the 409s and before the transaction that deletes the previous transcript. `isOutsideWritableLocale` is the predicate `restrictCreateToRequestLocale` already needed, so the comparison has one home rather than two: a non-admin manager whose `req.locale` differs from the document's language is refused, and the admin bypass answers first as it does for a write. The Transcript tab hides Transcribe-again on the same condition. A button that can only answer 403 is what the access layer avoided for Save. The predicate is mirrored in `transcriptModel.ts` rather than imported: the module owning the refusal pulls `payload` in with it, and the tab is a `'use client'` component. Both halves watched failing. With the refusal disarmed the new int case reads `expected 200 to be 403`; with the control's gate removed the tab case offers a button on a French meditation. The existing "admits them in theirs" case now uses a French meditation, since an `en` row with `?locale=fr` is the refusal this adds. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01J5xLK465nuE74yP41pduBW
Summary
tests/PERF.md's pinned spec count was already red onmain— re-pinned with the new specs.Change outline
Contract —
POST /api/meditations/:id/transcribeThe whole surface. No request body; the locale is a permission, not an option.
Deliberately absent from
CUSTOM_ENDPOINT_PATHS, so it is not published in the OpenAPI spec —openapi-custom-endpoints.spec.tsalready held that for this path.Flow — the two bounds, then the pair of writes
Decisions nested under the call that makes them.
meditationTranscribe(req) src/collections/Meditations/endpoints/transcribe.ts requireManagerPermission(meditations: update) # owns roleScopeFromLocale(req.locale) findByID meditations, draft: true, select { filename, locale } absent → 404 # `trash` not passed, so a trashed row reads absent no filename → 409 find meditation-transcripts { meditation: id } # no select: `status` is virtual, by afterRead + transcriptPhase(row) @/lib/meditations/transcriptBounds + !transcriptPhaseIsRetryable → 409 # completed, or a run inside the stall bound + retranscribeWaitMs(row.createdAt) @/lib/meditations/transcriptBounds + > 0 → 429 + Retry-After initTransaction(req) # an endpoint inherits none delete meditation-transcripts where { meditation: id } errors.length → throw # a where-delete collects failures, never throws create { meditation, audioFilename, language } afterChange queueTranscription # the row is the request; nothing queues by hand commitTransaction / killTransaction on any throw ValidationError on `meditation` → 409 # the loser of a raceComponents — the Transcript tab
The notice table keeps saying what each phase is; whether it may be asked for again is read from
the same function the endpoint refuses from.
Files — where the shared rule went
Preview
Data: not seeded —
previewUrl.seedis unset for this repo, and a PR preview carries nomeditations. Upload one with audio (admin only) to get a transcript row, then follow the steps
under Manual verification.
Test results
pnpm lint,pnpm typecheck,pnpm typecheck:tests,pnpm test:unit(220 files, 2832 tests), pluspnpm format:checktests/int/meditation-transcription.int.spec.ts28 passedEvery new assertion was watched failing first, against the defect it guards: the transaction
dropped, the cooldown raised above the stall bound, the cooldown check removed, the locale dropped
from the URL, the gate bypassed, the control's cooldown branch removed, a
selectadded to thetranscript lookup, the delete's
errorsleft unread, and the 409 re-read removed.Manual verification
PREVIEW_ADMIN_EMAILand create a meditation with an audio file.payload-jobsrow errored so the Transcript tab reads Transcription failed.completedwith timed cues, with nopage reload.
hand-made
POSTshould answer 429 withRetry-After.meditations-editor(not an admin), confirm step 3 works without an administrator.Notes for reviewer
transcriptPhasereads the row's own virtualstatus. The ticket's Approach said tore-derive it with
deriveTranscriptStatus, to avoid a narrowselectstarving that field.The lookup passes no
selectat all, so the field is already computed and the re-derivation wasa second statement of the same rule — which is also what would have forced
MeditationTranscripts/status.tsintosrc/lib/. It stays where it is. The int lane's phasecases are what hold this: add a
selectand the retry case goes red.retryAfterSecondsin the 429 body. The wait travels inRetry-Afterand in themessage; nothing read a third copy, and the control computes its own from
createdAt.role-based-access.int.spec.tsfor the gate cases. They are inmeditation-transcription.int.spec.tsinstead, which is whereframes-by-narratoranduser-submissions-reviewkeep theirs, and one environment per file is a hard rule.Detail
Dismissed review findings.
/simplify's four lenses,/code-review highand/security-reviewran over the branch. The security pass was empty. These were raised and notacted on:
TranscribeMeditation.findRecording, and thedelete-and-create pair duplicates
syncMeditationTranscript. The owners differ where it matters— a delete by id vs by
where, a filename comparison, its own transaction — so sharing themmeans changing two modules this ticket does not touch, on a PR that already carries a feature.
Both couplings are real: if the two ever disagree about which filename to store, the task throws
"the recording was replaced", which is why this endpoint reads the draft.
refusalis a third private copy of the error envelope (the two atlas endpoints haveerrorResponse). Extracting it into@/lib/endpointstouches endpoints outside this diff.isDuplicateTranscriptcould live in@/lib/databaseErrors. It is Payload trivia, notPostgres trivia:
@payloadcms/drizzle'shandleUpsertErrorconverts the23505into aValidationErrorand drops the driver error, so there is no SQLSTATE for that module to find.It stays beside its one caller, with the ⚠ saying why.
pressing a button; sequencing keeps the refusal order obvious.
Acted on after review. Five threads, all adopted. The control reads the recording off
useDocumentInfo().datarather than form state, which is the readAudioUploadalready makes onthis collection — the key is in form state (
filenameisadmin.hidden, which does notshort-circuit
addFieldStatePromise), but nothing else here relied on that and the mocked tabspec could not tell. The three zod-free modules are now one,
transcriptBounds.ts. Collapsingthat into
transcript.tsas well still needstranscriptSegmentsSchemamoved to its own field,per
src/collections/AGENTS.md— out of scope here.The route is now spelled for its verb,
POST /api/meditations/:id/transcribe, with the handler,its file and the URL builder following it. And
findTranscript— named in this list as a thirdcopy of the same unique-row lookup, and left alone — is gone the other way instead: it wrapped one
findfor one call site, so it is inlined, and the reason the read passes noselectnow sits atthe read rather than a screen below it.
What the bounds leave. One run per meditation per 10 minutes, and only on a meditation that is
failed,stalled, or has a recording and no row. The back catalogue predates #968 and so has norows: one run each, after which those meditations stop being eligible. No attempt-count column, for
the reason the ticket's Notes give — it cannot be derived across the recreation, so it needs a
column, and the residual it buys is one doomed recording costing six runs an hour to an audited
account.
Fixture pre-mortem. The int cases assume two things about the real configuration, both
verified: a row reads
failedbecause its retained job row carrieshasError(
deriveTranscriptStatusreads nothing else, andrunTaskHandlerbypasses the queue so a rejectedrun leaves the flag unset); and
createdAtis writable throughpayload.updatewhileupdatedAtis not, which is why the stalled case moves the clock instead
(
cleanup-orphaned-media.int.spec.tsages rows the same way). The tab spec adds one boundarybehaviour read off the real thing:
Buttonrenderstype="button"by default, which is what keepsa press out of the document's save.
Not this ticket's.
perf-figures-pinned.spec.tswas failing onmainbefore this branch —216 unit specs on disk against 215 recorded. The count commit fixes it; no timing was re-measured.
Closes #984
🤖 Written by the sydevs autonomous loop — see what this is
🤖 Generated with Claude Code
https://claude.ai/code/session_01FhKEe64iU3R2GgZb266wEf