Files
Andrew Beveridge ☄️andClaude Opus 4.8 7cf42c8983 feat(pricing): duration-based credit pricing + long-duration input handling (#799)
@coderabbitai ignore

## Summary

Implements **duration-based credit pricing** for karaoke jobs, replacing
the flat 1-credit/job model. Credits now scale with input audio length
(`ceil(min/10)`, hard-block >60 min), with cost confirmed before heavy
processing and reconciled against the actual measured audio. Closes out
the planned fix from the 2026-06-04 long-duration mashup incident.

- Design:
`docs/archive/2026-06-04-long-duration-input-handling-design.md`
- Plan: `docs/archive/2026-06-04-long-duration-input-handling-plan.md`

## Pricing model

`credits = max(1, ceil(minutes / 10))` — 1 credit ≤10 min, 2 ≤20 min … 6
≤60 min. Inputs over 60 min are blocked. Single source of truth in
`backend/services/pricing.py`, mirrored in `frontend/lib/pricing.ts`.

## How it works

- **`state_data.credits_charged`** is the authoritative running total.
`create_job` charges the base (URL = full N via `acknowledged_credits`;
search/upload = 1); top-ups deduct only the **delta**
(`count_as_job_creation=False`).
- **Reconciliation engine** (`duration_reconciliation.py`) runs at the
single convergence point before separation+transcription in all three
processing paths (download / post-edit / `start_job_processing`),
exactly once each. It measures the audio actually sent to AudioShake
(post-edit if trimmed):
  - actual < estimate → auto-refund the difference
- actual > estimate → pause at new **`AWAITING_DURATION_CONFIRM`**
state, user re-confirms (inline Buy Credits)
  - actual > 60 min → refund everything + cancel
- **`POST /api/jobs/{id}/confirm-duration`** (+ `POST
/api/jobs/estimate`) reuse the review-stage pause/resume.
- **Notifications**: in-browser + push, 15-min idle email, 24h reminder,
**48h auto-cancel + full refund** — via the existing idle-reminder /
stale-job machinery.
- **Admin / made-for-you jobs bypass charging entirely**
(`payment_bypassed` → reconcile short-circuits).

## Endpoints

| Method | Path | Purpose |
|---|---|---|
| `POST` | `/api/jobs/estimate` | URL duration probe →
`{duration_seconds, credits, blocked, source}` |
| `POST` | `/api/jobs/{id}/confirm-duration` | confirm cost / resume
(402 insufficient, 409 mismatch) |
| `POST` | `/api/jobs` | URL create gains optional `duration_seconds`,
`acknowledged_credits` |
| `POST` | `/api/audio-search/{id}/select` | gains optional
`acknowledged_credits` |

## Frontend

`DurationCostConfirm` modal (Radix Dialog) surfaced via a "Confirm Cost"
action on `awaiting_duration_confirm` jobs (`useDurationConfirm` hook),
per-result cost chips on audio search, `pricing` i18n namespace in all
33 locales.

## Testing

- Backend: **3358 passing** (incl. boundary tables, money-math
conservation, reconcile up/down/over-limit, confirm 402/409, idempotency
guards, stale-expiry refund, an end-to-end integration test). Frontend:
**960 passing**. i18n completeness clean.
- Reviewed locally: per-task spec + quality review, a holistic
cross-cutting review, `/test-review`, and two CodeRabbit fix cycles.

## Notable bugs caught & fixed during review

- **Multi-credit under-refund**: `_refund_credit_for_job` refunded a
flat 1 — now refunds `credits_charged` (user-cancel of a long job).
- **Admin-bypass trap**: admin jobs would pause at the confirm gate and
be charged real credits — now short-circuited.
- Over-limit double-refund (suppress `cancel_job`'s built-in 1-credit
refund); over-limit email used the wrong "48h" message;
double-confirm/double-select idempotency guards.
- Hit the summary-projection gotcha (added fields to both projection
lists + regression test).

## Known residuals / follow-ups (non-blocking)

- **URL pre-flight cost-confirm is inert** until flacfetch's
`/check-youtube` returns a `duration` key — currently falls back to a
1-credit hold + post-download reconcile (functionally correct). Separate
flacfetch change.
- Duration-confirm email **bodies** are English (URLs are
locale-prefixed; backend i18n covers en/es/de) — `# TODO(i18n)` left.
- Concurrent confirm/select **double-charge TOCTOU** is an accepted
low-probability residual (atomic claim would need a Firestore
transaction); the status-transition guard handles the realistic
double-click case.

## Deploy note

Reuses the existing Cloud Tasks idle-reminder queue and the hourly
stale-review Cloud Scheduler (status-list / action-type expansions only)
— no new infra expected, but worth confirming `pulumi up` is a no-op on
deploy.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 18:39:06 -04:00

187 lines
5.3 KiB
TypeScript

/**
* @jest-environment jsdom
*
* Tests for api.estimateDuration and api.confirmDuration
*/
import { api } from '@/lib/api'
// ApiError is not exported from api.ts; we test error surfacing by catching throws
// and checking .status on the thrown object (which is an ApiError instance).
describe('api.estimateDuration', () => {
const fetchMock = jest.fn()
beforeEach(() => {
fetchMock.mockReset()
;(global as any).fetch = fetchMock
})
it('POSTs to /api/jobs/estimate with { url } and returns parsed body', async () => {
const responseBody = {
duration_seconds: 210,
credits: 1,
blocked: false,
source: 'youtube',
}
fetchMock.mockResolvedValue({
ok: true,
json: async () => responseBody,
})
const result = await api.estimateDuration('https://youtube.com/watch?v=abc')
expect(fetchMock).toHaveBeenCalledTimes(1)
const [url, init] = fetchMock.mock.calls[0]
expect(url).toMatch(/\/api\/jobs\/estimate$/)
expect(init.method).toBe('POST')
expect(JSON.parse(init.body)).toEqual({ url: 'https://youtube.com/watch?v=abc' })
expect(init.headers['Content-Type']).toBe('application/json')
expect(result).toEqual(responseBody)
expect(result.duration_seconds).toBe(210)
expect(result.credits).toBe(1)
expect(result.blocked).toBe(false)
expect(result.source).toBe('youtube')
})
it('handles null duration_seconds (unknown duration)', async () => {
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({
duration_seconds: null,
credits: 1,
blocked: false,
source: 'flacfetch',
}),
})
const result = await api.estimateDuration('https://example.com/audio.mp3')
expect(result.duration_seconds).toBeNull()
expect(result.credits).toBe(1)
})
it('throws on non-2xx response', async () => {
fetchMock.mockResolvedValue({
ok: false,
status: 400,
json: async () => ({ detail: 'Invalid URL' }),
})
await expect(api.estimateDuration('bad-url')).rejects.toMatchObject({
status: 400,
})
})
it('includes Authorization header when token is set', async () => {
// Use jsdom's window.localStorage (available in @jest-environment jsdom)
window.localStorage.setItem('karaoke_access_token', 'test-token-abc')
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ duration_seconds: 300, credits: 1, blocked: false, source: 'yt' }),
})
await api.estimateDuration('https://youtube.com/watch?v=xyz')
const [, init] = fetchMock.mock.calls[0]
expect(init.headers['Authorization']).toBe('Bearer test-token-abc')
// Restore
window.localStorage.removeItem('karaoke_access_token')
})
})
describe('api.confirmDuration', () => {
const fetchMock = jest.fn()
beforeEach(() => {
fetchMock.mockReset()
;(global as any).fetch = fetchMock
})
it('POSTs to /api/jobs/{jobId}/confirm-duration with { acknowledged_credits }', async () => {
const jobResponse = {
job_id: 'job-123',
status: 'pending',
progress: 0,
created_at: '2026-06-05T00:00:00Z',
updated_at: '2026-06-05T00:00:00Z',
}
fetchMock.mockResolvedValue({
ok: true,
json: async () => jobResponse,
})
const result = await api.confirmDuration('job-123', 3)
expect(fetchMock).toHaveBeenCalledTimes(1)
const [url, init] = fetchMock.mock.calls[0]
expect(url).toMatch(/\/api\/jobs\/job-123\/confirm-duration$/)
expect(init.method).toBe('POST')
expect(JSON.parse(init.body)).toEqual({ acknowledged_credits: 3 })
expect(init.headers['Content-Type']).toBe('application/json')
expect(result.job_id).toBe('job-123')
})
it('throws with status 402 on insufficient credits', async () => {
fetchMock.mockResolvedValue({
ok: false,
status: 402,
json: async () => ({ detail: 'Insufficient credits' }),
})
let caughtError: any
try {
await api.confirmDuration('job-456', 5)
} catch (e) {
caughtError = e
}
expect(caughtError).toBeDefined()
expect(caughtError.status).toBe(402)
expect(caughtError.message).toContain('Insufficient credits')
})
it('throws with status 409 on figure change / wrong state', async () => {
fetchMock.mockResolvedValue({
ok: false,
status: 409,
json: async () => ({ detail: 'Duration figure has changed' }),
})
let caughtError: any
try {
await api.confirmDuration('job-789', 2)
} catch (e) {
caughtError = e
}
expect(caughtError).toBeDefined()
expect(caughtError.status).toBe(409)
})
it('callers can distinguish 402 from 409 via .status', async () => {
// 402 path
fetchMock.mockResolvedValueOnce({
ok: false,
status: 402,
json: async () => ({ detail: 'Insufficient credits' }),
})
const err402 = await api.confirmDuration('j1', 3).catch((e) => e)
expect(err402.status).toBe(402)
// 409 path
fetchMock.mockResolvedValueOnce({
ok: false,
status: 409,
json: async () => ({ detail: 'State mismatch' }),
})
const err409 = await api.confirmDuration('j2', 3).catch((e) => e)
expect(err409.status).toBe(409)
// The two errors are distinguishable by .status
expect(err402.status).not.toBe(err409.status)
})
})