Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
57e8346d51 | ||
|
|
4dac437cc7 | ||
|
|
dc23dbeb69 | ||
|
|
a26c597d4f | ||
|
|
815191588c |
+1
-1
@@ -3,7 +3,7 @@
|
||||
"version": "0.0.0",
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
"start": "ng serve",
|
||||
"start": "ng serve --host 0.0.0.0",
|
||||
"build": "ng build",
|
||||
"watch": "ng build --watch --configuration development",
|
||||
"test": "ng test"
|
||||
|
||||
@@ -6,7 +6,7 @@ import { AuthService } from '../services/auth/auth.service';
|
||||
import { VoiceStreamService } from '../services/voice-stream/voice-stream.service';
|
||||
import { ThemeService } from '../services/theme/theme.service';
|
||||
|
||||
/** Navigation outside the assistant: document management is admin-only per the contract. */
|
||||
/** Settings remain discoverable; document-management operations require admin authority. */
|
||||
const BASE_NAV_ITEMS: NavItem[] = [
|
||||
{ icon: 'M12 5v14M5 12h14', label: 'چت جدید', route: '/' },
|
||||
{ icon: 'M4 4v16h16M8 20V11M12.5 20V6M17 20V9', label: 'گزارشات', route: '/reports' },
|
||||
@@ -53,11 +53,8 @@ export class LayoutComponent {
|
||||
|
||||
/** The signed-in identity exactly as the server reported it. */
|
||||
readonly userName = computed(() => this.authService.currentUserSubject.value?.username ?? '');
|
||||
/** Hiding a nav entry is only cosmetic: every request is still authorized server-side. */
|
||||
readonly navItems = computed<NavItem[]>(() => {
|
||||
const isAdmin = this.authService.currentUserSubject.value?.role === 'admin';
|
||||
return isAdmin ? BASE_NAV_ITEMS : BASE_NAV_ITEMS.filter((item) => item.route !== '/settings');
|
||||
});
|
||||
/** The settings page handles role-specific controls; the server authorizes each operation. */
|
||||
readonly navItems = signal<NavItem[]>(BASE_NAV_ITEMS);
|
||||
|
||||
onProfile(): void {
|
||||
this.sidebarOpen.set(false);
|
||||
|
||||
@@ -244,6 +244,47 @@
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
/* ---------- footnote row under the chat input: disclaimer + provider pill ---------- */
|
||||
.composer-footnote {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
padding: 0.4rem 0.75rem 0;
|
||||
max-width: 800px;
|
||||
margin-inline: auto;
|
||||
}
|
||||
|
||||
/* Fallback state (provider list failed to load, no pill to show): the footnote
|
||||
stacks as centered lines under the input instead of a squeezed side row. */
|
||||
.composer-footnote:has(.provider-picker.is-fallback) {
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.composer-footnote:has(.provider-picker.is-fallback) .composer-disclaimer {
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.composer-footnote:has(.provider-picker.is-fallback) app-voice-provider-picker {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.composer-disclaimer {
|
||||
margin: 0;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: 0.72rem;
|
||||
line-height: 1.8;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.composer-footnote app-voice-provider-picker {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* ---------- jump to latest ---------- */
|
||||
.jump-to-latest {
|
||||
position: absolute;
|
||||
@@ -330,4 +371,4 @@
|
||||
transition: none !important;
|
||||
animation: none !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,6 +61,12 @@
|
||||
(fileSelected)="onFileSelected($event)"
|
||||
(voiceToggled)="onVoiceToggled($event)"
|
||||
/>
|
||||
|
||||
<!-- footnote row under the input: disclaimer + selected provider pill -->
|
||||
<div class="composer-footnote" dir="rtl">
|
||||
<p class="composer-disclaimer">دستیار هوش مصنوعی ممکن است اشتباه کند؛ لطفاً پاسخها را بازبینی کنید.</p>
|
||||
<app-voice-provider-picker />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
@@ -17,6 +17,7 @@ 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 { VoiceProviderPickerComponent } from '../../shared/ui/voice-provider-picker/voice-provider-picker.component';
|
||||
import { VoiceStreamService } from '../../services/voice-stream/voice-stream.service';
|
||||
import { ThemeService } from '../../services/theme/theme.service';
|
||||
|
||||
@@ -41,7 +42,12 @@ const STICK_TO_BOTTOM_PX = 80;
|
||||
@Component({
|
||||
selector: 'app-home',
|
||||
standalone: true,
|
||||
imports: [AiChatInputComponent, VoiceStreamPanelComponent, VoiceTranscriptComponent],
|
||||
imports: [
|
||||
AiChatInputComponent,
|
||||
VoiceStreamPanelComponent,
|
||||
VoiceTranscriptComponent,
|
||||
VoiceProviderPickerComponent,
|
||||
],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
templateUrl: './home.page.html',
|
||||
styleUrl: './home.page.css',
|
||||
|
||||
@@ -120,6 +120,7 @@ describe('DocumentsService (backend handoff contract)', () => {
|
||||
|
||||
const req = httpMock.expectOne('/api/v1/documents/doc-1/retry');
|
||||
expect(req.request.method).toBe('POST');
|
||||
expect(req.request.serializeBody()).toBeNull();
|
||||
expect(req.request.headers.get('Idempotency-Key')).toBe('key-retry-1');
|
||||
req.flush({ job_id: 'job-1', status: 'queued' }, { status: 202, statusText: 'Accepted' });
|
||||
});
|
||||
|
||||
@@ -152,7 +152,7 @@ export class DocumentsService {
|
||||
): Observable<RetryResult> {
|
||||
return this.http.postRaw<RetryResult>(
|
||||
`${API}/documents/${encodeURIComponent(documentId)}/retry`,
|
||||
{},
|
||||
null,
|
||||
{ headers: this.idempotencyHeaders(idempotencyKey), skipToast: true },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -25,6 +25,10 @@ export class VoiceApiError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export type VoiceProvider = 'openai' | 'local_s2s' | 'gemini';
|
||||
export interface VoiceProviderOption { id: VoiceProvider; label: string; can_start: boolean; reason: string | null; }
|
||||
export interface VoiceProvidersResponse { default_provider: VoiceProvider; connection_checked: boolean; providers: VoiceProviderOption[]; }
|
||||
|
||||
export interface MeResponse {
|
||||
user: { id: string; username: string; role: string; organization_id: string };
|
||||
csrf_token: string;
|
||||
@@ -55,6 +59,7 @@ export interface ConversationResponse {
|
||||
}
|
||||
|
||||
export interface VoiceSessionResponse {
|
||||
provider?: VoiceProvider;
|
||||
session_id: string;
|
||||
conversation_id: string;
|
||||
status: string;
|
||||
@@ -84,8 +89,12 @@ export class VoiceApiService {
|
||||
}
|
||||
|
||||
/** F01: capabilities (the UI must check `voice` before offering a call). */
|
||||
configuration(): Promise<ConfigurationResponse> {
|
||||
return this.send(this.http.get<ConfigurationResponse>(this.url('/configuration'), this.readOptions()));
|
||||
configuration(provider?: VoiceProvider): Promise<ConfigurationResponse> {
|
||||
return this.send(this.http.get<ConfigurationResponse>(this.url('/configuration') + (provider ? '?provider=' + encodeURIComponent(provider) : ''), this.readOptions()));
|
||||
}
|
||||
|
||||
providers(): Promise<VoiceProvidersResponse> {
|
||||
return this.send(this.http.get<VoiceProvidersResponse>(this.url('/voice/sessions/providers'), this.readOptions()));
|
||||
}
|
||||
|
||||
/** C01: only `mode: "voice"` exists in the MVP. `clientRequestId` makes replays return the same conversation. */
|
||||
@@ -104,11 +113,12 @@ export class VoiceApiService {
|
||||
csrf: string,
|
||||
conversationId: string,
|
||||
clientRequestId: string,
|
||||
provider?: VoiceProvider,
|
||||
): Promise<VoiceSessionResponse> {
|
||||
return this.send(
|
||||
this.http.post<VoiceSessionResponse>(
|
||||
this.url('/voice/sessions'),
|
||||
{ conversation_id: conversationId, client_request_id: clientRequestId },
|
||||
{ conversation_id: conversationId, client_request_id: clientRequestId, ...(provider ? { provider } : {}) },
|
||||
this.writeOptions(csrf),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -56,6 +56,7 @@ type TransportMock = Omit<VoiceTransport, 'connect' | 'sendAudio' | 'sendControl
|
||||
describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
let service: VoiceStreamService;
|
||||
let api: {
|
||||
providers: ReturnType<typeof vi.fn>;
|
||||
me: ReturnType<typeof vi.fn>;
|
||||
configuration: ReturnType<typeof vi.fn>;
|
||||
createConversation: ReturnType<typeof vi.fn>;
|
||||
@@ -83,6 +84,10 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
engineClear = vi.fn();
|
||||
|
||||
api = {
|
||||
providers: vi.fn().mockResolvedValue({ default_provider: 'openai', connection_checked: false, providers: [
|
||||
{ id: 'openai', label: 'OpenAI', can_start: true, reason: null },
|
||||
{ id: 'local_s2s', label: 'سیستم جدید', can_start: true, reason: null },
|
||||
] }),
|
||||
me: vi.fn().mockResolvedValue(ME),
|
||||
configuration: vi.fn().mockResolvedValue(CONFIG),
|
||||
createConversation: vi.fn().mockResolvedValue(CONVERSATION),
|
||||
@@ -1067,4 +1072,49 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
expect(service.state()).toBe('LISTENING'); // completed turns finish immediately
|
||||
});
|
||||
});
|
||||
it('pins the selected provider in each new creation attempt', async () => {
|
||||
await service.loadProviders();
|
||||
await startConnected();
|
||||
expect(api.createVoiceSession.mock.calls[0][3]).toBe('openai');
|
||||
api.pollVoiceSession.mockResolvedValue({ session_id: 'ses-1', status: 'closed' });
|
||||
expect(await service.selectProvider('local_s2s')).toBe(true);
|
||||
expect(service.isOpen()).toBe(false);
|
||||
await startConnected();
|
||||
expect(api.createVoiceSession.mock.calls[1][3]).toBe('local_s2s');
|
||||
expect(api.createVoiceSession.mock.calls[1][2]).not.toBe(api.createVoiceSession.mock.calls[0][2]);
|
||||
});
|
||||
|
||||
it('keeps provider and request ids when the previous close is unconfirmed', async () => {
|
||||
await service.loadProviders();
|
||||
await startConnected();
|
||||
const previous = JSON.parse(sessionStorage.getItem('voice_creation_attempt')!);
|
||||
api.pollVoiceSession.mockResolvedValue({ session_id: 'ses-1', status: 'connected' });
|
||||
expect(await service.selectProvider('local_s2s')).toBe(false);
|
||||
expect(service.selectedProvider()).toBe('openai');
|
||||
expect(JSON.parse(sessionStorage.getItem('voice_creation_attempt')!)).toEqual(previous);
|
||||
expect(service.providerChoiceError()).toBeTruthy();
|
||||
api.pollVoiceSession.mockResolvedValue({ session_id: 'ses-1', status: 'closed' });
|
||||
expect(await service.selectProvider('local_s2s')).toBe(true);
|
||||
await startConnected();
|
||||
expect(api.createVoiceSession.mock.calls[1][3]).toBe('local_s2s');
|
||||
expect(api.createVoiceSession.mock.calls[1][2]).not.toBe(previous.sessionRequestId);
|
||||
});
|
||||
|
||||
it('rejects unavailable choices without touching the current call', async () => {
|
||||
await service.loadProviders();
|
||||
await startConnected();
|
||||
expect(await service.selectProvider('gemini')).toBe(false);
|
||||
expect(service.isOpen()).toBe(true);
|
||||
expect(api.closeVoiceSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses legacy default admission when an older backend has no provider discovery', async () => {
|
||||
service.selectedProvider.set('openai');
|
||||
api.providers.mockRejectedValue(new VoiceApiError(404, 'NOT_FOUND', 'missing'));
|
||||
await service.loadProviders();
|
||||
expect(service.selectedProvider()).toBeNull();
|
||||
await startConnected();
|
||||
expect(api.createVoiceSession.mock.calls[0][3]).toBeUndefined();
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Injectable, NgZone, computed, inject, isDevMode, signal } from '@angula
|
||||
import { Subject } from 'rxjs';
|
||||
import { MicrophoneError } from '../microphone/microphone.service';
|
||||
import { uuid } from '../../shared/utils/uuid';
|
||||
import { VoiceApiError, VoiceApiService, VoiceSessionResponse } from './voice-api.service';
|
||||
import { VoiceApiError, VoiceApiService, VoiceSessionResponse, VoiceProvider, VoiceProviderOption } from './voice-api.service';
|
||||
import { VoiceAudioEngine, VoiceEngineError } from './voice-audio-engine.service';
|
||||
import { VOICE_TRANSPORT_FACTORY, VoiceTransport } from './voice-transport';
|
||||
import {
|
||||
@@ -127,6 +127,10 @@ export class VoiceStreamService {
|
||||
private readonly createTransport = inject(VOICE_TRANSPORT_FACTORY);
|
||||
private readonly cues = inject(VoiceCueService);
|
||||
|
||||
readonly selectedProvider = signal<VoiceProvider | null>(null);
|
||||
readonly providerOptions = signal<VoiceProviderOption[]>([]);
|
||||
readonly providerChoiceError = signal('');
|
||||
readonly providerSwitching = signal(false);
|
||||
readonly state = signal<VoiceStreamState>('IDLE');
|
||||
readonly connection = signal<VoiceConnection>('disconnected');
|
||||
readonly messages = signal<VoiceMessage[]>([]);
|
||||
@@ -177,6 +181,7 @@ export class VoiceStreamService {
|
||||
|
||||
constructor() {
|
||||
this.attempt = loadPersistedAttempt();
|
||||
this.selectedProvider.set(this.attempt?.provider ?? null);
|
||||
// A reload during a call leaves an un-reconciled reservation: reconcile with the
|
||||
// server first (V02/V03), close what is still open, and drop the attempt. Media is
|
||||
// never auto-resumed — the user starts a fresh conversation explicitly.
|
||||
@@ -188,7 +193,59 @@ export class VoiceStreamService {
|
||||
|
||||
// ---- public API -----------------------------------------------------------
|
||||
|
||||
async loadProviders(): Promise<void> {
|
||||
try {
|
||||
const result = await this.api.providers();
|
||||
this.providerOptions.set(result.providers.filter(row => row.id !== 'gemini' || row.can_start || row.id === result.default_provider));
|
||||
this.providerChoiceError.set('');
|
||||
if (!this.isOpen() && !this.attempt && !this.selectedProvider()) {
|
||||
this.selectedProvider.set(result.default_provider);
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof VoiceApiError && err.status === 404 && !this.attempt && !this.isOpen()) {
|
||||
this.selectedProvider.set(null);
|
||||
}
|
||||
this.providerChoiceError.set('فهرست ارائهدهندگان دریافت نشد؛ انتخاب پیشفرض سرویس برقرار است.');
|
||||
}
|
||||
}
|
||||
|
||||
async selectProvider(provider: VoiceProvider): Promise<boolean> {
|
||||
if (this.providerSwitching()) return false;
|
||||
if (provider === this.selectedProvider()) return true;
|
||||
if (!this.providerOptions().some(row => row.id === provider && row.can_start)) return false;
|
||||
this.providerSwitching.set(true);
|
||||
this.providerChoiceError.set('');
|
||||
const previous = this.attempt;
|
||||
try {
|
||||
await this.close();
|
||||
// Changing provider must never discard an ambiguous reservation or reuse
|
||||
// its request ids with different arguments. Require a terminal server row.
|
||||
if (previous) {
|
||||
if (!previous.sessionId) throw new Error('Unresolved reservation');
|
||||
const me = await this.api.me();
|
||||
const status = await this.withTimeout(this.api.pollVoiceSession(me.csrf_token, previous.sessionId), CLOSE_WAIT_MS);
|
||||
if (!status || !['closed', 'failed'].includes(status.status)) throw new Error('Close not confirmed');
|
||||
}
|
||||
if (previous && this.attempt === previous) {
|
||||
this.attempt = null;
|
||||
clearPersistedAttempt();
|
||||
}
|
||||
this.selectedProvider.set(provider);
|
||||
return true;
|
||||
} catch {
|
||||
if (previous) { this.attempt = previous; persistAttempt(previous); }
|
||||
this.providerChoiceError.set('پایان تماس قبلی تأیید نشد؛ ارائهدهنده تغییر نکرد.');
|
||||
return false;
|
||||
} finally {
|
||||
this.providerSwitching.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
async start(options: { title?: string } = {}): Promise<VoiceStartResult> {
|
||||
if (this.providerSwitching()) return this.failure('cancelled', '');
|
||||
if (this.attempt?.provider && this.selectedProvider() && this.attempt.provider !== this.selectedProvider()) {
|
||||
return this.failure('api', 'ابتدا وضعیت تماس قبلی را مشخص کنید.');
|
||||
}
|
||||
if (this.isOpen()) return this.failure('cancelled', '');
|
||||
if (!this.isSupported) return this.failure('unsupported', MESSAGES.unsupported);
|
||||
|
||||
@@ -214,7 +271,7 @@ export class VoiceStreamService {
|
||||
this.connection.set('connecting');
|
||||
|
||||
// Reuse a persisted attempt (ambiguous outcome of a previous try); otherwise create one.
|
||||
if (!this.attempt) this.attempt = newCreationAttempt();
|
||||
if (!this.attempt) this.attempt = newCreationAttempt(this.selectedProvider());
|
||||
persistAttempt(this.attempt);
|
||||
|
||||
// 1) microphone + worklets (needs the user gesture; shows the permission prompt)
|
||||
@@ -242,7 +299,7 @@ export class VoiceStreamService {
|
||||
const me = await this.api.me();
|
||||
if (stale()) return this.failure('cancelled', '');
|
||||
|
||||
const configuration = await this.api.configuration();
|
||||
const configuration = await this.api.configuration(this.attempt?.provider);
|
||||
if (stale()) return this.failure('cancelled', '');
|
||||
if (!configuration.capabilities.voice) {
|
||||
return this.abortStart(session, { reason: 'unavailable', message: MESSAGES.voiceDisabled });
|
||||
@@ -1204,7 +1261,7 @@ export class VoiceStreamService {
|
||||
* replay — never new ids, never a blind retry of an unknown state.
|
||||
*/
|
||||
private async reserve(csrf: string, title: string): Promise<VoiceSessionResponse> {
|
||||
const attempt = this.attempt ?? newCreationAttempt();
|
||||
const attempt = this.attempt ?? newCreationAttempt(this.selectedProvider());
|
||||
this.attempt = attempt;
|
||||
|
||||
let activeCsrf = csrf;
|
||||
@@ -1238,6 +1295,7 @@ export class VoiceStreamService {
|
||||
activeCsrf,
|
||||
attempt.conversationId!,
|
||||
attempt.sessionRequestId,
|
||||
attempt.provider,
|
||||
);
|
||||
} catch (err) {
|
||||
const refreshed = await this.refreshAfterCsrfFailure(err);
|
||||
@@ -1254,6 +1312,7 @@ export class VoiceStreamService {
|
||||
activeCsrf,
|
||||
attempt.conversationId!,
|
||||
attempt.sessionRequestId,
|
||||
attempt.provider,
|
||||
);
|
||||
}
|
||||
} else if (err instanceof VoiceApiError && err.code === 'LIVE_SESSION_BUSY') {
|
||||
@@ -1358,12 +1417,14 @@ interface VoiceCreationAttempt {
|
||||
conversationId: string | null;
|
||||
sessionId: string | null;
|
||||
streamPath: string | null;
|
||||
provider?: VoiceProvider;
|
||||
}
|
||||
|
||||
const ATTEMPT_STORAGE_KEY = 'voice_creation_attempt';
|
||||
|
||||
function newCreationAttempt(): VoiceCreationAttempt {
|
||||
function newCreationAttempt(provider: VoiceProvider | null = null): VoiceCreationAttempt {
|
||||
return {
|
||||
...(provider ? { provider } : {}),
|
||||
conversationRequestId: uuid(),
|
||||
sessionRequestId: uuid(),
|
||||
conversationId: null,
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
:host {
|
||||
display: block;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.provider-picker {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
|
||||
.provider-pill-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
/* Fallback state (provider list failed to load, no pill): the error is the only
|
||||
content, so center it instead of pinning it to the end. */
|
||||
.provider-picker.is-fallback {
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* ---------- Pill trigger (like Claude's "Sonnet 5.5 Medium" badge) ---------- */
|
||||
.provider-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
padding: 0.2rem 0.6rem;
|
||||
border: 1px solid var(--surface-border);
|
||||
border-radius: 0.5rem;
|
||||
background: var(--sidebar-hover);
|
||||
color: var(--text-secondary);
|
||||
font-family: inherit;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 500;
|
||||
line-height: 1.6;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s ease, color 0.15s ease, border-color 0.15s ease;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.provider-pill:hover:not(:disabled) {
|
||||
background: var(--surface-border);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.provider-pill.is-open {
|
||||
border-color: var(--color-primary);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.provider-pill:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: wait;
|
||||
}
|
||||
|
||||
.provider-pill:focus-visible {
|
||||
outline: 2px solid var(--color-primary);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.provider-pill-dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: var(--color-success, #22c55e);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.provider-pill-dot.is-busy {
|
||||
background: var(--color-warning, #f59e0b);
|
||||
animation: pillPulse 1s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes pillPulse {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
opacity: 0.35;
|
||||
}
|
||||
}
|
||||
|
||||
.provider-pill-chevron {
|
||||
opacity: 0.6;
|
||||
transition: transform 0.18s ease;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.provider-pill.is-open .provider-pill-chevron {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
|
||||
/* ---------- Popover menu (opens upward, like the Claude screenshot) ---------- */
|
||||
.provider-menu {
|
||||
position: absolute;
|
||||
bottom: calc(100% + 0.5rem);
|
||||
inset-inline-end: 0;
|
||||
min-width: 290px;
|
||||
max-width: min(340px, calc(100vw - 2rem));
|
||||
background: var(--surface-bg);
|
||||
border: 1px solid var(--surface-border);
|
||||
border-radius: 0.875rem;
|
||||
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.16), 0 2px 8px rgba(0, 0, 0, 0.08);
|
||||
overflow: hidden;
|
||||
z-index: 60;
|
||||
animation: providerMenuIn 0.16s ease;
|
||||
}
|
||||
|
||||
@keyframes providerMenuIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(6px) scale(0.98);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0) scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
.provider-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
width: 100%;
|
||||
padding: 0.7rem 1rem;
|
||||
border: none;
|
||||
border-bottom: 1px solid var(--surface-border);
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font-family: inherit;
|
||||
text-align: start;
|
||||
cursor: pointer;
|
||||
transition: background 0.13s ease;
|
||||
}
|
||||
|
||||
.provider-item:last-of-type {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.provider-item:hover:not(:disabled),
|
||||
.provider-item:focus-visible:not(:disabled) {
|
||||
background: var(--sidebar-hover);
|
||||
}
|
||||
|
||||
.provider-item:focus-visible {
|
||||
outline: 2px solid var(--color-primary);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.provider-item:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.provider-item-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.1rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.provider-item-name {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.provider-item-reason {
|
||||
font-size: 0.75rem;
|
||||
color: var(--muted);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.provider-item-check {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
color: var(--color-primary);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.provider-menu-foot {
|
||||
padding: 0.55rem 1rem;
|
||||
border-top: 1px solid var(--surface-border);
|
||||
background: var(--sidebar-hover);
|
||||
color: var(--muted);
|
||||
font-size: 0.72rem;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
/* ---------- Inline error under the pill ---------- */
|
||||
.provider-error {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
max-width: 100%;
|
||||
padding: 0.2rem 0.55rem;
|
||||
border: 1px solid rgba(239, 68, 68, 0.4);
|
||||
border-radius: 0.5rem;
|
||||
background: rgba(239, 68, 68, 0.08);
|
||||
color: #dc2626;
|
||||
font-size: 0.72rem;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
/* Fallback state (provider list failed to load, no pill): the error is the only
|
||||
content, so it stretches full-width and centers like a footnote line under
|
||||
the chat input instead of hugging the side. */
|
||||
.provider-picker.is-fallback .provider-error {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
text-align: center;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
padding-inline: 0.75rem;
|
||||
}
|
||||
|
||||
.provider-error-close {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.provider-error-close:hover {
|
||||
background: rgba(239, 68, 68, 0.15);
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.provider-menu {
|
||||
min-width: min(270px, calc(100vw - 2rem));
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.provider-pill,
|
||||
.provider-pill-chevron,
|
||||
.provider-menu,
|
||||
.provider-item {
|
||||
transition: none !important;
|
||||
animation: none !important;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
<div class="provider-picker" #container dir="rtl" [class.is-fallback]="!options().length">
|
||||
@if (options().length) {
|
||||
<!-- Pill trigger pinned to the end of the footnote row (bottom-right in LTR screenshots, bottom-left in RTL) -->
|
||||
<div class="provider-pill-row">
|
||||
<button
|
||||
#trigger
|
||||
type="button"
|
||||
class="provider-pill"
|
||||
[class.is-open]="isOpen()"
|
||||
[disabled]="switching()"
|
||||
[attr.aria-expanded]="isOpen()"
|
||||
aria-haspopup="menu"
|
||||
aria-controls="voice-provider-menu"
|
||||
[attr.aria-label]="'ارائهدهنده: ' + selectedLabel() + ' — برای تغییر کلیک کنید'"
|
||||
(click)="toggleMenu()"
|
||||
>
|
||||
<span class="provider-pill-dot" [class.is-busy]="switching()" aria-hidden="true"></span>
|
||||
<span class="provider-pill-label">{{ switching() ? 'در حال تغییر…' : selectedLabel() }}</span>
|
||||
<svg
|
||||
class="provider-pill-chevron"
|
||||
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"
|
||||
>
|
||||
<path d="m6 9 6 6 6-6" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@if (isOpen()) {
|
||||
<div
|
||||
#menu
|
||||
id="voice-provider-menu"
|
||||
class="provider-menu"
|
||||
role="menu"
|
||||
aria-label="انتخاب ارائهدهندهٔ صدا"
|
||||
(keydown)="onMenuKeydown($event)"
|
||||
>
|
||||
@for (provider of options(); track provider.id) {
|
||||
<button
|
||||
type="button"
|
||||
class="provider-item"
|
||||
role="menuitemradio"
|
||||
[attr.aria-checked]="provider.id === selectedId()"
|
||||
[disabled]="!provider.can_start"
|
||||
[title]="!provider.can_start && provider.reason ? provider.reason : provider.label"
|
||||
(click)="choose(provider.id)"
|
||||
>
|
||||
<span class="provider-item-text">
|
||||
<span class="provider-item-name">{{ provider.label }}</span>
|
||||
@if (!provider.can_start) {
|
||||
<span class="provider-item-reason">{{ provider.reason || 'فعلاً در دسترس نیست' }}</span>
|
||||
} @else if (provider.id === selectedId()) {
|
||||
<span class="provider-item-reason">فعال برای گفتگوی بعدی</span>
|
||||
} @else {
|
||||
<span class="provider-item-reason">کلیک برای انتخاب</span>
|
||||
}
|
||||
</span>
|
||||
<span class="provider-item-check" aria-hidden="true">
|
||||
@if (provider.id === selectedId()) {
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M20 6 9 17l-5-5" />
|
||||
</svg>
|
||||
}
|
||||
</span>
|
||||
</button>
|
||||
}
|
||||
|
||||
<div class="provider-menu-foot">
|
||||
@if (callOpen()) {
|
||||
<span>تغییر ارائهدهنده تماس فعلی را پایان میدهد.</span>
|
||||
} @else {
|
||||
<span>انتخاب شما برای گفتگوی بعدی استفاده میشود.</span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
<!-- Load/switch failures render here: inside the footnote row, under the chat input.
|
||||
Kept outside the options guard on purpose — this error fires exactly when the
|
||||
provider list failed to load (options empty), so gating on options would hide it. -->
|
||||
@if (choiceError(); as err) {
|
||||
<div class="provider-error" role="status">
|
||||
<span>{{ err }}</span>
|
||||
<button type="button" class="provider-error-close" aria-label="بستن پیام" (click)="dismissError()">
|
||||
<svg width="12" height="12" 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>
|
||||
@@ -0,0 +1,139 @@
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
ElementRef,
|
||||
Injector,
|
||||
OnInit,
|
||||
afterNextRender,
|
||||
computed,
|
||||
effect,
|
||||
inject,
|
||||
signal,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
import { VoiceProvider } from '../../../services/voice-stream/voice-api.service';
|
||||
import { VoiceStreamService } from '../../../services/voice-stream/voice-stream.service';
|
||||
|
||||
/**
|
||||
* Claude-style provider picker that lives under the chat input.
|
||||
* A small pill shows the selected provider; clicking it opens a popover
|
||||
* menu with every provider option (checkmark on the active one).
|
||||
* All state lives in `VoiceStreamService` — this component only renders it.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-voice-provider-picker',
|
||||
standalone: true,
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
templateUrl: './voice-provider-picker.component.html',
|
||||
styleUrl: './voice-provider-picker.component.css',
|
||||
})
|
||||
export class VoiceProviderPickerComponent implements OnInit {
|
||||
private readonly injector = inject(Injector);
|
||||
private readonly voice = inject(VoiceStreamService);
|
||||
|
||||
readonly options = this.voice.providerOptions;
|
||||
readonly selectedId = this.voice.selectedProvider;
|
||||
readonly switching = this.voice.providerSwitching;
|
||||
readonly choiceError = this.voice.providerChoiceError;
|
||||
readonly callOpen = this.voice.isOpen;
|
||||
|
||||
readonly isOpen = signal(false);
|
||||
|
||||
readonly selectedOption = computed(() =>
|
||||
this.options().find((row) => row.id === this.selectedId()) ?? null,
|
||||
);
|
||||
|
||||
/** Pill text: backend label, or the legacy "service default" fallback. */
|
||||
readonly selectedLabel = computed(() => this.selectedOption()?.label ?? 'پیشفرض سرویس');
|
||||
|
||||
private readonly containerRef = viewChild<ElementRef<HTMLElement>>('container');
|
||||
private readonly menuRef = viewChild<ElementRef<HTMLDivElement>>('menu');
|
||||
private readonly triggerRef = viewChild<ElementRef<HTMLButtonElement>>('trigger');
|
||||
|
||||
constructor() {
|
||||
// Close on any pointer press outside the pill + menu, only while open.
|
||||
effect((onCleanup) => {
|
||||
if (!this.isOpen()) return;
|
||||
const onPointerDown = (event: PointerEvent): void => {
|
||||
const target = event.target as Node | null;
|
||||
if (target && this.containerRef()?.nativeElement.contains(target)) return;
|
||||
this.closeMenu();
|
||||
};
|
||||
document.addEventListener('pointerdown', onPointerDown);
|
||||
onCleanup(() => document.removeEventListener('pointerdown', onPointerDown));
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
void this.voice.loadProviders();
|
||||
}
|
||||
|
||||
toggleMenu(): void {
|
||||
if (this.switching()) return;
|
||||
const opening = !this.isOpen();
|
||||
this.isOpen.set(opening);
|
||||
if (opening) {
|
||||
afterNextRender(() => this.menuItems()[0]?.focus(), { injector: this.injector });
|
||||
}
|
||||
}
|
||||
|
||||
closeMenu(focusTrigger = false): void {
|
||||
if (!this.isOpen()) return;
|
||||
this.isOpen.set(false);
|
||||
if (focusTrigger) this.triggerRef()?.nativeElement.focus();
|
||||
}
|
||||
|
||||
async choose(provider: VoiceProvider): Promise<void> {
|
||||
if (provider === this.selectedId()) {
|
||||
this.closeMenu(true);
|
||||
return;
|
||||
}
|
||||
const ok = await this.voice.selectProvider(provider);
|
||||
// Keep the menu open on failure so the error stays visible next to it.
|
||||
if (ok) this.closeMenu(true);
|
||||
}
|
||||
|
||||
onMenuKeydown(event: KeyboardEvent): void {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
this.closeMenu(true);
|
||||
return;
|
||||
}
|
||||
const items = this.menuItems();
|
||||
if (!items.length) return;
|
||||
const index = items.indexOf(document.activeElement as HTMLElement);
|
||||
let next = -1;
|
||||
switch (event.key) {
|
||||
case 'ArrowDown':
|
||||
next = (index + 1) % items.length;
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
next = (index - 1 + items.length) % items.length;
|
||||
break;
|
||||
case 'Home':
|
||||
next = 0;
|
||||
break;
|
||||
case 'End':
|
||||
next = items.length - 1;
|
||||
break;
|
||||
case 'Tab':
|
||||
this.closeMenu();
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
items[next].focus();
|
||||
}
|
||||
|
||||
dismissError(): void {
|
||||
this.choiceError.set('');
|
||||
}
|
||||
|
||||
private menuItems(): HTMLElement[] {
|
||||
const menu = this.menuRef()?.nativeElement;
|
||||
return menu
|
||||
? Array.from(menu.querySelectorAll<HTMLElement>('[role="menuitemradio"]:not(:disabled)'))
|
||||
: [];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user