From 6bfa5ade7844ed4b0894044cd72e2503f3e945da Mon Sep 17 00:00:00 2001 From: Amin Mousavi Date: Wed, 16 Sep 2026 04:19:42 +0800 Subject: [PATCH 01/10] docs(voice): spec voice entry for a lab case line MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One dictation fills one case line — teeth, prosthesis stack, comment — plus the case due date. The header's identity fields stay typed, which is what keeps every extracted field free of a patient name and leaves the transcript decision in voice-treatment-entry §10 closed. Lab mode is an empty treatmentTypes and labs catalog, not a second prompt. The prompt already renders both as empty, so the model cannot emit a field it has no list for and no prompt text changes. Four findings from reading the code shaped it: - voice.controller.ts:22 puts ClinicOrgGuard on the whole controller, so a LAB org gets 403 on both voice routes today. - listLinkedLabs (voice.service.ts:272) does not filter by org type. For a LAB org it returns the linked CLINICS, and the prompt labels them "LABS THIS CLINIC CAN SEND TO". Emptying the list is what stops a referring clinic coming back as labId. - The lab write validates only the prosthesis code (cases.service.ts:481) because the line and its jobs arrive in one transaction. Nothing rejects a teeth/jobs mismatch, so the apply keeps decision 40 itself. - TAB_TREATMENT_EDIT is clinic-only (organization-type.ts:14), so reusing it for the lab side would 403 every lab member including the owner. TAB_CASES_EDIT is the one that already gates Add Case. Mode is derived from the org type, never sent by the client. The save model needs no refs: CaseCreatePanel autosaves one PUT carrying header, lines and jobs together, so the ref coupling behind three of the five clinic defects cannot occur here. 14 decisions and a verification list in §10. No code yet. Co-Authored-By: Claude Opus 5 (1M context) --- docs/specs/voice-lab-case-entry/spec.md | 370 ++++++++++++++++++++++++ 1 file changed, 370 insertions(+) create mode 100644 docs/specs/voice-lab-case-entry/spec.md diff --git a/docs/specs/voice-lab-case-entry/spec.md b/docs/specs/voice-lab-case-entry/spec.md new file mode 100644 index 0000000..8d55136 --- /dev/null +++ b/docs/specs/voice-lab-case-entry/spec.md @@ -0,0 +1,370 @@ +--- +type: task +status: active +created: 2026-09-16 +repos: + - repo: dyolink + path: ~/PersonalProjects/dyolink + branch: feat/cases/add-voice-input-for-lab-case-line + base: origin/master + role: lab-mode extraction catalog + lab line apply + shared review sheet + spec_slug: voice-lab-case-entry + merge_after: [] +aliases: [voice lab case, lab dictation, case line voice, lab mic] +--- + +# Voice entry for a lab case line + +**Area:** Cases tab (LAB orgs) — `CaseCreatePanel` +**Created:** 2026-09-16 +**Depends on:** [`voice-treatment-entry`](../voice-treatment-entry/spec.md), already merged +to `master`. Every resolver, the prompt, the review sheet and the stack rules come from +there unchanged. This spec records only what differs. + +A lab owner entering their own work fills a case draft by hand: Add Line, tap the FDI +chart, open the prosthesis popover, pick a leaf, repeat. The clinic side already replaced +that with a microphone. The same dictation describes the same thing on the lab side — the +teeth and the job — so the same contract should fill it. + +--- + +## 1. Scope + +**In:** one dictation fills **one case line** — its teeth, its prosthesis stack, its +comment — plus the case's due date. + +**Out:** the case header's identity fields. Patient name, patient mobile, referring +dentist, referring clinic and the partner-clinic dropdown stay typed by hand (§9). + +The header is where a case carries a person's name. Keeping the mic away from it is what +lets this ship without reopening the transcript decision in `voice-treatment-entry` §10. + +--- + +## 2. What a lab line is + +`LineDraft` (`CaseCreatePanel.tsx:35`) is already the shape the extraction produces: + +```ts +type LineDraft = { + clientId: string; + id?: string; + teeth: FdiToothId[]; + toothSelectionGroups: ToothSelectionGroup[]; + comment: string; + toothProsthesis: Array<{ tooth; prosthesisTypeCode; selectionGroupId?; detailClientId }>; + attachments: LabCaseAttachmentMeta[]; +}; +``` + +Against a clinic `TreatmentDetailDraft` it has no `treatmentType` — on the lab side that is +always `prosthesis`, written server-side at `cases.service.ts:488` — and it folds the +clinic's separate `LabCaseDraft` rows into `toothProsthesis` on the line itself. + +Attachments are out of scope: dictation cannot produce one. + +### The save model is simpler than the clinic's, and that matters + +`CaseCreatePanel` autosaves through **one** `PUT /cases/:id` carrying the header, the lines +and their `toothProsthesis` together. `buildPayload` (`:177`) reads React **state**; the +debounced effect (`:239`) fires 500 ms after any state change; `persist` (`:210`) sends it. + +Two consequences, both load-bearing: + +1. **No ref dance.** The clinic side reads `detailsRef.current` and `labCaseDraftsRef.current` + because a save runs before the re-render. Here nothing saves inside the handler, so + `setLines` is the whole apply. Three of the five defects found in clinic live use were in + that ref coupling; they cannot occur here. +2. **No cross-request validation.** The clinic's lab rows go in a second request that + re-reads the saved detail and rejects a tooth the detail does not carry + (`TREATMENT_TOOTH_NOT_ON_DETAIL`, `treatments.service.ts:806`). The lab write validates + only the prosthesis code (`cases.service.ts:481`) because the line and its jobs arrive in + one transaction from one payload and cannot disagree. + +Point 2 cuts both ways: nothing *rejects* a mismatch either. A line whose `teeth` and +`toothProsthesis` disagree would be written silently, and the case chart would then show +something the generated tasks do not. §6 keeps the clinic's invariant for that reason. + +--- + +## 3. User flow + +``` +Cases tab → Add Case → draft opens in the right pane (CaseCreatePanel) + +┌──────────────────────────────────┐ +│ Patient [ typed ] │ +│ Dentist [ typed ] │ +│ Clinic [ dropdown / typed ] │ +│ Due [ AppDateInput ] │ ← the mic may write this +├──────────────────────────────────┤ +│ Lines [+ Add Line][🎤]│ ← the mic lives here +│ · Line 1 12,13 · PFM crown │ +└──────────────────────────────────┘ +``` + +1. Tap the mic. `VoiceRecordingBar` shows elapsed time and the level meter, exactly as on + the clinic side. +2. Tap stop. The clip goes to `POST /voice/extract`. +3. `VoiceReviewSheet` opens in lab mode with at most three rows (§5). +4. Confirm. The line lands, the autosave effect picks it up 500 ms later. + +The mic sits beside **Add Line** (`CaseCreatePanel.tsx:412-426`), built the same way +`AddDetailWithVoice` builds the clinic's split button, and shares its `disabled` state. + +**No new i18n keys.** Every voice string is under `treatment.*`, and `CaseCreatePanel` +already holds `tTreatment = useTranslations('treatment')` at `:110`. + +--- + +## 4. Lab mode is an empty catalog, not a second prompt + +`buildExtractionPrompt` renders whatever catalog it is handed. It already prints +`(none available)` for an empty code list and `(none linked — labId must be null)` for an +empty lab list. So lab mode needs **no prompt text change at all**: + +| Catalog field | CLINIC | LAB | Why | +|---|---|---|---| +| `treatmentTypes` | full list | `[]` | the type is always `prosthesis`, written server-side | +| `labs` | linked labs | `[]` | the lab *is* the destination | +| `prosthesisTypes` / categories / subcategories | full tree | full tree | unchanged | + +The model cannot emit a `treatmentType` or a `labId` because neither list has anything in +it. The resolver needs no change; the two fields simply come back null. + +### The bug this avoids + +`listLinkedLabs` (`voice.service.ts:272`) does **not** filter by organisation type. For a +LAB org it returns the linked **clinics**, and the prompt would present them under the +heading `LABS THIS CLINIC CAN SEND TO`. A lab owner naming their referring clinic would get +that clinic's id back as `labId`. Emptying the list is what stops it. + +### The narrowing is a pure function + +`buildCatalog` (`:257`) stays untested I/O. The decision comes out: + +```ts +export function narrowCatalogForOrgType( + catalog: ExtractionCatalog, + orgType: OrganizationTypeName, +): ExtractionCatalog; +``` + +`LAB` returns the catalog with `treatmentTypes: []` and `labs: []`. `CLINIC` returns it +untouched. It has its own spec (§10) because it is the one place a future change to +`listLinkedLabs` could silently reach lab callers again. + +--- + +## 5. Gating and permissions + +`voice.controller.ts:22` carries `@UseGuards(JwtAuthGuard, ClinicOrgGuard)`, so a LAB org +gets 403 on both voice routes today. That guard comes off the controller. + +Mode is **derived from the organisation, never sent by the client.** The selected org is +already in the JWT and is already the authority for every other service in this repo. + +``` +extract(user, dto, locale) + │ + ├─ getOrganizationTypeName(orgId) organization-type.ts:76 + │ + ├─ CLINIC → assert TAB_TREATMENT_EDIT (voice.service.ts:186, unchanged) + │ catalog: full + │ + └─ LAB → assert TAB_CASES_EDIT + catalog: narrowed +``` + +A `mode` field on the DTO was rejected: it can only ever hold one correct value per org, and +a body field deciding authorisation is a hole to guard rather than a fact to read. + +`assertCanEditTreatment` (`:186`) is renamed and generalised to take the permission code; +the clinic call site keeps `TAB_TREATMENT_EDIT`. + +`TAB_TREATMENT_EDIT` is clinic-only in `permissionsAllowedForOrgType`, so reusing it for the +lab side would 403 every lab member including the owner. `TAB_CASES_EDIT` is the permission +that already gates Add Case. + +**Availability** (`GET /voice/availability`) is one config for both sides. A separate lab +toggle is speculative — if voice is on, it is on. + +--- + +## 6. Review sheet: one component, one `mode` prop + +`voiceRowAvailability` takes a third argument. Three rows disappear on their own once the +catalog is empty; one has to be forced. + +| Row | CLINIC | LAB | +|---|---|---| +| Treatment type | when heard | never | +| Teeth (plain) | when not lab-dependent | never | +| Teeth and prosthesis | when lab-dependent | **always** | +| Note | when heard | when heard | +| Lab | when heard | never | +| Due date | when heard | when heard | + +The one that breaks without a change: `voiceRowAvailability` derives `labDependent` from the +treatment type. In lab mode the type is null, so `labDependent` would be **false** — showing +the plain teeth row and hiding the prosthesis row, exactly backwards. In lab mode it is +forced true. + +Everything else is identical, because a lab line and a prosthesis detail hold the same data: +the mini FDI chart, the target list, the stack preview through `applyLeafToJobs`, the struck +-through refused codes, the jobless targets, the candidate chips. + +That shared surface is the point. Five defects were fixed in this component over the last +week. A forked lab sheet would have needed all five fixed twice. + +--- + +## 7. Apply + +`buildLabLineFromVoice` in `frontend/src/components/lab/voiceLine.ts`, pure, its own spec. + +```ts +export function buildLabLineFromVoice( + result: VoiceExtractionResult, + selection: VoiceApplySelection, + ctx: { prosthesisCatalog: readonly ProsthesisCatalogEntry[] }, +): { line: LineDraft; dueDate: string | null }; +``` + +A sibling of `buildVoiceApplyPlan`, not a mode on it: the return shapes have nothing in +common, and a union return would recreate the thing that made the original callback hard to +test. Both call the same `prosthesisTargetLines` and `groupsFromFlatTeeth`, so the stack +rules and the bridge splitting stay in one place. + +### Rules it keeps from the clinic side + +- **Decision 40 — a tooth is on the line only by carrying a job.** The plain `teeth` list is + never copied across. Nothing on the lab side enforces this (§2), which is exactly why the + apply must; otherwise the case chart and the generated tasks disagree and neither is wrong + enough to throw. +- **Decision 39 — teeth and prosthesis apply together**, as one row. +- A code the stack rules refuse is not applied, and the sheet already said so. +- Non-adjacent teeth never share a `selectionGroupId` (`splitDisconnectedRuns`). On this side + a shared group id tells the lab's own task generator to build a bridge, so the consequence + is more direct than on the clinic side. + +### Where the line goes + +Fill the active line when it is **blank** — no teeth, no jobs, no comment, no attachments, +the exact state `newLine()` produces (`:50`) — otherwise append and make the new line active. + +A fresh draft opens with one blank line (`linesFromDetail` returns `[newLine()]`), so +always-append would leave a blank line above the dictated one on every first use. Nothing +rejects it: `start` only requires that *some* line has jobs (`cases.service.ts:551`), so the +blank line would ship to the floor. + +### One dictation is one line + +Whatever the dictation held goes into one line, even when it names several different jobs. +A line's `id` becomes the `sourceKey` (`cases.service.ts:487`) that `generateLabCaseTasks` +groups by, so this is a real choice, not a display one — but "one utterance, one line" is the +rule a lab owner can predict without knowing how tasks are grouped. Two lines means dictating +twice. + +### The due date + +The row stays, and ticking it calls the panel's `setDueDate` — the same state the +`AppDateInput` writes (`:129`). This is the single field outside the line that the mic +touches. A date is a resolved value with no identity in it, the resolver already handles +Jalali and per-locale week starts, and a lab owner will say "تا پنجشنبه" whether or not the +design planned for it. The sheet shows it before it lands and it can be unticked. + +--- + +## 8. Data handling + +Nothing changes. The transcript never leaves the server and is logged there at info level +(`voice-treatment-entry` §10). `logTelemetry` stays patient-free. + +The lab side does not weaken that: no extracted field carries a name, because the header is +out of scope (§1) and the catalog is narrowed (§4). + +--- + +## 9. Known gaps + +Recorded so the first manual pass does not read them as bugs. + +1. **A dictated referring clinic is dropped, with no mention.** "از مطب دکتر احمدی" produces + nothing and the sheet says nothing about it. Matching it would mean handing the model the + linked organisations again — the list §4 deliberately empties — and the result is a name. + Revisit only if it proves annoying in use. +2. **Patient name and mobile are typed.** Same reason, more sharply: these are the fields the + transcript decision exists to protect. +3. **Attachments are not dictatable.** Nothing to extract. +4. **`VoiceThrottlerGuard` limits are tuned for a dentist**, who dictates a few times per + visit. A lab owner entering a morning's cases will dictate far more often. Watch it in the + manual pass; do not retune it blind. + +--- + +## 10. Verification + +### Automated + +- `cd backend && npm test -- narrowCatalogForOrgType` — **new**: + - LAB drops `treatmentTypes` and `labs`; + - LAB keeps the prosthesis tree, its categories and its subcategories intact; + - CLINIC is returned unchanged. +- `cd backend && npm test` — the existing 220 must stay green. The resolver is untouched. +- `cd backend && npm run build`. +- `cd frontend && npx vitest run` — **new** `voiceLine.spec.ts`: + - a tooth reaches `line.teeth` only by carrying a job; + - every `toothProsthesis` row naming a real tooth is in `line.teeth` (the invariant + nothing enforces server-side); + - a jaw sentinel is in `toothProsthesis` with an empty `selectionGroupId` and is not a + tooth on the line; + - two non-adjacent teeth never share a `selectionGroupId`; + - an unticked note row leaves `comment` empty; + - the due date comes back separately and is null when its row is unticked. + - Plus `voiceReviewRows.spec.ts`: lab mode forces the prosthesis row on and the type, plain + teeth and lab rows off. + - Each new test must be shown to fail with its rule reverted, not merely to pass. +- `cd frontend && npx tsc --noEmit` — the cross-cutting gate. +- `cd frontend && npm run build`. +- ESLint on every touched file, no new warnings. + +### Manual — `fa`, LAB org, a linked clinic present + +1. Cases → Add Case. The mic is enabled beside Add Line. +2. «برای دندون ۱۲ و ۱۳ روکش پی‌اف‌ام میخوام» → the sheet shows one row, both teeth, the + crown on each. No treatment-type row. No lab row. +3. Confirm → line 1 is filled, **not** line 2. Wait 1 s, reload the case: it persisted. +4. Dictate again, «۲۶ زیرکونیا» → line 2 appears and becomes active. +5. «یه کامپلیت دنچر برای فک بالا» → the jaw is selected, no tooth is invented, and the chart + shows the arch highlight. +6. «توی یادداشت‌ها بنویس رنگ A2» → the note row appears with `رنگ A2` and nothing else. +7. «تا پنجشنبه» → the due date row appears; ticking it fills the header field. +8. «از مطب دکتر احمدی، ۱۲ روکش» → the crown lands, the clinic field stays empty, nothing is + said about it (§9 item 1). +9. Start the case → tasks generate, and the task groups match the lines. +10. As a lab member **without** `TAB_CASES_EDIT`: the mic is disabled, and a forced request + returns 403. +11. As a clinic user: the treatment workspace mic still behaves exactly as before. +12. Safari and iPad, since that is where the original recording defects appeared. + +--- + +## 11. Decision log + +| # | Decision | Why | +|---|---|---| +| 1 | One dictation fills one line; the header is typed | Keeps names out of every extracted field, so `voice-treatment-entry` §10 does not reopen (§1) | +| 2 | Lab mode is an empty `treatmentTypes` + `labs` catalog | The prompt already renders both as empty; zero prompt text changes, and the model cannot emit a field it has no list for (§4) | +| 3 | Mode is derived from the org type, never sent | The JWT's org is already the authority; a body field deciding authorisation is a hole to guard (§5) | +| 4 | `ClinicOrgGuard` off the controller; `TAB_CASES_EDIT` for LAB | `TAB_TREATMENT_EDIT` is clinic-only, so reusing it would 403 every lab member (§5) | +| 5 | Reuse `VoiceReviewSheet` with a `mode` prop | Five fixes landed in it this week; a fork would need all five twice (§6) | +| 6 | Force `labDependent` true in lab mode | A null treatment type would otherwise show the plain teeth row and hide the prosthesis row (§6) | +| 7 | `buildLabLineFromVoice` is a sibling, not a mode | The return shapes share nothing; a union return recreates the untestable callback (§7) | +| 8 | Keep decision 40 even though nothing enforces it | The lab write validates only the prosthesis code, so a mismatch is written silently rather than rejected (§2, §7) | +| 9 | Fill a blank active line, otherwise append | A fresh draft already holds one blank line, and `start` would ship it (§7) | +| 10 | One dictation is one line | `sourceKey` groups tasks by line, so splitting is a real choice — but predictability wins (§7) | +| 11 | The due date row stays and writes the header | The one non-line field; a date carries no identity, and it will be dictated anyway (§7) | +| 12 | The referring clinic is dropped silently | Matching it needs the org list §4 empties, and the result is a name (§9) | +| 13 | `narrowCatalogForOrgType` is extracted and unit tested | `voice.service` has never been unit tested; this is the one decision in it worth pinning (§4, §10) | +| 14 | No new i18n keys | Every voice string is under `treatment.*`, and `CaseCreatePanel` already holds that namespace (§3) | -- 2.53.0.windows.1 From 54044e44e6334c95b06c74b1fd9e0ef11862fd23 Mon Sep 17 00:00:00 2001 From: Amin Mousavi Date: Wed, 16 Sep 2026 04:27:26 +0800 Subject: [PATCH 02/10] docs(voice): add the lab-case-entry progress ledger Every /orchestrate stop path writes here, and preflight aborts without it. Records the two preflight blockers: no merge request template, and the repo being on Gitea while /orchestrate ends in GitLab-shaped merge requests. Co-Authored-By: Claude Opus 5 (1M context) --- docs/specs/voice-lab-case-entry/progress.md | 62 +++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 docs/specs/voice-lab-case-entry/progress.md diff --git a/docs/specs/voice-lab-case-entry/progress.md b/docs/specs/voice-lab-case-entry/progress.md new file mode 100644 index 0000000..862da6d --- /dev/null +++ b/docs/specs/voice-lab-case-entry/progress.md @@ -0,0 +1,62 @@ +--- +type: task-progress +status: active +repos: + - repo: dyolink + path: ~/PersonalProjects/dyolink + branch: feat/cases/add-voice-input-for-lab-case-line + base: origin/master + role: lab-mode extraction catalog + lab line apply + shared review sheet + spec_slug: voice-lab-case-entry + merge_after: [] +--- + +# Voice entry for a lab case line — progress + +Ledger for [`spec.md`](spec.md). Every `/orchestrate` stop path appends here. + +## Ledger + +| # | Item | State | +|---|---|---| +| 1 | `narrowCatalogForOrgType` + spec | not started | +| 2 | `ClinicOrgGuard` off the controller; `extract` branches on org type | not started | +| 3 | `assertCanEditTreatment` generalised to take a permission code | not started | +| 4 | `voiceRowAvailability(result, codes, mode)` | not started | +| 5 | `mode` prop on `VoiceReviewSheet` | not started | +| 6 | `buildLabLineFromVoice` + spec | not started | +| 7 | Mic beside Add Line in `CaseCreatePanel` | not started | +| 8 | Manual pass, `fa`, both org types (§10) | not started | + +## 2026-09-16 — spec written, branch cut + +`/grill-me` settled 14 decisions across 10 questions. Spec committed as `93c592f` on +`feat/cases/add-voice-input-for-lab-case-line`, branched from `master` at `554a31f` — which +already carries the merged `voice-treatment-entry` work this depends on. + +Four findings from reading the code shaped the design, each cited in the spec: + +| Finding | Where | +|---|---| +| `ClinicOrgGuard` on the whole controller, so a LAB org gets 403 on both voice routes | `voice.controller.ts:22` | +| `listLinkedLabs` does not filter by org type — a LAB org is handed its linked **clinics** under the heading "LABS THIS CLINIC CAN SEND TO" | `voice.service.ts:272` | +| The lab write validates only the prosthesis code, so a teeth/jobs mismatch is written silently rather than rejected | `cases.service.ts:481` | +| `TAB_TREATMENT_EDIT` is clinic-only, so reusing it would 403 every lab member including the owner | `organization-type.ts:14` | + +No code yet. + +## 2026-09-16 — `/orchestrate --dry` preflight + +Two blockers found before any agent was spawned. + +1. **No merge request template.** `.gitlab/merge_request_templates/*.md` does not exist, and + neither does `.github/`. The repo is on **Gitea** (`origin` is + `http://178.131.50.201:3000/admin/dyolink.git`), and `/orchestrate` ends in GitLab-shaped + merge requests. This is the same blocker that ended the 2026-09-06 run at 1 h 31 m and + 116 M tokens, that time discovered at Ship rather than at preflight. +2. **No progress note.** Created by this entry. + +Blocker 1 is not fixable inside this repo — the Ship phase targets the wrong forge, so a +template alone would not be enough. Amin chose to run everything except Ship: `dry: true` +commits locally and never pushes, so the run never reaches the phase that needs a template. +Teaching the clerk and courier about Gitea is its own task, upstream in `~/.claude`. -- 2.53.0.windows.1 From d557d926698639b6dc6ba645ff9910cb8cd926af Mon Sep 17 00:00:00 2001 From: Amin Mousavi Date: Wed, 16 Sep 2026 05:10:49 +0800 Subject: [PATCH 03/10] feat(voice): extend voice extraction to lab case line entry Adds a lab-mode narrowing of the catalog for voice extraction, lab case line draft/apply helpers, and a shared review sheet reused by both treatment and lab case flows. Co-Authored-By: Claude Sonnet 5 --- .../voice/narrowCatalogForOrgType.spec.ts | 64 ++++ .../modules/voice/narrowCatalogForOrgType.ts | 20 ++ backend/src/modules/voice/voice.controller.ts | 7 +- .../src/modules/voice/voice.service.spec.ts | 218 ++++++++++++++ backend/src/modules/voice/voice.service.ts | 42 ++- docs/specs/voice-lab-case-entry/progress.md | 72 ++++- frontend/src/components/lab/caseLineDraft.ts | 48 +++ frontend/src/components/lab/voiceLine.spec.ts | 277 ++++++++++++++++++ frontend/src/components/lab/voiceLine.ts | 70 +++++ .../treatment/voiceReviewRows.spec.ts | 56 ++++ .../components/treatment/voiceReviewRows.ts | 18 +- .../src/components/ui/lab/CaseCreatePanel.tsx | 214 +++++++++++--- .../ui/treatment/VoiceReviewSheet.tsx | 28 +- frontend/src/types/voice.ts | 6 + 14 files changed, 1059 insertions(+), 81 deletions(-) create mode 100644 backend/src/modules/voice/narrowCatalogForOrgType.spec.ts create mode 100644 backend/src/modules/voice/narrowCatalogForOrgType.ts create mode 100644 backend/src/modules/voice/voice.service.spec.ts create mode 100644 frontend/src/components/lab/caseLineDraft.ts create mode 100644 frontend/src/components/lab/voiceLine.spec.ts create mode 100644 frontend/src/components/lab/voiceLine.ts diff --git a/backend/src/modules/voice/narrowCatalogForOrgType.spec.ts b/backend/src/modules/voice/narrowCatalogForOrgType.spec.ts new file mode 100644 index 0000000..e5a7f74 --- /dev/null +++ b/backend/src/modules/voice/narrowCatalogForOrgType.spec.ts @@ -0,0 +1,64 @@ +import { narrowCatalogForOrgType } from './narrowCatalogForOrgType'; +import type { ExtractionCatalog } from './voice.providers'; + +const catalog = (): ExtractionCatalog => ({ + treatmentTypes: [ + { code: 'prosthesis', label: 'Prosthesis' }, + { code: 'restoration', label: 'Restoration' }, + ], + prosthesisTypes: [ + { + code: 'pfm_crown', + label: 'PFM Crown', + category: 'crown', + subcategory: '', + chartRegion: 'crown', + stackGroup: 'restoration', + }, + { + code: 'complete_denture', + label: 'Complete Denture', + category: 'denture', + subcategory: '', + chartRegion: 'arch', + stackGroup: 'arch', + }, + ], + prosthesisCategories: [ + { code: 'crown', label: 'Crown' }, + { code: 'denture', label: 'Denture' }, + ], + prosthesisSubcategories: [{ code: 'veneer', label: 'Veneer' }], + labs: [{ id: 'org-lab-1', name: 'Some Lab' }], +}); + +describe('narrowCatalogForOrgType', () => { + it('drops the treatment types and the linked labs for a LAB org', () => { + const narrowed = narrowCatalogForOrgType(catalog(), 'LAB'); + expect(narrowed.treatmentTypes).toEqual([]); + expect(narrowed.labs).toEqual([]); + }); + + it('keeps the prosthesis tree, its categories and its subcategories intact for a LAB org', () => { + const full = catalog(); + const narrowed = narrowCatalogForOrgType(full, 'LAB'); + expect(narrowed.prosthesisTypes).toEqual(full.prosthesisTypes); + expect(narrowed.prosthesisCategories).toEqual(full.prosthesisCategories); + expect(narrowed.prosthesisSubcategories).toEqual( + full.prosthesisSubcategories, + ); + }); + + it('returns the catalog unchanged for a CLINIC org', () => { + const full = catalog(); + expect(narrowCatalogForOrgType(full, 'CLINIC')).toEqual(catalog()); + expect(narrowCatalogForOrgType(full, 'CLINIC').labs).toHaveLength(1); + }); + + it('does not mutate the catalog it was given', () => { + const full = catalog(); + narrowCatalogForOrgType(full, 'LAB'); + expect(full.treatmentTypes).toHaveLength(2); + expect(full.labs).toHaveLength(1); + }); +}); diff --git a/backend/src/modules/voice/narrowCatalogForOrgType.ts b/backend/src/modules/voice/narrowCatalogForOrgType.ts new file mode 100644 index 0000000..6bd477e --- /dev/null +++ b/backend/src/modules/voice/narrowCatalogForOrgType.ts @@ -0,0 +1,20 @@ +import type { OrganizationTypeName } from '../../common/organization-type'; +import type { ExtractionCatalog } from './voice.providers'; + +/** + * A LAB org dictates into a case line: the treatment type is always `prosthesis` (written + * server-side) and the lab is the destination itself. Emptying both lists is the whole of lab + * mode — the prompt already renders an empty list as "(none available)", so the model has no + * code left to emit for either field. + * + * It also closes a hole: `listLinkedLabs` does not filter by organisation type, so for a LAB + * org it returns the linked *clinics*, and a lab owner naming their referring clinic would get + * that clinic's id back as `labId`. + */ +export function narrowCatalogForOrgType( + catalog: ExtractionCatalog, + orgType: OrganizationTypeName, +): ExtractionCatalog { + if (orgType !== 'LAB') return catalog; + return { ...catalog, treatmentTypes: [], labs: [] }; +} diff --git a/backend/src/modules/voice/voice.controller.ts b/backend/src/modules/voice/voice.controller.ts index 0b93657..1ad2794 100644 --- a/backend/src/modules/voice/voice.controller.ts +++ b/backend/src/modules/voice/voice.controller.ts @@ -9,7 +9,6 @@ import { } from '@nestjs/common'; import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger'; import type { Request, Response } from 'express'; -import { ClinicOrgGuard } from '../../common/guards/clinic-org.guard'; import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { ExtractVoiceDto } from './dto/voice.dto'; import { VoiceThrottlerGuard } from './voice-throttler.guard'; @@ -19,7 +18,9 @@ type VoiceRequestUser = { id: string; organizationId?: string }; @ApiTags('voice') @ApiBearerAuth('JWT-auth') -@UseGuards(JwtAuthGuard, ClinicOrgGuard) +// No org-type guard: both org types dictate, and the service branches on the selected org's +// type for the permission it asserts and for the catalog it hands the model. +@UseGuards(JwtAuthGuard) @Controller('voice') export class VoiceController { constructor(private readonly voiceService: VoiceService) {} @@ -41,7 +42,7 @@ export class VoiceController { @UseGuards(VoiceThrottlerGuard) @ApiOperation({ summary: - 'Transcribe a recording and extract treatment detail intents (TAB_TREATMENT_EDIT)', + 'Transcribe a recording and extract entry intents (CLINIC: TAB_TREATMENT_EDIT, LAB: TAB_CASES_EDIT)', }) async extract( @Req() req: Request & { user: VoiceRequestUser }, diff --git a/backend/src/modules/voice/voice.service.spec.ts b/backend/src/modules/voice/voice.service.spec.ts new file mode 100644 index 0000000..c21152a --- /dev/null +++ b/backend/src/modules/voice/voice.service.spec.ts @@ -0,0 +1,218 @@ +import { AppException, ErrorCode } from '../../common/errors'; +import { VoiceService } from './voice.service'; +import type { ExtractionCatalog, ExtractionResult } from './voice.providers'; +import type { ExtractVoiceDto } from './dto/voice.dto'; + +const mockExtract = jest.fn< + Promise, + [string, ExtractionCatalog, string] +>(); + +jest.mock('./openrouter.provider', () => ({ + OpenRouterAsrProvider: jest.fn().mockImplementation(() => ({ + transcribe: () => + Promise.resolve({ + text: 'tooth twelve, pfm crown', + usage: { costUsd: 0.001, seconds: 3 }, + }), + })), + OpenRouterExtractionProvider: jest.fn().mockImplementation(() => ({ + extract: (transcript: string, catalog: ExtractionCatalog, locale: string) => + mockExtract(transcript, catalog, locale), + })), +})); + +const EMPTY_INTENT = { + treatmentType: null, + teeth: [], + connectedSpans: [], + comment: null, + commentTrigger: null, + prosthesis: [], + labId: null, + labMatchExact: false, + due: null, +}; + +const DTO: ExtractVoiceDto = { + audio: 'AAAA', + format: 'webm', + timeZone: 'UTC', + durationMs: 3_000, + locale: 'en', +}; + +function buildService(opts: { + orgType: 'CLINIC' | 'LAB'; + permissions: string[]; +}): VoiceService { + const prisma = { + organization: { + findUnique: jest.fn().mockResolvedValue({ type: { name: opts.orgType } }), + }, + membership: { + findFirst: jest.fn().mockResolvedValue({ + isOwner: false, + organization: { type: { name: opts.orgType }, plan: { name: 'pro' } }, + permissions: opts.permissions.map((name) => ({ + permission: { name }, + })), + }), + }, + // The counterpart link a lab org has: `listLinkedLabs` does not filter by org type, so + // for a LAB org this row is a linked *clinic*. + organizationLink: { + findMany: jest + .fn() + .mockResolvedValueOnce([ + { organizationB: { id: 'org-counterpart', name: 'Counterpart' } }, + ]) + .mockResolvedValue([]), + }, + }; + + const config = { + get: () => ({ + openRouter: { apiKey: 'test-key', baseUrl: 'https://example.invalid' }, + profiles: { + en: { + asr: { provider: 'openrouter', model: 'asr-model' }, + llm: { provider: 'openrouter', model: 'llm-model' }, + }, + }, + maxRecordingMs: 120_000, + throttle: { ttl: 60, limit: 10 }, + }), + }; + + const treatmentCatalog = { + list: jest.fn().mockResolvedValue([ + { code: 'prosthesis', label: 'Prosthesis', availableInTreatment: true }, + { code: 'restoration', label: 'Restoration', availableInTreatment: true }, + ]), + }; + + const prosthesisCatalog = { + list: jest.fn().mockResolvedValue([ + { + code: 'pfm_crown', + label: 'PFM Crown', + category: 'crown', + subcategory: '', + chartRegion: 'crown', + stackGroup: 'restoration', + }, + ]), + listCategories: jest + .fn() + .mockResolvedValue([{ code: 'crown', label: 'Crown' }]), + listSubcategories: jest + .fn() + .mockResolvedValue([{ code: 'veneer', label: 'Veneer' }]), + }; + + return new VoiceService( + prisma as never, + config as never, + treatmentCatalog as never, + prosthesisCatalog as never, + ); +} + +async function codeOfThrown(promise: Promise): Promise { + try { + await promise; + return 'NO_THROW'; + } catch (error) { + return error instanceof AppException + ? (error.getResponse() as { code: string }).code + : `UNEXPECTED:${String(error)}`; + } +} + +describe('VoiceService.extract — the org type decides the permission and the catalog', () => { + beforeEach(() => { + mockExtract.mockReset(); + mockExtract.mockResolvedValue({ intent: EMPTY_INTENT, costUsd: 0.002 }); + }); + + const user = { id: 'user-1', organizationId: 'org-1' }; + + it('C01 CLINIC granted: TAB_TREATMENT_EDIT passes, and the model gets the full catalog', async () => { + const service = buildService({ + orgType: 'CLINIC', + permissions: ['TAB_TREATMENT_EDIT'], + }); + + await service.extract(user, DTO, 'en'); + + const catalog = mockExtract.mock.calls[0][1]; + expect(catalog.treatmentTypes.map((t) => t.code)).toEqual([ + 'prosthesis', + 'restoration', + ]); + expect(catalog.labs).toHaveLength(1); + }); + + it('C02 CLINIC denied: no TAB_TREATMENT_EDIT is 403 and never reaches the model', async () => { + const service = buildService({ + orgType: 'CLINIC', + permissions: ['TAB_TREATMENT_READ'], + }); + + expect(await codeOfThrown(service.extract(user, DTO, 'en'))).toBe( + ErrorCode.PERMISSION_EDIT_TREATMENTS, + ); + expect(mockExtract).not.toHaveBeenCalled(); + }); + + it('C03 LAB granted: TAB_CASES_EDIT passes, and the model gets no treatment types and no labs', async () => { + const service = buildService({ + orgType: 'LAB', + permissions: ['TAB_CASES_EDIT'], + }); + + await service.extract(user, DTO, 'en'); + + const catalog = mockExtract.mock.calls[0][1]; + expect(catalog.treatmentTypes).toEqual([]); + expect(catalog.labs).toEqual([]); + expect(catalog.prosthesisTypes.map((p) => p.code)).toEqual(['pfm_crown']); + }); + + it('C04 LAB denied: no TAB_CASES_EDIT is 403 and never reaches the model', async () => { + const service = buildService({ + orgType: 'LAB', + permissions: ['TAB_CASES_READ'], + }); + + expect(await codeOfThrown(service.extract(user, DTO, 'en'))).toBe( + ErrorCode.PERMISSION_ACCESS_CASES, + ); + expect(mockExtract).not.toHaveBeenCalled(); + }); + + it('denies a LAB member holding the clinic-side edit permission', async () => { + // TAB_TREATMENT_EDIT is clinic-only, so it must not open the lab route. + const service = buildService({ + orgType: 'LAB', + permissions: ['TAB_TREATMENT_EDIT'], + }); + + expect(await codeOfThrown(service.extract(user, DTO, 'en'))).toBe( + ErrorCode.PERMISSION_ACCESS_CASES, + ); + }); + + it('rejects a request with no selected organisation before any vendor call', async () => { + const service = buildService({ + orgType: 'LAB', + permissions: ['TAB_CASES_EDIT'], + }); + + expect( + await codeOfThrown(service.extract({ id: 'user-1' }, DTO, 'en')), + ).toBe(ErrorCode.AUTH_ORG_NOT_SELECTED); + expect(mockExtract).not.toHaveBeenCalled(); + }); +}); diff --git a/backend/src/modules/voice/voice.service.ts b/backend/src/modules/voice/voice.service.ts index 7c554cf..68eb02a 100644 --- a/backend/src/modules/voice/voice.service.ts +++ b/backend/src/modules/voice/voice.service.ts @@ -9,6 +9,11 @@ import { } from '../../common/zoned-civil-time'; import type { VoiceConfig, VoiceProfile } from '../../configs/configurations'; import { hasEffectivePermission } from '../../common/membership-permissions'; +import { + getOrganizationTypeName, + type OrganizationTypeName, +} from '../../common/organization-type'; +import { narrowCatalogForOrgType } from './narrowCatalogForOrgType'; import { normalizeCatalogLocale } from '../catalog/catalog-label.service'; import { ProsthesisCatalogService } from '../prosthesis-catalog/prosthesis-catalog.service'; import { TreatmentCatalogService } from '../treatment-catalog/treatment-catalog.service'; @@ -80,7 +85,7 @@ export class VoiceService { ): Promise { const startedAt = Date.now(); const organizationId = this.assertOrganization(user); - await this.assertCanEditTreatment(user.id, organizationId); + const orgType = await this.assertCanDictate(user.id, organizationId); const catalogLocale = normalizeCatalogLocale(locale); const profile = this.resolveProfile(catalogLocale); @@ -136,7 +141,10 @@ export class VoiceService { try { // Inside the try: a catalog/DB failure here must surface as VOICE_EXTRACT_FAILED, which // the clinician can act on, rather than a generic 500. - const catalog = await this.buildCatalog(organizationId, catalogLocale); + const catalog = narrowCatalogForOrgType( + await this.buildCatalog(organizationId, catalogLocale), + orgType, + ); const result = await extraction.extract( transcript, catalog, @@ -183,7 +191,27 @@ export class VoiceService { return user.organizationId; } - private async assertCanEditTreatment(userId: string, organizationId: string) { + /** + * The one gate on dictation, and the source of the extraction mode: the selected org's type + * decides both the permission asserted and — through the returned type — the catalog the + * model is handed. It is never taken from the request body. + * + * `TAB_TREATMENT_EDIT` is clinic-only in `permissionsAllowedForOrgType`, so reusing it on + * the lab side would deny every lab member including the owner. + */ + private async assertCanDictate( + userId: string, + organizationId: string, + ): Promise { + const orgType = await getOrganizationTypeName(this.prisma, organizationId); + const [permission, deniedCode] = + orgType === 'LAB' + ? (['TAB_CASES_EDIT', ErrorCode.PERMISSION_ACCESS_CASES] as const) + : ([ + 'TAB_TREATMENT_EDIT', + ErrorCode.PERMISSION_EDIT_TREATMENTS, + ] as const); + const membership = await this.prisma.membership.findFirst({ where: { userId, @@ -201,12 +229,10 @@ export class VoiceService { HttpStatus.FORBIDDEN, ); } - if (!hasEffectivePermission(membership, 'TAB_TREATMENT_EDIT')) { - throw new AppException( - ErrorCode.PERMISSION_EDIT_TREATMENTS, - HttpStatus.FORBIDDEN, - ); + if (!hasEffectivePermission(membership, permission)) { + throw new AppException(deniedCode, HttpStatus.FORBIDDEN); } + return orgType; } private resolveProfile(locale: string): VoiceProfile { diff --git a/docs/specs/voice-lab-case-entry/progress.md b/docs/specs/voice-lab-case-entry/progress.md index 862da6d..2e5edd6 100644 --- a/docs/specs/voice-lab-case-entry/progress.md +++ b/docs/specs/voice-lab-case-entry/progress.md @@ -19,13 +19,13 @@ Ledger for [`spec.md`](spec.md). Every `/orchestrate` stop path appends here. | # | Item | State | |---|---|---| -| 1 | `narrowCatalogForOrgType` + spec | not started | -| 2 | `ClinicOrgGuard` off the controller; `extract` branches on org type | not started | -| 3 | `assertCanEditTreatment` generalised to take a permission code | not started | -| 4 | `voiceRowAvailability(result, codes, mode)` | not started | -| 5 | `mode` prop on `VoiceReviewSheet` | not started | -| 6 | `buildLabLineFromVoice` + spec | not started | -| 7 | Mic beside Add Line in `CaseCreatePanel` | not started | +| 1 | `narrowCatalogForOrgType` + spec | done | +| 2 | `ClinicOrgGuard` off the controller; `extract` branches on org type | done | +| 3 | `assertCanEditTreatment` generalised to take a permission code | done | +| 4 | `voiceRowAvailability(result, codes, mode)` | done | +| 5 | `mode` prop on `VoiceReviewSheet` | done | +| 6 | `buildLabLineFromVoice` + spec | done | +| 7 | Mic beside Add Line in `CaseCreatePanel` | done | | 8 | Manual pass, `fa`, both org types (§10) | not started | ## 2026-09-16 — spec written, branch cut @@ -60,3 +60,61 @@ Blocker 1 is not fixable inside this repo — the Ship phase targets the wrong f template alone would not be enough. Amin chose to run everything except Ship: `dry: true` commits locally and never pushes, so the run never reaches the phase that needs a template. Teaching the clerk and courier about Gitea is its own task, upstream in `~/.claude`. + +## 2026-09-16 — implementation, repo `dyolink` + +All seven code items landed on `feat/cases/add-voice-input-for-lab-case-line`. Not committed. + +### Backend + +| File | Change | +|---|---| +| `backend/src/modules/voice/narrowCatalogForOrgType.ts` | **new** — `LAB` empties `treatmentTypes` and `labs`, `CLINIC` passes through | +| `backend/src/modules/voice/narrowCatalogForOrgType.spec.ts` | **new** — the three §10 cases plus a no-mutation case | +| `backend/src/modules/voice/voice.controller.ts` | `ClinicOrgGuard` removed; `JwtAuthGuard` stays | +| `backend/src/modules/voice/voice.service.ts` | `assertCanEditTreatment` → `assertCanDictate`, which resolves the org type, asserts `TAB_TREATMENT_EDIT` (CLINIC) or `TAB_CASES_EDIT` (LAB), and returns the type so `extract` narrows the catalog with it | +| `backend/src/modules/voice/voice.service.spec.ts` | **new** — the four matrix cells through `extract`, with the OpenRouter providers mocked so the catalog handed to the model is asserted | + +The LAB denial code is `PERMISSION_ACCESS_CASES`, matching `cases.service.ts:1391`. The spec did +not name one and no `PERMISSION_EDIT_CASES` exists; reusing the existing code keeps decision 14 +(no new i18n keys) intact. + +### Frontend + +| File | Change | +|---|---| +| `frontend/src/types/voice.ts` | **new** `VoiceEntryMode = 'clinic' \| 'lab'` | +| `frontend/src/components/treatment/voiceReviewRows.ts` | `voiceRowAvailability` / `initialVoiceSelection` / `hasAnythingToApply` take `mode`, defaulting to `'clinic'`; lab mode forces `labDependent` true and hides the type and lab rows | +| `frontend/src/components/ui/treatment/VoiceReviewSheet.tsx` | `mode` prop; `treatmentCatalog`, `labs` and `labDependentCodes` are now optional, since lab mode renders none of the rows that need them | +| `frontend/src/components/lab/caseLineDraft.ts` | **new** — `LineDraft`, `newLine` and `isBlankLine`, moved out of `CaseCreatePanel` so the pure apply helper can use them without importing from `ui/` | +| `frontend/src/components/lab/voiceLine.ts` | **new** `buildLabLineFromVoice`, through the shared `prosthesisTargetLines` and `groupsFromFlatTeeth` | +| `frontend/src/components/lab/voiceLine.spec.ts` | **new** — the six §10 rules plus the `isBlankLine` bounds | +| `frontend/src/components/treatment/voiceReviewRows.spec.ts` | lab-mode rows added | +| `frontend/src/components/ui/lab/CaseCreatePanel.tsx` | `useVoiceCapture` + `VoiceRecordingBar` + `VoiceReviewSheet mode="lab"`; `AddLineWithVoice` split button beside Add Line, sharing its `disabled` | + +### Verification + +| Command | Result | +|---|---| +| `cd backend && npm test` | 230 passed, 18 suites | +| `cd backend && npm run build` | clean | +| `cd frontend && npx vitest run` | 98 passed, 5 files | +| `cd frontend && npx tsc --noEmit` | clean | +| `cd frontend && npm run build` | clean | +| `cd frontend && npm run lint` | 0 errors and 0 warnings on every touched file | + +Matrix cells recorded through `gate-run` (`.git/orchestrate/ledger.jsonl`), each running exactly +one test: C01 CLINIC granted, C02 CLINIC denied, C03 LAB granted, C04 LAB denied. + +Every new rule was also shown to fail when reverted: the decision-40 filter, the +`splitDisconnectedRuns` seeding, the forced `labDependent`, the hidden type/lab rows, the +catalog narrowing, and the per-org-type permission branch. + +### Left for the manual pass + +- §10 items 1–12, `fa`, a LAB org with a linked clinic. +- `treatment.voiceStart` reads "Record treatment" beside Add Line. It is reused rather than + duplicated, per decision 14. Rename it later if it reads wrong in `fa`. +- If the model emits a `labId` or a `treatmentType` despite the emptied lists, the resolver + still pushes an `unknown_catalog_code` unresolved item, which the sheet renders. The spec + does not say lab mode should drop those, so nothing does. Watch for it at §10 item 8. diff --git a/frontend/src/components/lab/caseLineDraft.ts b/frontend/src/components/lab/caseLineDraft.ts new file mode 100644 index 0000000..8ae904a --- /dev/null +++ b/frontend/src/components/lab/caseLineDraft.ts @@ -0,0 +1,48 @@ +import type { ToothSelectionGroup } from '@/components/treatment/toothSelectionGroups'; +import type { LabCaseAttachmentMeta } from '@/types/cases'; +import type { FdiToothId } from '@/types/treatment'; + +/** + * One editable case line. Against a clinic `TreatmentDetailDraft` it carries no treatment type + * — the lab side is always `prosthesis`, written server-side — and folds the clinic's separate + * lab-case rows into `toothProsthesis` on the line itself. + */ +export type LineDraft = { + clientId: string; + id?: string; + teeth: FdiToothId[]; + toothSelectionGroups: ToothSelectionGroup[]; + comment: string; + toothProsthesis: Array<{ + tooth: string; + prosthesisTypeCode: string; + selectionGroupId?: string; + detailClientId: string; + }>; + attachments: LabCaseAttachmentMeta[]; +}; + +export function newLine(): LineDraft { + const clientId = + typeof crypto !== 'undefined' && 'randomUUID' in crypto + ? crypto.randomUUID() + : `line-${Date.now()}`; + return { + clientId, + teeth: [], + toothSelectionGroups: [], + comment: '', + toothProsthesis: [], + attachments: [], + }; +} + +/** Exactly the state `newLine` produces — what a dictation may overwrite instead of appending. */ +export function isBlankLine(line: LineDraft): boolean { + return ( + line.teeth.length === 0 && + line.toothProsthesis.length === 0 && + line.comment.trim() === '' && + line.attachments.length === 0 + ); +} diff --git a/frontend/src/components/lab/voiceLine.spec.ts b/frontend/src/components/lab/voiceLine.spec.ts new file mode 100644 index 0000000..4532f0e --- /dev/null +++ b/frontend/src/components/lab/voiceLine.spec.ts @@ -0,0 +1,277 @@ +import { describe, expect, it } from 'vitest'; +import { ARCH_TOOTH_UPPER, isArchSentinel } from '@/components/treatment/prosthesisTree'; +import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog'; +import type { VoiceApplySelection, VoiceExtractionResult } from '@/types/voice'; +import { isBlankLine, newLine } from './caseLineDraft'; +import { buildLabLineFromVoice } from './voiceLine'; + +const CATALOG: ProsthesisCatalogEntry[] = [ + { + code: 'pfm_crown', + sortOrder: 1, + label: 'PFM Crown', + category: 'crown', + subcategory: '', + chartRegion: 'crown', + stackGroup: 'restoration', + }, + { + code: 'cast_post_core', + sortOrder: 2, + label: 'Cast Post & Core', + category: 'post_core', + subcategory: '', + chartRegion: 'root', + stackGroup: 'post_core', + }, + { + code: 'complete_denture', + sortOrder: 3, + label: 'Complete Denture', + category: 'denture', + subcategory: '', + chartRegion: 'arch', + stackGroup: 'arch', + }, +]; + +const ctx = { prosthesisCatalog: CATALOG }; + +const result = (overrides: Partial = {}): VoiceExtractionResult => ({ + treatmentType: null, + teeth: [], + toothSelectionGroups: [], + comment: null, + prosthesisAssignments: [], + labId: null, + labMatchExact: false, + dueDate: null, + unresolved: [], + ...overrides, +}); + +const allTicked: VoiceApplySelection = { + treatmentType: true, + teeth: true, + comment: true, + prosthesis: true, + lab: true, + dueDate: true, +}; +const tick = (overrides: Partial = {}): VoiceApplySelection => ({ + ...allTicked, + ...overrides, +}); + +describe('buildLabLineFromVoice — which teeth reach the line', () => { + it('puts a tooth on the line only when it carries a job', () => { + const { line } = buildLabLineFromVoice( + result({ + teeth: ['12', '14', '16'], + prosthesisAssignments: [{ targets: ['12', '14'], types: ['pfm_crown'], spoken: '' }], + }), + tick(), + ctx, + ); + expect(line.teeth).toEqual(['12', '14']); + }); + + it('never copies the plain teeth list across', () => { + const { line } = buildLabLineFromVoice(result({ teeth: ['21', '22'] }), tick(), ctx); + expect(line.teeth).toEqual([]); + expect(line.toothProsthesis).toEqual([]); + }); + + it('leaves a target off the line when every code it named was refused', () => { + const { line } = buildLabLineFromVoice( + result({ + teeth: ['12'], + // Not in the catalog, so the stack rules refuse it and nothing lands. + prosthesisAssignments: [{ targets: ['12'], types: ['not_in_catalog'], spoken: '' }], + }), + tick(), + ctx, + ); + expect(line.teeth).toEqual([]); + expect(line.toothProsthesis).toEqual([]); + }); + + it('keeps the invariant nothing enforces server-side: every job names a tooth on the line', () => { + const { line } = buildLabLineFromVoice( + result({ + teeth: ['16'], + prosthesisAssignments: [ + { targets: ['12', '13'], types: ['pfm_crown'], spoken: '' }, + { targets: [ARCH_TOOTH_UPPER], types: ['complete_denture'], spoken: '' }, + ], + }), + tick(), + ctx, + ); + const onTeeth = line.toothProsthesis + .filter((row) => !isArchSentinel(row.tooth)) + .map((row) => row.tooth); + expect(onTeeth.length).toBeGreaterThan(0); + for (const tooth of onTeeth) { + expect(line.teeth).toContain(tooth); + } + }); +}); + +describe('buildLabLineFromVoice — prosthesis rows', () => { + it('applies a stack in landing order and drops a code the stack rules refuse', () => { + const { line } = buildLabLineFromVoice( + result({ + prosthesisAssignments: [ + // A post & core cannot go under a crown that is already there. + { targets: ['12'], types: ['pfm_crown', 'cast_post_core'], spoken: '' }, + ], + }), + tick(), + ctx, + ); + expect(line.toothProsthesis.map((row) => row.prosthesisTypeCode)).toEqual(['pfm_crown']); + }); + + it('carries a jaw appliance with an empty selection group and adds no tooth', () => { + const { line } = buildLabLineFromVoice( + result({ + prosthesisAssignments: [ + { targets: [ARCH_TOOTH_UPPER], types: ['complete_denture'], spoken: '' }, + ], + }), + tick(), + ctx, + ); + expect(line.toothProsthesis).toEqual([ + { + detailClientId: line.clientId, + tooth: ARCH_TOOTH_UPPER, + prosthesisTypeCode: 'complete_denture', + selectionGroupId: '', + }, + ]); + expect(line.teeth).toEqual([]); + }); + + it('never gives two non-adjacent teeth the same selection group', () => { + const { line } = buildLabLineFromVoice( + result({ + // Dictated as one connected span, but 12 and 16 are not neighbours: a shared group id + // would tell the task generator to build a bridge across the gap. + toothSelectionGroups: [{ groupId: 'g1', kind: 'connected', teeth: ['12', '16'] }], + prosthesisAssignments: [{ targets: ['12', '16'], types: ['pfm_crown'], spoken: '' }], + }), + tick(), + ctx, + ); + const groupOf = (tooth: string) => + line.toothProsthesis.find((row) => row.tooth === tooth)?.selectionGroupId; + expect(groupOf('12')).toBeTruthy(); + expect(groupOf('16')).toBeTruthy(); + expect(groupOf('12')).not.toBe(groupOf('16')); + }); + + it('keeps adjacent teeth dictated as a bridge in one selection group', () => { + const { line } = buildLabLineFromVoice( + result({ + toothSelectionGroups: [{ groupId: 'g1', kind: 'connected', teeth: ['12', '13'] }], + prosthesisAssignments: [{ targets: ['12', '13'], types: ['pfm_crown'], spoken: '' }], + }), + tick(), + ctx, + ); + const groupOf = (tooth: string) => + line.toothProsthesis.find((row) => row.tooth === tooth)?.selectionGroupId; + expect(groupOf('12')).toBe(groupOf('13')); + }); + + it('writes nothing at all when the prosthesis row is unticked', () => { + const { line } = buildLabLineFromVoice( + result({ + prosthesisAssignments: [{ targets: ['12'], types: ['pfm_crown'], spoken: '' }], + }), + tick({ prosthesis: false }), + ctx, + ); + expect(line.teeth).toEqual([]); + expect(line.toothProsthesis).toEqual([]); + }); +}); + +describe('buildLabLineFromVoice — the note and the due date', () => { + it('takes the note when its row is ticked', () => { + const { line } = buildLabLineFromVoice(result({ comment: 'shade A2' }), tick(), ctx); + expect(line.comment).toBe('shade A2'); + }); + + it('leaves the comment empty when the note row is unticked', () => { + const { line } = buildLabLineFromVoice( + result({ comment: 'shade A2' }), + tick({ comment: false }), + ctx, + ); + expect(line.comment).toBe(''); + }); + + it('returns the due date separately from the line', () => { + const built = buildLabLineFromVoice(result({ dueDate: '2026-09-24' }), tick(), ctx); + expect(built.dueDate).toBe('2026-09-24'); + expect(built.line).not.toHaveProperty('dueDate'); + }); + + it('returns a null due date when its row is unticked', () => { + const built = buildLabLineFromVoice( + result({ dueDate: '2026-09-24' }), + tick({ dueDate: false }), + ctx, + ); + expect(built.dueDate).toBeNull(); + }); + + it('writes no lab destination anywhere, even with a labId and its row ticked', () => { + const { line } = buildLabLineFromVoice( + result({ labId: 'org-clinic-1', labMatchExact: true }), + tick(), + ctx, + ); + expect(JSON.stringify(line)).not.toContain('org-clinic-1'); + }); +}); + +describe('isBlankLine — whether a dictation fills the active line or appends', () => { + it('is true for the exact state newLine produces', () => { + expect(isBlankLine(newLine())).toBe(true); + }); + + it('is false once the line carries teeth, a job, a comment or an attachment', () => { + expect(isBlankLine({ ...newLine(), teeth: ['12'] })).toBe(false); + expect( + isBlankLine({ + ...newLine(), + toothProsthesis: [ + { tooth: '12', prosthesisTypeCode: 'pfm_crown', detailClientId: 'x' }, + ], + }), + ).toBe(false); + expect(isBlankLine({ ...newLine(), comment: 'shade A2' })).toBe(false); + expect( + isBlankLine({ + ...newLine(), + attachments: [ + { + id: 'a1', + fileName: 'x.png', + mimeType: 'image/png', + sizeBytes: 1, + createdAt: '2026-09-16', + } as never, + ], + }), + ).toBe(false); + }); + + it('is true for a line whose only content is whitespace', () => { + expect(isBlankLine({ ...newLine(), comment: ' ' })).toBe(true); + }); +}); diff --git a/frontend/src/components/lab/voiceLine.ts b/frontend/src/components/lab/voiceLine.ts new file mode 100644 index 0000000..c37761c --- /dev/null +++ b/frontend/src/components/lab/voiceLine.ts @@ -0,0 +1,70 @@ +import { groupsFromFlatTeeth } from '@/components/treatment/toothSelectionGroups'; +import { prosthesisTargetLines } from '@/components/treatment/voiceReviewRows'; +import type { FdiToothId } from '@/types/treatment'; +import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog'; +import type { VoiceApplySelection, VoiceExtractionResult } from '@/types/voice'; +import { newLine, type LineDraft } from './caseLineDraft'; + +export interface VoiceLineContext { + prosthesisCatalog: readonly ProsthesisCatalogEntry[]; +} + +/** + * Turns a confirmed review sheet into one case line, plus the case's due date. + * + * A sibling of `buildVoiceApplyPlan` rather than a mode on it — the return shapes share + * nothing — but both go through `prosthesisTargetLines` and `groupsFromFlatTeeth`, so the + * stack rules and the bridge splitting stay in one place. + * + * The due date comes back separately because it belongs to the case header, not to the line. + */ +export function buildLabLineFromVoice( + result: VoiceExtractionResult, + selection: VoiceApplySelection, + ctx: VoiceLineContext, +): { line: LineDraft; dueDate: string | null } { + const line = newLine(); + + if (selection.comment && result.comment) { + line.comment = result.comment; + } + + // The stack that will actually land, built through the same `applyLeafToJobs` the manual + // chart writes through — a code the stack rules refuse is not applied. + const targetLines = selection.prosthesis + ? prosthesisTargetLines(result.prosthesisAssignments, ctx.prosthesisCatalog) + : []; + + // A tooth is on the line only by carrying a job (decision 40). The plain `teeth` list is + // never copied across: the lab write validates only the prosthesis code, so a line whose + // teeth and jobs disagree would be saved silently and the generated tasks would not match + // the chart. + const teeth = targetLines + .filter((target) => !target.isJaw && target.applied.length > 0) + .map((target) => target.target as FdiToothId); + + line.teeth = teeth; + // Seeded from the dictated groups, so `splitDisconnectedRuns` runs: on this side a shared + // group id tells the task generator to build a bridge across the gap. + line.toothSelectionGroups = groupsFromFlatTeeth(teeth, result.toothSelectionGroups); + + line.toothProsthesis = targetLines.flatMap((target) => { + // A jaw appliance belongs to no selection group; a tooth takes the group it landed in. + const selectionGroupId = target.isJaw + ? '' + : (line.toothSelectionGroups.find((group) => + (group.teeth as readonly string[]).includes(target.target), + )?.groupId ?? ''); + return target.applied.map((prosthesisTypeCode) => ({ + detailClientId: line.clientId, + tooth: target.target, + prosthesisTypeCode, + selectionGroupId, + })); + }); + + return { + line, + dueDate: selection.dueDate && result.dueDate ? result.dueDate : null, + }; +} diff --git a/frontend/src/components/treatment/voiceReviewRows.spec.ts b/frontend/src/components/treatment/voiceReviewRows.spec.ts index 7b997ca..05f8635 100644 --- a/frontend/src/components/treatment/voiceReviewRows.spec.ts +++ b/frontend/src/components/treatment/voiceReviewRows.spec.ts @@ -425,3 +425,59 @@ describe('hasAnythingToApply', () => { expect(hasAnythingToApply(baseResult({ teeth: ['14'] }), LAB_DEPENDENT)).toBe(true); }); }); + +describe('voiceRowAvailability in lab mode', () => { + // A lab line has no treatment type at all, so the derived labDependent flag would be false + // and the rows would come out exactly backwards. + const labResult = baseResult({ + treatmentType: null, + teeth: ['12'], + prosthesisAssignments: [{ targets: ['12'], types: ['pfm_crown'], spoken: '' }], + }); + + it('shows the merged teeth-and-prosthesis row even with no treatment type', () => { + const available = voiceRowAvailability(labResult, LAB_DEPENDENT, 'lab'); + expect(available.prosthesis).toBe(true); + expect(available.teeth).toBe(false); + }); + + it('never shows the treatment type row, even when one was resolved', () => { + const forced = baseResult({ treatmentType: 'prosthesis' }); + expect(voiceRowAvailability(forced, LAB_DEPENDENT, 'lab').treatmentType).toBe(false); + expect(voiceRowAvailability(forced, LAB_DEPENDENT).treatmentType).toBe(true); + }); + + it('never shows the lab row, even when a labId came back', () => { + const withLab = baseResult({ labId: 'org-1' }); + expect(voiceRowAvailability(withLab, LAB_DEPENDENT, 'lab').lab).toBe(false); + expect(voiceRowAvailability(withLab, LAB_DEPENDENT).lab).toBe(true); + }); + + it('keeps the note and due date rows on the same when-heard rule', () => { + const heard = baseResult({ comment: 'shade A2', dueDate: '2026-09-24' }); + const available = voiceRowAvailability(heard, LAB_DEPENDENT, 'lab'); + expect(available.comment).toBe(true); + expect(available.dueDate).toBe(true); + const silent = voiceRowAvailability(baseResult(), LAB_DEPENDENT, 'lab'); + expect(silent.comment).toBe(false); + expect(silent.dueDate).toBe(false); + }); + + it('ticks the prosthesis row and nothing clinic-only by default', () => { + const selection = initialVoiceSelection(labResult, LAB_DEPENDENT, 'lab'); + expect(selection.prosthesis).toBe(true); + expect(selection.treatmentType).toBe(false); + expect(selection.teeth).toBe(false); + expect(selection.lab).toBe(false); + }); + + it('still reports a recording that produced nothing usable', () => { + expect(hasAnythingToApply(baseResult(), LAB_DEPENDENT, 'lab')).toBe(false); + }); + + it('defaults to clinic mode when no mode is given', () => { + expect(voiceRowAvailability(labResult, LAB_DEPENDENT)).toEqual( + voiceRowAvailability(labResult, LAB_DEPENDENT, 'clinic'), + ); + }); +}); diff --git a/frontend/src/components/treatment/voiceReviewRows.ts b/frontend/src/components/treatment/voiceReviewRows.ts index b40ae56..3119dbc 100644 --- a/frontend/src/components/treatment/voiceReviewRows.ts +++ b/frontend/src/components/treatment/voiceReviewRows.ts @@ -25,6 +25,7 @@ import type { FdiToothId } from '@/types/treatment'; import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog'; import type { VoiceApplySelection, + VoiceEntryMode, VoiceExtractionResult, VoiceProsthesisAssignment, VoiceUnresolvedItem, @@ -52,14 +53,19 @@ function hasProsthesisWork(result: VoiceExtractionResult): boolean { export function voiceRowAvailability( result: VoiceExtractionResult, labDependentCodes: ReadonlySet, + mode: VoiceEntryMode = 'clinic', ) { - const labDependent = isLabDependentResult(result, labDependentCodes); + const isLab = mode === 'lab'; + // A lab line is always prosthesis work, and the catalog it was extracted against carries no + // treatment types at all — so the derived flag would be false and the rows exactly backwards: + // the plain teeth row shown, the merged prosthesis row hidden (decision 6). + const labDependent = isLab || isLabDependentResult(result, labDependentCodes); return { - treatmentType: result.treatmentType != null, + treatmentType: !isLab && result.treatmentType != null, teeth: !labDependent && result.teeth.length > 0, prosthesis: labDependent && (result.teeth.length > 0 || hasProsthesisWork(result)), comment: Boolean(result.comment?.trim()), - lab: result.labId != null, + lab: !isLab && result.labId != null, dueDate: result.dueDate != null, }; } @@ -72,8 +78,9 @@ export function voiceRowAvailability( export function initialVoiceSelection( result: VoiceExtractionResult, labDependentCodes: ReadonlySet, + mode: VoiceEntryMode = 'clinic', ): VoiceApplySelection { - const available = voiceRowAvailability(result, labDependentCodes); + const available = voiceRowAvailability(result, labDependentCodes, mode); return { treatmentType: available.treatmentType, teeth: available.teeth, @@ -399,8 +406,9 @@ export function unresolvedForAssignment( export function hasAnythingToApply( result: VoiceExtractionResult, labDependentCodes: ReadonlySet, + mode: VoiceEntryMode = 'clinic', ): boolean { - return Object.values(voiceRowAvailability(result, labDependentCodes)).some(Boolean); + return Object.values(voiceRowAvailability(result, labDependentCodes, mode)).some(Boolean); } export { archSentinels, allAssignmentTargets }; diff --git a/frontend/src/components/ui/lab/CaseCreatePanel.tsx b/frontend/src/components/ui/lab/CaseCreatePanel.tsx index 8fecaf4..844fd07 100644 --- a/frontend/src/components/ui/lab/CaseCreatePanel.tsx +++ b/frontend/src/components/ui/lab/CaseCreatePanel.tsx @@ -1,8 +1,8 @@ 'use client'; import { useCallback, useEffect, useRef, useState } from 'react'; -import { useTranslations } from 'next-intl'; -import { Trash2 } from 'lucide-react'; +import { useLocale, useTranslations } from 'next-intl'; +import { Mic, Square, Trash2 } from 'lucide-react'; import { getUserFacingError } from '@/components/shared/formatApiError'; import { FORM_SELECT_CLASS } from '@/components/shared/formSelectStyles'; import { @@ -20,52 +20,33 @@ import { pruneToothProsthesisForGroups, toothEdgeKey, unlinkAdjacentTeeth, - type ToothSelectionGroup, } from '@/components/treatment/toothSelectionGroups'; import { AppDateInput } from '@/components/ui/shared/AppDateInput'; import { Button } from '@/components/ui/shared/Button'; import { ProsthesisAssignChart } from '@/components/ui/treatment/ProsthesisAssignChart'; +import { VoiceRecordingBar } from '@/components/ui/treatment/VoiceRecordingBar'; +import { VoiceReviewSheet } from '@/components/ui/treatment/VoiceReviewSheet'; +import { isBlankLine, newLine, type LineDraft } from '@/components/lab/caseLineDraft'; import { toDateInputValue } from '@/components/lab/labCaseDueDateDisplay'; +import { buildLabLineFromVoice } from '@/components/lab/voiceLine'; import { casesApi } from '@/lib/api/cases'; import { prosthesisCatalogApi } from '@/lib/api/prosthesis-catalog'; -import type { LabCaseAttachmentMeta, LabCaseDetail } from '@/types/cases'; +import { voiceApi } from '@/lib/api/voice'; +import { isMediaRecorderSupported } from '@/lib/voice/audioFormat'; +import { useVoiceCapture, type VoiceCaptureState } from '@/lib/voice/useVoiceCapture'; +import type { LabCaseDetail } from '@/types/cases'; import type { FdiToothId } from '@/types/treatment'; import type { LinkedOrganizationOption } from '@/types/treatment'; import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog'; +import type { + VoiceApplySelection, + VoiceAvailability, + VoiceExtractionResult, +} from '@/types/voice'; const INPUT_CLASS = 'mt-1 w-full rounded-[var(--radius-md)] border border-border bg-background-secondary/90 text-text-primary text-sm px-3 py-2 placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-primary/35'; -type LineDraft = { - clientId: string; - id?: string; - teeth: FdiToothId[]; - toothSelectionGroups: ToothSelectionGroup[]; - comment: string; - toothProsthesis: Array<{ - tooth: string; - prosthesisTypeCode: string; - selectionGroupId?: string; - detailClientId: string; - }>; - attachments: LabCaseAttachmentMeta[]; -}; - -function newLine(): LineDraft { - const clientId = - typeof crypto !== 'undefined' && 'randomUUID' in crypto - ? crypto.randomUUID() - : `line-${Date.now()}`; - return { - clientId, - teeth: [], - toothSelectionGroups: [], - comment: '', - toothProsthesis: [], - attachments: [], - }; -} - function linesFromDetail(labCase: LabCaseDetail): LineDraft[] { const source = labCase.lines ?? []; if (source.length === 0) return [newLine()]; @@ -116,6 +97,7 @@ export function CaseCreatePanel({ const tTreatment = useTranslations('treatment'); const tErrors = useTranslations('errors'); const tCommon = useTranslations('common'); + const locale = useLocale(); const [referringClinicName, setReferringClinicName] = useState( labCase.referringClinicName ?? '', @@ -139,6 +121,8 @@ export function CaseCreatePanel({ const [prosthesisOptions, setProsthesisOptions] = useState( prosthesisCatalog ?? [], ); + const [voiceAvailability, setVoiceAvailability] = useState(null); + const [voiceResult, setVoiceResult] = useState(null); const [saving, setSaving] = useState(false); const [starting, setStarting] = useState(false); const [deleting, setDeleting] = useState(false); @@ -170,6 +154,7 @@ export function CaseCreatePanel({ useEffect(() => { void casesApi.listLinkedClinics().then((r) => setPartners(r.data)).catch(() => undefined); + void voiceApi.availability().then((r) => setVoiceAvailability(r.data)).catch(() => undefined); }, []); useEffect(() => { @@ -180,6 +165,24 @@ export function CaseCreatePanel({ void prosthesisCatalogApi.list().then((r) => setProsthesisOptions(r.data)).catch(() => undefined); }, [prosthesisCatalog]); + const voice = useVoiceCapture({ + // The locale the lab owner is reading and speaking in, so the ASR hint, the catalog labels + // and the week start all match what the microphone was offered for. + locale, + maxMs: voiceAvailability?.maxRecordingMs ?? null, + onExtracted: setVoiceResult, + onError: (error) => + onError(getUserFacingError(error, tErrors, tTreatment('voiceFailed'))), + }); + + // Absence renders the Add Line button unsplit. Gated on the browser's own recording support + // as well as the server config: without it the control appears on a browser that cannot + // record and fails on tap. + const voiceEnabled = + Boolean(voiceAvailability?.enabled) && + (voiceAvailability?.locales.includes(locale) ?? false) && + isMediaRecorderSupported(); + const activeLine = lines.find((l) => l.clientId === activeLineId) ?? lines[0]; const groups = activeLine?.toothSelectionGroups.length @@ -293,12 +296,54 @@ export function CaseCreatePanel({ return () => clearTimeout(timeout); }, [buildPayload, canEdit]); + function addLine() { + const line = newLine(); + setLines((prev) => [...prev, line]); + setActiveLineId(line.clientId); + } + function updateActiveLine(patch: (line: LineDraft) => LineDraft) { setLines((prev) => prev.map((line) => (line.clientId === activeLine?.clientId ? patch(line) : line)), ); } + /** + * One dictation is one line. It fills the active line while that line is still blank — a + * fresh draft opens with one, and always appending would leave it above the dictated line + * and ship it to the floor, since `start` only requires that *some* line carries jobs. + */ + function applyVoice(selection: VoiceApplySelection, applied: VoiceExtractionResult) { + const { line, dueDate: dictatedDueDate } = buildLabLineFromVoice(applied, selection, { + prosthesisCatalog: prosthesisOptions, + }); + setVoiceResult(null); + if (dictatedDueDate) setDueDate(dictatedDueDate); + + const target = activeLine; + if (target && isBlankLine(target)) { + setLines((prev) => + prev.map((l) => + l.clientId === target.clientId + ? { + ...line, + // Keep the line's identity: it may already have been saved once. + clientId: target.clientId, + id: target.id, + toothProsthesis: line.toothProsthesis.map((tp) => ({ + ...tp, + detailClientId: target.clientId, + })), + } + : l, + ), + ); + return; + } + setLines((prev) => [...prev, line]); + setActiveLineId(line.clientId); + } + async function handleDelete() { if (!canEdit) return; if (!window.confirm(t('confirmDeleteDraftCase'))) return; @@ -463,20 +508,25 @@ export function CaseCreatePanel({ -
-

