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:
@@ -4,23 +4,30 @@
|
||||
* Bounded playout queue. The cap is on OUTSTANDING SOURCE PCM — BOUND_BYTES (96,000 bytes
|
||||
* = 48,000 source samples ≈ 2 s at 24 kHz mono PCM16) — and each stage uses ONE unit
|
||||
* consistently:
|
||||
* admission + progress are booked in SOURCE samples (the contract/wire unit);
|
||||
* the ring stores the RESAMPLED OUTPUT samples the AudioContext actually consumes.
|
||||
* admission is booked in SOURCE samples (the contract/wire unit);
|
||||
* the ring stores the RESAMPLED OUTPUT samples the AudioContext actually consumes;
|
||||
* PROGRESS is booked in OUTPUT samples (an integer the resampler fully controls), and
|
||||
* rendered as milliseconds at the context rate. Because resampling preserves duration,
|
||||
* output-time equals source-time, so this reports the same ms as source/srcRate — but it
|
||||
* is exact (no float drift over thousands of iterations).
|
||||
* The output ring is sized to hold the source bound at the worst-case ratio
|
||||
* (source bound ÷ ratio), so the SAME 2 s source cap holds at any real context rate
|
||||
* (24k / 44.1k / 48k …) without widening the source limit, suppressing overflow or
|
||||
* silently dropping PCM. If the queue fills anyway the processor posts `overflow` and the
|
||||
* call fails safely.
|
||||
* (24k / 44.1k / 48k …) without widening the source limit, suppressing overflow or silently
|
||||
* dropping PCM. If the queue fills anyway the processor posts `overflow` and the call fails
|
||||
* safely.
|
||||
*
|
||||
* Real playback progress: played_ms for a server audio_ref is the cumulative SOURCE
|
||||
* samples of THAT ref actually consumed by process(), never a timer. Queued audio keeps
|
||||
* its own audio_ref when a different ref arrives (a FIFO of per-ref source spans), so
|
||||
* progress is never credited to the wrong turn. Reported ~4×/s, on ref completion, and on
|
||||
* clear/flush/idle, so the main thread can send the contract's playback_progress message.
|
||||
* End-of-turn tail: the resample loop keeps the window's last sample as `prev` (for
|
||||
* cross-chunk continuity) and only emits it at the start of the NEXT chunk. At the final
|
||||
* chunk there is no next chunk, so without an explicit flush the last source sample is never
|
||||
* emitted — queued source never reaches zero and played_ms under-reports by ~1 ms, which the
|
||||
* backend reads as perpetual outstanding playback (a stall/overflow signature). `flush()`
|
||||
* (raised on audio_ended) emits that deferred tail so every admitted source sample becomes
|
||||
* output and fully played audio drains to exactly its real duration. `clear()` (barge-in)
|
||||
* discards the tail instead, so interrupted audio is never credited as played.
|
||||
*
|
||||
* Messages in: { type: 'push', pcm: ArrayBuffer (Int16 mono), sampleRate, audioRef }
|
||||
* { type: 'clear' } barge-in: drop everything immediately
|
||||
* { type: 'flush' } end of turn: play what is left, then report 'idle'
|
||||
* { type: 'flush' } end of turn: emit the tail, play what is left, then idle
|
||||
* Messages out: { type: 'progress', audioRef, playedMs }
|
||||
* { type: 'idle' } buffer ran dry after playing
|
||||
* { type: 'overflow' } bounded queue filled — caller fails the session safely
|
||||
@@ -32,7 +39,7 @@ const REPORT_INTERVAL_MS = 250;
|
||||
class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
super();
|
||||
this.sourceCapacity = Math.floor(BOUND_BYTES / 2); // 48,000 SOURCE samples (the admission bound)
|
||||
this.sourceCapacity = Math.floor(BOUND_BYTES / 2); // 48,000 SOURCE samples (admission bound)
|
||||
this.ratio = 1; // SOURCE samples per OUTPUT sample (resolved on first push)
|
||||
this.sized = false; // true once the output ring matches the real context rate
|
||||
this.capacity = this.sourceCapacity; // OUTPUT slots currently allocated (grows for upsampling)
|
||||
@@ -45,14 +52,22 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
||||
this.started = false;
|
||||
this.prev = 0;
|
||||
this.pos = 1;
|
||||
// Per-audio_ref attribution. `refQueue` keeps the still-queued SOURCE span of each ref
|
||||
// (merged per ref so it stays ≤ the number of turns); `refPlayedSamples` keeps each
|
||||
// ref's cumulative consumed source. Together they tie queued audio to its own ref and
|
||||
// End-of-turn tail accounting (per turn, reset on flush/clear). `admittedSrc` +
|
||||
// `emittedOut` let flush() emit the exact OUTPUT count for all admitted source; the last
|
||||
// chunk window is retained so the tail can be interpolated correctly.
|
||||
this.admittedSrc = 0; // SOURCE samples admitted this turn
|
||||
this.emittedOut = 0; // OUTPUT samples emitted for them so far
|
||||
this.windowSrc = null; // last chunk's src window (for tail interpolation)
|
||||
this.windowN = 0;
|
||||
// Per-audio_ref attribution. `refQueue` keeps the still-queued OUTPUT span of each ref
|
||||
// (merged per ref so it stays ≤ the number of turns); `refPlayedOut` keeps each ref's
|
||||
// cumulative OUTPUT samples consumed. Together they tie queued audio to its own ref and
|
||||
// keep progress cumulative and correct across ref changes.
|
||||
this.refQueue = []; // [{ ref, src }] src = remaining SOURCE samples of that ref
|
||||
this.refPlayedSamples = new Map();
|
||||
this.refQueue = []; // [{ ref, out }] out = remaining OUTPUT samples of that ref
|
||||
this.refPlayedOut = new Map();
|
||||
this.playingRef = null; // ref currently being consumed / reported
|
||||
this.unreportedSamples = 0;
|
||||
this.pendingRef = null; // audio_ref of the most recent push (the one flush() tail belongs to)
|
||||
this.unreportedOut = 0;
|
||||
this.overflowPosted = false;
|
||||
this.port.onmessage = (e) => {
|
||||
const m = e.data;
|
||||
@@ -86,19 +101,59 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
||||
this.started = false;
|
||||
this.prev = 0;
|
||||
this.pos = 1;
|
||||
// Discard the deferred tail too: interrupted audio is NOT played, so it must not be
|
||||
// credited or emitted.
|
||||
this.admittedSrc = 0;
|
||||
this.emittedOut = 0;
|
||||
this.windowSrc = null;
|
||||
this.windowN = 0;
|
||||
this.playingRef = null;
|
||||
}
|
||||
|
||||
flush() {
|
||||
this.finalizeTail(); // emit the deferred tail so every admitted sample becomes output
|
||||
if (this.count === 0) {
|
||||
this.started = false;
|
||||
this.reportFinal();
|
||||
this.port.postMessage({ type: 'idle' });
|
||||
} else {
|
||||
this.started = true; // short tail: do not wait for the prebuffer
|
||||
this.started = true; // play the remaining audio + tail without waiting for the prebuffer
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* End-of-turn tail: emit the OUTPUT samples for every admitted SOURCE sample that the push
|
||||
* loop deferred (it keeps the window's last sample as `prev` for cross-chunk continuity and
|
||||
* only emits it at the start of the next chunk). Continuing the interpolation past the last
|
||||
* sample — holding its value — produces real output so fully played audio leaves queued
|
||||
* source at zero and played_ms reflects the true duration (never fabricated upward).
|
||||
*/
|
||||
finalizeTail() {
|
||||
const src = this.windowSrc;
|
||||
const n = this.windowN;
|
||||
if (src && n > 0) {
|
||||
const target = Math.round(this.admittedSrc / this.ratio); // exact OUTPUT count for the turn
|
||||
let pos = n + this.pos; // continue from where the push loop stopped (abs. in this window)
|
||||
while (this.emittedOut < target) {
|
||||
const base = Math.min(Math.floor(pos), n);
|
||||
const frac = Math.min(1, Math.max(0, pos - base));
|
||||
const a = src[base];
|
||||
const b = src[Math.min(base + 1, n)]; // clamp: hold the last sample past the boundary
|
||||
this.write(a * (1 - frac) + b * frac);
|
||||
this.creditQueue(1); // the emitted tail belongs to the current (last) ref
|
||||
this.emittedOut++;
|
||||
pos += this.ratio;
|
||||
}
|
||||
}
|
||||
// Each turn is an independent signal: reset the resampler for the next one.
|
||||
this.admittedSrc = 0;
|
||||
this.emittedOut = 0;
|
||||
this.windowSrc = null;
|
||||
this.windowN = 0;
|
||||
this.pos = 1;
|
||||
this.prev = 0;
|
||||
}
|
||||
|
||||
push(int16, srcRate, audioRef) {
|
||||
const n = int16.length;
|
||||
if (!n) return;
|
||||
@@ -106,7 +161,7 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
||||
const ratio = srcRate / sampleRate; // SOURCE samples per OUTPUT sample
|
||||
this.configure(ratio);
|
||||
|
||||
// OUTPUT samples this chunk will add — the exact count the resample loop performs.
|
||||
// OUTPUT samples this chunk's main loop will add — an upper bound on the exact count.
|
||||
const produced = this.pos < n ? Math.ceil((n - this.pos) / this.ratio) : 0;
|
||||
|
||||
// Bounded queue — two consistent guards, each in its own unit:
|
||||
@@ -116,26 +171,38 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
||||
if (this.count + produced > this.capacity) return this.overflow();
|
||||
|
||||
this.queuedSource += n;
|
||||
|
||||
// Keep the audio_ref of the queued source span so consumption is credited correctly
|
||||
// even when the next ref arrives while this one is still playing.
|
||||
const last = this.refQueue[this.refQueue.length - 1];
|
||||
if (last && last.ref === audioRef) last.src += n;
|
||||
else this.refQueue.push({ ref: audioRef, src: n });
|
||||
this.admittedSrc += n; // every admitted source sample must eventually become output
|
||||
|
||||
const src = new Float32Array(n + 1);
|
||||
src[0] = this.prev;
|
||||
for (let i = 0; i < n; i++) src[i + 1] = int16[i] / 32768;
|
||||
|
||||
// Retain this window so flush() can emit the deferred tail correctly.
|
||||
this.windowSrc = src;
|
||||
this.windowN = n;
|
||||
|
||||
let pos = this.pos;
|
||||
let mainOut = 0;
|
||||
while (pos < n) {
|
||||
const i = Math.floor(pos);
|
||||
const frac = pos - i;
|
||||
this.write(src[i] * (1 - frac) + src[i + 1] * frac);
|
||||
mainOut++;
|
||||
pos += this.ratio;
|
||||
}
|
||||
this.prev = src[n];
|
||||
this.pos = pos - n;
|
||||
this.emittedOut += mainOut;
|
||||
this.pendingRef = audioRef;
|
||||
this.creditQueue(mainOut); // attribute this chunk's OUTPUT to its audio_ref
|
||||
}
|
||||
|
||||
/** Adds `out` OUTPUT samples to the current ref's span (merging consecutive same-ref pushes). */
|
||||
creditQueue(out) {
|
||||
const ref = this.pendingRef;
|
||||
const last = this.refQueue[this.refQueue.length - 1];
|
||||
if (last && last.ref === ref) last.out += out;
|
||||
else this.refQueue.push({ ref, out });
|
||||
}
|
||||
|
||||
overflow() {
|
||||
@@ -173,12 +240,13 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
||||
}
|
||||
}
|
||||
if (played > 0) {
|
||||
const consumedSource = played * this.ratio; // OUTPUT played → SOURCE consumed
|
||||
this.queuedSource = Math.max(0, this.queuedSource - consumedSource);
|
||||
this.consumeSpans(consumedSource);
|
||||
this.queuedSource = Math.max(0, this.queuedSource - played * this.ratio); // OUTPUT→SOURCE
|
||||
this.consumeSpans(played);
|
||||
this.reportCadence();
|
||||
}
|
||||
if (this.count === 0) {
|
||||
// Ring drained: nothing is outstanding, so no phantom source remains for this turn.
|
||||
this.queuedSource = 0;
|
||||
this.started = false;
|
||||
this.reportFinal();
|
||||
this.port.postMessage({ type: 'idle' });
|
||||
@@ -191,48 +259,44 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Draw `amount` SOURCE samples off the front of the ref FIFO, crediting each ref. */
|
||||
consumeSpans(amount) {
|
||||
while (amount > 1e-6 && this.refQueue.length) {
|
||||
/** Draw `played` OUTPUT samples off the front of the ref FIFO, crediting each ref. */
|
||||
consumeSpans(played) {
|
||||
while (played > 0 && this.refQueue.length) {
|
||||
const span = this.refQueue[0];
|
||||
const take = amount < span.src ? amount : span.src;
|
||||
span.src -= take;
|
||||
amount -= take;
|
||||
this.creditRef(span.ref, take);
|
||||
if (span.src <= 1e-6) {
|
||||
const take = played < span.out ? played : span.out;
|
||||
span.out -= take;
|
||||
played -= take;
|
||||
this.refPlayedOut.set(span.ref, (this.refPlayedOut.get(span.ref) ?? 0) + take);
|
||||
this.playingRef = span.ref;
|
||||
this.unreportedOut += take;
|
||||
if (span.out <= 0) {
|
||||
this.refQueue.shift();
|
||||
this.postProgress(span.ref); // ref finished: post its final cumulative before the next ref
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
creditRef(ref, sourceSamples) {
|
||||
this.refPlayedSamples.set(ref, (this.refPlayedSamples.get(ref) ?? 0) + sourceSamples);
|
||||
this.playingRef = ref;
|
||||
this.unreportedSamples += sourceSamples;
|
||||
}
|
||||
|
||||
/** Final cumulative report for the ref currently playing (interruption / drain / clear). */
|
||||
reportFinal() {
|
||||
this.unreportedSamples = 0;
|
||||
this.unreportedOut = 0;
|
||||
if (!this.playingRef) return;
|
||||
this.postProgress(this.playingRef);
|
||||
}
|
||||
|
||||
/** Cadence report for the ref currently playing (~REPORT_INTERVAL_MS of consumed source). */
|
||||
/** Cadence report for the ref currently playing (~REPORT_INTERVAL_MS of consumed output). */
|
||||
reportCadence() {
|
||||
if (!this.playingRef) return;
|
||||
const srcRate = this.ratio * sampleRate;
|
||||
if ((this.unreportedSamples / srcRate) * 1000 >= REPORT_INTERVAL_MS) {
|
||||
if ((this.unreportedOut / sampleRate) * 1000 >= REPORT_INTERVAL_MS) {
|
||||
this.reportFinal();
|
||||
}
|
||||
}
|
||||
|
||||
postProgress(ref) {
|
||||
const playedSamples = this.refPlayedSamples.get(ref) ?? 0;
|
||||
const srcRate = this.ratio * sampleRate;
|
||||
// floor: never claims an unheard millisecond; monotonic because it is cumulative.
|
||||
const playedMs = Math.floor((playedSamples / srcRate) * 1000);
|
||||
const playedOut = this.refPlayedOut.get(ref) ?? 0;
|
||||
// OUTPUT samples at the context rate → milliseconds; floor never claims an unheard ms and
|
||||
// stays monotonic because it is cumulative. Output-time equals source-time (SRC preserves
|
||||
// duration), so this equals the contract's played source / srcRate.
|
||||
const playedMs = Math.floor((playedOut / sampleRate) * 1000);
|
||||
if (playedMs <= 0) return;
|
||||
this.port.postMessage({ type: 'progress', audioRef: ref, playedMs });
|
||||
}
|
||||
|
||||
+199
-123
@@ -1,33 +1,21 @@
|
||||
/* --------------------------------------------------------------------------
|
||||
Home page — Claude-style chat column
|
||||
Structure:
|
||||
.home-page
|
||||
.chat-column
|
||||
.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;
|
||||
}
|
||||
/* ==========================================================================
|
||||
Layout: .home-page > .chat-column > ( .transcript-list + .composer )
|
||||
- Landing (no conversation): greeting + composer are centered as one group.
|
||||
- Conversation: the greeting collapses, the transcript list grows to fill the
|
||||
column (it is the only scroller) and the composer sits at the bottom.
|
||||
========================================================================== */
|
||||
|
||||
.home-page {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
height: 100dvh;
|
||||
min-height: 100dvh;
|
||||
box-sizing: border-box;
|
||||
padding: 0;
|
||||
position: relative;
|
||||
/* Flat page color; every decorative glow lives in ::below so it can fade out as one. */
|
||||
background: var(--app-bg);
|
||||
overflow: hidden;
|
||||
background:
|
||||
radial-gradient(ellipse 50% 40% at 50% 45%, rgba(59, 130, 246, 0.1), transparent 70%),
|
||||
var(--app-bg);
|
||||
}
|
||||
|
||||
.home-page::before {
|
||||
@@ -35,91 +23,38 @@
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
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 35% 55%, rgba(99, 102, 241, 0.05), transparent 50%),
|
||||
radial-gradient(circle at 65% 50%, rgba(59, 130, 246, 0.04), transparent 45%);
|
||||
pointer-events: none;
|
||||
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 {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
/* ---- Chat column (Claude: one continuous column) ---- */
|
||||
.chat-column {
|
||||
position: relative;
|
||||
/* ---------- Logo (landing only) ---------- */
|
||||
.home-header {
|
||||
position: absolute;
|
||||
top: 2rem;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
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;
|
||||
padding: 2rem 1rem;
|
||||
min-height: 0;
|
||||
opacity: 1;
|
||||
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 {
|
||||
@@ -141,9 +76,44 @@
|
||||
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 {
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
margin: 0 0 1rem;
|
||||
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -182,56 +152,144 @@
|
||||
45% {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
46%,
|
||||
100% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Voice panel becomes the transcript body — no extra card chrome */
|
||||
.chat-transcript-body {
|
||||
display: block;
|
||||
flex: 1 1 auto;
|
||||
/* ---------- transcript list (the page's only scroller) ---------- */
|
||||
.transcript-list {
|
||||
flex: 0 1 auto;
|
||||
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) ---- */
|
||||
.composer {
|
||||
flex-shrink: 0;
|
||||
width: 100%;
|
||||
padding: 0.75rem 1rem 1.25rem;
|
||||
.home-page.has-conversation .transcript-list {
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
.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;
|
||||
background: transparent;
|
||||
/* Subtle top fade so messages don't collide with the input */
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
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 {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
inset-inline: 0;
|
||||
bottom: 100%;
|
||||
height: 1.5rem;
|
||||
pointer-events: none;
|
||||
background: linear-gradient(to top, var(--app-bg), transparent);
|
||||
pointer-events: none;
|
||||
opacity: 0;
|
||||
transition: opacity 0.25s ease;
|
||||
transition: opacity 0.3s ease;
|
||||
}
|
||||
|
||||
.home-page.has-conversation .composer::before {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* ---- Responsive ---- */
|
||||
@media (max-width: 640px) {
|
||||
.transcript-list {
|
||||
padding: 1rem 0.75rem 0.5rem;
|
||||
}
|
||||
.composer > :not(.jump-to-latest) {
|
||||
max-width: 800px;
|
||||
margin-inline: auto;
|
||||
}
|
||||
|
||||
.composer {
|
||||
padding: 0.5rem 0.75rem 1rem;
|
||||
.home-call-dock {
|
||||
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 {
|
||||
@@ -243,15 +301,33 @@
|
||||
.home-title {
|
||||
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) {
|
||||
.home-page,
|
||||
.home-page::before,
|
||||
.home-header,
|
||||
.home-greeting,
|
||||
.transcript-list,
|
||||
.composer::before {
|
||||
.composer::before,
|
||||
.jump-to-latest {
|
||||
transition: none !important;
|
||||
animation: none !important;
|
||||
scroll-behavior: auto !important;
|
||||
}
|
||||
}
|
||||
@@ -1,52 +1,67 @@
|
||||
<div
|
||||
class="home-page"
|
||||
[class.has-conversation]="hasConversation()"
|
||||
>
|
||||
<!-- Claude-style chat column: transcript list + composer in one continuous column -->
|
||||
<div class="chat-column" role="main">
|
||||
<!-- Transcript list (scrollable). Empty state or live/ended voice transcript. -->
|
||||
<div class="home-page" [class.has-conversation]="hasConversation()">
|
||||
|
||||
<!-- Brand logo: shown only on the empty landing state -->
|
||||
<div class="home-header" aria-hidden="true">
|
||||
<div class="home-icon-wrapper">
|
||||
<img class="home-logo" [src]="logoSrc()" alt="Raymand" />
|
||||
</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
|
||||
class="transcript-list"
|
||||
#transcriptScroller
|
||||
#transcriptList
|
||||
role="log"
|
||||
aria-label="متن گفتگو"
|
||||
aria-live="polite"
|
||||
aria-relevant="additions"
|
||||
(scroll)="onTranscriptScroll()"
|
||||
>
|
||||
@if (!hasConversation()) {
|
||||
<!-- Empty state: logo + typing title (Claude empty chat feel) -->
|
||||
<div class="empty-state">
|
||||
<div class="home-icon-wrapper">
|
||||
<img
|
||||
class="home-logo"
|
||||
[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 class="transcript-inner">
|
||||
@if (callOpen() && voiceMessages().length === 0) {
|
||||
<p class="transcript-empty">صحبت کنید؛ گفتگو اینجا نمایش داده میشود</p>
|
||||
}
|
||||
<app-voice-transcript [messages]="voiceMessages()" />
|
||||
</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">
|
||||
@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
|
||||
data-chat-input
|
||||
placeholder="پیام خود را بنویسید..."
|
||||
[hasMessages]="hasConversation()"
|
||||
(messageSent)="onMessageSent($event)"
|
||||
(fileSelected)="onFileSelected($event)"
|
||||
(voiceToggled)="onVoiceToggled($event)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
+100
-21
@@ -1,20 +1,24 @@
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
ElementRef,
|
||||
OnDestroy,
|
||||
OnInit,
|
||||
computed,
|
||||
effect,
|
||||
inject,
|
||||
signal,
|
||||
computed,
|
||||
OnInit,
|
||||
OnDestroy,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
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 { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';
|
||||
import { Router, NavigationEnd } from '@angular/router';
|
||||
import { filter } from 'rxjs/operators';
|
||||
import { ThemeService } from '../../services/theme/theme.service';
|
||||
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 = [
|
||||
'چه چیزی میخواهید بدانید؟',
|
||||
@@ -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({
|
||||
selector: 'app-home',
|
||||
standalone: true,
|
||||
imports: [CommonModule, AiChatInputComponent, VoiceStreamPanelComponent],
|
||||
imports: [AiChatInputComponent, VoiceStreamPanelComponent, VoiceTranscriptComponent],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
templateUrl: './home.page.html',
|
||||
styleUrl: './home.page.css',
|
||||
@@ -47,26 +56,29 @@ export class HomePage implements OnInit, OnDestroy {
|
||||
readonly logoSrc = () =>
|
||||
this.isDarkMode() ? 'assets/images/RaymandLogo.png' : 'assets/images/login.png';
|
||||
|
||||
// ---- conversation state ---------------------------------------------------
|
||||
readonly hasMessages = signal(false);
|
||||
readonly callOpen = this.voiceStream.isOpen;
|
||||
readonly voiceMessages = this.voiceStream.messages;
|
||||
|
||||
/**
|
||||
* Conversation owns the layout when there is a live voice call,
|
||||
* leftover voice transcript, or text messages — same idea as Claude's
|
||||
* chat column switching from empty state to transcript list.
|
||||
*/
|
||||
readonly voiceHasTranscript = computed(
|
||||
() => this.voiceStream.isOpen() || this.voiceStream.messages().length > 0,
|
||||
/** Anything on screen that belongs in the chat column: text sent, a live call, or a finished call's transcript. */
|
||||
readonly hasConversation = computed(
|
||||
() => this.hasMessages() || this.callOpen() || this.voiceMessages().length > 0,
|
||||
);
|
||||
|
||||
readonly hasConversation = computed(() => this.hasMessages() || this.voiceHasTranscript());
|
||||
|
||||
/** @deprecated use hasConversation — kept for any external bindings */
|
||||
readonly voicePanelVisible = this.hasConversation;
|
||||
/** The call bar stays mounted briefly after the call ends so it can animate out. */
|
||||
readonly callDockMounted = signal(false);
|
||||
readonly jumpVisible = signal(false);
|
||||
|
||||
// ---- title typing ---------------------------------------------------------
|
||||
readonly homeTitle = signal('');
|
||||
readonly streamedText = signal('');
|
||||
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 routerSubscription?: Subscription;
|
||||
|
||||
@@ -79,6 +91,28 @@ export class HomePage implements OnInit, OnDestroy {
|
||||
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 {
|
||||
@@ -87,9 +121,48 @@ export class HomePage implements OnInit, OnDestroy {
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.stopTyping();
|
||||
this.clearDockTimer();
|
||||
if (this.scrollFrame !== null) cancelAnimationFrame(this.scrollFrame);
|
||||
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 {
|
||||
this.stopTyping();
|
||||
|
||||
@@ -115,9 +188,12 @@ export class HomePage implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
index++;
|
||||
|
||||
this.streamedText.set(text.substring(0, index));
|
||||
|
||||
// Slightly random timing makes it feel more natural
|
||||
const delay = 16 + Math.random() * 8;
|
||||
|
||||
this.typingTimer = setTimeout(typeNextCharacter, delay);
|
||||
};
|
||||
|
||||
@@ -129,9 +205,12 @@ export class HomePage implements OnInit, OnDestroy {
|
||||
clearTimeout(this.typingTimer);
|
||||
this.typingTimer = null;
|
||||
}
|
||||
|
||||
this.isStreaming.set(false);
|
||||
}
|
||||
|
||||
// ---- composer events ------------------------------------------------------
|
||||
|
||||
onMessageSent(message: string): void {
|
||||
this.hasMessages.set(true);
|
||||
console.log('Message sent:', message);
|
||||
|
||||
@@ -435,7 +435,7 @@
|
||||
</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="flex items-center gap-2">
|
||||
<select
|
||||
@@ -456,22 +456,43 @@
|
||||
</label>
|
||||
<span class="text-xs text-[var(--text-muted)]">فقط فعال</span>
|
||||
</div>
|
||||
<button type="button" class="btn btn--outline" (click)="refreshDocuments()" [disabled]="documentsLoading()">
|
||||
<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>بهروزرسانی</span>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn--outline"
|
||||
(click)="refreshDocuments()"
|
||||
[disabled]="documentsLoading()"
|
||||
[attr.aria-busy]="documentsLoading()"
|
||||
>
|
||||
@if (documentsLoading()) {
|
||||
<svg
|
||||
class="w-4 h-4 animate-spin"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
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>
|
||||
</div>
|
||||
|
||||
@@ -614,18 +635,29 @@
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
} @empty {
|
||||
@if (!documentsLoading()) {
|
||||
<tr>
|
||||
<td
|
||||
colspan="7"
|
||||
class="px-3 py-10 text-center text-sm text-[var(--text-muted)]"
|
||||
>
|
||||
هیچ سندی با فیلتر انتخابشده مطابقت ندارد.
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
@if (!hasMoreDocuments() && !documentsLoading()) {
|
||||
@if (documents().length > 0 && !hasMoreDocuments() && !documentsLoading()) {
|
||||
<p class="text-xs text-[var(--text-muted)] text-center mt-3">
|
||||
{{ documents().length }} سند ثبت شده
|
||||
</p>
|
||||
}
|
||||
|
||||
@if (hasMoreDocuments() && !documentsLoading()) {
|
||||
@if (documents().length > 0 && hasMoreDocuments() && !documentsLoading()) {
|
||||
<div class="documents-pagination mt-3 text-center">
|
||||
<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();
|
||||
});
|
||||
});
|
||||
@@ -203,6 +203,13 @@ export class SettingsPage implements OnInit, OnDestroy {
|
||||
readonly activeFilter = signal<DocumentStatus | 'all'>('all');
|
||||
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 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
|
||||
@@ -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 {
|
||||
|
||||
@@ -16,6 +16,12 @@
|
||||
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 */
|
||||
.composer-layer,
|
||||
.voice-layer {
|
||||
@@ -57,14 +63,6 @@
|
||||
transform: translateY(0) scale(1);
|
||||
}
|
||||
|
||||
:host-context(.has-messages) {
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
/* ---------- Chat composer ---------- */
|
||||
.chat-composer {
|
||||
/* 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 {
|
||||
background: var(--muted);
|
||||
border: none;
|
||||
border-radius: 9999px;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
class="ai-chat-input-wrapper"
|
||||
[class.voice-active]="anyVoiceActive()"
|
||||
[class.dictation-active]="isVoiceMode()"
|
||||
[class.stream-open]="streamOpen()"
|
||||
[attr.data-voice-state]="voiceState()"
|
||||
(keydown.escape)="onEscape()"
|
||||
>
|
||||
@@ -207,4 +208,4 @@
|
||||
</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 {
|
||||
display: block;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
display: grid;
|
||||
grid-template-rows: 1fr;
|
||||
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 {
|
||||
--footer-h: 3.5rem;
|
||||
--orb-zone: 7.25rem;
|
||||
--orb-gap: 0.75rem;
|
||||
--reserve: calc(var(--footer-h) + var(--orb-gap) + var(--orb-zone) + var(--orb-gap));
|
||||
:host(.is-ended) {
|
||||
grid-template-rows: 0fr;
|
||||
opacity: 0;
|
||||
margin-bottom: 0 !important;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
.call-dock {
|
||||
direction: rtl;
|
||||
box-sizing: border-box;
|
||||
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;
|
||||
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) ---------- */
|
||||
.stream-orb-layer {
|
||||
position: absolute;
|
||||
bottom: calc(var(--footer-h) + var(--orb-gap));
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 1;
|
||||
:host(.is-ended) .call-dock {
|
||||
border-color: transparent;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.dock-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
transition: opacity 0.45s ease, transform 0.45s ease;
|
||||
gap: 0.75rem;
|
||||
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 {
|
||||
width: 88px;
|
||||
height: 88px;
|
||||
max-width: 100%;
|
||||
width: 96px;
|
||||
height: 96px;
|
||||
margin-block: -20px;
|
||||
margin-inline: -14px;
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -56,11 +61,11 @@
|
||||
|
||||
/* Shown only when WebGL is unavailable */
|
||||
.orb-fallback {
|
||||
width: 70%;
|
||||
height: 70%;
|
||||
width: 55%;
|
||||
height: 55%;
|
||||
border-radius: 50%;
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -70,12 +75,14 @@
|
||||
transform: scale(1);
|
||||
}
|
||||
50% {
|
||||
transform: scale(1.06);
|
||||
transform: scale(1.08);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- Status ---------- */
|
||||
.stream-status {
|
||||
.dock-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
@@ -83,9 +90,12 @@
|
||||
|
||||
.status-text {
|
||||
margin: 0;
|
||||
font-size: 0.8125rem;
|
||||
min-width: 0;
|
||||
font-size: 0.875rem;
|
||||
color: var(--text-secondary);
|
||||
text-align: center;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.status-dot {
|
||||
@@ -97,22 +107,22 @@
|
||||
transition: background 0.3s ease;
|
||||
}
|
||||
|
||||
.stream-status[data-state='LISTENING'] .status-dot {
|
||||
.status-dot[data-state='LISTENING'] {
|
||||
background: #22c55e;
|
||||
animation: dotPulse 1.6s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.stream-status[data-state='PROCESSING'] .status-dot {
|
||||
.status-dot[data-state='PROCESSING'] {
|
||||
background: #818cf8;
|
||||
animation: dotPulse 0.9s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.stream-status[data-state='SPEAKING'] .status-dot {
|
||||
.status-dot[data-state='SPEAKING'] {
|
||||
background: #a78bfa;
|
||||
animation: dotPulse 0.7s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.stream-status[data-state='INTERRUPTED'] .status-dot {
|
||||
.status-dot[data-state='INTERRUPTED'] {
|
||||
background: #f59e0b;
|
||||
}
|
||||
|
||||
@@ -128,56 +138,91 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- Transcript (overlaid on top of the orb) ---------- */
|
||||
.stream-transcript {
|
||||
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;
|
||||
/* ---------- Controls ---------- */
|
||||
.dock-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
width: min(100% - 1.5rem, 640px);
|
||||
box-sizing: border-box;
|
||||
padding: 0.5rem 0.75rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.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-radius: 0.875rem;
|
||||
border-radius: 0.75rem;
|
||||
color: #dc2626;
|
||||
font-size: 0.8125rem;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.stream-error span {
|
||||
.dock-error span {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.stream-error-close {
|
||||
.dock-error-close {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -191,112 +236,20 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.stream-error-close:focus-visible {
|
||||
.dock-error-close:focus-visible {
|
||||
outline: 2px solid var(--color-primary);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
/* ---------- Controls ---------- */
|
||||
.stream-footer {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 3;
|
||||
display: flex;
|
||||
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;
|
||||
@keyframes dockIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.sr-only {
|
||||
@@ -312,31 +265,34 @@
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
:host,
|
||||
.status-dot,
|
||||
.orb-fallback,
|
||||
.stream-btn,
|
||||
.stream-orb-layer,
|
||||
.stream-footer,
|
||||
.stream-transcript {
|
||||
.dock-btn {
|
||||
animation: none !important;
|
||||
transition: none !important;
|
||||
scroll-behavior: auto !important;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.stream-panel {
|
||||
--footer-h: 3.25rem;
|
||||
--orb-zone: 6rem;
|
||||
--orb-gap: 0.5rem;
|
||||
.dock-row {
|
||||
gap: 0.5rem;
|
||||
padding: 0.375rem 0.625rem;
|
||||
}
|
||||
|
||||
.orb-container {
|
||||
width: 68px;
|
||||
height: 68px;
|
||||
width: 84px;
|
||||
height: 84px;
|
||||
margin-block: -16px;
|
||||
margin-inline: -12px;
|
||||
}
|
||||
|
||||
.stream-btn {
|
||||
padding: 0.5rem 1rem;
|
||||
.dock-btn-label {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.dock-btn.is-end {
|
||||
padding: 0;
|
||||
width: 40px;
|
||||
}
|
||||
}
|
||||
@@ -1,55 +1,27 @@
|
||||
<div
|
||||
class="stream-panel"
|
||||
class="call-dock"
|
||||
role="region"
|
||||
aria-label="گفتگوی صوتی"
|
||||
[class.is-ended]="ended()"
|
||||
[attr.data-state]="state()"
|
||||
>
|
||||
<div class="sr-only" role="status" aria-live="polite">{{ statusText() }}</div>
|
||||
|
||||
<!-- Orb layer: behind the transcript, anchored just above the controls -->
|
||||
<div class="stream-orb-layer" aria-hidden="true">
|
||||
<div class="orb-container" #orbContainer>
|
||||
<div class="dock-row">
|
||||
<div class="orb-container" #orbContainer aria-hidden="true">
|
||||
@if (!orbAvailable()) {
|
||||
<div class="orb-fallback"></div>
|
||||
}
|
||||
</div>
|
||||
<div class="stream-status" [attr.data-state]="state()">
|
||||
<span class="status-dot" aria-hidden="true"></span>
|
||||
<p class="status-text">{{ statusText() }}</p>
|
||||
|
||||
<div class="dock-info" aria-hidden="true">
|
||||
<span class="status-dot" [attr.data-state]="state()"></span>
|
||||
<p class="status-text" [attr.title]="statusText()">{{ statusText() }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Transcript: overlaid on top of the orb, keeps streaming while the call runs -->
|
||||
<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">
|
||||
<div class="dock-actions">
|
||||
<button
|
||||
type="button"
|
||||
class="stream-btn"
|
||||
class="dock-btn"
|
||||
[class.is-active]="muted()"
|
||||
[attr.aria-pressed]="muted()"
|
||||
[attr.aria-label]="muteLabel()"
|
||||
@@ -73,16 +45,27 @@
|
||||
<line x1="12" x2="12" y1="19" y2="22" />
|
||||
</svg>
|
||||
}
|
||||
<span>{{ muted() ? 'فعالسازی' : 'بیصدا' }}</span>
|
||||
</button>
|
||||
|
||||
<button type="button" class="stream-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">
|
||||
<button type="button" class="dock-btn is-end" aria-label="پایان گفتگوی صوتی" (click)="endCall()">
|
||||
<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="6" x2="18" y1="6" y2="18" />
|
||||
</svg>
|
||||
<span>پایان گفتگو</span>
|
||||
<span class="dock-btn-label">پایان</span>
|
||||
</button>
|
||||
</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 { VoiceStreamService } from '../../../services/voice-stream/voice-stream.service';
|
||||
import { VoiceStreamState } from '../../../services/voice-stream/voice-stream.types';
|
||||
import { VoiceTranscriptComponent } from '../voice-transcript/voice-transcript.component';
|
||||
|
||||
const ORB_MODE: Record<VoiceStreamState, OrbMode> = {
|
||||
IDLE: 'listening',
|
||||
@@ -23,12 +22,16 @@ const ORB_MODE: Record<VoiceStreamState, OrbMode> = {
|
||||
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({
|
||||
selector: 'app-voice-stream-panel',
|
||||
standalone: true,
|
||||
imports: [VoiceTranscriptComponent],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
host: { '[class.is-ended]': 'ended()' },
|
||||
templateUrl: './voice-stream-panel.component.html',
|
||||
styleUrl: './voice-stream-panel.component.css',
|
||||
})
|
||||
@@ -38,15 +41,13 @@ export class VoiceStreamPanelComponent implements AfterViewInit, OnDestroy {
|
||||
|
||||
readonly state = this.voice.state;
|
||||
readonly connection = this.voice.connection;
|
||||
readonly messages = this.voice.messages;
|
||||
readonly muted = this.voice.muted;
|
||||
readonly streamError = this.voice.streamError;
|
||||
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');
|
||||
|
||||
private readonly orbContainer = viewChild.required<ElementRef<HTMLDivElement>>('orbContainer');
|
||||
private readonly scroller = viewChild<ElementRef<HTMLDivElement>>('scroller');
|
||||
private orbRunning = false;
|
||||
|
||||
readonly statusText = computed(() => {
|
||||
@@ -73,16 +74,7 @@ export class VoiceStreamPanelComponent implements AfterViewInit, OnDestroy {
|
||||
constructor() {
|
||||
effect(() => this.orb.setMode(ORB_MODE[this.state()]));
|
||||
|
||||
// Keep the newest message in view as text streams in.
|
||||
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.
|
||||
// The orb animates only while a call is live.
|
||||
effect(() => {
|
||||
if (this.ended()) {
|
||||
this.orb.stopAnimation();
|
||||
@@ -120,4 +112,4 @@ export class VoiceStreamPanelComponent implements AfterViewInit, OnDestroy {
|
||||
endCall(): void {
|
||||
this.voice.end();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -105,6 +105,7 @@
|
||||
|
||||
.transcript-empty {
|
||||
margin: auto;
|
||||
margin-bottom:10px;
|
||||
font-size: 0.875rem;
|
||||
color: var(--muted);
|
||||
text-align: center;
|
||||
|
||||
Reference in New Issue
Block a user