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 * 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 * = 48,000 source samples ≈ 2 s at 24 kHz mono PCM16) — and each stage uses ONE unit
* consistently: * consistently:
* admission + progress are booked in SOURCE samples (the contract/wire unit); * admission is booked in SOURCE samples (the contract/wire unit);
* the ring stores the RESAMPLED OUTPUT samples the AudioContext actually consumes. * 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 * 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 * (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 * (24k / 44.1k / 48k …) without widening the source limit, suppressing overflow or silently
* silently dropping PCM. If the queue fills anyway the processor posts `overflow` and the * dropping PCM. If the queue fills anyway the processor posts `overflow` and the call fails
* call fails safely. * safely.
* *
* Real playback progress: played_ms for a server audio_ref is the cumulative SOURCE * End-of-turn tail: the resample loop keeps the window's last sample as `prev` (for
* samples of THAT ref actually consumed by process(), never a timer. Queued audio keeps * cross-chunk continuity) and only emits it at the start of the NEXT chunk. At the final
* its own audio_ref when a different ref arrives (a FIFO of per-ref source spans), so * chunk there is no next chunk, so without an explicit flush the last source sample is never
* progress is never credited to the wrong turn. Reported ~4×/s, on ref completion, and on * emitted — queued source never reaches zero and played_ms under-reports by ~1 ms, which the
* clear/flush/idle, so the main thread can send the contract's playback_progress message. * 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 } * Messages in: { type: 'push', pcm: ArrayBuffer (Int16 mono), sampleRate, audioRef }
* { type: 'clear' } barge-in: drop everything immediately * { 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 } * Messages out: { type: 'progress', audioRef, playedMs }
* { type: 'idle' } buffer ran dry after playing * { type: 'idle' } buffer ran dry after playing
* { type: 'overflow' } bounded queue filled — caller fails the session safely * { type: 'overflow' } bounded queue filled — caller fails the session safely
@@ -32,7 +39,7 @@ const REPORT_INTERVAL_MS = 250;
class PcmPlaybackProcessor extends AudioWorkletProcessor { class PcmPlaybackProcessor extends AudioWorkletProcessor {
constructor() { constructor() {
super(); 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.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.sized = false; // true once the output ring matches the real context rate
this.capacity = this.sourceCapacity; // OUTPUT slots currently allocated (grows for upsampling) this.capacity = this.sourceCapacity; // OUTPUT slots currently allocated (grows for upsampling)
@@ -45,14 +52,22 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
this.started = false; this.started = false;
this.prev = 0; this.prev = 0;
this.pos = 1; this.pos = 1;
// Per-audio_ref attribution. `refQueue` keeps the still-queued SOURCE span of each ref // End-of-turn tail accounting (per turn, reset on flush/clear). `admittedSrc` +
// (merged per ref so it stays ≤ the number of turns); `refPlayedSamples` keeps each // `emittedOut` let flush() emit the exact OUTPUT count for all admitted source; the last
// ref's cumulative consumed source. Together they tie queued audio to its own ref and // 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. // keep progress cumulative and correct across ref changes.
this.refQueue = []; // [{ ref, src }] src = remaining SOURCE samples of that ref this.refQueue = []; // [{ ref, out }] out = remaining OUTPUT samples of that ref
this.refPlayedSamples = new Map(); this.refPlayedOut = new Map();
this.playingRef = null; // ref currently being consumed / reported 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.overflowPosted = false;
this.port.onmessage = (e) => { this.port.onmessage = (e) => {
const m = e.data; const m = e.data;
@@ -86,19 +101,59 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
this.started = false; this.started = false;
this.prev = 0; this.prev = 0;
this.pos = 1; 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; this.playingRef = null;
} }
flush() { flush() {
this.finalizeTail(); // emit the deferred tail so every admitted sample becomes output
if (this.count === 0) { if (this.count === 0) {
this.started = false; this.started = false;
this.reportFinal(); this.reportFinal();
this.port.postMessage({ type: 'idle' }); this.port.postMessage({ type: 'idle' });
} else { } 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) { push(int16, srcRate, audioRef) {
const n = int16.length; const n = int16.length;
if (!n) return; if (!n) return;
@@ -106,7 +161,7 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
const ratio = srcRate / sampleRate; // SOURCE samples per OUTPUT sample const ratio = srcRate / sampleRate; // SOURCE samples per OUTPUT sample
this.configure(ratio); 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; const produced = this.pos < n ? Math.ceil((n - this.pos) / this.ratio) : 0;
// Bounded queue — two consistent guards, each in its own unit: // 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(); if (this.count + produced > this.capacity) return this.overflow();
this.queuedSource += n; this.queuedSource += n;
this.admittedSrc += n; // every admitted source sample must eventually become output
// 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 });
const src = new Float32Array(n + 1); const src = new Float32Array(n + 1);
src[0] = this.prev; src[0] = this.prev;
for (let i = 0; i < n; i++) src[i + 1] = int16[i] / 32768; 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 pos = this.pos;
let mainOut = 0;
while (pos < n) { while (pos < n) {
const i = Math.floor(pos); const i = Math.floor(pos);
const frac = pos - i; const frac = pos - i;
this.write(src[i] * (1 - frac) + src[i + 1] * frac); this.write(src[i] * (1 - frac) + src[i + 1] * frac);
mainOut++;
pos += this.ratio; pos += this.ratio;
} }
this.prev = src[n]; this.prev = src[n];
this.pos = pos - 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() { overflow() {
@@ -173,12 +240,13 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
} }
} }
if (played > 0) { if (played > 0) {
const consumedSource = played * this.ratio; // OUTPUT played → SOURCE consumed this.queuedSource = Math.max(0, this.queuedSource - played * this.ratio); // OUTPUT→SOURCE
this.queuedSource = Math.max(0, this.queuedSource - consumedSource); this.consumeSpans(played);
this.consumeSpans(consumedSource);
this.reportCadence(); this.reportCadence();
} }
if (this.count === 0) { if (this.count === 0) {
// Ring drained: nothing is outstanding, so no phantom source remains for this turn.
this.queuedSource = 0;
this.started = false; this.started = false;
this.reportFinal(); this.reportFinal();
this.port.postMessage({ type: 'idle' }); this.port.postMessage({ type: 'idle' });
@@ -191,48 +259,44 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
return true; return true;
} }
/** Draw `amount` SOURCE samples off the front of the ref FIFO, crediting each ref. */ /** Draw `played` OUTPUT samples off the front of the ref FIFO, crediting each ref. */
consumeSpans(amount) { consumeSpans(played) {
while (amount > 1e-6 && this.refQueue.length) { while (played > 0 && this.refQueue.length) {
const span = this.refQueue[0]; const span = this.refQueue[0];
const take = amount < span.src ? amount : span.src; const take = played < span.out ? played : span.out;
span.src -= take; span.out -= take;
amount -= take; played -= take;
this.creditRef(span.ref, take); this.refPlayedOut.set(span.ref, (this.refPlayedOut.get(span.ref) ?? 0) + take);
if (span.src <= 1e-6) { this.playingRef = span.ref;
this.unreportedOut += take;
if (span.out <= 0) {
this.refQueue.shift(); this.refQueue.shift();
this.postProgress(span.ref); // ref finished: post its final cumulative before the next ref 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). */ /** Final cumulative report for the ref currently playing (interruption / drain / clear). */
reportFinal() { reportFinal() {
this.unreportedSamples = 0; this.unreportedOut = 0;
if (!this.playingRef) return; if (!this.playingRef) return;
this.postProgress(this.playingRef); 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() { reportCadence() {
if (!this.playingRef) return; if (!this.playingRef) return;
const srcRate = this.ratio * sampleRate; if ((this.unreportedOut / sampleRate) * 1000 >= REPORT_INTERVAL_MS) {
if ((this.unreportedSamples / srcRate) * 1000 >= REPORT_INTERVAL_MS) {
this.reportFinal(); this.reportFinal();
} }
} }
postProgress(ref) { postProgress(ref) {
const playedSamples = this.refPlayedSamples.get(ref) ?? 0; const playedOut = this.refPlayedOut.get(ref) ?? 0;
const srcRate = this.ratio * sampleRate; // OUTPUT samples at the context rate → milliseconds; floor never claims an unheard ms and
// floor: never claims an unheard millisecond; monotonic because it is cumulative. // stays monotonic because it is cumulative. Output-time equals source-time (SRC preserves
const playedMs = Math.floor((playedSamples / srcRate) * 1000); // duration), so this equals the contract's played source / srcRate.
const playedMs = Math.floor((playedOut / sampleRate) * 1000);
if (playedMs <= 0) return; if (playedMs <= 0) return;
this.port.postMessage({ type: 'progress', audioRef: ref, playedMs }); this.port.postMessage({ type: 'progress', audioRef: ref, playedMs });
} }
+199 -123
View File
@@ -1,33 +1,21 @@
/* -------------------------------------------------------------------------- /* ==========================================================================
Home page — Claude-style chat column Layout: .home-page > .chat-column > ( .transcript-list + .composer )
Structure: - Landing (no conversation): greeting + composer are centered as one group.
.home-page - Conversation: the greeting collapses, the transcript list grows to fill the
.chat-column column (it is the only scroller) and the composer sits at the bottom.
.transcript-list (flex: 1, scroll) ========================================================================== */
.composer (pinned bottom of column)
Two layouts, CSS-only, driven by [class.has-conversation]:
- empty state column hugs its content and centers (logo + composer as a group)
- conversation column is exactly one viewport tall, transcript scrolls inside it
-------------------------------------------------------------------------- */
/* The host defaults to `display: inline`, which adds a line-box strut under the
full-height column and pushes the page into Y overflow. Block removes it. */
:host {
display: block;
min-height: 0;
}
.home-page { .home-page {
position: relative;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: center; height: 100dvh;
min-height: 100dvh; min-height: 100dvh;
box-sizing: border-box; box-sizing: border-box;
padding: 0; overflow: hidden;
position: relative; background:
/* Flat page color; every decorative glow lives in ::below so it can fade out as one. */ radial-gradient(ellipse 50% 40% at 50% 45%, rgba(59, 130, 246, 0.1), transparent 70%),
background: var(--app-bg); var(--app-bg);
} }
.home-page::before { .home-page::before {
@@ -35,91 +23,38 @@
position: absolute; position: absolute;
inset: 0; inset: 0;
background: background:
radial-gradient(ellipse 50% 40% at 50% 45%, rgba(59, 130, 246, 0.1), transparent 70%),
radial-gradient(circle at 50% 40%, rgba(59, 130, 246, 0.07), transparent 55%), radial-gradient(circle at 50% 40%, rgba(59, 130, 246, 0.07), transparent 55%),
radial-gradient(circle at 35% 55%, rgba(99, 102, 241, 0.05), transparent 50%), radial-gradient(circle at 35% 55%, rgba(99, 102, 241, 0.05), transparent 50%),
radial-gradient(circle at 65% 50%, rgba(59, 130, 246, 0.04), transparent 45%); radial-gradient(circle at 65% 50%, rgba(59, 130, 246, 0.04), transparent 45%);
pointer-events: none; pointer-events: none;
z-index: 0; z-index: 0;
transition: opacity 0.35s ease; transition: opacity 0.5s ease;
}
.home-page.has-conversation {
background: var(--app-bg);
} }
/* Conversation open (messages or voice call): the bluish glow disappears completely. */
.home-page.has-conversation::before { .home-page.has-conversation::before {
opacity: 0; opacity: 0;
} }
/* ---- Chat column (Claude: one continuous column) ---- */ /* ---------- Logo (landing only) ---------- */
.chat-column { .home-header {
position: relative; position: absolute;
top: 2rem;
left: 50%;
transform: translateX(-50%);
z-index: 1; z-index: 1;
display: flex;
flex-direction: column;
width: 100%;
max-width: 800px;
/* Auto height + viewport floor: grows only if the empty group cannot fit (then the
shell scrolls) instead of clipping. */
height: auto;
min-height: 100dvh;
box-sizing: border-box;
}
/* Conversation: the column is exactly one viewport tall so the composer stays pinned
and only the transcript area scrolls. `overflow` keeps any stray child box from
propagating phantom height to the page. */
.home-page.has-conversation .chat-column {
height: 100dvh;
overflow: hidden;
}
/* Empty state: the column stops stretching, so the empty content and the composer are
centered together in the viewport instead of the composer being pinned to the bottom. */
.home-page:not(.has-conversation) .chat-column {
justify-content: center;
}
.home-page:not(.has-conversation) .transcript-list {
flex: 0 0 auto;
overflow: visible;
}
.home-page:not(.has-conversation) .empty-state {
flex: 0 0 auto;
}
/* ---- Transcript list (scrollable body) ---- */
.transcript-list {
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
overflow-x: hidden;
/* Hide the scrollbar, keep wheel / trackpad / touch scrolling */
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* legacy Edge */
scroll-behavior: smooth;
display: flex;
flex-direction: column;
/* Space so last message clears the composer */
padding: 1.25rem 1rem 0.5rem;
box-sizing: border-box;
}
.transcript-list::-webkit-scrollbar {
display: none; /* Chrome, Safari, Edge */
width: 0;
height: 0;
}
/* Empty state centered in the transcript area */
.empty-state {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center; text-align: center;
padding: 2rem 1rem; opacity: 1;
min-height: 0; transition: opacity 0.35s ease, transform 0.35s ease;
}
.home-page.has-conversation .home-header {
opacity: 0;
transform: translateX(-50%) translateY(-8px);
pointer-events: none;
} }
.home-icon-wrapper { .home-icon-wrapper {
@@ -141,9 +76,44 @@
display: block; display: block;
} }
/* ---------- chat column ---------- */
.chat-column {
position: relative;
z-index: 1;
flex: 1 1 auto;
min-height: 0;
width: 100%;
display: flex;
flex-direction: column;
justify-content: center; /* landing: greeting + composer centered together */
}
.home-page.has-conversation .chat-column {
justify-content: flex-start;
}
/* ---------- greeting (typed title) ---------- */
.home-greeting {
flex: none;
box-sizing: border-box;
max-height: 8rem;
padding: 0 1rem;
overflow: hidden;
opacity: 1;
transition:
max-height 0.5s cubic-bezier(0.22, 1, 0.36, 1),
opacity 0.3s ease;
}
.home-page.has-conversation .home-greeting {
max-height: 0;
opacity: 0;
pointer-events: none;
}
.home-title { .home-title {
width: 100%; width: 100%;
margin: 0; margin: 0 0 1rem;
display: flex; display: flex;
align-items: center; align-items: center;
@@ -182,56 +152,144 @@
45% { 45% {
opacity: 1; opacity: 1;
} }
46%, 46%,
100% { 100% {
opacity: 0; opacity: 0;
} }
} }
/* Voice panel becomes the transcript body — no extra card chrome */ /* ---------- transcript list (the page's only scroller) ---------- */
.chat-transcript-body { .transcript-list {
display: block; flex: 0 1 auto;
flex: 1 1 auto;
min-height: 0; min-height: 0;
width: 100%; overflow-x: hidden;
overflow-y: auto;
overscroll-behavior: contain;
transition: flex-grow 0.5s cubic-bezier(0.22, 1, 0.36, 1);
} }
/* ---- Composer (pinned bottom of the chat column) ---- */ .home-page.has-conversation .transcript-list {
.composer { flex-grow: 1;
flex-shrink: 0; }
width: 100%;
padding: 0.75rem 1rem 1.25rem; .transcript-list::-webkit-scrollbar {
width: 6px;
}
.transcript-list::-webkit-scrollbar-thumb {
background: var(--muted);
border-radius: 9999px;
}
/* Same width as the composer so text and input line up */
.transcript-inner {
box-sizing: border-box; box-sizing: border-box;
background: transparent; display: flex;
/* Subtle top fade so messages don't collide with the input */ flex-direction: column;
position: relative; width: 100%;
max-width: 800px;
min-height: 100%;
margin: 0 auto;
padding: 0 1rem;
} }
.home-page.has-conversation .transcript-inner {
padding: 1.5rem 1rem 1rem;
}
.transcript-empty {
margin: auto;
font-size: 0.875rem;
color: var(--muted);
text-align: center;
}
/* ---------- composer (call bar + chat input) ---------- */
.composer {
position: relative;
z-index: 2;
flex: none;
box-sizing: border-box;
padding: 0 1rem 1rem;
}
.home-page.has-conversation .composer {
padding-bottom: calc(1rem + env(safe-area-inset-bottom, 0px));
}
/* Transcript text fades out under the composer instead of being cut off */
.composer::before { .composer::before {
content: ''; content: '';
position: absolute; position: absolute;
left: 0; inset-inline: 0;
right: 0;
bottom: 100%; bottom: 100%;
height: 1.5rem; height: 1.5rem;
pointer-events: none;
background: linear-gradient(to top, var(--app-bg), transparent); background: linear-gradient(to top, var(--app-bg), transparent);
pointer-events: none;
opacity: 0; opacity: 0;
transition: opacity 0.25s ease; transition: opacity 0.3s ease;
} }
.home-page.has-conversation .composer::before { .home-page.has-conversation .composer::before {
opacity: 1; opacity: 1;
} }
/* ---- Responsive ---- */ .composer > :not(.jump-to-latest) {
@media (max-width: 640px) { max-width: 800px;
.transcript-list { margin-inline: auto;
padding: 1rem 0.75rem 0.5rem; }
}
.composer { .home-call-dock {
padding: 0.5rem 0.75rem 1rem; margin-bottom: 0.5rem;
}
/* ---------- jump to latest ---------- */
.jump-to-latest {
position: absolute;
bottom: calc(100% + 0.5rem);
left: 50%;
transform: translateX(-50%);
display: inline-flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
border: 1px solid var(--surface-border);
border-radius: 50%;
background: var(--surface-bg);
color: var(--text-secondary);
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.12);
cursor: pointer;
animation: jumpIn 0.2s ease;
transition: background 0.2s ease, color 0.2s ease;
}
.jump-to-latest:hover {
background: var(--sidebar-hover);
color: var(--text-primary);
}
.jump-to-latest:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
@keyframes jumpIn {
from {
opacity: 0;
transform: translateX(-50%) translateY(6px);
}
to {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
}
/* ---------- responsive ---------- */
@media (max-width: 640px) {
.home-header {
top: 1.25rem;
} }
.home-icon-wrapper { .home-icon-wrapper {
@@ -243,15 +301,33 @@
.home-title { .home-title {
font-size: 1.375rem; font-size: 1.375rem;
} }
.composer {
padding: 0 0.75rem 0.75rem;
}
.home-page.has-conversation .composer {
padding-bottom: calc(0.75rem + env(safe-area-inset-bottom, 0px));
}
.transcript-inner {
padding-inline: 0.75rem;
}
.home-page.has-conversation .transcript-inner {
padding: 1rem 0.75rem 0.75rem;
}
} }
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
.home-page, .home-page,
.home-page::before, .home-page::before,
.home-header,
.home-greeting,
.transcript-list, .transcript-list,
.composer::before { .composer::before,
.jump-to-latest {
transition: none !important; transition: none !important;
animation: none !important; animation: none !important;
scroll-behavior: auto !important;
} }
} }
+48 -33
View File
@@ -1,52 +1,67 @@
<div <div class="home-page" [class.has-conversation]="hasConversation()">
class="home-page"
[class.has-conversation]="hasConversation()" <!-- Brand logo: shown only on the empty landing state -->
> <div class="home-header" aria-hidden="true">
<!-- Claude-style chat column: transcript list + composer in one continuous column --> <div class="home-icon-wrapper">
<div class="chat-column" role="main"> <img class="home-logo" [src]="logoSrc()" alt="Raymand" />
<!-- Transcript list (scrollable). Empty state or live/ended voice transcript. --> </div>
</div>
<!-- chat column: transcript list on top, composer docked at the bottom -->
<div class="chat-column">
<div class="home-greeting" [attr.aria-hidden]="hasConversation() ? 'true' : null">
<h1 class="home-title">
<span class="home-title-text">{{ streamedText() }}</span>
<span class="cursor" [class.cursor-hidden]="!isStreaming()" aria-hidden="true"></span>
</h1>
</div>
<!-- transcript list: the only scrolling region of the page -->
<div <div
class="transcript-list" class="transcript-list"
#transcriptScroller #transcriptList
role="log" role="log"
aria-label="متن گفتگو" aria-label="متن گفتگو"
aria-live="polite" aria-live="polite"
aria-relevant="additions" aria-relevant="additions"
(scroll)="onTranscriptScroll()"
> >
@if (!hasConversation()) { <div class="transcript-inner">
<!-- Empty state: logo + typing title (Claude empty chat feel) --> @if (callOpen() && voiceMessages().length === 0) {
<div class="empty-state"> <p class="transcript-empty">صحبت کنید؛ گفتگو اینجا نمایش داده می‌شود</p>
<div class="home-icon-wrapper"> }
<img <app-voice-transcript [messages]="voiceMessages()" />
class="home-logo" </div>
[src]="logoSrc()"
alt="Raymand"
/>
</div>
<h1 class="home-title">
<span class="home-title-text">{{ streamedText() }}</span>
<span
class="cursor"
[class.cursor-hidden]="!isStreaming()"
aria-hidden="true"
></span>
</h1>
</div>
} @else if (voiceHasTranscript()) {
<!-- Voice stream fills the transcript list (no separate card chrome) -->
<app-voice-stream-panel class="chat-transcript-body" />
}
</div> </div>
<!-- Composer: always at the bottom of the same column (Claude pattern) --> <!-- composer: call bar (while a call runs) + the chat input -->
<div class="composer"> <div class="composer">
@if (jumpVisible()) {
<button
type="button"
class="jump-to-latest"
aria-label="رفتن به آخرین پیام"
(click)="scrollToLatest()"
>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M12 5v14M5 12l7 7 7-7" />
</svg>
</button>
}
@if (callDockMounted()) {
<app-voice-stream-panel class="home-call-dock" />
}
<app-ai-chat-input <app-ai-chat-input
data-chat-input
placeholder="پیام خود را بنویسید..." placeholder="پیام خود را بنویسید..."
[hasMessages]="hasConversation()"
(messageSent)="onMessageSent($event)" (messageSent)="onMessageSent($event)"
(fileSelected)="onFileSelected($event)" (fileSelected)="onFileSelected($event)"
(voiceToggled)="onVoiceToggled($event)" (voiceToggled)="onVoiceToggled($event)"
/> />
</div> </div>
</div> </div>
</div> </div>
+100 -21
View File
@@ -1,20 +1,24 @@
import { import {
ChangeDetectionStrategy, ChangeDetectionStrategy,
Component, Component,
ElementRef,
OnDestroy,
OnInit,
computed,
effect,
inject, inject,
signal, signal,
computed, viewChild,
OnInit,
OnDestroy,
} from '@angular/core'; } from '@angular/core';
import { CommonModule } from '@angular/common'; import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';
import { AiChatInputComponent } from '../../shared/ui/ai-chat-input/ai-chat-input.component';
import { VoiceStreamPanelComponent } from '../../shared/ui/voice-stream-panel/voice-stream-panel.component';
import { VoiceStreamService } from '../../services/voice-stream/voice-stream.service';
import { Router, NavigationEnd } from '@angular/router'; import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators'; import { filter } from 'rxjs/operators';
import { ThemeService } from '../../services/theme/theme.service';
import { Subscription } from 'rxjs'; import { Subscription } from 'rxjs';
import { AiChatInputComponent } from '../../shared/ui/ai-chat-input/ai-chat-input.component';
import { VoiceStreamPanelComponent } from '../../shared/ui/voice-stream-panel/voice-stream-panel.component';
import { VoiceTranscriptComponent } from '../../shared/ui/voice-transcript/voice-transcript.component';
import { VoiceStreamService } from '../../services/voice-stream/voice-stream.service';
import { ThemeService } from '../../services/theme/theme.service';
const HOME_TITLES = [ const HOME_TITLES = [
'چه چیزی می‌خواهید بدانید؟', 'چه چیزی می‌خواهید بدانید؟',
@@ -24,15 +28,20 @@ const HOME_TITLES = [
'سوالتان را مطرح کنید، پاسخ می‌دهم...', 'سوالتان را مطرح کنید، پاسخ می‌دهم...',
'بپرسید؛ با هم به پاسخ می‌رسیم...', 'بپرسید؛ با هم به پاسخ می‌رسیم...',
'هر سوالی در ذهن دارید، بپرسید...', 'هر سوالی در ذهن دارید، بپرسید...',
'دنبال یک پاسخ دقیق هستید؟...', 'دنبال یک پاسخ دقیق هستید؟',
'سوالتان را همین‌جا مطرح کنید...', 'سوالتان را همین‌جا مطرح کنید...',
'آماده‌ام به سوالتان پاسخ بدهم...', 'آماده‌ام به سوالتان پاسخ بدهم...',
]; ];
/** Keeps the call bar mounted this long after the call ends so it can fade/collapse out (matches the CSS). */
const CALL_DOCK_EXIT_MS = 400;
/** Within this distance of the bottom the list keeps following new text. */
const STICK_TO_BOTTOM_PX = 80;
@Component({ @Component({
selector: 'app-home', selector: 'app-home',
standalone: true, standalone: true,
imports: [CommonModule, AiChatInputComponent, VoiceStreamPanelComponent], imports: [AiChatInputComponent, VoiceStreamPanelComponent, VoiceTranscriptComponent],
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './home.page.html', templateUrl: './home.page.html',
styleUrl: './home.page.css', styleUrl: './home.page.css',
@@ -47,26 +56,29 @@ export class HomePage implements OnInit, OnDestroy {
readonly logoSrc = () => readonly logoSrc = () =>
this.isDarkMode() ? 'assets/images/RaymandLogo.png' : 'assets/images/login.png'; this.isDarkMode() ? 'assets/images/RaymandLogo.png' : 'assets/images/login.png';
// ---- conversation state ---------------------------------------------------
readonly hasMessages = signal(false); readonly hasMessages = signal(false);
readonly callOpen = this.voiceStream.isOpen;
readonly voiceMessages = this.voiceStream.messages;
/** /** Anything on screen that belongs in the chat column: text sent, a live call, or a finished call's transcript. */
* Conversation owns the layout when there is a live voice call, readonly hasConversation = computed(
* leftover voice transcript, or text messages — same idea as Claude's () => this.hasMessages() || this.callOpen() || this.voiceMessages().length > 0,
* chat column switching from empty state to transcript list.
*/
readonly voiceHasTranscript = computed(
() => this.voiceStream.isOpen() || this.voiceStream.messages().length > 0,
); );
readonly hasConversation = computed(() => this.hasMessages() || this.voiceHasTranscript()); /** The call bar stays mounted briefly after the call ends so it can animate out. */
readonly callDockMounted = signal(false);
/** @deprecated use hasConversation — kept for any external bindings */ readonly jumpVisible = signal(false);
readonly voicePanelVisible = this.hasConversation;
// ---- title typing ---------------------------------------------------------
readonly homeTitle = signal(''); readonly homeTitle = signal('');
readonly streamedText = signal(''); readonly streamedText = signal('');
readonly isStreaming = signal(false); readonly isStreaming = signal(false);
private readonly listRef = viewChild<ElementRef<HTMLElement>>('transcriptList');
private stickToBottom = true;
private scrollFrame: number | null = null;
private dockTimer: ReturnType<typeof setTimeout> | null = null;
private typingTimer: ReturnType<typeof setTimeout> | null = null; private typingTimer: ReturnType<typeof setTimeout> | null = null;
private routerSubscription?: Subscription; private routerSubscription?: Subscription;
@@ -79,6 +91,28 @@ export class HomePage implements OnInit, OnDestroy {
this.setRandomTitle(); this.setRandomTitle();
} }
}); });
// Mount the call bar when a call starts; unmount it after the exit animation.
toObservable(this.callOpen)
.pipe(takeUntilDestroyed())
.subscribe((open) => {
this.clearDockTimer();
if (open) {
this.callDockMounted.set(true);
} else if (this.callDockMounted()) {
this.dockTimer = setTimeout(() => {
this.dockTimer = null;
this.callDockMounted.set(false);
}, CALL_DOCK_EXIT_MS);
}
});
// Follow new transcript text, unless the user scrolled up to read.
effect(() => {
this.voiceMessages();
this.callOpen();
if (this.stickToBottom) this.scheduleScrollToBottom();
});
} }
ngOnInit(): void { ngOnInit(): void {
@@ -87,9 +121,48 @@ export class HomePage implements OnInit, OnDestroy {
ngOnDestroy(): void { ngOnDestroy(): void {
this.stopTyping(); this.stopTyping();
this.clearDockTimer();
if (this.scrollFrame !== null) cancelAnimationFrame(this.scrollFrame);
this.routerSubscription?.unsubscribe(); this.routerSubscription?.unsubscribe();
} }
// ---- transcript list scrolling -------------------------------------------
onTranscriptScroll(): void {
const el = this.listRef()?.nativeElement;
if (!el) return;
const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
this.stickToBottom = distance < STICK_TO_BOTTOM_PX;
this.jumpVisible.set(!this.stickToBottom && this.hasConversation());
}
scrollToLatest(): void {
this.stickToBottom = true;
this.jumpVisible.set(false);
this.listRef()?.nativeElement.scrollTo({
top: this.listRef()!.nativeElement.scrollHeight,
behavior: 'smooth',
});
}
private scheduleScrollToBottom(): void {
if (this.scrollFrame !== null) return;
this.scrollFrame = requestAnimationFrame(() => {
this.scrollFrame = null;
const el = this.listRef()?.nativeElement;
if (el) el.scrollTo({ top: el.scrollHeight, behavior: 'instant' });
});
}
private clearDockTimer(): void {
if (this.dockTimer !== null) {
clearTimeout(this.dockTimer);
this.dockTimer = null;
}
}
// ---- title typing (unchanged) ---------------------------------------------
private setRandomTitle(): void { private setRandomTitle(): void {
this.stopTyping(); this.stopTyping();
@@ -115,9 +188,12 @@ export class HomePage implements OnInit, OnDestroy {
} }
index++; index++;
this.streamedText.set(text.substring(0, index)); this.streamedText.set(text.substring(0, index));
// Slightly random timing makes it feel more natural
const delay = 16 + Math.random() * 8; const delay = 16 + Math.random() * 8;
this.typingTimer = setTimeout(typeNextCharacter, delay); this.typingTimer = setTimeout(typeNextCharacter, delay);
}; };
@@ -129,9 +205,12 @@ export class HomePage implements OnInit, OnDestroy {
clearTimeout(this.typingTimer); clearTimeout(this.typingTimer);
this.typingTimer = null; this.typingTimer = null;
} }
this.isStreaming.set(false); this.isStreaming.set(false);
} }
// ---- composer events ------------------------------------------------------
onMessageSent(message: string): void { onMessageSent(message: string): void {
this.hasMessages.set(true); this.hasMessages.set(true);
console.log('Message sent:', message); console.log('Message sent:', message);
+51 -19
View File
@@ -435,7 +435,7 @@
</div> </div>
} }
@if (documents().length > 0) { @if (documents().length > 0 || hasActiveFilters()) {
<div class="documents-filters mb-3 flex items-center justify-between gap-2"> <div class="documents-filters mb-3 flex items-center justify-between gap-2">
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<select <select
@@ -456,22 +456,43 @@
</label> </label>
<span class="text-xs text-[var(--text-muted)]">فقط فعال</span> <span class="text-xs text-[var(--text-muted)]">فقط فعال</span>
</div> </div>
<button type="button" class="btn btn--outline" (click)="refreshDocuments()" [disabled]="documentsLoading()"> <button
<svg type="button"
class="w-4 h-4" class="btn btn--outline"
viewBox="0 0 24 24" (click)="refreshDocuments()"
fill="none" [disabled]="documentsLoading()"
stroke="currentColor" [attr.aria-busy]="documentsLoading()"
stroke-width="2" >
stroke-linecap="round" @if (documentsLoading()) {
stroke-linejoin="round" <svg
> class="w-4 h-4 animate-spin"
<path d="M20 7v5h-5" /> viewBox="0 0 24 24"
<path d="M4 17v-5h5" /> fill="none"
<path d="M5.6 9a7 7 0 0 1 11.55-2.6L20 12" /> stroke="currentColor"
<path d="M4 12l2.85 5.6A7 7 0 0 0 18.4 15" /> stroke-width="2"
</svg> stroke-linecap="round"
<span>به‌روزرسانی</span> aria-hidden="true"
>
<circle cx="12" cy="12" r="9" stroke-opacity="0.2" />
<path d="M21 12a9 9 0 0 0-9-9" />
</svg>
} @else {
<svg
class="w-4 h-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M20 7v5h-5" />
<path d="M4 17v-5h5" />
<path d="M5.6 9a7 7 0 0 1 11.55-2.6L20 12" />
<path d="M4 12l2.85 5.6A7 7 0 0 0 18.4 15" />
</svg>
}
<span>{{ documentsLoading() ? 'در حال به‌روزرسانی…' : 'به‌روزرسانی' }}</span>
</button> </button>
</div> </div>
@@ -614,18 +635,29 @@
</div> </div>
</td> </td>
</tr> </tr>
} @empty {
@if (!documentsLoading()) {
<tr>
<td
colspan="7"
class="px-3 py-10 text-center text-sm text-[var(--text-muted)]"
>
هیچ سندی با فیلتر انتخاب‌شده مطابقت ندارد.
</td>
</tr>
}
} }
</tbody> </tbody>
</table> </table>
</div> </div>
@if (!hasMoreDocuments() && !documentsLoading()) { @if (documents().length > 0 && !hasMoreDocuments() && !documentsLoading()) {
<p class="text-xs text-[var(--text-muted)] text-center mt-3"> <p class="text-xs text-[var(--text-muted)] text-center mt-3">
{{ documents().length }} سند ثبت شده {{ documents().length }} سند ثبت شده
</p> </p>
} }
@if (hasMoreDocuments() && !documentsLoading()) { @if (documents().length > 0 && hasMoreDocuments() && !documentsLoading()) {
<div class="documents-pagination mt-3 text-center"> <div class="documents-pagination mt-3 text-center">
<button type="button" class="btn btn--outline" (click)="loadMoreDocuments()"> <button type="button" class="btn btn--outline" (click)="loadMoreDocuments()">
بیشتر بارگذاری بیشتر بارگذاری
@@ -0,0 +1,158 @@
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { of, Subject, type Observable } from 'rxjs';
import { vi } from 'vitest';
import { SettingsPage } from './settings.page';
import { DocumentsService } from '../../services/documents/documents.service';
import {
DocumentListItem,
DocumentListResponse,
} from '../../services/documents/documents.types';
import { AuthService } from '../../services/auth/auth.service';
import { HttpService } from '../../services/http-request/http.service';
import { ThemeService } from '../../services/theme/theme.service';
import { ToastrService } from 'ngx-toastr';
function readyDoc(): DocumentListItem {
return {
id: 'doc-1',
title: 'سند آزمون',
filename: 'guide.pdf',
status: 'ready',
is_active: true,
searchable: true,
chunk_count: 12,
created_at: '2024-01-01T10:00:00Z',
job: { id: 'job-1', status: 'ready', stage: null, attempt_count: 0, retry_generation: 0, can_retry: false, error: null },
review_required: false,
};
}
const filterSelect = (el: HTMLElement): HTMLSelectElement | null => el.querySelector('.documents-filters select');
describe('SettingsPage — document filters', () => {
let getDocuments: ReturnType<typeof vi.fn>;
beforeEach(async () => {
// Server-side filtering: `all` returns one ready doc; every other status matches none.
getDocuments = vi.fn((params: { status?: string } = {}): Observable<DocumentListResponse> => {
const items = params.status ? [] : [readyDoc()];
return of({ items, next_cursor: null, knowledge_revision: 0 });
});
await TestBed.configureTestingModule({
imports: [SettingsPage],
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
{
provide: DocumentsService,
useValue: {
getConfiguration: () => of({}),
getDocuments,
getKnowledgeSelection: () => of({ revision: 0, document_ids: ['doc-1'] }),
},
},
{ provide: AuthService, useValue: { getCurrentUserValue: () => ({ role: 'admin' }) } },
{ provide: HttpService, useValue: { apiUrl: '/api/v1' } },
{ provide: ThemeService, useValue: { isDarkMode: () => false, toggleDarkMode: () => {} } },
{ provide: ToastrService, useValue: { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() } },
],
}).compileComponents();
});
it('renders the filter select and one document row initially', () => {
const fixture = TestBed.createComponent(SettingsPage);
fixture.detectChanges(); // ngOnInit → load all documents
expect(filterSelect(fixture.nativeElement as HTMLElement)).not.toBeNull();
expect((fixture.nativeElement as HTMLElement).querySelectorAll('.documents-table tbody tr').length).toBe(1);
});
it('keeps the filter select and table shell when a filter matches no rows', () => {
const fixture = TestBed.createComponent(SettingsPage);
fixture.detectChanges();
const el = fixture.nativeElement as HTMLElement;
// Select a status that has zero documents.
const component = fixture.componentInstance;
component.activeFilter.set('failed');
component.applyDocumentFilters();
fixture.detectChanges();
// Regression: the whole panel used to vanish; the select + table must stay so the user
// can change the filter back, and an in-table "no match" message is shown instead.
expect(filterSelect(el)).not.toBeNull();
expect(el.querySelector('.documents-table tbody tr')).not.toBeNull();
expect(el.textContent).toContain('هیچ سندی با فیلتر انتخاب‌شده مطابقت ندارد.');
expect(el.textContent).not.toContain('هنوز سندی آپلود نشده است.');
// The "N سند ثبت شده" footer must not claim 0 documents.
expect(el.textContent).not.toContain('سند ثبت شده');
});
it('restores the rows when the filter is reset back to all', () => {
const fixture = TestBed.createComponent(SettingsPage);
fixture.detectChanges();
const component = fixture.componentInstance;
component.activeFilter.set('processing'); // empty
component.applyDocumentFilters();
fixture.detectChanges();
expect((fixture.nativeElement as HTMLElement).querySelectorAll('.documents-table tbody tr').length).toBe(1); // just the empty row
component.activeFilter.set('all'); // back to everything
component.applyDocumentFilters();
fixture.detectChanges();
const rows = (fixture.nativeElement as HTMLElement).querySelectorAll('.documents-table tbody tr');
expect(rows.length).toBe(1);
expect(rows[0].textContent).toContain('guide.pdf');
});
it('hasActiveFilters reflects the active status/active-only filters', () => {
const component = TestBed.createComponent(SettingsPage).componentInstance;
expect(component.hasActiveFilters()).toBe(false);
component.activeFilter.set('failed');
expect(component.hasActiveFilters()).toBe(true);
component.activeFilter.set('all');
component.activeOnly.set(true);
expect(component.hasActiveFilters()).toBe(true);
});
it('shows a loading spinner on the به‌روزرسانی button while documents are being fetched', () => {
// The initial load resolves immediately; the refresh load stays pending so we can observe
// the in-flight state (previously the button only disabled with no visible feedback).
let call = 0;
let pending!: Subject<DocumentListResponse>;
getDocuments.mockReset();
getDocuments.mockImplementation((): Observable<DocumentListResponse> => {
call += 1;
if (call === 1) return of({ items: [readyDoc()], next_cursor: null, knowledge_revision: 0 });
pending = new Subject<DocumentListResponse>();
return pending;
});
const fixture = TestBed.createComponent(SettingsPage);
fixture.detectChanges(); // initial load
const el = fixture.nativeElement as HTMLElement;
const refresh = el.querySelector('.documents-filters button') as HTMLButtonElement;
expect(refresh.textContent).toContain('به‌روزرسانی');
expect(refresh.querySelector('.animate-spin')).toBeNull();
refresh.click(); // start refresh → stays pending
fixture.detectChanges();
expect(refresh.disabled).toBe(true);
expect(refresh.getAttribute('aria-busy')).toBe('true');
expect(refresh.textContent).toContain('در حال به‌روزرسانی');
expect(refresh.querySelector('.animate-spin')).not.toBeNull();
pending.next({ items: [readyDoc()], next_cursor: null, knowledge_revision: 0 });
fixture.detectChanges();
expect(refresh.disabled).toBe(false);
expect(refresh.textContent).toContain('به‌روزرسانی');
expect(refresh.querySelector('.animate-spin')).toBeNull();
});
});
+7
View File
@@ -203,6 +203,13 @@ export class SettingsPage implements OnInit, OnDestroy {
readonly activeFilter = signal<DocumentStatus | 'all'>('all'); readonly activeFilter = signal<DocumentStatus | 'all'>('all');
readonly activeOnly = signal<boolean>(false); readonly activeOnly = signal<boolean>(false);
/**
* True when a document filter (status other than "all", or active-only) is applied. Keeps
* the filter controls + table shell visible even when the filter matches zero rows, so the
* user can change/reset the filter instead of the whole panel vanishing.
*/
readonly hasActiveFilters = computed(() => this.activeFilter() !== 'all' || this.activeOnly());
readonly hasActiveDocuments = computed(() => this.documents().some((d) => d.is_active)); readonly hasActiveDocuments = computed(() => this.documents().some((d) => d.is_active));
readonly currentUserRole = computed<'admin' | 'user' | null>(() => { readonly currentUserRole = computed<'admin' | 'user' | null>(() => {
@@ -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 * Loads the REAL public/assets/worklets/pcm-playback.worklet.js in a stubbed AudioWorklet
@@ -15,7 +15,7 @@ interface Proc {
capacity: number; capacity: number;
queuedSource: number; queuedSource: number;
sourceCapacity: number; sourceCapacity: number;
refPlayedSamples: Map<string, number>; refPlayedOut: Map<string, number>;
process: (inputs: unknown[][][], outputs: Float32Array[][]) => boolean; process: (inputs: unknown[][][], outputs: Float32Array[][]) => boolean;
} }
@@ -68,6 +68,10 @@ function clear(proc: Proc): void {
proc.port.onmessage({ data: { type: 'clear' } }); 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. */ /** One render quantum: emit `samples` output slots and let process() consume/emit. */
function render(proc: Proc, samples = 128): void { function render(proc: Proc, samples = 128): void {
proc.process([[]], [[new Float32Array(samples)]]); 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', () => { describe('progress is accurate, monotonic and per audio_ref', () => {
it('credits each queued ref its own consumed source (never the next ref)', async () => { 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 const proc = await loadPlaybackProcessor(24000); // ratio 1 → 3,000 source ≈ 125 ms
@@ -188,10 +274,10 @@ describe('pcm-playback.worklet', () => {
drain(proc); 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. // 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.refPlayedOut.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-b') ?? 0) - 3000)).toBeLessThanOrEqual(1);
const finalA = playedFor(proc, 'aud-a'); const finalA = playedFor(proc, 'aud-a');
const finalB = playedFor(proc, 'aud-b'); const finalB = playedFor(proc, 'aud-b');
expect(finalA).toBeGreaterThanOrEqual(124); 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. // 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'); const finals = proc.out.filter((m) => m.type === 'progress' && m.audioRef === 'aud-a');
expect(finals.at(-1)?.playedMs).toBe(5); 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. // A fresh ref plays normally after the interruption.
push(proc, frame(0, 3000), 'aud-b'); push(proc, frame(0, 3000), 'aud-b');
@@ -65,6 +65,8 @@ describe('VoiceStreamService (backend handoff contract)', () => {
let controls: PlaybackProgressMessage[]; let controls: PlaybackProgressMessage[];
let transportMock: TransportMock; let transportMock: TransportMock;
let engineStop: ReturnType<typeof vi.fn>; let engineStop: ReturnType<typeof vi.fn>;
let engineFlush: Mock;
let engineClear: Mock;
beforeEach(() => { beforeEach(() => {
sessionStorage.clear(); sessionStorage.clear();
@@ -72,6 +74,8 @@ describe('VoiceStreamService (backend handoff contract)', () => {
transportHandlers = null; transportHandlers = null;
controls = []; controls = [];
engineStop = vi.fn(); engineStop = vi.fn();
engineFlush = vi.fn();
engineClear = vi.fn();
api = { api = {
me: vi.fn().mockResolvedValue(ME), me: vi.fn().mockResolvedValue(ME),
@@ -113,8 +117,8 @@ describe('VoiceStreamService (backend handoff contract)', () => {
stop: engineStop, stop: engineStop,
setMuted: vi.fn(), setMuted: vi.fn(),
enqueuePlayback: vi.fn(), enqueuePlayback: vi.fn(),
clearPlayback: vi.fn(), clearPlayback: engineClear,
flushPlayback: vi.fn(), flushPlayback: engineFlush,
inputLevel: () => 0, inputLevel: () => 0,
outputLevel: () => 0, outputLevel: () => 0,
}, },
@@ -310,6 +314,38 @@ describe('VoiceStreamService (backend handoff contract)', () => {
expect(api.closeVoiceSession).toHaveBeenCalledTimes(1); 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 () => { it('requires a fresh conversation after CONTEXT_REVOKED and drops the old attempt', async () => {
await startConnected(); await startConnected();
const ended = firstEndedError(); const ended = firstEndedError();
@@ -371,6 +407,51 @@ describe('VoiceStreamService (backend handoff contract)', () => {
expect(assistant?.final).toBe(true); 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 () => { it('closes the reservation (V04) when the call ends on user request', async () => {
await startConnected(); await startConnected();
await service.close(); await service.close();
@@ -137,6 +137,7 @@ export class VoiceStreamService {
private session = 0; private session = 0;
private streaming = false; private streaming = false;
private turnEnded = false; private turnEnded = false;
private audioGenerationDone = false; // server finished sending this audio_ref's frames
private interruptTimer: ReturnType<typeof setTimeout> | null = null; private interruptTimer: ReturnType<typeof setTimeout> | null = null;
private settleTimer: ReturnType<typeof setTimeout> | null = null; private settleTimer: ReturnType<typeof setTimeout> | null = null;
private errorTimer: ReturnType<typeof setTimeout> | null = null; private errorTimer: ReturnType<typeof setTimeout> | null = null;
@@ -490,11 +491,16 @@ export class VoiceStreamService {
case 'audio_started': case 'audio_started':
this.currentAudioRef = event.audio_ref; this.currentAudioRef = event.audio_ref;
this.audioGenerationDone = false; // frames for this ref are now streaming in
break; break;
case 'audio_ended': case 'audio_ended':
// Generation ended; the ref's audio may still be playing — its final progress is // Generation finished: emit the worklet's deferred tail and drain what is buffered so
// reported when the queue drains or the turn is interrupted. // 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; break;
case 'turn_interrupted': case 'turn_interrupted':
@@ -524,9 +530,10 @@ export class VoiceStreamService {
} }
if (event.status === 'completed') { 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.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); const index = list.findIndex((m) => m.id === id);
if (index === -1) { if (index === -1) {
if (!event.text.trim()) return list; if (!event.text.trim()) return list;
return [ return this.insertTranscript(list, {
...list, id,
{ turnRef: event.turn_ref,
id, role: event.role,
turnRef: event.turn_ref, text: event.text,
role: event.role, final,
text: event.text, interrupted: interrupted || undefined,
final, });
interrupted: interrupted || undefined,
},
];
} }
const current = list[index]; const current = list[index];
@@ -679,13 +683,38 @@ export class VoiceStreamService {
} }
const next = { ...current, sources }; const next = { ...current, sources };
if (index === -1) return [...list, next]; if (index === -1) return this.insertTranscript(list, next);
const copy = [...list]; const copy = [...list];
copy[index] = next; copy[index] = next;
return copy; 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 { private markInterrupted(turnRef: string): void {
const id = `${turnRef}:assistant`; const id = `${turnRef}:assistant`;
this.messages.update((list) => { this.messages.update((list) => {
@@ -882,6 +911,7 @@ export class VoiceStreamService {
private resetTurnFlags(): void { private resetTurnFlags(): void {
this.turnEnded = false; this.turnEnded = false;
this.audioGenerationDone = false;
} }
private clearSettleTimer(): void { private clearSettleTimer(): void {
@@ -16,6 +16,12 @@
min-height: 460px; min-height: 460px;
} }
/* A live call replaces the composer: the call bar (rendered by the page) sits where the input was,
so the wrapper collapses instead of leaving an empty 72px box under it. */
.ai-chat-input-wrapper.stream-open {
min-height: 0;
}
/* Layers cross-fade */ /* Layers cross-fade */
.composer-layer, .composer-layer,
.voice-layer { .voice-layer {
@@ -57,14 +63,6 @@
transform: translateY(0) scale(1); transform: translateY(0) scale(1);
} }
:host-context(.has-messages) {
position: fixed;
bottom: 0;
left: 0;
right: 0;
z-index: 10;
}
/* ---------- Chat composer ---------- */ /* ---------- Chat composer ---------- */
.chat-composer { .chat-composer {
/* The composer lays itself out RTL explicitly: Plus on the right edge, Send on the left. /* The composer lays itself out RTL explicitly: Plus on the right edge, Send on the left.
@@ -128,7 +126,6 @@
} }
.composer-textarea::-webkit-scrollbar-thumb { .composer-textarea::-webkit-scrollbar-thumb {
background: var(--muted); background: var(--muted);
border: none;
border-radius: 9999px; border-radius: 9999px;
} }
@@ -2,6 +2,7 @@
class="ai-chat-input-wrapper" class="ai-chat-input-wrapper"
[class.voice-active]="anyVoiceActive()" [class.voice-active]="anyVoiceActive()"
[class.dictation-active]="isVoiceMode()" [class.dictation-active]="isVoiceMode()"
[class.stream-open]="streamOpen()"
[attr.data-voice-state]="voiceState()" [attr.data-voice-state]="voiceState()"
(keydown.escape)="onEscape()" (keydown.escape)="onEscape()"
> >
@@ -207,4 +208,4 @@
</div> </div>
} }
</div> </div>
</div> </div>
@@ -1,47 +1,52 @@
/* Host collapses its row to 0 when the call ends, so the composer never jumps when the bar is removed. */
:host { :host {
display: block; display: grid;
min-height: 0; grid-template-rows: 1fr;
height: 100%; opacity: 1;
animation: dockIn 0.35s cubic-bezier(0.22, 1, 0.36, 1);
transition:
grid-template-rows 0.35s cubic-bezier(0.22, 1, 0.36, 1),
opacity 0.3s ease,
margin 0.35s ease;
} }
.stream-panel { :host(.is-ended) {
--footer-h: 3.5rem; grid-template-rows: 0fr;
--orb-zone: 7.25rem; opacity: 0;
--orb-gap: 0.75rem; margin-bottom: 0 !important;
--reserve: calc(var(--footer-h) + var(--orb-gap) + var(--orb-zone) + var(--orb-gap)); pointer-events: none;
}
position: relative; .call-dock {
display: flex; direction: rtl;
flex-direction: column;
box-sizing: border-box; box-sizing: border-box;
min-height: 0; min-height: 0;
height: 100%;
direction: rtl;
background: transparent; /* was surface card */
border: none; /* removed card border */
border-radius: 0;
box-shadow: none; /* removed card shadow */
overflow: hidden; overflow: hidden;
background: var(--surface-bg);
border: 1px solid var(--surface-border);
border-radius: 1.25rem;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.03);
} }
/* ---------- Orb layer (behind the transcript) ---------- */ :host(.is-ended) .call-dock {
.stream-orb-layer { border-color: transparent;
position: absolute; box-shadow: none;
bottom: calc(var(--footer-h) + var(--orb-gap)); }
left: 50%;
transform: translateX(-50%); .dock-row {
z-index: 1;
display: flex; display: flex;
flex-direction: column;
align-items: center; align-items: center;
gap: 0.5rem; gap: 0.75rem;
transition: opacity 0.45s ease, transform 0.45s ease; padding: 0.5rem 0.75rem;
} }
/* ---------- Orb ---------- */
/* The canvas is larger than the bar is tall (negative margin) so the orb and its glow are not tiny. */
.orb-container { .orb-container {
width: 88px; width: 96px;
height: 88px; height: 96px;
max-width: 100%; margin-block: -20px;
margin-inline: -14px;
flex-shrink: 0; flex-shrink: 0;
display: flex; display: flex;
align-items: center; align-items: center;
@@ -56,11 +61,11 @@
/* Shown only when WebGL is unavailable */ /* Shown only when WebGL is unavailable */
.orb-fallback { .orb-fallback {
width: 70%; width: 55%;
height: 70%; height: 55%;
border-radius: 50%; border-radius: 50%;
background: radial-gradient(circle at 35% 30%, #93c5fd, #3b82f6 55%, #1e3a5f); background: radial-gradient(circle at 35% 30%, #93c5fd, #3b82f6 55%, #1e3a5f);
box-shadow: 0 0 40px rgba(59, 130, 246, 0.35); box-shadow: 0 0 24px rgba(59, 130, 246, 0.35);
animation: fallbackPulse 2.4s ease-in-out infinite; animation: fallbackPulse 2.4s ease-in-out infinite;
} }
@@ -70,12 +75,14 @@
transform: scale(1); transform: scale(1);
} }
50% { 50% {
transform: scale(1.06); transform: scale(1.08);
} }
} }
/* ---------- Status ---------- */ /* ---------- Status ---------- */
.stream-status { .dock-info {
flex: 1;
min-width: 0;
display: flex; display: flex;
align-items: center; align-items: center;
gap: 0.5rem; gap: 0.5rem;
@@ -83,9 +90,12 @@
.status-text { .status-text {
margin: 0; margin: 0;
font-size: 0.8125rem; min-width: 0;
font-size: 0.875rem;
color: var(--text-secondary); color: var(--text-secondary);
text-align: center; white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
} }
.status-dot { .status-dot {
@@ -97,22 +107,22 @@
transition: background 0.3s ease; transition: background 0.3s ease;
} }
.stream-status[data-state='LISTENING'] .status-dot { .status-dot[data-state='LISTENING'] {
background: #22c55e; background: #22c55e;
animation: dotPulse 1.6s ease-in-out infinite; animation: dotPulse 1.6s ease-in-out infinite;
} }
.stream-status[data-state='PROCESSING'] .status-dot { .status-dot[data-state='PROCESSING'] {
background: #818cf8; background: #818cf8;
animation: dotPulse 0.9s ease-in-out infinite; animation: dotPulse 0.9s ease-in-out infinite;
} }
.stream-status[data-state='SPEAKING'] .status-dot { .status-dot[data-state='SPEAKING'] {
background: #a78bfa; background: #a78bfa;
animation: dotPulse 0.7s ease-in-out infinite; animation: dotPulse 0.7s ease-in-out infinite;
} }
.stream-status[data-state='INTERRUPTED'] .status-dot { .status-dot[data-state='INTERRUPTED'] {
background: #f59e0b; background: #f59e0b;
} }
@@ -128,56 +138,91 @@
} }
} }
/* ---------- Transcript (overlaid on top of the orb) ---------- */ /* ---------- Controls ---------- */
.stream-transcript { .dock-actions {
position: relative;
z-index: 2;
flex: 1;
min-height: 0;
width: 100%;
max-width: 680px;
margin: 0 auto;
overflow-y: auto;
/* Hide the scrollbar, keep wheel / trackpad / touch scrolling */
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* legacy Edge */
padding: 1rem 0.75rem var(--reserve);
scroll-behavior: smooth;
transition: padding-bottom 0.45s ease;
}
.stream-transcript::-webkit-scrollbar {
display: none; /* Chrome, Safari, Edge */
width: 0;
height: 0;
}
/* ---------- Retryable server error ---------- */
.stream-error {
position: absolute;
bottom: calc(var(--footer-h) + 0.5rem);
left: 50%;
transform: translateX(-50%);
z-index: 3;
display: flex; display: flex;
align-items: center; align-items: center;
gap: 0.5rem; gap: 0.5rem;
width: min(100% - 1.5rem, 640px); flex-shrink: 0;
box-sizing: border-box; }
padding: 0.5rem 0.75rem;
.dock-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.375rem;
height: 40px;
min-width: 40px;
padding: 0 0.75rem;
border: 1px solid var(--surface-border);
border-radius: 9999px;
background: var(--surface-bg);
color: var(--text-secondary);
font-family: inherit;
font-size: 0.875rem;
cursor: pointer;
transition: background 0.2s ease, color 0.2s ease, border-color 0.2s ease, transform 0.15s ease;
user-select: none;
}
.dock-btn:hover:not(:disabled) {
background: var(--sidebar-hover);
color: var(--text-primary);
transform: scale(1.04);
}
.dock-btn:active:not(:disabled) {
transform: scale(0.96);
}
.dock-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.dock-btn:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
.dock-btn.is-active {
background: rgba(239, 68, 68, 0.1);
border-color: rgba(239, 68, 68, 0.5);
color: #dc2626;
}
.dock-btn.is-end {
background: #ef4444;
border-color: #ef4444;
color: #ffffff;
}
.dock-btn.is-end:hover:not(:disabled) {
background: #dc2626;
border-color: #dc2626;
color: #ffffff;
}
/* ---------- Retryable server error (second row inside the bar) ---------- */
.dock-error {
display: flex;
align-items: center;
gap: 0.5rem;
margin: 0 0.75rem 0.5rem;
padding: 0.375rem 0.625rem;
border: 1px solid rgba(239, 68, 68, 0.45); border: 1px solid rgba(239, 68, 68, 0.45);
border-radius: 0.875rem; border-radius: 0.75rem;
color: #dc2626; color: #dc2626;
font-size: 0.8125rem; font-size: 0.8125rem;
line-height: 1.6; line-height: 1.6;
} }
.stream-error span { .dock-error span {
flex: 1; flex: 1;
min-width: 0; min-width: 0;
} }
.stream-error-close { .dock-error-close {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
@@ -191,112 +236,20 @@
flex-shrink: 0; flex-shrink: 0;
} }
.stream-error-close:focus-visible { .dock-error-close:focus-visible {
outline: 2px solid var(--color-primary); outline: 2px solid var(--color-primary);
outline-offset: 1px; outline-offset: 1px;
} }
/* ---------- Controls ---------- */ @keyframes dockIn {
.stream-footer { from {
position: absolute; opacity: 0;
bottom: 0; transform: translateY(10px);
left: 0; }
right: 0; to {
z-index: 3; opacity: 1;
display: flex; transform: translateY(0);
align-items: center; }
justify-content: center;
padding-bottom: 0.25rem;
transition: opacity 0.45s ease, transform 0.45s ease;
}
.stream-actions {
display: flex;
align-items: center;
justify-content: center;
gap: 0.625rem;
flex-wrap: wrap;
}
.stream-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
padding: 0.625rem 1.25rem;
border: 1px solid var(--surface-border);
border-radius: 9999px;
background: var(--surface-bg);
color: var(--text-secondary);
font-family: inherit;
font-size: 0.875rem;
cursor: pointer;
transition: background 0.2s ease, color 0.2s ease, border-color 0.2s ease, transform 0.15s ease;
user-select: none;
}
.stream-btn:hover:not(:disabled) {
background: var(--sidebar-hover);
color: var(--text-primary);
transform: scale(1.03);
}
.stream-btn:active:not(:disabled) {
transform: scale(0.97);
}
.stream-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.stream-btn:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
.stream-btn.is-active {
background: rgba(239, 68, 68, 0.1);
border-color: rgba(239, 68, 68, 0.5);
color: #dc2626;
}
.stream-btn.is-end {
background: #ef4444;
border-color: #ef4444;
color: #ffffff;
}
.stream-btn.is-end:hover:not(:disabled) {
background: #dc2626;
border-color: #dc2626;
color: #ffffff;
}
/* ---------- Ended: orb + controls fade out, transcript stays ---------- */
/* The orb + footer reserve only exists while the call is live; collapsing it stops the
bottom padding from forcing the panel (and the chat column) taller than the viewport. */
.stream-panel.is-ended {
--reserve: 0rem;
}
.stream-panel.is-ended .stream-orb-layer {
opacity: 0;
transform: translateX(-50%) translateY(14px) scale(0.9);
pointer-events: none;
}
.stream-panel.is-ended .stream-footer {
opacity: 0;
transform: translateY(10px);
pointer-events: none;
}
/* The transcript keeps the full height of the chat column: no max-height, so it never
collapses into a short nested scroll box — scrolling stays on the full-height area. */
.stream-panel.is-ended .stream-transcript {
padding: 1rem 0.75rem;
} }
.sr-only { .sr-only {
@@ -312,31 +265,34 @@
} }
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
:host,
.status-dot, .status-dot,
.orb-fallback, .orb-fallback,
.stream-btn, .dock-btn {
.stream-orb-layer,
.stream-footer,
.stream-transcript {
animation: none !important; animation: none !important;
transition: none !important; transition: none !important;
scroll-behavior: auto !important;
} }
} }
@media (max-width: 640px) { @media (max-width: 640px) {
.stream-panel { .dock-row {
--footer-h: 3.25rem; gap: 0.5rem;
--orb-zone: 6rem; padding: 0.375rem 0.625rem;
--orb-gap: 0.5rem;
} }
.orb-container { .orb-container {
width: 68px; width: 84px;
height: 68px; height: 84px;
margin-block: -16px;
margin-inline: -12px;
} }
.stream-btn { .dock-btn-label {
padding: 0.5rem 1rem; display: none;
} }
}
.dock-btn.is-end {
padding: 0;
width: 40px;
}
}
@@ -1,55 +1,27 @@
<div <div
class="stream-panel" class="call-dock"
role="region" role="region"
aria-label="گفتگوی صوتی" aria-label="گفتگوی صوتی"
[class.is-ended]="ended()"
[attr.data-state]="state()" [attr.data-state]="state()"
> >
<div class="sr-only" role="status" aria-live="polite">{{ statusText() }}</div> <div class="sr-only" role="status" aria-live="polite">{{ statusText() }}</div>
<!-- Orb layer: behind the transcript, anchored just above the controls --> <div class="dock-row">
<div class="stream-orb-layer" aria-hidden="true"> <div class="orb-container" #orbContainer aria-hidden="true">
<div class="orb-container" #orbContainer>
@if (!orbAvailable()) { @if (!orbAvailable()) {
<div class="orb-fallback"></div> <div class="orb-fallback"></div>
} }
</div> </div>
<div class="stream-status" [attr.data-state]="state()">
<span class="status-dot" aria-hidden="true"></span> <div class="dock-info" aria-hidden="true">
<p class="status-text">{{ statusText() }}</p> <span class="status-dot" [attr.data-state]="state()"></span>
<p class="status-text" [attr.title]="statusText()">{{ statusText() }}</p>
</div> </div>
</div>
<!-- Transcript: overlaid on top of the orb, keeps streaming while the call runs --> <div class="dock-actions">
<div
class="stream-transcript"
#scroller
role="log"
aria-label="متن گفتگو"
aria-live="polite"
aria-relevant="additions"
>
<app-voice-transcript [messages]="messages()" />
</div>
@if (streamError(); as errorText) {
<div class="stream-error" role="alert">
<span>{{ errorText }}</span>
<button type="button" class="stream-error-close" aria-label="بستن پیام" (click)="dismissError()">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<line x1="18" x2="6" y1="6" y2="18" />
<line x1="6" x2="18" y1="6" y2="18" />
</svg>
</button>
</div>
}
<!-- Controls: fade out together with the orb when the call ends -->
<div class="stream-footer">
<div class="stream-actions">
<button <button
type="button" type="button"
class="stream-btn" class="dock-btn"
[class.is-active]="muted()" [class.is-active]="muted()"
[attr.aria-pressed]="muted()" [attr.aria-pressed]="muted()"
[attr.aria-label]="muteLabel()" [attr.aria-label]="muteLabel()"
@@ -73,16 +45,27 @@
<line x1="12" x2="12" y1="19" y2="22" /> <line x1="12" x2="12" y1="19" y2="22" />
</svg> </svg>
} }
<span>{{ muted() ? 'فعال‌سازی' : 'بی‌صدا' }}</span>
</button> </button>
<button type="button" class="stream-btn is-end" aria-label="پایان گفتگوی صوتی" (click)="endCall()"> <button type="button" class="dock-btn is-end" aria-label="پایان گفتگوی صوتی" (click)="endCall()">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<line x1="18" x2="6" y1="6" y2="18" /> <line x1="18" x2="6" y1="6" y2="18" />
<line x1="6" x2="18" y1="6" y2="18" /> <line x1="6" x2="18" y1="6" y2="18" />
</svg> </svg>
<span>پایان گفتگو</span> <span class="dock-btn-label">پایان</span>
</button> </button>
</div> </div>
</div> </div>
</div>
@if (streamError(); as errorText) {
<div class="dock-error" role="alert">
<span>{{ errorText }}</span>
<button type="button" class="dock-error-close" aria-label="بستن پیام" (click)="dismissError()">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<line x1="18" x2="6" y1="6" y2="18" />
<line x1="6" x2="18" y1="6" y2="18" />
</svg>
</button>
</div>
}
</div>
@@ -13,7 +13,6 @@ import {
import { OrbMode, VoiceOrbService } from '../../../services/voice-orb/voice-orb.service'; import { OrbMode, VoiceOrbService } from '../../../services/voice-orb/voice-orb.service';
import { VoiceStreamService } from '../../../services/voice-stream/voice-stream.service'; import { VoiceStreamService } from '../../../services/voice-stream/voice-stream.service';
import { VoiceStreamState } from '../../../services/voice-stream/voice-stream.types'; import { VoiceStreamState } from '../../../services/voice-stream/voice-stream.types';
import { VoiceTranscriptComponent } from '../voice-transcript/voice-transcript.component';
const ORB_MODE: Record<VoiceStreamState, OrbMode> = { const ORB_MODE: Record<VoiceStreamState, OrbMode> = {
IDLE: 'listening', IDLE: 'listening',
@@ -23,12 +22,16 @@ const ORB_MODE: Record<VoiceStreamState, OrbMode> = {
SPEAKING: 'speaking', SPEAKING: 'speaking',
}; };
/** Live call view: orb behind an overlaid running transcript, mute / end controls. */ /**
* Compact call bar that sits right above the chat input while a voice call runs:
* orb + status on one side, mute / end on the other. The transcript is NOT part of it;
* the home page's transcript list renders the messages.
*/
@Component({ @Component({
selector: 'app-voice-stream-panel', selector: 'app-voice-stream-panel',
standalone: true, standalone: true,
imports: [VoiceTranscriptComponent],
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
host: { '[class.is-ended]': 'ended()' },
templateUrl: './voice-stream-panel.component.html', templateUrl: './voice-stream-panel.component.html',
styleUrl: './voice-stream-panel.component.css', styleUrl: './voice-stream-panel.component.css',
}) })
@@ -38,15 +41,13 @@ export class VoiceStreamPanelComponent implements AfterViewInit, OnDestroy {
readonly state = this.voice.state; readonly state = this.voice.state;
readonly connection = this.voice.connection; readonly connection = this.voice.connection;
readonly messages = this.voice.messages;
readonly muted = this.voice.muted; readonly muted = this.voice.muted;
readonly streamError = this.voice.streamError; readonly streamError = this.voice.streamError;
readonly orbAvailable = signal(true); readonly orbAvailable = signal(true);
/** The call is over: the orb and controls fade out, the transcript stays. */ /** The call is over: the bar fades and collapses (the host drops it shortly after). */
readonly ended = computed(() => this.connection() === 'disconnected'); readonly ended = computed(() => this.connection() === 'disconnected');
private readonly orbContainer = viewChild.required<ElementRef<HTMLDivElement>>('orbContainer'); private readonly orbContainer = viewChild.required<ElementRef<HTMLDivElement>>('orbContainer');
private readonly scroller = viewChild<ElementRef<HTMLDivElement>>('scroller');
private orbRunning = false; private orbRunning = false;
readonly statusText = computed(() => { readonly statusText = computed(() => {
@@ -73,16 +74,7 @@ export class VoiceStreamPanelComponent implements AfterViewInit, OnDestroy {
constructor() { constructor() {
effect(() => this.orb.setMode(ORB_MODE[this.state()])); effect(() => this.orb.setMode(ORB_MODE[this.state()]));
// Keep the newest message in view as text streams in. // The orb animates only while a call is live.
effect(() => {
this.messages();
requestAnimationFrame(() => {
const el = this.scroller()?.nativeElement;
if (el) el.scrollTop = el.scrollHeight;
});
});
// The orb animates only while a call is live; it fades out (and stops) when the call ends.
effect(() => { effect(() => {
if (this.ended()) { if (this.ended()) {
this.orb.stopAnimation(); this.orb.stopAnimation();
@@ -120,4 +112,4 @@ export class VoiceStreamPanelComponent implements AfterViewInit, OnDestroy {
endCall(): void { endCall(): void {
this.voice.end(); this.voice.end();
} }
} }
@@ -105,6 +105,7 @@
.transcript-empty { .transcript-empty {
margin: auto; margin: auto;
margin-bottom:10px;
font-size: 0.875rem; font-size: 0.875rem;
color: var(--muted); color: var(--muted);
text-align: center; text-align: center;