@cartanova/qgrid-cli 2.18.0 → 2.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.ko.md +26 -0
  2. package/README.md +29 -0
  3. package/bundle/dist/_virtual/_rolldown/runtime.js +1 -0
  4. package/bundle/dist/application/qgrid/qgrid-response-format.js +14 -5
  5. package/bundle/dist/application/qgrid/qgrid-run-lifecycle.js +8 -3
  6. package/bundle/dist/application/qgrid/qgrid.frame.js +30 -44
  7. package/bundle/dist/application/qgrid/qgrid.types.js +4 -4
  8. package/bundle/dist/startup-migrations.js +1 -1
  9. package/bundle/dist/utils/providers/common/schema-validation.js +2 -2
  10. package/bundle/dist/utils/providers/grok/grok-voice-client.js +10 -5
  11. package/bundle/dist/utils/speech-aligner.js +302 -0
  12. package/bundle/dist/utils/speech-alignment.js +2 -102
  13. package/bundle/src/application/qgrid/qgrid-response-format.test.ts +14 -4
  14. package/bundle/src/application/qgrid/qgrid-response-format.ts +18 -2
  15. package/bundle/src/application/qgrid/qgrid-run-lifecycle.test.ts +23 -1
  16. package/bundle/src/application/qgrid/qgrid-run-lifecycle.ts +14 -2
  17. package/bundle/src/application/qgrid/qgrid.frame.test.ts +56 -17
  18. package/bundle/src/application/qgrid/qgrid.frame.ts +41 -51
  19. package/bundle/src/application/qgrid/qgrid.types.ts +14 -11
  20. package/bundle/src/utils/providers/common/schema-validation.ts +1 -1
  21. package/bundle/src/utils/providers/grok/grok-voice-client.test.ts +4 -3
  22. package/bundle/src/utils/providers/grok/grok-voice-client.ts +13 -1
  23. package/bundle/src/utils/speech-aligner.test.ts +100 -0
  24. package/bundle/src/utils/speech-aligner.ts +435 -0
  25. package/bundle/src/utils/speech-alignment.test.ts +2 -50
  26. package/bundle/src/utils/speech-alignment.ts +1 -141
  27. package/bundle/web-dist/client/assets/{index-CbElySnT.js → index-DvW4Yb82.js} +3 -3
  28. package/bundle/web-dist/client/assets/{logs-BJZmjJan.js → logs-DAif2re1.js} +1 -1
  29. package/bundle/web-dist/client/assets/{monit-CO4TQDhe.js → monit-DYczkiu0.js} +1 -1
  30. package/bundle/web-dist/client/assets/{routes-D_pSsIQS.js → routes--6kS1pgJ.js} +1 -1
  31. package/bundle/web-dist/client/assets/{settings-LKaZCi07.js → settings-Dah87LB2.js} +1 -1
  32. package/bundle/web-dist/client/assets/{show-BvATehjq.js → show-DQWFaVDW.js} +2 -2
  33. package/bundle/web-dist/client/assets/{tokens-D5KX_VAe.js → tokens-CIHja806.js} +1 -1
  34. package/bundle/web-dist/client/assets/{use-oauth-login-flow-DcqeDFdp.js → use-oauth-login-flow-DeJCqHDJ.js} +1 -1
  35. package/bundle/web-dist/client/assets/{use-update-token-mutation-IqmKULKf.js → use-update-token-mutation-Cn_Po_rH.js} +1 -1
  36. package/bundle/web-dist/client/assets/voice-6i785ieC.js +1 -0
  37. package/bundle/web-dist/client/index.html +1 -1
  38. package/bundle/web-dist/server/assets/{show-B_l5dOcT.js → show-CnLDFCtW.js} +2 -5
  39. package/bundle/web-dist/server/assets/{voice-BhVkiSJl.js → voice-BvAl-vTr.js} +12 -6
  40. package/bundle/web-dist/server/entry-server.generated.js +3 -3
  41. package/dist/cli.js +141 -3
  42. package/package.json +1 -1
  43. package/skills/qgrid/references/cli-env-and-server-boot.md +1 -0
  44. package/skills/qgrid/references/decision-rationale.md +1 -1
  45. package/skills/qgrid/references/grok-runtime.md +3 -3
  46. package/skills/qgrid/references/openai-codex-runtime.md +2 -0
  47. package/skills/qgrid/references/request-log-run-lifecycle.md +2 -2
  48. package/skills/qgrid/references/sonamu-api-web-flow.md +2 -2
  49. package/bundle/web-dist/client/assets/voice-BvjMZbB5.js +0 -1
