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
@@ -1,4 +1,4 @@
import { describe, it, vi } from 'vitest';
import { describe, it, expect, vi } from 'vitest';
/**
* Loads the REAL public/assets/worklets/pcm-playback.worklet.js in a stubbed AudioWorklet
@@ -15,7 +15,7 @@ interface Proc {
capacity: number;
queuedSource: number;
sourceCapacity: number;
refPlayedSamples: Map<string, number>;
refPlayedOut: Map<string, number>;
process: (inputs: unknown[][][], outputs: Float32Array[][]) => boolean;
}
@@ -68,6 +68,10 @@ function clear(proc: Proc): void {
proc.port.onmessage({ data: { type: 'clear' } });
}
function flush(proc: Proc): void {
proc.port.onmessage({ data: { type: 'flush' } });
}
/** One render quantum: emit `samples` output slots and let process() consume/emit. */
function render(proc: Proc, samples = 128): void {
proc.process([[]], [[new Float32Array(samples)]]);
@@ -172,6 +176,88 @@ describe('pcm-playback.worklet', () => {
}
});
describe('end-of-turn draining (regression for premature session termination)', () => {
// The exact incident: 24,000 source samples at 24 kHz = 1000 ms. The resampler must emit
// all 24,000 outputs (main loop defers the final sample; flush() emits the tail) so fully
// drained playback reports exactly 1000 ms and leaves no phantom queued source sample.
it('drains 24,000 source samples at 24 kHz to exactly 1000 ms with no phantom', async () => {
const proc = await loadPlaybackProcessor(24000);
push(proc, frame(0, 24000), 'aud-1');
flush(proc); // audio_ended
drain(proc);
expect(playedFor(proc, 'aud-1')).toBe(1000);
expect(proc.queuedSource).toBe(0); // fully played audio must not retain a phantom sample
expect(proc.refPlayedOut.get('aud-1') ?? 0).toBeCloseTo(24000, 3);
});
it('emits a one-sample tail: a single source sample at 24 kHz reports 0 ms but drains clean', async () => {
const proc = await loadPlaybackProcessor(24000);
push(proc, frame(0, 1), 'aud-1');
flush(proc);
drain(proc);
expect(proc.queuedSource).toBe(0);
// 1 sample = 0.0417 ms → floor is 0, so playedFor is 0, but the sample is not stuck.
expect(playedFor(proc, 'aud-1')).toBe(0);
expect(overflowCount(proc)).toBe(0);
});
// 2,000 source samples at 24 kHz = 83.33 ms → must report 83 ms (floor), not 84, and drain.
it('reports non-integer-millisecond durations by flooring, never rounding up', async () => {
const proc = await loadPlaybackProcessor(24000);
push(proc, frame(0, 2000), 'aud-1');
flush(proc);
drain(proc);
expect(proc.queuedSource).toBe(0);
expect(playedFor(proc, 'aud-1')).toBe(83); // floor(2000/24000*1000) = 83, not 84
});
// Even 44.1k/48k contexts must retire the full source on flush (the backend breaks are
// computed from played source bytes, so a missing tail would look like a perpetual stall).
for (const rate of [44100, 48000]) {
it(`retires all source with no phantom at a ${rate} Hz context`, async () => {
const proc = await loadPlaybackProcessor(rate);
push(proc, frame(0, 24000), 'aud-1');
flush(proc);
drain(proc);
expect(proc.queuedSource).toBe(0);
// 24,000 source samples = 1000 ms regardless of the context/output rate.
expect(playedFor(proc, 'aud-1')).toBe(1000);
});
}
it('drains a final chunk smaller than the prebuffer threshold', async () => {
const proc = await loadPlaybackProcessor(24000); // prebuffer = 1920 output samples
// Two chunks: a large one that starts playback, then a tiny trailing chunk (< prebuffer)
// that must still be flushed out instead of being stuck below the prebuffer gate.
push(proc, frame(0, 4800), 'aud-1');
render(proc, 128); // started
push(proc, frame(4800, 400), 'aud-1'); // 400 samples < prebuffer
flush(proc);
drain(proc);
expect(proc.queuedSource).toBe(0);
// 5200 source samples = 216.66 ms → 216 ms.
expect(playedFor(proc, 'aud-1')).toBe(216);
});
it('credits a new ref its own audio even when it arrives while the prior ref still queued', async () => {
const proc = await loadPlaybackProcessor(24000);
push(proc, frame(0, 4800), 'aud-a'); // 200 ms
flush(proc); // aud-a generation ended → its tail is emitted
push(proc, frame(0, 24000), 'aud-b'); // arrives; aud-a still draining
flush(proc);
drain(proc);
expect(proc.queuedSource).toBe(0);
expect(playedFor(proc, 'aud-a')).toBe(200);
expect(playedFor(proc, 'aud-b')).toBe(1000);
});
});
describe('progress is accurate, monotonic and per audio_ref', () => {
it('credits each queued ref its own consumed source (never the next ref)', async () => {
const proc = await loadPlaybackProcessor(24000); // ratio 1 → 3,000 source ≈ 125 ms
@@ -188,10 +274,10 @@ describe('pcm-playback.worklet', () => {
drain(proc);
// Each ref consumed only its own ~3,000 source samples (±1 sample of resampler lag),
// Each ref consumed only its own ~3,000 OUTPUT samples (±1 sample of resampler lag),
// never the other ref's samples. The next-ref bug would credit 'aud-b' with 6,000.
expect(Math.abs((proc.refPlayedSamples.get('aud-a') ?? 0) - 3000)).toBeLessThanOrEqual(1);
expect(Math.abs((proc.refPlayedSamples.get('aud-b') ?? 0) - 3000)).toBeLessThanOrEqual(1);
expect(Math.abs((proc.refPlayedOut.get('aud-a') ?? 0) - 3000)).toBeLessThanOrEqual(1);
expect(Math.abs((proc.refPlayedOut.get('aud-b') ?? 0) - 3000)).toBeLessThanOrEqual(1);
const finalA = playedFor(proc, 'aud-a');
const finalB = playedFor(proc, 'aud-b');
expect(finalA).toBeGreaterThanOrEqual(124);
@@ -212,7 +298,7 @@ describe('pcm-playback.worklet', () => {
// Final progress reflects what was actually heard (~5 ms), not the whole 3,000 queue.
const finals = proc.out.filter((m) => m.type === 'progress' && m.audioRef === 'aud-a');
expect(finals.at(-1)?.playedMs).toBe(5);
expect(proc.refPlayedSamples.get('aud-a') ?? 0).toBeCloseTo(128, 5);
expect(proc.refPlayedOut.get('aud-a') ?? 0).toBeCloseTo(128, 5);
// A fresh ref plays normally after the interruption.
push(proc, frame(0, 3000), 'aud-b');
@@ -65,6 +65,8 @@ describe('VoiceStreamService (backend handoff contract)', () => {
let controls: PlaybackProgressMessage[];
let transportMock: TransportMock;
let engineStop: ReturnType<typeof vi.fn>;
let engineFlush: Mock;
let engineClear: Mock;
beforeEach(() => {
sessionStorage.clear();
@@ -72,6 +74,8 @@ describe('VoiceStreamService (backend handoff contract)', () => {
transportHandlers = null;
controls = [];
engineStop = vi.fn();
engineFlush = vi.fn();
engineClear = vi.fn();
api = {
me: vi.fn().mockResolvedValue(ME),
@@ -113,8 +117,8 @@ describe('VoiceStreamService (backend handoff contract)', () => {
stop: engineStop,
setMuted: vi.fn(),
enqueuePlayback: vi.fn(),
clearPlayback: vi.fn(),
flushPlayback: vi.fn(),
clearPlayback: engineClear,
flushPlayback: engineFlush,
inputLevel: () => 0,
outputLevel: () => 0,
},
@@ -310,6 +314,38 @@ describe('VoiceStreamService (backend handoff contract)', () => {
expect(api.closeVoiceSession).toHaveBeenCalledTimes(1);
});
it('drains on audio_ended so the ref reaches its true final progress (not solely on transcript)', async () => {
await startConnected();
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' });
// A `completed` transcript that arrives BEFORE audio_ended must NOT flush the queue: the
// audio is still streaming, so finalizing the tail now would be premature.
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: '…',
status: 'completed',
});
expect(engineFlush).not.toHaveBeenCalled();
// audio_ended (generation complete) drives the drain: the worklet emits the deferred
// tail and plays out, so playback progress retires the whole ref before the backend's
// stall timeout — this is the fix for the premature LIVE_BUFFER_OVERFLOW termination.
transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'aud-1' });
expect(engineFlush).toHaveBeenCalledTimes(1);
// Once generation is done, a late/second completed transcript re-flushes idempotently.
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: '…',
status: 'completed',
});
expect(engineFlush).toHaveBeenCalledTimes(2);
});
it('requires a fresh conversation after CONTEXT_REVOKED and drops the old attempt', async () => {
await startConnected();
const ended = firstEndedError();
@@ -371,6 +407,51 @@ describe('VoiceStreamService (backend handoff contract)', () => {
expect(assistant?.final).toBe(true);
});
it('orders a user request above its AI response even when the assistant transcript arrives first', async () => {
await startConnected();
// The server streams assistant partials before the user transcript for the same turn.
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 'turn-1', role: 'assistant', text: 'پاسخ فارسی', status: 'partial' });
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 'turn-1', role: 'user', text: 'سلام', status: 'completed' });
const list = service.messages();
const userIndex = list.findIndex((m) => m.id === 'turn-1:user');
const assistantIndex = list.findIndex((m) => m.id === 'turn-1:assistant');
expect(userIndex).toBeGreaterThanOrEqual(0);
expect(assistantIndex).toBeGreaterThan(userIndex);
});
it('keeps user→assistant order and stable turn order across turns', async () => {
await startConnected();
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'user', text: 'سوال ۱', status: 'completed' });
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'پاسخ ۱', status: 'completed' });
// turn 2's assistant lands before its user transcript
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't2', role: 'assistant', text: 'پاسخ ۲', status: 'partial' });
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't2', role: 'user', text: 'سوال ۲', status: 'completed' });
expect(service.messages().map((m) => m.id)).toEqual([
't1:user',
't1:assistant',
't2:user',
't2:assistant',
]);
});
it('keeps the user request above a sources-only assistant bubble of the same turn', async () => {
await startConnected();
// A `sources` frame can create the assistant bubble before the user transcript arrives.
transportHandlers?.onEvent({
type: 'sources',
turn_ref: 't1',
sources: [{ source_ref: 's1', document_id: 'd1', chunk_id: 'c1', title: 'سند', excerpt: 'بند' }],
});
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'user', text: 'سلام', status: 'completed' });
expect(service.messages().map((m) => m.id)).toEqual(['t1:user', 't1:assistant']);
});
it('closes the reservation (V04) when the call ends on user request', async () => {
await startConnected();
await service.close();
@@ -137,6 +137,7 @@ export class VoiceStreamService {
private session = 0;
private streaming = false;
private turnEnded = false;
private audioGenerationDone = false; // server finished sending this audio_ref's frames
private interruptTimer: ReturnType<typeof setTimeout> | null = null;
private settleTimer: ReturnType<typeof setTimeout> | null = null;
private errorTimer: ReturnType<typeof setTimeout> | null = null;
@@ -490,11 +491,16 @@ export class VoiceStreamService {
case 'audio_started':
this.currentAudioRef = event.audio_ref;
this.audioGenerationDone = false; // frames for this ref are now streaming in
break;
case 'audio_ended':
// Generation ended; the ref's audio may still be playing — its final progress is
// reported when the queue drains or the turn is interrupted.
// Generation finished: emit the worklet's deferred tail and drain what is buffered so
// the ref's FINAL playback progress reaches its true duration (no phantom outstanding
// sample the backend would read as a stall). This drives the drain on generation
// completion, cooperating with — not depending solely on — the completed transcript.
this.audioGenerationDone = true;
this.engine.flushPlayback();
break;
case 'turn_interrupted':
@@ -524,9 +530,10 @@ export class VoiceStreamService {
}
if (event.status === 'completed') {
// All text for this turn is out. Play what is buffered, then return to LISTENING.
// All text for this turn is out. Drain the queue only once generation has ended
// (audio_ended); otherwise the tail would be finalized while audio is still streamed.
this.turnEnded = true;
this.engine.flushPlayback();
if (this.audioGenerationDone) this.engine.flushPlayback();
}
}
@@ -616,17 +623,14 @@ export class VoiceStreamService {
const index = list.findIndex((m) => m.id === id);
if (index === -1) {
if (!event.text.trim()) return list;
return [
...list,
{
id,
turnRef: event.turn_ref,
role: event.role,
text: event.text,
final,
interrupted: interrupted || undefined,
},
];
return this.insertTranscript(list, {
id,
turnRef: event.turn_ref,
role: event.role,
text: event.text,
final,
interrupted: interrupted || undefined,
});
}
const current = list[index];
@@ -679,13 +683,38 @@ export class VoiceStreamService {
}
const next = { ...current, sources };
if (index === -1) return [...list, next];
if (index === -1) return this.insertTranscript(list, next);
const copy = [...list];
copy[index] = next;
return copy;
});
}
/**
* Inserts a new transcript bubble so the invariant always holds: WITHIN a turn the user
* request precedes the AI response, and turns keep their first-seen order. This matters when
* an assistant partial/response for a turn arrives before that turn's user transcript (the
* server streams transcripts per role and does not guarantee the user text lands first) —
* a plain append would then show the AI answer above the user's question.
*/
private insertTranscript(list: VoiceMessage[], message: VoiceMessage): VoiceMessage[] {
const roleRank = message.role === 'user' ? 0 : 1;
// Stable turn order = the order turns first appear in the current list; a turn we have
// not seen yet sorts after all existing ones.
const turns: string[] = [];
for (const m of list) if (!turns.includes(m.turnRef)) turns.push(m.turnRef);
const turnRank = turns.includes(message.turnRef) ? turns.indexOf(message.turnRef) : turns.length;
for (let i = 0; i < list.length; i++) {
const existingTurn = turns.indexOf(list[i].turnRef);
const existingRank = list[i].role === 'user' ? 0 : 1;
const comesAfter =
existingTurn > turnRank || (existingTurn === turnRank && existingRank > roleRank);
if (comesAfter) return [...list.slice(0, i), message, ...list.slice(i)];
}
return [...list, message];
}
private markInterrupted(turnRef: string): void {
const id = `${turnRef}:assistant`;
this.messages.update((list) => {
@@ -882,6 +911,7 @@ export class VoiceStreamService {
private resetTurnFlags(): void {
this.turnEnded = false;
this.audioGenerationDone = false;
}
private clearSettleTimer(): void {