feat(voice): implement real-time voice-to-voice streaming engine
Introduce a complete low-level audio processing and streaming pipeline for live voice conversations. - Implement `VoiceAudioEngine` using `AudioWorklet` for low-latency PCM16 capture and playback. - Add `pcm-capture` and `pcm-playback` worklets for high-performance audio processing outside the main thread. - Implement `VoiceStreamService` to manage the voice-to-voice state machine (LISTENING, PROCESSING, SPEAKING, INTERRUPTED). - Add `VoiceApiService` for managing conversation and session lifecycle via REST and WebSocket. - Create `VoiceStreamPanelComponent` to display real-time transcripts, status indicators, and the animated voice orb. - Integrate voice streaming into the `AiChatInputComponent` with support for seamless UI transitions between text and voice modes.
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* Mic capture: downsamples the context rate to `targetRate` (default 16 kHz),
|
||||
* converts to PCM16 mono and posts fixed-size frames (default 20 ms) to the main thread.
|
||||
* Message: { pcm: ArrayBuffer (Int16), rms: number (0..1) }
|
||||
*/
|
||||
class PcmCaptureProcessor extends AudioWorkletProcessor {
|
||||
constructor(options) {
|
||||
super();
|
||||
const o = (options && options.processorOptions) || {};
|
||||
this.targetRate = o.targetRate || 16000;
|
||||
this.frameSamples = o.frameSamples || 320;
|
||||
this.ratio = sampleRate / this.targetRate; // input samples per output sample
|
||||
this.pos = 0;
|
||||
this.sum = 0;
|
||||
this.count = 0;
|
||||
this.frame = new Float32Array(this.frameSamples);
|
||||
this.filled = 0;
|
||||
}
|
||||
|
||||
process(inputs) {
|
||||
const channel = inputs[0] && inputs[0][0];
|
||||
if (!channel) return true;
|
||||
|
||||
for (let i = 0; i < channel.length; i++) {
|
||||
this.sum += channel[i];
|
||||
this.count++;
|
||||
this.pos += 1;
|
||||
if (this.pos >= this.ratio) {
|
||||
// box-filter average of the input samples that fall into one output sample
|
||||
this.frame[this.filled++] = this.sum / this.count;
|
||||
this.sum = 0;
|
||||
this.count = 0;
|
||||
this.pos -= this.ratio;
|
||||
if (this.filled === this.frameSamples) this.flush();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
flush() {
|
||||
const out = new Int16Array(this.frameSamples);
|
||||
let energy = 0;
|
||||
for (let i = 0; i < this.frameSamples; i++) {
|
||||
const v = Math.max(-1, Math.min(1, this.frame[i]));
|
||||
energy += v * v;
|
||||
out[i] = v < 0 ? v * 0x8000 : v * 0x7fff;
|
||||
}
|
||||
this.filled = 0;
|
||||
this.port.postMessage({ pcm: out.buffer, rms: Math.sqrt(energy / this.frameSamples) }, [out.buffer]);
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor('pcm-capture', PcmCaptureProcessor);
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* Streaming PCM playback with a ring buffer.
|
||||
* Messages in: { type: 'push', pcm: ArrayBuffer (Int16 mono), sampleRate }
|
||||
* { type: 'clear' } barge-in: drop everything immediately
|
||||
* { type: 'flush' } end of turn: play what is left, then report 'idle'
|
||||
* Messages out: { type: 'idle' } buffer ran dry after playing
|
||||
*/
|
||||
class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
super();
|
||||
this.capacity = Math.floor(sampleRate * 30);
|
||||
this.buf = new Float32Array(this.capacity);
|
||||
this.r = 0;
|
||||
this.w = 0;
|
||||
this.count = 0;
|
||||
this.prebuffer = Math.floor(sampleRate * 0.08); // jitter buffer before (re)starting
|
||||
this.started = false;
|
||||
this.prev = 0;
|
||||
this.pos = 1;
|
||||
this.port.onmessage = (e) => {
|
||||
const m = e.data;
|
||||
if (!m) return;
|
||||
if (m.type === 'push') this.push(new Int16Array(m.pcm), m.sampleRate);
|
||||
else if (m.type === 'clear') this.clear();
|
||||
else if (m.type === 'flush') this.flush();
|
||||
};
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.r = this.w = this.count = 0;
|
||||
this.started = false;
|
||||
this.prev = 0;
|
||||
this.pos = 1;
|
||||
}
|
||||
|
||||
flush() {
|
||||
if (this.count === 0) {
|
||||
this.started = false;
|
||||
this.port.postMessage({ type: 'idle' });
|
||||
} else {
|
||||
this.started = true; // short tail: do not wait for the prebuffer
|
||||
}
|
||||
}
|
||||
|
||||
push(int16, srcRate) {
|
||||
const n = int16.length;
|
||||
if (!n) return;
|
||||
const ratio = srcRate / sampleRate; // source samples per output sample
|
||||
const src = new Float32Array(n + 1);
|
||||
src[0] = this.prev;
|
||||
for (let i = 0; i < n; i++) src[i + 1] = int16[i] / 32768;
|
||||
|
||||
let pos = this.pos;
|
||||
while (pos < n) {
|
||||
const i = Math.floor(pos);
|
||||
const frac = pos - i;
|
||||
this.write(src[i] * (1 - frac) + src[i + 1] * frac);
|
||||
pos += ratio;
|
||||
}
|
||||
this.prev = src[n];
|
||||
this.pos = pos - n;
|
||||
}
|
||||
|
||||
write(v) {
|
||||
if (this.count === this.capacity) {
|
||||
this.r = (this.r + 1) % this.capacity; // overflow: drop the oldest sample
|
||||
this.count--;
|
||||
}
|
||||
this.buf[this.w] = v;
|
||||
this.w = (this.w + 1) % this.capacity;
|
||||
this.count++;
|
||||
}
|
||||
|
||||
process(inputs, outputs) {
|
||||
const out = outputs[0];
|
||||
const ch0 = out[0];
|
||||
|
||||
if (!this.started && this.count >= this.prebuffer) this.started = true;
|
||||
|
||||
if (this.started) {
|
||||
for (let i = 0; i < ch0.length; i++) {
|
||||
if (this.count > 0) {
|
||||
ch0[i] = this.buf[this.r];
|
||||
this.r = (this.r + 1) % this.capacity;
|
||||
this.count--;
|
||||
} else {
|
||||
ch0[i] = 0;
|
||||
}
|
||||
}
|
||||
if (this.count === 0) {
|
||||
this.started = false;
|
||||
this.port.postMessage({ type: 'idle' });
|
||||
}
|
||||
} else {
|
||||
ch0.fill(0);
|
||||
}
|
||||
|
||||
for (let c = 1; c < out.length; c++) out[c].set(ch0);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor('pcm-playback', PcmPlaybackProcessor);
|
||||
@@ -26,8 +26,12 @@ export class MicrophoneService {
|
||||
/**
|
||||
* Requests microphone permission and returns the stream.
|
||||
* @param onEnded called if the capture track ends unexpectedly (e.g. device unplugged).
|
||||
* @param audio `true` for browser defaults, or explicit constraints (e.g. echo cancellation for calls).
|
||||
*/
|
||||
async request(onEnded?: () => void): Promise<MediaStream> {
|
||||
async request(
|
||||
onEnded?: () => void,
|
||||
audio: MediaTrackConstraints | boolean = true,
|
||||
): Promise<MediaStream> {
|
||||
if (!this.isSupported) {
|
||||
throw new MicrophoneError('unsupported');
|
||||
}
|
||||
@@ -36,7 +40,7 @@ export class MicrophoneService {
|
||||
|
||||
let stream: MediaStream;
|
||||
try {
|
||||
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
stream = await navigator.mediaDevices.getUserMedia({ audio });
|
||||
} catch (err) {
|
||||
throw this.mapError(err);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,15 @@ import { Injectable, NgZone, inject } from '@angular/core';
|
||||
import * as THREE from 'three';
|
||||
import { mergeVertices } from 'three/examples/jsm/utils/BufferGeometryUtils.js';
|
||||
|
||||
/** Visual mode of the orb (colour + behaviour). */
|
||||
export type OrbMode = 'listening' | 'processing' | 'speaking';
|
||||
|
||||
const ORB_COLORS: Record<OrbMode, number> = {
|
||||
listening: 0x60a5fa,
|
||||
processing: 0x818cf8,
|
||||
speaking: 0xa78bfa,
|
||||
};
|
||||
|
||||
/** Icosphere subdivision. 20 → ~4.4k shared vertices: smooth and cheap to deform every frame. */
|
||||
const ORB_DETAIL = 20;
|
||||
const FALLBACK_SIZE = 260;
|
||||
@@ -33,6 +42,11 @@ export class VoiceOrbService {
|
||||
private audioData: Uint8Array<ArrayBuffer> | null = null;
|
||||
private smoothedLevel = 0;
|
||||
|
||||
private levelProvider: (() => number) | null = null;
|
||||
private mode: OrbMode = 'listening';
|
||||
private orbMaterial: THREE.MeshPhysicalMaterial | null = null;
|
||||
private readonly targetColor = new THREE.Color(ORB_COLORS.listening);
|
||||
|
||||
/**
|
||||
* Creates the scene once and reuses it on later calls (re-attaching the canvas if needed).
|
||||
* Returns false if WebGL is unavailable so the caller can show a fallback.
|
||||
@@ -104,6 +118,7 @@ export class VoiceOrbService {
|
||||
clearcoat: 1,
|
||||
clearcoatRoughness: 0.08,
|
||||
});
|
||||
this.orbMaterial = orbMaterial;
|
||||
this.orb = new THREE.Mesh(geometry, orbMaterial);
|
||||
this.scene.add(this.orb);
|
||||
|
||||
@@ -197,6 +212,21 @@ export class VoiceOrbService {
|
||||
this.audioContext = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drives the orb from an external level source (0..1) instead of attachStream().
|
||||
* Used by the voice call, where the level switches between mic and assistant playback.
|
||||
*/
|
||||
setLevelProvider(provider: (() => number) | null): void {
|
||||
this.levelProvider = provider;
|
||||
this.smoothedLevel = 0;
|
||||
}
|
||||
|
||||
/** Changes the orb's colour and behaviour ('processing' breathes on its own). */
|
||||
setMode(mode: OrbMode): void {
|
||||
this.mode = mode;
|
||||
this.targetColor.setHex(ORB_COLORS[mode]);
|
||||
}
|
||||
|
||||
// ---- cleanup --------------------------------------------------------------
|
||||
|
||||
dispose(): void {
|
||||
@@ -226,6 +256,10 @@ export class VoiceOrbService {
|
||||
this.orbGeometry = null;
|
||||
this.glowShell = null;
|
||||
this.originalPositions = null;
|
||||
this.orbMaterial = null;
|
||||
this.levelProvider = null;
|
||||
this.mode = 'listening';
|
||||
this.targetColor.setHex(ORB_COLORS.listening);
|
||||
}
|
||||
|
||||
// ---- internals ------------------------------------------------------------
|
||||
@@ -252,6 +286,7 @@ export class VoiceOrbService {
|
||||
const speed = this.reducedMotion ? 0.35 : 1;
|
||||
const t = performance.now() * 0.001 * speed;
|
||||
const level = this.updateAudioLevel();
|
||||
this.orbMaterial?.color.lerp(this.targetColor, 0.06);
|
||||
|
||||
this.updateOrbGeometry(t, level);
|
||||
|
||||
@@ -305,6 +340,12 @@ export class VoiceOrbService {
|
||||
}
|
||||
|
||||
private readAudioLevel(): number {
|
||||
if (this.mode === 'processing') {
|
||||
return 0.14 + 0.1 * Math.sin(performance.now() * 0.004);
|
||||
}
|
||||
if (this.levelProvider) {
|
||||
return Math.min(1, Math.max(0, this.levelProvider())) * (this.reducedMotion ? 0.5 : 1);
|
||||
}
|
||||
if (!this.analyser || !this.audioData) return 0;
|
||||
|
||||
this.analyser.getByteFrequencyData(this.audioData);
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { firstValueFrom, Observable } from 'rxjs';
|
||||
import { VOICE_STREAM_CONFIG } from './voice-stream.types';
|
||||
|
||||
/** Error envelope from the catalog: { error: { code, message, request_id, retryable, details } }. */
|
||||
export class VoiceApiError extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
readonly code: string,
|
||||
message: string,
|
||||
readonly retryable = false,
|
||||
readonly requestId?: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'VoiceApiError';
|
||||
}
|
||||
}
|
||||
|
||||
export interface MeResponse {
|
||||
user: { id: string; username: string; role: string; organization_id: string };
|
||||
csrf_token: string;
|
||||
expires_at: string;
|
||||
}
|
||||
|
||||
export interface ConfigurationResponse {
|
||||
capabilities: { text: boolean; voice: boolean; captions: boolean };
|
||||
}
|
||||
|
||||
export interface ConversationResponse {
|
||||
id: string;
|
||||
mode: 'voice';
|
||||
title: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export interface VoiceSessionResponse {
|
||||
session_id: string;
|
||||
conversation_id: string;
|
||||
status: string;
|
||||
stream_path: string;
|
||||
expires_at: string;
|
||||
poll_url: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Thin client for the endpoints the live voice call needs (A03, F01, C01, V01, V04).
|
||||
* Uses HttpClient so the app's existing interceptors (401 → login redirect, etc.) still apply.
|
||||
* Auth is the HttpOnly `rag_session` cookie; state-changing calls also need `X-CSRF-Token`.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class VoiceApiService {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly config = inject(VOICE_STREAM_CONFIG);
|
||||
|
||||
/** A03: identity + a fresh CSRF token. 401 AUTH_REQUIRED when not logged in. */
|
||||
me(): Promise<MeResponse> {
|
||||
return this.send(this.http.get<MeResponse>(this.url('/me'), { withCredentials: true }));
|
||||
}
|
||||
|
||||
/** F01: capabilities (the UI must check `voice` before offering a call). */
|
||||
configuration(): Promise<ConfigurationResponse> {
|
||||
return this.send(
|
||||
this.http.get<ConfigurationResponse>(this.url('/configuration'), { withCredentials: true }),
|
||||
);
|
||||
}
|
||||
|
||||
/** C01: only `mode: "voice"` exists in the MVP. */
|
||||
createConversation(csrf: string, title: string): Promise<ConversationResponse> {
|
||||
return this.send(
|
||||
this.http.post<ConversationResponse>(
|
||||
this.url('/conversations'),
|
||||
{ client_request_id: crypto.randomUUID(), mode: 'voice', title },
|
||||
this.options(csrf),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** V01: reserves a live session; connect the WebSocket to the returned `stream_path`. */
|
||||
createVoiceSession(csrf: string, conversationId: string): Promise<VoiceSessionResponse> {
|
||||
return this.send(
|
||||
this.http.post<VoiceSessionResponse>(
|
||||
this.url('/voice/sessions'),
|
||||
{ conversation_id: conversationId, client_request_id: crypto.randomUUID() },
|
||||
this.options(csrf),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** V04: closes the session (idempotent from the UI's point of view). */
|
||||
async closeVoiceSession(csrf: string, sessionId: string): Promise<void> {
|
||||
await this.send(
|
||||
this.http.post<unknown>(
|
||||
this.url(`/voice/sessions/${encodeURIComponent(sessionId)}/close`),
|
||||
{},
|
||||
this.options(csrf),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** `wss://…` URL for a V01 `stream_path`. */
|
||||
streamUrl(streamPath: string): string {
|
||||
const base = this.config.apiOrigin || window.location.origin;
|
||||
const url = new URL(streamPath, base);
|
||||
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
private url(path: string): string {
|
||||
return `${this.config.apiOrigin}${this.config.apiBase}${path}`;
|
||||
}
|
||||
|
||||
private options(csrf: string) {
|
||||
return {
|
||||
withCredentials: true,
|
||||
headers: new HttpHeaders({ 'X-CSRF-Token': csrf, 'X-Request-ID': crypto.randomUUID() }),
|
||||
};
|
||||
}
|
||||
|
||||
private async send<T>(request: Observable<T>): Promise<T> {
|
||||
try {
|
||||
return await firstValueFrom(request);
|
||||
} catch (err) {
|
||||
throw this.toApiError(err);
|
||||
}
|
||||
}
|
||||
|
||||
private toApiError(err: unknown): VoiceApiError {
|
||||
if (err instanceof HttpErrorResponse) {
|
||||
const envelope = (err.error as { error?: Record<string, unknown> } | null)?.error;
|
||||
return new VoiceApiError(
|
||||
err.status,
|
||||
typeof envelope?.['code'] === 'string' ? envelope['code'] : err.status === 0 ? 'NETWORK' : 'UNKNOWN',
|
||||
typeof envelope?.['message'] === 'string' ? envelope['message'] : err.message,
|
||||
envelope?.['retryable'] === true,
|
||||
typeof envelope?.['request_id'] === 'string' ? envelope['request_id'] : undefined,
|
||||
);
|
||||
}
|
||||
return new VoiceApiError(0, 'UNKNOWN', err instanceof Error ? err.message : 'unknown error');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
import { Injectable, NgZone, inject } from '@angular/core';
|
||||
import { MicrophoneService } from '../microphone/microphone.service';
|
||||
import { VOICE_STREAM_CONFIG } from './voice-stream.types';
|
||||
|
||||
export interface VoiceEngineHandlers {
|
||||
/** One PCM16 frame (config.inputSampleRate, config.frameMs). Runs outside Angular's zone. */
|
||||
onFrame(pcm: ArrayBuffer, rms: number): void;
|
||||
/** The playback buffer ran dry (or `flushPlayback()` found it empty). */
|
||||
onPlaybackIdle(): void;
|
||||
/** The microphone track ended unexpectedly. */
|
||||
onMicEnded(): void;
|
||||
}
|
||||
|
||||
export class VoiceEngineError extends Error {
|
||||
constructor(readonly code: 'unsupported' | 'worklet-failed') {
|
||||
super(code);
|
||||
this.name = 'VoiceEngineError';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Low-level audio for the call:
|
||||
* mic → [pcm-capture worklet] → PCM16 frames → (service → transport)
|
||||
* (transport → service) → PCM16 chunks → [pcm-playback worklet] → speakers
|
||||
* Everything here runs outside Angular's zone; frames arrive ~50×/s and must not trigger change detection.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class VoiceAudioEngine {
|
||||
private readonly ngZone = inject(NgZone);
|
||||
private readonly mic = inject(MicrophoneService);
|
||||
private readonly config = inject(VOICE_STREAM_CONFIG);
|
||||
|
||||
private ctx: AudioContext | null = null;
|
||||
private source: MediaStreamAudioSourceNode | null = null;
|
||||
private capture: AudioWorkletNode | null = null;
|
||||
private playback: AudioWorkletNode | null = null;
|
||||
private sink: GainNode | null = null;
|
||||
private analyser: AnalyserNode | null = null;
|
||||
private analyserData: Uint8Array<ArrayBuffer> | null = null;
|
||||
private stream: MediaStream | null = null;
|
||||
private inputRms = 0;
|
||||
|
||||
get isSupported(): boolean {
|
||||
return (
|
||||
this.mic.isSupported &&
|
||||
typeof AudioContext !== 'undefined' &&
|
||||
typeof AudioWorkletNode !== 'undefined'
|
||||
);
|
||||
}
|
||||
|
||||
/** Requests the mic, loads the worklets and starts capturing. Throws MicrophoneError / VoiceEngineError. */
|
||||
async start(handlers: VoiceEngineHandlers): Promise<void> {
|
||||
if (!this.isSupported) throw new VoiceEngineError('unsupported');
|
||||
this.stop();
|
||||
|
||||
const stream = await this.mic.request(handlers.onMicEnded, {
|
||||
echoCancellation: true,
|
||||
noiseSuppression: true,
|
||||
autoGainControl: true,
|
||||
channelCount: 1,
|
||||
});
|
||||
this.stream = stream;
|
||||
|
||||
try {
|
||||
await this.ngZone.runOutsideAngular(() => this.buildGraph(stream, handlers));
|
||||
} catch (err) {
|
||||
this.stop();
|
||||
throw err instanceof Error && err.name === 'MicrophoneError' ? err : new VoiceEngineError('worklet-failed');
|
||||
}
|
||||
}
|
||||
|
||||
private async buildGraph(stream: MediaStream, handlers: VoiceEngineHandlers): Promise<void> {
|
||||
const cfg = this.config;
|
||||
const ctx = new AudioContext({ latencyHint: 'interactive' });
|
||||
this.ctx = ctx;
|
||||
|
||||
const base = cfg.workletBasePath.replace(/\/$/, '');
|
||||
await ctx.audioWorklet.addModule(`${base}/pcm-capture.worklet.js`);
|
||||
await ctx.audioWorklet.addModule(`${base}/pcm-playback.worklet.js`);
|
||||
if (ctx.state === 'suspended') await ctx.resume();
|
||||
|
||||
// capture: mic → worklet → (silent sink so the graph is pulled)
|
||||
this.source = ctx.createMediaStreamSource(stream);
|
||||
this.capture = new AudioWorkletNode(ctx, 'pcm-capture', {
|
||||
numberOfInputs: 1,
|
||||
numberOfOutputs: 1,
|
||||
outputChannelCount: [1],
|
||||
processorOptions: {
|
||||
targetRate: cfg.inputSampleRate,
|
||||
frameSamples: Math.round((cfg.inputSampleRate * cfg.frameMs) / 1000),
|
||||
},
|
||||
});
|
||||
this.capture.port.onmessage = (event: MessageEvent<{ pcm: ArrayBuffer; rms: number }>) => {
|
||||
this.inputRms = event.data.rms;
|
||||
handlers.onFrame(event.data.pcm, event.data.rms);
|
||||
};
|
||||
this.sink = ctx.createGain();
|
||||
this.sink.gain.value = 0; // never play the mic back
|
||||
this.source.connect(this.capture);
|
||||
this.capture.connect(this.sink);
|
||||
this.sink.connect(ctx.destination);
|
||||
|
||||
// playback: worklet → analyser (output level) → speakers
|
||||
this.playback = new AudioWorkletNode(ctx, 'pcm-playback', {
|
||||
numberOfInputs: 0,
|
||||
numberOfOutputs: 1,
|
||||
outputChannelCount: [1],
|
||||
});
|
||||
this.playback.port.onmessage = (event: MessageEvent<{ type: string }>) => {
|
||||
if (event.data?.type === 'idle') handlers.onPlaybackIdle();
|
||||
};
|
||||
this.analyser = ctx.createAnalyser();
|
||||
this.analyser.fftSize = 1024;
|
||||
this.analyser.smoothingTimeConstant = 0.6;
|
||||
this.analyserData = new Uint8Array(this.analyser.fftSize);
|
||||
this.playback.connect(this.analyser);
|
||||
this.analyser.connect(ctx.destination);
|
||||
}
|
||||
|
||||
// ---- playback --------------------------------------------------------------
|
||||
|
||||
/** Queues a PCM16 mono chunk at config.outputSampleRate. Ownership of the buffer moves to the worklet. */
|
||||
enqueuePlayback(chunk: ArrayBuffer): void {
|
||||
if (!this.playback) return;
|
||||
const buffer = chunk.byteLength % 2 === 0 ? chunk : chunk.slice(0, chunk.byteLength - 1);
|
||||
this.playback.port.postMessage(
|
||||
{ type: 'push', pcm: buffer, sampleRate: this.config.outputSampleRate },
|
||||
[buffer],
|
||||
);
|
||||
}
|
||||
|
||||
/** Barge-in: drop all queued audio immediately. */
|
||||
clearPlayback(): void {
|
||||
this.playback?.port.postMessage({ type: 'clear' });
|
||||
}
|
||||
|
||||
/** End of turn: play the remaining audio, then report idle. */
|
||||
flushPlayback(): void {
|
||||
this.playback?.port.postMessage({ type: 'flush' });
|
||||
}
|
||||
|
||||
// ---- mic / meters ----------------------------------------------------------
|
||||
|
||||
setMuted(muted: boolean): void {
|
||||
this.stream?.getAudioTracks().forEach((track) => (track.enabled = !muted));
|
||||
}
|
||||
|
||||
/** Mic level 0..1 (for the orb). */
|
||||
inputLevel(): number {
|
||||
return Math.min(1, this.inputRms * 6);
|
||||
}
|
||||
|
||||
/** Assistant playback level 0..1 (for the orb). */
|
||||
outputLevel(): number {
|
||||
if (!this.analyser || !this.analyserData) return 0;
|
||||
this.analyser.getByteTimeDomainData(this.analyserData);
|
||||
let sum = 0;
|
||||
for (let i = 0; i < this.analyserData.length; i++) {
|
||||
const v = (this.analyserData[i] - 128) / 128;
|
||||
sum += v * v;
|
||||
}
|
||||
return Math.min(1, Math.sqrt(sum / this.analyserData.length) * 5);
|
||||
}
|
||||
|
||||
// ---- cleanup ---------------------------------------------------------------
|
||||
|
||||
stop(): void {
|
||||
if (this.capture) this.capture.port.onmessage = null;
|
||||
if (this.playback) this.playback.port.onmessage = null;
|
||||
|
||||
this.source?.disconnect();
|
||||
this.capture?.disconnect();
|
||||
this.sink?.disconnect();
|
||||
this.playback?.disconnect();
|
||||
this.analyser?.disconnect();
|
||||
|
||||
if (this.ctx && this.ctx.state !== 'closed') {
|
||||
this.ctx.close().catch(() => undefined);
|
||||
}
|
||||
this.mic.release(this.stream);
|
||||
|
||||
this.ctx = null;
|
||||
this.source = null;
|
||||
this.capture = null;
|
||||
this.playback = null;
|
||||
this.sink = null;
|
||||
this.analyser = null;
|
||||
this.analyserData = null;
|
||||
this.stream = null;
|
||||
this.inputRms = 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,631 @@
|
||||
import { Injectable, NgZone, computed, inject, signal } from '@angular/core';
|
||||
import { Subject } from 'rxjs';
|
||||
import { MicrophoneError } from '../microphone/microphone.service';
|
||||
import { VoiceApiError, VoiceApiService } from './voice-api.service';
|
||||
import { VoiceAudioEngine, VoiceEngineError } from './voice-audio-engine.service';
|
||||
import { VOICE_TRANSPORT_FACTORY, VoiceTransport } from './voice-transport';
|
||||
import {
|
||||
VOICE_STREAM_CONFIG,
|
||||
VoiceConnection,
|
||||
VoiceMessage,
|
||||
VoiceServerEvent,
|
||||
VoiceSessionEnd,
|
||||
VoiceStreamState,
|
||||
} from './voice-stream.types';
|
||||
|
||||
export type VoiceStartFailure =
|
||||
| 'cancelled'
|
||||
| 'unsupported'
|
||||
| 'mic'
|
||||
| 'engine'
|
||||
| 'auth'
|
||||
| 'unavailable'
|
||||
| 'api'
|
||||
| 'connect';
|
||||
|
||||
export type VoiceStartResult =
|
||||
| { ok: true }
|
||||
| { ok: false; reason: VoiceStartFailure; message: string };
|
||||
|
||||
type TranscriptEvent = Extract<VoiceServerEvent, { type: 'transcript' }>;
|
||||
type SourcesEvent = Extract<VoiceServerEvent, { type: 'sources' }>;
|
||||
type ErrorEvent = Extract<VoiceServerEvent, { type: 'error' }>;
|
||||
|
||||
const MESSAGES = {
|
||||
unsupported: 'گفتگوی صوتی در این مرورگر پشتیبانی نمیشود (اتصال امن HTTPS و مرورگر جدید لازم است).',
|
||||
micDenied: 'دسترسی به میکروفون رد شد. اجازهی دسترسی را در تنظیمات مرورگر فعال کنید.',
|
||||
micUnavailable: 'میکروفونی پیدا نشد یا در حال استفادهی برنامهی دیگری است.',
|
||||
micLost: 'اتصال میکروفون قطع شد و گفتگو پایان یافت.',
|
||||
engine: 'راهاندازی پردازشگر صوتی ناموفق بود. صفحه را دوباره بارگذاری کنید.',
|
||||
auth: 'نشست شما منقضی شده است. دوباره وارد شوید.',
|
||||
voiceDisabled: 'گفتگوی صوتی برای این سامانه فعال نیست.',
|
||||
rateLimited: 'تعداد درخواستها زیاد است. کمی بعد دوباره تلاش کنید.',
|
||||
unavailable: 'سرویس موقتاً در دسترس نیست. کمی بعد دوباره تلاش کنید.',
|
||||
sessionUnusable: 'نشست صوتی بسته شده است. گفتگوی جدیدی شروع کنید.',
|
||||
api: 'شروع گفتگوی صوتی ناموفق بود. دوباره تلاش کنید.',
|
||||
connect: 'اتصال به سرور صوتی برقرار نشد. دوباره تلاش کنید.',
|
||||
badFormat: 'فرمت صدای سرور با برنامه سازگار نیست.',
|
||||
disconnected: 'ارتباط با سرور قطع شد و گفتگو پایان یافت.',
|
||||
server: 'سرور گفتگوی صوتی با خطا مواجه شد.',
|
||||
conversationTitle: 'گفتگوی صوتی',
|
||||
} as const;
|
||||
|
||||
/** How long INTERRUPTED stays visible before returning to LISTENING. */
|
||||
const INTERRUPTED_FLASH_MS = 150;
|
||||
/** How long a retryable server error stays on screen. */
|
||||
const ERROR_BANNER_MS = 6000;
|
||||
|
||||
/**
|
||||
* One live voice call against the MVP API (mvp_ui_api_catalog.md §6):
|
||||
*
|
||||
* mic ─▶ engine ─▶ PCM16 16 kHz frames ─▶ WSS ─▶ server
|
||||
* server ─▶ session_ready / transcript / sources / turn_interrupted / error (JSON)
|
||||
* ─▶ PCM16 24 kHz audio (binary) ─▶ engine playback
|
||||
*
|
||||
* Start: mic permission → GET /me (CSRF) → GET /configuration (voice enabled?)
|
||||
* → POST /conversations → POST /voice/sessions → WSS stream_path → `session_ready`.
|
||||
* End: close the socket, stop audio, POST /voice/sessions/{id}/close.
|
||||
*
|
||||
* Barge-in is decided by the server: it sends `turn_interrupted` and the client flushes playback.
|
||||
* (The contract has no client→server interrupt message.)
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class VoiceStreamService {
|
||||
private readonly ngZone = inject(NgZone);
|
||||
private readonly engine = inject(VoiceAudioEngine);
|
||||
private readonly api = inject(VoiceApiService);
|
||||
private readonly config = inject(VOICE_STREAM_CONFIG);
|
||||
private readonly createTransport = inject(VOICE_TRANSPORT_FACTORY);
|
||||
|
||||
readonly state = signal<VoiceStreamState>('IDLE');
|
||||
readonly connection = signal<VoiceConnection>('disconnected');
|
||||
readonly messages = signal<VoiceMessage[]>([]);
|
||||
readonly muted = signal(false);
|
||||
/** Non-fatal, retryable server error to show as a banner (e.g. SEARCH_TIMEOUT). */
|
||||
readonly streamError = signal<string | null>(null);
|
||||
|
||||
/** true from the moment start() is called until the call is over. */
|
||||
readonly isOpen = computed(() => this.connection() !== 'disconnected');
|
||||
readonly isSupported = this.engine.isSupported && typeof WebSocket !== 'undefined';
|
||||
|
||||
/** Emits once for every call that reached `connected` (normal end or failure). */
|
||||
readonly sessionEnded$ = new Subject<VoiceSessionEnd>();
|
||||
|
||||
private transport: VoiceTransport | null = null;
|
||||
private remote: { sessionId: string; conversationId: string; csrf: string } | null = null;
|
||||
private session = 0;
|
||||
private streaming = false;
|
||||
private turnEnded = false;
|
||||
private interruptTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private settleTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private errorTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private readyWaiter: {
|
||||
resolve: () => void;
|
||||
reject: (error: Error) => void;
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
} | null = null;
|
||||
private lastConversationId: string | null = null;
|
||||
|
||||
// ---- public API -----------------------------------------------------------
|
||||
|
||||
async start(options: { title?: string } = {}): Promise<VoiceStartResult> {
|
||||
if (this.isOpen()) return this.failure('cancelled', '');
|
||||
if (!this.isSupported) return this.failure('unsupported', MESSAGES.unsupported);
|
||||
|
||||
const session = ++this.session;
|
||||
const stale = (): boolean => session !== this.session;
|
||||
|
||||
this.messages.set([]);
|
||||
this.muted.set(false);
|
||||
this.clearError();
|
||||
this.resetTurnFlags();
|
||||
this.lastConversationId = null;
|
||||
this.state.set('IDLE');
|
||||
this.connection.set('connecting');
|
||||
|
||||
// 1) microphone + worklets (needs the user gesture; shows the permission prompt)
|
||||
try {
|
||||
await this.engine.start({
|
||||
onFrame: (pcm) => this.onMicFrame(pcm),
|
||||
onPlaybackIdle: () => this.ngZone.run(() => this.onPlaybackIdle()),
|
||||
onMicEnded: () => this.ngZone.run(() => this.failSession(MESSAGES.micLost, session)),
|
||||
});
|
||||
} catch (err) {
|
||||
return this.abortStart(session, this.mapEngineError(err));
|
||||
}
|
||||
if (stale()) {
|
||||
// Cancelled while the permission prompt / worklets were loading: release what was just opened.
|
||||
if (!this.isOpen()) this.engine.stop();
|
||||
return this.failure('cancelled', '');
|
||||
}
|
||||
|
||||
// 2) REST: identity/CSRF → capabilities → conversation → voice session
|
||||
let streamPath: string;
|
||||
try {
|
||||
const me = await this.api.me();
|
||||
if (stale()) return this.failure('cancelled', '');
|
||||
|
||||
const configuration = await this.api.configuration();
|
||||
if (stale()) return this.failure('cancelled', '');
|
||||
if (!configuration.capabilities.voice) {
|
||||
return this.abortStart(session, { reason: 'unavailable', message: MESSAGES.voiceDisabled });
|
||||
}
|
||||
|
||||
const conversation = await this.api.createConversation(me.csrf_token, MESSAGES.conversationTitle);
|
||||
if (stale()) return this.failure('cancelled', '');
|
||||
|
||||
const voiceSession = await this.api.createVoiceSession(me.csrf_token, conversation.id);
|
||||
const remote = {
|
||||
sessionId: voiceSession.session_id,
|
||||
conversationId: conversation.id,
|
||||
csrf: me.csrf_token,
|
||||
};
|
||||
if (stale()) {
|
||||
this.closeRemote(remote); // cancelled after the server already reserved the session
|
||||
return this.failure('cancelled', '');
|
||||
}
|
||||
this.remote = remote;
|
||||
this.lastConversationId = conversation.id;
|
||||
streamPath = voiceSession.stream_path;
|
||||
} catch (err) {
|
||||
if (stale()) return this.failure('cancelled', '');
|
||||
return this.abortStart(session, this.mapApiError(err));
|
||||
}
|
||||
|
||||
// 3) WebSocket (created outside the zone so socket events don't trigger change detection)
|
||||
const transport = this.createTransport(this.api.streamUrl(streamPath));
|
||||
this.transport = transport;
|
||||
try {
|
||||
await this.ngZone.runOutsideAngular(() =>
|
||||
transport.connect({
|
||||
onEvent: (event) => this.ngZone.run(() => this.onServerEvent(event, session)),
|
||||
onAudio: (chunk) => this.onServerAudio(chunk, session),
|
||||
onClose: () => this.ngZone.run(() => this.failSession(MESSAGES.disconnected, session)),
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
if (stale()) return this.failure('cancelled', '');
|
||||
return this.abortStart(session, { reason: 'connect', message: MESSAGES.connect });
|
||||
}
|
||||
if (stale()) return this.failure('cancelled', '');
|
||||
|
||||
// 4) wait for `session_ready` (the server pushes it; the client sends no handshake)
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(
|
||||
() => reject(new Error('ready-timeout')),
|
||||
this.config.connectTimeoutMs,
|
||||
);
|
||||
this.readyWaiter = { resolve, reject, timer };
|
||||
});
|
||||
} catch (err) {
|
||||
if (stale()) return this.failure('cancelled', '');
|
||||
const badFormat = err instanceof Error && err.message === 'format';
|
||||
return this.abortStart(session, {
|
||||
reason: 'connect',
|
||||
message: badFormat ? MESSAGES.badFormat : MESSAGES.connect,
|
||||
});
|
||||
}
|
||||
if (stale()) return this.failure('cancelled', '');
|
||||
|
||||
this.connection.set('connected');
|
||||
this.state.set('LISTENING');
|
||||
this.streaming = true;
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/** User ends the call. Safe to call at any time. */
|
||||
end(): void {
|
||||
if (!this.isOpen()) return;
|
||||
this.finishSession();
|
||||
}
|
||||
|
||||
toggleMute(): void {
|
||||
const next = !this.muted();
|
||||
this.muted.set(next);
|
||||
this.engine.setMuted(next); // frames keep flowing (silent), so the server never sees a gap
|
||||
}
|
||||
|
||||
/** Level (0..1) the orb should follow: assistant audio while speaking, otherwise the mic. */
|
||||
orbLevel(): number {
|
||||
if (this.state() === 'SPEAKING') return this.engine.outputLevel();
|
||||
return this.muted() ? 0 : this.engine.inputLevel();
|
||||
}
|
||||
|
||||
dismissError(): void {
|
||||
this.clearError();
|
||||
}
|
||||
|
||||
/** Component teardown: release everything without emitting events. */
|
||||
dispose(): void {
|
||||
this.rejectReady();
|
||||
this.teardown();
|
||||
}
|
||||
|
||||
// ---- audio from the microphone (outside the zone) --------------------------
|
||||
|
||||
private onMicFrame(pcm: ArrayBuffer): void {
|
||||
if (this.streaming) this.transport?.sendAudio(pcm);
|
||||
}
|
||||
|
||||
// ---- audio from the server (outside the zone) ------------------------------
|
||||
|
||||
private onServerAudio(chunk: ArrayBuffer, session: number): void {
|
||||
if (session !== this.session || !this.streaming) return;
|
||||
this.engine.enqueuePlayback(chunk);
|
||||
this.clearSettleTimer();
|
||||
|
||||
if (this.state() !== 'SPEAKING') {
|
||||
this.ngZone.run(() => {
|
||||
if (this.interruptTimer) {
|
||||
clearTimeout(this.interruptTimer);
|
||||
this.interruptTimer = null;
|
||||
}
|
||||
this.state.set('SPEAKING');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ---- JSON events from the server -------------------------------------------
|
||||
|
||||
private onServerEvent(event: VoiceServerEvent, session: number): void {
|
||||
if (session !== this.session) return;
|
||||
|
||||
switch (event.type) {
|
||||
case 'session_ready': {
|
||||
const { input_audio: input, output_audio: output } = event;
|
||||
const compatible =
|
||||
input.encoding === 'pcm_s16le' &&
|
||||
output.encoding === 'pcm_s16le' &&
|
||||
input.channels === 1 &&
|
||||
output.channels === 1 &&
|
||||
input.sample_rate === this.config.inputSampleRate &&
|
||||
output.sample_rate === this.config.outputSampleRate;
|
||||
if (compatible) this.resolveReady();
|
||||
else this.rejectReady(new Error('format'));
|
||||
break;
|
||||
}
|
||||
|
||||
case 'transcript':
|
||||
this.onTranscript(event);
|
||||
break;
|
||||
|
||||
case 'sources':
|
||||
this.upsertSources(event);
|
||||
break;
|
||||
|
||||
case 'turn_interrupted':
|
||||
this.onTurnInterrupted(event.turn_ref);
|
||||
break;
|
||||
|
||||
case 'error':
|
||||
this.onServerError(event, session);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private onTranscript(event: TranscriptEvent): void {
|
||||
this.upsertTranscript(event);
|
||||
|
||||
if (event.status === 'interrupted') {
|
||||
this.onTurnInterrupted(event.turn_ref);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.role === 'user') {
|
||||
// The user finished their sentence; the assistant is working on it.
|
||||
if (event.status === 'completed' && this.state() === 'LISTENING') {
|
||||
this.state.set('PROCESSING');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.status === 'completed') {
|
||||
// All text for this turn is out. Play what is buffered, then return to LISTENING.
|
||||
this.turnEnded = true;
|
||||
this.engine.flushPlayback();
|
||||
}
|
||||
}
|
||||
|
||||
/** Server-side barge-in: the user spoke over the assistant. */
|
||||
private onTurnInterrupted(turnRef: string): void {
|
||||
this.engine.clearPlayback(); // empty the playback queue immediately
|
||||
this.turnEnded = false;
|
||||
this.clearSettleTimer();
|
||||
this.markInterrupted(turnRef);
|
||||
|
||||
const state = this.state();
|
||||
if (state === 'SPEAKING' || state === 'PROCESSING') {
|
||||
this.state.set('INTERRUPTED');
|
||||
if (this.interruptTimer) clearTimeout(this.interruptTimer);
|
||||
this.interruptTimer = setTimeout(() => {
|
||||
this.interruptTimer = null;
|
||||
if (this.state() === 'INTERRUPTED') this.state.set('LISTENING');
|
||||
}, INTERRUPTED_FLASH_MS);
|
||||
}
|
||||
}
|
||||
|
||||
private onServerError(event: ErrorEvent, session: number): void {
|
||||
const { message, retryable, code } = event.error;
|
||||
console.warn('VoiceStreamService: server error', code, event.error.request_id);
|
||||
|
||||
if (!retryable) {
|
||||
this.failSession(message || MESSAGES.server, session);
|
||||
return;
|
||||
}
|
||||
|
||||
// The session survives a retryable failure (e.g. SEARCH_TIMEOUT): drop the failed turn and keep listening.
|
||||
this.engine.clearPlayback();
|
||||
this.turnEnded = false;
|
||||
this.clearSettleTimer();
|
||||
this.finalizeAssistant();
|
||||
if (this.state() === 'PROCESSING' || this.state() === 'SPEAKING') this.state.set('LISTENING');
|
||||
this.showError(message || MESSAGES.server);
|
||||
}
|
||||
|
||||
// ---- end of an assistant turn ----------------------------------------------
|
||||
|
||||
private onPlaybackIdle(): void {
|
||||
const state = this.state();
|
||||
if (state !== 'SPEAKING' && state !== 'PROCESSING') return;
|
||||
|
||||
if (this.turnEnded) {
|
||||
this.finishTurn();
|
||||
} else if (state === 'SPEAKING') {
|
||||
// The buffer drained but no `completed` transcript arrived (yet). If no more audio comes, the turn is over.
|
||||
this.clearSettleTimer();
|
||||
this.settleTimer = setTimeout(() => {
|
||||
this.settleTimer = null;
|
||||
if (this.state() === 'SPEAKING') this.finishTurn();
|
||||
}, this.config.settleMs);
|
||||
}
|
||||
}
|
||||
|
||||
private finishTurn(): void {
|
||||
this.turnEnded = false;
|
||||
this.clearSettleTimer();
|
||||
this.finalizeAssistant();
|
||||
this.state.set('LISTENING');
|
||||
}
|
||||
|
||||
// ---- transcript ------------------------------------------------------------
|
||||
|
||||
private upsertTranscript(event: TranscriptEvent): void {
|
||||
const id = `${event.turn_ref}:${event.role}`;
|
||||
const final = event.status !== 'partial';
|
||||
const interrupted = event.status === 'interrupted';
|
||||
|
||||
this.messages.update((list) => {
|
||||
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,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const current = list[index];
|
||||
if (current.interrupted && !interrupted) return list; // late partial for a cut-off message
|
||||
const copy = [...list];
|
||||
copy[index] = {
|
||||
...current,
|
||||
text: this.mergeTranscriptText(current.text, event),
|
||||
final: current.final || final,
|
||||
interrupted: current.interrupted || interrupted || undefined,
|
||||
};
|
||||
return copy;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The catalog does not say whether a `partial` carries the full text so far or only the new fragment,
|
||||
* so both are handled:
|
||||
* - `completed` with text → the final full text replaces whatever was accumulated
|
||||
* - text that starts with what we already have → cumulative, replace
|
||||
* - anything else → a fragment, append as-is (fragments carry their own spacing)
|
||||
* If the backend turns out to use only one style, this is the single place to simplify.
|
||||
*/
|
||||
private mergeTranscriptText(previous: string, event: TranscriptEvent): string {
|
||||
const next = event.text;
|
||||
if (!next) return previous;
|
||||
if (!previous || event.status === 'completed') return next;
|
||||
if (next.startsWith(previous)) return next;
|
||||
return previous + next;
|
||||
}
|
||||
|
||||
private upsertSources(event: SourcesEvent): void {
|
||||
const id = `${event.turn_ref}:assistant`;
|
||||
this.messages.update((list) => {
|
||||
const index = list.findIndex((m) => m.id === id);
|
||||
const current: VoiceMessage =
|
||||
index === -1
|
||||
? { id, turnRef: event.turn_ref, role: 'assistant', text: '', final: false }
|
||||
: list[index];
|
||||
|
||||
const sources = [...(current.sources ?? [])];
|
||||
for (const source of event.sources) {
|
||||
if (!sources.some((s) => s.source_ref === source.source_ref && s.chunk_id === source.chunk_id)) {
|
||||
sources.push(source);
|
||||
}
|
||||
}
|
||||
|
||||
const next = { ...current, sources };
|
||||
if (index === -1) return [...list, next];
|
||||
const copy = [...list];
|
||||
copy[index] = next;
|
||||
return copy;
|
||||
});
|
||||
}
|
||||
|
||||
private markInterrupted(turnRef: string): void {
|
||||
const id = `${turnRef}:assistant`;
|
||||
this.messages.update((list) => {
|
||||
const index = list.findIndex((m) => m.id === id);
|
||||
if (index === -1 || list[index].interrupted) return list;
|
||||
const copy = [...list];
|
||||
copy[index] = { ...copy[index], final: true, interrupted: true };
|
||||
return copy;
|
||||
});
|
||||
}
|
||||
|
||||
private finalizeAssistant(): void {
|
||||
this.messages.update((list) =>
|
||||
list.some((m) => m.role === 'assistant' && !m.final)
|
||||
? list.map((m) => (m.role === 'assistant' && !m.final ? { ...m, final: true } : m))
|
||||
: list,
|
||||
);
|
||||
}
|
||||
|
||||
private finalizeAll(): void {
|
||||
this.messages.update((list) =>
|
||||
list.some((m) => !m.final) ? list.map((m) => (m.final ? m : { ...m, final: true })) : list,
|
||||
);
|
||||
}
|
||||
|
||||
// ---- lifecycle -------------------------------------------------------------
|
||||
|
||||
private failSession(message: string, session: number): void {
|
||||
if (session !== this.session || !this.isOpen()) return;
|
||||
this.finishSession(message);
|
||||
}
|
||||
|
||||
private finishSession(error?: string): void {
|
||||
const wasConnected = this.connection() === 'connected';
|
||||
const conversationId = this.remote?.conversationId ?? this.lastConversationId;
|
||||
this.rejectReady();
|
||||
this.finalizeAll();
|
||||
const messages = this.messages();
|
||||
this.teardown();
|
||||
if (wasConnected) this.sessionEnded$.next({ conversationId, messages, error });
|
||||
}
|
||||
|
||||
private abortStart(
|
||||
session: number,
|
||||
failure: { reason: VoiceStartFailure; message: string },
|
||||
): VoiceStartResult {
|
||||
if (session === this.session) this.teardown();
|
||||
return this.failure(failure.reason, failure.message);
|
||||
}
|
||||
|
||||
/** Releases every resource; idempotent. Invalidates all pending async work via `session`. */
|
||||
private teardown(): void {
|
||||
this.session++;
|
||||
this.streaming = false;
|
||||
this.resetTurnFlags();
|
||||
this.clearSettleTimer();
|
||||
this.clearError();
|
||||
if (this.interruptTimer) {
|
||||
clearTimeout(this.interruptTimer);
|
||||
this.interruptTimer = null;
|
||||
}
|
||||
|
||||
const transport = this.transport;
|
||||
this.transport = null;
|
||||
transport?.close();
|
||||
this.engine.stop();
|
||||
|
||||
// V04: tell the server the session is over (best effort).
|
||||
const remote = this.remote;
|
||||
this.remote = null;
|
||||
if (remote) this.closeRemote(remote);
|
||||
|
||||
this.connection.set('disconnected');
|
||||
this.state.set('IDLE');
|
||||
this.muted.set(false);
|
||||
}
|
||||
|
||||
private closeRemote(remote: { sessionId: string; csrf: string }): void {
|
||||
this.api.closeVoiceSession(remote.csrf, remote.sessionId).catch(() => {
|
||||
/* already closed / expired (e.g. 409 LIVE_SESSION_UNUSABLE): nothing to do */
|
||||
});
|
||||
}
|
||||
|
||||
private resetTurnFlags(): void {
|
||||
this.turnEnded = false;
|
||||
}
|
||||
|
||||
private clearSettleTimer(): void {
|
||||
if (this.settleTimer) {
|
||||
clearTimeout(this.settleTimer);
|
||||
this.settleTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private showError(message: string): void {
|
||||
this.clearError();
|
||||
this.streamError.set(message);
|
||||
this.errorTimer = setTimeout(() => this.clearError(), ERROR_BANNER_MS);
|
||||
}
|
||||
|
||||
private clearError(): void {
|
||||
if (this.errorTimer) {
|
||||
clearTimeout(this.errorTimer);
|
||||
this.errorTimer = null;
|
||||
}
|
||||
if (this.streamError() !== null) this.streamError.set(null);
|
||||
}
|
||||
|
||||
private resolveReady(): void {
|
||||
const waiter = this.readyWaiter;
|
||||
this.readyWaiter = null;
|
||||
if (!waiter) return;
|
||||
clearTimeout(waiter.timer);
|
||||
waiter.resolve();
|
||||
}
|
||||
|
||||
private rejectReady(error: Error = new Error('cancelled')): void {
|
||||
const waiter = this.readyWaiter;
|
||||
this.readyWaiter = null;
|
||||
if (!waiter) return;
|
||||
clearTimeout(waiter.timer);
|
||||
waiter.reject(error);
|
||||
}
|
||||
|
||||
// ---- error mapping ---------------------------------------------------------
|
||||
|
||||
private mapEngineError(err: unknown): { reason: VoiceStartFailure; message: string } {
|
||||
if (err instanceof MicrophoneError) {
|
||||
if (err.code === 'unsupported') return { reason: 'unsupported', message: MESSAGES.unsupported };
|
||||
return {
|
||||
reason: 'mic',
|
||||
message: err.code === 'denied' ? MESSAGES.micDenied : MESSAGES.micUnavailable,
|
||||
};
|
||||
}
|
||||
if (err instanceof VoiceEngineError && err.code === 'unsupported') {
|
||||
return { reason: 'unsupported', message: MESSAGES.unsupported };
|
||||
}
|
||||
return { reason: 'engine', message: MESSAGES.engine };
|
||||
}
|
||||
|
||||
/** Maps the catalog's error codes (§7) to a user-facing Persian message. */
|
||||
private mapApiError(err: unknown): { reason: VoiceStartFailure; message: string } {
|
||||
if (!(err instanceof VoiceApiError)) return { reason: 'api', message: MESSAGES.api };
|
||||
|
||||
switch (err.code) {
|
||||
case 'AUTH_REQUIRED':
|
||||
return { reason: 'auth', message: MESSAGES.auth };
|
||||
case 'RATE_LIMITED':
|
||||
return { reason: 'api', message: MESSAGES.rateLimited };
|
||||
case 'DEPENDENCY_UNAVAILABLE':
|
||||
return { reason: 'unavailable', message: MESSAGES.unavailable };
|
||||
case 'LIVE_SESSION_UNUSABLE':
|
||||
return { reason: 'api', message: MESSAGES.sessionUnusable };
|
||||
case 'NETWORK':
|
||||
return { reason: 'connect', message: MESSAGES.connect };
|
||||
default:
|
||||
return { reason: 'api', message: MESSAGES.api };
|
||||
}
|
||||
}
|
||||
|
||||
private failure(reason: VoiceStartFailure, message: string): VoiceStartResult {
|
||||
return { ok: false, reason, message };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { InjectionToken } from '@angular/core';
|
||||
|
||||
/**
|
||||
* Voice-to-voice state machine.
|
||||
* The server sends no explicit state events, so the client derives them:
|
||||
* LISTENING after session_ready, and after an assistant turn has finished playing
|
||||
* PROCESSING user transcript `completed`, assistant audio has not started yet
|
||||
* SPEAKING assistant audio is arriving / playing
|
||||
* INTERRUPTED transient (~150 ms) after the server's `turn_interrupted`, then LISTENING
|
||||
*/
|
||||
export type VoiceStreamState = 'IDLE' | 'LISTENING' | 'PROCESSING' | 'SPEAKING' | 'INTERRUPTED';
|
||||
export type VoiceConnection = 'disconnected' | 'connecting' | 'connected';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Backend contract: mvp_ui_api_catalog.md (§6, "Live Voice Conversations & WSS")
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface VoiceSource {
|
||||
source_ref: string;
|
||||
document_id: string;
|
||||
chunk_id: string;
|
||||
title: string;
|
||||
excerpt?: string;
|
||||
location?: { page?: number; section?: string };
|
||||
available?: boolean;
|
||||
}
|
||||
|
||||
export interface VoiceAudioFormat {
|
||||
encoding: string;
|
||||
sample_rate: number;
|
||||
channels: number;
|
||||
}
|
||||
|
||||
export type TranscriptStatus = 'partial' | 'completed' | 'interrupted';
|
||||
|
||||
export type VoiceServerEvent =
|
||||
| {
|
||||
type: 'session_ready';
|
||||
session_id: string;
|
||||
input_audio: VoiceAudioFormat;
|
||||
output_audio: VoiceAudioFormat;
|
||||
}
|
||||
| {
|
||||
type: 'transcript';
|
||||
turn_ref: string;
|
||||
role: 'user' | 'assistant';
|
||||
/**
|
||||
* Full text so far OR a new fragment: the catalog does not say which, so
|
||||
* `VoiceStreamService.mergeTranscriptText` accepts both (`completed` always carries the final text).
|
||||
*/
|
||||
text: string;
|
||||
status: TranscriptStatus;
|
||||
}
|
||||
| { type: 'sources'; turn_ref: string; tool_call_id: string; sources: VoiceSource[] }
|
||||
| { type: 'turn_interrupted'; turn_ref: string; cancelled_tool_call_ids: string[] }
|
||||
| {
|
||||
type: 'error';
|
||||
turn_ref?: string;
|
||||
error: { code: string; message: string; request_id?: string; retryable: boolean };
|
||||
};
|
||||
|
||||
export interface VoiceMessage {
|
||||
/** `${turn_ref}:${role}` */
|
||||
id: string;
|
||||
turnRef: string;
|
||||
role: 'user' | 'assistant';
|
||||
text: string;
|
||||
/** false while the text is still being recognized / generated */
|
||||
final: boolean;
|
||||
/** assistant message cut short by the user speaking over it */
|
||||
interrupted?: boolean;
|
||||
/** retrieved documents that back this answer */
|
||||
sources?: VoiceSource[];
|
||||
}
|
||||
|
||||
export interface VoiceSessionEnd {
|
||||
conversationId: string | null;
|
||||
messages: VoiceMessage[];
|
||||
/** User-facing (Persian) message when the session ended because of a failure. */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface VoiceStreamConfig {
|
||||
/** API prefix. */
|
||||
apiBase: string;
|
||||
/** Origin of the API; '' = same origin as the app (required for the `rag_session` cookie handshake). */
|
||||
apiOrigin: string;
|
||||
/** Fixed by the contract: 16 kHz up, 24 kHz down, mono PCM16. */
|
||||
inputSampleRate: number;
|
||||
outputSampleRate: number;
|
||||
frameMs: number;
|
||||
connectTimeoutMs: number;
|
||||
/** After playback drains without a `completed` assistant transcript, wait this long, then return to LISTENING. */
|
||||
settleMs: number;
|
||||
/** Folder (relative to <base href>) holding the two *.worklet.js files. */
|
||||
workletBasePath: string;
|
||||
}
|
||||
|
||||
export const DEFAULT_VOICE_STREAM_CONFIG: VoiceStreamConfig = {
|
||||
apiBase: '/api/v1',
|
||||
apiOrigin: '',
|
||||
inputSampleRate: 16000,
|
||||
outputSampleRate: 24000,
|
||||
frameMs: 20,
|
||||
connectTimeoutMs: 8000,
|
||||
settleMs: 700,
|
||||
workletBasePath: 'assets/worklets',
|
||||
};
|
||||
|
||||
/** Override in app.config.ts: `{ provide: VOICE_STREAM_CONFIG, useValue: { ...DEFAULT_VOICE_STREAM_CONFIG, apiOrigin: 'https://api.example.com' } }` */
|
||||
export const VOICE_STREAM_CONFIG = new InjectionToken<VoiceStreamConfig>('VOICE_STREAM_CONFIG', {
|
||||
providedIn: 'root',
|
||||
factory: () => DEFAULT_VOICE_STREAM_CONFIG,
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import { InjectionToken, inject } from '@angular/core';
|
||||
import { VOICE_STREAM_CONFIG, VoiceServerEvent } from './voice-stream.types';
|
||||
|
||||
export interface VoiceTransportHandlers {
|
||||
onEvent(event: VoiceServerEvent): void;
|
||||
onAudio(chunk: ArrayBuffer): void;
|
||||
/** Only called for closes the client did not ask for. */
|
||||
onClose(info: { clean: boolean; code: number; reason: string }): void;
|
||||
}
|
||||
|
||||
export interface VoiceTransport {
|
||||
connect(handlers: VoiceTransportHandlers): Promise<void>;
|
||||
/** PCM16 mono 16 kHz frame. */
|
||||
sendAudio(frame: ArrayBuffer): void;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
/** Drop mic frames instead of queueing when the socket is this far behind (~0.5 MB ≈ 16 s of audio). */
|
||||
const MAX_BUFFERED_BYTES = 512 * 1024;
|
||||
|
||||
/**
|
||||
* Plain WebSocket. Authentication is the `rag_session` cookie sent automatically on the handshake,
|
||||
* so the page must be served from the same site as the API. The contract has no client→server
|
||||
* JSON messages: the client only sends binary audio frames.
|
||||
*/
|
||||
export class WebSocketVoiceTransport implements VoiceTransport {
|
||||
private ws: WebSocket | null = null;
|
||||
private closedByClient = false;
|
||||
|
||||
constructor(
|
||||
private readonly url: string,
|
||||
private readonly connectTimeoutMs: number,
|
||||
) {}
|
||||
|
||||
connect(handlers: VoiceTransportHandlers): Promise<void> {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const ws = new WebSocket(this.url);
|
||||
ws.binaryType = 'arraybuffer';
|
||||
this.ws = ws;
|
||||
|
||||
let opened = false;
|
||||
const timer = setTimeout(() => {
|
||||
reject(new Error('connect-timeout'));
|
||||
this.close();
|
||||
}, this.connectTimeoutMs);
|
||||
|
||||
ws.onopen = () => {
|
||||
opened = true;
|
||||
clearTimeout(timer);
|
||||
resolve();
|
||||
};
|
||||
|
||||
ws.onmessage = (event: MessageEvent) => {
|
||||
if (typeof event.data === 'string') {
|
||||
try {
|
||||
handlers.onEvent(JSON.parse(event.data) as VoiceServerEvent);
|
||||
} catch {
|
||||
/* ignore malformed control frames */
|
||||
}
|
||||
} else if (event.data instanceof ArrayBuffer) {
|
||||
handlers.onAudio(event.data);
|
||||
}
|
||||
};
|
||||
|
||||
ws.onerror = () => {
|
||||
if (!opened) {
|
||||
clearTimeout(timer);
|
||||
reject(new Error('connect-failed'));
|
||||
}
|
||||
};
|
||||
|
||||
ws.onclose = (event: CloseEvent) => {
|
||||
clearTimeout(timer);
|
||||
if (!opened) {
|
||||
reject(new Error('connect-failed'));
|
||||
return;
|
||||
}
|
||||
if (!this.closedByClient) {
|
||||
handlers.onClose({ clean: event.wasClean, code: event.code, reason: event.reason });
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
sendAudio(frame: ArrayBuffer): void {
|
||||
const ws = this.ws;
|
||||
if (ws?.readyState === WebSocket.OPEN && ws.bufferedAmount < MAX_BUFFERED_BYTES) {
|
||||
ws.send(frame);
|
||||
}
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closedByClient = true;
|
||||
const ws = this.ws;
|
||||
this.ws = null;
|
||||
if (!ws) return;
|
||||
ws.onmessage = null;
|
||||
ws.onerror = null;
|
||||
try {
|
||||
ws.close(1000);
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Replace in tests, or to plug a different transport. */
|
||||
export const VOICE_TRANSPORT_FACTORY = new InjectionToken<(url: string) => VoiceTransport>(
|
||||
'VOICE_TRANSPORT_FACTORY',
|
||||
{
|
||||
providedIn: 'root',
|
||||
factory: () => {
|
||||
const config = inject(VOICE_STREAM_CONFIG);
|
||||
return (url: string) => new WebSocketVoiceTransport(url, config.connectTimeoutMs);
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -2,14 +2,6 @@
|
||||
display: block;
|
||||
}
|
||||
|
||||
:host-context(.has-messages) {
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.ai-chat-input-wrapper {
|
||||
width: 100%;
|
||||
max-width: 800px;
|
||||
@@ -27,9 +19,7 @@
|
||||
/* Layers cross-fade */
|
||||
.composer-layer,
|
||||
.voice-layer {
|
||||
transition:
|
||||
opacity 0.35s ease,
|
||||
transform 0.35s ease;
|
||||
transition: opacity 0.35s ease, transform 0.35s ease;
|
||||
}
|
||||
|
||||
.composer-layer {
|
||||
@@ -57,6 +47,13 @@
|
||||
transform: translateY(0) scale(1);
|
||||
pointer-events: auto;
|
||||
}
|
||||
:host-context(.has-messages) {
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
/* ---------- Chat composer ---------- */
|
||||
.chat-composer {
|
||||
@@ -69,30 +66,26 @@
|
||||
padding: 0.625rem 0.75rem;
|
||||
background: var(--surface-bg);
|
||||
border: 1px solid var(--surface-border);
|
||||
border-radius: 2rem;
|
||||
box-shadow:
|
||||
0 2px 12px rgba(0, 0, 0, 0.05),
|
||||
0 1px 3px rgba(0, 0, 0, 0.03);
|
||||
transition:
|
||||
box-shadow 0.2s ease,
|
||||
border-color 0.2s ease;
|
||||
border-radius: 1.5rem;
|
||||
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.03);
|
||||
transition: box-shadow 0.2s ease, border-color 0.2s ease;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.chat-composer:focus-within {
|
||||
border-color: var(--color-primary);
|
||||
box-shadow:
|
||||
0 4px 20px rgba(59, 130, 246, 0.12),
|
||||
0 1px 3px rgba(0, 0, 0, 0.03);
|
||||
box-shadow: 0 4px 20px rgba(59, 130, 246, 0.12), 0 1px 3px rgba(0, 0, 0, 0.03);
|
||||
}
|
||||
|
||||
.composer-textarea-wrapper {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
align-self: stretch;
|
||||
}
|
||||
|
||||
.composer-textarea {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-height: 24px;
|
||||
max-height: 192px;
|
||||
padding: 0.375rem 0;
|
||||
@@ -140,10 +133,7 @@
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background 0.2s ease,
|
||||
color 0.2s ease,
|
||||
transform 0.15s ease;
|
||||
transition: background 0.2s ease, color 0.2s ease, transform 0.15s ease;
|
||||
flex-shrink: 0;
|
||||
user-select: none;
|
||||
}
|
||||
@@ -208,9 +198,7 @@
|
||||
background: var(--surface-bg);
|
||||
border: 1px solid var(--surface-border);
|
||||
border-radius: 0.875rem;
|
||||
box-shadow:
|
||||
0 8px 30px rgba(0, 0, 0, 0.12),
|
||||
0 2px 8px rgba(0, 0, 0, 0.06);
|
||||
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12), 0 2px 8px rgba(0, 0, 0, 0.06);
|
||||
overflow: hidden;
|
||||
z-index: 50;
|
||||
animation: menuFadeIn 0.15s ease;
|
||||
@@ -318,9 +306,7 @@
|
||||
background: var(--surface-bg);
|
||||
border: 1px solid var(--surface-border);
|
||||
border-radius: 1.5rem;
|
||||
box-shadow:
|
||||
0 2px 12px rgba(0, 0, 0, 0.05),
|
||||
0 1px 3px rgba(0, 0, 0, 0.03);
|
||||
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.03);
|
||||
}
|
||||
|
||||
.orb-container {
|
||||
@@ -447,11 +433,7 @@
|
||||
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;
|
||||
transition: background 0.2s ease, color 0.2s ease, border-color 0.2s ease, transform 0.15s ease;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
@@ -571,3 +553,35 @@
|
||||
min-width: 160px;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- Live voice call (taller view for the running transcript) ---------- */
|
||||
.ai-chat-input-wrapper.stream-active {
|
||||
min-height: min(580px, 78vh);
|
||||
}
|
||||
|
||||
.send-btn svg {
|
||||
animation: sendIconIn 0.18s ease;
|
||||
}
|
||||
|
||||
@keyframes sendIconIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: scale(0.7);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.send-btn svg {
|
||||
animation: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.ai-chat-input-wrapper.stream-active {
|
||||
min-height: min(540px, 80vh);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
<div
|
||||
class="ai-chat-input-wrapper"
|
||||
[class.voice-active]="isVoiceMode()"
|
||||
[class.voice-active]="anyVoiceActive()"
|
||||
[class.stream-active]="streamOpen()"
|
||||
[attr.data-voice-state]="voiceState()"
|
||||
(keydown.escape)="onEscape()"
|
||||
>
|
||||
<!-- Announces every voice state change to screen readers -->
|
||||
<div class="sr-only" role="status" aria-live="polite">{{ statusText() }}</div>
|
||||
|
||||
<div class="composer-layer" [attr.inert]="isVoiceMode() ? '' : null">
|
||||
<div class="composer-layer" [attr.inert]="anyVoiceActive() ? '' : null">
|
||||
<div class="chat-composer" #composer>
|
||||
<button
|
||||
#plusBtn
|
||||
@@ -61,13 +62,26 @@
|
||||
<button
|
||||
type="button"
|
||||
class="composer-btn send-btn"
|
||||
[disabled]="!message().trim() || disabled()"
|
||||
(click)="sendMessage()"
|
||||
aria-label="ارسال پیام"
|
||||
[class.is-voice-call]="!canSend()"
|
||||
[disabled]="disabled()"
|
||||
[attr.aria-label]="actionLabel()"
|
||||
[attr.title]="actionLabel()"
|
||||
(click)="onPrimaryAction()"
|
||||
>
|
||||
@if (canSend()) {
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<path d="M12 19V5M5 12l7-7 7 7" />
|
||||
</svg>
|
||||
} @else {
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<path d="M2 10v3" />
|
||||
<path d="M6 6v11" />
|
||||
<path d="M10 3v18" />
|
||||
<path d="M14 8v7" />
|
||||
<path d="M18 5v13" />
|
||||
<path d="M22 10v3" />
|
||||
</svg>
|
||||
}
|
||||
</button>
|
||||
|
||||
@if (isAttachmentMenuOpen()) {
|
||||
@@ -136,9 +150,12 @@
|
||||
|
||||
<div
|
||||
class="voice-layer"
|
||||
[attr.inert]="isVoiceMode() ? null : ''"
|
||||
[attr.aria-hidden]="isVoiceMode() ? null : 'true'"
|
||||
[attr.inert]="anyVoiceActive() ? null : ''"
|
||||
[attr.aria-hidden]="anyVoiceActive() ? null : 'true'"
|
||||
>
|
||||
@if (layerMode() === 'stream') {
|
||||
<app-voice-stream-panel />
|
||||
} @else {
|
||||
<div class="voice-mode" role="region" aria-label="حالت صوتی">
|
||||
<div class="orb-container" #orbContainer aria-hidden="true">
|
||||
@if (!orbAvailable()) {
|
||||
@@ -190,5 +207,6 @@
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,3 +1,4 @@
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
@@ -21,6 +22,9 @@ import {
|
||||
SpeechTranscript,
|
||||
} from '../../../services/speech-recognition/speech-recognition.service';
|
||||
import { VoiceOrbService } from '../../../services/voice-orb/voice-orb.service';
|
||||
import { VoiceStreamService } from '../../../services/voice-stream/voice-stream.service';
|
||||
import { VoiceMessage } from '../../../services/voice-stream/voice-stream.types';
|
||||
import { VoiceStreamPanelComponent } from '../voice-stream-panel/voice-stream-panel.component';
|
||||
|
||||
export type VoiceState =
|
||||
| 'idle'
|
||||
@@ -49,6 +53,8 @@ export const DEFAULT_ATTACHMENT_ACTIONS: readonly AttachmentAction[] = [
|
||||
];
|
||||
|
||||
const NOTICE_TIMEOUT_MS = 7000;
|
||||
/** Keeps the previous voice view mounted while the layer fades out (matches the 0.35 s CSS fade). */
|
||||
const LAYER_SWAP_MS = 400;
|
||||
|
||||
const MIC_ERRORS: Record<string, string> = {
|
||||
unsupported: 'مرورگر شما از دسترسی به میکروفون پشتیبانی نمیکند (اتصال امن HTTPS لازم است).',
|
||||
@@ -70,6 +76,7 @@ const SPEECH_ERRORS: Record<SpeechErrorKind, string> = {
|
||||
@Component({
|
||||
selector: 'app-ai-chat-input',
|
||||
standalone: true,
|
||||
imports: [VoiceStreamPanelComponent],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
templateUrl: './ai-chat-input.component.html',
|
||||
styleUrl: './ai-chat-input.component.css',
|
||||
@@ -79,6 +86,7 @@ export class AiChatInputComponent implements OnDestroy {
|
||||
private readonly voiceOrb = inject(VoiceOrbService);
|
||||
private readonly mic = inject(MicrophoneService);
|
||||
private readonly speech = inject(SpeechRecognitionService);
|
||||
private readonly voiceStream = inject(VoiceStreamService);
|
||||
|
||||
// ---- API ------------------------------------------------------------------
|
||||
readonly placeholder = input<string>('پیام خود را بنویسید...');
|
||||
@@ -91,6 +99,8 @@ export class AiChatInputComponent implements OnDestroy {
|
||||
readonly messageSent = output<string>();
|
||||
readonly fileSelected = output<File>();
|
||||
readonly voiceToggled = output<boolean>();
|
||||
/** Emitted when a live voice call ends, with the full two-sided transcript. */
|
||||
readonly voiceSessionEnded = output<VoiceMessage[]>();
|
||||
|
||||
// ---- state ----------------------------------------------------------------
|
||||
readonly message = signal('');
|
||||
@@ -102,6 +112,14 @@ export class AiChatInputComponent implements OnDestroy {
|
||||
readonly liveInterim = signal('');
|
||||
readonly orbAvailable = signal(true);
|
||||
|
||||
// Live voice call (voice-to-voice stream)
|
||||
readonly streamOpen = this.voiceStream.isOpen;
|
||||
/** Which view the voice layer shows; swapped after the fade so nothing flashes. */
|
||||
readonly layerMode = signal<'dictation' | 'stream'>('dictation');
|
||||
readonly canSend = computed(() => !!this.message().trim());
|
||||
readonly anyVoiceActive = computed(() => this.isVoiceMode() || this.streamOpen());
|
||||
readonly actionLabel = computed(() => (this.canSend() ? 'ارسال پیام' : 'شروع گفتگوی صوتی'));
|
||||
|
||||
readonly voiceSupported = this.mic.isSupported && this.speech.isSupported;
|
||||
|
||||
/** The orb view replaces the composer while recording, transcribing and stopping. */
|
||||
@@ -155,6 +173,7 @@ export class AiChatInputComponent implements OnDestroy {
|
||||
/** Textarea content when recording started; dictated text is appended to it. */
|
||||
private baseText = '';
|
||||
private noticeTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private layerTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
constructor() {
|
||||
// The outside-click listener only exists while the menu is open.
|
||||
@@ -169,13 +188,23 @@ export class AiChatInputComponent implements OnDestroy {
|
||||
document.addEventListener('mousedown', onMouseDown);
|
||||
onCleanup(() => document.removeEventListener('mousedown', onMouseDown));
|
||||
});
|
||||
|
||||
this.voiceStream.sessionEnded$.pipe(takeUntilDestroyed()).subscribe(({ messages, error }) => {
|
||||
this.voiceToggled.emit(false);
|
||||
this.voiceSessionEnded.emit(messages);
|
||||
if (error) this.showNotice({ kind: 'error', text: error });
|
||||
this.scheduleLayerReset();
|
||||
this.focusTextarea();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.voiceSession++;
|
||||
this.speech.dispose();
|
||||
this.mic.release();
|
||||
this.voiceStream.dispose();
|
||||
this.voiceOrb.dispose();
|
||||
if (this.layerTimer) clearTimeout(this.layerTimer);
|
||||
this.clearNoticeTimer();
|
||||
}
|
||||
|
||||
@@ -297,11 +326,61 @@ export class AiChatInputComponent implements OnDestroy {
|
||||
if (this.isAttachmentMenuOpen()) {
|
||||
this.closeAttachmentMenu();
|
||||
this.plusBtnRef()?.nativeElement.focus();
|
||||
} else if (this.streamOpen()) {
|
||||
this.voiceStream.end();
|
||||
} else if (this.isVoiceMode()) {
|
||||
void this.stopVoice(true);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- live voice call (voice-to-voice stream) --------------------------------
|
||||
|
||||
/** Send arrow when there is text, waveform (start call) when the textarea is empty. */
|
||||
onPrimaryAction(): void {
|
||||
if (this.canSend()) {
|
||||
this.sendMessage();
|
||||
} else {
|
||||
void this.startVoiceStream();
|
||||
}
|
||||
}
|
||||
|
||||
async startVoiceStream(): Promise<void> {
|
||||
if (this.disabled() || this.streamOpen()) return;
|
||||
const dictating = this.voiceState() !== 'idle' && this.voiceState() !== 'error';
|
||||
if (dictating) return;
|
||||
|
||||
this.dismissNotice();
|
||||
this.closeAttachmentMenu();
|
||||
this.cancelLayerReset();
|
||||
this.layerMode.set('stream');
|
||||
this.voiceToggled.emit(true);
|
||||
|
||||
const result = await this.voiceStream.start();
|
||||
if (!result.ok) {
|
||||
// The call never connected, so no sessionEnded event is emitted for it.
|
||||
this.voiceToggled.emit(false);
|
||||
this.scheduleLayerReset();
|
||||
if (result.reason !== 'cancelled') {
|
||||
this.showNotice({ kind: 'error', text: result.message });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleLayerReset(): void {
|
||||
this.cancelLayerReset();
|
||||
this.layerTimer = setTimeout(() => {
|
||||
this.layerTimer = null;
|
||||
if (!this.streamOpen()) this.layerMode.set('dictation');
|
||||
}, LAYER_SWAP_MS);
|
||||
}
|
||||
|
||||
private cancelLayerReset(): void {
|
||||
if (this.layerTimer) {
|
||||
clearTimeout(this.layerTimer);
|
||||
this.layerTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- voice: start ---------------------------------------------------------
|
||||
|
||||
async toggleVoiceMode(): Promise<void> {
|
||||
@@ -322,8 +401,10 @@ export class AiChatInputComponent implements OnDestroy {
|
||||
}
|
||||
|
||||
private async startVoice(): Promise<void> {
|
||||
if (this.disabled()) return;
|
||||
if (this.disabled() || this.streamOpen()) return;
|
||||
|
||||
this.cancelLayerReset();
|
||||
this.layerMode.set('dictation');
|
||||
this.dismissNotice();
|
||||
this.closeAttachmentMenu();
|
||||
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
:host {
|
||||
display: block;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.stream-panel {
|
||||
direction: rtl;
|
||||
box-sizing: border-box;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 1rem 1.25rem 1.25rem;
|
||||
background: var(--surface-bg);
|
||||
border: 1px solid var(--surface-border);
|
||||
border-radius: 1.5rem;
|
||||
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.03);
|
||||
}
|
||||
|
||||
/* ---------- Orb ---------- */
|
||||
.orb-container {
|
||||
width: 170px;
|
||||
height: 170px;
|
||||
max-width: 100%;
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.orb-container canvas {
|
||||
display: block;
|
||||
width: 100% !important;
|
||||
height: 100% !important;
|
||||
}
|
||||
|
||||
.orb-fallback {
|
||||
width: 70%;
|
||||
height: 70%;
|
||||
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);
|
||||
animation: fallbackPulse 2.4s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes fallbackPulse {
|
||||
0%,
|
||||
100% {
|
||||
transform: scale(1);
|
||||
}
|
||||
50% {
|
||||
transform: scale(1.06);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- Status ---------- */
|
||||
.stream-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.status-text {
|
||||
margin: 0;
|
||||
font-size: 0.9375rem;
|
||||
color: var(--text-secondary);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.status-dot {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 50%;
|
||||
background: var(--muted);
|
||||
flex-shrink: 0;
|
||||
transition: background 0.3s ease;
|
||||
}
|
||||
|
||||
.stream-status[data-state='LISTENING'] .status-dot {
|
||||
background: #22c55e;
|
||||
animation: dotPulse 1.6s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.stream-status[data-state='PROCESSING'] .status-dot {
|
||||
background: #818cf8;
|
||||
animation: dotPulse 0.9s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.stream-status[data-state='SPEAKING'] .status-dot {
|
||||
background: #a78bfa;
|
||||
animation: dotPulse 0.7s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.stream-status[data-state='INTERRUPTED'] .status-dot {
|
||||
background: #f59e0b;
|
||||
}
|
||||
|
||||
@keyframes dotPulse {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
50% {
|
||||
opacity: 0.55;
|
||||
transform: scale(1.3);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- Transcript ---------- */
|
||||
.stream-transcript {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
max-width: 640px;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
padding: 0.25rem 0.25rem;
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
.stream-transcript::-webkit-scrollbar {
|
||||
width: 4px;
|
||||
}
|
||||
.stream-transcript::-webkit-scrollbar-thumb {
|
||||
background: var(--muted);
|
||||
border-radius: 9999px;
|
||||
}
|
||||
|
||||
.transcript-empty {
|
||||
margin: auto;
|
||||
font-size: 0.875rem;
|
||||
color: var(--muted);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* RTL: user bubbles sit on the right (start), assistant bubbles on the left (end). */
|
||||
.bubble-row {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.bubble-row.is-user {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.bubble {
|
||||
max-width: 85%;
|
||||
padding: 0.5rem 0.875rem;
|
||||
border-radius: 1.125rem;
|
||||
background: var(--sidebar-hover);
|
||||
color: var(--text-primary);
|
||||
font-size: 0.9375rem;
|
||||
line-height: 1.7;
|
||||
text-align: right;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
border-end-end-radius: 0.375rem;
|
||||
transition: opacity 0.2s ease;
|
||||
}
|
||||
|
||||
.bubble.is-user {
|
||||
background: var(--color-primary);
|
||||
color: #ffffff;
|
||||
border-end-end-radius: 1.125rem;
|
||||
border-end-start-radius: 0.375rem;
|
||||
}
|
||||
|
||||
.bubble.is-partial {
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.bubble.is-interrupted .bubble-text {
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.bubble-tag {
|
||||
margin-inline-start: 0.375rem;
|
||||
font-size: 0.75rem;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
/* ---------- Sources (retrieved documents) ---------- */
|
||||
.source-list {
|
||||
list-style: none;
|
||||
margin: 0.375rem 0 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.source-chip {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 0.375rem;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border: 1px solid var(--surface-border);
|
||||
border-radius: 0.625rem;
|
||||
background: var(--surface-bg);
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.75rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.source-chip.is-unavailable {
|
||||
opacity: 0.55;
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
.source-ref {
|
||||
flex-shrink: 0;
|
||||
padding: 0 0.375rem;
|
||||
border-radius: 9999px;
|
||||
background: var(--color-primary);
|
||||
color: #ffffff;
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* ---------- Retryable server error ---------- */
|
||||
.stream-error {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
width: 100%;
|
||||
max-width: 640px;
|
||||
box-sizing: border-box;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border: 1px solid rgba(239, 68, 68, 0.45);
|
||||
border-radius: 0.875rem;
|
||||
color: #dc2626;
|
||||
font-size: 0.8125rem;
|
||||
line-height: 1.6;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.stream-error span {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.stream-error-close {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.stream-error-close:focus-visible {
|
||||
outline: 2px solid var(--color-primary);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
/* ---------- Actions ---------- */
|
||||
.stream-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.625rem;
|
||||
flex-wrap: wrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
||||
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.status-dot,
|
||||
.orb-fallback,
|
||||
.stream-btn,
|
||||
.bubble,
|
||||
.stream-transcript {
|
||||
animation: none !important;
|
||||
transition: none !important;
|
||||
scroll-behavior: auto !important;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.stream-panel {
|
||||
gap: 0.5rem;
|
||||
padding: 0.75rem 0.75rem 1rem;
|
||||
}
|
||||
|
||||
.orb-container {
|
||||
width: 130px;
|
||||
height: 130px;
|
||||
}
|
||||
|
||||
.bubble {
|
||||
max-width: 92%;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.stream-btn {
|
||||
padding: 0.5rem 1rem;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
<div class="stream-panel" role="region" aria-label="گفتگوی صوتی" [attr.data-state]="state()">
|
||||
<div class="sr-only" role="status" aria-live="polite">{{ statusText() }}</div>
|
||||
|
||||
<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>
|
||||
|
||||
@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>
|
||||
}
|
||||
|
||||
<div class="stream-transcript" #scroller role="log" aria-label="متن گفتگو" aria-live="polite" aria-relevant="additions">
|
||||
@for (message of messages(); track message.role + message.id) {
|
||||
<div class="bubble-row" [class.is-user]="message.role === 'user'">
|
||||
<div
|
||||
class="bubble"
|
||||
[class.is-user]="message.role === 'user'"
|
||||
[class.is-partial]="!message.final"
|
||||
[class.is-interrupted]="message.interrupted"
|
||||
dir="rtl"
|
||||
>
|
||||
@if (message.text) {
|
||||
<span class="bubble-text">{{ message.text }}</span>
|
||||
}
|
||||
@if (message.interrupted) {
|
||||
<span class="bubble-tag">(قطع شد)</span>
|
||||
}
|
||||
@if (message.sources?.length) {
|
||||
<ul class="source-list" aria-label="منابع پاسخ">
|
||||
@for (source of message.sources ?? []; track source.source_ref + source.chunk_id) {
|
||||
<li
|
||||
class="source-chip"
|
||||
[class.is-unavailable]="source.available === false"
|
||||
[attr.title]="source.excerpt ?? null"
|
||||
>
|
||||
<span class="source-ref">{{ source.source_ref }}</span>
|
||||
<span class="source-label">{{ sourceLabel(source) }}</span>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
} @empty {
|
||||
<p class="transcript-empty">صحبت کنید؛ گفتگو اینجا نمایش داده میشود</p>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="stream-actions">
|
||||
<button
|
||||
type="button"
|
||||
class="stream-btn"
|
||||
[class.is-active]="muted()"
|
||||
[attr.aria-pressed]="muted()"
|
||||
[attr.aria-label]="muteLabel()"
|
||||
[attr.title]="muteLabel()"
|
||||
[disabled]="connection() !== 'connected'"
|
||||
(click)="toggleMute()"
|
||||
>
|
||||
@if (muted()) {
|
||||
<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">
|
||||
<line x1="2" x2="22" y1="2" y2="22" />
|
||||
<path d="M18.89 13.23A7.12 7.12 0 0 0 19 12v-2" />
|
||||
<path d="M5 10v2a7 7 0 0 0 12 5" />
|
||||
<path d="M15 9.34V5a3 3 0 0 0-5.68-1.33" />
|
||||
<path d="M9 9v3a3 3 0 0 0 5.12 2.12" />
|
||||
<line x1="12" x2="12" y1="19" y2="22" />
|
||||
</svg>
|
||||
} @else {
|
||||
<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 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z" />
|
||||
<path d="M19 10v2a7 7 0 0 1-14 0v-2" />
|
||||
<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">
|
||||
<line x1="18" x2="6" y1="6" y2="18" />
|
||||
<line x1="6" x2="18" y1="6" y2="18" />
|
||||
</svg>
|
||||
<span>پایان گفتگو</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,116 @@
|
||||
import {
|
||||
AfterViewInit,
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
ElementRef,
|
||||
OnDestroy,
|
||||
computed,
|
||||
effect,
|
||||
inject,
|
||||
signal,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
import { OrbMode, VoiceOrbService } from '../../../services/voice-orb/voice-orb.service';
|
||||
import { VoiceStreamService } from '../../../services/voice-stream/voice-stream.service';
|
||||
import { VoiceSource, VoiceStreamState } from '../../../services/voice-stream/voice-stream.types';
|
||||
|
||||
const ORB_MODE: Record<VoiceStreamState, OrbMode> = {
|
||||
IDLE: 'listening',
|
||||
LISTENING: 'listening',
|
||||
INTERRUPTED: 'listening',
|
||||
PROCESSING: 'processing',
|
||||
SPEAKING: 'speaking',
|
||||
};
|
||||
|
||||
/** Live call view: orb, status, running two-sided transcript, mute / end controls. */
|
||||
@Component({
|
||||
selector: 'app-voice-stream-panel',
|
||||
standalone: true,
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
templateUrl: './voice-stream-panel.component.html',
|
||||
styleUrl: './voice-stream-panel.component.css',
|
||||
})
|
||||
export class VoiceStreamPanelComponent implements AfterViewInit, OnDestroy {
|
||||
private readonly voice = inject(VoiceStreamService);
|
||||
private readonly orb = inject(VoiceOrbService);
|
||||
|
||||
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);
|
||||
|
||||
private readonly orbContainer = viewChild.required<ElementRef<HTMLDivElement>>('orbContainer');
|
||||
private readonly scroller = viewChild<ElementRef<HTMLDivElement>>('scroller');
|
||||
|
||||
readonly statusText = computed(() => {
|
||||
if (this.connection() === 'connecting') return 'در حال اتصال...';
|
||||
if (this.connection() === 'disconnected') return 'گفتگو پایان یافت';
|
||||
switch (this.state()) {
|
||||
case 'LISTENING':
|
||||
return this.muted() ? 'میکروفون بیصدا است' : 'در حال گوش دادن...';
|
||||
case 'PROCESSING':
|
||||
return 'در حال پردازش...';
|
||||
case 'SPEAKING':
|
||||
return 'در حال پاسخ دادن... (برای قطع کردن صحبت کنید)';
|
||||
case 'INTERRUPTED':
|
||||
return 'پاسخ قطع شد';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
});
|
||||
|
||||
readonly muteLabel = computed(() =>
|
||||
this.muted() ? 'فعالسازی میکروفون' : 'بیصدا کردن میکروفون',
|
||||
);
|
||||
|
||||
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;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
ngAfterViewInit(): void {
|
||||
const ready = this.orb.init(this.orbContainer().nativeElement);
|
||||
this.orbAvailable.set(ready);
|
||||
if (!ready) return;
|
||||
|
||||
this.orb.resetOrbGeometry();
|
||||
this.orb.setLevelProvider(() => this.voice.orbLevel());
|
||||
this.orb.startAnimation();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.orb.stopAnimation();
|
||||
this.orb.setLevelProvider(null);
|
||||
this.orb.setMode('listening');
|
||||
}
|
||||
|
||||
/** "عنوان — صفحه ۱، بند ۲" */
|
||||
sourceLabel(source: VoiceSource): string {
|
||||
const parts: string[] = [];
|
||||
if (source.location?.page != null) parts.push(`صفحه ${source.location.page}`);
|
||||
if (source.location?.section) parts.push(source.location.section);
|
||||
return parts.length ? `${source.title} — ${parts.join('، ')}` : source.title;
|
||||
}
|
||||
|
||||
dismissError(): void {
|
||||
this.voice.dismissError();
|
||||
}
|
||||
|
||||
toggleMute(): void {
|
||||
this.voice.toggleMute();
|
||||
}
|
||||
|
||||
endCall(): void {
|
||||
this.voice.end();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user