@@ -85,9 +85,9 @@ TTS timestamps (2.16.0+): `withTimestamps: true` on `speak` sends `with_timestam
85
85
 
86
86
  TTS voices and delivery: the subscription token lists 28 `/tts` voices (9 female, 19 male), and all 28 generated English mp3 on 2026-11-09 (the dashboard samples); other languages and codecs are unverified. The body's `voice` is accepted as an alias of xAI's documented `voice_id`. Tags from xAI's speech-tag list (`[pause]`, `[long-pause]`, `[laugh]`, `<whisper>`, `<slow>`, `<soft>`) are performed, not read aloud; ElevenLabs-style emotion tags such as `[deadpan]` are not in the list. `speed` (2.18.0+, xAI's documented 0.7-1.5, enforced by `SpeakInput`) passes through to `/tts`: one line ran 6.91 / 4.79 / 3.23 s at 0.7 / 1.0 / 1.5 on 2026-11-09. OpenAI realtime speech rejects `speed` with HTTP 400, and the SDK still warns `unsupported` for it there.
87
87
 
88
- STT words (2.17.0+): `/stt` sends word-level `words` (`text`, `start`, `end`; `speaker` with diarize) by default; `transcribe` returns them as `TranscribeOutput.words` (`text`, `start`, `end` only). Against Grok TTS timing of the same clip, 17/17 words matched with a median boundary difference of 46 ms (p90 67 ms, STT consistently about 45 ms later), in 0.5 s.
88
+ STT words (2.17.0+): `/stt` sends word-level `words` (`text`, `start`, `end`; `speaker` with diarize) by default; `transcribe` returns them as `TranscribeOutput.words` (`text`, `start`, `end` only). Against Grok TTS timing of the same clip, 17/17 words matched with a median boundary difference of 46 ms (p90 67 ms, in 0.5 s. The constant ~45 ms offset is not STT lag: the Grok TTS mp3 has no LAME/Xing gapless tag, so a decoder keeps the ~46 ms encoder delay and the audio starts later than `audioTimestamps` say (SON-589 bench, where an independent aligner showed the same offset). Since 2.19.0 the Grok client adds that delay (1105 samples at 24 kHz, 46 ms) to every time in mp3 responses (`grok-voice-client.ts`), so timing matches the decoded audio (residual against the aligner: 3 ms); earlier servers returned the raw xAI timing.
89
89
 
90
- OpenAI speech timing (2.17.0+): OpenAI realtime has no timing data, so `speak` with `withTimestamps` transcribes the generated WAV with Grok STT on an automatically selected Grok token and aligns the heard words to the script (`utils/speech-alignment.ts`: edit-distance pairing, so mis-heard words keep their slot and a spoken preamble is skipped; unpaired script words split the gap between neighbours; each word's span is split over its characters). The result is `timestampsSource: "aligned"`; the step log records the heard text and matched/script word counts. A failed Grok step is fail-soft: the audio returns with `timestampsError`.
90
+ OpenAI speech timing no longer touches Grok (2.19.0+; 2.17.x ran a Grok STT pass): see `openai-codex-runtime.md`, Realtime voice.
91
91
 
92
92
  Image generation and editing default to `grok-imagine-image-2.0`; the public SDK lists it and
93
93
  `grok-imagine-image` (1.0). Quality omission passes through as upstream `auto`, currently low for
@@ -97,7 +97,7 @@ uses the active model's output resolution/quality and input-image count at the o
97
97
 
98
98
  Chat turns also accept `imageGeneration` (the dashboard chat sends `"auto"`): the dispatcher adds the proxy's server-side `{ "type": "image_generation" }` tool, and completed `image_generation_call` items (base64 JPEG, Grok Imagine) become `GenerateResult.images`, so generation and edits of earlier images work inside a conversation. `imageGenerationOptions` (OpenAI quality/size/background) is rejected. The turn's provider-reported cost already includes the image, so the request log stores `image_cost_usd = 0` with `image_cost_method = "included:grok-provider-cost"`. Verified 2026-10-21 through the subscription proxy; the model occasionally answers "I'll do it" without calling the tool (1 of 5 edit attempts).
99
99
 
100
- Inline audio, each inline image, and the aggregate inline images in one request are capped at 7 MiB decoded. The server maps Fastify's oversized-body error to HTTP 413 (`packages/api/src/application/qgrid/qgrid.types.ts`, `qgrid.frame.ts`).
100
+ Inline audio, each inline image, and the aggregate inline images in one request are capped at 19 MiB decoded, inside a 26 MiB JSON body limit (2.19.0+). The server maps Fastify's oversized-body error to HTTP 413 (`packages/api/src/application/qgrid/qgrid.types.ts`, `qgrid.frame.ts`).
101
101
 
102
102
  Video starts return a random 128-bit in-memory job handle. Handles expire after 24 hours, polling stays pinned to the starting token, and `projectName` must match the owner supplied at start. A started job is already admitted and billed, so `getVideo` polls with `ungated: true`: it checks only credential state (inactive, reauth, refresh failure) and skips the quota-threshold, cooldown, in-flight, on-demand, and ZDR gates that admit new requests. After the upstream poll returns, `videoStatus` re-checks `job.final`, so overlapping polls of a finished job write the request log once and return the same result. D4 returns the upstream `api.x.ai` video URL unchanged; qgrid does not fetch, proxy, or store the bytes (`qgrid.frame.ts`, `grok-media-client.ts`, `packages/ai-sdk/README.md`).
103
103
 
@@ -236,5 +236,7 @@ Sources: `openai-realtime-protocol.ts` (wire constants, session builders, PCM he
236
236
 
237
237
  - STT is the Codex subscription path: `POST https://chatgpt.com/backend-api/codex/realtime/calls` with `{sdp, session}` (synthetic Opus-only SDP offer; the transcription session is Codex's exact V2 shape), `201` + `Location: /v1/realtime/calls/rtc_…`, then a sideband `wss://api.openai.com/v1/realtime?call_id=…`. Per-request `language`/`prompt` and `turn_detection: null` go in a sideband `session.update`; audio goes as 1 s `input_audio_buffer.append` chunks plus one `commit`; the result is `conversation.item.input_audio_transcription.completed`. A call with no ICE connection is torn down about 30 s after creation (25 s idle fine, 31 s gone), so the client enforces a 25 s deadline from the POST. When that attempt ends in teardown (deadline, sideband closed/errored or handshake rejected before the transcript — `isSidebandTeardownError`), the client retries once on the direct `wss://api.openai.com/v1/realtime?intent=transcription` socket with the same headers and session (`OpenAIVoiceClientOptions.sttDirectFallback`, default on; 60 s bound). Server `error` events and `/calls` 4xx never trigger the fallback. The request log records `transport` (`realtime-calls` | `realtime-ws`) and `fallbackReason`; `callId` and quota headers are absent after a fallback. The direct socket is the same non-Codex path as TTS, so a 401/403 there means it was gated. Input must already be PCM16: WAV (`audio/wav`) or raw PCM (`audio/pcm;rate=…;channels=…`), downmixed and linearly resampled to 24 kHz mono like Codex's `convert_pcm16`; compressed input is a 400. The server reports no language or duration: `durationSec` is computed from the PCM sent and `language` echoes the request.
238
238
  - TTS is the one deviation from Codex. The `/calls` sideband never carries `response.output_audio.delta` (media stays on RTP, verified twice), and qgrid has no RTP stack, so speech uses the direct `wss://api.openai.com/v1/realtime?model=<id>` socket, which Codex itself treats as API-key-only (`realtime_conversation.rs:1931-1955`) but which accepts the ChatGPT bearer today. The session is Codex's V2 conversational payload minus `tools`, with a verbatim-reading system prompt (labeled `# Role & Objective` / `# Rules` / `# Examples` sections with capitalized never-answer rules; the caller's `instructions` follow as `# Style`), the text wrapped in `<script>…</script>` as the one `conversation.item.create` user item, and `response.create`; the output is concatenated PCM16 24 kHz returned as WAV (default) or raw PCM. OpenAI realtime has 10 preset voices, matching the Codex v2 list (`alloy ash ballad coral echo sage shimmer verse marin cedar`, default `marin`); others fail with 400. The model's own `response.output_audio_transcript.done` and `response.done.usage` audio/text tokens are logged with the request for fidelity checks. Treat a 401/403 on this socket as the path being gated: fail with the upstream error, do not fall back.
