refactor: overhaul home UI and audio playback reliability

Redesign the home page and voice stream panel into a compact dock
layout to improve the chat experience. Implement a flush mechanism in
the PCM playback worklet to handle the resampler tail, preventing
premature session termination due to phantom outstanding playback.
Fix document filter visibility in settings to ensure controls remain
accessible when no results match, and refactor transcript insertion
to maintain correct user/assistant ordering.
This commit is contained in:
PeymanHonarjoo
2026-10-10 17:47:51 +03:30
parent be17544f2d
commit 28590c6dce
16 changed files with 1092 additions and 534 deletions
+115 -51
View File
@@ -4,23 +4,30 @@
* Bounded playout queue. The cap is on OUTSTANDING SOURCE PCM — BOUND_BYTES (96,000 bytes
* = 48,000 source samples ≈ 2 s at 24 kHz mono PCM16) — and each stage uses ONE unit
* consistently:
* admission + progress are booked in SOURCE samples (the contract/wire unit);
* the ring stores the RESAMPLED OUTPUT samples the AudioContext actually consumes.
* admission is booked in SOURCE samples (the contract/wire unit);
* the ring stores the RESAMPLED OUTPUT samples the AudioContext actually consumes;
* PROGRESS is booked in OUTPUT samples (an integer the resampler fully controls), and
* rendered as milliseconds at the context rate. Because resampling preserves duration,
* output-time equals source-time, so this reports the same ms as source/srcRate — but it
* is exact (no float drift over thousands of iterations).
* The output ring is sized to hold the source bound at the worst-case ratio
* (source bound ÷ ratio), so the SAME 2 s source cap holds at any real context rate
* (24k / 44.1k / 48k …) without widening the source limit, suppressing overflow or
* silently dropping PCM. If the queue fills anyway the processor posts `overflow` and the
* call fails safely.
* (24k / 44.1k / 48k …) without widening the source limit, suppressing overflow or silently
* dropping PCM. If the queue fills anyway the processor posts `overflow` and the call fails
* safely.
*
* Real playback progress: played_ms for a server audio_ref is the cumulative SOURCE
* samples of THAT ref actually consumed by process(), never a timer. Queued audio keeps
* its own audio_ref when a different ref arrives (a FIFO of per-ref source spans), so
* progress is never credited to the wrong turn. Reported ~4×/s, on ref completion, and on
* clear/flush/idle, so the main thread can send the contract's playback_progress message.
* End-of-turn tail: the resample loop keeps the window's last sample as `prev` (for
* cross-chunk continuity) and only emits it at the start of the NEXT chunk. At the final
* chunk there is no next chunk, so without an explicit flush the last source sample is never
* emitted — queued source never reaches zero and played_ms under-reports by ~1 ms, which the
* backend reads as perpetual outstanding playback (a stall/overflow signature). `flush()`
* (raised on audio_ended) emits that deferred tail so every admitted source sample becomes
* output and fully played audio drains to exactly its real duration. `clear()` (barge-in)
* discards the tail instead, so interrupted audio is never credited as played.
*
* Messages in: { type: 'push', pcm: ArrayBuffer (Int16 mono), sampleRate, audioRef }
* { type: 'clear' } barge-in: drop everything immediately
* { type: 'flush' } end of turn: play what is left, then report 'idle'
* { type: 'flush' } end of turn: emit the tail, play what is left, then idle
* Messages out: { type: 'progress', audioRef, playedMs }
* { type: 'idle' } buffer ran dry after playing
* { type: 'overflow' } bounded queue filled — caller fails the session safely
@@ -32,7 +39,7 @@ const REPORT_INTERVAL_MS = 250;
class PcmPlaybackProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.sourceCapacity = Math.floor(BOUND_BYTES / 2); // 48,000 SOURCE samples (the admission bound)
this.sourceCapacity = Math.floor(BOUND_BYTES / 2); // 48,000 SOURCE samples (admission bound)
this.ratio = 1; // SOURCE samples per OUTPUT sample (resolved on first push)
this.sized = false; // true once the output ring matches the real context rate
this.capacity = this.sourceCapacity; // OUTPUT slots currently allocated (grows for upsampling)
@@ -45,14 +52,22 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
this.started = false;
this.prev = 0;
this.pos = 1;
// Per-audio_ref attribution. `refQueue` keeps the still-queued SOURCE span of each ref
// (merged per ref so it stays ≤ the number of turns); `refPlayedSamples` keeps each
// ref's cumulative consumed source. Together they tie queued audio to its own ref and
// End-of-turn tail accounting (per turn, reset on flush/clear). `admittedSrc` +
// `emittedOut` let flush() emit the exact OUTPUT count for all admitted source; the last
// chunk window is retained so the tail can be interpolated correctly.
this.admittedSrc = 0; // SOURCE samples admitted this turn
this.emittedOut = 0; // OUTPUT samples emitted for them so far
this.windowSrc = null; // last chunk's src window (for tail interpolation)
this.windowN = 0;
// Per-audio_ref attribution. `refQueue` keeps the still-queued OUTPUT span of each ref
// (merged per ref so it stays ≤ the number of turns); `refPlayedOut` keeps each ref's
// cumulative OUTPUT samples consumed. Together they tie queued audio to its own ref and
// keep progress cumulative and correct across ref changes.
this.refQueue = []; // [{ ref, src }] src = remaining SOURCE samples of that ref
this.refPlayedSamples = new Map();
this.refQueue = []; // [{ ref, out }] out = remaining OUTPUT samples of that ref
this.refPlayedOut = new Map();
this.playingRef = null; // ref currently being consumed / reported
this.unreportedSamples = 0;
this.pendingRef = null; // audio_ref of the most recent push (the one flush() tail belongs to)
this.unreportedOut = 0;
this.overflowPosted = false;
this.port.onmessage = (e) => {
const m = e.data;
@@ -86,19 +101,59 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
this.started = false;
this.prev = 0;
this.pos = 1;
// Discard the deferred tail too: interrupted audio is NOT played, so it must not be
// credited or emitted.
this.admittedSrc = 0;
this.emittedOut = 0;
this.windowSrc = null;
this.windowN = 0;
this.playingRef = null;
}
flush() {
this.finalizeTail(); // emit the deferred tail so every admitted sample becomes output
if (this.count === 0) {
this.started = false;
this.reportFinal();
this.port.postMessage({ type: 'idle' });
} else {
this.started = true; // short tail: do not wait for the prebuffer
this.started = true; // play the remaining audio + tail without waiting for the prebuffer
}
}
/**
* End-of-turn tail: emit the OUTPUT samples for every admitted SOURCE sample that the push
* loop deferred (it keeps the window's last sample as `prev` for cross-chunk continuity and
* only emits it at the start of the next chunk). Continuing the interpolation past the last
* sample — holding its value — produces real output so fully played audio leaves queued
* source at zero and played_ms reflects the true duration (never fabricated upward).
*/
finalizeTail() {
const src = this.windowSrc;
const n = this.windowN;
if (src && n > 0) {
const target = Math.round(this.admittedSrc / this.ratio); // exact OUTPUT count for the turn
let pos = n + this.pos; // continue from where the push loop stopped (abs. in this window)
while (this.emittedOut < target) {
const base = Math.min(Math.floor(pos), n);
const frac = Math.min(1, Math.max(0, pos - base));
const a = src[base];
const b = src[Math.min(base + 1, n)]; // clamp: hold the last sample past the boundary
this.write(a * (1 - frac) + b * frac);
this.creditQueue(1); // the emitted tail belongs to the current (last) ref
this.emittedOut++;
pos += this.ratio;
}
}
// Each turn is an independent signal: reset the resampler for the next one.
this.admittedSrc = 0;
this.emittedOut = 0;
this.windowSrc = null;
this.windowN = 0;
this.pos = 1;
this.prev = 0;
}
push(int16, srcRate, audioRef) {
const n = int16.length;
if (!n) return;
@@ -106,7 +161,7 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
const ratio = srcRate / sampleRate; // SOURCE samples per OUTPUT sample
this.configure(ratio);
// OUTPUT samples this chunk will add — the exact count the resample loop performs.
// OUTPUT samples this chunk's main loop will add — an upper bound on the exact count.
const produced = this.pos < n ? Math.ceil((n - this.pos) / this.ratio) : 0;
// Bounded queue — two consistent guards, each in its own unit:
@@ -116,26 +171,38 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
if (this.count + produced > this.capacity) return this.overflow();
this.queuedSource += n;
// Keep the audio_ref of the queued source span so consumption is credited correctly
// even when the next ref arrives while this one is still playing.
const last = this.refQueue[this.refQueue.length - 1];
if (last && last.ref === audioRef) last.src += n;
else this.refQueue.push({ ref: audioRef, src: n });
this.admittedSrc += n; // every admitted source sample must eventually become output
const src = new Float32Array(n + 1);
src[0] = this.prev;
for (let i = 0; i < n; i++) src[i + 1] = int16[i] / 32768;
// Retain this window so flush() can emit the deferred tail correctly.
this.windowSrc = src;
this.windowN = n;
let pos = this.pos;
let mainOut = 0;
while (pos < n) {
const i = Math.floor(pos);
const frac = pos - i;
this.write(src[i] * (1 - frac) + src[i + 1] * frac);
mainOut++;
pos += this.ratio;
}
this.prev = src[n];
this.pos = pos - n;
this.emittedOut += mainOut;
this.pendingRef = audioRef;
this.creditQueue(mainOut); // attribute this chunk's OUTPUT to its audio_ref
}
/** Adds `out` OUTPUT samples to the current ref's span (merging consecutive same-ref pushes). */
creditQueue(out) {
const ref = this.pendingRef;
const last = this.refQueue[this.refQueue.length - 1];
if (last && last.ref === ref) last.out += out;
else this.refQueue.push({ ref, out });
}
overflow() {
@@ -173,12 +240,13 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
}
}
if (played > 0) {
const consumedSource = played * this.ratio; // OUTPUT played → SOURCE consumed
this.queuedSource = Math.max(0, this.queuedSource - consumedSource);
this.consumeSpans(consumedSource);
this.queuedSource = Math.max(0, this.queuedSource - played * this.ratio); // OUTPUT→SOURCE
this.consumeSpans(played);
this.reportCadence();
}
if (this.count === 0) {
// Ring drained: nothing is outstanding, so no phantom source remains for this turn.
this.queuedSource = 0;
this.started = false;
this.reportFinal();
this.port.postMessage({ type: 'idle' });
@@ -191,48 +259,44 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
return true;
}
/** Draw `amount` SOURCE samples off the front of the ref FIFO, crediting each ref. */
consumeSpans(amount) {
while (amount > 1e-6 && this.refQueue.length) {
/** Draw `played` OUTPUT samples off the front of the ref FIFO, crediting each ref. */
consumeSpans(played) {
while (played > 0 && this.refQueue.length) {
const span = this.refQueue[0];
const take = amount < span.src ? amount : span.src;
span.src -= take;
amount -= take;
this.creditRef(span.ref, take);
if (span.src <= 1e-6) {
const take = played < span.out ? played : span.out;
span.out -= take;
played -= take;
this.refPlayedOut.set(span.ref, (this.refPlayedOut.get(span.ref) ?? 0) + take);
this.playingRef = span.ref;
this.unreportedOut += take;
if (span.out <= 0) {
this.refQueue.shift();
this.postProgress(span.ref); // ref finished: post its final cumulative before the next ref
}
}
}
creditRef(ref, sourceSamples) {
this.refPlayedSamples.set(ref, (this.refPlayedSamples.get(ref) ?? 0) + sourceSamples);
this.playingRef = ref;
this.unreportedSamples += sourceSamples;
}
/** Final cumulative report for the ref currently playing (interruption / drain / clear). */
reportFinal() {
this.unreportedSamples = 0;
this.unreportedOut = 0;
if (!this.playingRef) return;
this.postProgress(this.playingRef);
}
/** Cadence report for the ref currently playing (~REPORT_INTERVAL_MS of consumed source). */
/** Cadence report for the ref currently playing (~REPORT_INTERVAL_MS of consumed output). */
reportCadence() {
if (!this.playingRef) return;
const srcRate = this.ratio * sampleRate;
if ((this.unreportedSamples / srcRate) * 1000 >= REPORT_INTERVAL_MS) {
if ((this.unreportedOut / sampleRate) * 1000 >= REPORT_INTERVAL_MS) {
this.reportFinal();
}
}
postProgress(ref) {
const playedSamples = this.refPlayedSamples.get(ref) ?? 0;
const srcRate = this.ratio * sampleRate;
// floor: never claims an unheard millisecond; monotonic because it is cumulative.
const playedMs = Math.floor((playedSamples / srcRate) * 1000);
const playedOut = this.refPlayedOut.get(ref) ?? 0;
// OUTPUT samples at the context rate → milliseconds; floor never claims an unheard ms and
// stays monotonic because it is cumulative. Output-time equals source-time (SRC preserves
// duration), so this equals the contract's played source / srcRate.
const playedMs = Math.floor((playedOut / sampleRate) * 1000);
if (playedMs <= 0) return;
this.port.postMessage({ type: 'progress', audioRef: ref, playedMs });
}