{t('caseLinesTitle')}

- +
+
+

{t('caseLinesTitle')}

+ {voiceEnabled ? ( + + ) : ( + + )} +
+ {voiceEnabled ? : null}
@@ -623,6 +673,74 @@ export function CaseCreatePanel({
) : null} + + {voiceResult ? ( + applyVoice(selection, applied)} + onDiscard={() => setVoiceResult(null)} + /> + ) : null} +
+ ); +} + +/** + * "Add line", split into two segments with the microphone at the logical end — built like the + * clinic's `AddDetailWithVoice`, out of two raw buttons rather than two shared `Button`s, which + * hardcode their own rounding and would fight a segmented control. + */ +function AddLineWithVoice({ + addLabel, + startLabel, + stopLabel, + disabled, + onAddLine, + voice, +}: { + addLabel: string; + startLabel: string; + stopLabel: string; + disabled: boolean; + onAddLine: () => void; + voice: VoiceCaptureState; +}) { + const isRecording = voice.phase === 'recording'; + const isBusy = voice.phase !== 'idle'; + const micLabel = isRecording ? stopLabel : startLabel; + + return ( +
+ +
); } diff --git a/frontend/src/components/ui/treatment/VoiceReviewSheet.tsx b/frontend/src/components/ui/treatment/VoiceReviewSheet.tsx index 0b369df..f823a87 100644 --- a/frontend/src/components/ui/treatment/VoiceReviewSheet.tsx +++ b/frontend/src/components/ui/treatment/VoiceReviewSheet.tsx @@ -34,17 +34,21 @@ import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog'; import type { FdiToothId, LinkedOrganizationOption } from '@/types/treatment'; import type { VoiceApplySelection, + VoiceEntryMode, VoiceExtractionResult, VoiceUnresolvedItem, } from '@/types/voice'; interface VoiceReviewSheetProps { result: VoiceExtractionResult; - treatmentCatalog: TreatmentCatalogEntry[]; + /** `lab` hides the treatment type, plain teeth and lab rows — see `voiceRowAvailability`. */ + mode?: VoiceEntryMode; + /** Unused in lab mode: the type row never renders, so no catalog is needed to label it. */ + treatmentCatalog?: TreatmentCatalogEntry[]; prosthesisCatalog: ProsthesisCatalogEntry[]; /** `prosthesis` today, but kept generic — the same set the workspace already tracks. */ - labDependentCodes: ReadonlySet; - labs: LinkedOrganizationOption[]; + labDependentCodes?: ReadonlySet; + labs?: LinkedOrganizationOption[]; /** The result is handed back because the sheet may have added teeth or jobs the model missed. */ onApply: (selection: VoiceApplySelection, result: VoiceExtractionResult) => void; onDiscard: () => void; @@ -52,6 +56,9 @@ interface VoiceReviewSheetProps { type ArchPick = 'upper' | 'lower'; +/** Module-level so the default prop is referentially stable across renders. */ +const NO_LAB_DEPENDENT_CODES: ReadonlySet = new Set(); + /** * Confirmation step between the model's output and the form. * @@ -60,10 +67,11 @@ type ArchPick = 'upper' | 'lower'; */ export function VoiceReviewSheet({ result, - treatmentCatalog, + mode = 'clinic', + treatmentCatalog = [], prosthesisCatalog, - labDependentCodes, - labs, + labDependentCodes = NO_LAB_DEPENDENT_CODES, + labs = [], onApply, onDiscard, }: VoiceReviewSheetProps) { @@ -71,7 +79,7 @@ export function VoiceReviewSheet({ const tProsthesis = useTranslations('prosthesis'); const { formatDate } = useAppFormatters(); const [selection, setSelection] = useState(() => - initialVoiceSelection(result, labDependentCodes), + initialVoiceSelection(result, labDependentCodes, mode), ); // Every kind of candidate chip the sheet can offer, tracked separately because each folds @@ -101,8 +109,8 @@ export function VoiceReviewSheet({ }, [result, chosenTeeth, chosenAssignmentTeeth, chosenArches, chosenLeaves]); const available = useMemo( - () => voiceRowAvailability(effective, labDependentCodes), - [effective, labDependentCodes], + () => voiceRowAvailability(effective, labDependentCodes, mode), + [effective, labDependentCodes, mode], ); const connectedTeeth = useMemo(() => connectedTeethFromResult(effective), [effective]); const selectedTeeth = useMemo(() => new Set(effective.teeth), [effective.teeth]); @@ -142,7 +150,7 @@ export function VoiceReviewSheet({ ? { ...selection, treatmentType: true } : selection; - const nothingToApply = !hasAnythingToApply(effective, labDependentCodes); + const nothingToApply = !hasAnythingToApply(effective, labDependentCodes, mode); const selectedCount = countSelected(effectiveSelection, available); const targetLabel = (target: string): string => { diff --git a/frontend/src/types/voice.ts b/frontend/src/types/voice.ts index 8aa6ae6..be01cc8 100644 --- a/frontend/src/types/voice.ts +++ b/frontend/src/types/voice.ts @@ -80,3 +80,9 @@ export interface VoiceApplySelection { } export type VoicePhase = 'idle' | 'recording' | 'processing'; + +/** + * Which side dictated. Derived from the organisation on the server; on the client it only + * picks which review rows exist, since a lab line has no treatment type and no destination. + */ +export type VoiceEntryMode = 'clinic' | 'lab'; -- 2.53.0.windows.1 From 0584b794723fb8c6df13fdd1e44b9cfd73c27b9b Mon Sep 17 00:00:00 2001 From: Amin Mousavi Date: Wed, 16 Sep 2026 05:29:47 +0800 Subject: [PATCH 04/10] fix(voice): never append a blank line from a dictation that built none MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Found by the /orchestrate correctness critic, verified by hand. applyVoice checked isBlankLine on the TARGET line but never on the line it had just built. A dictation carrying no line content — a due date on its own, or one whose codes were all refused — returned a blank newLine(), fell past the blank-target branch and appended it. The panel then made it active and autosaved it, and start only requires that SOME line carries jobs (cases.service.ts:549), so the empty line shipped to the lab floor. That is what decision 9 exists to prevent; the decision only covered filling a blank target, not appending one. The spec's own manual step 7 triggers it: dictate «تا پنجشنبه» with line 1 already filled. buildLabLineFromVoice now returns line: null for a blank line, so the rule sits in the pure function a test can reach rather than in a component nothing renders. The due date still lands — it belongs to the case header, not the line. Six tests that asserted an empty line now assert null, and one new test covers a due date riding along with real work. Reverting the guard fails five of them. Co-Authored-By: Claude Opus 5 (1M context) --- frontend/src/components/lab/voiceLine.spec.ts | 95 ++++++++++++------- frontend/src/components/lab/voiceLine.ts | 10 +- .../src/components/ui/lab/CaseCreatePanel.tsx | 2 + 3 files changed, 68 insertions(+), 39 deletions(-) diff --git a/frontend/src/components/lab/voiceLine.spec.ts b/frontend/src/components/lab/voiceLine.spec.ts index 4532f0e..e446ee0 100644 --- a/frontend/src/components/lab/voiceLine.spec.ts +++ b/frontend/src/components/lab/voiceLine.spec.ts @@ -63,27 +63,32 @@ const tick = (overrides: Partial = {}): VoiceApplySelection ...overrides, }); +/** Narrows the nullable line and fails loudly when the dictation produced nothing. */ +function built(out: ReturnType) { + if (!out.line) throw new Error('expected a line, got null'); + return out.line; +} + describe('buildLabLineFromVoice — which teeth reach the line', () => { it('puts a tooth on the line only when it carries a job', () => { - const { line } = buildLabLineFromVoice( + const line = built(buildLabLineFromVoice( result({ teeth: ['12', '14', '16'], prosthesisAssignments: [{ targets: ['12', '14'], types: ['pfm_crown'], spoken: '' }], }), tick(), ctx, - ); + )); expect(line.teeth).toEqual(['12', '14']); }); - it('never copies the plain teeth list across', () => { - const { line } = buildLabLineFromVoice(result({ teeth: ['21', '22'] }), tick(), ctx); - expect(line.teeth).toEqual([]); - expect(line.toothProsthesis).toEqual([]); + it('never copies the plain teeth list across, so bare teeth build no line', () => { + const out = buildLabLineFromVoice(result({ teeth: ['21', '22'] }), tick(), ctx); + expect(out.line).toBeNull(); }); it('leaves a target off the line when every code it named was refused', () => { - const { line } = buildLabLineFromVoice( + const out = buildLabLineFromVoice( result({ teeth: ['12'], // Not in the catalog, so the stack rules refuse it and nothing lands. @@ -92,12 +97,11 @@ describe('buildLabLineFromVoice — which teeth reach the line', () => { tick(), ctx, ); - expect(line.teeth).toEqual([]); - expect(line.toothProsthesis).toEqual([]); + expect(out.line).toBeNull(); }); it('keeps the invariant nothing enforces server-side: every job names a tooth on the line', () => { - const { line } = buildLabLineFromVoice( + const line = built(buildLabLineFromVoice( result({ teeth: ['16'], prosthesisAssignments: [ @@ -107,7 +111,7 @@ describe('buildLabLineFromVoice — which teeth reach the line', () => { }), tick(), ctx, - ); + )); const onTeeth = line.toothProsthesis .filter((row) => !isArchSentinel(row.tooth)) .map((row) => row.tooth); @@ -120,7 +124,7 @@ describe('buildLabLineFromVoice — which teeth reach the line', () => { describe('buildLabLineFromVoice — prosthesis rows', () => { it('applies a stack in landing order and drops a code the stack rules refuse', () => { - const { line } = buildLabLineFromVoice( + const line = built(buildLabLineFromVoice( result({ prosthesisAssignments: [ // A post & core cannot go under a crown that is already there. @@ -129,12 +133,12 @@ describe('buildLabLineFromVoice — prosthesis rows', () => { }), tick(), ctx, - ); + )); expect(line.toothProsthesis.map((row) => row.prosthesisTypeCode)).toEqual(['pfm_crown']); }); it('carries a jaw appliance with an empty selection group and adds no tooth', () => { - const { line } = buildLabLineFromVoice( + const line = built(buildLabLineFromVoice( result({ prosthesisAssignments: [ { targets: [ARCH_TOOTH_UPPER], types: ['complete_denture'], spoken: '' }, @@ -142,7 +146,7 @@ describe('buildLabLineFromVoice — prosthesis rows', () => { }), tick(), ctx, - ); + )); expect(line.toothProsthesis).toEqual([ { detailClientId: line.clientId, @@ -155,7 +159,7 @@ describe('buildLabLineFromVoice — prosthesis rows', () => { }); it('never gives two non-adjacent teeth the same selection group', () => { - const { line } = buildLabLineFromVoice( + const line = built(buildLabLineFromVoice( result({ // Dictated as one connected span, but 12 and 16 are not neighbours: a shared group id // would tell the task generator to build a bridge across the gap. @@ -164,7 +168,7 @@ describe('buildLabLineFromVoice — prosthesis rows', () => { }), tick(), ctx, - ); + )); const groupOf = (tooth: string) => line.toothProsthesis.find((row) => row.tooth === tooth)?.selectionGroupId; expect(groupOf('12')).toBeTruthy(); @@ -173,69 +177,88 @@ describe('buildLabLineFromVoice — prosthesis rows', () => { }); it('keeps adjacent teeth dictated as a bridge in one selection group', () => { - const { line } = buildLabLineFromVoice( + const line = built(buildLabLineFromVoice( result({ toothSelectionGroups: [{ groupId: 'g1', kind: 'connected', teeth: ['12', '13'] }], prosthesisAssignments: [{ targets: ['12', '13'], types: ['pfm_crown'], spoken: '' }], }), tick(), ctx, - ); + )); const groupOf = (tooth: string) => line.toothProsthesis.find((row) => row.tooth === tooth)?.selectionGroupId; expect(groupOf('12')).toBe(groupOf('13')); }); - it('writes nothing at all when the prosthesis row is unticked', () => { - const { line } = buildLabLineFromVoice( + it('builds no line at all when the prosthesis row is unticked', () => { + const out = buildLabLineFromVoice( result({ prosthesisAssignments: [{ targets: ['12'], types: ['pfm_crown'], spoken: '' }], }), tick({ prosthesis: false }), ctx, ); - expect(line.teeth).toEqual([]); - expect(line.toothProsthesis).toEqual([]); + expect(out.line).toBeNull(); }); }); describe('buildLabLineFromVoice — the note and the due date', () => { it('takes the note when its row is ticked', () => { - const { line } = buildLabLineFromVoice(result({ comment: 'shade A2' }), tick(), ctx); + const line = built(buildLabLineFromVoice(result({ comment: 'shade A2' }), tick(), ctx)); expect(line.comment).toBe('shade A2'); }); - it('leaves the comment empty when the note row is unticked', () => { - const { line } = buildLabLineFromVoice( + it('builds no line when the note row is unticked and nothing else was dictated', () => { + const out = buildLabLineFromVoice( result({ comment: 'shade A2' }), tick({ comment: false }), ctx, ); - expect(line.comment).toBe(''); + expect(out.line).toBeNull(); }); - it('returns the due date separately from the line', () => { - const built = buildLabLineFromVoice(result({ dueDate: '2026-09-24' }), tick(), ctx); - expect(built.dueDate).toBe('2026-09-24'); - expect(built.line).not.toHaveProperty('dueDate'); + it('returns a due-date-only dictation as a date and NO line', () => { + // The bug the correctness critic found: this used to return a blank line, which the + // panel appended and autosaved. `start` only requires that *some* line carries jobs, + // so the empty line shipped to the floor (decision 9). + const out = buildLabLineFromVoice(result({ dueDate: '2026-09-24' }), tick(), ctx); + expect(out.dueDate).toBe('2026-09-24'); + expect(out.line).toBeNull(); + }); + + it('still returns the line when a due date rides along with real work', () => { + const out = buildLabLineFromVoice( + result({ + dueDate: '2026-09-24', + prosthesisAssignments: [{ targets: ['12'], types: ['pfm_crown'], spoken: '' }], + }), + tick(), + ctx, + ); + expect(out.dueDate).toBe('2026-09-24'); + expect(out.line?.teeth).toEqual(['12']); }); it('returns a null due date when its row is unticked', () => { - const built = buildLabLineFromVoice( + const out = buildLabLineFromVoice( result({ dueDate: '2026-09-24' }), tick({ dueDate: false }), ctx, ); - expect(built.dueDate).toBeNull(); + expect(out.dueDate).toBeNull(); }); it('writes no lab destination anywhere, even with a labId and its row ticked', () => { - const { line } = buildLabLineFromVoice( - result({ labId: 'org-clinic-1', labMatchExact: true }), + const out = buildLabLineFromVoice( + result({ + labId: 'org-clinic-1', + labMatchExact: true, + prosthesisAssignments: [{ targets: ['12'], types: ['pfm_crown'], spoken: '' }], + }), tick(), ctx, ); - expect(JSON.stringify(line)).not.toContain('org-clinic-1'); + expect(JSON.stringify(out)).not.toContain('org-clinic-1'); }); }); diff --git a/frontend/src/components/lab/voiceLine.ts b/frontend/src/components/lab/voiceLine.ts index c37761c..71da2b0 100644 --- a/frontend/src/components/lab/voiceLine.ts +++ b/frontend/src/components/lab/voiceLine.ts @@ -3,7 +3,7 @@ import { prosthesisTargetLines } from '@/components/treatment/voiceReviewRows'; import type { FdiToothId } from '@/types/treatment'; import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog'; import type { VoiceApplySelection, VoiceExtractionResult } from '@/types/voice'; -import { newLine, type LineDraft } from './caseLineDraft'; +import { isBlankLine, newLine, type LineDraft } from './caseLineDraft'; export interface VoiceLineContext { prosthesisCatalog: readonly ProsthesisCatalogEntry[]; @@ -17,12 +17,16 @@ export interface VoiceLineContext { * stack rules and the bridge splitting stay in one place. * * The due date comes back separately because it belongs to the case header, not to the line. + * + * `line` is null when the dictation produced no line content. A due-date-only dictation, or one + * whose codes were all refused, must not append an empty line: `start` only requires that *some* + * line carries jobs, so an empty one ships to the floor (decision 9). */ export function buildLabLineFromVoice( result: VoiceExtractionResult, selection: VoiceApplySelection, ctx: VoiceLineContext, -): { line: LineDraft; dueDate: string | null } { +): { line: LineDraft | null; dueDate: string | null } { const line = newLine(); if (selection.comment && result.comment) { @@ -64,7 +68,7 @@ export function buildLabLineFromVoice( }); return { - line, + line: isBlankLine(line) ? null : line, dueDate: selection.dueDate && result.dueDate ? result.dueDate : null, }; } diff --git a/frontend/src/components/ui/lab/CaseCreatePanel.tsx b/frontend/src/components/ui/lab/CaseCreatePanel.tsx index 844fd07..da745b5 100644 --- a/frontend/src/components/ui/lab/CaseCreatePanel.tsx +++ b/frontend/src/components/ui/lab/CaseCreatePanel.tsx @@ -319,6 +319,8 @@ export function CaseCreatePanel({ }); setVoiceResult(null); if (dictatedDueDate) setDueDate(dictatedDueDate); + // Null when the dictation carried no line content — a due date on its own still lands. + if (!line) return; const target = activeLine; if (target && isBlankLine(target)) { -- 2.53.0.windows.1 From beba7bb4d4f43bc3862f72ec9eb1687bead7eb21 Mon Sep 17 00:00:00 2001 From: Amin Mousavi Date: Wed, 16 Sep 2026 11:47:44 +0800 Subject: [PATCH 05/10] docs(voice): record the blank-line fix and the decision to leave lint red Amin's call: the repo-wide lint gate stays red. Both commands fail identically on origin/master and no error is in a file this branch touched. The repair means restructuring auth, realtime and toast effects with no component tests to catch a regression, so it is its own attended task. Notes the consequence: the Stop guard blocks on this ledger and every future /orchestrate here inherits the same red. Co-Authored-By: Claude Opus 5 (1M context) --- docs/specs/voice-lab-case-entry/progress.md | 138 ++++++++++++++++++++ 1 file changed, 138 insertions(+) diff --git a/docs/specs/voice-lab-case-entry/progress.md b/docs/specs/voice-lab-case-entry/progress.md index 2e5edd6..b6807c2 100644 --- a/docs/specs/voice-lab-case-entry/progress.md +++ b/docs/specs/voice-lab-case-entry/progress.md @@ -118,3 +118,141 @@ catalog narrowing, and the per-org-type permission branch. - If the model emits a `labId` or a `treatmentType` despite the emptied lists, the resolver still pushes an `unknown_catalog_code` unresolved item, which the sheet renders. The spec does not say lab mode should drop those, so nothing does. Watch for it at §10 item 8. + +## 2026-09-16 — Verify phase, repo `dyolink` — FAILED, nothing pushed + +An unattended `/orchestrate` run stopped in the **Verify** phase. The verifier FAILED `dyolink` +against observed ground truth. No commit was pushed. + +### Failed because + +- AC11 has no executing check: no component test renders VoiceRecordingBar, and vitest.config.ts includes only 'src/**/*.spec.ts' with no jsdom environment. +- AC12 has no executing check: nothing observed a clip being posted to POST /voice/extract — no test, no browser run, and the API is not running (curl exit 7). +- AC28 has no executing check: the debounced autosave and a reload were never exercised; no frontend integration test and no live system available. +- AC32 has no executing check: no test or live query observed task generation from a dictated case line. +- AC4 is PASS but guarded:false — only the diff removing ClinicOrgGuard stands behind it; re-adding the guard would break no test. +- AC9 is PASS but guarded:false — getAvailability takes no org argument, but no test or request ever calls the route as a LAB org. +- AC10 is PASS but guarded:false — the split mic control is only readable in JSX; no render is executed. +- AC24 is PASS but guarded:false — the applyVoice-to-setDueDate wiring has no test. +- AC25 is PASS but guarded:false — isBlankLine is tested, but the fill-the-blank-line branch inside applyVoice is not. +- AC26 is PASS but guarded:false — the append-and-activate branch inside applyVoice is not executed by any test. +- AC31 is PASS but guarded:false — the arch-highlight clause depends on ProsthesisAssignChart, which no executed test renders. +- AC33 is PASS but guarded:false — VoiceReviewSheet.tsx (a clinic component) changed and no test renders it; only tsc covers the prop change. +- Ledger entries 0026 (backend `npx eslint {src,apps,libs,test}/**/*.ts`) and 0028 (frontend `npm run lint`) are verification commands recorded with exit 1. + +### Unguarded criteria + +| ID | Behaviour | Evidence only from | +|---|---|---| +| AC4 | A LAB org can call both voice routes; the controller no longer rejects a LAB org with 403 through ClinicOrgGuard. | `git diff origin/master...HEAD -- backend/src/modules/voice/voice.controller.ts`; `grep -rn 'ClinicOrgGuard\|LabOrgGuard' backend/src/modules/voice/` | +| AC9 | GET /voice/availability returns the same configuration for a LAB org as for a CLINIC org, with no separate lab toggle. | `git diff origin/master...HEAD -- backend/src/modules/voice/voice.service.ts`; `sed -n '55,80p' backend/src/modules/voice/voice.service.ts` | +| AC10 | A mic control sits beside Add Line in CaseCreatePanel and is disabled whenever Add Line is disabled. | `git diff origin/master...HEAD -- frontend/src/components/ui/lab/CaseCreatePanel.tsx` | +| AC24 | Ticking the due-date row writes the case header's due-date field, the same state AppDateInput writes. | `grep -n 'setDueDate\|dueDate' frontend/src/components/ui/lab/CaseCreatePanel.tsx` | +| AC25 | Applying a dictation fills the active line when that line is blank (no teeth, no jobs, no comment, no attachments). | `git diff origin/master...HEAD -- frontend/src/components/ui/lab/CaseCreatePanel.tsx`; `npx vitest run src/components/lab/voiceLine.spec.ts` | +| AC26 | Applying a dictation onto a non-blank active line appends a new line and makes it the active line. | `git diff origin/master...HEAD -- frontend/src/components/ui/lab/CaseCreatePanel.tsx` | +| AC31 | A dictated arch selects the jaw, invents no tooth, and the chart shows the arch highlight. | `cd frontend && npx vitest run --reporter=verbose src/components/lab/voiceLine.spec.ts src/components/treatment/voiceReviewRows.spec.ts` | +| AC33 | The clinic treatment workspace mic behaves exactly as it did before this change. | `cd frontend && npx vitest run` (98 tests) ; `git diff --name-only origin/master...HEAD` | + +### Failing criteria + +**AC11** — While recording on the lab side, VoiceRecordingBar shows the elapsed time and the level meter as on the clinic side. +- result: FAIL · evidence_kind: test_stdout · guarded: false · exit_code: 0 +- command: `cd frontend && npx vitest run` +- evidence: Looked for an executed render of VoiceRecordingBar and found none. The suite is 5 files / 98 tests, all pure helpers: toothSelectionGroups, prosthesisTree, voiceReviewRows, voiceLine, voiceApply. vitest.config.ts: include ['src/**/*.spec.ts'], no environment set. The only trace of the criterion is the JSX `{voiceEnabled ? : null}` in the diff. +- log: `/Users/aminmsvi/PersonalProjects/dyolink/.git/orchestrate/logs/0024-test.log` + +**AC12** — Stopping the lab recording posts the clip to POST /voice/extract. +- result: FAIL · evidence_kind: test_stdout · guarded: false · exit_code: 0 +- command: `cd frontend && npx vitest run; grep -n 'voice/extract' frontend/src/lib/api/voice.ts` +- evidence: Looked for an executed check of the stop-to-POST path and found none. Static chain only: CaseCreatePanel wires `onClick={isRecording ? voice.onStop : voice.onStart}` to useVoiceCapture, and frontend/src/lib/api/voice.ts:26 does `apiClient.post('/voice/extract', payload, ...)`. No test, no browser run, no server request observed (API not running, curl exit 7). +- log: `/Users/aminmsvi/PersonalProjects/dyolink/.git/orchestrate/logs/0024-test.log` + +**AC28** — After confirming the sheet, the debounced autosave persists the case, so reloading it shows the dictated line. +- result: FAIL · evidence_kind: test_stdout · guarded: false · exit_code: 7 +- command: `cd frontend && npx vitest run ; curl --max-time 3 http://localhost:3000/api/voice/availability` +- evidence: Looked for an executed persistence check and found none. No frontend component or integration test exists; the backend suite (18 suites, 230 tests) holds no case-autosave-from-voice test; the API is not running (curl exit 7, HTTP code 000), so no live query could confirm a reload. The 500 ms autosave effect is only visible as source at CaseCreatePanel.tsx:247-252. +- log: (none) + +**AC32** — Starting a case built by dictation generates tasks whose groups match the lines. +- result: FAIL · evidence_kind: test_stdout · guarded: false · exit_code: 0 +- command: `cd backend && npm test` +- evidence: Looked for an executed start-case / task-generation check driven by a dictated line and found none. The backend suite passes 230 tests in 18 suites, but no ledger entry and no suite exercises LabCase start with a voice-built line; the API and database are not running, so no live query could observe the generated task groups. +- log: `/Users/aminmsvi/PersonalProjects/dyolink/.git/orchestrate/logs/0022-test.log` + +### Unexecuted cells + +None. + +### Stale evidence + +- ledger 0001-0008 (ts 1789505529-1789505699, cells C01-C04, `npm test -- voice.service.spec -t C0x`) ran BEFORE the last edit of backend/src/modules/voice/voice.service.ts, voice.service.spec.ts and narrowCatalogForOrgType.spec.ts (mtime 1789505987). Superseded by fresh entries 0018-0021 (ts 1789506102-1789506123). +- ledger 0012 (ts 1789505763, `npx eslint src/modules/voice/...`, exit 1) is stale and superseded by 0027 (ts 1789506206, exit 0). +- ledger 0013 (ts 1789505784, cell C03, `npx vitest run`), 0014 (ts 1789505792, cell C01, `npx tsc --noEmit`), 0017 (ts 1789505820, cell C03, `npm run build`) are stale and mis-tagged: whole-suite frontend commands carrying single cell ids that do not describe them. Superseded by untagged fresh runs 0024, 0025, 0030. + +### git_status + +(empty) + +### Why + +The earlier gates passed on what agents said about their own work. This one passed nothing. + +## 2026-09-16 — the blank-line bug, and the lint gate left red + +### Fixed: a dictation that built no line still appended one + +The `/orchestrate` correctness critic refuted, and the finding held up when checked by hand. + +`applyVoice` tested `isBlankLine` on the **target** line but never on the line it had just +**built**. A dictation carrying no line content — a due date alone, or one whose codes were all +refused — returned a blank `newLine()`, fell past the blank-target branch and was appended, made +active, and autosaved. `start` only requires that *some* line carries jobs +(`cases.service.ts:549`), so the empty line shipped to the floor. That is what decision 9 exists +to prevent; decision 9 only ever covered *filling* a blank target, not *appending* one. + +The spec's own §10 manual step 7 triggers it: dictate «تا پنجشنبه» with line 1 already filled. + +Fixed in the pure layer rather than guarded in the component: `buildLabLineFromVoice` returns +`line: null` when the line is blank, so a test can hold the rule. The due date still lands, since +it belongs to the case header. Six tests that asserted an empty line now assert null, one new test +covers a due date riding along with real work, and reverting the guard fails five of them. +Commit `c881fdf`. + +### Left red: the repo-wide lint gate + +| Command | Exit | On `origin/master` | +|---|---|---| +| `npx eslint "{src,apps,libs,test}/**/*.ts"` (backend) | 1 — 1285 errors, 95 warnings | identical, byte for byte | +| `npm run lint` (frontend) | 1 | identical | + +**No error is in a file this branch touched.** Verified by running both commands against +`origin/master` in a throwaway worktree. + +- **Backend:** 1109 of the 1285 are auto-fixable; **176 survive `--fix`**, across 25 files, 74 of + them in `auth/` — mostly `no-unsafe-member-access` on what looks like an untyped `req.user`. + The repo's own pinned script already carries `--fix`, so even that exits 1. +- **Frontend:** `npm run lint` runs `next lint`, which Next 16 removed, so it reads `lint` as a + directory and has never linted anything. Repointing it at `eslint` surfaces 22 errors: 10 + `react-hooks/set-state-in-effect` in `useAuth`, `RealtimeProvider`, `ToastProvider`, + `ThemeToggle`, `AppDateInput` and the badge hooks; 7 `no-explicit-any` in the auth layer; 3 + `static-components`; 2 trivial. + +**This repo has never had a green lint gate on either side**, and `.gitea/workflows/*` runs no +lint step, so nothing ever reported it. `/orchestrate` is the first thing to run it. + +Amin's call, 2026-09-16: **leave it.** The repair means restructuring effects in authentication, +realtime and toast providers, and the frontend has no component tests to catch a regression — a +broken `useAuth` effect would first be noticed by a human unable to sign in. It is its own task, +on its own branch, done attended. + +Consequence to expect: `test-exit-guard.mjs --stop` blocks on this ledger, and every future +`/orchestrate` in this repo inherits the same red, until that task is done. + +### State + +Branch `feat/cases/add-voice-input-for-lab-case-line` at `c881fdf`, **not pushed**. +Green: backend 230 tests / 18 suites, `nest build`; frontend 99 tests, `tsc --noEmit`, +`next build`; eslint clean on each of the 13 touched files. +Red: the two repo-wide lint commands above. +Outstanding: §10 manual pass, and the verifier's 4 FAILs / 8 unguarded criteria, which need +either component tests or a running API — see the Verify entry above. -- 2.53.0.windows.1 From b2f2825beba0b71577281922b76ee6a29fc7181f Mon Sep 17 00:00:00 2001 From: Amin Mousavi Date: Wed, 16 Sep 2026 21:17:20 +0800 Subject: [PATCH 06/10] fix(voice): say so when a dictation lands nothing on the line MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit buildLabLineFromVoice returns null whenever no prosthesis job survives — bare teeth with no material, an out-of-catalog code, every code refused by the stack rules. applyVoice then closed the sheet and returned in silence. Dictate "دندون ۱۲ و ۱۴" with no material: lab mode forces labDependent, so the merged row is available and ticked and the button reads Apply (1). Tapping it changed nothing and said nothing. It now raises voiceNothingExtracted through the panel's existing toast, unless a due date landed — a due-date-only dictation did do something and must stay quiet. Found by /code-review. Co-Authored-By: Claude Opus 5 (1M context) --- frontend/src/components/ui/lab/CaseCreatePanel.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/frontend/src/components/ui/lab/CaseCreatePanel.tsx b/frontend/src/components/ui/lab/CaseCreatePanel.tsx index da745b5..a5d93cd 100644 --- a/frontend/src/components/ui/lab/CaseCreatePanel.tsx +++ b/frontend/src/components/ui/lab/CaseCreatePanel.tsx @@ -320,7 +320,11 @@ export function CaseCreatePanel({ setVoiceResult(null); if (dictatedDueDate) setDueDate(dictatedDueDate); // Null when the dictation carried no line content — a due date on its own still lands. - if (!line) return; + // Without the notice, Apply on a row that lands no job closes the sheet and changes nothing. + if (!line) { + if (!dictatedDueDate) onError(tTreatment('voiceNothingExtracted')); + return; + } const target = activeLine; if (target && isBlankLine(target)) { -- 2.53.0.windows.1 From 5565dba60414ca4e96747be285e5e6394a623775 Mon Sep 17 00:00:00 2001 From: Amin Mousavi Date: Wed, 16 Sep 2026 21:47:01 +0800 Subject: [PATCH 07/10] feat(errors): add PERMISSION_EDIT_CASES and use it for the lab voice denial MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cases was the one feature with no edit-specific error code, so cases.service.ts throws PERMISSION_ACCESS_CASES for a failed read check (:1375) and for a failed edit check (:1391) alike. The lab voice branch checks TAB_CASES_EDIT, so reusing it told a member holding TAB_CASES_READ "you do not have access to cases" — false, and it points them at the wrong setting. All three layers: the code in error-codes.ts, the throw in assertCanDictate, and errors.PERMISSION_EDIT_CASES in en, fa and nl. The two voice.service.spec cases asserting the old code failed on the change and were updated — they are the guard that caught it. cases.service.ts:1391 has the same mismatch and is left alone; it is an existing endpoint's message, not this task's. Co-Authored-By: Claude Opus 5 (1M context) --- backend/src/common/errors/error-codes.ts | 1 + backend/src/modules/voice/voice.service.spec.ts | 4 ++-- backend/src/modules/voice/voice.service.ts | 2 +- docs/specs/voice-lab-case-entry/spec.md | 8 ++++++++ frontend/messages/en.json | 1 + frontend/messages/fa.json | 1 + frontend/messages/nl.json | 1 + 7 files changed, 15 insertions(+), 3 deletions(-) diff --git a/backend/src/common/errors/error-codes.ts b/backend/src/common/errors/error-codes.ts index 82aed6d..9445af4 100644 --- a/backend/src/common/errors/error-codes.ts +++ b/backend/src/common/errors/error-codes.ts @@ -41,6 +41,7 @@ export const ErrorCode = { PERMISSION_ACCESS_TASKS: 'PERMISSION_ACCESS_TASKS', PERMISSION_EDIT_TASKS: 'PERMISSION_EDIT_TASKS', PERMISSION_ACCESS_CASES: 'PERMISSION_ACCESS_CASES', + PERMISSION_EDIT_CASES: 'PERMISSION_EDIT_CASES', PERMISSION_ACCESS_BILLING: 'PERMISSION_ACCESS_BILLING', PERMISSION_EDIT_BILLING: 'PERMISSION_EDIT_BILLING', PERMISSION_ACCESS_STAFF: 'PERMISSION_ACCESS_STAFF', diff --git a/backend/src/modules/voice/voice.service.spec.ts b/backend/src/modules/voice/voice.service.spec.ts index c21152a..fdb8a77 100644 --- a/backend/src/modules/voice/voice.service.spec.ts +++ b/backend/src/modules/voice/voice.service.spec.ts @@ -187,7 +187,7 @@ describe('VoiceService.extract — the org type decides the permission and the c }); expect(await codeOfThrown(service.extract(user, DTO, 'en'))).toBe( - ErrorCode.PERMISSION_ACCESS_CASES, + ErrorCode.PERMISSION_EDIT_CASES, ); expect(mockExtract).not.toHaveBeenCalled(); }); @@ -200,7 +200,7 @@ describe('VoiceService.extract — the org type decides the permission and the c }); expect(await codeOfThrown(service.extract(user, DTO, 'en'))).toBe( - ErrorCode.PERMISSION_ACCESS_CASES, + ErrorCode.PERMISSION_EDIT_CASES, ); }); diff --git a/backend/src/modules/voice/voice.service.ts b/backend/src/modules/voice/voice.service.ts index 68eb02a..17d5f22 100644 --- a/backend/src/modules/voice/voice.service.ts +++ b/backend/src/modules/voice/voice.service.ts @@ -206,7 +206,7 @@ export class VoiceService { const orgType = await getOrganizationTypeName(this.prisma, organizationId); const [permission, deniedCode] = orgType === 'LAB' - ? (['TAB_CASES_EDIT', ErrorCode.PERMISSION_ACCESS_CASES] as const) + ? (['TAB_CASES_EDIT', ErrorCode.PERMISSION_EDIT_CASES] as const) : ([ 'TAB_TREATMENT_EDIT', ErrorCode.PERMISSION_EDIT_TREATMENTS, diff --git a/docs/specs/voice-lab-case-entry/spec.md b/docs/specs/voice-lab-case-entry/spec.md index 8d55136..4709536 100644 --- a/docs/specs/voice-lab-case-entry/spec.md +++ b/docs/specs/voice-lab-case-entry/spec.md @@ -186,6 +186,13 @@ the clinic call site keeps `TAB_TREATMENT_EDIT`. lab side would 403 every lab member including the owner. `TAB_CASES_EDIT` is the permission that already gates Add Case. +The denial code is **`PERMISSION_EDIT_CASES`**, added by this task. Cases was the one feature +with no edit-specific code, so `cases.service.ts` throws `PERMISSION_ACCESS_CASES` for both a +failed read check (`:1375`) and a failed edit check (`:1391`). Reusing it here would tell a lab +member who holds `TAB_CASES_READ` that they have no access to cases, which is false — they can +read every case, they just cannot edit one. All three layers of the error contract carry the new +code (§11 decision 15). + **Availability** (`GET /voice/availability`) is one config for both sides. A separate lab toggle is speculative — if voice is on, it is on. @@ -368,3 +375,4 @@ Recorded so the first manual pass does not read them as bugs. | 12 | The referring clinic is dropped silently | Matching it needs the org list §4 empties, and the result is a name (§9) | | 13 | `narrowCatalogForOrgType` is extracted and unit tested | `voice.service` has never been unit tested; this is the one decision in it worth pinning (§4, §10) | | 14 | No new i18n keys | Every voice string is under `treatment.*`, and `CaseCreatePanel` already holds that namespace (§3) | +| 15 | `PERMISSION_EDIT_CASES` is added rather than reusing `PERMISSION_ACCESS_CASES` | The check is on an edit permission; "no access to cases" is false for a `TAB_CASES_READ` holder and points them at the wrong setting (§5) | diff --git a/frontend/messages/en.json b/frontend/messages/en.json index b144db1..a681a4b 100644 --- a/frontend/messages/en.json +++ b/frontend/messages/en.json @@ -1299,6 +1299,7 @@ "PERMISSION_ACCESS_TASKS": "You do not have access to tasks.", "PERMISSION_EDIT_TASKS": "You cannot edit tasks.", "PERMISSION_ACCESS_CASES": "You do not have access to cases.", + "PERMISSION_EDIT_CASES": "You cannot edit cases.", "PERMISSION_ACCESS_BILLING": "You do not have access to billing.", "PERMISSION_EDIT_BILLING": "You cannot edit billing for this organization.", "LAB_CASE_ACCESS_DENIED": "You do not have permission to view this shared case.", diff --git a/frontend/messages/fa.json b/frontend/messages/fa.json index 6771170..03dc2b1 100644 --- a/frontend/messages/fa.json +++ b/frontend/messages/fa.json @@ -1300,6 +1300,7 @@ "PERMISSION_ACCESS_TASKS": "به وظایف دسترسی ندارید.", "PERMISSION_EDIT_TASKS": "نمی‌توانید وظایف را ویرایش کنید.", "PERMISSION_ACCESS_CASES": "به پرونده‌ها دسترسی ندارید.", + "PERMISSION_EDIT_CASES": "نمی‌توانید پرونده‌ها را ویرایش کنید.", "PERMISSION_ACCESS_BILLING": "به صورتحساب دسترسی ندارید.", "PERMISSION_EDIT_BILLING": "نمی‌توانید صورتحساب این سازمان را ویرایش کنید.", "LAB_CASE_ACCESS_DENIED": "اجازه مشاهده این پرونده اشتراک‌گذاری‌شده را ندارید.", diff --git a/frontend/messages/nl.json b/frontend/messages/nl.json index b180d9f..dea4a9c 100644 --- a/frontend/messages/nl.json +++ b/frontend/messages/nl.json @@ -1299,6 +1299,7 @@ "PERMISSION_ACCESS_TASKS": "U hebt geen toegang tot taken.", "PERMISSION_EDIT_TASKS": "U kunt taken niet bewerken.", "PERMISSION_ACCESS_CASES": "U hebt geen toegang tot dossiers.", + "PERMISSION_EDIT_CASES": "U kunt dossiers niet bewerken.", "PERMISSION_ACCESS_BILLING": "U hebt geen toegang tot facturatie.", "PERMISSION_EDIT_BILLING": "U kunt facturatie voor deze organisatie niet bewerken.", "LAB_CASE_ACCESS_DENIED": "U hebt geen toestemming om dit gedeelde dossier te bekijken.", -- 2.53.0.windows.1 From c3d6581d2af7c16fc97ad8b3d8b0c49c71ec0741 Mon Sep 17 00:00:00 2001 From: Amin Mousavi Date: Wed, 16 Sep 2026 21:49:27 +0800 Subject: [PATCH 08/10] fix(cases): tell an edit denial from an access denial MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit assertCanEditCases checks TAB_CASES_EDIT but threw PERMISSION_ACCESS_CASES — "you do not have access to cases" — at a member who holds TAB_CASES_READ and can open and read every case. It sent them to the wrong setting. Nine call sites: start, delete, assign, external code, important flag and the rest. assertCanReadCases (:1378) keeps PERMISSION_ACCESS_CASES, which is accurate there, and so do both lab-case-activity.service.ts sites — those check READ. Co-Authored-By: Claude Opus 5 (1M context) --- backend/src/modules/cases/cases.service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/modules/cases/cases.service.ts b/backend/src/modules/cases/cases.service.ts index b08976d..c146a0f 100644 --- a/backend/src/modules/cases/cases.service.ts +++ b/backend/src/modules/cases/cases.service.ts @@ -1474,7 +1474,7 @@ export class CasesService { if (names.includes('TAB_CASES_EDIT')) { return; } - throw new AppException(ErrorCode.PERMISSION_ACCESS_CASES, HttpStatus.FORBIDDEN); + throw new AppException(ErrorCode.PERMISSION_EDIT_CASES, HttpStatus.FORBIDDEN); } private async getMembership(userId: string, organizationId: string) { -- 2.53.0.windows.1 From 39bfec1d3f5c375a25c086ef9958729c83c2b0c8 Mon Sep 17 00:00:00 2001 From: Amin Mousavi Date: Wed, 16 Sep 2026 21:54:12 +0800 Subject: [PATCH 09/10] docs(voice): one flat spec file, no progress note MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Amin's call: specs live at docs/specs/.md, and the repo does not carry a progress ledger. The ledger was an /orchestrate requirement, not something the codebase needs to keep. The link to voice-treatment-entry is repointed — that spec still sits in its own folder on master. Co-Authored-By: Claude Opus 5 (1M context) --- .../spec.md => voice-lab-case-entry.md} | 0 docs/specs/voice-lab-case-entry/progress.md | 258 ------------------ 2 files changed, 258 deletions(-) rename docs/specs/{voice-lab-case-entry/spec.md => voice-lab-case-entry.md} (100%) delete mode 100644 docs/specs/voice-lab-case-entry/progress.md diff --git a/docs/specs/voice-lab-case-entry/spec.md b/docs/specs/voice-lab-case-entry.md similarity index 100% rename from docs/specs/voice-lab-case-entry/spec.md rename to docs/specs/voice-lab-case-entry.md diff --git a/docs/specs/voice-lab-case-entry/progress.md b/docs/specs/voice-lab-case-entry/progress.md deleted file mode 100644 index b6807c2..0000000 --- a/docs/specs/voice-lab-case-entry/progress.md +++ /dev/null @@ -1,258 +0,0 @@ ---- -type: task-progress -status: active -repos: - - repo: dyolink - path: ~/PersonalProjects/dyolink - branch: feat/cases/add-voice-input-for-lab-case-line - base: origin/master - role: lab-mode extraction catalog + lab line apply + shared review sheet - spec_slug: voice-lab-case-entry - merge_after: [] ---- - -# Voice entry for a lab case line — progress - -Ledger for [`spec.md`](spec.md). Every `/orchestrate` stop path appends here. - -## Ledger - -| # | Item | State | -|---|---|---| -| 1 | `narrowCatalogForOrgType` + spec | done | -| 2 | `ClinicOrgGuard` off the controller; `extract` branches on org type | done | -| 3 | `assertCanEditTreatment` generalised to take a permission code | done | -| 4 | `voiceRowAvailability(result, codes, mode)` | done | -| 5 | `mode` prop on `VoiceReviewSheet` | done | -| 6 | `buildLabLineFromVoice` + spec | done | -| 7 | Mic beside Add Line in `CaseCreatePanel` | done | -| 8 | Manual pass, `fa`, both org types (§10) | not started | - -## 2026-09-16 — spec written, branch cut - -`/grill-me` settled 14 decisions across 10 questions. Spec committed as `93c592f` on -`feat/cases/add-voice-input-for-lab-case-line`, branched from `master` at `554a31f` — which -already carries the merged `voice-treatment-entry` work this depends on. - -Four findings from reading the code shaped the design, each cited in the spec: - -| Finding | Where | -|---|---| -| `ClinicOrgGuard` on the whole controller, so a LAB org gets 403 on both voice routes | `voice.controller.ts:22` | -| `listLinkedLabs` does not filter by org type — a LAB org is handed its linked **clinics** under the heading "LABS THIS CLINIC CAN SEND TO" | `voice.service.ts:272` | -| The lab write validates only the prosthesis code, so a teeth/jobs mismatch is written silently rather than rejected | `cases.service.ts:481` | -| `TAB_TREATMENT_EDIT` is clinic-only, so reusing it would 403 every lab member including the owner | `organization-type.ts:14` | - -No code yet. - -## 2026-09-16 — `/orchestrate --dry` preflight - -Two blockers found before any agent was spawned. - -1. **No merge request template.** `.gitlab/merge_request_templates/*.md` does not exist, and - neither does `.github/`. The repo is on **Gitea** (`origin` is - `http://178.131.50.201:3000/admin/dyolink.git`), and `/orchestrate` ends in GitLab-shaped - merge requests. This is the same blocker that ended the 2026-09-06 run at 1 h 31 m and - 116 M tokens, that time discovered at Ship rather than at preflight. -2. **No progress note.** Created by this entry. - -Blocker 1 is not fixable inside this repo — the Ship phase targets the wrong forge, so a -template alone would not be enough. Amin chose to run everything except Ship: `dry: true` -commits locally and never pushes, so the run never reaches the phase that needs a template. -Teaching the clerk and courier about Gitea is its own task, upstream in `~/.claude`. - -## 2026-09-16 — implementation, repo `dyolink` - -All seven code items landed on `feat/cases/add-voice-input-for-lab-case-line`. Not committed. - -### Backend - -| File | Change | -|---|---| -| `backend/src/modules/voice/narrowCatalogForOrgType.ts` | **new** — `LAB` empties `treatmentTypes` and `labs`, `CLINIC` passes through | -| `backend/src/modules/voice/narrowCatalogForOrgType.spec.ts` | **new** — the three §10 cases plus a no-mutation case | -| `backend/src/modules/voice/voice.controller.ts` | `ClinicOrgGuard` removed; `JwtAuthGuard` stays | -| `backend/src/modules/voice/voice.service.ts` | `assertCanEditTreatment` → `assertCanDictate`, which resolves the org type, asserts `TAB_TREATMENT_EDIT` (CLINIC) or `TAB_CASES_EDIT` (LAB), and returns the type so `extract` narrows the catalog with it | -| `backend/src/modules/voice/voice.service.spec.ts` | **new** — the four matrix cells through `extract`, with the OpenRouter providers mocked so the catalog handed to the model is asserted | - -The LAB denial code is `PERMISSION_ACCESS_CASES`, matching `cases.service.ts:1391`. The spec did -not name one and no `PERMISSION_EDIT_CASES` exists; reusing the existing code keeps decision 14 -(no new i18n keys) intact. - -### Frontend - -| File | Change | -|---|---| -| `frontend/src/types/voice.ts` | **new** `VoiceEntryMode = 'clinic' \| 'lab'` | -| `frontend/src/components/treatment/voiceReviewRows.ts` | `voiceRowAvailability` / `initialVoiceSelection` / `hasAnythingToApply` take `mode`, defaulting to `'clinic'`; lab mode forces `labDependent` true and hides the type and lab rows | -| `frontend/src/components/ui/treatment/VoiceReviewSheet.tsx` | `mode` prop; `treatmentCatalog`, `labs` and `labDependentCodes` are now optional, since lab mode renders none of the rows that need them | -| `frontend/src/components/lab/caseLineDraft.ts` | **new** — `LineDraft`, `newLine` and `isBlankLine`, moved out of `CaseCreatePanel` so the pure apply helper can use them without importing from `ui/` | -| `frontend/src/components/lab/voiceLine.ts` | **new** `buildLabLineFromVoice`, through the shared `prosthesisTargetLines` and `groupsFromFlatTeeth` | -| `frontend/src/components/lab/voiceLine.spec.ts` | **new** — the six §10 rules plus the `isBlankLine` bounds | -| `frontend/src/components/treatment/voiceReviewRows.spec.ts` | lab-mode rows added | -| `frontend/src/components/ui/lab/CaseCreatePanel.tsx` | `useVoiceCapture` + `VoiceRecordingBar` + `VoiceReviewSheet mode="lab"`; `AddLineWithVoice` split button beside Add Line, sharing its `disabled` | - -### Verification - -| Command | Result | -|---|---| -| `cd backend && npm test` | 230 passed, 18 suites | -| `cd backend && npm run build` | clean | -| `cd frontend && npx vitest run` | 98 passed, 5 files | -| `cd frontend && npx tsc --noEmit` | clean | -| `cd frontend && npm run build` | clean | -| `cd frontend && npm run lint` | 0 errors and 0 warnings on every touched file | - -Matrix cells recorded through `gate-run` (`.git/orchestrate/ledger.jsonl`), each running exactly -one test: C01 CLINIC granted, C02 CLINIC denied, C03 LAB granted, C04 LAB denied. - -Every new rule was also shown to fail when reverted: the decision-40 filter, the -`splitDisconnectedRuns` seeding, the forced `labDependent`, the hidden type/lab rows, the -catalog narrowing, and the per-org-type permission branch. - -### Left for the manual pass - -- §10 items 1–12, `fa`, a LAB org with a linked clinic. -- `treatment.voiceStart` reads "Record treatment" beside Add Line. It is reused rather than - duplicated, per decision 14. Rename it later if it reads wrong in `fa`. -- If the model emits a `labId` or a `treatmentType` despite the emptied lists, the resolver - still pushes an `unknown_catalog_code` unresolved item, which the sheet renders. The spec - does not say lab mode should drop those, so nothing does. Watch for it at §10 item 8. - -## 2026-09-16 — Verify phase, repo `dyolink` — FAILED, nothing pushed - -An unattended `/orchestrate` run stopped in the **Verify** phase. The verifier FAILED `dyolink` -against observed ground truth. No commit was pushed. - -### Failed because - -- AC11 has no executing check: no component test renders VoiceRecordingBar, and vitest.config.ts includes only 'src/**/*.spec.ts' with no jsdom environment. -- AC12 has no executing check: nothing observed a clip being posted to POST /voice/extract — no test, no browser run, and the API is not running (curl exit 7). -- AC28 has no executing check: the debounced autosave and a reload were never exercised; no frontend integration test and no live system available. -- AC32 has no executing check: no test or live query observed task generation from a dictated case line. -- AC4 is PASS but guarded:false — only the diff removing ClinicOrgGuard stands behind it; re-adding the guard would break no test. -- AC9 is PASS but guarded:false — getAvailability takes no org argument, but no test or request ever calls the route as a LAB org. -- AC10 is PASS but guarded:false — the split mic control is only readable in JSX; no render is executed. -- AC24 is PASS but guarded:false — the applyVoice-to-setDueDate wiring has no test. -- AC25 is PASS but guarded:false — isBlankLine is tested, but the fill-the-blank-line branch inside applyVoice is not. -- AC26 is PASS but guarded:false — the append-and-activate branch inside applyVoice is not executed by any test. -- AC31 is PASS but guarded:false — the arch-highlight clause depends on ProsthesisAssignChart, which no executed test renders. -- AC33 is PASS but guarded:false — VoiceReviewSheet.tsx (a clinic component) changed and no test renders it; only tsc covers the prop change. -- Ledger entries 0026 (backend `npx eslint {src,apps,libs,test}/**/*.ts`) and 0028 (frontend `npm run lint`) are verification commands recorded with exit 1. - -### Unguarded criteria - -| ID | Behaviour | Evidence only from | -|---|---|---| -| AC4 | A LAB org can call both voice routes; the controller no longer rejects a LAB org with 403 through ClinicOrgGuard. | `git diff origin/master...HEAD -- backend/src/modules/voice/voice.controller.ts`; `grep -rn 'ClinicOrgGuard\|LabOrgGuard' backend/src/modules/voice/` | -| AC9 | GET /voice/availability returns the same configuration for a LAB org as for a CLINIC org, with no separate lab toggle. | `git diff origin/master...HEAD -- backend/src/modules/voice/voice.service.ts`; `sed -n '55,80p' backend/src/modules/voice/voice.service.ts` | -| AC10 | A mic control sits beside Add Line in CaseCreatePanel and is disabled whenever Add Line is disabled. | `git diff origin/master...HEAD -- frontend/src/components/ui/lab/CaseCreatePanel.tsx` | -| AC24 | Ticking the due-date row writes the case header's due-date field, the same state AppDateInput writes. | `grep -n 'setDueDate\|dueDate' frontend/src/components/ui/lab/CaseCreatePanel.tsx` | -| AC25 | Applying a dictation fills the active line when that line is blank (no teeth, no jobs, no comment, no attachments). | `git diff origin/master...HEAD -- frontend/src/components/ui/lab/CaseCreatePanel.tsx`; `npx vitest run src/components/lab/voiceLine.spec.ts` | -| AC26 | Applying a dictation onto a non-blank active line appends a new line and makes it the active line. | `git diff origin/master...HEAD -- frontend/src/components/ui/lab/CaseCreatePanel.tsx` | -| AC31 | A dictated arch selects the jaw, invents no tooth, and the chart shows the arch highlight. | `cd frontend && npx vitest run --reporter=verbose src/components/lab/voiceLine.spec.ts src/components/treatment/voiceReviewRows.spec.ts` | -| AC33 | The clinic treatment workspace mic behaves exactly as it did before this change. | `cd frontend && npx vitest run` (98 tests) ; `git diff --name-only origin/master...HEAD` | - -### Failing criteria - -**AC11** — While recording on the lab side, VoiceRecordingBar shows the elapsed time and the level meter as on the clinic side. -- result: FAIL · evidence_kind: test_stdout · guarded: false · exit_code: 0 -- command: `cd frontend && npx vitest run` -- evidence: Looked for an executed render of VoiceRecordingBar and found none. The suite is 5 files / 98 tests, all pure helpers: toothSelectionGroups, prosthesisTree, voiceReviewRows, voiceLine, voiceApply. vitest.config.ts: include ['src/**/*.spec.ts'], no environment set. The only trace of the criterion is the JSX `{voiceEnabled ? : null}` in the diff. -- log: `/Users/aminmsvi/PersonalProjects/dyolink/.git/orchestrate/logs/0024-test.log` - -**AC12** — Stopping the lab recording posts the clip to POST /voice/extract. -- result: FAIL · evidence_kind: test_stdout · guarded: false · exit_code: 0 -- command: `cd frontend && npx vitest run; grep -n 'voice/extract' frontend/src/lib/api/voice.ts` -- evidence: Looked for an executed check of the stop-to-POST path and found none. Static chain only: CaseCreatePanel wires `onClick={isRecording ? voice.onStop : voice.onStart}` to useVoiceCapture, and frontend/src/lib/api/voice.ts:26 does `apiClient.post('/voice/extract', payload, ...)`. No test, no browser run, no server request observed (API not running, curl exit 7). -- log: `/Users/aminmsvi/PersonalProjects/dyolink/.git/orchestrate/logs/0024-test.log` - -**AC28** — After confirming the sheet, the debounced autosave persists the case, so reloading it shows the dictated line. -- result: FAIL · evidence_kind: test_stdout · guarded: false · exit_code: 7 -- command: `cd frontend && npx vitest run ; curl --max-time 3 http://localhost:3000/api/voice/availability` -- evidence: Looked for an executed persistence check and found none. No frontend component or integration test exists; the backend suite (18 suites, 230 tests) holds no case-autosave-from-voice test; the API is not running (curl exit 7, HTTP code 000), so no live query could confirm a reload. The 500 ms autosave effect is only visible as source at CaseCreatePanel.tsx:247-252. -- log: (none) - -**AC32** — Starting a case built by dictation generates tasks whose groups match the lines. -- result: FAIL · evidence_kind: test_stdout · guarded: false · exit_code: 0 -- command: `cd backend && npm test` -- evidence: Looked for an executed start-case / task-generation check driven by a dictated line and found none. The backend suite passes 230 tests in 18 suites, but no ledger entry and no suite exercises LabCase start with a voice-built line; the API and database are not running, so no live query could observe the generated task groups. -- log: `/Users/aminmsvi/PersonalProjects/dyolink/.git/orchestrate/logs/0022-test.log` - -### Unexecuted cells - -None. - -### Stale evidence - -- ledger 0001-0008 (ts 1789505529-1789505699, cells C01-C04, `npm test -- voice.service.spec -t C0x`) ran BEFORE the last edit of backend/src/modules/voice/voice.service.ts, voice.service.spec.ts and narrowCatalogForOrgType.spec.ts (mtime 1789505987). Superseded by fresh entries 0018-0021 (ts 1789506102-1789506123). -- ledger 0012 (ts 1789505763, `npx eslint src/modules/voice/...`, exit 1) is stale and superseded by 0027 (ts 1789506206, exit 0). -- ledger 0013 (ts 1789505784, cell C03, `npx vitest run`), 0014 (ts 1789505792, cell C01, `npx tsc --noEmit`), 0017 (ts 1789505820, cell C03, `npm run build`) are stale and mis-tagged: whole-suite frontend commands carrying single cell ids that do not describe them. Superseded by untagged fresh runs 0024, 0025, 0030. - -### git_status - -(empty) - -### Why - -The earlier gates passed on what agents said about their own work. This one passed nothing. - -## 2026-09-16 — the blank-line bug, and the lint gate left red - -### Fixed: a dictation that built no line still appended one - -The `/orchestrate` correctness critic refuted, and the finding held up when checked by hand. - -`applyVoice` tested `isBlankLine` on the **target** line but never on the line it had just -**built**. A dictation carrying no line content — a due date alone, or one whose codes were all -refused — returned a blank `newLine()`, fell past the blank-target branch and was appended, made -active, and autosaved. `start` only requires that *some* line carries jobs -(`cases.service.ts:549`), so the empty line shipped to the floor. That is what decision 9 exists -to prevent; decision 9 only ever covered *filling* a blank target, not *appending* one. - -The spec's own §10 manual step 7 triggers it: dictate «تا پنجشنبه» with line 1 already filled. - -Fixed in the pure layer rather than guarded in the component: `buildLabLineFromVoice` returns -`line: null` when the line is blank, so a test can hold the rule. The due date still lands, since -it belongs to the case header. Six tests that asserted an empty line now assert null, one new test -covers a due date riding along with real work, and reverting the guard fails five of them. -Commit `c881fdf`. - -### Left red: the repo-wide lint gate - -| Command | Exit | On `origin/master` | -|---|---|---| -| `npx eslint "{src,apps,libs,test}/**/*.ts"` (backend) | 1 — 1285 errors, 95 warnings | identical, byte for byte | -| `npm run lint` (frontend) | 1 | identical | - -**No error is in a file this branch touched.** Verified by running both commands against -`origin/master` in a throwaway worktree. - -- **Backend:** 1109 of the 1285 are auto-fixable; **176 survive `--fix`**, across 25 files, 74 of - them in `auth/` — mostly `no-unsafe-member-access` on what looks like an untyped `req.user`. - The repo's own pinned script already carries `--fix`, so even that exits 1. -- **Frontend:** `npm run lint` runs `next lint`, which Next 16 removed, so it reads `lint` as a - directory and has never linted anything. Repointing it at `eslint` surfaces 22 errors: 10 - `react-hooks/set-state-in-effect` in `useAuth`, `RealtimeProvider`, `ToastProvider`, - `ThemeToggle`, `AppDateInput` and the badge hooks; 7 `no-explicit-any` in the auth layer; 3 - `static-components`; 2 trivial. - -**This repo has never had a green lint gate on either side**, and `.gitea/workflows/*` runs no -lint step, so nothing ever reported it. `/orchestrate` is the first thing to run it. - -Amin's call, 2026-09-16: **leave it.** The repair means restructuring effects in authentication, -realtime and toast providers, and the frontend has no component tests to catch a regression — a -broken `useAuth` effect would first be noticed by a human unable to sign in. It is its own task, -on its own branch, done attended. - -Consequence to expect: `test-exit-guard.mjs --stop` blocks on this ledger, and every future -`/orchestrate` in this repo inherits the same red, until that task is done. - -### State - -Branch `feat/cases/add-voice-input-for-lab-case-line` at `c881fdf`, **not pushed**. -Green: backend 230 tests / 18 suites, `nest build`; frontend 99 tests, `tsc --noEmit`, -`next build`; eslint clean on each of the 13 touched files. -Red: the two repo-wide lint commands above. -Outstanding: §10 manual pass, and the verifier's 4 FAILs / 8 unguarded criteria, which need -either component tests or a running API — see the Verify entry above. -- 2.53.0.windows.1 From af10e7f1a0eafb79853664790ef8a19a88555fb4 Mon Sep 17 00:00:00 2001 From: Amin Mousavi Date: Thu, 17 Sep 2026 14:25:16 +0330 Subject: [PATCH 10/10] fix(docs): correct link path for voice treatment entry spec --- docs/specs/voice-lab-case-entry.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/specs/voice-lab-case-entry.md b/docs/specs/voice-lab-case-entry.md index 4709536..93d845e 100644 --- a/docs/specs/voice-lab-case-entry.md +++ b/docs/specs/voice-lab-case-entry.md @@ -17,7 +17,7 @@ aliases: [voice lab case, lab dictation, case line voice, lab mic] **Area:** Cases tab (LAB orgs) — `CaseCreatePanel` **Created:** 2026-09-16 -**Depends on:** [`voice-treatment-entry`](../voice-treatment-entry/spec.md), already merged +**Depends on:** [`voice-treatment-entry`](voice-treatment-entry/spec.md), already merged to `master`. Every resolver, the prompt, the review sheet and the stack rules come from there unchanged. This spec records only what differs. -- 2.53.0.windows.1