239
+ - TTS timing (2.19.0+): realtime speech carries no timing, so `speak` with `withTimestamps` force-aligns the text to the generated PCM in process (`utils/speech-aligner.ts`; 2.17.x transcribed the audio with Grok STT instead, removed by user decision 2026-11-09). The model is MMS-FA (Meta's CTC forced aligner, 1,130 languages, CC BY-NC 4.0, adopted with that license risk accepted) converted to int8 ONNX by us (355 MB, about 640 MB resident, about 0.17 s per 6 s clip on Apple Silicon). It scores 20 ms frames of 16 kHz audio against 28 letters; a Viterbi pass walks the script's letters in order. The script is romanized (Hangul per syllable, Latin accents stripped); digits, symbols, and other scripts become a star token (log-probability 0, matches any sound), and a star also wraps the script so a spoken preamble is absorbed. Audio over 30 s is scored in 30 s windows with 2 s context. The session loads on first use and unloads after 10 idle minutes. Output keeps `timestampsSource: "aligned"`; the step log records `alignMs`. The model path is `QGRID_ALIGNER_MODEL`, else `~/.cache/qgrid/models/mms-300m-fa-int8.onnx` (where `qgrid --install-aligner` downloads it), and `onnxruntime-node` is an api devDependency kept external in the build (`tsdown.config.ts` `neverBundle`; a bundled import resolves to a missing pnpm path): the Docker image installs both in layers before Claude Code and qgrid (model from the `aligner-model-v1` GitHub release, pinned by checksum, attribution in `/opt/qgrid/models/NOTICE.md`), and the image smoke test runs one alignment. An npm or pnpm install lacks both until `qgrid --install-aligner`, which fetches the model and the pinned `onnxruntime-node`/`onnxruntime-common` tarballs straight from their URLs (SRI hashes checked), unpacks the runtime with `tar` into `~/.cache/qgrid/runtime/node_modules` keeping only this platform's binary, and never calls npm or pnpm: a pnpm v11 global install isolates each global package, so a globally installed `onnxruntime-node` was invisible to qgrid (verified 2026-11-09). The server imports `onnxruntime-node` normally and falls back to that folder through `createRequire`. The Viterbi back-pointer table is frames x (2 x tokens + 1) bytes, capped at 100 MB: both grow with the audio, so about 4 minutes of dense English (251 s at 16.7 chars/s) is the most it can time; `alignSpeech` rejects longer input before running the model. Bench (SON-589): against Grok TTS character timing, word-boundary error median 4 ms / p90 20 ms / p99 25 ms on 523 words (the STT pass: 5 / 24 / 165 ms, failing on dropped fillers like "Hmm" and code-switched lines), digit words median 9 ms / p90 63 ms; on 126 OpenAI clips it agreed with the STT pass within one frame for 96% of words.
240
+ - STT words (2.19.0+): `transcribe` aligns the OpenAI transcript to the input audio with the same aligner (`prepareRealtimeInput` PCM at 24 kHz) and returns `TranscribeOutput.words`, the shape Grok STT returns; the step log records `alignMs`, or `wordsError` when alignment fails and the transcript returns without words. Measured 2026-11-09 on Apple Silicon: 2.9 s for a 54 s clip (cold load included), 9.9 s for 3.6 min; a 4.9 min clip exceeded the table cap.
239
241
  - Dispatcher: `OpenAIDispatcher.runVoice` selects a token with the same quota gate as Responses, refreshes once on a 401 and retries once, and invalidates the rate-limit cache afterwards. `OpenAIVoiceInputError` (unsupported audio, bad voice, empty text) becomes HTTP 400 `qgrid.openaiVoiceInvalidRequest`; everything else propagates as an upstream failure.
240
242
  - Exposed ids (user decision 2026-10-17: keep every reachable id, document limits): STT `gpt-4o-mini-transcribe`, `gpt-4o-transcribe`, `gpt-transcribe` (4/4 on the matrix), `gpt-live-transcribe` and `gpt-realtime-whisper` (return about half of a 60 s clip; whisper also mangles Korean), `whisper-1` (ignores `prompt`). `gpt-realtime-whisper` rejects `prompt` upstream, so `OPENAI_TRANSCRIPTION_MODELS_WITHOUT_PROMPT` makes the client fail with a 400 before the realtime call. TTS `gpt-realtime-2.1-mini` (13/13 verbatim, default), `gpt-realtime-2.1` (12/13) on the 2026-10-17 statement texts; `gpt-realtime-1.5` (6/13, often answers instead of repeating) was removed from the server list, SDK union and READMEs on 2026-11-09 (user decision, 2.18.0). Realtime models are conversational and answer text addressed to the listener: on question-form character lines the original one-sentence prompt let `gpt-realtime-2.1` answer 7 of 12, while the current sectioned prompt with `<script>` delimiters read 12/12 on both 2.1 and 2.1-mini (`docs/diagnosis/2026-11-06-openai-realtime-tts-prompt.md`). That 12/12 was judged by the model's own transcript, which can omit a spoken preamble; on 2026-11-09 two independent STT models (gpt-4o-transcribe, Grok) judged 108 English clips (6 lines x `marin` `cedar` `ballad` x 3): 2.1 54/54, 2.1-mini 53/54 (one take opened with "Sure, let me read that out loud for you exactly as written."), and both read all 9 Korean/English mixed takes in full. gpt-4o-transcribe itself dropped the English part of 3 of 18 mixed clips that Grok STT heard in full. Keep every instruction in the system prompt: an instruction placed in the user item was read aloud. Model behavior is tracked by the live matrix (`OPENAI_LIVE=1 pnpm tsx scripts/live-openai-voice-matrix.ts`, results in `docs/diagnosis/2026-10-17-openai-realtime-audio-probe.md`). Remove an id from `OPENAI_TRANSCRIPTION_MODELS`/`OPENAI_SPEECH_MODELS`, the SDK unions, and the READMEs together when it stops passing. Unavailable on subscription (verified 2026-10-17): `/backend-api/codex/audio/transcriptions`, `/audio/speech`, `gpt-4o-mini-tts`, `tts-1*`, `gpt-transcribe` via `/codex/responses`, Responses `input_audio`. The ChatGPT-web `POST /backend-api/transcribe` works but is not used (removed from Codex in PR #16114, ignores model/language, retains uploads 30 days).
@@ -100,14 +100,14 @@ For `imageGeneration: "auto"`, set `is_image_generation` only when returned cont
100
100
 
101
101
  If the auto image stage fails or is cancelled after the chat driver has completed, preserve the completed driver result as internal failure metadata. The frame converts it with the same usage/pricing mapper used on success; terminal logging writes one generate step before aggregating the run and retains the actual/requested model and token. The parent remains `error` or `aborted` with the original error message. Do not write a completed image step, invent an image cost, expose failure metadata in the HTTP error, or record this step again on success. A driver that never completed and a direct image-only call have no completed chat usage to retain. `logger: false` still creates no logs. Log-writing failures must not replace the original generation failure.
102
102
 
103
- Input images are not stored in `request_logs.user_prompt`; that field remains the text prompt. `beforeQuery` stores the current turn's `args.input` images on the run as `request_logs.input_images` (`{ mediaType, data, byteSize }` or `{ url }`), for text and image runs alike. Earlier-turn images in `history` stay in `request_logs.history`. For inspection in the detail view, qgrid stores reference image metadata/base64 in the synthetic `image_generation` step's `tool_args.inputImages`. If Codex returns multiple image outputs, store `inputImages` only on the first synthetic image tool step so multi-output logs do not duplicate the same input payload on every output.
103
+ Input images are not stored in `request_logs.user_prompt`; that field remains the text prompt. `beforeQuery` stores the current turn's `args.input` images on the run as `request_logs.input_images` (`{ mediaType, data, byteSize }` or `{ url }`), for text and image runs alike. Each image is stored once (2.19.1+, SON-590; dev0 had 27 GB of step results duplicating responses). `request_logs.history` keeps earlier-turn messages with every base64 data URL replaced by `[data-url N chars]`: nothing reads history images back, and the detail view shows only history text. The synthetic `image_generation` step's `tool_args.inputImages` keeps `{ mediaType, byteSize }` (or a non-data `url`) without base64, because `input_images` holds the bytes; only the first output step carries `inputImages`. A synthetic step's `tool_result` is `[image <mime> N bytes, shown in the response]` when the run's response carries that image, which is every step except one ending in `tool-calls` (that one keeps the `<img>` tag). The `generateImage` endpoint (Grok media) also stores placeholders as step results, but keeps reference images in step `tool_args.inputImages`, its only copy, since media runs do not fill `input_images`. Rows written before this keep their duplicates.
104
104
 
105
105
  ## Media fields
106
106
 
107
107
  - `media_kind`: nullable enum (`image`, `video`, `stt`, `tts`) written at `createRun` by `startMediaRun` from the media endpoint's kind; text and chat runs keep NULL (chat-generated images are marked only by `is_image_generation`). The list `Fmt` column reads it, so any new media endpoint must open its run through `startMediaRun` or set it explicitly.
108
108
  - Speech `response`: browser-playable audio is embedded as an `<audio>` data URL (see `sonamu-api-web-flow.md`); speech `ttft_ms` is the first audio byte, passed explicitly to `finishRun` because media runs have no generate step to derive it from.
109
109
 
110
- - Voice cost (2.17.1+): subscription voice calls have no per-call bill, so `cost_usd` records the public API list-price estimate with `cost_source: "pricing_table"` (`model-cost.ts`, prices checked 2026-11-09): OpenAI realtime speech from its response usage per token type (cached input is not split out, so all input is charged as uncached text), plus the Grok STT alignment pass when timing was requested; transcription per minute of audio (OpenAI's published per-minute estimates, Grok $0.10/hour); Grok TTS $15 per 1M input characters. Unknown model ids stay unpriced (NULL). The detail page labels the figure "Voice" instead of "Driver". OpenAI speech rows store the caller's style `instructions`, and OpenAI transcription rows the STT `prompt`, as `system_prompt` (2.17.1+); the detail page titles that panel "Style instructions" or "Prompt".
110
+ - Voice cost (2.17.1+): subscription voice calls have no per-call bill, so `cost_usd` records the public API list-price estimate with `cost_source: "pricing_table"` (`model-cost.ts`, prices checked 2026-11-09): OpenAI realtime speech from its response usage per token type (cached input is not split out, so all input is charged as uncached text; the in-process timing alignment costs nothing, 2.19.0+); transcription per minute of audio (OpenAI's published per-minute estimates, Grok $0.10/hour); Grok TTS $15 per 1M input characters. Unknown model ids stay unpriced (NULL). The detail page labels the figure "Voice" instead of "Driver". OpenAI speech rows store the caller's style `instructions`, and OpenAI transcription rows the STT `prompt`, as `system_prompt` (2.17.1+); the detail page titles that panel "Style instructions" or "Prompt".
111
111
 
112
112
  ## Structured output fields
113
113
 
@@ -64,9 +64,9 @@ The list header ends its filter row with a reload button (2.10.2+) that calls th
64
64
 
65
65
  Structured output visibility: the list has an `Fmt` column (`voice/stt` or `voice/tts` when `media_kind` is `stt` or `tts`, `video` when it is `video`, otherwise `img` when `is_image_generation` is true, otherwise `json` when `is_structured` is true, otherwise `text`) and a `broken` badge driven by `response_json_ok = false`; there is no broken-JSON list filter. At review time, all 114,647 succeeded structured rows had `response_json_ok = true` and zero false rows existed; the unindexed zero-result lookup scanned 1,286,016 rows and took about 3 seconds. Before reinstating the filter, validate the failure-signal semantics and index the predicate. The detail page shows a dark Response Type panel (zod expression by default, `type` declaration via toggle) rendered server-side from the stored `json_schema`. Plain-text rows render no panel. Rows written by pre-2.7.2 servers show `text`.
66
66
 
67
- Media rows (2.15.5+): `startMediaRun` writes the nullable `media_kind` column (`image`, `video`, `stt`, `tts`) at `createRun`; text runs keep it NULL, and media rows written before the column stay NULL and show their old `Fmt` label (no backfill). Speech rows store browser-playable audio (`audio/wav`, `audio/mpeg`) in `response` as `<audio src="data:...;base64,..."></audio>`, the same inline pattern image rows use, and the detail page renders it as an `<audio controls>` player; OpenAI `pcm` output is wrapped as WAV for the log copy only, while Grok `pcm`/`mulaw`/`alaw` keep the `[audio <mime> <bytes> bytes]` placeholder. The audio is stored once, not repeated in the `speech` step result. Speech `ttft_ms` is time to the first audio byte measured from the same start as `duration_ms`: the first `response.output_audio.delta` for OpenAI realtime, response-header arrival for Grok `/tts` (not streamed, so it is close to the full duration). `finishRun` takes an explicit `ttft_ms` for runs without generate steps and otherwise derives it from the first generate step. STT rows record no TTFT; since 2.16.0 their browser-playable input audio is embedded the same way in `user_prompt` (the detail page renders the USER panel through the same media parser), and other input types keep the placeholder. Inline audio grows the request-log table with every logged voice call; `logger: false` skips it. Voice step results keep word timing (`words`: TTS output words, or the words Grok heard in the STT input; 2.17.0+); the detail page fetches that one step (subset `A`) for `tts`/`stt` rows and renders the RESPONSE or USER clip with the shared `TimedPlayer` (highlighted, clickable words).
67
+ Media rows (2.15.5+): `startMediaRun` writes the nullable `media_kind` column (`image`, `video`, `stt`, `tts`) at `createRun`; text runs keep it NULL, and media rows written before the column stay NULL and show their old `Fmt` label (no backfill). Speech rows store browser-playable audio (`audio/wav`, `audio/mpeg`) in `response` as `<audio src="data:...;base64,..."></audio>`, the same inline pattern image rows use, and the detail page renders it as an `<audio controls>` player; OpenAI `pcm` output is wrapped as WAV for the log copy only, while Grok `pcm`/`mulaw`/`alaw` keep the `[audio <mime> <bytes> bytes]` placeholder. The audio is stored once, not repeated in the `speech` step result. Speech `ttft_ms` is time to the first audio byte measured from the same start as `duration_ms`: the first `response.output_audio.delta` for OpenAI realtime, response-header arrival for Grok `/tts` (not streamed, so it is close to the full duration). `finishRun` takes an explicit `ttft_ms` for runs without generate steps and otherwise derives it from the first generate step. STT rows record no TTFT; since 2.16.0 their browser-playable input audio is embedded the same way in `user_prompt` (the detail page renders the USER panel through the same media parser), and other input types keep the placeholder. Inline audio grows the request-log table with every logged voice call; `logger: false` skips it. Voice step results keep word timing (`words`: TTS output words, or the words heard in the STT input; 2.17.0+). The detail page fetches that one step (subset `A`) only for `tts` rows and renders the RESPONSE clip with the shared `TimedPlayer` (highlighted, clickable words); `stt` rows show the input audio as a plain player (2.19.0+, by user decision 2026-11-09: timing on the user prompt read as wrong).
68
68
 
69
- Voice playground (2.15.5+): the sidebar's Playground section links `/voice`, a dashboard-only test page with Text to speech and Speech to text panels that call the generated `QgridService.useSpeakMutation` / `useTranscribeMutation` with project name `qgrid_voice`; no API was added. Voice lists are web constants: OpenAI's 10 realtime presets and the 28 Grok `/tts` voices (9 female, 19 male) listed for the subscription token on 2026-11-06; the server still validates them. Instructions and the STT prompt are shown only for `openai/` models; in their place Grok TTS shows a Speed slider (0.7-1.5 in 0.05 steps, 2.18.0+), sent as `speed` only when it is not 1, and the history row title carries the speed. STT sends no `language`: a 2026-11-09 run (6 OpenAI STT models × auto/en/ko × 6 synthetic learner clips) found `en` no better than auto and `ko` translating English audio into Korean on gpt-4o-transcribe and whisper-1. The STT model list keeps only `openai/gpt-4o-transcribe` (default), `openai/gpt-4o-mini-transcribe`, and the unmeasured `grok/grok-voice-transcribe-2.0`; the server still accepts the other ids. The page is one card with Text to speech / Speech to text tabs; both panels stay mounted (the inactive one is hidden) so form state and history survive tab switches. Each result is prepended to an in-memory history row (removable, lost on reload) with a request-log link that opens in a new tab so the history is kept. TTS voices are chips (Grok split Female/Male) above the text: a name selects the voice, and ▶ plays a bundled sample from `packages/web/public/voice-samples/{openai,grok}/<voice>.mp3` without a request (and selects it; pressing again stops). Each of the 38 samples introduces itself ("I'm <Voice>. Nice to meet you. How's it going?"), regenerated on 2026-11-09 through qgrid (`grok/grok-tts`, `openai/gpt-realtime-2.1-mini`) and checked with STT; re-encoded to 40 kbps mono MP3 (about 640 KB, shipped in the CLI bundle via `web-dist`). Do not trust the OpenAI speech self-transcript as a verbatim check: one ballad take carried an audible "Okay, let's read that line aloud exactly as written." preamble that two STT models heard while `response.output_audio_transcript.done` showed only the script. A voice added upstream needs a sample file or its ▶ fails to load. STT recordings and uploads are numbered clips so one clip run through several models reads as a comparison. A "Word timing" checkbox (default on, 2.17.0+) sends `withTimestamps`; TTS rows and Grok STT rows then render the clip with its words under the player (`TimedPlayer`), highlight the word being spoken (animation-frame polling with a `timeupdate` fallback when frames are throttled), and show the timing source (Grok TTS, aligned via Grok STT, or the failure). Clicking a word plays from its start. Recordings (MediaRecorder webm/opus) and uploads are decoded with `AudioContext` at 24 kHz, mixed to mono, and sent as PCM16 WAV (`voice-audio.ts`), because the OpenAI transcription route accepts only WAV or raw PCM. Results link to their request log.
69
+ Voice playground (2.15.5+): the sidebar's Playground section links `/voice`, a dashboard-only test page with Text to speech and Speech to text panels that call the generated `QgridService.useSpeakMutation` / `useTranscribeMutation` with project name `qgrid_voice`; no API was added. Voice lists are web constants: OpenAI's 10 realtime presets and the 28 Grok `/tts` voices (9 female, 19 male) listed for the subscription token on 2026-11-06; the server still validates them. Instructions and the STT prompt are shown only for `openai/` models; in their place Grok TTS shows a Speed slider (0.7-1.5 in 0.05 steps, 2.18.0+), sent as `speed` only when it is not 1, and the history row title carries the speed. STT sends no `language`: a 2026-11-09 run (6 OpenAI STT models × auto/en/ko × 6 synthetic learner clips) found `en` no better than auto and `ko` translating English audio into Korean on gpt-4o-transcribe and whisper-1. The STT model list keeps only `openai/gpt-4o-transcribe` (default), `openai/gpt-4o-mini-transcribe`, and the unmeasured `grok/grok-voice-transcribe-2.0`; the server still accepts the other ids. The page is one card with Text to speech / Speech to text tabs; both panels stay mounted (the inactive one is hidden) so form state and history survive tab switches. Each result is prepended to an in-memory history row (removable, lost on reload) with a request-log link that opens in a new tab so the history is kept. TTS voices are chips (Grok split Female/Male) above the text: a name selects the voice, and ▶ plays a bundled sample from `packages/web/public/voice-samples/{openai,grok}/<voice>.mp3` without a request (and selects it; pressing again stops). Each of the 38 samples introduces itself ("I'm <Voice>. Nice to meet you. How's it going?"), regenerated on 2026-11-09 through qgrid (`grok/grok-tts`, `openai/gpt-realtime-2.1-mini`) and checked with STT; re-encoded to 40 kbps mono MP3 (about 640 KB, shipped in the CLI bundle via `web-dist`). Do not trust the OpenAI speech self-transcript as a verbatim check: one ballad take carried an audible "Okay, let's read that line aloud exactly as written." preamble that two STT models heard while `response.output_audio_transcript.done` showed only the script. A voice added upstream needs a sample file or its ▶ fails to load. STT recordings and uploads are numbered clips so one clip run through several models reads as a comparison. A "Word timing" checkbox (default on, 2.17.0+) sends `withTimestamps`; TTS rows and STT rows with word timing (Grok, or OpenAI through the qgrid aligner, 2.19.0+) then render the clip with its words under the player (`TimedPlayer`), highlight the word being spoken (animation-frame polling with a `timeupdate` fallback when frames are throttled), and show the timing source (Grok TTS, qgrid aligner, or the failure). Clicking a word plays from its start. For OpenAI models, recordings (MediaRecorder webm/opus) and uploads are decoded with `AudioContext` at 24 kHz, mixed to mono, and sent as PCM16 WAV (`voice-audio.ts`), because the OpenAI transcription route accepts only WAV or raw PCM; Grok gets the original file (2.19.0+), which keeps a compressed upload far under the 19 MiB inline limit. Results link to their request log.
70
70
 
71
71
  Tool contract visibility: the detail page renders a Tools panel between Response Type and Steps for requests whose `tools` is non-empty. It starts collapsed and its header shows the tool count plus a responsive, truncated name list built from the detail subset — collapsed views issue no extra query. Expanding fires `toolsView` once and caches it for that request id, since a stored tool contract never changes. Each card shows the name, the full description, the parameter count, and a compact display-only zod shape; enum values past the sixth collapse to `/* +N */`, with the full shape reachable through hover and keyboard focus. All JSON Schema conversion happens server-side — the web renders completed strings and holds no schema logic.
72
72
 
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-XKyaHtl9.js";import{i as t,r as n}from"./vendor-react-8xo7RSum.js";import{u as r}from"./vendor-tanstack-6B86itGS.js";import{b as i,o as a,y as o}from"./index-CbElySnT.js";import{t as s}from"./TimedPlayer-cuEgYA3Q.js";var c=e(t()),l=n(),u=(0,c.forwardRef)(({title:e,titleId:t,...n},r)=>(0,l.jsxs)(`svg`,{viewBox:`0 0 24 24`,width:`1.2em`,height:`1.2em`,ref:r,"aria-labelledby":t,...n,children:[e?(0,l.jsx)(`title`,{id:t,children:e}):null,(0,l.jsx)(`path`,{fill:`none`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M15 3h6v6m-11 5L21 3m-3 10v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`})]})),d=(0,c.forwardRef)(({title:e,titleId:t,...n},r)=>(0,l.jsxs)(`svg`,{viewBox:`0 0 24 24`,width:`1.2em`,height:`1.2em`,ref:r,"aria-labelledby":t,...n,children:[e?(0,l.jsx)(`title`,{id:t,children:e}):null,(0,l.jsx)(`path`,{fill:`none`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M21 12a9 9 0 1 1-6.219-8.56`})]})),f=(0,c.forwardRef)(({title:e,titleId:t,...n},r)=>(0,l.jsxs)(`svg`,{viewBox:`0 0 24 24`,width:`1.2em`,height:`1.2em`,ref:r,"aria-labelledby":t,...n,children:[e?(0,l.jsx)(`title`,{id:t,children:e}):null,(0,l.jsxs)(`g`,{fill:`none`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,children:[(0,l.jsx)(`path`,{d:`M12 19v3m7-12v2a7 7 0 0 1-14 0v-2`}),(0,l.jsx)(`rect`,{width:6,height:13,x:9,y:2,rx:3})]})]})),p=(0,c.forwardRef)(({title:e,titleId:t,...n},r)=>(0,l.jsxs)(`svg`,{viewBox:`0 0 24 24`,width:`1.2em`,height:`1.2em`,ref:r,"aria-labelledby":t,...n,children:[e?(0,l.jsx)(`title`,{id:t,children:e}):null,(0,l.jsx)(`path`,{fill:`none`,stroke:`currentColor`,strokeLinecap:`round`,strokeLinejoin:`round`,strokeWidth:2,d:`M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z`})]})),m=24e3;function h(e,t=m){let n=new Uint8Array(44+e.length*2),r=new DataView(n.buffer),i=(e,t)=>{for(let n=0;n<t.length;n++)r.setUint8(e+n,t.charCodeAt(n))};return i(0,`RIFF`),r.setUint32(4,36+e.length*2,!0),i(8,`WAVE`),i(12,`fmt `),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,1,!0),r.setUint32(24,t,!0),r.setUint32(28,t*2,!0),r.setUint16(32,2,!0),r.setUint16(34,16,!0),i(36,`data`),r.setUint32(40,e.length*2,!0),e.forEach((e,t)=>{let n=Math.max(-1,Math.min(1,e));r.setInt16(44+t*2,n<0?n*32768:n*32767,!0)}),n}function g(e){let t=``;for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}async function _(e){let t=new AudioContext({sampleRate:m});try{let n=await t.decodeAudioData(await e.arrayBuffer()),r=new Float32Array(n.length);for(let e=0;e<n.numberOfChannels;e++){let t=n.getChannelData(e);for(let e=0;e<t.length;e++)r[e]+=t[e]/n.numberOfChannels}return g(h(r))}finally{await t.close()}}var v=`qgrid_voice`,y=[`grok/grok-tts`,`openai/gpt-realtime-2.1-mini`,`openai/gpt-realtime-2.1`],b=[`openai/gpt-4o-transcribe`,`openai/gpt-4o-mini-transcribe`,`grok/grok-voice-transcribe-2.0`],x=`marin cedar alloy ash ballad coral echo sage shimmer verse`.split(` `),S=[{label:`Female`,voices:`ara aurora carina celeste eve iris liora luna ursa`.split(` `)},{label:`Male`,voices:`altair atlas castor cosmo helios helix kepler leo lumen lux naksh orion perseus rex rigel sal sirius zagan zenith`.split(` `)}],C=[{label:``,voices:x}],w={provider:`timing from Grok TTS`,aligned:`timing aligned via Grok STT`},T=e=>e.startsWith(`openai/`),E=`w-full rounded-lg border border-sand-200/80 bg-white px-2.5 py-1.5 text-[12px] text-sand-800 placeholder:text-sand-400 focus:outline-none focus:border-sienna-300 disabled:opacity-50`,D=`${E} h-8`,O=`px-3.5 py-1.5 text-[12px] font-medium rounded-lg bg-sienna-500 text-white hover:bg-sienna-600 disabled:opacity-50 transition-all duration-150 active:scale-[0.97] inline-flex items-center gap-1.5 shadow-sm`;function k({label:e,children:t}){return(0,l.jsxs)(`label`,{className:`flex flex-col gap-1`,children:[(0,l.jsx)(`span`,{className:`text-[11px] font-medium text-sand-500`,children:e}),t]})}var A=e=>e.slice(e.indexOf(`/`)+1);function j({title:e,meta:t,requestLogId:n,onRemove:i,children:a}){return(0,l.jsxs)(`li`,{className:`flex flex-col gap-1.5 px-4 py-3`,children:[(0,l.jsxs)(`div`,{className:`flex items-center gap-2 text-[12px]`,children:[(0,l.jsx)(`span`,{className:`font-medium text-sand-800`,children:e}),(0,l.jsx)(`span`,{className:`tabular-nums text-sand-400`,children:t}),(0,l.jsxs)(`span`,{className:`ml-auto flex items-center gap-2`,children:[n!==void 0&&(0,l.jsxs)(r,{to:`/requests/show`,search:{id:n},target:`_blank`,className:`inline-flex items-center gap-1 tabular-nums text-sand-500 hover:text-sienna-500`,children:[`request log #`,n,(0,l.jsx)(u,{className:`size-3`})]}),(0,l.jsx)(`button`,{type:`button`,onClick:i,title:`Remove from history`,className:`text-sand-300 hover:text-sand-600`,children:(0,l.jsx)(o,{className:`size-3.5`})})]})]}),a]})}function M({empty:e,children:t}){return t.length===0?(0,l.jsx)(`p`,{className:`px-4 py-6 text-center text-[12px] text-sand-400`,children:e}):(0,l.jsx)(`ul`,{className:`divide-y divide-sand-100`,children:t})}function N(e){if(!e)return;let t=[],n;return e.graphChars.forEach((r,i)=>{let[a,o]=e.graphTimes[i];/\s/.test(r)?n=void 0:n?(n.text+=r,n.end=o):(n={text:r,start:a,end:o},t.push(n))}),t}function P(){let[e,t]=(0,c.useState)(y[0]),[n,r]=(0,c.useState)(`ara`),[o,u]=(0,c.useState)(``),[f,m]=(0,c.useState)(`Hi! What did you do this weekend?`),[h,g]=(0,c.useState)([]),[_,b]=(0,c.useState)(!0),[P,F]=(0,c.useState)(1),I=(0,c.useRef)(0),L=a.useSpeakMutation(),R=T(e),z=e=>{T(e)!==R&&r(T(e)?x[0]:`ara`),t(e)},B=R&&o.trim()?o.trim():void 0,V=t=>{let n=performance.now(),r={model:e,text:f,voice:t,projectName:v};B&&(r.instructions=B),_&&(r.withTimestamps=!0),!R&&P!==1&&(r.speed=P),L.mutate({params:r},{onSuccess:i=>{let a={key:I.current++,src:`data:${i.mimeType};base64,${i.audio}`,model:e,voice:t,instructions:r.instructions,speed:r.speed,text:f,elapsedMs:performance.now()-n,requestLogId:i.requestLogId,words:N(i.audioTimestamps),timing:i.timestampsError?`timing failed: ${i.timestampsError}`:i.timestampsSource&&w[i.timestampsSource]};g(e=>[a,...e])}})},H=(0,c.useRef)(null),[U,W]=(0,c.useState)();(0,c.useEffect)(()=>()=>H.current?.pause(),[]);let G=e=>{if(r(e),H.current?.pause(),U===e){W(void 0);return}let t=new Audio(`/voice-samples/${R?`openai`:`grok`}/${e}.mp3`);t.addEventListener(`ended`,()=>W(t=>t===e?void 0:t),{once:!0}),H.current=t,W(e),t.play()};return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`div`,{className:`flex flex-col gap-3 p-4`,children:[(0,l.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,l.jsx)(k,{label:`Model`,children:(0,l.jsx)(`select`,{value:e,onChange:e=>z(e.target.value),className:D,children:y.map(e=>(0,l.jsx)(`option`,{value:e,children:e},e))})}),R?(0,l.jsx)(k,{label:`Style instructions (OpenAI only)`,children:(0,l.jsx)(`input`,{value:o,onChange:e=>u(e.target.value),placeholder:`e.g. Speak with a gentle Irish accent.`,className:D})}):(0,l.jsx)(k,{label:`Speed (Grok only) — ${P.toFixed(2)}×`,children:(0,l.jsx)(`input`,{type:`range`,min:.7,max:1.5,step:.05,value:P,onChange:e=>F(Number(e.target.value)),className:`h-8 accent-sienna-500`})})]}),(0,l.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,l.jsx)(`span`,{className:`text-[11px] font-medium text-sand-500`,children:`Voice — ▶ plays a short self-introduction sample, a name selects it`}),(R?C:S).map(e=>(0,l.jsxs)(`div`,{className:`flex items-start gap-2`,children:[e.label&&(0,l.jsx)(`span`,{className:`w-12 shrink-0 pt-1 text-[11px] text-sand-400`,children:e.label}),(0,l.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.voices.map(e=>(0,l.jsxs)(`span`,{className:`inline-flex items-center overflow-hidden rounded-full border text-[12px] ${n===e?`border-sienna-400 bg-sienna-50 text-sienna-700`:`border-sand-200/80 bg-white text-sand-700`}`,children:[(0,l.jsx)(`button`,{type:`button`,onClick:()=>r(e),"aria-pressed":n===e,className:`py-0.5 pl-2.5 pr-1 hover:text-sienna-600`,children:e}),(0,l.jsx)(`button`,{type:`button`,onClick:()=>G(e),title:U===e?`Stop "${e}"`:`Play a "${e}" sample`,className:`py-1 pl-1 pr-2 hover:text-sienna-500 ${U===e?`text-sienna-500`:`text-sand-400`}`,children:U===e?(0,l.jsx)(i,{className:`size-3`}):(0,l.jsx)(p,{className:`size-3`})})]},e))})]},e.label))]}),(0,l.jsx)(k,{label:`Text`,children:(0,l.jsx)(`textarea`,{value:f,onChange:e=>m(e.target.value),rows:3,className:`${E} resize-y`})}),(0,l.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,l.jsxs)(`button`,{type:`button`,onClick:()=>V(n),disabled:L.isPending||!f.trim(),className:O,children:[L.isPending&&(0,l.jsx)(d,{className:`size-3.5 animate-spin`}),`Generate with `,n]}),(0,l.jsxs)(`label`,{className:`flex items-center gap-1.5 text-[12px] text-sand-600`,children:[(0,l.jsx)(`input`,{type:`checkbox`,checked:_,onChange:e=>b(e.target.checked),className:`accent-sienna-500`}),`Word timing`]}),L.isError&&(0,l.jsx)(`p`,{className:`text-[12px] text-danger-500 break-words`,children:L.error?.message})]})]}),(0,l.jsx)(`div`,{className:`border-t border-sand-100`,children:(0,l.jsx)(M,{empty:`Generated clips stack here, newest first, so voices can be compared side by side.`,children:h.map(e=>(0,l.jsxs)(j,{title:[e.voice,A(e.model),e.speed&&`${e.speed}×`].filter(Boolean).join(` · `),meta:[`${(e.elapsedMs/1e3).toFixed(1)}s`,e.timing].filter(Boolean).join(` · `),requestLogId:e.requestLogId,onRemove:()=>g(t=>t.filter(t=>t.key!==e.key)),children:[(!e.words||e.instructions)&&(0,l.jsxs)(`p`,{className:`truncate text-[12px] text-sand-600`,title:e.text,children:[!e.words&&e.text,e.instructions&&(0,l.jsxs)(`span`,{className:`text-sand-400`,children:[` — `,e.instructions]})]}),(0,l.jsx)(s,{src:e.src,words:e.words,autoPlay:!0})]},e.key))})})]})}function F(){let[e,t]=(0,c.useState)(b[0]),[n,r]=(0,c.useState)(``),[o,u]=(0,c.useState)(),[p,m]=(0,c.useState)(!1),[h,g]=(0,c.useState)(),[y,x]=(0,c.useState)([]),S=(0,c.useRef)(null),C=(0,c.useRef)([]),w=(0,c.useRef)(0),E=a.useTranscribeMutation(),N=T(e);(0,c.useEffect)(()=>()=>{S.current?.stream.getTracks().forEach(e=>e.stop()),C.current.forEach(e=>URL.revokeObjectURL(e))},[]);let P=e=>{let t=URL.createObjectURL(e);C.current.push(t),u({blob:e,url:t,clip:C.current.length})};return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)(`div`,{className:`flex flex-col gap-3 p-4`,children:[(0,l.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,l.jsx)(k,{label:`Model`,children:(0,l.jsx)(`select`,{value:e,onChange:e=>t(e.target.value),className:D,children:b.map(e=>(0,l.jsx)(`option`,{value:e,children:e},e))})}),N&&(0,l.jsx)(k,{label:`Prompt (OpenAI only)`,children:(0,l.jsx)(`input`,{value:n,onChange:e=>r(e.target.value),placeholder:`domain words, e.g. qgrid, Kuma`,className:D})})]}),(0,l.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,l.jsxs)(`button`,{type:`button`,onClick:async()=>{if(p)S.current?.stop(),m(!1);else{g(void 0);try{let e=await navigator.mediaDevices.getUserMedia({audio:!0}),t=new MediaRecorder(e),n=[];t.ondataavailable=e=>n.push(e.data),t.onstop=()=>{e.getTracks().forEach(e=>e.stop()),P(new Blob(n,{type:t.mimeType}))},t.start(),S.current=t,m(!0)}catch(e){g(e instanceof Error?e.message:String(e))}}},className:`${O} ${p?`bg-danger-500 hover:bg-danger-500`:``}`,children:[p?(0,l.jsx)(i,{className:`size-3.5`}):(0,l.jsx)(f,{className:`size-3.5`}),p?`Stop`:`Record`]}),(0,l.jsxs)(`label`,{className:`text-[12px] text-sand-600 cursor-pointer hover:text-sienna-500`,children:[`or upload a file`,(0,l.jsx)(`input`,{type:`file`,accept:`audio/*`,className:`hidden`,onChange:e=>{let t=e.target.files?.[0];t&&P(t)}})]}),h&&(0,l.jsx)(`p`,{className:`text-[12px] text-danger-500 break-words`,children:h})]}),o&&(0,l.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,l.jsxs)(`span`,{className:`shrink-0 text-[11px] font-medium text-sand-500`,children:[`clip `,o.clip]}),(0,l.jsx)(`audio`,{controls:!0,src:o.url,className:`h-8 w-full`})]}),(0,l.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,l.jsxs)(`button`,{type:`button`,onClick:async()=>{if(!o)return;g(void 0);let t;try{t=await _(o.blob)}catch(e){g(`could not decode audio: ${e instanceof Error?e.message:String(e)}`);return}let r={model:e,audio:t,mediaType:`audio/wav`,projectName:v};N&&n.trim()&&(r.prompt=n.trim());let i=performance.now();E.mutate({params:r},{onSuccess:t=>{let n={key:w.current++,clip:o.clip,clipUrl:o.url,model:e,prompt:r.prompt,text:t.text,elapsedMs:performance.now()-i,durationSec:t.durationSec,requestLogId:t.requestLogId,words:t.words};x(e=>[n,...e])}})},disabled:!o||p||E.isPending,className:O,children:[E.isPending&&(0,l.jsx)(d,{className:`size-3.5 animate-spin`}),`Transcribe`]}),E.isError&&(0,l.jsx)(`p`,{className:`text-[12px] text-danger-500 break-words`,children:E.error?.message})]})]}),(0,l.jsx)(`div`,{className:`border-t border-sand-100`,children:(0,l.jsx)(M,{empty:`Transcripts stack here, newest first; run one clip through several models to compare.`,children:y.map(e=>(0,l.jsx)(j,{title:`clip ${e.clip} · ${A(e.model)}`,meta:[`${(e.elapsedMs/1e3).toFixed(1)}s`,e.durationSec===void 0?``:`${e.durationSec.toFixed(1)}s audio`,e.prompt?`prompt: ${e.prompt}`:``].filter(Boolean).join(` · `),requestLogId:e.requestLogId,onRemove:()=>x(t=>t.filter(t=>t.key!==e.key)),children:e.words&&e.words.length>0?(0,l.jsx)(s,{src:e.clipUrl,words:e.words}):(0,l.jsx)(`p`,{className:`rounded-lg bg-sand-50 px-3 py-2 text-[13px] text-sand-800 whitespace-pre-wrap`,children:e.text||`(empty transcript)`})},e.key))})})]})}var I=[{id:`tts`,label:`Text to speech`},{id:`stt`,label:`Speech to text`}];function L(){let[e,t]=(0,c.useState)(`tts`);return(0,l.jsxs)(`section`,{className:`rounded-xl border border-sand-200/70 bg-white overflow-hidden`,children:[(0,l.jsx)(`div`,{role:`tablist`,className:`flex gap-1 border-b border-sand-100 px-3 pt-2`,children:I.map(n=>(0,l.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":e===n.id,onClick:()=>t(n.id),className:`-mb-px border-b-2 px-3 py-2 text-[13px] transition-colors duration-150 ${e===n.id?`border-sienna-500 font-medium text-sand-800`:`border-transparent text-sand-500 hover:text-sand-700`}`,children:n.label},n.id))}),(0,l.jsx)(`div`,{role:`tabpanel`,hidden:e!==`tts`,children:(0,l.jsx)(P,{})}),(0,l.jsx)(`div`,{role:`tabpanel`,hidden:e!==`stt`,children:(0,l.jsx)(F,{})})]})}function R(){return(0,l.jsx)(`div`,{className:`max-w-3xl mx-auto`,children:(0,l.jsx)(L,{})})}export{R as component};