Repository navigation
#75 Phase 2/3: analytics scoping, terminal technician release, reset/tech-phone fidelity - #76
Conversation
…, reset error UX Three independent fixes from the Half-Shell Demo Tenant Audit (issue #75): - src/app/(app)/analytics/page.tsx never filtered is_demo at all, on any of its six jobs/quotes queries -- same bug class as PR #74 fixed elsewhere, just missed there. Applied the same isCompanySandboxDemo() scoping: an ordinary company's load-test rows (scripts/load-tech-actions.mjs etc.) now stay out of response-time/completion/acceptance-rate/revenue metrics, while a sandbox tenant's rows (which are the metrics) still count. - PATCH /api/jobs/[id] updated technician availability_status/ current_job_id on assignment, reassignment, and unassignment, but never on a status-only transition straight to a terminal status. Both the real technician "Complete" button and the dispatcher kanban board's drag-move (moveJobStatus) send {status} alone with no technician_id, so neither path ever released the technician -- they stayed on_job against a finished job indefinitely. Quote acceptance already got this right (/api/quotes/[id]/accept releases the technician on its completed transition); this applies the same release for completed/cancelled/ no_access reached through this route instead. Pre-existing production bug the demo tenant exposed, not demo-specific. - ResetDemoButton swallowed every failure (non-2xx or network error) silently -- the button just returned to normal with no feedback, so a failed destructive reset looked like nothing happened. Now shows the server's error message (or a fallback) for 6 seconds. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015m3No73eyqpRxGLXWbccVw
Donatello's P1 finding: TechPhoneModal's "Complete" button only checked the generic state-machine transition (canTransition(status, 'completed')), unlike the real technician UI (TechJobActionsClient), which additionally requires hasAcceptedQuote. That let a demo tech complete a job with no quote at all -- a state the real product cannot reach. Fixed by fetching the same accepted-quote check tech/page.tsx already does server-side and gating the button on it too. Michelangelo's P2 fidelity gaps, fixed: address now opens Google Maps and phone is a tel: link, both copied exactly from the real tech/job/[id] page's markup, instead of being styled as actionable text that did nothing. Left alone, flagging separately: the "Build Quote" button still directly PATCHes job status to quote_pending. Investigation found this is a deeper behavioral gap than a simple fix -- in the real product a technician's Build Quote link is read-only (it opens /tech/job/[jobId], which has no mutation UI at all); the in_progress -> quote_pending transition and the quote itself are built by the DISPATCHER via QuoteBuilder on the job detail page, not by the technician. Reusing the real component here would need either a technician-session impersonation adapter or a real quote-builder embedded in the phone mockup -- both larger, product-shape decisions the audit itself frames as open questions rather than a single correct fix, so this is called out to the user instead of decided unilaterally. "Sign out" is left inert for the same reason: it borrows the dispatcher's own session, so making it functional would sign the dispatcher out of their real account mid-demo. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015m3No73eyqpRxGLXWbccVw
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 17b876ad44
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| await supabase | ||
| .from('technicians') | ||
| .update({ availability_status: 'available', current_job_id: null }) | ||
| .eq('id', currentJob.technician_id) |
There was a problem hiding this comment.
Preserve technicians assigned to another active job
When a technician has multiple nonterminal assignments—which the demo seed deliberately creates and the assignment API permits—terminating any one of those jobs unconditionally clears the technician row, even if current_job_id points to a different active job. The technician rail and technician dashboard then report the technician as available with no active job while that other assignment remains open; scope the release to current_job_id = id and determine the next active assignment when appropriate.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed. Fixed in f8fb55d: the release now scopes with .eq('current_job_id', id) too, so it no-ops unless this job is the one the technician is actually marked as working — a different active assignment they hold simultaneously is left untouched. Added a regression test for exactly this case. Thanks for catching it.
Generated by Claude Code
Generated by Claude Code
| await supabase | ||
| .from('technicians') | ||
| .update({ availability_status: 'available', current_job_id: null }) | ||
| .eq('id', currentJob.technician_id) |
There was a problem hiding this comment.
Release the technician only after the job update succeeds
The technician update runs before the guarded job update at lines 232–254. If the job write errors, or a technician request loses ownership and matches zero rows, this endpoint returns 400/403 after already marking the technician available and clearing current_job_id, leaving the still-active job assigned to an apparently available technician. Apply the release only after the job mutation returns data successfully, ideally in the same transaction.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed. Fixed in f8fb55d: the release now runs after the job write's data is confirmed non-null, not before it. Added a regression test that races technician ownership the same way the file's existing TOCTOU test does, confirming a rejected (403) write leaves the technician untouched.
Generated by Claude Code
Generated by Claude Code
…MS suppression Three fixes from the product decisions made on the Half-Shell Demo Tenant Audit (#75): - TechPhoneModal's "Build Quote" no longer PATCHes the job status directly. A real technician session can't trigger this transition either -- the real Build Quote link is read-only, and quote_pending/quote-building is entirely dispatcher-driven via QuoteBuilder. The button is now disabled once in_progress, with an explanatory title, instead of faking a capability no real technician has. - DemoBanner's "Admin settings" link now only renders for an admin-role profile. The private preview demo user stays dispatcher (decision: keep dispatcher, hide the CTA rather than promote the demo user to admin), so it no longer shows a link that just bounces back to Dispatch. - Centralized sandbox external-side-effect suppression at the one real choke point for outbound SMS: processSmsOutboxBatch() in src/lib/smsOutbox.ts, which every SMS trigger (intake, tech-action, quote-approval, invoice, status updates) already funnels through. Sandbox-tenant messages now simulate delivery (skip the real Twilio call, mark sent with a demo-simulated id) instead of relying on the accident that seeded phone numbers are NANP-invalid. Deliberately NOT done per-route via is_demo filters -- that conflates a data-visibility concern with an external-side-effect concern, which is exactly what broke in PR #74 the first time around. Payment is a non-issue today: demo companies are seeded with payment_provider="manual", and ManualPaymentProvider never makes an external call (writes only to our own `invoices` table) -- confirmed by reading src/lib/payments/manual.ts rather than assumed. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015m3No73eyqpRxGLXWbccVw
…aseline
Per user decision: "Reset data" should match the tutorial copy's promise
("wipe it back to sample data"), not just reset job state.
- Technician lookup switched from name-keyed to positional (ordered by
created_at, matching the original seed script's insertion order). The
old name lookup broke silently the moment a technician was renamed --
that row would drop out of techByName and stop receiving demo job
assignments on every future reseed. Positional matching survives that.
- Technician name/phone are now restored to the canonical demoTechnicians
values on every reset if drifted. handle/pin/auth_user_id are never
touched -- those are the technician's actual Supabase Auth login
identity, and resetting them would break their credentials.
- Added demoTemplate to src/lib/demo-data.ts (mirroring TEMPLATE in
scripts/seed-demo-tenant.mjs, same can't-share-with-a-bundler-less-.mjs
constraint as SANDBOX_DEMO_SLUGS/issue #73) and resetOneCompany() now
ensures/restores the canonical quote_templates row every reset.
Deliberately NOT restored, flagged rather than silently decided:
company-level settings (name/email/phone/timezone/sms_sender_name/
payment_provider) and user roles. There's no canonical source of truth
for per-tenant company settings without new config infrastructure (the
private preview's name/email were one-time CLI args to the seed script,
never persisted anywhere reset can read back), and blanket-resetting user
roles risks silently undoing a legitimate internal admin account someone
set up on purpose.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015m3No73eyqpRxGLXWbccVw
Two P1 findings on the terminal-status technician release added earlier
in this PR (src/app/api/jobs/[id]/route.ts):
1. It released the technician unconditionally by technician_id alone. The
demo seed (and the real assignment API) let one technician hold
multiple simultaneous nonterminal jobs -- current_job_id tracks only
one of them. Completing/cancelling a DIFFERENT job than the one
current_job_id points to was clearing that other, still-active
assignment. Fixed by scoping the release update with
.eq('current_job_id', id) too, so it's a no-op unless this job is the
one they're actually marked as working.
2. It ran before the guarded job update, so a rejected write (validation
error, or a technician's ownership changing mid-request -- the same
TOCTOU race already covered by an existing test) left the technician
released against a job that was never actually updated. Moved the
release to after `data` (the successful job write) is confirmed.
Added regression coverage for both: a job completed while current_job_id
points elsewhere must not release the technician, and a 403'd TOCTOU
write must not release the technician either.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015m3No73eyqpRxGLXWbccVw
diese-tech
left a comment
There was a problem hiding this comment.
Half-Shell review
Leonardo verdict: NOT READY yet. One remaining correctness blocker.
April O'Neil — contract check
This PR is a good first #75 cleanup batch. Analytics now follows the sandbox-vs-normal visibility contract from #74, reset failures are surfaced, and the tech-phone preview is materially closer to the real technician experience instead of inventing its own completion rule.
The terminal-technician release fix also addresses a real production bug, but the invariant is not complete yet.
Donatello — architecture
The latest head correctly incorporates the two Codex findings from the earlier revision:
- release happens only after the guarded job update succeeds
- release is scoped to
current_job_id = id, so terminating some secondary assignment does not clear a different active current assignment
That is much safer.
The remaining state model issue is the inverse case: SwiftDispatch currently permits one technician to hold multiple nonterminal assignments, while current_job_id represents only one of them. If the job being terminated is the current pointer and another active job is still assigned to that technician, the new code clears the pointer and marks the technician available rather than promoting another active assignment.
Raphael — correctness edge
Concrete failure shape:
- Tech has active Job A and active Job B.
current_job_id = Job A,availability_status = on_job.- Job A transitions to
completed,cancelled, orno_access. - New release code matches
current_job_id = Job Aand writes{ available, null }. - Job B is still active and still assigned to that tech.
- Tech rail/dashboard now say available/no current job while open work remains assigned.
That is the same class of stale runtime-state bug this PR is trying to eliminate, just on the multi-assignment branch.
Required fix: after a successful terminal transition, reconcile the technician against remaining nonterminal jobs. If another active assignment exists, keep availability_status = on_job and set current_job_id to a deterministic remaining job (oldest active is already the convention used by the demo seed/reset logic). Only mark available/null when no active assignments remain.
Michelangelo — UX/test reality
The TechPhone changes are solid for this scope:
- Complete now requires an accepted quote like the real tech UI
- address opens Maps
- phone uses
tel: - fake Build Quote mutation is removed instead of pretending it works
Leaving Build Quote disabled with an explanatory title is acceptable as a partial fidelity fix while #75 decides the final product shape.
Please add one regression test for the multi-assignment terminal case above so the rail/dashboard state cannot drift again.
Casey Jones — ugly ops path
This is the exact kind of bug that shows up after a dispatcher stacks two calls on one tech during a busy day. Closing the first call must not suddenly advertise that tech as free while the second call is still assigned.
Splinter — scope discipline
Keep the fix narrow. No redesign is needed. Reuse the same nonterminal-status definition and deterministic selection convention already present in the demo seed/reset path.
Shredder — adversarial challenge
Give a technician two active jobs. Make the older/current one terminal. If the technician row becomes available while the second job remains assigned, the invariant is still broken.
Leonardo — final
Blocking finding: terminal-status reconciliation must preserve on_job and select another active assignment when the completed/cancelled/no-access job was current_job_id but additional nonterminal jobs remain.
Everything else in this batch looks directionally good. Exact-head CI is green on f8fb55df, but the current tests do not cover this remaining multi-assignment branch.
…e (PR #76) Half-Shell review, one remaining blocker after the two Codex fixes: the prior fix correctly scoped release to current_job_id = id (so terminating a job that ISN'T the current pointer leaves a different active assignment alone), but never handled the inverse -- if the terminated job WAS the current pointer and the technician still has another active (nonterminal) job, it just released them to available/null, hiding that remaining open work from the tech rail and dashboard. Fixed by looking up the technician's oldest other active job (same deterministic "oldest active wins" convention seed-demo-tenant.mjs/ resetDemoTenant.ts already use) after the job write succeeds, and promoting it -- keeping availability_status='on_job' and repointing current_job_id -- instead of blanket-releasing when one exists. Added a regression test: technician holds two active jobs, current_job_id points at the one being cancelled, and the other active job's id is promoted rather than the technician going available. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015m3No73eyqpRxGLXWbccVw
|
Confirmed and fixed in Current head ( Generated by Claude Code Generated by Claude Code |
diese-tech
left a comment
There was a problem hiding this comment.
Half-Shell re-review
April O'Neil — follow-up
The remaining technician-state blocker from the previous review has been addressed directly. The contract now matches the product's actual multiple-assignment behavior: finishing one job must not make a technician look idle if another active assignment remains.
Donatello — architecture
The reconciliation path now has a coherent invariant:
- terminal write must succeed first
- if
current_job_idno longer points at the completed job, leave the technician row alone - if it does, select another nonterminal assignment for that same technician/company
- promote the oldest remaining active job deterministically
- only set
available+current_job_id=nullwhen no active assignments remain
That matches the existing seed/reset convention rather than introducing a second ordering rule.
Raphael — correctness
The previously identified edge is closed. A technician with Job A and Job B active, with current_job_id=Job A, no longer becomes falsely available when Job A terminates. Job B is promoted instead.
The earlier Codex race fixes are still preserved: reconciliation occurs after the guarded job write succeeds, and the technician update remains scoped by current_job_id=id so a pointer that moved concurrently is not clobbered.
Michelangelo — tests
The new regression test covers the exact failure mode from the prior Half-Shell review and asserts availability_status='on_job' plus promotion to the remaining job. The existing tests still cover the inverse case where the pointer already references another active job, as well as failed-write/TOCTOU behavior.
Casey Jones — ops path
This is the version I'd want in production. Ending one call no longer tells dispatch a tech is free while another open assignment still belongs to them.
Splinter — scope
The fix stayed narrow to terminal-state reconciliation. No extra demo branching or broader scheduler redesign was introduced.
Shredder — adversarial pass
The main failure paths are now covered: no remaining work, another active job, pointer already moved, different technician, and rejected job write.
Leonardo — final
READY from review perspective.
The last blocking correctness issue is resolved on head 0c474fd3b0497e402c206ed308cb1364389d753e. Exact-head CI run 35564213910 is green.
The broader open demo-audit items in #75 remain follow-up work and do not block this PR.
…ipped The doc described a proposal (a /demo/tech route reusing /tech/page.tsx JSX via a shared TechJobView extraction, company.slug === 'demo' detection, an admin-role demo login) that was never built. What actually shipped across PRs #72/#74/#76 took a different shape: a floating TechPhoneModal widget on /dispatch running under the viewer's own dispatcher session (not a separate tech route or auth), a three-predicate demo-detection scheme (isDemoCompany/isSandboxDemoCompany/ isPrivateSandboxDemoCompany) answering three different questions, a dispatcher-role (not admin) private preview login, per-route is_demo visibility scoping, and a centralized SMS-suppression choke point instead of per-route filters. Rewrote the doc to describe the current architecture as-built, so it's useful as a reference instead of a misleading roadmap. Flagged in the new doc's "Open follow-ups" section rather than treated as done: a dedicated E2E quote-lifecycle regression suite (added separately, this same session) and whether TechPhoneModal should eventually get a real shared-component/impersonation connection to the production technician UI instead of its current parallel implementation. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015m3No73eyqpRxGLXWbccVw
…lease bug Added src/lib/__tests__/demoTenantQuoteLifecycle.test.ts: drives the real route handlers in sequence (POST /api/quotes -> line-items -> send-sms -> accept/decline) against one shared in-memory fake, the way a prospect's actual click-through exercises them -- the explicit Phase 1/4 ask in issue #75 ("Add end-to-end behavior coverage for the complete sandbox quote path"). Per-route is_demo visibility unit coverage already exists elsewhere; this file's job is proving the sequence works end to end and that technician state comes out correct at the finish line. Building it surfaced a real bug: POST /api/quotes/[id]/accept completes jobs and releases technicians on its own, independently of PATCH /api/jobs/[id] -- and had the exact same unconditional-release gap PR #76 just fixed there (releasing a technician even when they hold another still-active job). Extracted the fix into a shared src/lib/technicianReconciliation.ts helper (reconcileTechnicianAfterTerminalJob) and now call it from both routes instead of duplicating the logic a second time. Added a regression test to accept/route.test.ts mirroring the one already in jobs/[id]/route.test.ts. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015m3No73eyqpRxGLXWbccVw
Summary
First batch of fixes from the Half-Shell Demo Tenant Audit (#75), picked up after PR #74 merged. Three independent, low-risk correctness fixes plus one partial fidelity fix:
src/app/(app)/analytics/page.tsxnever filteredis_demoat all across its sixjobs/quotesqueries — same bug class PR Fix demo-tenant quote actions and stale technician availability #74 fixed elsewhere, just missed there. Applied the sameisCompanySandboxDemo()scoping so an ordinary company's load-test rows (scripts/load-tech-actions.mjsetc.) stay out of response-time/completion/acceptance-rate/revenue metrics, while a sandbox tenant's rows still count.PATCH /api/jobs/[id]updated technicianavailability_status/current_job_idon assignment/reassignment/unassignment, but never on a status-only transition straight to a terminal status. Both the real technician "Complete" button and the dispatcher kanban board's drag-move send{status}alone, so neither path ever released the technician — they stayedon_jobagainst a finished job indefinitely. This is pre-existing production behavior the demo exposed, not demo-specific (Raphael's P2 finding). Fixed to match how quote acceptance already releases the technician on its own completed transition.ResetDemoButtonswallowed every failure (non-2xx or network error) silently. Now shows the server's error message for 6 seconds.TechPhoneModal's "Complete" button only checked the generic state-machine transition, unlike the real technician UI, which additionally requires an accepted quote — closed that gap, plus made the address a Maps link and phone atel:link (copied from the real/tech/job/[id]page). The "Build Quote" button's deeper issue (it directly PATCHes job status, which no real technician session can do — that's dispatcher-only in the real product) is investigated but not fixed here; it's a genuine product-shape decision the audit itself frames as open, being raised separately rather than decided unilaterally.Test plan
npx tsc --noEmit— cleannpx vitest run— 359 passed / 8 skipped, no failures (added regression coverage for the terminal-technician-release fix, both the technician's own status-only completion and the dispatcher's kanban-drag path)🤖 Generated with Claude Code
https://claude.ai/code/session_015m3No73eyqpRxGLXWbccVw
Generated by Claude Code