Author SHA1 Message Date
PeymanHonarjoo 102ce9b909 Merge branch 'feat/backend-changes' of http://git.raymandcti.com/p.honarjoo/faq_chatbot_frontend into feat/backend-changes 2026-10-13 09:32:29 +03:30
PeymanHonarjoo 3dddf1f12b fix(settings): center document table alignment and actions
The documents table headers and cells were inheriting text-align: right
from the RTL context, causing visual skewing. This change ensures they
are centered. Additionally, document actions are now centered within
their container.
2026-10-13 09:23:41 +03:30
11linear11 52202c2a35 Add live voice playback diagnostics and sample accounting 2026-10-12 17:52:20 -04:00
amirhosein mazaheri 58c3c20933 feat(voice): enhance audio stream lifecycle with sent_bytes validation and ref-attributed idle tracking 2026-10-12 18:51:05 +03:30
amirhosein mazaheri 89c6bc6d44 build: adjust initial and component style budgets in angular.json 2026-10-12 17:52:07 +03:30
amirhosein mazaheri 97427a1581 fix(voice): handle exact consumed-sample progress and direct native-rate playback 2026-10-12 17:51:52 +03:30
PeymanHonarjoo b3eb4a6de5 feat(settings): adjust document actions layout to prevent button wrapping 2026-10-12 17:30:23 +03:30
PeymanHonarjoo 9e8dd33927 feat: implement answer-limited state handling in voice stream service
- Introduced handling for 'answer_limited' events from the server, allowing the UI to reflect when an assistant's answer has reached the output-token limit.
- Updated the VoiceStreamService to manage limited and interrupted turns with bounded memory.
- Enhanced the transcript component to display appropriate messages for limited answers, including a fallback for unavailable text.
- Added styles to visually indicate limited answers in the UI.
- Created unit tests for the new functionality, ensuring correct behavior for limited answers and their presentation.
2026-10-12 16:51:04 +03:30
PeymanHonarjoo 0af55f52a3 feat(uuid): implement UUID generation for non-secure contexts and replace crypto.randomUUID() usage 2026-10-12 16:50:52 +03:30
PeymanHonarjoo e268631386 feat(voice): add audio cues for session lifecycle
Introduce VoiceCueService to play 'ready' and 'end' audio cues during
voice stream sessions. This provides auditory feedback when a session
starts and concludes.
2026-10-11 17:25:44 +03:30
PeymanHonarjoo a6c466e1ba feat(settings): implement document removal and responsive table layout
Add a confirmation workflow for removing documents and refactor the
documents table to support responsive layouts. The table now uses
a fixed layout with defined column widths and handles overflow on
mobile devices. The redundant filename column has been removed.
2026-10-11 17:25:28 +03:30
PeymanHonarjoo 2ac7a099b5 feat(ui): add ngx-toastr with zoneless compatibility
Add ngx-toastr and a proxy-based ToastrService wrapper that
manually triggers appRef.tick() to ensure toast notifications
render correctly in a zoneless change detection environment.
2026-10-11 17:24:52 +03:30
PeymanHonarjoo c1e7a8ac5a feat(sidebar): implement smooth expansion animations and RTL support
Add staggered transitions to sidebar labels to prevent text reflow during expansion. Update account menu to RTL direction and localize logout text. Refine collapsed sidebar layout for improved icon alignment.
2026-10-11 17:23:34 +03:30
PeymanHonarjoo e0b22868f2 refactor(ui): remove unused sourceKind and update text in chat questions 2026-10-11 11:01:27 +03:30
PeymanHonarjoo 28590c6dce refactor: overhaul home UI and audio playback reliability
Redesign the home page and voice stream panel into a compact dock
layout to improve the chat experience. Implement a flush mechanism in
the PCM playback worklet to handle the resampler tail, preventing
premature session termination due to phantom outstanding playback.
Fix document filter visibility in settings to ensure controls remain
accessible when no results match, and refactor transcript insertion
to maintain correct user/assistant ordering.
2026-10-10 17:47:51 +03:30
PeymanHonarjoo be17544f2d feat(voice): enhance streaming engine and improve system reliability
Improve the PCM playback worklet with robust resampling and buffer
management. Refactor the voice-stream service for better session
teardown and error handling. Fix authentication issues by enabling
credentials in HttpService and using relative URLs. Add Jalali date
support and an AI model configuration tab in settings. Enhance
diagnostics for voice transport and the audio engine.
2026-10-10 15:12:57 +03:30
Peyman Honarjoo ff7fcbc4bb build(ui): expand application shell and implement administrative dashboard pages
This commit significantly expands the application's routing, navigation, and administrative capabilities. It introduces several new functional modules and refines the core layout for a more professional, dashboard-oriented experience.

- **Routing & Navigation**:
  - Added routes for `wallboard`, `call-center`, `call-center/calls`, and `chat-questions`.
  - Updated `SidebarComponent` to include all new navigation items.
  - Enhanced `LayoutComponent` with dynamic navigation based on user roles (admin vs. user).
- **New Administrative Pages**:
  - `WallboardPage`: Implements a real-time KPI dashboard with call activity trends and outcome distributions.
  - `CallCenterPage`: Provides a symbolic interface for managing call center connectivity and synchronization.
  - `CallCenterCallsPage`: Implements a call history retrieval interface with filtering capabilities.
  - `ChatQuestionsPage`: Adds a module for reviewing user questions from web and mobile channels.
- **Core Infrastructure & Refinement**:
  - Updated `AppConfig` to include an `APP_INITIALIZER` for validating user identity via `AuthService` on startup.
  - Refined `HomeComponent` layout to a "Claude-style" continuous chat column.
  - Implemented global themed scrollbars and integrated the 'Lahze' font family.
  - Added `proxy.conf.json` and updated `angular.json` to support local backend development.
- **Documentation**:
  - Added comprehensive API handoff guides for frontend-backend connection and MVP API catalog.
2026-10-10 00:20:00 +03:30
Peyman Honarjoo 0b5a882ecb feat(reports): implement reports page and data visualization components
Implement a comprehensive reports dashboard including user question
summaries, AI performance metrics, and usage trends. This includes
the creation of several reusable chart components and supporting
services.

- Add `ReportsPage` with tabbed navigation for questions and performance
- Implement `ReportsService` with mock data support for rapid development
- Create reusable UI components: `BarChartComponent`, `DoughnutChartComponent`, and `LineChartComponent`
- Add `format.util.ts` for Persian digit and number formatting
- Integrate 'Lahze' font family and add font assets
- Add unit tests for `ReportsPage` and `ReportsService`
2026-10-09 17:48:18 +03:30
PeymanHonarjoo 72e7d0a007 refactor(core): improve auth flow and update service configurations
Refactor authentication handling and update environment-specific
configurations for local development.

- Update `LayoutComponent` to handle asynchronous logout and redirect
  to login page.
- Update `LoginPage` to navigate to home after successful submission.
- Hardcode API and image URLs to local development IP in `HttpService`
  and `VoiceStreamConfig`.
- Adjust typing animation delay in `HomePage` for more natural feel.
- Comment out unused settings items and update `AiChatInputComponent`
  border radius.
2026-10-08 13:45:30 +03:30
PeymanHonarjoo f6ce43453a 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.
2026-10-08 12:52:29 +03:30
PeymanHonarjoo 447849289e feat(auth): implement login page and authentication flow
Implement a complete authentication system including a new login page,
updated authentication service, and conditional routing.

- Add `LoginPage` component with animated UI and form validation
- Update `AuthService` to handle user sessions, CSRF tokens, and
  enhanced user data structures
- Implement conditional rendering in `App` component based on
  authentication state
- Add `postRaw` and `getRaw` methods to `HttpService` for direct
  API interaction
- Update routing to include login path and prepare for auth guards
- Add rate limiting error handling (429) in `HttpService`
2026-10-08 12:49:13 +03:30
Peyman Honarjoo 4db40bfc64 style(settings): update dark mode styles and improve component usability
- Replace direct attribute selectors with :host-context for better encapsulation
- Add pointer cursor to tab buttons
- Update background colors for settings cards and content in dark mode
2026-10-07 23:03:03 +03:30
Peyman Honarjoo dd0a661919 refactor(ui): optimize layout responsiveness and component positioning
- Switch to dynamic viewport height (dvh) for better mobile support
- Implement fixed positioning for chat input using :host-context
- Simplify home page layout logic and remove redundant padding
- Disable Angular CLI analytics in configuration
2026-10-07 23:02:57 +03:30
PeymanHonarjoo d22cd65e28 feat(ui): implement voice interaction and enhanced home page animations
Introduces a comprehensive voice interaction system and upgrades the home page
experience with dynamic typing effects and improved layout transitions.

Key changes:
- Added `MicrophoneService` for managing media stream lifecycle and permissions.
- Added `SpeechRecognitionService` for continuous speech-to-text processing.
- Added `VoiceOrbService` using Three.js to render an animated audio-reactive
  orb.
- Enhanced `HomePage` with a randomized typing effect for welcome titles
  and improved state management for message transitions.
- Refactored `AiChatInputComponent` to support seamless switching between
  text composer and voice recording modes.
- Improved `SidebarComponent` navigation logic and styling.
- Updated global styles and component CSS for better theme consistency
  and smoother animations.
2026-10-06 17:27:52 +03:30
PeymanHonarjoo 3a0001c30d feat(ui): implement home page and ai chat input with voice orb
Implement the core user interface components including the home page,
a sophisticated AI chat input component, and a 3D voice visualization
service using Three.js.

- Add `HomePage` component with responsive layout and theme integration.
- Add `AiChatInputComponent` supporting text, file attachments, and
  voice mode transitions.
- Implement `VoiceOrbService` using Three.js to provide a reactive
  3D animated orb for voice interaction.
- Update routing to include the new home page.
- Refactor `SettingsPage` to clean up unused RTL logic and improve
  UI styling.
- Adjust Angular build budgets in `angular.json` to accommodate
  increased bundle size from Three.js.
2026-10-06 12:03:02 +03:30
122 changed files with 20733 additions and 384 deletions
+90
View File
@@ -0,0 +1,90 @@
---
name: ponytail
description: >
Forces the laziest solution that actually works, simplest, shortest, most
minimal. Channels a senior dev who has seen everything: question whether the
task needs to exist at all (YAGNI), reach for the standard library before
custom code, native platform features before dependencies, one line before
fifty. Use whenever the user says "ponytail", "be lazy", "lazy mode",
"simplest solution", "minimal solution", "yagni", "do less", or "shortest
path", and whenever they complain about over-engineering, bloat, boilerplate,
or unnecessary dependencies.
license: MIT
metadata:
category: development
source:
repository: 'https://github.com/DietrichGebert/ponytail'
path: skills/ponytail
commit: a945778b4a73b0b78c3c781a594b62cd3a324637
---
# Ponytail
You are a lazy senior developer. Lazy means efficient, not careless. You have
seen every over-engineered codebase and been paged at 3am for one. The best
code is the code never written.
## Persistence
ACTIVE EVERY RESPONSE. No drift back to over-building. Still active if
unsure. Off only: "stop ponytail" / "normal mode".
## The ladder
Stop at the first rung that holds:
1. **Does this need to exist at all?** Speculative need = skip it, say so in one line. (YAGNI)
2. **Stdlib does it?** Use it.
3. **Native platform feature covers it?** `<input type="date">` over a picker lib, CSS over JS, DB constraint over app code.
4. **Already-installed dependency solves it?** Use it. Never add a new one for what a few lines can do.
5. **Can it be one line?** One line.
6. **Only then:** the minimum code that works.
The ladder is a reflex, not a research project. Two rungs work → take the
higher one and move on. The first lazy solution that works is the right one.
## Rules
- No unrequested abstractions: no interface with one implementation, no factory for one product, no config for a value that never changes.
- No boilerplate, no scaffolding "for later", later can scaffold for itself.
- Deletion over addition. Boring over clever, clever is what someone decodes at 3am.
- Fewest files possible. Shortest working diff wins.
- Complex request? Ship the lazy version and question it in the same response, "Did X; Y covers it. Need full X? Say so." Never stall on an answer you can default.
- Two stdlib options, same size? Take the one that's correct on edge cases. Lazy means writing less code, not picking the flimsier algorithm.
- Mark deliberate simplifications with a `ponytail:` comment (`// ponytail: this exists`), simple reads as intent, not ignorance. Shortcut with a known ceiling (global lock, O(n²) scan, naive heuristic)? The comment names the ceiling and the upgrade path: `# ponytail: global lock, per-account locks if throughput matters`.
## Output
Code first. Then at most three short lines: what was skipped, when to add it.
No essays, no feature tours, no design notes. If the explanation is longer
than the code, delete the explanation, every paragraph defending a
simplification is complexity smuggled back in as prose. Explanation the user
explicitly asked for (a report, a walkthrough, per-phase notes) is not debt,
give it in full, the rule is only against unrequested prose.
Pattern: `[code] → skipped: [X], add when [Y].`
## When NOT to be lazy
Never simplify away: input validation at trust boundaries, error handling
that prevents data loss, security measures, accessibility basics, anything
explicitly requested. User insists on the full version → build it, no
re-arguing.
Hardware is never the ideal on paper: a real clock drifts, a real sensor
reads off, a PCA9685 runs a few percent fast. Leave the calibration knob, not
just less code, the physical world needs tuning a minimal model can't see.
Lazy code without its check is unfinished. Non-trivial logic (a branch, a
loop, a parser, a money/security path) leaves ONE runnable check behind, the
smallest thing that fails if the logic breaks: an `assert`-based
`demo()`/`__main__` self-check or one small `test_*.py`. No frameworks, no
fixtures, no per-function suites unless asked. Trivial one-liners need no
test, YAGNI applies to tests too.
## Boundaries
Ponytail governs what you build, not how you talk (pair with Caveman for
terse prose). "stop ponytail" / "normal mode": revert.
The shortest path to done is the right path.
+12 -22
View File
@@ -26,22 +26,20 @@
"output": "assets"
}
],
"styles": [
"src/styles.css"
]
"styles": ["node_modules/ngx-toastr/toastr.css", "src/styles.css"]
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kB",
"maximumError": "1MB"
"maximumWarning": "2MB",
"maximumError": "3MB"
},
{
"type": "anyComponentStyle",
"maximumWarning": "4kB",
"maximumError": "8kB"
"maximumWarning": "20kB",
"maximumError": "30kB"
}
],
"outputHashing": "all"
@@ -56,6 +54,9 @@
},
"serve": {
"builder": "@angular/build:dev-server",
"options": {
"proxyConfig": "proxy.conf.json"
},
"configurations": {
"production": {
"buildTarget": "faq-chatbot:build:production"
@@ -74,24 +75,13 @@
"options": {
"tsConfig": "tsconfig.spec.json",
"runner": "vitest",
"buildTarget": "faq-chatbot:build:development",
"assets": [
{
"glob": "**/*",
"input": "public"
},
{
"glob": "**/*",
"input": "src/assets",
"output": "assets"
}
],
"styles": [
"src/styles.css"
]
"buildTarget": "faq-chatbot:build:development"
}
}
}
}
},
"cli": {
"analytics": false
}
}
@@ -0,0 +1,445 @@
# راهنمای اتصال UI به backend دستیار اسناد و مکالمهٔ صوتی
تاریخ تهیه: ۲۰۲۶-۱۰-۰۹
این فایل برای توسعه‌دهندهٔ frontend تهیه شده است تا UI موجود را به backend فعلی وصل کند. قرارداد مرورگر برای Gemini Live و OpenAI Realtime یکسان است؛ انتخاب provider و کلیدهای آن فقط سمت backend قرار دارند. فعلاً Gemini پیش‌فرض موقت است.
این راهنما دستور اتصال است و به معنی پذیرش اجراشدهٔ UI، کیفیت گفتار فارسی یا سخت‌افزار مرورگر نیست. نمونه‌های JSON شکل داده را نشان می‌دهند؛ شناسه، digest، revision و مسیر نشست باید از پاسخ واقعی سرور گرفته شوند.
## ۱. اطلاعاتی که تیم backend باید تحویل دهد
پیش از تست مشترک، جدول زیر با اطلاعات محیط واقعی تکمیل شود. جای‌خالی‌ها نباید به تنظیمات اجرایی تبدیل شوند.
| مورد | مقدار مورد توافق |
| ---------------------------------------------- | --------------------------------------------------------------- |
| آدرس backend قابل‌دسترسی از ماشین اجرای پراکسی | `TO_BE_PROVIDED`؛ پیش‌فرض محلی Compose: `http://localhost:8080` |
| آدرس و Origin دقیق UI | `TO_BE_PROVIDED`؛ نمونهٔ محلی: `http://localhost:5173` |
| نسخهٔ مشترک backend و فایل‌های نمونه | commit یا snapshot مورد توافق: `TO_BE_PROVIDED` |
| حساب تست administrator | نام کاربری و رمز از مسیر جداگانه و امن تحویل شوند |
| حساب تست user | نام کاربری و رمز از مسیر جداگانه و امن تحویل شوند |
| فایل نمونه برای آپلود و بازبینی انسانی | `TO_BE_PROVIDED` |
| سند آماده و انتخاب‌شده برای تست مکالمه | شناسهٔ واقعی و سؤال دارای پاسخ در همان سند: `TO_BE_PROVIDED` |
| آمادگی صوت و calibration | تیم backend وضعیت واقعی را اعلام کند؛ UI نیز F01 را بخواند |
| زمان تست مشترک مرورگر، میکروفن و بلندگو | `TO_BE_PROVIDED` |
اگر frontend و backend روی دو ماشین جدا اجرا می‌شوند، `localhost` در target پراکسی به ماشین frontend اشاره می‌کند. آدرس قابل‌دسترسی backend را جایگزین کنید.
کلید provider، رمز دیتابیس و فایل `.env` حاوی اسرار وارد کد، build، تنظیمات عمومی یا storage مرورگر نشوند. UI برای ورود فقط اطلاعات حساب کاربردی دریافت می‌کند.
## ۲. فایل‌های همراه و مرجع قرارداد
این فایل Markdown همراه با فایل‌های زیر تحویل شود. لینک‌ها نسبت به محل این فایل در repository هستند؛ برای تحویل خارج از repository، فایل‌های اشاره‌شده را نیز ارسال کنید.
| فایل | کاربرد |
| --------------------------------------------------------------- | --------------------------------------------------------------- |
| [راهنمای backend فاز ۳](realtime-agent-phase3-handoff.md) | قرارداد اسناد، review، retry، selection و تنظیمات توسعه |
| [راهنمای صوت](frontend-voice-integration-example.md) | جریان صوت، کنترل‌ها، رویدادها و recovery |
| [API catalog](../specifications/RAG-Phase1-API-Catalog.md) | قرارداد مرجع API؛ فقط endpointهای MVP در این تحویل استفاده شوند |
| [document-client.js](../../examples/document-client.js) | helper عملیات اسناد و configuration |
| [voice-client.js](../../examples/voice-client.js) | helper ورود، ساخت نشست، صوت و cleanup |
| [voice-audio-worklet.js](../../examples/voice-audio-worklet.js) | capture و playback و گزارش نمونه‌های واقعاً پخش‌شده |
| [vite-proxy.config.js](../../examples/vite-proxy.config.js) | پراکسی توسعهٔ HTTP و WebSocket |
helperها نمونهٔ توسعه‌اند؛ مدیریت صفحات، وضعیت UI، خطا، درخواست‌های لغوشده و ذخیرهٔ تلاش‌های نامطمئن بر عهدهٔ frontend است. در صورت اختلاف با یک پاسخ واقعی، کد خطا و request ID را به تیم backend بدهید؛ پاسخ یا قرارداد را خودسرانه بازتعریف نکنید.
## ۳. محدودهٔ UI و مسئولیت طرفین
| قابلیت | مسئولیت UI | مسئولیت backend |
| ---------- | ----------------------------------------------------------------- | ------------------------------------------------------- |
| ورود و نقش | فرم ورود، نگهداری وضعیت کاربر، نمایش قابلیت‌های مجاز | cookie، اعتبارسنجی حساب و مجوز هر درخواست |
| اسناد | آپلود، نمایش وضعیت، مرور شواهد، approve/reject، retry و selection | ذخیرهٔ immutable، پردازش worker، کنترل review و انتشار |
| صوت | میکروفن، playback، transcript، منابع، توقف و recovery | اتصال provider، ابزار جست‌وجو، lifecycle و کنترل دسترسی |
| خطا | پیام قابل‌فهم و اقدام مناسب، نگهداری شناسهٔ خطا | error envelope امن و correlation |
`admin` به اسناد، review، retry و selection دسترسی دارد. `admin` و `user` می‌توانند configuration را بخوانند و مکالمهٔ صوتی متعلق به خودشان را بسازند. پنهان‌کردن دکمه در UI جای کنترل مجوز سرور را نمی‌گیرد.
در MVP فعلی UI برای ثبت‌نام عمومی، مدیریت حساب، حذف سند، ویرایش configuration، انتخاب مدل/provider، public text chat یا تاریخچهٔ کامل و پایدار transcript ساخته نشود. routeهای deferred در API catalog به معنی route قابل‌استفاده نیستند.
## ۴. تنظیم اتصال محلی
### پراکسی same-origin
در مثال فعلی UI روی `http://localhost:5173` است و API از میزبان روی `8080` در دسترس خواهد بود. مرورگر تمام HTTPها را به `/api/v1/...` روی Origin خود UI می‌فرستد. پراکسی همان مسیر `/api` را بدون حذف prefix به backend منتقل می‌کند.
نمونهٔ Vite را در configuration موجود ادغام کنید؛ تنظیمات دیگر پروژه را جایگزین نکنید:
```js
export default {
server: {
host: 'localhost',
port: 5173,
strictPort: true,
proxy: {
'/api': {
target: 'http://127.0.0.1:8080',
ws: true,
changeOrigin: false,
},
},
},
};
```
`changeOrigin: false`، Host مرورگر را حفظ می‌کند. تیم backend برای این مثال محلی تنظیم کند:
```dotenv
TRUSTED_HOSTS=["localhost:5173","localhost:8080"]
TRUSTED_ORIGINS=["http://localhost:5173"]
COOKIE_SECURE=false
```
Host دوم برای دسترسی مستقیم محلی به health و schema است؛ اجرای mutation از Origin دیگری نیازمند تنظیم صریح همان Origin است. در محیط HTTPS، cookie باید Secure باشد و اتصال صوت WSS باشد. از wildcard برای CORS همراه credentials استفاده نشود. مرورگر برای میکروفن و AudioWorklet به secure context، مثل HTTPS یا localhost، نیاز دارد.
پیش‌فرض Docker Compose: API داخل container روی `8000` و روی میزبان با `${API_PORT:-8080}` منتشر می‌شود. اگر `API_PORT` عوض شد، target پراکسی را هماهنگ کنید. برای اجرای مستقیم مطابق این مثال، تیم backend از یک API process روی `8080` و worker جداگانه استفاده کند:
```sh
python -m app.server --host 0.0.0.0 --port 8080
python -m app.worker
```
آماده‌سازی دیتابیس، migration، حساب‌ها، storage، credentials و calibration وظیفهٔ تیم backend است. شروع worker می‌تواند provider call ایجاد کند و باید مطابق مجوز محیط انجام شود. frontend چند API worker یا reload برای محیط تست صوت درخواست نکند.
### تشخیص اتصال
با Host مجاز و backend آماده:
- `GET http://localhost:8080/health/live`: پاسخ `200` و `{"status":"ok"}`.
- `GET http://localhost:8080/health/ready`: پاسخ `200` هنگام readiness و `503` هنگام آماده‌نبودن.
- `GET http://localhost:8080/openapi.json`: schema محیط جاری.
- `http://localhost:8080/docs`: نمایش schema؛ اجرای درخواست‌های تعاملی نیز باید الزامات Origin/CSRF را رعایت کند.
پراکسی نمونه فقط `/api` را منتقل می‌کند؛ برای health از آدرس مستقیم مجاز استفاده کنید، یا مسیر health را صریحاً در پراکسی خود اضافه کنید. هیچ‌کدام از healthها گواه کیفیت provider نیستند.
## ۵. احراز هویت و قرارداد HTTP
تمام routeهای جدول‌های بعدی زیر `/api/v1` هستند.
| عملیات | درخواست | نتیجه |
| ---------------------- | --------------------------------------------- | -------------------------------- |
| ورود | `POST /auth/login` با `username` و `password` | `200`، cookie و user/CSRF/expiry |
| خواندن یا refresh هویت | `GET /me` | `200` با همان شکل هویت؛ یا `401` |
| خروج | `POST /auth/logout` بدون body | `204` بدون JSON |
| خواندن قابلیت‌ها | `GET /configuration` | `200` برای هر دو نقش |
نمونهٔ ورود:
```json
{ "username": "<test-account>", "password": "<password-from-login-form>" }
```
شکل پاسخ ورود و `/me`:
```json
{
"user": {
"id": "<server-user-id>",
"username": "<actual-username>",
"role": "admin",
"organization_id": "<server-organization-id>"
},
"csrf_token": "<server-csrf-token>",
"expires_at": "<server-ISO-timestamp>"
}
```
- cookie به نام `rag_session`، HttpOnly است؛ آن را از JavaScript نخوانید و token جایگزین نسازید.
- در معماری same-origin از `credentials: 'same-origin'` استفاده کنید.
- mutationهای authenticated، شامل upload و ساخت نشست، `X-CSRF-Token` می‌خواهند. CSRF از login یا `/me` گرفته شود. login خودش trusted Origin می‌خواهد.
- پس از reload ابتدا `/me` را بخوانید. روی `401` وضعیت authenticated را پاک و ورود مجدد را نمایش دهید.
- برای `FormData`، Content-Type را دستی ننویسید؛ browser باید boundary را بسازد. برای JSON از `application/json` استفاده کنید.
- پاسخ `204` را با `response.json()` نخوانید.
- `organization_id`، actor، reviewer یا مدل را برای تحمیل scope در درخواست‌ها اضافه نکنید.
configuration شامل `revision`، `assistant_name`، `instruction` و `capabilities` است. UI از مقادیر واقعی `text`، `voice`، `captions`، `supported_upload_types`، `max_upload_bytes`، `max_pdf_pages` و مشخصات audio استفاده کند. در صورت `voice=false`، شروع صوت غیرفعال و پیش‌نیاز به تیم backend اعلام شود؛ این flag گواه کیفیت گفتار نیست. `ocr_review_required` در configuration سیاست فعلی deployment است، نه سیاست همهٔ اسناد قبلی.
## ۶. جریان اسناد برای administrator
| عملیات | route | موفقیت و نکته |
| ------------------ | ----------------------------------------------------------- | ------------------------------------------------ |
| آپلود | `POST /documents` | `202`؛ multipart؛ required `Idempotency-Key` |
| فهرست | `GET /documents` | `200`؛ pagination و فیلتر |
| polling جزئیات | `GET /documents/{document_id}` | `200`؛ وضعیت واقعی processing/review/retry |
| شواهد pending | `GET /documents/{document_id}/extraction-review` | `200`؛ paginated |
| preview | مسیر `preview_path` در پاسخ شواهد | تصویر authenticated؛ بدون path ساخته‌شده توسط UI |
| تصمیم انسانی | `POST /documents/{document_id}/extraction-review/decisions` | `200`؛ JSON و required `Idempotency-Key` |
| retry همان job | `POST /documents/{document_id}/retry` | `202`؛ بدون body و required `Idempotency-Key` |
| خواندن selection | `GET /knowledge-selection` | `200` |
| جایگزینی selection | `PATCH /knowledge-selection` | `200`؛ کل مجموعه با expected revision |
### آپلود و وضعیت
body فقط یک `file` و `title` اختیاری دارد. title حداکثر ۲۰۰ کاراکتر است؛ محدودیت فایل را از configuration بخوانید. UI اعتبارسنجی اولیه انجام دهد، ولی format و محتوا را سرور تصمیم می‌گیرد.
```js
const uploadKey = crypto.randomUUID();
const uploaded = await documents.upload(file, title, uploadKey);
// uploaded.document_id و uploaded.job_id را از پاسخ واقعی نگه دارید.
```
هر upload با کلید تازه یک سند مستقل می‌سازد. برای نتیجهٔ نامطمئن همان File، title و کلید را نگه دارید و همان درخواست را replay کنید؛ تولید کلید جدید می‌تواند سند دیگری بسازد. کلید در header `Idempotency-Key` ارسال می‌شود. replay موفق header `Idempotency-Replayed: true` دارد؛ تغییر payload زیر همان کلید، `409 IDEMPOTENCY_CONFLICT` می‌دهد.
تا زمانی که document وضعیت `queued` یا `processing` دارد polling کنید؛ فاصلهٔ پیشنهادی دو ثانیه است، در tab پنهان آهسته‌تر شود. polling با خروج از صفحه لغو شود و پاسخ دیررس نتواند سند جدیدِ انتخاب‌شده در UI را بازنویسی کند. درصد پیشرفت ساختگی نمایش ندهید؛ از `job.stage` و وضعیت واقعی استفاده کنید.
| وضعیت یا فیلد پاسخ | رفتار UI |
| ---------------------------------- | -------------------------------------------- |
| `queued` / `processing` | نمایش انتظار و مرحله، ادامهٔ polling |
| `failed` و `review_required=true` | دریافت و نمایش شواهد pending |
| `failed` و `job.can_retry=true` | امکان retry صریح؛ علت خطا نیز نمایش داده شود |
| `failed` و `review_state=rejected` | نمایش رد؛ retry خودکار انجام نشود |
| `ready` و `is_active=false` | آمادهٔ انتخاب؛ هنوز وارد جست‌وجو نشده است |
| `searchable=true` | سند طبق پاسخ فعلی سرور قابل جست‌وجو است |
`job.error` ممکن است null یا شامل `code`، `message` و `retryable` باشد. امکان retry را از `job.can_retry` بگیرید؛ صرف `retryable=true` مجوز retry خودکار نیست.
فهرست اسناد `limit` پیش‌فرض ۲۰ و حداکثر ۱۰۰ دارد؛ فیلترهای `status` و `is_active` پشتیبانی می‌شوند. پاسخ شامل `items`، `next_cursor` و `knowledge_revision` است. cursor opaque است؛ آن را تغییر ندهید و در query URL encode کنید.
### review و سیاست OCR
شواهد review پیش‌فرض ۱۰ و حداکثر ۲۰ item در هر صفحه دارد. از `next_cursor` برای ادامه استفاده کنید. اگر مجموعه پس از تصمیم‌ها تغییر کرد و cursor نامعتبر شد، pendingها را دوباره از ابتدای مجموعه بخوانید. item شامل digest واقعی، `review_kind`، blocks، `required_checks` و preview احتمالی است.
UI برای انسان، متن دقیق، گروه‌های Q&A و تصویر موجود را نمایش دهد. تصمیم approve/reject و یادداشت از انسان گرفته شود؛ روی دکمهٔ approve تمام چک‌ها به‌طور خودکار تأیید نشوند.
```json
{
"evidence_sha256": "<digest-from-current-review-item>",
"decision": "approve",
"checked": ["<actual-required-check-names-confirmed-by-human>"],
"note": "<nonblank-human-review-note>",
"excluded_group_ids": []
}
```
برای approval، مجموعهٔ `checked` باید دقیقاً با چک‌های موردنیاز item تطبیق کند. note غیرخالی و حداکثر ۲۰۰۰ کاراکتر است. برای rejection نیز note لازم است؛ چک‌های تکمیل‌نشده را تأییدشده وانمود نکنید.
در review استخراج، `excluded_group_ids` باید خالی باشد. در `factual_corpus` فقط گروه‌های کامل موجود را می‌توان exclude کرد؛ دست‌کاری متن اصلی یا حذف نیمهٔ سؤال/پاسخ مجاز نیست. approval باید دست‌کم یک گروه factual واجد شرایط باقی بگذارد و placeholderهای نامعتبر را وارد corpus نکند. `preview_path` برای factual ممکن است null باشد.
سیاست `INGEST_OCR_REVIEW_REQUIRED` فقط تنظیم backend است، default آن true است و در هر job ثابت می‌ماند. UI از فیلدهای همان document استفاده کند:
- `ocr_review_required`: سیاست frozen آن سند.
- `review_required`: وجود تصمیم pending.
- `review_state`: `not_evaluated`، `not_required`، `pending`، `approved` یا `rejected`.
- `extraction_quality_decision`: null، `passed`، `reviewed` یا `partially_reviewed`؛ بدون ساختن ادعای تأیید انسانی.
false بودن سیاست OCR، review factual یا reviewهای دیگر را حذف نمی‌کند. UI toggle برای تغییر این سیاست ندارد. در preview از URL سرور با cookie استفاده کنید؛ path ذخیره‌سازی یا URL provider ساخته نشود.
approve به‌تنهایی retry، انتشار یا activation نمی‌کند. پس از تکمیل pendingها، detail را بخوانید و در صورت `job.can_retry=true`، retry صریح با کلید مستقل ارسال کنید. صفحات بعدی استخراج نیز ممکن است review تازه بخواهند. retry همان سند و همان job را ادامه می‌دهد. retry با body غیرخالی، `422 VALIDATION_ERROR` است.
### selection
برای اضافه یا حذف یک سند، ابتدا K01 را بخوانید، مجموعهٔ کامل جدید را بسازید و K02 را ارسال کنید:
```json
{
"expected_revision": 3,
"document_ids": ["<all-selected-document-ids-in-the-desired-new-set>"]
}
```
`expected_revision` در مثال فرضی است و باید از آخرین K01 بیاید. PATCH یک delta نیست؛ ارسال فقط یک ID می‌تواند بقیهٔ اسناد را حذف کند. شناسه‌ها unique و سندها ready باشند.
بعد از timeout یا `REVISION_CONFLICT` ابتدا K01 را دوباره بخوانید. درخواست قبلی ممکن است commit شده باشد؛ آن را کورکورانه تکرار نکنید. حذف سند فعال می‌تواند epoch را تغییر دهد و نشست‌های صوت قبلی را ببندد. UI منابع قدیمی را معتبر نمایش ندهد و ساخت مکالمهٔ تازه را پیشنهاد کند.
## ۷. ساخت و کنترل نشست صوت
| عملیات | route | کاربرد |
| ------ | ---------------------------------------------------- | ---------------------------------------------- |
| C01 | `POST /conversations` | ساخت owned conversation با `mode=voice`؛ `201` |
| V01 | `POST /voice/sessions` | رزرو session؛ `201` یا replay با `201/202` |
| V02 | `GET /voice/sessions/{session_id}` | وضعیت، diagnostics امن و toolهای اخیر |
| V03 | `GET /voice/sessions/by-request/{client_request_id}` | بازیابی رزرو بدون اتصال provider |
| V04 | `POST /voice/sessions/{session_id}/close` | بستن صریح بدون body؛ `200` |
| media | WebSocket روی `stream_path` دریافتی | یک اتصال فعال؛ cookie و Origin |
ابتدا C01 و سپس V01:
```json
{ "client_request_id": "<conversation-request-uuid>", "mode": "voice" }
```
```json
{ "conversation_id": "<id-from-C01>", "client_request_id": "<session-request-uuid>" }
```
این دو request ID جدا هستند و در JSON می‌آیند؛ با header کلید عملیات سند اشتباه نشوند. پاسخ V01 شامل `session_id`، `conversation_id`، `status`، `stream_path`، `expires_at` و `poll_url` است. مسیر اتصال را از `stream_path` بگیرید؛ route provider یا path ثابت اختراع نکنید.
برای نتیجهٔ نامطمئن، payload و IDهای همان تلاش حفظ و replay شوند. V03 برای reconciliation است و provider جدید باز نمی‌کند. نشست connected یا terminal اتصال media را از نو احیا نمی‌کند؛ recovery به معنی seamless reconnect نیست.
دو WebSocket هم‌زمان برای یک session ساخته نشود. پس از loss، وضعیت را از V02/V03 بگیرید، رزرو قدیمی را ببندید و با اقدام صریح کاربر مکالمه و نشست تازه بسازید. هنگام refresh صفحه، helper فعلی تلاش ایجاد را فقط در حافظهٔ همان instance نگه می‌دارد؛ اگر recovery بین reload لازم است، UI باید IDها و payload همان تلاش را بدون provider secret نگه دارد و ابتدا با سرور reconcile کند.
## ۸. راه‌اندازی helper و فایل صوت
در پروژهٔ UI، دو client module را در مسیر source قرار دهید و worklet را به‌عنوان asset مستقل از همان Origin سرو کنید. برای Vite می‌توان worklet را در `public/voice-audio-worklet.js` گذاشت و URL زیر را به constructor داد. متن worklet باید JavaScript باشد؛ fallback HTML مربوط به SPA برای این URL برنگردد.
```js
import { VoiceClient } from './integrations/voice-client.js';
import { DocumentClient } from './integrations/document-client.js';
// handleVoiceEvent و showFailure توابع UI خودتان هستند.
const voice = new VoiceClient(handleVoiceEvent, '/voice-audio-worklet.js');
const documents = new DocumentClient(voice);
async function signIn(username, password) {
const identity = await voice.login(username, password);
const configuration = await documents.configuration();
return { identity, configuration };
}
async function prepareVoice() {
const configuration = await documents.configuration();
if (!configuration.capabilities.voice) throw new Error('VOICE_UNAVAILABLE');
voice.newCreationAttempt(); // فقط برای یک تلاش واقعاً تازه
return voice.reserve();
}
// ابتدا prepareVoice موفق شود؛ سپس دکمهٔ شروع برای کاربر فعال شود.
// connect مستقیماً از gesture کاربر فراخوانی شود تا AudioContext مجاز باشد.
startButton.addEventListener('click', () => {
void voice.connect().catch(showFailure);
});
stopButton.addEventListener('click', () => {
void voice.close().catch(showFailure);
});
// logoutButton در handler خود voice.logout() را فراخوانی کند.
// route/component هنگام خروج باید voice.close() را await کند و خطا را مدیریت کند.
```
`prepareVoice` را با نشست فعال دوباره اجرا نکنید. پس از timeout ایجاد، به‌جای `newCreationAttempt` از `retryCreation()` همان تلاش استفاده کنید. شروع و cleanup باید برای هر connection مالکیت مشخص داشته باشند؛ جواب دیررس permission یا callback نشست قدیمی نباید نشست جدید را ببندد.
متدهای اصلی نمونه:
| client | متدها |
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| VoiceClient | `login`، `refreshIdentity`، `newCreationAttempt`، `reserve`، `retryCreation`، `recover`، `poll`، `connect`، `close`، `logout`، `freshSession` |
| DocumentClient | `configuration`، `upload`، `list`، `poll`، `review`، `decide`، `retry`، `selection`، `replace` |
برای recovery صوت، اگر از `freshSession()` استفاده می‌کنید آن را با gesture مناسب کاربر اجرا کنید و روی browser واقعی مجازبودن AudioContext را تست کنید. UI نباید پس از refresh یا قطع شبکه خودکار میکروفن را باز کند.
## ۹. قرارداد صوت و رویدادها
صوت در هر دو جهت raw mono signed PCM16 little-endian با نرخ **۲۴۰۰۰ Hz**، یک channel و بدون WAV header است؛ معادل ۴۸۰۰۰ byte در ثانیه. WebM، Opus یا blob خروجی MediaRecorder را روی این stream نفرستید. capture دستگاه باید به نرخ قرارداد تبدیل شود. helper و worklet این مسیر را پیاده می‌کنند و AudioContext با نرخ نامعتبر را رد می‌کنند.
میکروفن فقط پس از `session_ready` شروع به ارسال کند. سقف هر پیام binary در نمونهٔ فعلی ۹۶۰۰ byte است و طول باید sample-aligned باشد. capture و playback نمونه دارای دو سقف مستقل ۹۶۰۰۰ byte و ۱۰۰ پیام هستند. در adaptation، هر دو کنترل و cleanup آن‌ها حفظ شوند؛ ظرفیت پرشده باید با failure امن پایان یابد، نه با حذف بی‌صدای PCM و ادامهٔ همان context.
| رویداد سرور | رفتار UI |
| --------------------- | -------------------------------------------------------------------------- |
| `session_ready` | session ID و audio format را تطبیق دهید؛ آماده‌شدن واقعی را نمایش دهید |
| `user_speech_started` | turn جدید را با `turn_ref` ثبت کنید |
| `transcript` | برحسب turn و role، partial را به‌روز و completed را نهایی کنید |
| `sources` | منابع را به همان turn/tool call مرتبط کنید؛ منابع turnهای دیگر مخلوط نشوند |
| `audio_started` | `audio_ref` فعلی را برای binaryهای بعدی تعیین کنید |
| `audio_ended` | پایان generation همان audio ref؛ به معنی شنیده‌شدن نیست |
| `turn_interrupted` | صوت صف‌شده را flush و progress نهایی مصرف‌شده را گزارش کنید |
| `error` | خطای turn یا session را با قواعد راهنمای صوت مدیریت کنید |
شکل readiness:
```json
{
"type": "session_ready",
"session_id": "<reserved-session-id>",
"input_audio": { "encoding": "pcm_s16le", "sample_rate": 24000, "channels": 1 },
"output_audio": { "encoding": "pcm_s16le", "sample_rate": 24000, "channels": 1 }
}
```
شکل transcript:
```json
{
"type": "transcript",
"turn_ref": "<server-turn-ref>",
"role": "assistant",
"text": "<actual-transcript>",
"status": "completed"
}
```
تنها کنترل JSON از سمت client:
```json
{ "type": "playback_progress", "audio_ref": "<server-audio-ref>", "played_ms": 120 }
```
`played_ms` مقدار تجمعی واقعی است؛ از sampleهای مصرف‌شدهٔ worklet محاسبه می‌شود، نه elapsed timer، دریافت شبکه یا طول کل فایل. flush یا admission به معنی شنیدن نیست. مقدار را برای هر `audio_ref` جدا نگه دارید و گزارش نهایی interruption را بفرستید. helper این کار را انجام می‌دهد؛ UI کانال progress موازی با شمارش حدسی اضافه نکند.
برای sources از `source_ref`، title و location دریافتی استفاده کنید. location می‌تواند page یا section خالی داشته باشد. منبع، excerpt، لینک دانلود یا مسیر اصل سند را از خودتان نسازید؛ API دانلود اصل سند در این تحویل وجود ندارد. در polling، `available=false` یعنی excerpt قبلی معتبر نیست و نباید همچنان نمایش داده شود.
خطای canonical search برای turn واجد شرایط می‌تواند با توضیح صوتی امن ادامه یابد. خطای setup، transport، overflow، authority یا context sync نشست را متوقف می‌کند. fatal بودن را فقط از `retryable` استنتاج نکنید؛ رفتار helper و قرارداد guide را حفظ کنید. UI ابزار backend را خودش دوباره اجرا نمی‌کند.
### محدودیت‌های فعلی که در UX رعایت شوند
- Gemini فعلاً truncation نمونه‌دقیقِ تأییدشده برای context ندارد؛ interruption می‌تواند نشست را ببندد و نیازمند مکالمهٔ تازه باشد. seamless barge-in وعده داده نشود.
- ورودی commitنشده، شامل سکوت، سقف ده ثانیه دارد. UI ack یا مرز گفتار ساختگی برای دورزدن این محدودیت نفرستد؛ شکست و recovery را مطابق سرور مدیریت کند.
- transcript و منابع متعلق به نشست فعلی‌اند؛ history کامل و ماندگار وعده داده نشود.
- logout، خروج از صفحه و توقف باید trackهای میکروفن، worklet، AudioContext و WebSocket را آزاد کنند. در توقف عمدی، progress نهایی و V04 پیش از بسته‌شدن transport انجام شوند؛ `voice.close()` این ترتیب را اجرا می‌کند.
## ۱۰. خطا و بازیابی
شکل HTTP error:
```json
{
"error": {
"code": "REVISION_CONFLICT",
"message": "Request could not be completed.",
"request_id": "<correlation-uuid>",
"retryable": false
}
}
```
header `X-Request-ID` همان correlation را فراهم می‌کند؛ بعضی خطاها `details` دارند. متن خام error را به‌عنوان تنها UX استفاده نکنید؛ برحسب code پیام فارسی مناسب نمایش دهید. لایهٔ request در UI، status، code و request ID را حفظ کند. DocumentClient این فیلدها را ارائه می‌کند؛ VoiceClient.request نمونه فقط code/status را در exception نگه می‌دارد و برای diagnostics کامل باید metadata امن response را در adaptation حفظ کنید.
| کد یا وضعیت | اقدام |
| ----------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| `401 AUTH_REQUIRED` | cleanup رسانه و ورود مجدد؛ `/me` برای وضعیت هویت |
| `403 CSRF_INVALID` | در صورت باقی‌بودن هویت، refresh از `/me`؛ replay فقط با همان کلید/payload و پس از رفع علت |
| `403 FORBIDDEN` | بررسی نقش یا Host/Origin؛ درخواست تکراری بدون تغییر علت مفید نیست |
| `404 NOT_FOUND` | ID مخفی/حذف‌شده یا رزرو پیدا نشده؛ ابتدا نوع عملیات و تلاش ایجاد را بررسی کنید |
| `409 IDEMPOTENCY_CONFLICT` | payload زیر کلید تغییر کرده؛ تلاش اصلی را reconcile کنید |
| `409 REVISION_CONFLICT` | K01 جدید و اقدام کاربر بر اساس state تازه |
| `409 DOCUMENT_NOT_READY` | موارد rejected در details را نمایش دهید؛ selection ناقص نفرستید |
| `409 EXTRACTION_REVIEW_PENDING` | pendingها را بخوانید و review انسانی را تکمیل کنید |
| `409 DOCUMENT_NOT_RETRYABLE` | detail تازه و شرایط retry؛ دکمه بر اساس can_retry |
| `409 REVIEW_STALE` / `REVIEW_ALREADY_DECIDED` | شواهد و وضعیت تازه؛ approval قدیمی را روی output جدید کپی نکنید |
| `409 LIVE_SESSION_BUSY` | نشست موجود را reconcile کنید؛ اتصال دوم نسازید |
| `CONTEXT_REVOKED` / `CONVERSATION_STALE` | context و خروجی قدیمی را کنار بگذارید؛ نشست تازه، بدون کپی context revoked |
| `413 FILE_TOO_LARGE` / `PAYLOAD_TOO_LARGE` | محدودیت فایل یا envelope درخواست؛ تغییر اندازه به معنی تغییر payload است |
| `415 UNSUPPORTED_FILE_TYPE` | فایل مجاز طبق configuration انتخاب شود |
| `422 INVALID_FILE` / `VALIDATION_ERROR` | مشکل file یا شکل درخواست را اصلاح کنید |
| `429 RATE_LIMITED` | `Retry-After` را رعایت کنید؛ از retry burst جلوگیری کنید |
| `503 DEPENDENCY_UNAVAILABLE` / `CALIBRATION_REQUIRED` | آمادگی backend بررسی شود؛ نتیجهٔ mutation ممکن است نامطمئن باشد |
| قطع WebSocket یا API restart | cleanup، polling/reconciliation و تلاش تازهٔ صریح؛ ادامهٔ context فرضی ممنوع |
انتظار برای دریافت JSON در backend ۱۵ ثانیه و برای body خالی retry پنج ثانیه است؛ محدودیت envelope تصمیم ۶۰٬۱۵۱٬۰۷۲ byte و selection یک MiB است. این‌ها تضمین مدت تکمیل processing نیستند. تایم‌اوت کوتاه client به معنی rollback نیست. helper صوت HTTP deadline پنج ثانیه دارد؛ helper اسناد deadline اختصاصی ندارد و UI باید سیاست timeout و لغو خود را با حفظ semantics عملیات اضافه کند.
هیچ retry خودکار نباید کلید تازهٔ upload/decision/retry بسازد. K02 کلید عملیات سند ندارد و با revision کنترل می‌شود. پس از timeout آن K01 بخوانید. در logout حتی اگر V04 شکست خورد، تلاش برای A02 و پاک‌سازی محلی انجام شود؛ helper فعلی این کار را می‌کند.
در diagnostics فقط زمان، نوع عملیات، status، code، request/session/turn/audio refs لازم ثبت شوند؛ رمز، cookie، CSRF، audio، متن سند و متن خصوصی transcript در log ثبت نشوند.
## ۱۱. معیارهای تست مشترک UI و backend
| سناریو | نتیجهٔ مورد انتظار |
| ------------------------------------- | ------------------------------------------------------------------------- |
| ورود admin و user، reload و `/me` | هویت واقعی و مجوز صحیح؛ CSRF تازه |
| logout هنگام صوت | توقف میکروفن و پخش، revoke حساب session و UI خارج‌شده |
| user روی عملیات اسناد | دسترسی UI محدود و رد واقعی سرور |
| آپلود فایل تازه | document/job واقعی و مستقل، ابتدا inactive |
| timeout یا double-click آپلود | replay با همان کلید؛ سند تکراری ناخواسته ساخته نشود |
| فایل نامعتبر یا بیش‌ازحد | پیام برحسب code و حفظ امکان انتخاب فایل جدید |
| processing و تغییر صفحه | وضعیت واقعی، polling قابل‌لغو و عدم نمایش پاسخ دیررس برای سند دیگر |
| review چندصفحه‌ای و preview | شواهد واقعی، cookie، چک انسانی و تصمیم evidence-bound |
| approve/reject و retry | approve خودکار منتشر نکند؛ rejected ادامه نگیرد؛ retry همان job باشد |
| OCR اختیاری و factual | UI سیاست frozen سند و نیاز مستقل factual را رعایت کند |
| selection و revision conflict | ready-only، کل مجموعه، re-read پس از conflict یا timeout |
| قطع پاسخ C01/V01 | همان تلاش با UUID و payload قبلی replay/reconcile شود |
| شروع صوت با کلیک و permission ردشده | صدای واقعی یا پیام قابل‌فهم، بدون میکروفن یا context رهاشده |
| سؤال فارسی و پیگیری | transcript و sourceها به turn صحیح متصل باشند؛ شنیده‌شدن انسانی بررسی شود |
| پاسخ بی‌مدرک یا خطای جست‌وجو | منبع ساختگی نشان داده نشود؛ خطای turn با fatal session اشتباه نشود |
| interruption هنگام جست‌وجو و playback | صوت قدیمی متوقف، progress واقعی، recovery مطابق provider منتخب |
| قطع provider، شبکه و API restart | cleanup و state سرور روشن؛ اتصال خودکار به همان نشست فرض نشود |
| حذف سند از selection هنگام صوت | نشست قدیمی بی‌اعتبار و excerpt revoked پنهان شود |
| مرورگر یا tab دوم | نشست دیگر مجوز مالکیت ایجاد نکند؛ دو اتصال یک session رد شوند |
برای هر نتیجه، نوع محیط/browser، نسخهٔ مشترک، حساب/نقش بدون رمز، سناریو، زمان و request IDهای امن ثبت شود. provider و hardware واقعی جدا از mock بررسی شوند. هیچ خانهٔ اجرا‌نشده به‌عنوان pass ثبت نشود.
+628
View File
@@ -0,0 +1,628 @@
# RAG Assistant — Frontend MVP API Catalog & Integration Guide
این سند کاتالوگ دقیق و رسمی API برای تیم توسعه رابط کاربری (UI Developer) در فاز **MVP (Phase 1)** است. کلیه اندپوینت‌های غیرمرتبط با MVP (مانند چت متنی، هیستوری قدیمی، ویرایش تنظیمات و حذف فایل) از این کاتالوگ حذف شده‌اند.
---
## ۱. اصول عمومی و استانداردهای ارتباطی (Conventions & Auth)
* **Base URL**: `/api/v1` (روت‌های سلامت خارج از پیشوند هستند: `/health/live` و `/health/ready`).
* **فرمت داده**: تمام درخواست‌ها و پاسخ‌ها به صورت `application/json; charset=utf-8` هستند (به جز اندپوینت آپلود فایل که `multipart/form-data` است).
* **احراز هویت (Authentication)**:
* از کوکی امن HttpOnly به نام `rag_session` استفاده می‌شود که پس از لاگین به صورت خودکار توسط مرورگر ست می‌شود.
* تمام درخواست‌ها باید به همان مبدا (`Same-Origin`) یا مبدا مجاز فرستاده شوند (`credentials: "include"` در `fetch` یا Axios).
* **امنیت CSRF**:
* در کلیه درخواست‌های تغییر وضعیت (`POST` و `PATCH`) پس از لاگین، باید توکن CSRF در هدر فرستاده شود:
`X-CSRF-Token: <token_from_login_or_me>`
* **هدرهای ردیابی و همزمانی (Idempotency)**:
* `X-Request-ID`: شناسه اختیاری کلاینت برای ردیابی لاگ‌ها (در صورت ارسال نشدن، سرور یک مقدار تولید می‌کند).
* `Idempotency-Key`: هدر اجباری (فرمت UUID v4) برای عملیات‌های غیرتکرارپذیر:
* `POST /documents` (آپلود)
* `POST /documents/{id}/retry` (تلاش مجدد)
* `POST /documents/{id}/extraction-review/decisions` (ثبت تصمیم بازبینی)
* **ساختار استاندارد خطا (Error Envelope)**:
در تمامی خطاهای کلاینت/سرور (4xx و 5xx) ساختار پاسخ دقیقاً به این شکل است:
```json
{
"error": {
"code": "REVISION_CONFLICT",
"message": "Selection changed; reload and try again.",
"request_id": "req-98fbc182",
"retryable": false,
"details": {}
}
}
```
---
## ۲. احراز هویت و اطلاعات کاربر (Authentication)
### A01. ورود به سیستم (Login)
* **متد و آدرس**: `POST /api/v1/auth/login`
* **دسترسی**: عمومی (Public)
* **Request Headers**:
* `Content-Type: application/json`
* **Request Body**:
```json
{
"username": "demo.admin",
"password": "SecurePassword123"
}
```
* **Response (200 OK)**:
* مرورگر کوکی `rag_session` را دریافت می‌کند.
```json
{
"user": {
"id": "01000000-0000-4000-8000-000000000001",
"username": "demo.admin",
"role": "admin",
"organization_id": "02000000-0000-4000-8000-000000000001"
},
"csrf_token": "a1b2c3d4e5f6-csrf-token",
"expires_at": "2026-10-08T18:00:00Z"
}
```
* **خطاها**:
* `401 Unauthorized` (`INVALID_CREDENTIALS`): نام کاربری یا رمز عبور اشتباه است.
* `429 Too Many Requests` (`RATE_LIMITED`): تلاش‌های بیش از حد مجاز.
---
### A02. خروج از سیستم (Logout)
* **متد و آدرس**: `POST /api/v1/auth/logout`
* **دسترسی**: لاگین‌شده
* **Request Headers**:
* `X-CSRF-Token: <token>`
* **Response (204 No Content)**: بدون بدنه. کوکی پاک می‌شود و سشن‌های صوتی فعال کاربر بسته می‌شوند.
---
### A03. دریافت وضعیت و هویت کاربر جاری (Current User / Refresh Token)
* **متد و آدرس**: `GET /api/v1/me`
* **دسترسی**: لاگین‌شده
* **Response (200 OK)**:
```json
{
"user": {
"id": "01000000-0000-4000-8000-000000000001",
"username": "demo.admin",
"role": "admin",
"organization_id": "02000000-0000-4000-8000-000000000001"
},
"csrf_token": "a1b2c3d4e5f6-csrf-token",
"expires_at": "2026-10-08T18:00:00Z"
}
```
* **خطاها**:
* `401 Unauthorized` (`AUTH_REQUIRED`): کاربر لاگین نیست یا سشن منقضی شده است.
---
## ۳. تنظیمات و قابلیت‌های سیستم (Configuration - Read-only)
### F01. دریافت قابلیت‌ها و محدودیت‌ها (Capabilities)
UI باید قبل از رندر فرم آپلود یا فضای صوتی این اطلاعات را بخواند تا محدودیت‌های فایل و ویژگی‌های فعال را نمایش دهد.
* **متد و آدرس**: `GET /api/v1/configuration`
* **دسترسی**: لاگین‌شده (Admin یا User)
* **Response (200 OK)**:
```json
{
"revision": 1,
"assistant_name": "سامانه پاسخگوی فنی اسناد",
"instruction": "پاسخ‌ها را دقیق و صرفاً بر اساس مستندات مصوب و به زبان فارسی ارائه دهید.",
"capabilities": {
"text": false,
"voice": true,
"captions": true,
"supported_upload_types": [
"application/pdf",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"image/jpeg",
"image/png",
"text/markdown"
],
"max_upload_bytes": 20971520,
"max_pdf_pages": 50,
"supported_structure_notes": "پشتیبانی از ساختارهای بخشنامه‌ها، جداول، اینفوگرافیک و پرسش‌وپاسخ"
}
}
```
---
## ۴. مدیریت اسناد و پردازش (Admin Documents & Ingestion)
> **نکته دسترسی**: تمامی اندپوینت‌های این بخش نیاز به نقش `role: "admin"` دارند.
### D01. آپلود سند جدید (Upload Document)
* **متد و آدرس**: `POST /api/v1/documents`
* **Request Headers**:
* `Content-Type: multipart/form-data`
* `X-CSRF-Token: <token>`
* `Idempotency-Key: <uuid-v4>` (الزامی)
* **Form Data**:
* `file`: فایل انتخابی (Binary)
* `title`: (اختیاری) عنوان مدرک (حداکثر ۲۰۰ کاراکتر). در صورت عدم ارسال، نام فایل استفاده می‌شود.
* **Response (202 Accepted)**:
```json
{
"document_id": "10000000-0000-4000-8000-000000000001",
"job_id": "40000000-0000-4000-8000-000000000001",
"status": "queued",
"is_active": false,
"searchable": false
}
```
* **خطاها**:
* `413 Payload Too Large` (`FILE_TOO_LARGE`): فایل بزرگتر از `max_upload_bytes` است.
* `415 Unsupported Media Type` (`UNSUPPORTED_FILE_TYPE`): فرمت فایل غیرمجاز است.
* `409 Conflict` (`IDEMPOTENCY_CONFLICT`): ارسال مجدد با همان کلید اما با فایلی متفاوت.
---
### D02. لیست اسناد (List Documents)
* **متد و آدرس**: `GET /api/v1/documents`
* **Query Parameters**:
* `limit`: پیش‌فرض ۲۰، حداکثر ۱۰۰ (اختیاری)
* `cursor`: شناسه مکان‌نما برای صفحه بعد (اختیاری)
* `status`: فیلتر وضعیت: `queued` | `processing` | `ready` | `failed` (اختیاری)
* `is_active`: `true` | `false` (اختیاری)
* **Response (200 OK)**:
```json
{
"items": [
{
"id": "10000000-0000-4000-8000-000000000001",
"title": "دستورالعمل ساعات کاری",
"filename": "working-hours.pdf",
"status": "ready",
"is_active": true,
"searchable": true,
"chunk_count": 8,
"created_at": "2026-10-07T09:00:00Z",
"job": {
"id": "40000000-0000-4000-8000-000000000001",
"status": "succeeded",
"stage": "publish",
"attempt_count": 1,
"retry_generation": 0,
"can_retry": false,
"error": null
}
}
],
"next_cursor": null,
"knowledge_revision": 2
}
```
---
### D03. جزئیات و استعلام وضعیت پردازش سند (Document Detail / Polling)
کلاینت برای اسنادی که در وضعیت `queued` یا `processing` هستند، این اندپوینت را هر ۲ ثانیه Poll می‌کند تا به وضعیت پایانی (`ready` یا `failed`) برسد.
* **متد و آدرس**: `GET /api/v1/documents/{document_id}`
* **Response (200 OK)** (نمونه وضعیت نیازمند بازبینی):
```json
{
"id": "10000000-0000-4000-8000-000000000001",
"title": "ساعات کاری شعب",
"filename": "working-hours.pdf",
"status": "failed",
"is_active": false,
"searchable": false,
"created_at": "2026-10-07T09:00:00Z",
"chunk_count": 0,
"review_required": true,
"job": {
"id": "40000000-0000-4000-8000-000000000001",
"status": "failed",
"stage": "extract",
"attempt_count": 1,
"retry_generation": 0,
"can_retry": false,
"error": {
"code": "EXTRACTION_REVIEW_REQUIRED",
"message": "استخراج تصویر/صفحه نیازمند بازبینی و تایید ادمین است.",
"retryable": true
}
}
}
```
* **توضیح وضعیت `searchable`**:
`searchable = (status == "ready") && (is_active == true)`
---
### D06. دریافت شواهد نیازمند بازبینی (Extraction Review Candidates)
وقتی سندی خطای `review_required: true` خورده باشد، ادمین برای دیدن محتوای استخراج‌شده و مقایسه با تصویر اصلی از این اندپوینت استفاده می‌کند.
* **متد و آدرس**: `GET /api/v1/documents/{document_id}/extraction-review`
* **Response (200 OK)**:
```json
{
"document_id": "10000000-0000-4000-8000-000000000001",
"status": "failed",
"review_required": true,
"items": [
{
"evidence_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"review_kind": "extraction",
"location": {
"page": 1,
"section": "pdf/page/1"
},
"blocks": [
{
"block_id": "pdf/page/1/block/1",
"text": "ساعات کاری کلیه شعب در روزهای پنجشنبه از ساعت ۰۸:۰۰ الی ۱۲:۰۰ می‌باشد.",
"group_id": null
}
],
"required_checks": [
"readability",
"order",
"completeness",
"numbers",
"dates",
"negation",
"exceptions"
],
"decision": null,
"preview_path": "/api/v1/documents/10000000-0000-4000-8000-000000000001/extraction-review/e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855/preview"
}
],
"next_cursor": null
}
```
#### پیش‌نمایش تصویر (Preview Subresource):
آدرس داخل فیلد `preview_path` مستقیماً به صورت تگ `<img src="...">` (همراه با کوکی معتبر) قابل نمایش است و تصویر رندرشده صفحه را برمی‌گرداند (`Content-Type: image/jpeg` یا `image/png`).
---
### D07. ثبت تصمیم بازبینی (Submit Review Decision)
برای هر آیتم بازبینی، ادمین باید چک‌باکس‌های الزامی (`required_checks`) را تایید کرده و تصمیم خود را ثبت کند.
* **متد و آدرس**: `POST /api/v1/documents/{document_id}/extraction-review/decisions`
* **Request Headers**:
* `X-CSRF-Token: <token>`
* `Idempotency-Key: <uuid-v4>` (الزامی)
* **Request Body**:
```json
{
"evidence_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"decision": "approve",
"checked": [
"readability",
"order",
"completeness",
"numbers",
"dates",
"negation",
"exceptions"
],
"note": "متن با صفحه اصلی مقایسه و تاریخ و ساعت تایید شد.",
"excluded_group_ids": []
}
```
* **مقادیر فیلد `decision`**: فقط `"approve"` یا `"reject"`.
* **Response (200 OK)**:
```json
{
"document_id": "10000000-0000-4000-8000-000000000001",
"evidence_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"decision": "approve",
"review_required": false
}
```
*(اگر هنوز صفحات دیگری نیاز به بازبینی داشته باشند، `review_required: true` خواهد بود).*
---
### D04. تلاش مجدد برای پردازش سند (Retry Document)
پس از آنکه همه شواهد سندی که نیازمند بازبینی بوده تایید شد (یا اگر سندی به دلیل خطای شبکه در امبدینگ موقتاً fail شده بود)، این اندپوینت فراخوانی می‌شود تا ورکر ادامه پردازش را انجام دهد.
* **متد و آدرس**: `POST /api/v1/documents/{document_id}/retry`
* **Request Headers**:
* `X-CSRF-Token: <token>`
* `Idempotency-Key: <uuid-v4>` (الزامی)
* **Request Body**: ندارد (بدون بدنه).
* **Response (202 Accepted)**:
```json
{
"document_id": "10000000-0000-4000-8000-000000000001",
"job_id": "40000000-0000-4000-8000-000000000001",
"status": "queued",
"retry_generation": 1
}
```
* **خطاها**:
* `409 Conflict` (`EXTRACTION_REVIEW_PENDING`): هنوز آیتم‌های تاییدنشده برای این سند باقی مانده است.
* `409 Conflict` (`DOCUMENT_NOT_RETRYABLE`): سند در حال پردازش یا وضعیت غیرقابل تلاش مجدد است.
---
## ۵. انتخاب دانش فعال برای سرچ صوتی (Knowledge Selection)
این بخش وظیفه فعال یا غیرفعال کردن اسناد آماده (`ready`) را برای ورود به حوزه سرچ مدل صوتی بر عهده دارد.
### K01. دریافت لیست اسناد فعال (Get Selection)
* **متد و آدرس**: `GET /api/v1/knowledge-selection`
* **دسترسی**: فقط Admin
* **Response (200 OK)**:
```json
{
"revision": 2,
"access_epoch": 1,
"document_ids": [
"10000000-0000-4000-8000-000000000001"
]
}
```
---
### K02. تغییر لیست اسناد فعال (Replace Selection)
این عملیات جایگزین‌کننده کل لیست است (نه به صورت اضافه/کم کردن). ابتدا با `K01` لیست فعلی و `revision` را دریافت کنید، سپس تغییرات چک‌باکس‌ها را ارسال نمایید.
* **متد و آدرس**: `PATCH /api/v1/knowledge-selection`
* **دسترسی**: فقط Admin
* **Request Headers**:
* `X-CSRF-Token: <token>`
* **Request Body**:
```json
{
"expected_revision": 2,
"document_ids": [
"10000000-0000-4000-8000-000000000001",
"10000000-0000-4000-8000-000000000002"
]
}
```
* **Response (200 OK)**:
```json
{
"revision": 3,
"access_epoch": 1,
"document_ids": [
"10000000-0000-4000-8000-000000000001",
"10000000-0000-4000-8000-000000000002"
],
"conversations_invalidated": false
}
```
* **خطاها**:
* `409 Conflict` (`DOCUMENT_NOT_READY`): تلاش برای فعال‌سازی سندی که هنوز در وضعیت `ready` نیست.
* `409 Conflict` (`REVISION_CONFLICT`): ادمین دیگری همزمان پایگاه دانش را تغییر داده است (UI باید با `K01` مجدداً صفحه را به‌روز کند).
* **نکته**: اگر سندی غیرفعال (حذف از لیست) شود، فیلد `conversations_invalidated: true` خواهد شد و سشن‌های صوتی فعال گذشته متوقف می‌شوند تا اطلاعات نامعتبر به کاربر داده نشود.
---
## ۶. مکالمه صوتی زنده (Live Voice Conversations & WSS)
این بخش هسته تعامل کاربر و هوش مصنوعی در MVP است.
### C01. ایجاد مکالمه صوتی (Create Conversation)
* **متد و آدرس**: `POST /api/v1/conversations`
* **دسترسی**: لاگین‌شده (Admin یا User)
* **Request Headers**:
* `X-CSRF-Token: <token>`
* **Request Body**:
```json
{
"client_request_id": "50000000-0000-4000-8000-000000000001",
"mode": "voice",
"title": "مکالمه صوتی ساعت کاری"
}
```
*(در فاز MVP فقط مقدار `mode: "voice"` مجاز است).*
* **Response (201 Created)**:
```json
{
"id": "60000000-0000-4000-8000-000000000001",
"mode": "voice",
"title": "مکالمه صوتی ساعت کاری",
"status": "active",
"access_epoch": 1,
"created_at": "2026-10-07T09:05:00Z"
}
```
---
### V01. رزرو و ایجاد سشن صوتی لایو (Start Voice Session)
* **متد و آدرس**: `POST /api/v1/voice/sessions`
* **دسترسی**: مالک مکالمه
* **Request Headers**:
* `X-CSRF-Token: <token>`
* **Request Body**:
```json
{
"conversation_id": "60000000-0000-4000-8000-000000000001",
"client_request_id": "91000000-0000-4000-8000-000000000001"
}
```
* **Response (201 Created)**:
```json
{
"session_id": "a0000000-0000-4000-8000-000000000001",
"conversation_id": "60000000-0000-4000-8000-000000000001",
"status": "connecting",
"stream_path": "/api/v1/voice/sessions/a0000000-0000-4000-8000-000000000001/stream",
"expires_at": "2026-10-07T09:35:00Z",
"poll_url": "/api/v1/voice/sessions/a0000000-0000-4000-8000-000000000001"
}
```
*(آدرس `stream_path` مسیری است که فرانت‌اند بلافاصله به آن WebSocket متصل می‌کند).*
---
### V02. استعلام وضعیت سشن صوتی و شواهد اخیر (Poll Voice Session)
* **متد و آدرس**: `GET /api/v1/voice/sessions/{session_id}`
* **دسترسی**: مالک مکالمه
* **Response (200 OK)**:
```json
{
"session_id": "a0000000-0000-4000-8000-000000000001",
"status": "connected",
"close_reason": null,
"expires_at": "2026-10-07T09:35:00Z",
"recent_tool_results": [
{
"tool_call_id": "b0000000-0000-4000-8000-000000000001",
"status": "succeeded",
"created_at": "2026-10-07T09:08:00Z",
"sources": [
{
"source_ref": "S1",
"document_id": "10000000-0000-4000-8000-000000000001",
"chunk_id": "30000000-0000-4000-8000-000000000001",
"title": "دستورالعمل ساعات کاری",
"excerpt": "ساعات کاری شعب در روزهای پنجشنبه از ساعت ۰۸:۰۰ الی ۱۲:۰۰ می‌باشد.",
"location": {
"page": 1,
"section": "بند ۲ - ساعات اداری"
},
"available": true
}
]
}
]
}
```
---
### V04. پایان مکالمه صوتی (Close Voice Session)
* **متد و آدرس**: `POST /api/v1/voice/sessions/{session_id}/close`
* **دسترسی**: مالک مکالمه
* **Request Headers**:
* `X-CSRF-Token: <token>`
* **Response (200 OK)**:
```json
{
"session_id": "a0000000-0000-4000-8000-000000000001",
"status": "closed",
"close_reason": "user_requested"
}
```
---
### پروتکل وب‌سوکت استریم صوتی (WebSocket Stream Contract)
* **آدرس اتصال**: `wss://<host>/api/v1/voice/sessions/{session_id}/stream`
* **احراز هویت**: به صورت خودکار از طریق کوکی `rag_session` هنگام Handshake برقرار می‌شود.
#### ۱. فرمت صوت باینری (Binary Audio Frames):
* **ارسال از کلاینت به سرور (Microphone Input)**:
* فرمت باینری: `PCM 16-bit Little-Endian`
* نرخ نمونه‌برداری: `16,000 Hz (16 kHz)`
* تعداد کانال: `1 (Mono)`
* **دریافت از سرور به کلاینت (Speaker Output)**:
* فرمت باینری: `PCM 16-bit Little-Endian`
* نرخ نمونه‌برداری: `24,000 Hz (24 kHz)`
* تعداد کانال: `1 (Mono)`
#### ۲. پیام‌های کنترلی متنی (JSON Control Messages):
##### الف) اعلام آماده‌بودن سشن (`session_ready`):
```json
{
"type": "session_ready",
"session_id": "a0000000-0000-4000-8000-000000000001",
"input_audio": {
"encoding": "pcm_s16le",
"sample_rate": 16000,
"channels": 1
},
"output_audio": {
"encoding": "pcm_s16le",
"sample_rate": 24000,
"channels": 1
}
}
```
##### ب) زیرنویس و رونوشت زنده (`transcript`):
```json
{
"type": "transcript",
"turn_ref": "live-turn-1",
"role": "assistant",
"text": "طبق بخشنامه ساعات کاری شعب در پنجشنبه‌ها تا ساعت ۱۲ ظهر است.",
"status": "completed"
}
```
*(مقادیر `status`: `"partial"` برای متن در حال تولید، `"completed"` برای پایان پاسخ، `"interrupted"` در صورت قطع شدن توسط کاربر).*
##### ج) کارت منابع بازیابی‌شده (`sources`):
همزمان با پاسخ صوتی یا قبل از آن به فرانت‌اند فرستاده می‌شود تا در کنار زیرنویس رندر شود:
```json
{
"type": "sources",
"turn_ref": "live-turn-1",
"tool_call_id": "call-1",
"sources": [
{
"source_ref": "S1",
"document_id": "10000000-0000-4000-8000-000000000001",
"chunk_id": "30000000-0000-4000-8000-000000000001",
"title": "دستورالعمل ساعات کاری",
"location": {
"page": 1,
"section": "بند ۲"
}
}
]
}
```
##### د) وقفه توسط کاربر / Barge-in (`turn_interrupted`):
اگر کاربر در میان صحبت مدل شروع به صحبت کند:
```json
{
"type": "turn_interrupted",
"turn_ref": "live-turn-1",
"cancelled_tool_call_ids": ["call-1"]
}
```
*(کلاینت باید فورا صف بافر پخش صدا را خالی کرده و وضعیت رونوشت جاری را به Interrupted تغییر دهد).*
##### ه) خطا در استریم (`error`):
```json
{
"type": "error",
"turn_ref": "live-turn-1",
"error": {
"code": "SEARCH_TIMEOUT",
"message": "مهلت زمان جستجوی اسناد به پایان رسید.",
"request_id": "req-98fbc182",
"retryable": true
}
}
```
---
## ۷. برگه راهنمای کدهای خطا (Error Codes Quick Reference)
| کد HTTP | `error.code` | توضیح و اقدام پیشنهادی برای UI |
| :--- | :--- | :--- |
| `401` | `AUTH_REQUIRED` | ریدایرکت به صفحه لاگین |
| `401` | `INVALID_CREDENTIALS` | نمایش پیام "نام کاربری یا رمز عبور نامعتبر است" |
| `403` | `CSRF_INVALID` | درخواست توکن مجدد از `/api/v1/me` و تکرار درخواست |
| `404` | `NOT_FOUND` | منبع یافت نشد |
| `409` | `REVISION_CONFLICT` | رفرش مجدد وضعیت با `GET /knowledge-selection` |
| `409` | `DOCUMENT_NOT_READY` | فقط اسناد وضعیت `ready` قابلیت فعال‌سازی دارند |
| `409` | `EXTRACTION_REVIEW_PENDING` | قبل از زدن دکمه Retry، باید شواهد تایید شوند |
| `409` | `IDEMPOTENCY_CONFLICT` | اصلاح کلید یا عدم ارسال دیتای متفاوت با کلید قبلی |
| `409` | `LIVE_SESSION_UNUSABLE` | سشن صوتی بسته شده؛ باید سشن جدید با `V01` ساخته شود |
| `413` | `FILE_TOO_LARGE` | نمایش خطای حجم بالای فایل طبق `max_upload_bytes` |
| `415` | `UNSUPPORTED_FILE_TYPE` | نمایش فرمت‌های مجاز اعلام‌شده در `F01` |
| `429` | `RATE_LIMITED` | نمایش پیام صبر و محدودیت نرخ درخواست |
| `503` | `DEPENDENCY_UNAVAILABLE` | خطای موقت سرور/پایگاه داده؛ درخواست بررسی اتصال |
+129 -62
View File
@@ -21,6 +21,7 @@
"@popperjs/core": "^2.11.8",
"ag-grid-angular": "^36.2.0",
"ag-grid-community": "^36.2.0",
"moment-jalaali": "^0.10.5",
"ngx-toastr": "^14.3.0",
"papaparse": "^5.7.0",
"rxjs": "~7.8.0",
@@ -34,6 +35,8 @@
"@playwright/test": "^1.63.0",
"@tailwindcss/postcss": "^4.3.3",
"@types/audioworklet": "^0.0.100",
"@types/moment": "^2.11.29",
"@types/moment-jalaali": "^0.7.9",
"@types/papaparse": "^5.5.2",
"@types/three": "^0.186.0",
"jsdom": "^30.1.2",
@@ -541,7 +544,6 @@
"version": "20.3.33",
"resolved": "https://registry.npmjs.org/@angular/compiler-cli/-/compiler-cli-20.3.33.tgz",
"integrity": "sha512-NKE4N4ssXysHLJQ7xVqvAv/yf3JfJxaFz5H+Ue+EnYToAmTxXe7uyt2MPRIydef/H63n7O9uphVp5P5GkRxVuA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/core": "7.29.7",
@@ -613,6 +615,31 @@
"rxjs": "^6.5.3 || ^7.4.0"
}
},
"node_modules/@angular/localize": {
"version": "20.3.33",
"resolved": "https://registry.npmjs.org/@angular/localize/-/localize-20.3.33.tgz",
"integrity": "sha512-2Rr23xegscTKOwSNJE4O/vqpK+owLPH6Z7MojctI/cIcu5RSE7RVw/r9Hs5XS4fhr81yHRWp/jRFQzzm3i6F4g==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/core": "7.29.7",
"@types/babel__core": "7.20.5",
"tinyglobby": "^0.2.12",
"yargs": "^18.0.0"
},
"bin": {
"localize-extract": "tools/bundles/src/extract/cli.js",
"localize-migrate": "tools/bundles/src/migrate/cli.js",
"localize-translate": "tools/bundles/src/translate/cli.js"
},
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
},
"peerDependencies": {
"@angular/compiler": "20.3.33",
"@angular/compiler-cli": "20.3.33"
}
},
"node_modules/@angular/platform-browser": {
"version": "20.3.33",
"resolved": "https://registry.npmjs.org/@angular/platform-browser/-/platform-browser-20.3.33.tgz",
@@ -710,7 +737,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
"integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-validator-identifier": "^7.29.7",
@@ -725,7 +751,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz",
"integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
@@ -735,7 +760,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz",
"integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/code-frame": "^7.29.7",
@@ -766,14 +790,12 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
"integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
"dev": true,
"license": "MIT"
},
"node_modules/@babel/core/node_modules/semver": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
"integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
@@ -783,7 +805,6 @@
"version": "7.29.8",
"resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz",
"integrity": "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/parser": "^7.29.8",
@@ -813,7 +834,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz",
"integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/compat-data": "^7.29.7",
@@ -830,7 +850,6 @@
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
"integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
@@ -840,7 +859,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz",
"integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
@@ -850,7 +868,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz",
"integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/traverse": "^7.29.7",
@@ -864,7 +881,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz",
"integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-module-imports": "^7.29.7",
@@ -895,7 +911,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
"integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
@@ -905,7 +920,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
"integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
@@ -915,7 +929,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz",
"integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
@@ -925,7 +938,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz",
"integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/template": "^7.29.7",
@@ -939,7 +951,6 @@
"version": "7.29.9",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz",
"integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/types": "^7.29.8"
@@ -955,7 +966,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz",
"integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/code-frame": "^7.29.7",
@@ -970,7 +980,6 @@
"version": "7.29.8",
"resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.8.tgz",
"integrity": "sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/code-frame": "^7.29.7",
@@ -989,7 +998,6 @@
"version": "7.29.8",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz",
"integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-string-parser": "^7.29.7",
@@ -2019,7 +2027,6 @@
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
"integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.0",
@@ -2030,7 +2037,6 @@
"version": "2.3.5",
"resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",
"integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/gen-mapping": "^0.3.5",
@@ -2041,7 +2047,6 @@
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
"integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.0.0"
@@ -2051,14 +2056,12 @@
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
"integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
"dev": true,
"license": "MIT"
},
"node_modules/@jridgewell/trace-mapping": {
"version": "0.3.31",
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
"integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/resolve-uri": "^3.1.0",
@@ -4100,6 +4103,51 @@
"dev": true,
"license": "Apache-2.0"
},
"node_modules/@types/babel__core": {
"version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
"integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/parser": "^7.20.7",
"@babel/types": "^7.20.7",
"@types/babel__generator": "*",
"@types/babel__template": "*",
"@types/babel__traverse": "*"
}
},
"node_modules/@types/babel__generator": {
"version": "7.27.0",
"resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz",
"integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/types": "^7.0.0"
}
},
"node_modules/@types/babel__template": {
"version": "7.4.4",
"resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz",
"integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/parser": "^7.1.0",
"@babel/types": "^7.0.0"
}
},
"node_modules/@types/babel__traverse": {
"version": "7.28.0",
"resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz",
"integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==",
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/types": "^7.28.2"
}
},
"node_modules/@types/chai": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
@@ -4125,6 +4173,23 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/moment": {
"version": "2.11.29",
"resolved": "https://registry.npmjs.org/@types/moment/-/moment-2.11.29.tgz",
"integrity": "sha512-D5WIgbLYQzvgfsDnBhZFSTnt/BjGPOE+Jsh3k1BYYijJAkrn7ceeLvU4jtjKKXXuXN42O3ARlU4D/P9ezbQYFA==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/moment-jalaali": {
"version": "0.7.9",
"resolved": "https://registry.npmjs.org/@types/moment-jalaali/-/moment-jalaali-0.7.9.tgz",
"integrity": "sha512-gsDOoAzRnCfQTbfdlUrCvX6R0wIto6CvwfvV2C3j4qJLK+DEiTK8Rl/xlOCBO9C6qeUfX8oyZ2UfjnXJTOvHSA==",
"dev": true,
"license": "MIT",
"dependencies": {
"moment": ">=2.14.0"
}
},
"node_modules/@types/node": {
"version": "26.6.4",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.4.tgz",
@@ -4460,7 +4525,6 @@
"version": "6.4.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz",
"integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
@@ -4473,7 +4537,6 @@
"version": "6.2.3",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
"integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
@@ -4496,7 +4559,6 @@
"version": "2.11.27",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.27.tgz",
"integrity": "sha512-ElY12DaROGuan+lMmZ8Cvo/ZUbXPe7Enc/9VU/b1T3Kp4dwytRcNdR8DoSJN5SNJT/CuvcCA0DHDVmMOCePdRQ==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"baseline-browser-mapping": "dist/cli.cjs"
@@ -4585,7 +4647,6 @@
"version": "4.29.3",
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.3.tgz",
"integrity": "sha512-1R4kiYKXGViqEN0CnoDrXc1StD9niAwu+j2dukWzrD4bJgsD4lDmEp0CRbc6E/vYJIfTHwPmwyaKtVSudICdPA==",
"dev": true,
"funding": [
{
"type": "opencollective",
@@ -4766,7 +4827,6 @@
"version": "1.0.30001814",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001814.tgz",
"integrity": "sha512-/Uaf1lAzr59XcMpW0o96WoEfr+VXK2OX4U9AgFoiSHsVJ4HppnIFUjtYzsyDH2+tgANaQb2/oxYGwCPapN1FpA==",
"dev": true,
"funding": [
{
"type": "opencollective",
@@ -4834,7 +4894,6 @@
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz",
"integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==",
"dev": true,
"license": "MIT",
"dependencies": {
"readdirp": "^4.0.1"
@@ -4916,7 +4975,6 @@
"version": "9.0.1",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz",
"integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==",
"dev": true,
"license": "ISC",
"dependencies": {
"string-width": "^7.2.0",
@@ -4931,7 +4989,6 @@
"version": "9.0.2",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",
"integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^6.2.1",
@@ -5000,7 +5057,6 @@
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz",
"integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==",
"dev": true,
"license": "MIT"
},
"node_modules/cookie": {
@@ -5118,7 +5174,6 @@
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"dev": true,
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
@@ -5254,14 +5309,12 @@
"version": "1.5.444",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.444.tgz",
"integrity": "sha512-5ss/uJfoDYDHT0lfJzT6FbcskIzROIOPf0BbbFkGcvDzoJU7i//9GDrwwIHQVmIsrAGiF3ihpADBRIsrEFt1rQ==",
"dev": true,
"license": "ISC"
},
"node_modules/emoji-regex": {
"version": "10.6.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",
"integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",
"dev": true,
"license": "MIT"
},
"node_modules/encodeurl": {
@@ -5410,7 +5463,6 @@
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
"integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -5575,7 +5627,6 @@
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12.0.0"
@@ -5680,7 +5731,6 @@
"version": "1.0.0-beta.2",
"resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
"integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
@@ -5690,7 +5740,6 @@
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
"dev": true,
"license": "ISC",
"engines": {
"node": "6.* || 8.* || >= 10.*"
@@ -5700,7 +5749,6 @@
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz",
"integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
@@ -6177,6 +6225,12 @@
"node": ">=10"
}
},
"node_modules/jalaali-js": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/jalaali-js/-/jalaali-js-1.2.8.tgz",
"integrity": "sha512-Jl/EwY84JwjW2wsWqeU4pNd22VNQ7EkjI36bDuLw31wH98WQW4fPjD0+mG7cdCK+Y8D6s9R3zLiQ3LaKu6bD8A==",
"license": "MIT"
},
"node_modules/jiti": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",
@@ -6201,7 +6255,6 @@
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
"dev": true,
"license": "MIT"
},
"node_modules/jsdom": {
@@ -6268,7 +6321,6 @@
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",
"integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==",
"dev": true,
"license": "MIT",
"bin": {
"jsesc": "bin/jsesc"
@@ -6305,7 +6357,6 @@
"version": "2.2.3",
"resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
"integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
"dev": true,
"license": "MIT",
"bin": {
"json5": "lib/cli.js"
@@ -6775,7 +6826,6 @@
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
"integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
"dev": true,
"license": "ISC",
"dependencies": {
"yallist": "^3.0.2"
@@ -7049,6 +7099,38 @@
"node": ">= 18"
}
},
"node_modules/moment": {
"version": "2.31.0",
"resolved": "https://registry.npmjs.org/moment/-/moment-2.31.0.tgz",
"integrity": "sha512-0acOTfMiWOheYS4eoWb80yYMb/JLvVv9SHbs2PehaDzfUG0Bw855SKyk0IKTnPGa5+U2bmi3W68l1+sGLX/pvw==",
"license": "MIT",
"engines": {
"node": "*"
}
},
"node_modules/moment-jalaali": {
"version": "0.10.5",
"resolved": "https://registry.npmjs.org/moment-jalaali/-/moment-jalaali-0.10.5.tgz",
"integrity": "sha512-Xp0FsC0+jWG89/xcOrL880f97Tq7197P3saoMAqSIaF8vKr4Atr9XKtIOREGHTLUjOzJksfTHhQgxMgUJQupuw==",
"license": "MIT",
"dependencies": {
"jalaali-js": "^1.2.8",
"moment": "^2.30.1",
"moment-timezone": "^0.6.2"
}
},
"node_modules/moment-timezone": {
"version": "0.6.5",
"resolved": "https://registry.npmjs.org/moment-timezone/-/moment-timezone-0.6.5.tgz",
"integrity": "sha512-KKzZAxGv2Qx4cnk6eSlvf4C+DLFW52vmMY5MN7UARY7GONbozkutylQG3DrrtmLCTXdQ5XZrqao9cI16bLFzXA==",
"license": "MIT",
"dependencies": {
"moment": "^2.29.4"
},
"engines": {
"node": "*"
}
},
"node_modules/mrmime": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz",
@@ -7063,7 +7145,6 @@
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"dev": true,
"license": "MIT"
},
"node_modules/msgpackr": {
@@ -7263,7 +7344,6 @@
"version": "2.0.57",
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.57.tgz",
"integrity": "sha512-kQK9LGGFiHtrWiNhZtA7Qbw17AQz+dmsEKODRIVTXA9+e5MS/2gZEBhYJt13GrAz5/IOZKddH/0Z3TP/Zgo+yw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
@@ -7726,14 +7806,12 @@
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
"dev": true,
"license": "ISC"
},
"node_modules/picomatch": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
@@ -8004,7 +8082,6 @@
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",
"integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 14.18.0"
@@ -8018,7 +8095,6 @@
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
"integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",
"dev": true,
"license": "Apache-2.0"
},
"node_modules/require-from-string": {
@@ -8192,7 +8268,6 @@
"version": "7.7.2",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz",
"integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==",
"dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
@@ -8570,7 +8645,6 @@
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",
"integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"emoji-regex": "^10.3.0",
@@ -8588,7 +8662,6 @@
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",
"integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",
"dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^6.2.2"
@@ -8705,7 +8778,6 @@
"version": "0.2.14",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz",
"integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"fdir": "^6.4.4",
@@ -8872,7 +8944,7 @@
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"devOptional": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
@@ -8913,7 +8985,6 @@
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.3.tgz",
"integrity": "sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==",
"dev": true,
"funding": [
{
"type": "opencollective",
@@ -9365,7 +9436,6 @@
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
"integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
"dev": true,
"license": "ISC",
"engines": {
"node": ">=10"
@@ -9375,14 +9445,12 @@
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
"integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",
"dev": true,
"license": "ISC"
},
"node_modules/yargs": {
"version": "18.0.0",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-18.0.0.tgz",
"integrity": "sha512-4UEqdc2RYGHZc7Doyqkrqiln3p9X2DZVxaGbwhn2pi7MrRagKaOcIKe8L3OxYcbhXLgLFUS3zAYuQjKBQgmuNg==",
"dev": true,
"license": "MIT",
"dependencies": {
"cliui": "^9.0.1",
@@ -9400,7 +9468,6 @@
"version": "22.0.0",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz",
"integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==",
"dev": true,
"license": "ISC",
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=23"
+3
View File
@@ -35,6 +35,7 @@
"@popperjs/core": "^2.11.8",
"ag-grid-angular": "^36.2.0",
"ag-grid-community": "^36.2.0",
"moment-jalaali": "^0.10.5",
"ngx-toastr": "^14.3.0",
"papaparse": "^5.7.0",
"rxjs": "~7.8.0",
@@ -48,6 +49,8 @@
"@playwright/test": "^1.63.0",
"@tailwindcss/postcss": "^4.3.3",
"@types/audioworklet": "^0.0.100",
"@types/moment": "^2.11.29",
"@types/moment-jalaali": "^0.7.9",
"@types/papaparse": "^5.5.2",
"@types/three": "^0.186.0",
"jsdom": "^30.1.2",
+14
View File
@@ -0,0 +1,14 @@
{
"/api": {
"target": "http://192.168.180.151:8080",
"secure": false,
"changeOrigin": true,
"ws": true,
"logLevel": "debug"
},
"/users": {
"target": "http://192.168.180.151:8080",
"secure": false,
"changeOrigin": true
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,54 @@
/**
* Mic capture: downsamples the context rate to `targetRate` (default 24 kHz per the
* voice contract), converts to PCM16 mono and posts fixed-size frames (default 20 ms)
* to the main thread. Frames are always sample-aligned PCM16.
* Message: { pcm: ArrayBuffer (Int16), rms: number (0..1) }
*/
class PcmCaptureProcessor extends AudioWorkletProcessor {
constructor(options) {
super();
const o = (options && options.processorOptions) || {};
this.targetRate = o.targetRate || 24000;
this.frameSamples = o.frameSamples || 480;
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,327 @@
/**
* Streaming PCM16 playback (contract: 24 kHz mono PCM16LE output, no WAV header).
*
* Bounded playout queue. The cap is on OUTSTANDING SOURCE PCM — BOUND_BYTES (96,000 bytes
* = 48,000 source samples ≈ 2 s at 24 kHz mono PCM16) — and each stage uses ONE unit
* consistently:
* admission is booked in SOURCE samples (the contract/wire unit);
* the ring stores the RESAMPLED OUTPUT samples the AudioContext actually consumes;
* PROGRESS is booked in OUTPUT samples (an integer the resampler fully controls), and
* rendered as milliseconds at the context rate. Because resampling preserves duration,
* output-time equals source-time, so this reports the same ms as source/srcRate — but it
* is exact (no float drift over thousands of iterations).
* The output ring is sized to hold the source bound at the worst-case ratio
* (source bound ÷ ratio), so the SAME 2 s source cap holds at any real context rate
* (24k / 44.1k / 48k …) without widening the source limit, suppressing overflow or silently
* dropping PCM. If the queue fills anyway the processor posts `overflow` and the call fails
* safely.
*
* End-of-turn tail: the resample loop keeps the window's last sample as `prev` (for
* cross-chunk continuity) and only emits it at the start of the NEXT chunk. At the final
* chunk there is no next chunk, so without an explicit flush the last source sample is never
* emitted — queued source never reaches zero and played_ms under-reports by ~1 ms, which the
* backend reads as perpetual outstanding playback (a stall/overflow signature). `flush()`
* (raised on audio_ended) emits that deferred tail so every admitted source sample becomes
* output and fully played audio drains to exactly its real duration. `clear()` (barge-in)
* discards the tail instead, so interrupted audio is never credited as played.
*
* Messages in: { type: 'push', pcm: ArrayBuffer (Int16 mono), sampleRate, audioRef }
* { type: 'clear' } barge-in: drop everything immediately
* { type: 'flush', audioRef } end of turn: emit the tail, play what is left, then idle
* Messages out: { type: 'progress', audioRef, playedMs }
* { type: 'idle', audioRef } buffer ran dry after playing
* { type: 'overflow' } bounded queue filled — caller fails the session safely
*/
const BOUND_BYTES = 96000; // contract cap on outstanding SOURCE PCM16
const RESAMPLE_MARGIN = 64; // slack for fractional-boundary rounding (never widens the source bound)
const REPORT_INTERVAL_MS = 250;
class PcmPlaybackProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.sourceCapacity = Math.floor(BOUND_BYTES / 2); // 48,000 SOURCE samples (admission bound)
this.ratio = 1; // SOURCE samples per OUTPUT sample (resolved on first push)
this.sized = false; // true once the output ring matches the real context rate
this.capacity = this.sourceCapacity; // OUTPUT slots currently allocated (grows for upsampling)
this.buf = new Float32Array(this.capacity);
this.r = 0;
this.w = 0;
this.count = 0; // OUTPUT samples currently queued
this.queuedSource = 0; // SOURCE samples currently queued (the admission bound unit)
this.prebuffer = Math.floor(sampleRate * 0.08); // jitter buffer before (re)starting
this.started = false;
this.prev = 0;
this.pos = 1;
// End-of-turn tail accounting (per turn, reset on flush/clear). `admittedSrc` +
// `emittedOut` let flush() emit the exact OUTPUT count for all admitted source; the last
// chunk window is retained so the tail can be interpolated correctly.
this.admittedSrc = 0; // SOURCE samples admitted this turn
this.emittedOut = 0; // OUTPUT samples emitted for them so far
this.windowSrc = null; // last chunk's src window (for tail interpolation)
this.windowN = 0;
// Per-audio_ref attribution. `refQueue` keeps the still-queued OUTPUT span of each ref
// (merged per ref so it stays ≤ the number of turns); `refPlayedOut` keeps each ref's
// cumulative OUTPUT samples consumed. Together they tie queued audio to its own ref and
// keep progress cumulative and correct across ref changes.
this.refQueue = []; // [{ ref, out }] out = remaining OUTPUT samples of that ref
this.refPlayedOut = new Map();
this.playingRef = null; // ref currently being consumed / reported
this.pendingRef = null; // audio_ref of the most recent push (the one flush() tail belongs to)
this.unreportedOut = 0;
this.overflowPosted = false;
this.port.onmessage = (e) => {
const m = e.data;
if (!m) return;
if (m.type === 'push') this.push(new Int16Array(m.pcm), m.sampleRate, m.audioRef || null);
else if (m.type === 'clear') this.clear();
else if (m.type === 'flush') this.flush(m.audioRef);
};
}
/** Resolve the source→output ratio and size the output ring to hold the source bound. */
configure(ratio) {
if (this.sized && ratio === this.ratio) return;
this.ratio = ratio > 0 ? ratio : 1;
const need = Math.ceil(this.sourceCapacity / this.ratio) + RESAMPLE_MARGIN;
// Only grow while the ring is empty (first push): never drop queued audio.
if (need > this.capacity && this.count === 0) {
this.capacity = need;
this.buf = new Float32Array(this.capacity);
this.r = 0;
this.w = 0;
}
this.sized = true;
}
clear() {
this.reportFinal(); // final cumulative report for the interrupted ref
// Attribute queued output and the deferred tail to their real references.
const discarded = new Map();
for (const span of this.refQueue) {
discarded.set(span.ref, (discarded.get(span.ref) ?? 0) + span.out);
}
const tail = Math.max(0, Math.round(this.admittedSrc / this.ratio) - this.emittedOut);
if (tail > 0) discarded.set(this.pendingRef, (discarded.get(this.pendingRef) ?? 0) + tail);
for (const [audioRef, discardedSamples] of discarded) {
this.port.postMessage({ type: 'discarded', audioRef, discardedSamples, contextRate: sampleRate });
}
this.r = this.w = this.count = 0;
this.queuedSource = 0;
this.refQueue.length = 0;
this.started = false;
this.prev = 0;
this.pos = 1;
// Discard the deferred tail too: interrupted audio is NOT played, so it must not be
// credited or emitted.
this.admittedSrc = 0;
this.emittedOut = 0;
this.windowSrc = null;
this.windowN = 0;
this.playingRef = null;
}
flush(audioRef = this.pendingRef) {
this.finalizeTail(); // emit the deferred tail so every admitted sample becomes output
if (this.count === 0) {
this.started = false;
this.reportFinal();
this.port.postMessage({ type: 'idle', audioRef: audioRef || this.pendingRef });
} else {
this.started = true; // play the remaining audio + tail without waiting for the prebuffer
}
}
/**
* End-of-turn tail: emit the OUTPUT samples for every admitted SOURCE sample that the push
* loop deferred (it keeps the window's last sample as `prev` for cross-chunk continuity and
* only emits it at the start of the next chunk). Continuing the interpolation past the last
* sample — holding its value — produces real output so fully played audio leaves queued
* source at zero and played_ms reflects the true duration (never fabricated upward).
*/
finalizeTail() {
const src = this.windowSrc;
const n = this.windowN;
if (src && n > 0) {
const target = Math.round(this.admittedSrc / this.ratio); // exact OUTPUT count for the turn
let pos = n + this.pos; // continue from where the push loop stopped (abs. in this window)
while (this.emittedOut < target) {
const base = Math.min(Math.floor(pos), n);
const frac = Math.min(1, Math.max(0, pos - base));
const a = src[base];
const b = src[Math.min(base + 1, n)]; // clamp: hold the last sample past the boundary
this.write(a * (1 - frac) + b * frac);
this.creditQueue(1); // the emitted tail belongs to the current (last) ref
this.emittedOut++;
pos += this.ratio;
}
}
// Each turn is an independent signal: reset the resampler for the next one.
this.admittedSrc = 0;
this.emittedOut = 0;
this.windowSrc = null;
this.windowN = 0;
this.pos = 1;
this.prev = 0;
}
push(int16, srcRate, audioRef) {
const n = int16.length;
if (!n) return;
const ratio = srcRate / sampleRate; // SOURCE samples per OUTPUT sample
this.configure(ratio);
// OUTPUT samples this chunk's main loop will add — an upper bound on the exact count.
const produced =
this.ratio === 1 ? n : this.pos < n ? Math.ceil((n - this.pos) / this.ratio) : 0;
// Bounded queue — two consistent guards, each in its own unit:
// 1) SOURCE bound: the contract 96,000-byte cap, invariant across context rates.
if (this.queuedSource + n > this.sourceCapacity) return this.overflow();
// 2) OUTPUT storage: never let the ring overrun because a chunk resampled larger.
if (this.count + produced > this.capacity) return this.overflow();
this.queuedSource += n;
this.admittedSrc += n; // every admitted source sample must eventually become output
// Matching rates need no interpolation or deferred tail. Render every admitted
// sample even while generation is still open; progress reflects only consumed PCM.
if (this.ratio === 1) {
this.pendingRef = audioRef;
for (let i = 0; i < n; i++) this.write(int16[i] / 32768);
this.creditQueue(n);
this.emittedOut += n;
return;
}
const src = new Float32Array(n + 1);
src[0] = this.prev;
for (let i = 0; i < n; i++) src[i + 1] = int16[i] / 32768;
// Retain this window so flush() can emit the deferred tail correctly.
this.windowSrc = src;
this.windowN = n;
let pos = this.pos;
let mainOut = 0;
while (pos < n) {
const i = Math.floor(pos);
const frac = pos - i;
this.write(src[i] * (1 - frac) + src[i + 1] * frac);
mainOut++;
pos += this.ratio;
}
this.prev = src[n];
this.pos = pos - n;
this.emittedOut += mainOut;
this.pendingRef = audioRef;
this.creditQueue(mainOut); // attribute this chunk's OUTPUT to its audio_ref
}
/** Adds `out` OUTPUT samples to the current ref's span (merging consecutive same-ref pushes). */
creditQueue(out) {
const ref = this.pendingRef;
const last = this.refQueue[this.refQueue.length - 1];
if (last && last.ref === ref) last.out += out;
else this.refQueue.push({ ref, out });
}
overflow() {
if (!this.overflowPosted) {
this.overflowPosted = true;
this.port.postMessage({ type: 'overflow' });
}
}
write(v) {
// Defense in depth: admission already reserves the room, so this never discards in
// normal flow — but it guarantees the ring is never overwritten nor exceeds capacity.
if (this.count >= this.capacity) return;
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) {
let played = 0;
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--;
played++;
} else {
ch0[i] = 0;
}
}
if (played > 0) {
this.queuedSource = Math.max(0, this.queuedSource - played * this.ratio); // OUTPUT→SOURCE
this.consumeSpans(played);
this.reportCadence();
}
if (this.count === 0) {
// Ring drained: nothing is outstanding, so no phantom source remains for this turn.
this.queuedSource = 0;
this.started = false;
this.reportFinal();
this.port.postMessage({ type: 'idle', audioRef: this.pendingRef });
}
} else {
ch0.fill(0);
}
for (let c = 1; c < out.length; c++) out[c].set(ch0);
return true;
}
/** Draw `played` OUTPUT samples off the front of the ref FIFO, crediting each ref. */
consumeSpans(played) {
while (played > 0 && this.refQueue.length) {
const span = this.refQueue[0];
const take = played < span.out ? played : span.out;
span.out -= take;
played -= take;
this.refPlayedOut.set(span.ref, (this.refPlayedOut.get(span.ref) ?? 0) + take);
this.playingRef = span.ref;
this.unreportedOut += take;
if (span.out <= 0) {
this.refQueue.shift();
this.postProgress(span.ref); // ref finished: post its final cumulative before the next ref
}
}
}
/** Final cumulative report for the ref currently playing (interruption / drain / clear). */
reportFinal() {
this.unreportedOut = 0;
if (!this.playingRef) return;
this.postProgress(this.playingRef);
}
/** Cadence report for the ref currently playing (~REPORT_INTERVAL_MS of consumed output). */
reportCadence() {
if (!this.playingRef) return;
if ((this.unreportedOut / sampleRate) * 1000 >= REPORT_INTERVAL_MS) {
this.reportFinal();
}
}
postProgress(ref) {
const playedOut = this.refPlayedOut.get(ref) ?? 0;
// OUTPUT samples at the context rate → milliseconds; floor never claims an unheard ms and
// stays monotonic because it is cumulative. Output-time equals source-time (SRC preserves
// duration), so this equals the contract's played source / srcRate.
// Multiply integer counts first to avoid rounding an exact whole millisecond down.
const playedMs = Math.floor((playedOut * 1000) / sampleRate);
if (playedMs <= 0) return;
this.port.postMessage({ type: 'progress', audioRef: ref, playedMs, consumedSamples: playedOut, contextRate: sampleRate });
}
}
registerProcessor('pcm-playback', PcmPlaybackProcessor);
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

+78 -9
View File
@@ -1,10 +1,57 @@
import { ApplicationConfig, provideBrowserGlobalErrorListeners, provideZonelessChangeDetection } from '@angular/core';
import {
ApplicationConfig,
provideBrowserGlobalErrorListeners,
provideZonelessChangeDetection,
APP_INITIALIZER,
importProvidersFrom,
ApplicationRef,
Injector,
NgZone,
} from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { DomSanitizer } from '@angular/platform-browser';
import { Overlay, ToastrModule, ToastrService, TOAST_CONFIG } from 'ngx-toastr';
import { routes } from './app.routes';
import { AuthService } from './services/auth/auth.service';
/** The type of the injected TOAST_CONFIG value (the `{ default, config }` toast token). */
type ToastConfigToken = ConstructorParameters<typeof ToastrService>[0];
/**
* Builds the real ToastrService wrapped so every method forces an `ApplicationRef.tick()`.
* ngx-toastr v14 attaches each toast to ApplicationRef without rendering it; under this app's
* ZONELESS change detection there is no zone tick to render it, so without this no toast
* appears. `tick()` renders the just-attached overlay view.
*/
function zonelessToastr(
real: ToastrService,
appRef: ApplicationRef,
): ToastrService {
return new Proxy(real, {
get(target, prop, receiver) {
const value = Reflect.get(target, prop, receiver);
return typeof value === 'function'
? (...args: unknown[]) => {
const result = (value as (...a: unknown[]) => unknown).apply(target, args);
appRef.tick();
return result;
}
: value;
},
}) as ToastrService;
}
/**
* On every page load the HttpOnly `rag_session` cookie is validated with `GET /me`
* before the first route activates; a 401 drops the authenticated state so the
* guard sends the user to the login page.
*/
function initializeAuth(auth: AuthService): () => Promise<boolean> {
return () => auth.ensureIdentity().catch(() => false);
}
export const appConfig: ApplicationConfig = {
providers: [
@@ -13,12 +60,34 @@ export const appConfig: ApplicationConfig = {
provideRouter(routes),
provideAnimations(),
provideHttpClient(),
// Registers ngx-toastr's Toast component + TOAST_CONFIG.
importProvidersFrom(
ToastrModule.forRoot({
timeOut: 4000,
positionClass: 'toast-bottom-left',
preventDuplicates: true,
}),
),
{
provide: TOAST_CONFIG,
useValue: {
default: DefaultGlobalConfig,
config: {}
}
}
]
// Override the library's root ToastrService with a zoneless-aware wrapper so toasts
// actually render (see zonelessToastr()).
provide: ToastrService,
useFactory: (
appRef: ApplicationRef,
injector: Injector,
config: ToastConfigToken,
overlay: Overlay,
sanitizer: DomSanitizer,
zone: NgZone,
) =>
zonelessToastr(new ToastrService(config, overlay, injector, sanitizer, zone), appRef),
deps: [ApplicationRef, Injector, TOAST_CONFIG, Overlay, DomSanitizer, NgZone],
},
{
provide: APP_INITIALIZER,
useFactory: initializeAuth,
deps: [AuthService],
multi: true,
},
],
};
+9
View File
@@ -0,0 +1,9 @@
/* `app-root` defaults to `display: inline`, which adds a line-box strut below the
full-height shell and makes the body scroll. Block + fixed viewport height keeps
every page inside the viewport; scrolling happens in the shell's scroll container. */
:host {
display: block;
height: 100vh;
height: 100dvh;
overflow: hidden;
}
+5 -1
View File
@@ -1 +1,5 @@
<app-layout></app-layout>
@if (isAuthenticated()) {
<app-layout></app-layout>
} @else {
<app-login></app-login>
}
+65 -1
View File
@@ -1,11 +1,75 @@
import { Routes } from '@angular/router';
import { HomePage } from './pages/home/home.page';
import { SettingsPage } from './pages/settings/settings.page';
import { LoginPage } from './pages/login/login.page';
import { ReportsPage } from './pages/reports/reports.page';
import { WallboardPage } from './pages/wallboard/wallboard.page';
import { CallCenterPage } from './pages/call-center/call-center.page';
import { CallCenterCallsPage } from './pages/call-center/call-center-calls.page';
import { ChatQuestionsPage } from './pages/chat-questions/chat-questions.page';
import { AuthService } from './services/auth/auth.service';
import { authGuard } from './services/auth/auth.guard';
import { Router } from '@angular/router';
import { inject } from '@angular/core';
const redirectAuthenticated = () => {
const authService = inject(AuthService);
const router = inject(Router);
if (authService.isAuthenticated()) {
router.navigate(['/']);
return false;
}
return true;
};
export const routes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: '' },
{
path: 'login',
title: 'ورود',
component: LoginPage,
canActivate: [redirectAuthenticated],
},
{
path: '',
title: 'دستیار هوش مصنوعی',
component: HomePage,
canActivate: [authGuard],
},
{
path: 'settings',
title: 'تنظیمات',
component: SettingsPage,
canActivate: [authGuard],
},
{
path: 'reports',
title: 'گزارشات',
component: ReportsPage,
canActivate: [authGuard],
},
{
path: 'wallboard',
title: 'والبورد',
component: WallboardPage,
canActivate: [authGuard],
},
{
path: 'call-center',
title: 'ارتباط با کال سنتر',
component: CallCenterPage,
canActivate: [authGuard],
},
{
path: 'call-center/calls',
title: 'بازخوانی تماس‌ها از کال سنتر',
component: CallCenterCallsPage,
canActivate: [authGuard],
},
{
path: 'chat-questions',
title: 'سوالات چت وب اپلیکیشن',
component: ChatQuestionsPage,
canActivate: [authGuard],
},
];
+11 -1
View File
@@ -1,12 +1,22 @@
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { App } from './app';
describe('App', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [App],
providers: [provideZonelessChangeDetection()]
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
],
}).compileComponents();
});
+20 -4
View File
@@ -1,10 +1,26 @@
import { Component } from '@angular/core';
import { Component, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LayoutComponent } from './layout/layout.component';
import { LoginPage } from './pages/login/login.page';
import { AuthService } from './services/auth/auth.service';
@Component({
selector: 'app-root',
imports: [LayoutComponent],
standalone: true,
imports: [CommonModule, LayoutComponent, LoginPage],
templateUrl: './app.html',
styleUrl: './app.css'
styleUrl: './app.css',
})
export class App {}
export class App {
private readonly authService = inject(AuthService);
readonly isAuthenticated = signal<boolean>(this.authService.isAuthenticated());
constructor() {
this.authService.currentUserSubject.subscribe({
next: () => {
this.isAuthenticated.set(this.authService.isAuthenticated());
},
});
}
}
+14
View File
@@ -40,9 +40,20 @@
background: var(--menu-toggle-hover);
}
/* The shell owns the viewport: exactly one screen tall, nothing scrolls at the page
level. Routed pages scroll inside .main-content instead. */
.app-layout {
display: flex;
height: 100vh;
height: 100dvh;
overflow: hidden;
}
.main-content {
flex: 1;
min-height: 0;
overflow-y: auto;
overflow-x: hidden;
background: var(--main-content-bg);
}
@@ -51,6 +62,9 @@
flex-direction: column;
flex: 1;
min-width: 0;
/* Lets .main-content shrink and scroll instead of growing past the viewport. */
min-height: 0;
margin-right: 72px;
transition: margin-right 0.3s ease;
}
+3 -1
View File
@@ -1,9 +1,11 @@
<div class="app-layout">
<app-sidebar
[isOpen]="sidebarOpen()"
[userName]="userName()"
[navItems]="navItems()"
[chatHistory]="chatHistory()"
(close)="sidebarOpen.set(false)"
(navClick)="sidebarOpen.set(false)"
(navClick)="sidebarOpen.set(true)"
(open)="sidebarOpen.set(true)"
(profileClick)="onProfile()"
(logoutClick)="onLogout()"
+54 -4
View File
@@ -1,10 +1,38 @@
import { ChangeDetectionStrategy, Component, signal, inject } from '@angular/core';
import { ChangeDetectionStrategy, Component, signal, inject, computed } from '@angular/core';
import { RouterModule } from '@angular/router';
import { RouterOutlet } from '@angular/router';
import { SidebarComponent, ChatHistoryItem } from '../shared/ui/sidebar/sidebar.component';
import { SidebarComponent, ChatHistoryItem, NavItem } from '../shared/ui/sidebar/sidebar.component';
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. */
const BASE_NAV_ITEMS: NavItem[] = [
{ icon: 'M12 5v14M5 12h14', label: 'چت جدید', route: '/' },
{ icon: 'M4 4v16h16M8 20V11M12.5 20V6M17 20V9', label: 'گزارشات', route: '/reports' },
{ icon: 'M2 4h20v12H2zM8 20h8M12 16v4', label: 'والبورد', route: '/wallboard' },
{
icon: 'M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71',
label: 'ارتباط با کال سنتر',
route: '/call-center',
},
{
icon: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3',
label: 'بازخوانی تماس‌ها از کال سنتر',
route: '/call-center/calls',
},
{
icon: 'M7.9 20A9 9 0 1 0 4 16.1L2 22Z',
label: 'سوالات چت وب اپلیکیشن',
route: '/chat-questions',
},
{
icon: 'M19.14 12.94c.04-.3.06-.61.06-.94s-.02-.64-.07-.94l2.03-1.58a.5.5 0 0 0 .12-.64l-1.92-3.32a.5.5 0 0 0-.61-.22l-2.39.96a7.3 7.3 0 0 0-1.63-.94l-.36-2.54A.49.49 0 0 0 13.87 2h-3.84a.49.49 0 0 0-.49.42L9.18 4.96c-.59.23-1.14.55-1.63.94l-2.39-.96a.5.5 0 0 0-.61.22L2.63 8.48a.5.5 0 0 0 .12.64l2.03 1.58a7 7 0 0 0 0 1.88l-2.03 1.58a.5.5 0 0 0-.12.64l1.92 3.32c.13.22.39.31.61.22l2.39-.96c.49.39 1.04.71 1.63.94l.36 2.54c.03.24.24.42.49.42h3.84c.25 0 .46-.18.49-.42l.36-2.54c.59-.23 1.14-.55 1.63-.94l2.39.96c.22.09.48 0 .61-.22l1.92-3.32a.5.5 0 0 0-.12-.64zM12 15.5a3.5 3.5 0 1 1 0-7 3.5 3.5 0 0 1 0 7z',
label: 'تنظیمات',
route: '/settings',
},
];
@Component({
selector: 'app-layout',
standalone: true,
@@ -16,18 +44,40 @@ import { ThemeService } from '../services/theme/theme.service';
export class LayoutComponent {
private readonly authService = inject(AuthService);
private readonly themeService = inject(ThemeService);
private readonly voiceStream = inject(VoiceStreamService);
readonly sidebarOpen = signal(false);
readonly sidebarOpen = signal(true);
readonly chatHistory = signal<ChatHistoryItem[]>([]);
readonly isDarkMode = this.themeService.isDarkMode;
/** 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');
});
onProfile(): void {
this.sidebarOpen.set(false);
}
/**
* Logout releases the live voice session first (final playback progress, then V04),
* then A02 — even if V04 fails the logout still completes and local state is dropped.
*/
onLogout(): void {
this.authService.logout();
this.sidebarOpen.set(false);
void this.voiceStream.close().finally(() => {
this.authService.logout().subscribe({
next: () => this.navigateToLogin(),
error: () => this.navigateToLogin(),
});
});
}
private navigateToLogin(): void {
window.location.href = '/login';
}
}
@@ -0,0 +1,25 @@
/* Page-specific styles for «بازخوانی تماس‌ها از کال سنتر» (shared chrome: shared/styles/demo-page.css) */
.demo-filters {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr)) auto;
gap: 1rem 1.25rem;
align-items: end;
}
@media (max-width: 1024px) {
.demo-filters {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.demo-filters .demo-btn {
grid-column: 1 / -1;
justify-self: start;
}
}
@media (max-width: 640px) {
.demo-filters {
grid-template-columns: minmax(0, 1fr);
}
}
@@ -0,0 +1,148 @@
<div class="demo-page">
<header class="demo-header">
<div class="demo-title-group">
<span class="demo-title-icon">
<svg
width="22"
height="22"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3" />
</svg>
</span>
<div>
<h1 class="demo-title">بازخوانی تماس‌ها از کال سنتر</h1>
<p class="demo-subtitle">دریافت و بازخوانی سابقه تماس‌ها از سامانه کال سنتر</p>
</div>
</div>
<span class="demo-chip">نمایشی</span>
</header>
<section class="demo-card demo-notice">
<span class="demo-notice-icon">
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="9" />
<path d="M12 8v4M12 16h.01" />
</svg>
</span>
<div>
<h2>این بخش هنوز فعال نیست</h2>
<p>
این صفحه مکانیزم بازخوانی سابقه تماس‌ها از کال سنتر را نمایش می‌دهد. رکوردهای زیر داده نمونه
هستند و از سرور واقعی دریافت نشده‌اند؛ پس از اتصال به کال سنتر، بازخوانی بر اساس بازه تاریخ و
وضعیت تماس انجام می‌شود.
</p>
</div>
</section>
<section class="demo-card">
<div class="demo-card-header">
<div>
<h2 class="demo-card-title">فیلتر بازخوانی</h2>
<p class="demo-card-description">
بازه تاریخ و وضعیت مورد نظر را انتخاب کنید تا گزارش تماس‌ها دریافت شود.
</p>
</div>
</div>
<div class="demo-filters">
@for (filter of filters; track filter.label) {
<label class="demo-field">
<span class="demo-field-label">{{ filter.label }}</span>
@if (filter.type === 'select') {
<select class="demo-field-input" disabled>
@for (option of filter.options ?? []; track option) {
<option [value]="option">{{ option }}</option>
}
</select>
} @else {
<input class="demo-field-input" type="text" [value]="filter.value" readonly />
}
<span class="demo-field-hint">{{ filter.hint }}</span>
</label>
}
<button type="button" class="demo-btn demo-btn--primary" disabled>بازخوانی تماس‌ها</button>
</div>
<div class="demo-actions">
<span class="demo-hint">
این کنترل‌ها در فاز جاری فعال نیستند و هیچ درخواستی به کال سنتر ارسال نمی‌شود.
</span>
</div>
</section>
<section class="demo-card">
<div class="demo-card-header">
<div>
<h2 class="demo-card-title">سابقه تماس‌ها</h2>
<p class="demo-card-description">
نمونه‌ای از رکوردهایی که پس از اتصال، از کال سنتر بازخوانی می‌شود.
</p>
</div>
<span class="demo-badge">داده نمونه</span>
</div>
<div class="demo-table-wrapper">
<table class="demo-table">
<thead>
<tr>
<th>شماره تماس</th>
<th>مدت تماس</th>
<th>وضعیت</th>
<th>تاریخ</th>
</tr>
</thead>
<tbody>
@for (call of exampleCalls; track call.phone) {
<tr>
<td>{{ call.phone }}</td>
<td>{{ call.duration }}</td>
<td>
<span class="demo-tag demo-tag--{{ call.statusKind }}">{{ call.status }}</span>
</td>
<td>{{ call.date }}</td>
</tr>
}
</tbody>
</table>
</div>
</section>
<section class="demo-card">
<div class="demo-empty">
<svg
width="40"
height="40"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M3 3v18h18" />
<path d="M7 15l4-6 4 4 4-7" />
</svg>
<h3>هنوز گزارشی بازخوانی نشده است</h3>
<p>
پس از اتصال به سامانه کال سنتر، گزارش‌های تماس بر اساس بازه زمانی انتخاب‌شده در این صفحه
نمایش داده می‌شود.
</p>
</div>
</section>
</div>
@@ -0,0 +1,46 @@
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { CallCenterCallsPage } from './call-center-calls.page';
describe('CallCenterCallsPage', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [CallCenterCallsPage],
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
],
}).compileComponents();
});
it('should create the page', () => {
const fixture = TestBed.createComponent(CallCenterCallsPage);
expect(fixture.componentInstance).toBeTruthy();
});
it('renders example call rows and disabled symbolic controls', () => {
const fixture = TestBed.createComponent(CallCenterCallsPage);
fixture.detectChanges();
const element: HTMLElement = fixture.nativeElement;
expect(element.querySelector('.demo-title')?.textContent?.trim()).toBe('بازخوانی تماس‌ها از کال سنتر');
expect(element.textContent).toContain('این بخش هنوز فعال نیست');
expect(element.textContent).toContain('داده نمونه');
const rows = element.querySelectorAll('.demo-table tbody tr');
expect(rows.length).toBe(4);
expect(element.textContent).toContain('۰۹۱۲۱۲۳۴۵۶۷');
expect(element.textContent).toContain('پاسخ‌داده شده');
const buttons = Array.from(element.querySelectorAll('button')) as HTMLButtonElement[];
buttons.forEach((button) => expect(button.disabled).toBe(true));
expect(element.querySelector('select')?.disabled).toBe(true);
});
});
@@ -0,0 +1,85 @@
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { CommonModule } from '@angular/common';
interface ExampleCall {
phone: string;
duration: string;
status: string;
statusKind: 'answered' | 'pending' | 'missed';
date: string;
}
interface CallFilter {
label: string;
value: string;
hint: string;
type: 'text' | 'select';
options?: string[];
}
/**
* Symbolic demonstration page for retrieving call records from the call
* center. The rows are example data and every control is a placeholder.
*/
@Component({
selector: 'app-call-center-calls',
standalone: true,
imports: [CommonModule],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './call-center-calls.page.html',
styleUrls: ['./call-center-calls.page.css', '../../shared/styles/demo-page.css'],
})
export class CallCenterCallsPage {
readonly filters: CallFilter[] = [
{
label: 'از تاریخ',
value: '۱۴۰۴/۰۷/۰۱',
hint: 'نمونه — بازه تاریخ قابل انتخاب است.',
type: 'text',
},
{
label: 'تا تاریخ',
value: '۱۴۰۴/۰۷/۳۰',
hint: 'نمونه — بازه تاریخ قابل انتخاب است.',
type: 'text',
},
{
label: 'وضعیت تماس',
value: 'همه وضعیت‌ها',
hint: 'فیلتر نمونه.',
type: 'select',
options: ['همه وضعیت‌ها', 'پاسخ‌داده شده', 'بدون پاسخ', 'در انتظار بازبینی'],
},
];
readonly exampleCalls: ExampleCall[] = [
{
phone: '۰۹۱۲۱۲۳۴۵۶۷',
duration: '۲:۴۵',
status: 'پاسخ‌داده شده',
statusKind: 'answered',
date: '۱۴ مهر ۱۴۰۴',
},
{
phone: '۰۹۳۵۱۱۲۲۳۳۴۴',
duration: '۰:۳۸',
status: 'بدون پاسخ',
statusKind: 'missed',
date: '۱۴ مهر ۱۴۰۴',
},
{
phone: '۰۹۱۲۹۸۷۶۵۴۳۲',
duration: '۵:۱۲',
status: 'پاسخ‌داده شده',
statusKind: 'answered',
date: '۱۳ مهر ۱۴۰۴',
},
{
phone: '۰۹۱۵۵۵۱۲۳۴۵',
duration: '۱:۰۳',
status: 'در انتظار بازبینی',
statusKind: 'pending',
date: '۱۳ مهر ۱۴۰۴',
},
];
}
@@ -0,0 +1,5 @@
/* Page-specific styles for «ارتباط با کال سنتر» (shared chrome: shared/styles/demo-page.css) */
.demo-field-input--masked {
letter-spacing: 0.2em;
}
@@ -0,0 +1,158 @@
<div class="demo-page">
<header class="demo-header">
<div class="demo-title-group">
<span class="demo-title-icon">
<svg
width="22"
height="22"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path
d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"
/>
</svg>
</span>
<div>
<h1 class="demo-title">ارتباط با کال سنتر</h1>
<p class="demo-subtitle">اتصال برنامه به سامانه کال سنتر و همگام‌سازی تماس‌ها</p>
</div>
</div>
<span class="demo-chip">نمایشی</span>
</header>
<section class="demo-card demo-notice">
<span class="demo-notice-icon">
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="9" />
<path d="M12 8v4M12 16h.01" />
</svg>
</span>
<div>
<h2>این بخش هنوز فعال نیست</h2>
<p>
این صفحه نحوه اتصال برنامه به سامانه کال سنتر را نمایش می‌دهد. در فاز جاری هیچ اتصالی برقرار
نشده است و مقادیر نشان‌داده‌شده صرفاً نمونه هستند؛ پس از راه‌اندازی، اتصال از همین‌جا پیکربندی
و بررسی می‌شود.
</p>
</div>
</section>
<section class="demo-card">
<div class="demo-card-header">
<div>
<h2 class="demo-card-title">وضعیت اتصال</h2>
<p class="demo-card-description">
آخرین وضعیت بررسی اتصال برنامه به سامانه کال سنتر.
</p>
</div>
<div class="demo-status-row">
<span class="demo-status demo-status--off">اتصال برقرار نشده</span>
</div>
</div>
<p class="demo-card-description">
تا زمانی که اتصال برقرار نشده باشد، تماس‌های کال سنتر در والبرد و گزارش‌ها ثبت نمی‌شوند و
انتقال تماس از هوش مصنوعی به کارشناس انجام نمی‌شود.
</p>
</section>
<section class="demo-card">
<div class="demo-card-header">
<div>
<h2 class="demo-card-title">اطلاعات اتصال</h2>
<p class="demo-card-description">
مقادیر زیر از نمونه‌های نمایشی گرفته شده‌اند و قابل ویرایش نیستند.
</p>
</div>
</div>
<div class="demo-form-grid">
@for (field of connectionFields; track field.label) {
<label class="demo-field">
<span class="demo-field-label">{{ field.label }}</span>
<input
class="demo-field-input"
[class.demo-field-input--masked]="field.masked"
type="text"
[value]="field.value"
readonly
/>
<span class="demo-field-hint">{{ field.hint }}</span>
</label>
}
</div>
<div class="demo-actions">
<button type="button" class="demo-btn demo-btn--primary" disabled>بررسی اتصال</button>
<button type="button" class="demo-btn demo-btn--outline" disabled>ذخیره تنظیمات</button>
<span class="demo-hint">این کنترل‌ها در فاز جاری فعال نیستند.</span>
</div>
</section>
<section class="demo-card">
<div class="demo-card-header">
<div>
<h2 class="demo-card-title">قابلیت‌های پس از اتصال</h2>
<p class="demo-card-description">با برقراری اتصال به کال سنتر، این قابلیت‌ها فعال می‌شوند.</p>
</div>
</div>
<div class="demo-features">
@for (feature of features; track feature.id) {
<article class="demo-feature">
<span class="demo-feature-icon">
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path [attr.d]="feature.icon" />
</svg>
</span>
<h3>{{ feature.title }}</h3>
<p>{{ feature.description }}</p>
</article>
}
</div>
</section>
<section class="demo-card">
<div class="demo-empty">
<svg
width="40"
height="40"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M22 12h-4l-3 9L9 3l-3 9H2" />
</svg>
<h3>رخداد اتصالی ثبت نشده است</h3>
<p>
پس از برقراری اتصال، رخدادهای آزمایش اتصال، قطع و راه‌اندازی مجدد در این بخش نمایش داده
می‌شود.
</p>
</div>
</section>
</div>
@@ -0,0 +1,47 @@
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { CallCenterPage } from './call-center.page';
describe('CallCenterPage', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [CallCenterPage],
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
],
}).compileComponents();
});
it('should create the page', () => {
const fixture = TestBed.createComponent(CallCenterPage);
expect(fixture.componentInstance).toBeTruthy();
});
it('renders the symbolic call-center connection state', () => {
const fixture = TestBed.createComponent(CallCenterPage);
fixture.detectChanges();
const element: HTMLElement = fixture.nativeElement;
expect(element.querySelector('.demo-title')?.textContent?.trim()).toBe('ارتباط با کال سنتر');
expect(element.textContent).toContain('این بخش هنوز فعال نیست');
expect(element.textContent).toContain('اتصال برقرار نشده');
expect(element.querySelectorAll('.demo-feature').length).toBe(3);
const inputs = Array.from(element.querySelectorAll('input')) as HTMLInputElement[];
expect(inputs.some((input) => input.value.includes('callcenter.raymand.ir'))).toBe(true);
expect(inputs.some((input) => input.readOnly)).toBe(true);
// every control stays a disabled placeholder
const buttons = Array.from(element.querySelectorAll('button')) as HTMLButtonElement[];
expect(buttons.length).toBeGreaterThan(0);
buttons.forEach((button) => expect(button.disabled).toBe(true));
});
});
@@ -0,0 +1,74 @@
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { CommonModule } from '@angular/common';
interface ConnectionField {
label: string;
value: string;
hint: string;
masked?: boolean;
}
interface CenterFeature {
id: string;
icon: string;
title: string;
description: string;
}
/**
* Symbolic demonstration page for the call-center integration. No backend
* connection exists yet: every value shown is illustrative and the controls
* are disabled placeholders.
*/
@Component({
selector: 'app-call-center',
standalone: true,
imports: [CommonModule],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './call-center.page.html',
styleUrls: ['./call-center.page.css', '../../shared/styles/demo-page.css'],
})
export class CallCenterPage {
readonly connectionFields: ConnectionField[] = [
{
label: 'آدرس سرویس کال سنتر',
value: 'https://callcenter.raymandcti.com/api/v1',
hint: 'مقدار نمونه — آدرس واقعی پس از راه‌اندازی ثبت می‌شود.',
},
{
label: 'کلید API',
value: '••••••••••••••••••••',
hint: 'کلید به‌صورت رمزنگاری‌شده نگهداری می‌شود.',
masked: true,
},
{
label: 'صف پیش‌فرض',
value: 'پشتیبانی',
hint: 'تماس‌های ارجاع‌شده به این صف وصل می‌شوند.',
},
];
readonly features: CenterFeature[] = [
{
id: 'live',
icon: 'M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z',
title: 'تماس‌های در جریان',
description:
'فهرست تماس‌های فعال و وضعیت لحظه‌ای هر کارشناس به‌صورت بلادرنگ نمایش داده می‌شود.',
},
{
id: 'transfer',
icon: 'M8 3 4 7l4 4M4 7h16M16 21l4-4-4-4M20 17H4',
title: 'انتقال از هوش مصنوعی به کارشناس',
description:
'تماس‌هایی که هوش مصنوعی نتوانسته پاسخ دهد، به همراه سابقه گفتگو به کارشناس ارجاع می‌شود.',
},
{
id: 'sync',
icon: 'M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8M21 3v5h-5M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16M8 16H3v5',
title: 'همگام‌سازی وضعیت کارشناسان',
description:
'حاضر بودن، مرخصی و خارج‌شدن کارشناسان بین برنامه و سامانه کال سنتر همگام می‌شود.',
},
];
}
@@ -0,0 +1,6 @@
/* Page-specific styles for «سوالات چت وب اپلیکیشن» (shared chrome: shared/styles/demo-page.css) */
.demo-list-main {
flex: 1 1 22rem;
min-width: 0;
}
@@ -0,0 +1,105 @@
<div class="demo-page">
<header class="demo-header">
<div class="demo-title-group">
<span class="demo-title-icon">
<svg
width="22"
height="22"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z" />
</svg>
</span>
<div>
<h1 class="demo-title">سوالات چت وب اپلیکیشن</h1>
<p class="demo-subtitle">پرسش‌های ثبت‌شده در چت وب اپلیکیشن </p>
</div>
</div>
<span class="demo-chip">نمایشی</span>
</header>
<section class="demo-card demo-notice">
<span class="demo-notice-icon">
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="9" />
<path d="M12 8v4M12 16h.01" />
</svg>
</span>
<div>
<h2>این بخش هنوز فعال نیست</h2>
<p>
این صفحه پرسش‌هایی را که کاربران در چت وب اپلیکیشن ثبت کرده‌اند نمایش می‌دهد. در
فاز جاری این کانال‌ها به برنامه متصل نیستند و موارد زیر صرفاً نمونه هستند؛ پس از اتصال،
پرسش‌های بی‌پاسخ در این صفحه برای بررسی و افزودن به پایگاه دانش نمایش داده می‌شوند.
</p>
</div>
</section>
<section class="demo-card">
<div class="demo-card-header">
<div>
<h2 class="demo-card-title">نمونه پرسش‌های چت</h2>
<p class="demo-card-description">پرسش‌های دریافتی به همراه منبع ثبت و وضعیت پاسخ‌گویی.</p>
</div>
<span class="demo-badge">داده نمونه</span>
</div>
<div class="demo-list">
@for (item of exampleQuestions; track item.id) {
<article class="demo-list-item">
<div class="demo-list-main">
<p class="demo-question">{{ item.question }}</p>
<div class="demo-meta">
<span
class="demo-tag"
[class.demo-tag--answered]="item.statusKind === 'answered'"
[class.demo-tag--pending]="item.statusKind === 'pending'"
>
{{ item.status }}
</span>
<span>{{ item.date }}</span>
</div>
</div>
<button type="button" class="demo-btn demo-btn--outline" disabled>پاسخ به پرسش</button>
</article>
}
</div>
</section>
<section class="demo-card">
<div class="demo-empty">
<svg
width="40"
height="40"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
<path d="M8 10h8M8 14h5" />
</svg>
<h3>پرسشی از چت ثبت نشده است</h3>
<p>
پس از اتصال چت سایت و اپلیکیشن موبایل، پرسش‌های جدید کاربران به‌صورت خودکار در این صفحه
نمایش داده می‌شود تا برای آن‌ها پاسخ ثبت شود.
</p>
</div>
</section>
</div>
@@ -0,0 +1,47 @@
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { ChatQuestionsPage } from './chat-questions.page';
describe('ChatQuestionsPage', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ChatQuestionsPage],
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
],
}).compileComponents();
});
it('should create the page', () => {
const fixture = TestBed.createComponent(ChatQuestionsPage);
expect(fixture.componentInstance).toBeTruthy();
});
it('renders example chat questions with source and status tags', () => {
const fixture = TestBed.createComponent(ChatQuestionsPage);
fixture.detectChanges();
const element: HTMLElement = fixture.nativeElement;
expect(element.querySelector('.demo-title')?.textContent?.trim()).toBe('سوالات چت وب اپلیکیشن');
expect(element.textContent).toContain('این بخش هنوز فعال نیست');
expect(element.textContent).toContain('داده نمونه');
const items = element.querySelectorAll('.demo-list-item');
expect(items.length).toBe(3);
expect(element.querySelectorAll('.demo-tag--site').length).toBe(2);
expect(element.querySelectorAll('.demo-tag--app').length).toBe(1);
expect(element.querySelectorAll('.demo-tag--pending').length).toBe(1);
expect(element.textContent).toContain('هزینه ارسال به شهرستان‌ها چگونه محاسبه می‌شود؟');
const buttons = Array.from(element.querySelectorAll('button')) as HTMLButtonElement[];
buttons.forEach((button) => expect(button.disabled).toBe(true));
});
});
@@ -0,0 +1,52 @@
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { CommonModule } from '@angular/common';
interface ExampleQuestion {
id: string;
question: string;
source: string;
status: string;
statusKind: 'answered' | 'pending';
date: string;
}
/**
* Symbolic demonstration page for questions submitted through the website and
* mobile application chat channels. Example data only; no channel is connected.
*/
@Component({
selector: 'app-chat-questions',
standalone: true,
imports: [CommonModule],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './chat-questions.page.html',
styleUrls: ['./chat-questions.page.css', '../../shared/styles/demo-page.css'],
})
export class ChatQuestionsPage {
readonly exampleQuestions: ExampleQuestion[] = [
{
id: 'q-1',
question: 'برای ایمپورت محصولات جدید چه مراحلی را باید طی کنم؟',
source: 'سایت',
status: 'پاسخ داده شده',
statusKind: 'answered',
date: '۱۴ مهر ۱۴۰۴',
},
{
id: 'q-2',
question: 'هزینه ارسال به شهرستان‌ها چگونه محاسبه می‌شود؟',
source: 'اپلیکیشن',
status: 'در انتظار پاسخ',
statusKind: 'pending',
date: '۱۴ مهر ۱۴۰۴',
},
{
id: 'q-3',
question: 'آیا امکان لغو سفارش پس از پرداخت وجود دارد؟',
source: 'سایت',
status: 'پاسخ داده شده',
statusKind: 'answered',
date: '۱۳ مهر ۱۴۰۴',
},
];
}
+333
View File
@@ -0,0 +1,333 @@
/* ==========================================================================
Layout: .home-page > .chat-column > ( .transcript-list + .composer )
- Landing (no conversation): greeting + composer are centered as one group.
- Conversation: the greeting collapses, the transcript list grows to fill the
column (it is the only scroller) and the composer sits at the bottom.
========================================================================== */
.home-page {
position: relative;
display: flex;
flex-direction: column;
height: 100dvh;
min-height: 100dvh;
box-sizing: border-box;
overflow: hidden;
background:
radial-gradient(ellipse 50% 40% at 50% 45%, rgba(59, 130, 246, 0.1), transparent 70%),
var(--app-bg);
}
.home-page::before {
content: '';
position: absolute;
inset: 0;
background:
radial-gradient(circle at 50% 40%, rgba(59, 130, 246, 0.07), transparent 55%),
radial-gradient(circle at 35% 55%, rgba(99, 102, 241, 0.05), transparent 50%),
radial-gradient(circle at 65% 50%, rgba(59, 130, 246, 0.04), transparent 45%);
pointer-events: none;
z-index: 0;
transition: opacity 0.5s ease;
}
.home-page.has-conversation {
background: var(--app-bg);
}
.home-page.has-conversation::before {
opacity: 0;
}
/* ---------- Logo (landing only) ---------- */
.home-header {
position: absolute;
top: 2rem;
left: 50%;
transform: translateX(-50%);
z-index: 1;
text-align: center;
opacity: 1;
transition: opacity 0.35s ease, transform 0.35s ease;
}
.home-page.has-conversation .home-header {
opacity: 0;
transform: translateX(-50%) translateY(-8px);
pointer-events: none;
}
.home-icon-wrapper {
display: inline-flex;
align-items: center;
justify-content: center;
width: 140px;
height: 140px;
border-radius: 50%;
background: transparent;
margin-bottom: 1.5rem;
padding: 0.75rem;
}
.home-logo {
width: 100%;
height: 100%;
object-fit: contain;
display: block;
}
/* ---------- chat column ---------- */
.chat-column {
position: relative;
z-index: 1;
flex: 1 1 auto;
min-height: 0;
width: 100%;
display: flex;
flex-direction: column;
justify-content: center; /* landing: greeting + composer centered together */
}
.home-page.has-conversation .chat-column {
justify-content: flex-start;
}
/* ---------- greeting (typed title) ---------- */
.home-greeting {
flex: none;
box-sizing: border-box;
max-height: 8rem;
padding: 0 1rem;
overflow: hidden;
opacity: 1;
transition:
max-height 0.5s cubic-bezier(0.22, 1, 0.36, 1),
opacity 0.3s ease;
}
.home-page.has-conversation .home-greeting {
max-height: 0;
opacity: 0;
pointer-events: none;
}
.home-title {
width: 100%;
margin: 0 0 1rem;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
direction: rtl;
font-size: 1.45rem;
font-weight: 400;
line-height: 1.5;
color: var(--text-primary);
}
.home-title-text {
white-space: pre-wrap;
}
.cursor {
display: inline-block;
width: 2px;
height: 1.15em;
margin-right: 3px;
background-color: var(--text-primary);
border-radius: 1px;
animation: cursorBlink 0.8s ease-in-out infinite;
flex-shrink: 0;
}
.cursor-hidden {
display: none;
}
@keyframes cursorBlink {
0%,
45% {
opacity: 1;
}
46%,
100% {
opacity: 0;
}
}
/* ---------- transcript list (the page's only scroller) ---------- */
.transcript-list {
flex: 0 1 auto;
min-height: 0;
overflow-x: hidden;
overflow-y: auto;
overscroll-behavior: contain;
transition: flex-grow 0.5s cubic-bezier(0.22, 1, 0.36, 1);
}
.home-page.has-conversation .transcript-list {
flex-grow: 1;
}
.transcript-list::-webkit-scrollbar {
width: 6px;
}
.transcript-list::-webkit-scrollbar-thumb {
background: var(--muted);
border-radius: 9999px;
}
/* Same width as the composer so text and input line up */
.transcript-inner {
box-sizing: border-box;
display: flex;
flex-direction: column;
width: 100%;
max-width: 800px;
min-height: 100%;
margin: 0 auto;
padding: 0 1rem;
}
.home-page.has-conversation .transcript-inner {
padding: 1.5rem 1rem 1rem;
}
.transcript-empty {
margin: auto;
font-size: 0.875rem;
color: var(--muted);
text-align: center;
}
/* ---------- composer (call bar + chat input) ---------- */
.composer {
position: relative;
z-index: 2;
flex: none;
box-sizing: border-box;
padding: 0 1rem 1rem;
}
.home-page.has-conversation .composer {
padding-bottom: calc(1rem + env(safe-area-inset-bottom, 0px));
}
/* Transcript text fades out under the composer instead of being cut off */
.composer::before {
content: '';
position: absolute;
inset-inline: 0;
bottom: 100%;
height: 1.5rem;
background: linear-gradient(to top, var(--app-bg), transparent);
pointer-events: none;
opacity: 0;
transition: opacity 0.3s ease;
}
.home-page.has-conversation .composer::before {
opacity: 1;
}
.composer > :not(.jump-to-latest) {
max-width: 800px;
margin-inline: auto;
}
.home-call-dock {
margin-bottom: 0.5rem;
}
/* ---------- jump to latest ---------- */
.jump-to-latest {
position: absolute;
bottom: calc(100% + 0.5rem);
left: 50%;
transform: translateX(-50%);
display: inline-flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
border: 1px solid var(--surface-border);
border-radius: 50%;
background: var(--surface-bg);
color: var(--text-secondary);
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.12);
cursor: pointer;
animation: jumpIn 0.2s ease;
transition: background 0.2s ease, color 0.2s ease;
}
.jump-to-latest:hover {
background: var(--sidebar-hover);
color: var(--text-primary);
}
.jump-to-latest:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
@keyframes jumpIn {
from {
opacity: 0;
transform: translateX(-50%) translateY(6px);
}
to {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
}
/* ---------- responsive ---------- */
@media (max-width: 640px) {
.home-header {
top: 1.25rem;
}
.home-icon-wrapper {
width: 100px;
height: 100px;
padding: 0.5rem;
}
.home-title {
font-size: 1.375rem;
}
.composer {
padding: 0 0.75rem 0.75rem;
}
.home-page.has-conversation .composer {
padding-bottom: calc(0.75rem + env(safe-area-inset-bottom, 0px));
}
.transcript-inner {
padding-inline: 0.75rem;
}
.home-page.has-conversation .transcript-inner {
padding: 1rem 0.75rem 0.75rem;
}
}
@media (prefers-reduced-motion: reduce) {
.home-page,
.home-page::before,
.home-header,
.home-greeting,
.transcript-list,
.composer::before,
.jump-to-latest {
transition: none !important;
animation: none !important;
}
}
+67
View File
@@ -0,0 +1,67 @@
<div class="home-page" [class.has-conversation]="hasConversation()">
<!-- Brand logo: shown only on the empty landing state -->
<div class="home-header" aria-hidden="true">
<div class="home-icon-wrapper">
<img class="home-logo" [src]="logoSrc()" alt="Raymand" />
</div>
</div>
<!-- chat column: transcript list on top, composer docked at the bottom -->
<div class="chat-column">
<div class="home-greeting" [attr.aria-hidden]="hasConversation() ? 'true' : null">
<h1 class="home-title">
<span class="home-title-text">{{ streamedText() }}</span>
<span class="cursor" [class.cursor-hidden]="!isStreaming()" aria-hidden="true"></span>
</h1>
</div>
<!-- transcript list: the only scrolling region of the page -->
<div
class="transcript-list"
#transcriptList
role="log"
aria-label="متن گفتگو"
aria-live="polite"
aria-relevant="additions"
(scroll)="onTranscriptScroll()"
>
<div class="transcript-inner">
@if (callOpen() && voiceMessages().length === 0) {
<p class="transcript-empty">صحبت کنید؛ گفتگو اینجا نمایش داده می‌شود</p>
}
<app-voice-transcript [messages]="voiceMessages()" />
</div>
</div>
<!-- composer: call bar (while a call runs) + the chat input -->
<div class="composer">
@if (jumpVisible()) {
<button
type="button"
class="jump-to-latest"
aria-label="رفتن به آخرین پیام"
(click)="scrollToLatest()"
>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M12 5v14M5 12l7 7 7-7" />
</svg>
</button>
}
@if (callDockMounted()) {
<app-voice-stream-panel class="home-call-dock" />
}
<app-ai-chat-input
data-chat-input
placeholder="پیام خود را بنویسید..."
(messageSent)="onMessageSent($event)"
(fileSelected)="onFileSelected($event)"
(voiceToggled)="onVoiceToggled($event)"
/>
</div>
</div>
</div>
+226
View File
@@ -0,0 +1,226 @@
import {
ChangeDetectionStrategy,
Component,
ElementRef,
OnDestroy,
OnInit,
computed,
effect,
inject,
signal,
viewChild,
} from '@angular/core';
import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
import { Subscription } from 'rxjs';
import { AiChatInputComponent } from '../../shared/ui/ai-chat-input/ai-chat-input.component';
import { VoiceStreamPanelComponent } from '../../shared/ui/voice-stream-panel/voice-stream-panel.component';
import { VoiceTranscriptComponent } from '../../shared/ui/voice-transcript/voice-transcript.component';
import { VoiceStreamService } from '../../services/voice-stream/voice-stream.service';
import { ThemeService } from '../../services/theme/theme.service';
const HOME_TITLES = [
'چه چیزی می‌خواهید بدانید؟',
'سوالتان را بپرسید، با شما هستم...',
'هر سوالی دارید، از من بپرسید...',
'از هر چیزی که می‌خواهید شروع کنید...',
'سوالتان را مطرح کنید، پاسخ می‌دهم...',
'بپرسید؛ با هم به پاسخ می‌رسیم...',
'هر سوالی در ذهن دارید، بپرسید...',
'دنبال یک پاسخ دقیق هستید؟',
'سوالتان را همین‌جا مطرح کنید...',
'آماده‌ام به سوالتان پاسخ بدهم...',
];
/** Keeps the call bar mounted this long after the call ends so it can fade/collapse out (matches the CSS). */
const CALL_DOCK_EXIT_MS = 400;
/** Within this distance of the bottom the list keeps following new text. */
const STICK_TO_BOTTOM_PX = 80;
@Component({
selector: 'app-home',
standalone: true,
imports: [AiChatInputComponent, VoiceStreamPanelComponent, VoiceTranscriptComponent],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './home.page.html',
styleUrl: './home.page.css',
})
export class HomePage implements OnInit, OnDestroy {
private readonly themeService = inject(ThemeService);
private readonly router = inject(Router);
private readonly voiceStream = inject(VoiceStreamService);
readonly isDarkMode = this.themeService.isDarkMode;
readonly logoSrc = () =>
this.isDarkMode() ? 'assets/images/RaymandLogo.png' : 'assets/images/login.png';
// ---- conversation state ---------------------------------------------------
readonly hasMessages = signal(false);
readonly callOpen = this.voiceStream.isOpen;
readonly voiceMessages = this.voiceStream.messages;
/** Anything on screen that belongs in the chat column: text sent, a live call, or a finished call's transcript. */
readonly hasConversation = computed(
() => this.hasMessages() || this.callOpen() || this.voiceMessages().length > 0,
);
/** The call bar stays mounted briefly after the call ends so it can animate out. */
readonly callDockMounted = signal(false);
readonly jumpVisible = signal(false);
// ---- title typing ---------------------------------------------------------
readonly homeTitle = signal('');
readonly streamedText = signal('');
readonly isStreaming = signal(false);
private readonly listRef = viewChild<ElementRef<HTMLElement>>('transcriptList');
private stickToBottom = true;
private scrollFrame: number | null = null;
private dockTimer: ReturnType<typeof setTimeout> | null = null;
private typingTimer: ReturnType<typeof setTimeout> | null = null;
private routerSubscription?: Subscription;
constructor() {
this.routerSubscription = this.router.events
.pipe(filter((event) => event instanceof NavigationEnd))
.subscribe((event: NavigationEnd) => {
if (event.url === '/' || event.url === '') {
this.hasMessages.set(false);
this.setRandomTitle();
}
});
// Mount the call bar when a call starts; unmount it after the exit animation.
toObservable(this.callOpen)
.pipe(takeUntilDestroyed())
.subscribe((open) => {
this.clearDockTimer();
if (open) {
this.callDockMounted.set(true);
} else if (this.callDockMounted()) {
this.dockTimer = setTimeout(() => {
this.dockTimer = null;
this.callDockMounted.set(false);
}, CALL_DOCK_EXIT_MS);
}
});
// Follow new transcript text, unless the user scrolled up to read.
effect(() => {
this.voiceMessages();
this.callOpen();
if (this.stickToBottom) this.scheduleScrollToBottom();
});
}
ngOnInit(): void {
this.setRandomTitle();
}
ngOnDestroy(): void {
this.stopTyping();
this.clearDockTimer();
if (this.scrollFrame !== null) cancelAnimationFrame(this.scrollFrame);
this.routerSubscription?.unsubscribe();
}
// ---- transcript list scrolling -------------------------------------------
onTranscriptScroll(): void {
const el = this.listRef()?.nativeElement;
if (!el) return;
const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
this.stickToBottom = distance < STICK_TO_BOTTOM_PX;
this.jumpVisible.set(!this.stickToBottom && this.hasConversation());
}
scrollToLatest(): void {
this.stickToBottom = true;
this.jumpVisible.set(false);
this.listRef()?.nativeElement.scrollTo({
top: this.listRef()!.nativeElement.scrollHeight,
behavior: 'smooth',
});
}
private scheduleScrollToBottom(): void {
if (this.scrollFrame !== null) return;
this.scrollFrame = requestAnimationFrame(() => {
this.scrollFrame = null;
const el = this.listRef()?.nativeElement;
if (el) el.scrollTo({ top: el.scrollHeight, behavior: 'instant' });
});
}
private clearDockTimer(): void {
if (this.dockTimer !== null) {
clearTimeout(this.dockTimer);
this.dockTimer = null;
}
}
// ---- title typing (unchanged) ---------------------------------------------
private setRandomTitle(): void {
this.stopTyping();
const index = Math.floor(Math.random() * HOME_TITLES.length);
const title = HOME_TITLES[index];
this.homeTitle.set(title);
this.startTyping(title);
}
private startTyping(text: string): void {
this.streamedText.set('');
this.isStreaming.set(true);
let index = 0;
const typeNextCharacter = () => {
if (index >= text.length) {
this.streamedText.set(text);
this.isStreaming.set(false);
this.typingTimer = null;
return;
}
index++;
this.streamedText.set(text.substring(0, index));
// Slightly random timing makes it feel more natural
const delay = 16 + Math.random() * 8;
this.typingTimer = setTimeout(typeNextCharacter, delay);
};
typeNextCharacter();
}
private stopTyping(): void {
if (this.typingTimer !== null) {
clearTimeout(this.typingTimer);
this.typingTimer = null;
}
this.isStreaming.set(false);
}
// ---- composer events ------------------------------------------------------
onMessageSent(message: string): void {
this.hasMessages.set(true);
console.log('Message sent:', message);
}
onFileSelected(file: File): void {
console.log('File selected:', file.name);
}
onVoiceToggled(active: boolean): void {
console.log('Voice mode:', active ? 'active' : 'inactive');
}
}
+894
View File
@@ -0,0 +1,894 @@
.login-page {
position: relative;
display: flex;
align-items: center;
justify-content: center;
min-height: 100dvh;
padding: 1.5rem 1rem;
box-sizing: border-box;
overflow: hidden;
background: #0f172a;
transition: background 0.6s ease;
}
.login-page.shaking {
overflow: hidden;
}
.login-card {
position: relative;
z-index: 1;
width: 100%;
max-width: 440px;
perspective: 1200px;
will-change: transform;
transform: translate3d(0, 0, 0);
transition: transform 0.5s cubic-bezier(0.22, 1, 0.36, 1);
}
.login-card.enter {
animation: cardEntrance 1s cubic-bezier(0.22, 1, 0.36, 1) both;
}
.login-card.shaking {
animation: shake 0.7s cubic-bezier(0.22, 1, 0.36, 1) forwards;
}
.login-ambient-bg {
position: absolute;
inset: 0;
overflow: hidden;
pointer-events: none;
z-index: 0;
}
.particles {
position: absolute;
inset: 0;
background-image:
radial-gradient(circle, rgba(148, 163, 184, 0.08) 1px, transparent 1px),
radial-gradient(circle, rgba(148, 163, 184, 0.06) 1px, transparent 1px);
background-size: 50px 50px, 80px 80px;
background-position: 0 0, 25px 25px;
}
.particles-spotlight {
position: absolute;
inset: 0;
background-image:
radial-gradient(circle, rgba(148, 163, 184, 0.35) 1px, transparent 1px),
radial-gradient(circle, rgba(148, 163, 184, 0.25) 1px, transparent 1px);
background-size: 50px 50px, 80px 80px;
background-position: 0 0, 25px 25px;
mask-image: radial-gradient(
circle 200px at var(--mouse-x) var(--mouse-y),
black 0%,
black 25%,
transparent 65%
);
-webkit-mask-image: radial-gradient(
circle 200px at var(--mouse-x) var(--mouse-y),
black 0%,
black 25%,
transparent 65%
);
transition: mask-image 0.12s ease-out;
}
@keyframes particlesFloat {
0% {
transform: translateY(0);
}
100% {
transform: translateY(-50px);
}
}
.blob {
position: absolute;
border-radius: 50%;
filter: blur(90px);
opacity: 0.55;
animation: floatBlob 14s ease-in-out infinite;
will-change: transform;
}
.blob-1 {
width: 520px;
height: 520px;
background: radial-gradient(circle, rgba(59, 130, 246, 0.5), transparent 70%);
top: -18%;
right: -12%;
animation-delay: 0s;
animation-duration: 16s;
}
.blob-2 {
width: 420px;
height: 420px;
background: radial-gradient(circle, rgba(139, 92, 246, 0.4), transparent 70%);
bottom: -14%;
left: -10%;
animation-delay: -6s;
animation-duration: 18s;
}
.blob-3 {
width: 360px;
height: 360px;
background: radial-gradient(circle, rgba(59, 130, 246, 0.35), transparent 70%);
top: 45%;
left: 45%;
animation-delay: -11s;
animation-duration: 20s;
}
@keyframes floatBlob {
0%,
100% {
transform: translate(0, 0) scale(1);
}
25% {
transform: translate(50px, -40px) scale(1.1);
}
50% {
transform: translate(-30px, 35px) scale(0.92);
}
75% {
transform: translate(-45px, -20px) scale(1.06);
}
}
.login-card-inner {
position: relative;
background: rgba(15, 23, 42, 0.65);
border: 1px solid rgba(148, 163, 184, 0.15);
border-radius: 1.5rem;
padding: 2.5rem 2rem 2rem;
box-shadow:
0 0 0 1px rgba(255, 255, 255, 0.05) inset,
0 20px 50px -12px rgba(0, 0, 0, 0.5),
0 0 80px -20px rgba(59, 130, 246, 0.3);
transition:
background 0.6s ease,
border-color 0.6s ease,
box-shadow 0.6s ease,
transform 0.4s cubic-bezier(0.22, 1, 0.36, 1);
animation: innerReveal 1.1s cubic-bezier(0.22, 1, 0.36, 1) 0.12s both;
transform-style: preserve-3d;
}
.login-card-inner:hover {
transform: translateY(-4px) rotateX(2deg);
box-shadow:
0 0 0 1px rgba(255, 255, 255, 0.08) inset,
0 30px 70px -15px rgba(0, 0, 0, 0.6),
0 0 100px -20px rgba(59, 130, 246, 0.4);
}
.login-spotlight {
position: absolute;
inset: 0;
border-radius: inherit;
background: radial-gradient(
700px circle at var(--mouse-x) var(--mouse-y),
rgba(59, 130, 246, 0.2),
transparent 40%
);
pointer-events: none;
z-index: 0;
opacity: 0;
transition: opacity 0.5s ease;
mix-blend-mode: screen;
}
.login-card-inner:hover .login-spotlight {
opacity: 1;
}
.login-glow-border {
position: absolute;
inset: -1px;
border-radius: inherit;
background: radial-gradient(
500px circle at var(--mouse-x) var(--mouse-y),
rgba(59, 130, 246, 0.7),
transparent 50%
);
pointer-events: none;
z-index: -1;
opacity: 0;
transition: opacity 0.5s ease;
mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
mask-composite: exclude;
padding: 1px;
}
.login-card-inner:hover .login-glow-border {
opacity: 1;
}
.login-header {
position: relative;
z-index: 1;
text-align: center;
margin-bottom: 2rem;
animation: fadeInUp 0.9s cubic-bezier(0.22, 1, 0.36, 1) 0.2s both;
}
.login-logo-wrapper {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
width: 96px;
height: 96px;
border-radius: 50%;
background: rgba(59, 130, 246, 0.1);
margin-bottom: 1.25rem;
padding: 0.625rem;
cursor: pointer;
transition: all 0.5s cubic-bezier(0.22, 1, 0.36, 1);
animation: logoEntrance 1.1s cubic-bezier(0.22, 1, 0.36, 1) 0.25s both;
}
.login-logo-wrapper:hover {
transform: scale(1.12) rotate(10deg);
background: rgba(59, 130, 246, 0.2);
box-shadow: 0 0 50px rgba(59, 130, 246, 0.4);
}
.logo-ring {
position: absolute;
inset: -6px;
border-radius: 50%;
border: 2px solid transparent;
background: linear-gradient(135deg, rgba(59, 130, 246, 0.7), rgba(139, 92, 246, 0.4), rgba(59, 130, 246, 0.7)) border-box;
mask: linear-gradient(#fff 0 0) padding-box, linear-gradient(#fff 0 0);
mask-composite: exclude;
-webkit-mask-composite: xor;
animation: logoRingPulse 3s ease-in-out infinite;
}
@keyframes logoRingPulse {
0%,
100% {
opacity: 0.5;
transform: scale(1) rotate(0deg);
}
50% {
opacity: 1;
transform: scale(1.15) rotate(180deg);
}
}
.login-logo {
position: relative;
z-index: 1;
width: 100%;
height: 100%;
object-fit: contain;
display: block;
transition: transform 0.5s cubic-bezier(0.22, 1, 0.36, 1);
filter: drop-shadow(0 4px 16px rgba(0, 0, 0, 0.4));
}
.login-logo-wrapper:hover .login-logo {
transform: scale(1.1) rotate(-8deg);
}
.login-title {
margin: 0 0 0.5rem;
font-size: 1.75rem;
font-weight: 700;
color: #f1f5f9;
line-height: 1.3;
letter-spacing: -0.02em;
text-shadow: 0 2px 8px rgba(0, 0, 0, 0.4);
animation: titleGlow 4s ease-in-out infinite;
}
@keyframes titleGlow {
0%,
100% {
text-shadow: 0 2px 8px rgba(0, 0, 0, 0.4), 0 0 0 transparent;
}
50% {
text-shadow: 0 2px 8px rgba(0, 0, 0, 0.4), 0 0 40px rgba(59, 130, 246, 0.5), 0 0 80px rgba(139, 92, 246, 0.3);
}
}
.login-subtitle {
margin: 0;
font-size: 0.9375rem;
color: #94a3b8;
line-height: 1.5;
animation: fadeInUp 0.9s cubic-bezier(0.22, 1, 0.36, 1) 0.3s both;
}
.login-form {
position: relative;
z-index: 1;
display: flex;
flex-direction: column;
gap: 1.25rem;
animation: formReveal 1s cubic-bezier(0.22, 1, 0.36, 1) 0.4s both;
}
@keyframes formReveal {
from {
opacity: 0;
transform: translateY(32px) scale(0.94);
}
to {
opacity: 1;
transform: translateY(0) scale(1);
}
}
.form-field {
position: relative;
display: flex;
flex-direction: column;
gap: 0.5rem;
animation: fieldSlideIn 0.8s cubic-bezier(0.22, 1, 0.36, 1) both;
}
.form-field:nth-child(1) {
animation-delay: 0.5s;
}
.form-field:nth-child(2) {
animation-delay: 0.65s;
}
@keyframes fieldSlideIn {
from {
opacity: 0;
transform: translateX(-20px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
.form-label {
display: block;
font-size: 0.875rem;
font-weight: 500;
color: #e2e8f0;
line-height: 1.4;
transition: color 0.3s ease;
}
.form-field:focus-within .form-label {
color: #60a5fa;
}
.input-wrapper {
position: relative;
display: flex;
align-items: center;
}
.input-icon {
position: absolute;
right: 0.875rem;
top: 50%;
transform: translateY(-50%);
color: #64748b;
pointer-events: none;
display: flex;
align-items: center;
transition: all 0.3s ease;
}
.form-field:focus-within .input-icon {
color: #60a5fa;
transform: translateY(-50%) scale(1.2);
}
.login-page .form-input {
width: 100%;
padding: 0.875rem 2.75rem 0.875rem 0.875rem;
border: 1.5px solid rgba(148, 163, 184, 0.2);
border-radius: 0.75rem;
background-color: rgba(15, 23, 42, 0.6) !important;
background: rgba(15, 23, 42, 0.6) !important;
color: #f1f5f9 !important;
font-family: inherit;
font-size: 0.9375rem;
line-height: 1.5;
transition: all 0.3s cubic-bezier(0.22, 1, 0.36, 1);
box-sizing: border-box;
appearance: none !important;
-webkit-appearance: none !important;
-moz-appearance: none !important;
}
.login-page .form-input:-webkit-autofill,
.login-page .form-input:-webkit-autofill:hover,
.login-page .form-input:-webkit-autofill:focus,
.login-page .form-input:-webkit-autofill:active {
-webkit-box-shadow: 0 0 0 1000px rgba(15, 23, 42, 0.85) inset !important;
box-shadow: 0 0 0 1000px rgba(15, 23, 42, 0.85) inset !important;
-webkit-text-fill-color: #f1f5f9 !important;
caret-color: #f1f5f9 !important;
border-color: rgba(148, 163, 184, 0.2) !important;
transition: background-color 5000s ease-in-out 0s;
}
.login-page .form-input:autofill {
background-color: rgba(15, 23, 42, 0.85) !important;
color: #f1f5f9 !important;
-webkit-text-fill-color: #f1f5f9 !important;
}
.login-page .form-input:disabled:-webkit-autofill {
-webkit-box-shadow: 0 0 0 1000px rgba(15, 23, 42, 0.4) inset !important;
box-shadow: 0 0 0 1000px rgba(15, 23, 42, 0.4) inset !important;
}
.login-page .form-input::placeholder {
color: #64748b;
opacity: 0.8;
}
.login-page .form-input:focus {
outline: none;
border-color: #3b82f6;
background-color: rgba(15, 23, 42, 0.8) !important;
background: rgba(15, 23, 42, 0.8) !important;
box-shadow:
0 0 0 4px rgba(59, 130, 246, 0.15),
0 0 40px rgba(59, 130, 246, 0.25),
0 0 0 1px rgba(59, 130, 246, 0.4) inset;
transform: translateY(-2px);
}
.login-page .form-input:disabled {
opacity: 0.5;
cursor: not-allowed;
background-color: rgba(15, 23, 42, 0.4) !important;
background: rgba(15, 23, 42, 0.4) !important;
}
.login-page .form-field.has-error .form-input {
border-color: #ef4444;
box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.15);
animation: errorPulse 2s ease-in-out infinite;
}
@keyframes errorPulse {
0%,
100% {
box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.15);
}
50% {
box-shadow: 0 0 0 8px rgba(239, 68, 68, 0.08);
}
}
.form-field.has-error .input-icon {
color: #ef4444;
}
.field-error {
display: flex;
align-items: center;
gap: 0.375rem;
font-size: 0.8125rem;
color: #f87171;
line-height: 1.4;
animation: errorShake 0.5s ease both;
}
@keyframes errorShake {
0%,
100% {
transform: translateX(0);
}
20% {
transform: translateX(-5px);
}
40% {
transform: translateX(5px);
}
60% {
transform: translateX(-4px);
}
80% {
transform: translateX(4px);
}
}
.password-toggle {
position: absolute;
left: 0.625rem;
top: 50%;
transform: translateY(-50%);
display: inline-flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
border: none;
background: transparent;
color: #64748b;
border-radius: 0.5rem;
cursor: pointer;
transition: all 0.2s ease;
padding: 0;
}
.password-toggle:hover {
color: #e2e8f0;
background: rgba(59, 130, 246, 0.15);
transform: translateY(-50%) scale(1.2);
}
.password-toggle:active {
transform: translateY(-50%) scale(0.9);
}
.password-toggle:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.form-options {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
animation: fadeInUp 0.9s cubic-bezier(0.22, 1, 0.36, 1) 0.8s both;
}
.remember-me {
display: flex;
align-items: center;
gap: 0.5rem;
cursor: pointer;
user-select: none;
position: relative;
}
.remember-checkbox {
width: 1.125rem;
height: 1.125rem;
accent-color: #3b82f6;
cursor: pointer;
flex-shrink: 0;
transition: transform 0.2s ease;
filter: invert(1) brightness(0.9);
}
.remember-checkbox:checked {
filter: invert(0) brightness(1);
}
.remember-me:hover .remember-checkbox {
transform: scale(1.25);
}
.remember-label {
font-size: 0.875rem;
color: #cbd5e1;
line-height: 1.4;
}
.general-error {
display: flex;
align-items: center;
gap: 0.625rem;
padding: 0.875rem 1rem;
background: rgba(239, 68, 68, 0.1);
border: 1px solid rgba(239, 68, 68, 0.25);
border-radius: 0.75rem;
color: #fca5a5;
font-size: 0.875rem;
line-height: 1.4;
animation: errorReveal 0.5s cubic-bezier(0.22, 1, 0.36, 1) both;
box-shadow: 0 0 25px rgba(239, 68, 68, 0.2);
}
@keyframes errorReveal {
from {
opacity: 0;
transform: translateY(-10px) scale(0.95);
}
to {
opacity: 1;
transform: translateY(0) scale(1);
}
}
.login-submit {
position: relative;
display: flex;
align-items: center;
justify-content: center;
gap: 0.625rem;
width: 100%;
padding: 0.9375rem 1.5rem;
border: none;
border-radius: 0.75rem;
background: linear-gradient(135deg, #3b82f6 0%, #6366f1 50%, #8b5cf6 100%);
background-size: 200% 200%;
color: #ffffff;
font-family: inherit;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
overflow: hidden;
transition: all 0.4s cubic-bezier(0.22, 1, 0.36, 1);
box-shadow:
0 0 0 1px rgba(255, 255, 255, 0.1) inset,
0 4px 20px rgba(59, 130, 246, 0.5),
0 0 50px rgba(99, 102, 241, 0.4);
animation: submitEntrance 1s cubic-bezier(0.22, 1, 0.36, 1) 0.75s both;
}
.login-submit::before {
content: '';
position: absolute;
inset: 0;
background: linear-gradient(
135deg,
rgba(255, 255, 255, 0) 0%,
rgba(255, 255, 255, 0.3) 50%,
rgba(255, 255, 255, 0) 100%
);
transform: translateX(-100%) skewX(-25deg);
transition: transform 0.8s ease;
}
.login-submit:hover:not(:disabled)::before {
transform: translateX(100%) skewX(-25deg);
}
.login-submit::after {
content: '';
position: absolute;
inset: 0;
background: radial-gradient(
circle at center,
rgba(255, 255, 255, 0.25) 0%,
transparent 70%
);
opacity: 0;
transition: opacity 0.3s ease;
}
.login-submit:active:not(:disabled)::after {
opacity: 1;
}
.login-submit:hover:not(:disabled) {
transform: translateY(-3px);
background-position: 100% 0;
box-shadow:
0 0 0 1px rgba(255, 255, 255, 0.2) inset,
0 10px 30px rgba(59, 130, 246, 0.6),
0 0 80px rgba(99, 102, 241, 0.5);
}
.login-submit:active:not(:disabled) {
transform: translateY(0) scale(0.96);
box-shadow:
0 0 0 1px rgba(255, 255, 255, 0.1) inset,
0 2px 10px rgba(59, 130, 246, 0.5),
0 0 40px rgba(99, 102, 241, 0.3);
transition: all 0.1s ease;
}
.login-submit:disabled {
opacity: 0.5;
cursor: not-allowed;
transform: none;
}
.login-submit.loading {
pointer-events: none;
}
.btn-shimmer {
position: absolute;
inset: 0;
background: linear-gradient(
90deg,
transparent 0%,
rgba(255, 255, 255, 0.2) 50%,
transparent 100%
);
animation: shimmer 3s ease-in-out infinite;
}
@keyframes shimmer {
0% {
transform: translateX(-100%);
}
100% {
transform: translateX(100%);
}
}
.btn-text {
position: relative;
z-index: 1;
}
.btn-arrow {
position: relative;
z-index: 1;
display: inline-flex;
transition: transform 0.4s cubic-bezier(0.22, 1, 0.36, 1);
}
.login-submit:hover:not(:disabled) .btn-arrow {
transform: translateX(8px);
}
.spinner {
width: 1.25rem;
height: 1.25rem;
border: 2.5px solid rgba(255, 255, 255, 0.2);
border-top-color: #ffffff;
border-radius: 50%;
animation: spin 0.7s linear infinite;
flex-shrink: 0;
position: relative;
z-index: 1;
box-shadow: 0 0 15px rgba(255, 255, 255, 0.4);
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(24px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes logoEntrance {
from {
opacity: 0;
transform: scale(0.4) translateY(30px) rotate(-20deg);
}
to {
opacity: 1;
transform: scale(1) translateY(0) rotate(0deg);
}
}
@keyframes cardEntrance {
from {
opacity: 0;
transform: translateY(60px) scale(0.8) rotateX(15deg);
}
to {
opacity: 1;
transform: translateY(0) scale(1) rotateX(0deg);
}
}
@keyframes innerReveal {
from {
opacity: 0;
transform: scale(0.88);
}
to {
opacity: 1;
transform: scale(1);
}
}
@keyframes shake {
0%,
100% {
transform: translate3d(0, 0, 0);
}
12% {
transform: translate3d(-10px, 0, 0);
}
24% {
transform: translate3d(10px, 0, 0);
}
36% {
transform: translate3d(-8px, 0, 0);
}
48% {
transform: translate3d(8px, 0, 0);
}
60% {
transform: translate3d(-5px, 0, 0);
}
72% {
transform: translate3d(5px, 0, 0);
}
84% {
transform: translate3d(-2px, 0, 0);
}
}
@media (max-width: 480px) {
.login-page {
padding: 1rem 0.75rem;
align-items: flex-start;
padding-top: 3.5rem;
}
.login-card-inner {
padding: 2rem 1.25rem 1.5rem;
border-radius: 1.25rem;
}
.login-logo-wrapper {
width: 80px;
height: 80px;
padding: 0.5rem;
}
.login-title {
font-size: 1.375rem;
}
.login-subtitle {
font-size: 0.875rem;
}
.form-input {
padding: 0.75rem 2.5rem 0.75rem 0.75rem;
font-size: 0.875rem;
}
.login-submit {
padding: 0.8125rem 1.25rem;
font-size: 0.9375rem;
}
}
@media (min-width: 1024px) {
.login-page {
padding: 2rem;
}
.login-card-inner {
padding: 3rem 2.5rem 2.5rem;
}
}
@media (prefers-reduced-motion: reduce) {
.login-page,
.login-card,
.login-card-inner,
.login-header,
.login-logo-wrapper,
.login-form,
.form-options,
.login-submit,
.form-field {
animation: none !important;
transition: none !important;
}
.blob {
animation: none !important;
}
.login-submit::before,
.btn-shimmer,
.login-spotlight {
display: none;
}
}
+225
View File
@@ -0,0 +1,225 @@
<div class="login-page" (mousemove)="onCardMouseMove($event)" (mouseleave)="onCardMouseLeave()">
<div class="login-ambient-bg" aria-hidden="true">
<span class="blob blob-1"></span>
<span class="blob blob-2"></span>
<span class="blob blob-3"></span>
<div
class="particles"
aria-hidden="true"
[style.--mouse-x]="mousePosition().x + '%'"
[style.--mouse-y]="mousePosition().y + '%'"
>
<div class="particles-spotlight" aria-hidden="true"></div>
</div>
</div>
<div class="login-card" [class.enter]="isEntering()" [class.shaking]="isShaking()">
<div
class="login-card-inner"
[style.--mouse-x]="mousePosition().x + '%'"
[style.--mouse-y]="mousePosition().y + '%'"
>
<div class="login-spotlight" aria-hidden="true"></div>
<div class="login-glow-border" aria-hidden="true"></div>
<div class="login-header">
<div class="login-logo-wrapper">
<div class="logo-ring" aria-hidden="true"></div>
<img
class="login-logo"
src="assets/images/RaymandLogo.png"
alt="Raymand"
(click)="onLogoClick()"
/>
</div>
<h1 class="login-title">ورود به حساب کاربری</h1>
</div>
<form class="login-form" (ngSubmit)="onSubmit()" novalidate autocomplete="on">
<div class="form-field" [class.has-error]="errors().username">
<label for="login-username" class="form-label"> نام کاربری </label>
<div class="input-wrapper">
<span class="input-icon" aria-hidden="true">
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
<circle cx="12" cy="7" r="4" />
</svg>
</span>
<input
id="login-username"
type="text"
class="form-input"
[value]="username()"
(input)="username.set($any($event.target).value)"
(blur)="onFieldBlur('username')"
placeholder="نام کاربری خود را وارد کنید"
autocomplete="username"
[disabled]="isLoading()"
aria-invalid="!!errors().username"
aria-describedby="username-error"
/>
</div>
@if (errors().username) {
<span id="username-error" class="field-error" role="alert">
{{ errors().username }}
</span>
}
</div>
<div class="form-field" [class.has-error]="errors().password">
<label for="login-password" class="form-label"> رمز عبور </label>
<div class="input-wrapper">
<span class="input-icon" aria-hidden="true">
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
<path d="M7 11V7a5 5 0 0 1 10 0v4" />
</svg>
</span>
<input
id="login-password"
[type]="showPassword() ? 'text' : 'password'"
class="form-input"
[value]="password()"
(input)="password.set($any($event.target).value)"
(blur)="onFieldBlur('password')"
placeholder="رمز عبور خود را وارد کنید"
autocomplete="current-password"
[disabled]="isLoading()"
aria-invalid="!!errors().password"
aria-describedby="password-error"
/>
<button
type="button"
class="password-toggle"
(click)="togglePasswordVisibility()"
[attr.aria-label]="showPassword() ? 'مخفی کردن رمز عبور' : 'نمایش رمز عبور'"
[disabled]="isLoading()"
>
@if (showPassword()) {
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path
d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"
/>
<path
d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"
/>
<path d="M14.12 14.12a3 3 0 1 1-4.24-4.24" />
<line x1="1" y1="1" x2="23" y2="23" />
</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"
>
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
<circle cx="12" cy="12" r="3" />
</svg>
}
</button>
</div>
@if (errors().password) {
<span id="password-error" class="field-error" role="alert">
{{ errors().password }}
</span>
}
</div>
<div class="form-options">
<label class="remember-me">
<input
type="checkbox"
class="remember-checkbox"
[checked]="rememberMe()"
(change)="rememberMe.set($any($event.target).checked)"
[disabled]="isLoading()"
/>
<span class="remember-label">مرا به خاطر بسپار</span>
</label>
</div>
@if (generalError()) {
<div class="general-error" role="alert">
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<circle cx="12" cy="12" r="10" />
<line x1="12" y1="8" x2="12" y2="12" />
<line x1="12" y1="16" x2="12.01" y2="16" />
</svg>
<span>{{ generalError() }}</span>
</div>
}
<button
type="submit"
class="login-submit"
[class.loading]="isLoading()"
[disabled]="isLoading()"
>
<span class="btn-shimmer" aria-hidden="true"></span>
@if (isLoading()) {
<span class="spinner" aria-hidden="true"></span>
<span class="btn-text">در حال ورود...</span>
} @else {
<span class="btn-text">ورود</span>
<span class="btn-arrow" aria-hidden="true">
<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="M5 12h14M12 5l7 7-7 7" />
</svg>
</span>
}
</button>
</form>
</div>
</div>
</div>
+198
View File
@@ -0,0 +1,198 @@
import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Router, NavigationEnd } from '@angular/router';
import { filter, Subscription } from 'rxjs';
import { AuthService, LoginResponse } from '../../services/auth/auth.service';
type LoginField = 'username' | 'password';
type LoginErrors = Partial<Record<LoginField, string>>;
@Component({
selector: 'app-login',
standalone: true,
imports: [CommonModule, FormsModule],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './login.page.html',
styleUrl: './login.page.css',
})
export class LoginPage {
private readonly authService = inject(AuthService);
private readonly router = inject(Router);
readonly username = signal('');
readonly password = signal('');
readonly rememberMe = signal(false);
readonly showPassword = signal(false);
readonly isLoading = signal(false);
readonly errors = signal<LoginErrors>({});
readonly generalError = signal<string | null>(null);
readonly isShaking = signal(false);
readonly isEntering = signal(true);
readonly mousePosition = signal({ x: 0, y: 0 });
private routerSubscription?: Subscription;
constructor() {
this.routerSubscription = this.router.events
.pipe(filter((event) => event instanceof NavigationEnd))
.subscribe(() => {
this.resetForm();
});
}
ngOnInit(): void {
this.restoreCredentials();
setTimeout(() => this.isEntering.set(false), 1100);
}
ngOnDestroy(): void {
this.routerSubscription?.unsubscribe();
}
private restoreCredentials(): void {
const saved = localStorage.getItem('remembered_credentials');
if (saved) {
try {
const parsed = JSON.parse(saved);
if (parsed?.username) {
this.username.set(parsed.username);
this.rememberMe.set(true);
}
} catch {
// ignore corrupt data
}
}
}
private saveCredentials(): void {
if (this.rememberMe()) {
localStorage.setItem('remembered_credentials', JSON.stringify({ username: this.username() }));
} else {
localStorage.removeItem('remembered_credentials');
}
}
onCardMouseMove(event: MouseEvent): void {
const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
const x = ((event.clientX - rect.left) / rect.width) * 100;
const y = ((event.clientY - rect.top) / rect.height) * 100;
this.mousePosition.set({ x, y });
}
onCardMouseLeave(): void {
this.mousePosition.set({ x: 50, y: 50 });
}
onFieldBlur(field: LoginField): void {
this.validateField(field);
}
private validateField(field: LoginField): void {
const currentErrors = { ...this.errors() };
switch (field) {
case 'username':
if (!this.username().trim()) {
currentErrors.username = 'نام کاربری الزامی است';
} else {
delete currentErrors.username;
}
break;
case 'password':
if (!this.password()) {
currentErrors.password = 'رمز عبور الزامی است';
} else {
delete currentErrors.password;
}
break;
}
this.errors.set(currentErrors);
}
validateAllFields(): LoginErrors {
const allErrors: LoginErrors = {};
if (!this.username().trim()) {
allErrors.username = 'نام کاربری الزامی است';
}
if (!this.password()) {
allErrors.password = 'رمز عبور الزامی است';
}
this.errors.set(allErrors);
return allErrors;
}
onSubmit(): void {
const allErrors = this.validateAllFields();
if (Object.keys(allErrors).length > 0) {
this.triggerShake();
return;
}
this.isLoading.set(true);
this.generalError.set(null);
this.errors.set({});
const credentials = {
username: this.username().trim(),
password: this.password(),
};
this.authService.login(credentials).subscribe({
next: (response: LoginResponse) => {
this.isLoading.set(false);
if (!response?.user?.username) {
this.generalError.set('نام کاربری یا رمز عبور اشتباه است');
this.triggerShake();
return;
}
this.saveCredentials();
this.router.navigate(['/']);
},
error: (err) => {
this.isLoading.set(false);
// Errors are mapped by backend code instead of showing the raw server message.
this.generalError.set(
AuthService.messageForError(
err,
'خطا در اتصال به سرور. لطفاً دوباره تلاش کنید.',
),
);
this.triggerShake();
},
});
}
private triggerShake(): void {
this.isShaking.set(true);
setTimeout(() => this.isShaking.set(false), 700);
}
togglePasswordVisibility(): void {
this.showPassword.update((v) => !v);
}
onLogoClick(): void {
this.router.navigate(['/login']);
}
private resetForm(): void {
this.username.set('');
this.password.set('');
this.rememberMe.set(false);
this.showPassword.set(false);
this.isLoading.set(false);
this.errors.set({});
this.generalError.set(null);
this.isShaking.set(false);
this.isEntering.set(false);
this.mousePosition.set({ x: 50, y: 50 });
}
}
+406
View File
@@ -0,0 +1,406 @@
.reports-page {
min-height: 100%;
padding: 2.25rem 3rem 3.5rem;
display: flex;
flex-direction: column;
gap: 1.5rem;
animation: fadeIn 0.4s ease-out;
}
.reports-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
}
.reports-title-group {
display: flex;
align-items: center;
gap: 0.875rem;
}
.reports-title-icon {
display: flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
border-radius: 0.875rem;
background: var(--color-primary) / 12;
color: var(--color-primary);
flex-shrink: 0;
}
.reports-title {
margin: 0;
font-size: 1.5rem;
font-weight: 700;
color: var(--text-primary);
line-height: 1.3;
}
.reports-subtitle {
margin: 0.15rem 0 0;
font-size: 0.8125rem;
color: var(--text-muted);
}
.period-chip {
padding: 0.45rem 0.9rem;
border: 1px solid var(--card-border);
border-radius: 9999px;
background: var(--card-bg);
font-size: 0.75rem;
color: var(--text-secondary);
white-space: nowrap;
}
.reports-tabs {
display: inline-flex;
align-self: flex-start;
gap: 0.25rem;
padding: 0.3rem;
border: 1px solid var(--card-border);
border-radius: 1rem;
background: var(--sidebar-hover);
}
.tab-btn {
position: relative;
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.55rem 1.15rem;
border: none;
border-radius: 0.75rem;
background: transparent;
color: var(--text-muted);
font-size: 0.8125rem;
font-weight: 500;
cursor: pointer;
transition: color 0.2s ease, background 0.2s ease;
white-space: nowrap;
}
.tab-btn:hover {
color: var(--text-primary);
}
.tab-btn.tab-active {
background: var(--card-bg);
color: var(--color-primary);
box-shadow: 0 4px 14px rgba(15, 23, 42, 0.08);
}
.tab-indicator {
position: absolute;
bottom: 0.3rem;
left: 50%;
transform: translateX(-50%);
width: 1.5rem;
height: 0.125rem;
border-radius: 9999px;
background: var(--color-primary);
animation: slideIn 0.3s ease-out;
}
.tab-panel {
display: flex;
flex-direction: column;
gap: 1.25rem;
animation: fadeIn 0.3s ease-out;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 1.25rem;
}
.charts-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 1.25rem;
}
.ai-grid {
display: grid;
grid-template-columns: minmax(0, 5fr) minmax(0, 7fr);
gap: 1.25rem;
}
.report-card {
padding: 1.25rem 1.4rem;
border: 1px solid var(--card-border);
border-radius: 1.25rem;
background: var(--card-bg);
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.06), 0 2px 10px rgba(0, 0, 0, 0.03);
animation: fadeInUp 0.5s ease-out both;
}
.report-card:nth-child(1) { animation-delay: 0.03s; }
.report-card:nth-child(2) { animation-delay: 0.06s; }
.report-card:nth-child(3) { animation-delay: 0.09s; }
.report-card:nth-child(4) { animation-delay: 0.12s; }
.stat-card {
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.stat-label {
font-size: 0.8125rem;
color: var(--text-muted);
}
.stat-value {
font-size: 1.75rem;
font-weight: 700;
color: var(--text-primary);
line-height: 1.2;
}
.stat-hint {
font-size: 0.6875rem;
color: var(--text-muted);
}
.stat-progress {
height: 6px;
border-radius: 9999px;
background: var(--stat-progress-bg, rgba(100, 116, 139, 0.16));
overflow: hidden;
}
.stat-progress-fill {
display: block;
height: 100%;
border-radius: 9999px;
background: var(--color-primary);
transition: width 0.8s cubic-bezier(0.22, 1, 0.36, 1);
}
.card-header {
margin-bottom: 1.1rem;
}
.card-title {
margin: 0;
font-size: 1.0625rem;
font-weight: 600;
color: var(--text-primary);
}
.card-description {
margin: 0.2rem 0 0;
font-size: 0.75rem;
color: var(--text-muted);
line-height: 1.7;
}
.trend-peak {
display: inline-block;
margin-inline-start: 0.35rem;
color: var(--text-secondary);
}
.ai-stats {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.9rem 1.25rem;
}
.ai-stat {
display: flex;
flex-direction: column;
gap: 0.3rem;
}
.ai-stat-label {
font-size: 0.75rem;
color: var(--text-muted);
}
.ai-stat-value {
font-size: 1.125rem;
font-weight: 700;
color: var(--text-primary);
}
.ai-channels {
margin-top: 1.4rem;
padding-top: 1.1rem;
border-top: 1px solid var(--card-border);
}
.ai-channels-title {
margin: 0 0 0.9rem;
font-size: 0.875rem;
font-weight: 600;
color: var(--text-secondary);
}
.error-card {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.5rem;
padding: 3rem 1.5rem;
text-align: center;
color: var(--text-muted);
}
.error-card h2 {
margin: 0.5rem 0 0;
font-size: 1.0625rem;
font-weight: 600;
color: var(--text-primary);
}
.error-card p {
margin: 0;
font-size: 0.8125rem;
}
.retry-btn {
margin-top: 0.75rem;
padding: 0.55rem 1.5rem;
border: none;
border-radius: 0.75rem;
background: var(--color-primary);
color: #ffffff;
font-size: 0.8125rem;
font-weight: 500;
cursor: pointer;
transition: opacity 0.2s ease, transform 0.2s ease;
}
.retry-btn:hover {
opacity: 0.9;
transform: translateY(-1px);
}
.skeleton-card {
min-height: 132px;
}
.skeleton {
border-radius: 0.5rem;
background: linear-gradient(
90deg,
var(--stat-progress-bg, rgba(100, 116, 139, 0.12)) 25%,
rgba(100, 116, 139, 0.05) 37%,
var(--stat-progress-bg, rgba(100, 116, 139, 0.12)) 63%
);
background-size: 400% 100%;
animation: skeletonShimmer 1.4s ease infinite;
}
.skeleton-title {
width: 45%;
height: 0.875rem;
}
.skeleton-value {
width: 30%;
height: 2rem;
margin-top: 0.75rem;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes slideIn {
from {
width: 0;
opacity: 0;
}
to {
width: 1.5rem;
opacity: 1;
}
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(16px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes skeletonShimmer {
from {
background-position: 100% 50%;
}
to {
background-position: 0 50%;
}
}
@media (prefers-reduced-motion: reduce) {
.report-card,
.skeleton {
animation: none;
}
}
@media (max-width: 1024px) {
.reports-page {
padding: 1.5rem 1.75rem 2.75rem;
}
.stats-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.charts-grid,
.ai-grid {
grid-template-columns: minmax(0, 1fr);
}
}
@media (max-width: 640px) {
.reports-page {
padding: 1.25rem 1.25rem 2.25rem;
}
.stats-grid {
grid-template-columns: minmax(0, 1fr);
}
.reports-tabs {
width: 100%;
}
.tab-btn {
flex: 1;
justify-content: center;
padding: 0.55rem 0.5rem;
}
}
:host-context([data-bs-theme='dark']) .report-card {
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3), 0 2px 10px rgba(0, 0, 0, 0.2);
}
:host-context([data-bs-theme='dark']) .stat-progress {
background: rgba(148, 163, 184, 0.2);
}
:host-context([data-bs-theme='dark']) .skeleton {
background: linear-gradient(90deg, rgba(148, 163, 184, 0.14) 25%, rgba(148, 163, 184, 0.05) 37%, rgba(148, 163, 184, 0.14) 63%);
background-size: 400% 100%;
}
+215
View File
@@ -0,0 +1,215 @@
<div class="reports-page">
<header class="reports-header">
<div class="reports-title-group">
<span class="reports-title-icon">
<svg
width="22"
height="22"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M4 4v16h16" />
<path d="M8 20V11" />
<path d="M12.5 20V6" />
<path d="M17 20V9" />
</svg>
</span>
<div>
<h1 class="reports-title">گزارشات</h1>
<p class="reports-subtitle">مروری بر استفاده از دستیار هوشمند و نتایج پاسخ‌های هوش مصنوعی</p>
</div>
</div>
@if (summary(); as summary) {
<span class="period-chip">بازه گزارش: {{ summary.periodLabel }}</span>
}
</header>
@if (loading()) {
<div class="stats-grid">
@for (card of [1, 2, 3, 4]; track card) {
<div class="report-card skeleton-card">
<div class="skeleton skeleton-title"></div>
<div class="skeleton skeleton-value"></div>
</div>
}
</div>
} @else if (loadError()) {
<div class="report-card error-card" role="alert">
<svg
width="40"
height="40"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="9" />
<path d="M12 8v4M12 16h.01" />
</svg>
<h2>دریافت گزارشات ممکن نشد</h2>
<p>ارتباط با سرور برقرار نشد. لطفاً دوباره تلاش کنید.</p>
<button type="button" class="retry-btn" (click)="retry()">تلاش مجدد</button>
</div>
} @else if (data(); as view) {
<nav class="reports-tabs" role="tablist" aria-label="بخش‌های گزارشات">
@for (tab of tabs; track tab.id) {
<button
type="button"
class="tab-btn"
role="tab"
[class.tab-active]="activeTab() === tab.id"
[attr.aria-selected]="activeTab() === tab.id"
(click)="selectTab(tab.id)"
>
<svg
width="15"
height="15"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path [attr.d]="tab.icon" />
</svg>
<span>{{ tab.label }}</span>
@if (activeTab() === tab.id) {
<span class="tab-indicator"></span>
}
</button>
}
</nav>
@if (activeTab() === 'questions') {
<div class="tab-panel" role="tabpanel">
<div class="stats-grid">
<section class="report-card stat-card">
<span class="stat-label">تعداد کل سوالات</span>
<strong class="stat-value">{{ formatCount(view.summary.totalQuestions) }}</strong>
<span class="stat-hint">در {{ view.summary.periodLabel }}</span>
</section>
<section class="report-card stat-card">
<span class="stat-label">کاربران یکتا</span>
<strong class="stat-value">{{ formatCount(view.summary.uniqueUsers) }}</strong>
<span class="stat-hint">کاربرانی که با دستیار گفتگو کرده‌اند</span>
</section>
<section class="report-card stat-card">
<span class="stat-label">پاسخ‌های هوش مصنوعی</span>
<strong class="stat-value">{{ formatCount(view.summary.aiAnswered) }}</strong>
<div class="stat-progress" aria-hidden="true">
<span class="stat-progress-fill" [style.width.%]="aiAnswerRate()"></span>
</div>
<span class="stat-hint">{{ formatPercent(aiAnswerRate()) }} از کل سوالات</span>
</section>
<section class="report-card stat-card">
<span class="stat-label">ارجاع به کارشناس</span>
<strong class="stat-value">{{ formatCount(view.summary.escalatedToAgent) }}</strong>
<span class="stat-hint">سوالات نیازمند بررسی انسانی</span>
</section>
</div>
<div class="charts-grid">
<section class="report-card chart-card">
<div class="card-header">
<h2 class="card-title">پرتکرارترین سوالات</h2>
<p class="card-description">پرپرسش‌ترین موضوعات کاربران، به ترتیب فراوانی</p>
</div>
<app-bar-chart
[items]="topQuestions()"
ariaLabel="نمودار میله‌ای پرتکرارترین سوالات کاربران"
/>
</section>
<section class="report-card chart-card">
<div class="card-header">
<h2 class="card-title">توزیع سوالات</h2>
<p class="card-description">سهم هر دسته از کل سوالات مطرح‌شده</p>
</div>
<app-doughnut-chart
[segments]="categories()"
centerLabel="کل سوالات"
ariaLabel="نمودار دایره‌ای توزیع سوالات بر اساس دسته"
/>
</section>
</div>
</div>
} @else {
<div class="tab-panel" role="tabpanel">
<div class="ai-grid">
<section class="report-card chart-card">
<div class="card-header">
<h2 class="card-title">عملکرد هوش مصنوعی</h2>
<p class="card-description">آمار پاسخ‌دهی و کیفیت عملکرد دستیار</p>
</div>
<div class="ai-stats">
<div class="ai-stat">
<span class="ai-stat-label">میانگین زمان پاسخ</span>
<strong class="ai-stat-value">{{ formatDecimal(view.aiPerformance.avgResponseSeconds) }} ثانیه</strong>
</div>
<div class="ai-stat">
<span class="ai-stat-label">نرخ موفقیت پاسخ‌ها</span>
<strong class="ai-stat-value">{{ formatPercent(view.aiPerformance.successRate) }}</strong>
<div class="stat-progress" aria-hidden="true">
<span class="stat-progress-fill" [style.width.%]="view.aiPerformance.successRate"></span>
</div>
</div>
<div class="ai-stat">
<span class="ai-stat-label">رضایت‌مندی کاربران</span>
<strong class="ai-stat-value">{{ formatPercent(view.aiPerformance.satisfactionRate) }}</strong>
<div class="stat-progress" aria-hidden="true">
<span class="stat-progress-fill" [style.width.%]="view.aiPerformance.satisfactionRate"></span>
</div>
</div>
<div class="ai-stat">
<span class="ai-stat-label">پاسخ بر پایه سوالات متداول</span>
<strong class="ai-stat-value">{{ formatPercent(faqBasedRate()) }}</strong>
<div class="stat-progress" aria-hidden="true">
<span class="stat-progress-fill" [style.width.%]="faqBasedRate()"></span>
</div>
</div>
</div>
<div class="ai-channels">
<h3 class="ai-channels-title">پاسخ‌ها بر اساس گونه گفتگو</h3>
<app-bar-chart
[items]="channels()"
valueSuffix=" پاسخ"
ariaLabel="نمودار میله‌ای پاسخ‌ها بر اساس گونه گفتگو"
/>
</div>
</section>
<section class="report-card chart-card">
<div class="card-header">
<h2 class="card-title">روند استفاده</h2>
<p class="card-description">
تغییرات حجم سوالات در {{ view.summary.periodLabel }} — مجموع
{{ formatCount(trendTotal()) }} سوال
@if (trendPeak(); as peak) {
<span class="trend-peak">بیشترین رشد در {{ peak.label }} با {{ formatCount(peak.value) }} سوال</span>
}
</p>
</div>
<app-line-chart
[points]="trend()"
seriesLabel="تعداد سوالات"
gradientId="reportsUsageTrend"
ariaLabel="نمودار خطی روند حجم سوالات در گذر زمان"
/>
</section>
</div>
</div>
}
}
</div>
@@ -0,0 +1,65 @@
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { ReportsPage } from './reports.page';
describe('ReportsPage', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ReportsPage],
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
],
}).compileComponents();
});
function titles(fixture: { nativeElement: HTMLElement }): (string | undefined)[] {
return Array.from(fixture.nativeElement.querySelectorAll('.card-title')).map((node) =>
node.textContent?.trim(),
);
}
it('should create the page', () => {
const fixture = TestBed.createComponent(ReportsPage);
expect(fixture.componentInstance).toBeTruthy();
});
it('renders the questions tab by default with its charts', () => {
const fixture = TestBed.createComponent(ReportsPage);
fixture.detectChanges();
const element: HTMLElement = fixture.nativeElement;
const tabLabels = Array.from(element.querySelectorAll('.tab-btn')).map((node) =>
node.textContent?.trim(),
);
expect(element.querySelector('.reports-title')?.textContent?.trim()).toBe('گزارشات');
expect(tabLabels).toEqual(['پرسش‌های کاربران', 'عملکرد و روند']);
expect(titles(fixture)).toEqual(['پرتکرارترین سوالات', 'توزیع سوالات']);
expect(element.querySelectorAll('.stat-card').length).toBe(4);
expect(element.querySelector('app-bar-chart')).toBeTruthy();
expect(element.querySelector('app-doughnut-chart')).toBeTruthy();
expect(element.textContent).toContain('۴,۸۰۲');
});
it('switches to the performance tab with AI and usage reports', () => {
const fixture = TestBed.createComponent(ReportsPage);
fixture.detectChanges();
const element = fixture.nativeElement as HTMLElement;
const tabButtons = element.querySelectorAll('.tab-btn');
(tabButtons[1] as HTMLButtonElement).click();
fixture.detectChanges();
expect(fixture.componentInstance.activeTab()).toBe('performance');
expect(titles(fixture)).toEqual(['عملکرد هوش مصنوعی', 'روند استفاده']);
expect(fixture.nativeElement.querySelector('app-line-chart')).toBeTruthy();
});
});
+146
View File
@@ -0,0 +1,146 @@
import { ChangeDetectionStrategy, Component, computed, inject, signal, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { forkJoin } from 'rxjs';
import { ReportsService } from '../../services/reports/reports.service';
import { ReportsView } from '../../services/reports/reports.types';
import { BarChartComponent, BarChartItem } from '../../shared/ui/charts/bar-chart.component';
import { DoughnutChartComponent, DoughnutSegment } from '../../shared/ui/charts/doughnut-chart.component';
import { LineChartComponent, LinePoint } from '../../shared/ui/charts/line-chart.component';
import { CHART_PALETTE } from '../../shared/utils/chart-palette';
import { formatCount, formatDecimal, formatPercent } from '../../shared/utils/format.util';
type ReportTabId = 'questions' | 'performance';
@Component({
selector: 'app-reports',
standalone: true,
imports: [CommonModule, BarChartComponent, DoughnutChartComponent, LineChartComponent],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './reports.page.html',
styleUrl: './reports.page.css',
})
export class ReportsPage implements OnInit {
private readonly reports = inject(ReportsService);
readonly tabs: { id: ReportTabId; label: string; icon: string }[] = [
{
id: 'questions',
label: 'پرسش‌های کاربران',
icon: 'M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z',
},
{
id: 'performance',
label: 'عملکرد و روند',
icon: 'M22 12h-4l-3 9L9 3l-3 9H2',
},
];
readonly activeTab = signal<ReportTabId>('questions');
readonly loading = signal(true);
readonly loadError = signal(false);
readonly data = signal<ReportsView | null>(null);
readonly summary = computed(() => this.data()?.summary ?? null);
readonly ai = computed(() => this.data()?.aiPerformance ?? null);
readonly topQuestions = computed<BarChartItem[]>(() => {
const questions = this.data()?.topQuestions ?? [];
return questions.map((question, index) => ({
label: question.text,
value: question.count,
color: CHART_PALETTE[index % CHART_PALETTE.length],
hint: `دسته: ${question.category}`,
}));
});
readonly categories = computed<DoughnutSegment[]>(() => {
const shares = this.data()?.categories ?? [];
return shares.map((share, index) => ({
label: share.category,
value: share.count,
color: CHART_PALETTE[index % CHART_PALETTE.length],
}));
});
readonly trend = computed<LinePoint[]>(() => {
const points = this.data()?.trend ?? [];
return points.map((point) => ({ label: point.label, value: point.count }));
});
readonly channels = computed<BarChartItem[]>(() => {
const channels = this.data()?.aiPerformance.channels ?? [];
return channels.map((channel, index) => ({
label: channel.label,
value: channel.count,
color: CHART_PALETTE[index % CHART_PALETTE.length],
}));
});
readonly aiAnswerRate = computed(() => {
const summary = this.summary();
if (!summary || summary.totalQuestions === 0) return 0;
return (summary.aiAnswered / summary.totalQuestions) * 100;
});
readonly faqBasedRate = computed(() => {
const ai = this.ai();
if (!ai || ai.totalResponses === 0) return 0;
return (ai.faqBasedResponses / ai.totalResponses) * 100;
});
readonly trendTotal = computed(() => this.trend().reduce((sum, point) => sum + point.value, 0));
readonly trendPeak = computed(() => {
const points = this.trend();
if (points.length === 0) return null;
return points.reduce((peak, point) => (point.value > peak.value ? point : peak), points[0]);
});
ngOnInit(): void {
this.load();
}
selectTab(id: ReportTabId): void {
this.activeTab.set(id);
}
load(): void {
this.loading.set(true);
this.loadError.set(false);
forkJoin({
topQuestions: this.reports.getTopQuestions(),
summary: this.reports.getQuestionSummary(),
categories: this.reports.getCategoryDistribution(),
trend: this.reports.getUsageTrend(),
aiPerformance: this.reports.getAiPerformance(),
}).subscribe({
next: (data) => {
this.data.set(data);
this.loading.set(false);
},
error: () => {
this.data.set(null);
this.loading.set(false);
this.loadError.set(true);
},
});
}
retry(): void {
this.load();
}
formatCount(value: number): string {
return formatCount(value);
}
formatDecimal(value: number): string {
return formatDecimal(value);
}
formatPercent(value: number): string {
return formatPercent(value);
}
}
+476 -102
View File
@@ -1,5 +1,8 @@
.settings-page {
min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
}
.settings-header {
@@ -12,10 +15,19 @@
.settings-tabs {
position: relative;
display: flex;
}
.tab-divider {
position: relative;
z-index: 10;
flex-shrink: 0;
margin: 0.75rem 0;
}
.tab-btn {
position: relative;
cursor: pointer;
}
.tab-btn.tab-active {
@@ -76,12 +88,6 @@
animation: slideInRight 0.3s ease-out;
}
.file-item:nth-child(1) { animation-delay: 0.05s; }
.file-item:nth-child(2) { animation-delay: 0.1s; }
.file-item:nth-child(3) { animation-delay: 0.15s; }
.file-item:nth-child(4) { animation-delay: 0.2s; }
.file-item:nth-child(5) { animation-delay: 0.25s; }
.file-icon-wrapper {
transition: all 0.2s ease;
}
@@ -96,14 +102,11 @@
}
.setting-item {
animation: fadeInUp 0.4s ease-out;
opacity: 0;
transform: translateY(20px);
animation: fadeInUp 0.4s ease-out forwards;
}
.setting-item:nth-child(1) { animation-delay: 0.05s; }
.setting-item:nth-child(2) { animation-delay: 0.1s; }
.setting-item:nth-child(3) { animation-delay: 0.15s; }
.setting-item:nth-child(4) { animation-delay: 0.2s; }
.form-select {
appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%2364748b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
@@ -183,9 +186,11 @@
border-color: var(--color-primary);
}
/* `.toggle-active` mirrors the checked state set by the host; keep it solid too
so it never wins over the neutral base with a transparent primary wash. */
.toggle-switch.toggle-active {
background-color: var(--color-primary)/15;
border-color: var(--color-primary)/25;
background-color: var(--color-primary);
border-color: var(--color-primary);
}
.toggle-switch:focus-within {
@@ -193,111 +198,59 @@
box-shadow: 0 0 0 3px var(--color-primary)/30;
}
.toggle-switch:hover {
background-color: var(--color-primary)/10;
/* Unchecked (off) hover: solid neutral, never transparent. */
.toggle-switch:hover:not(:has(input:checked)) {
background-color: color-mix(in srgb, var(--toggle-bg) 60%, #000);
}
.toggle-switch:hover:has(input:checked) {
background-color: var(--color-primary);
/* Checked hover: solid, slightly darker primary. */
.toggle-switch:has(input:checked):hover {
background-color: color-mix(in srgb, var(--color-primary) 78%, #000);
}
.toggle-switch:hover.toggle-active {
background-color: var(--color-primary)/20;
.file-remove-btn:hover{
cursor: pointer;
}
@keyframes fadeInDown {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
from { opacity: 0; transform: translateY(-10px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes slideInRight {
from {
opacity: 0;
transform: translateX(20px);
}
to {
opacity: 1;
transform: translateX(0);
}
from { opacity: 0; transform: translateX(20px); }
to { opacity: 1; transform: translateX(0); }
}
@keyframes slideIn {
from {
width: 0;
opacity: 0;
}
to {
width: 1.5rem;
opacity: 1;
}
from { width: 0; opacity: 0; }
to { width: 1.5rem; opacity: 1; }
}
@keyframes bounce {
0%, 20%, 50%, 80%, 100% {
transform: translateY(0);
}
40% {
transform: translateY(-5px);
}
60% {
transform: translateY(-3px);
}
0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
40% { transform: translateY(-5px); }
60% { transform: translateY(-3px); }
}
@keyframes pulse {
0%, 100% {
transform: scale(1);
}
50% {
transform: scale(1.1);
}
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
0%, 100% { transform: scale(1); }
50% { transform: scale(1.1); }
}
@media (max-width: 640px) {
@@ -313,11 +266,20 @@
flex-direction: column;
}
.tab-divider {
display: none;
}
.tab-btn {
justify-content: flex-start;
padding: 1rem;
}
.tab-btn span {
white-space: normal;
text-align: right;
}
.tab-btn .tab-indicator {
display: none;
}
@@ -346,31 +308,443 @@
}
}
[data-bs-theme="dark"] .dropzone-icon-wrapper svg,
[data-bs-theme="dark"] .file-icon-wrapper svg,
[data-bs-theme="dark"] .section-header svg {
:host-context([data-bs-theme="dark"]) .dropzone-icon-wrapper svg,
:host-context([data-bs-theme="dark"]) .file-icon-wrapper svg,
:host-context([data-bs-theme="dark"]) .section-header svg {
stroke: var(--color-primary);
}
[data-bs-theme="dark"] .form-select {
:host-context([data-bs-theme="dark"]) .form-select {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23cbd5e1' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
}
[data-bs-theme="dark"] .file-remove-btn:hover {
:host-context([data-bs-theme="dark"]) .file-remove-btn:hover {
background-color: rgba(239, 68, 68, 0.15);
}
[data-bs-theme="dark"] .toggle-switch input:checked + .toggle-slider {
:host-context([data-bs-theme="dark"]) .toggle-switch input:checked + .toggle-slider {
box-shadow: 0 1px 3px var(--color-primary)/40, 0 0 0 2px var(--color-primary)/30;
}
[data-bs-theme="dark"] .settings-card,
[data-bs-theme="dark"] .file-item,
[data-bs-theme="dark"] .setting-item {
:host-context([data-bs-theme="dark"]) .settings-card,
:host-context([data-bs-theme="dark"]) .file-item,
:host-context([data-bs-theme="dark"]) .setting-item {
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3), 0 2px 10px rgba(0, 0, 0, 0.2);
background-color: #111111;
}
[data-bs-theme="dark"] .file-item:hover,
[data-bs-theme="dark"] .setting-item:hover {
:host-context([data-bs-theme="dark"]) .settings-content {
background-color: #171717;
}
:host-context([data-bs-theme="dark"]) .file-item:hover,
:host-context([data-bs-theme="dark"]) .setting-item:hover {
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4), 0 2px 8px rgba(0, 0, 0, 0.3);
}
:host-context([data-bs-theme="dark"]) .btn--outline:hover:not(:disabled) {
background: color-mix(in srgb, var(--color-primary) 30%, #171717);
}
:host-context([data-bs-theme="dark"]) .toggle-switch:hover:not(:has(input:checked)) {
background-color: color-mix(in srgb, var(--toggle-bg) 50%, #000);
}
:host-context([data-bs-theme="dark"]) .toggle-switch:has(input:checked):hover {
background-color: color-mix(in srgb, var(--color-primary) 75%, #000);
}
/* ===== Dropzone disabled overlay ===== */
.dropzone-disabled {
opacity: 0.6;
pointer-events: none;
}
/* ===== Upload actions + queue ===== */
.upload-actions {
animation: fadeInUp 0.4s ease-out;
}
.upload-queue {
animation: fadeInUp 0.4s ease-out;
}
.upload-task {
animation: slideInRight 0.3s ease-out;
}
.upload-progress-bar {
background: var(--surface-border);
}
.upload-progress-bar > div {
background: var(--color-primary);
}
/* ===== Buttons ===== */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.4rem;
border-radius: 0.5rem;
padding: 0.5rem 0.9rem;
font-size: 0.85rem;
font-weight: 500;
border: 1px solid transparent;
cursor: pointer;
transition: background-color 0.2s, border-color 0.2s, color 0.2s;
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn--primary {
background: var(--color-primary);
color: #ffffff;
}
.btn--primary:hover:not(:disabled) {
background: color-mix(in srgb, var(--color-primary) 80%, #000);
}
.btn--primary:active:not(:disabled) {
background: color-mix(in srgb, var(--color-primary) 70%, #000);
}
.btn--outline {
background: transparent;
border-color: var(--color-input-border);
color: var(--text-secondary);
}
.btn--outline:hover:not(:disabled) {
background: color-mix(in srgb, var(--color-primary) 22%, #ffffff);
border-color: var(--color-primary);
color: var(--color-primary);
}
/* ===== Documents table ===== */
.documents-section {
animation: fadeInUp 0.5s ease-out;
}
.documents-filters {
animation: fadeInUp 0.4s ease-out;
}
.documents-table-wrapper {
border: 1px solid var(--color-card-border);
/* Clip the table to the rounded corners on wide layouts. */
overflow: hidden;
}
/*
* md and below (Tailwind md = 48rem/768px).
*
* Six fixed-percentage columns stop being readable well before 768px: the date wraps,
* and the status column's error text overflows its column and bleeds into the
* neighbouring cells — which is what makes the row contents look mixed.
*
* Switching to `table-layout: auto` lets each column size to its own content, so no
* cell can overflow into the next one. The table then grows past the card and the
* wrapper scrolls horizontally instead of squeezing the columns.
*/
@media (max-width: 767.98px) {
.documents-table-wrapper {
overflow-x: auto;
/* Keep the scroll chain inside the card instead of leaking to the page. */
overscroll-behavior-x: contain;
-webkit-overflow-scrolling: touch;
}
.documents-table {
/* Auto layout ignores the <col> percentages, so columns follow their content. */
table-layout: auto;
min-width: 720px;
}
/* Short cells stay on one line so each column keeps a clean width. */
.documents-table th,
.documents-table td {
white-space: nowrap;
}
/* Title and status hold long text; let them wrap instead of widening the table. */
.documents-table td:nth-child(1),
.documents-table td:nth-child(2) {
white-space: normal;
}
.documents-table td:nth-child(1) {
max-width: 220px;
}
}
.documents-table {
border-collapse: separate;
border-spacing: 0;
}
.documents-table th,
.documents-table td {
padding: 0.6rem 0.75rem;
/* Every column — labels and row content alike — is centred in the RTL table. */
text-align: center;
vertical-align: top;
border-bottom: 1px solid var(--color-card-border);
/* Fixed layout fits the card; wrap long tokens so a cell never widens the table. */
overflow-wrap: anywhere;
}
.documents-table thead th {
background: var(--sidebar-hover);
}
.table-row-animate {
animation: fadeInUp 0.3s ease-out;
}
.documents-table tbody tr:last-child td {
border-bottom: none;
}
/*
* Row actions: the buttons must not be squeezed by the fixed column.
* Flex items shrink by default, which used to wrap «تلاش‌مجدد» / «بازبینی سند»
* mid-word (the cell's `overflow-wrap: anywhere` leaked into the button), so
* each button keeps its intrinsic width and the cell wraps to a new line only
* when there is genuinely no room.
*/
.documents-actions {
align-items: flex-start;
justify-content: center;
flex-wrap: wrap;
}
.documents-actions > .btn {
flex: 0 0 auto;
white-space: nowrap;
overflow-wrap: normal;
word-break: normal;
}
/* Status badges */
.status-queued {
background: var(--color-warning)/15;
color: var(--color-warning);
}
.status-processing {
background: var(--color-info)/15;
color: var(--color-info);
}
.status-ready {
background: var(--color-success)/15;
color: var(--color-success);
}
.status-failed {
background: var(--color-danger)/15;
color: var(--color-danger);
}
/* Plain text colours for the document active flag (no badge background). */
.doc-active {
color: var(--color-success);
}
.doc-inactive {
color: var(--text-muted);
}
.status-dot,
.dot-queued,
.dot-processing,
.dot-ready,
.dot-failed {
width: 0.4rem;
height: 0.4rem;
border-radius: 9999px;
flex-shrink: 0;
}
.dot-queued { background: var(--color-warning); }
.dot-processing { background: var(--color-info); animation: pulse-dot 1.5s ease-in-out infinite; }
.dot-ready { background: var(--color-success); }
.dot-failed { background: var(--color-danger); }
@keyframes pulse-dot {
0%, 100% { opacity: 1; }
50% { opacity: 0.4; }
}
/* Active toggle button */
.active-toggle {
display: inline-flex;
align-items: center;
gap: 0.35rem;
border-radius: 9999px;
padding: 0.25rem 0.7rem;
font-size: 0.78rem;
font-weight: 600;
border: 1px solid var(--color-input-border);
cursor: pointer;
transition: background-color 0.2s, border-color 0.2s, color 0.2s;
}
.active-toggle--on {
background: var(--color-success)/15;
border-color: var(--color-success);
color: var(--color-success);
}
.active-toggle:not(.active-toggle--on) {
background: var(--color-input-border)/40;
color: var(--text-muted);
}
.active-toggle:hover {
opacity: 0.85;
}
.active-toggle:disabled {
cursor: default;
opacity: 0.6;
}
/* Documents empty / error / pagination */
.documents-loading,
.documents-empty,
.documents-error {
animation: fadeIn 0.3s ease-out;
}
/* ===== Review modal ===== */
.review-backdrop {
position: fixed;
inset: 0;
background: var(--overlay);
display: flex;
align-items: center;
justify-content: center;
z-index: 100;
padding: 1rem;
}
.review-modal {
background: var(--card-bg);
border: 1px solid var(--color-card-border);
border-radius: 1rem;
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
width: 100%;
max-width: 56rem;
max-height: 85dvh;
overflow: hidden;
display: flex;
flex-direction: column;
}
.review-modal-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1rem 1.25rem;
border-bottom: 1px solid var(--color-card-border);
}
/* Narrower variant for confirmations (e.g. remove document). */
.review-modal--sm {
max-width: 30rem;
}
.review-modal-body {
padding: 1.25rem;
overflow-y: auto;
flex: 1 1 auto;
min-height: 0;
}
.review-modal-footer {
border-top: 1px solid var(--color-card-border);
}
.review-loading {
animation: fadeIn 0.3s ease-out;
}
.review-items {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
gap: 1rem;
}
.review-item {
animation: fadeInUp 0.3s ease-out;
}
.review-item-header {
animation: fadeInDown 0.3s ease-out;
}
.review-item-body {
animation: fadeIn 0.3s ease-out;
}
.review-preview {
background: var(--sidebar-hover);
border: 1px dashed var(--color-card-border);
}
.review-preview img {
max-width: 100%;
height: auto;
display: block;
}
.review-item-actions {
animation: fadeInDown 0.3s ease-out;
}
/* ===== App settings: AI model cards grid ===== */
.ai-models-grid {
animation: fadeInUp 0.5s ease-out;
}
.ai-models-grid > app-ai-model-config-card {
animation: fadeInUp 0.4s ease-out;
}
/* Shared form utilities (also used by the review modal — page-scoped) */
.form-label {
font-size: 0.8rem;
font-weight: 500;
color: var(--text-secondary);
}
.form-input {
background: var(--color-input-bg);
color: var(--text-secondary);
border: 1px solid var(--color-input-border);
border-radius: 0.5rem;
padding: 0.5rem 0.75rem;
font-size: 0.875rem;
outline: none;
transition: border-color 0.2s, box-shadow 0.2s;
width: 100%;
box-sizing: border-box;
}
.form-input:focus {
border-color: var(--color-primary);
box-shadow: 0 0 0 3px var(--color-primary)/20;
}
.form-input:disabled {
background: var(--surface-bg);
cursor: default;
opacity: 0.7;
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
.dot-processing { animation: none; }
}
@media (max-width: 640px) {
.documents-table {
font-size: 0.75rem;
}
.documents-table th,
.documents-table td {
padding: 0.4rem 0.3rem;
}
.review-modal {
max-width: 100%;
max-height: 90dvh;
border-radius: 0.75rem;
}
.review-item-body {
grid-template-columns: 1fr;
}
.ai-models-grid {
grid-template-columns: 1fr;
}
}
@media (max-width: 480px) {
.documents-filters {
flex-wrap: wrap;
gap: 0.5rem;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,294 @@
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { of, Subject, type Observable } from 'rxjs';
import { vi } from 'vitest';
import { SettingsPage } from './settings.page';
import { DocumentsService } from '../../services/documents/documents.service';
import {
DocumentListItem,
DocumentListResponse,
} from '../../services/documents/documents.types';
import { AuthService } from '../../services/auth/auth.service';
import { HttpService } from '../../services/http-request/http.service';
import { ThemeService } from '../../services/theme/theme.service';
import { ToastrService } from 'ngx-toastr';
function readyDoc(): DocumentListItem {
return {
id: 'doc-1',
title: 'سند آزمون',
filename: 'guide.pdf',
status: 'ready',
is_active: true,
searchable: true,
chunk_count: 12,
created_at: '2024-01-01T10:00:00Z',
job: { id: 'job-1', status: 'ready', stage: null, attempt_count: 0, retry_generation: 0, can_retry: false, error: null },
review_required: false,
};
}
const toastr = { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() };
const filterSelect = (el: HTMLElement): HTMLSelectElement | null => el.querySelector('.documents-filters select');
describe('SettingsPage — document filters', () => {
let getDocuments: ReturnType<typeof vi.fn>;
beforeEach(async () => {
toastr.success.mockClear();
toastr.error.mockClear();
toastr.warning.mockClear();
toastr.info.mockClear();
// Server-side filtering: `all` returns one ready doc; every other status matches none.
getDocuments = vi.fn((params: { status?: string } = {}): Observable<DocumentListResponse> => {
const items = params.status ? [] : [readyDoc()];
return of({ items, next_cursor: null, knowledge_revision: 0 });
});
await TestBed.configureTestingModule({
imports: [SettingsPage],
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
{
provide: DocumentsService,
useValue: {
getConfiguration: () => of({}),
getDocuments,
getKnowledgeSelection: () => of({ revision: 0, document_ids: ['doc-1'] }),
},
},
{ provide: AuthService, useValue: { getCurrentUserValue: () => ({ role: 'admin' }) } },
{ provide: HttpService, useValue: { apiUrl: '/api/v1' } },
{ provide: ThemeService, useValue: { isDarkMode: () => false, toggleDarkMode: () => {} } },
{ provide: ToastrService, useValue: toastr },
],
}).compileComponents();
});
it('renders the filter select and one document row initially', () => {
const fixture = TestBed.createComponent(SettingsPage);
fixture.detectChanges(); // ngOnInit → load all documents
expect(filterSelect(fixture.nativeElement as HTMLElement)).not.toBeNull();
expect((fixture.nativeElement as HTMLElement).querySelectorAll('.documents-table tbody tr').length).toBe(1);
});
it('keeps the filter select and table shell when a filter matches no rows', () => {
const fixture = TestBed.createComponent(SettingsPage);
fixture.detectChanges();
const el = fixture.nativeElement as HTMLElement;
// Select a status that has zero documents.
const component = fixture.componentInstance;
component.activeFilter.set('failed');
component.applyDocumentFilters();
fixture.detectChanges();
// Regression: the whole panel used to vanish; the select + table must stay so the user
// can change the filter back, and an in-table "no match" message is shown instead.
expect(filterSelect(el)).not.toBeNull();
expect(el.querySelector('.documents-table tbody tr')).not.toBeNull();
expect(el.textContent).toContain('هیچ سندی با فیلتر انتخاب‌شده مطابقت ندارد.');
expect(el.textContent).not.toContain('هنوز سندی آپلود نشده است.');
// The "N سند ثبت شده" footer must not claim 0 documents.
expect(el.textContent).not.toContain('سند ثبت شده');
});
it('restores the rows when the filter is reset back to all', () => {
const fixture = TestBed.createComponent(SettingsPage);
fixture.detectChanges();
const component = fixture.componentInstance;
component.activeFilter.set('processing'); // empty
component.applyDocumentFilters();
fixture.detectChanges();
expect((fixture.nativeElement as HTMLElement).querySelectorAll('.documents-table tbody tr').length).toBe(1); // just the empty row
component.activeFilter.set('all'); // back to everything
component.applyDocumentFilters();
fixture.detectChanges();
const rows = (fixture.nativeElement as HTMLElement).querySelectorAll('.documents-table tbody tr');
expect(rows.length).toBe(1);
// نام فایل column was dropped (redundant with عنوان سند); the row shows the title.
expect(rows[0].textContent).toContain('سند آزمون');
expect(rows[0].textContent).not.toContain('guide.pdf');
});
it('drops the redundant نام فایل column and renders exactly 6 columns', () => {
const fixture = TestBed.createComponent(SettingsPage);
fixture.detectChanges();
const el = fixture.nativeElement as HTMLElement;
const headers = Array.from(el.querySelectorAll('.documents-table thead th')).map((t) =>
t.textContent?.trim(),
);
expect(headers).toEqual([
'عنوان سند',
'وضعیت پردازش',
'تعداد بخش‌ها',
'تاریخ آپلود',
'فعال‌سازی',
'عملیات',
]);
expect(headers).not.toContain('نام فایل');
// A data row has exactly 6 cells matching the 6 columns.
expect(el.querySelector('.documents-table tbody tr')?.children.length).toBe(6);
});
it('keeps row action buttons unwrapped inside the narrow عملیات column', () => {
// Regression: the actions column used to be only 15% wide and inherited the
// table's `overflow-wrap: anywhere`, so «تلاش‌مجدد» / «بازبینی سند» broke in
// the middle of the word and the button looked broken.
const fixture = TestBed.createComponent(SettingsPage);
fixture.detectChanges();
const el = fixture.nativeElement as HTMLElement;
const actionsCell = el.querySelector('.documents-table tbody tr td:last-child') as HTMLElement;
expect(actionsCell).not.toBeNull();
const wrapper = actionsCell.querySelector('.documents-actions') as HTMLElement;
expect(wrapper).not.toBeNull();
// Whatever renders inside must stay on a single line per button.
const actionButtons = Array.from(wrapper.querySelectorAll('button'));
expect(actionButtons.length).toBeGreaterThan(0);
for (const button of actionButtons) {
const style = getComputedStyle(button);
if (button.classList.contains('btn')) {
expect(style.whiteSpace).toBe('nowrap');
expect(style.overflowWrap).toBe('normal');
}
}
});
it('centres the documents table headers and row cells', () => {
// Regression: headers and cells both inherited the `text-align: right` of the
// RTL table, leaving the whole table visually skewed to one side.
const fixture = TestBed.createComponent(SettingsPage);
fixture.detectChanges();
const el = fixture.nativeElement as HTMLElement;
const headers = Array.from(el.querySelectorAll('.documents-table thead th'));
expect(headers.length).toBe(6);
for (const header of headers) {
expect(getComputedStyle(header).textAlign).toBe('center');
}
const cells = Array.from(el.querySelectorAll('.documents-table tbody td'));
expect(cells.length).toBe(6);
for (const cell of cells) {
expect(getComputedStyle(cell).textAlign).toBe('center');
}
});
it('confirms before removing: the bin button opens a modal, cancel keeps the doc, confirm shows the MVP notice', () => {
const fixture = TestBed.createComponent(SettingsPage);
fixture.detectChanges();
const el = fixture.nativeElement as HTMLElement;
const openRemoveModal = () => {
const row = el.querySelector('.documents-table tbody tr') as HTMLElement;
const remove = Array.from(row.querySelectorAll('button')).find((b) =>
(b.getAttribute('aria-label') ?? '').includes('حذف سند'),
) as HTMLButtonElement;
remove.click();
fixture.detectChanges();
};
openRemoveModal();
const modal = el.querySelector('[role="alertdialog"]') as HTMLElement;
expect(modal).toBeTruthy();
expect(modal.textContent).toContain('سند آزمون');
expect(modal.textContent).toContain('مطمئن هستید');
expect(toastr.info).not.toHaveBeenCalled(); // nothing happens until confirmed
// Cancel closes the modal and keeps the document, with no notice.
(modal.querySelector('.btn--outline') as HTMLButtonElement).click();
fixture.detectChanges();
expect(el.querySelector('[role="alertdialog"]')).toBeNull();
expect(el.querySelectorAll('.documents-table tbody tr').length).toBe(1);
expect(toastr.info).not.toHaveBeenCalled();
// Confirm closes the modal and surfaces the MVP notice (deletion is not yet implemented);
// the row is left in place and no backend delete call is made.
openRemoveModal();
(el.querySelector('[role="alertdialog"] .btn--primary') as HTMLButtonElement).click();
fixture.detectChanges();
expect(toastr.info).toHaveBeenCalledTimes(1);
expect(el.querySelector('[role="alertdialog"]')).toBeNull();
expect(el.querySelectorAll('.documents-table tbody tr').length).toBe(1);
});
it('renders OCR and FAQ admin-approval toggles in the app settings and toggles FAQ', () => {
const fixture = TestBed.createComponent(SettingsPage);
fixture.detectChanges();
const component = fixture.componentInstance;
component.selectTab('app');
fixture.detectChanges();
const el = fixture.nativeElement as HTMLElement;
const labels = Array.from(el.querySelectorAll('.setting-info label')).map((l) =>
l.textContent?.trim(),
);
expect(labels).toContain('نیاز به تأیید ادمین برای اسناد OCR شده');
expect(labels).toContain('نیاز به تأیید ادمین برای اسناد FAQ');
// Toggles in order: dark mode, OCR, FAQ. The FAQ toggle flips its own signal.
const switches = el.querySelectorAll('.setting-control .toggle-switch');
expect(switches.length).toBe(3);
expect(component.faqAdminApproval()).toBe(false);
(switches[2].querySelector('input') as HTMLInputElement).click();
fixture.detectChanges();
expect(component.faqAdminApproval()).toBe(true);
});
it('hasActiveFilters reflects the active status/active-only filters', () => {
const component = TestBed.createComponent(SettingsPage).componentInstance;
expect(component.hasActiveFilters()).toBe(false);
component.activeFilter.set('failed');
expect(component.hasActiveFilters()).toBe(true);
component.activeFilter.set('all');
component.activeOnly.set(true);
expect(component.hasActiveFilters()).toBe(true);
});
it('shows a loading spinner on the به‌روزرسانی button while documents are being fetched', () => {
// The initial load resolves immediately; the refresh load stays pending so we can observe
// the in-flight state (previously the button only disabled with no visible feedback).
let call = 0;
let pending!: Subject<DocumentListResponse>;
getDocuments.mockReset();
getDocuments.mockImplementation((): Observable<DocumentListResponse> => {
call += 1;
if (call === 1) return of({ items: [readyDoc()], next_cursor: null, knowledge_revision: 0 });
pending = new Subject<DocumentListResponse>();
return pending;
});
const fixture = TestBed.createComponent(SettingsPage);
fixture.detectChanges(); // initial load
const el = fixture.nativeElement as HTMLElement;
const refresh = el.querySelector('.documents-filters button') as HTMLButtonElement;
expect(refresh.textContent).toContain('به‌روزرسانی');
expect(refresh.querySelector('.animate-spin')).toBeNull();
refresh.click(); // start refresh → stays pending
fixture.detectChanges();
expect(refresh.disabled).toBe(true);
expect(refresh.getAttribute('aria-busy')).toBe('true');
expect(refresh.textContent).toContain('در حال به‌روزرسانی');
expect(refresh.querySelector('.animate-spin')).not.toBeNull();
pending.next({ items: [readyDoc()], next_cursor: null, knowledge_revision: 0 });
fixture.detectChanges();
expect(refresh.disabled).toBe(false);
expect(refresh.textContent).toContain('به‌روزرسانی');
expect(refresh.querySelector('.animate-spin')).toBeNull();
});
});
File diff suppressed because it is too large Load Diff
+398
View File
@@ -0,0 +1,398 @@
.wallboard-page {
min-height: 100%;
padding: 2.25rem 3rem 3.5rem;
display: flex;
flex-direction: column;
gap: 1.5rem;
animation: fadeIn 0.4s ease-out;
}
.wallboard-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
}
.wallboard-title-group {
display: flex;
align-items: center;
gap: 0.875rem;
}
.wallboard-title-icon {
display: flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
border-radius: 0.875rem;
background: var(--color-primary);
color: #ffffff;
flex-shrink: 0;
}
.wallboard-title {
margin: 0;
font-size: 1.5rem;
font-weight: 700;
color: var(--text-primary);
line-height: 1.3;
}
.wallboard-subtitle {
margin: 0.15rem 0 0;
font-size: 0.8125rem;
color: var(--text-muted);
}
.wallboard-header-actions {
display: flex;
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
}
.period-chip {
padding: 0.45rem 0.9rem;
border: 1px solid var(--card-border);
border-radius: 9999px;
background: var(--card-bg);
font-size: 0.75rem;
color: var(--text-secondary);
white-space: nowrap;
}
.last-updated {
font-size: 0.75rem;
color: var(--text-muted);
white-space: nowrap;
}
.refresh-btn {
display: inline-flex;
align-items: center;
gap: 0.45rem;
padding: 0.45rem 0.9rem;
border: 1px solid var(--card-border);
border-radius: 9999px;
background: var(--card-bg);
color: var(--text-secondary);
font-size: 0.75rem;
font-weight: 500;
cursor: pointer;
transition: color 0.2s ease, border-color 0.2s ease, transform 0.2s ease;
}
.refresh-btn:hover:not(:disabled) {
color: var(--color-primary);
border-color: var(--color-primary);
transform: translateY(-1px);
}
.refresh-btn:disabled {
opacity: 0.6;
cursor: default;
}
.refresh-icon--spinning {
animation: spin 1s linear infinite;
}
/* ---- KPI tiles ---- */
.kpi-grid {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 1.25rem;
}
.kpi-card {
position: relative;
display: flex;
flex-direction: column;
gap: 0.4rem;
padding: 1.1rem 1.25rem 1.15rem;
border: 1px solid var(--card-border);
border-radius: 1.25rem;
background: var(--card-bg);
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.06), 0 2px 10px rgba(0, 0, 0, 0.03);
overflow: hidden;
animation: fadeInUp 0.5s ease-out both;
}
.kpi-card::before {
content: '';
position: absolute;
inset-block-start: 0;
inset-inline: 0;
height: 3px;
background: var(--kpi-color, var(--color-primary));
}
.kpi-card:nth-child(1) { animation-delay: 0.03s; }
.kpi-card:nth-child(2) { animation-delay: 0.06s; }
.kpi-card:nth-child(3) { animation-delay: 0.09s; }
.kpi-card:nth-child(4) { animation-delay: 0.12s; }
.kpi-card:nth-child(5) { animation-delay: 0.15s; }
.kpi-card-top {
display: flex;
align-items: center;
gap: 0.6rem;
}
.kpi-icon {
display: flex;
align-items: center;
justify-content: center;
width: 34px;
height: 34px;
border-radius: 0.7rem;
background: var(--kpi-color, var(--color-primary));
color: #ffffff;
flex-shrink: 0;
}
.kpi-label {
margin: 0;
font-size: 0.8125rem;
font-weight: 500;
color: var(--text-secondary);
line-height: 1.5;
}
.kpi-value {
font-size: 1.75rem;
font-weight: 700;
color: var(--text-primary);
line-height: 1.2;
}
.kpi-progress {
height: 6px;
border-radius: 9999px;
background: var(--stat-progress-bg, rgba(100, 116, 139, 0.16));
overflow: hidden;
}
.kpi-progress-fill {
display: block;
height: 100%;
border-radius: 9999px;
background: var(--kpi-color, var(--color-primary));
transition: width 0.8s cubic-bezier(0.22, 1, 0.36, 1);
}
.kpi-hint {
font-size: 0.6875rem;
color: var(--text-muted);
line-height: 1.6;
}
/* ---- charts ---- */
.charts-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 1.25rem;
}
.report-card {
padding: 1.25rem 1.4rem;
border: 1px solid var(--card-border);
border-radius: 1.25rem;
background: var(--card-bg);
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.06), 0 2px 10px rgba(0, 0, 0, 0.03);
animation: fadeInUp 0.5s ease-out both;
}
.card-header {
margin-bottom: 1.1rem;
}
.card-title {
margin: 0;
font-size: 1.0625rem;
font-weight: 600;
color: var(--text-primary);
}
.card-description {
margin: 0.2rem 0 0;
font-size: 0.75rem;
color: var(--text-muted);
line-height: 1.7;
}
.chart-peak {
display: inline-block;
margin-inline-start: 0.35rem;
color: var(--text-secondary);
}
/* ---- states ---- */
.error-card {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.5rem;
padding: 3rem 1.5rem;
text-align: center;
color: var(--text-muted);
}
.error-card h2 {
margin: 0.5rem 0 0;
font-size: 1.0625rem;
font-weight: 600;
color: var(--text-primary);
}
.error-card p {
margin: 0;
font-size: 0.8125rem;
}
.retry-btn {
margin-top: 0.75rem;
padding: 0.55rem 1.5rem;
border: none;
border-radius: 0.75rem;
background: var(--color-primary);
color: #ffffff;
font-size: 0.8125rem;
font-weight: 500;
cursor: pointer;
transition: opacity 0.2s ease, transform 0.2s ease;
}
.retry-btn:hover {
opacity: 0.9;
transform: translateY(-1px);
}
.skeleton-card {
min-height: 148px;
}
.skeleton {
border-radius: 0.5rem;
background: linear-gradient(
90deg,
var(--stat-progress-bg, rgba(100, 116, 139, 0.12)) 25%,
rgba(100, 116, 139, 0.05) 37%,
var(--stat-progress-bg, rgba(100, 116, 139, 0.12)) 63%
);
background-size: 400% 100%;
animation: skeletonShimmer 1.4s ease infinite;
}
.skeleton-title {
width: 45%;
height: 0.875rem;
}
.skeleton-value {
width: 35%;
height: 2rem;
margin-top: 0.75rem;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(16px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes skeletonShimmer {
from {
background-position: 100% 50%;
}
to {
background-position: 0 50%;
}
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: reduce) {
.kpi-card,
.report-card,
.skeleton,
.refresh-icon--spinning {
animation: none;
}
}
@media (max-width: 1400px) {
.wallboard-page {
padding: 1.75rem 2rem 3rem;
}
.kpi-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
@media (max-width: 1024px) {
.wallboard-page {
padding: 1.5rem 1.75rem 2.75rem;
}
.kpi-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.charts-grid {
grid-template-columns: minmax(0, 1fr);
}
}
@media (max-width: 640px) {
.wallboard-page {
padding: 1.25rem 1.25rem 2.25rem;
}
.kpi-grid {
grid-template-columns: minmax(0, 1fr);
}
.wallboard-header-actions {
width: 100%;
}
}
:host-context([data-bs-theme='dark']) .report-card,
:host-context([data-bs-theme='dark']) .kpi-card {
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3), 0 2px 10px rgba(0, 0, 0, 0.2);
}
:host-context([data-bs-theme='dark']) .kpi-progress {
background: rgba(148, 163, 184, 0.2);
}
:host-context([data-bs-theme='dark']) .skeleton {
background: linear-gradient(90deg, rgba(148, 163, 184, 0.14) 25%, rgba(148, 163, 184, 0.05) 37%, rgba(148, 163, 184, 0.14) 63%);
background-size: 400% 100%;
}
+160
View File
@@ -0,0 +1,160 @@
<div class="wallboard-page">
<header class="wallboard-header">
<div class="wallboard-title-group">
<span class="wallboard-title-icon">
<svg
width="22"
height="22"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M2 4h20v12H2zM8 20h8M12 16v4" />
</svg>
</span>
<div>
<h1 class="wallboard-title">والبورد</h1>
<p class="wallboard-subtitle">نمای یک‌نگاه فعالیت مرکز تماس مبتنی بر هوش مصنوعی</p>
</div>
</div>
<div class="wallboard-header-actions">
@if (periodLabel()) {
<span class="period-chip">بازه گزارش: {{ periodLabel() }}</span>
}
<span class="last-updated">آخرین به‌روزرسانی: {{ lastUpdated() }}</span>
<button type="button" class="refresh-btn" (click)="refresh()" [disabled]="loading()">
<svg
class="refresh-icon"
[class.refresh-icon--spinning]="loading()"
width="15"
height="15"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M20 11a8.1 8.1 0 0 0-15.5-2M4 4v5h5" />
<path d="M4 13a8.1 8.1 0 0 0 15.5 2M20 20v-5h-5" />
</svg>
<span>به‌روزرسانی</span>
</button>
</div>
</header>
@if (loading()) {
<div class="kpi-grid">
@for (card of [1, 2, 3, 4, 5]; track card) {
<div class="kpi-card skeleton-card">
<div class="skeleton skeleton-title"></div>
<div class="skeleton skeleton-value"></div>
</div>
}
</div>
} @else if (loadError()) {
<div class="report-card error-card" role="alert">
<svg
width="40"
height="40"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="9" />
<path d="M12 8v4M12 16h.01" />
</svg>
<h2>دریافت اطلاعات والبرد ممکن نشد</h2>
<p>ارتباط با سرور برقرار نشد. لطفاً دوباره تلاش کنید.</p>
<button type="button" class="retry-btn" (click)="retry()">تلاش مجدد</button>
</div>
} @else if (data(); as view) {
<section class="kpi-grid" aria-label="شاخص‌های کلیدی والبرد">
@for (kpi of kpis(); track kpi.id) {
<article class="kpi-card" [style.--kpi-color]="kpi.color">
<div class="kpi-card-top">
<span class="kpi-icon" aria-hidden="true">
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path [attr.d]="kpi.icon" />
</svg>
</span>
<h2 class="kpi-label">{{ kpi.label }}</h2>
</div>
<strong class="kpi-value">{{ kpi.value }}</strong>
@if (kpi.progress !== null) {
<div class="kpi-progress" aria-hidden="true">
<span class="kpi-progress-fill" [style.width.%]="kpi.progress"></span>
</div>
}
<span class="kpi-hint">{{ kpi.hint }}</span>
</article>
}
</section>
<div class="charts-grid">
<section class="report-card chart-card">
<div class="card-header">
<h2 class="card-title">هوش مصنوعی در مقابل کارشناس</h2>
<p class="card-description">
سهم هر روش پاسخ‌گویی از کل {{ formatCount(view.kpis.totalCalls) }} تماس در
{{ view.kpis.periodLabel }}
</p>
</div>
<app-doughnut-chart
[segments]="outcomes()"
centerLabel="کل تماس‌ها"
ariaLabel="نمودار دایره‌ای سهم روش‌های پاسخ‌گویی به تماس‌ها"
/>
</section>
<section class="report-card chart-card">
<div class="card-header">
<h2 class="card-title">توزیع تماس‌ها در ساعات روز</h2>
<p class="card-description">
حجم تماس‌ها در بازه‌های دو ساعته
@if (busiestHour(); as peak) {
<span class="chart-peak">پرفشارترین بازه: {{ peak.label }}</span>
}
</p>
</div>
<app-bar-chart
[items]="hourly()"
valueSuffix=" تماس"
ariaLabel="نمودار میله‌ای توزیع تماس‌ها در ساعات روز"
/>
</section>
</div>
<section class="report-card chart-card chart-card--wide">
<div class="card-header">
<h2 class="card-title">روند فعالیت تماس‌ها</h2>
<p class="card-description">
تغییرات حجم کل تماس‌ها در ۱۴ روز گذشته — روی نمودار بر روی هر نقطه بایست تا جزئیات آن روز
را ببینید.
</p>
</div>
<app-line-chart
[points]="activity()"
seriesLabel="تعداد تماس‌ها"
gradientId="wallboardCallActivity"
ariaLabel="نمودار خطی روند فعالیت تماس‌ها در گذر زمان"
/>
</section>
}
</div>
@@ -0,0 +1,74 @@
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { WallboardPage } from './wallboard.page';
describe('WallboardPage', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [WallboardPage],
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
],
}).compileComponents();
});
function titles(fixture: { nativeElement: HTMLElement }): (string | undefined)[] {
return Array.from(fixture.nativeElement.querySelectorAll('.card-title')).map((node) =>
node.textContent?.trim(),
);
}
it('should create the page', () => {
const fixture = TestBed.createComponent(WallboardPage);
expect(fixture.componentInstance).toBeTruthy();
});
it('renders the five wallboard KPIs with Persian values', () => {
const fixture = TestBed.createComponent(WallboardPage);
fixture.detectChanges();
const element: HTMLElement = fixture.nativeElement;
expect(element.querySelector('.wallboard-title')?.textContent?.trim()).toBe('والبورد');
const labels = Array.from(element.querySelectorAll('.kpi-label')).map((node) =>
node.textContent?.trim(),
);
expect(labels).toEqual([
'تعداد کل تماس‌ها',
'تعداد تماس با هوش مصنوعی',
'میانگین زمان صحبت با هوش مصنوعی',
'تعداد تماس موفق با هوش مصنوعی',
'تعداد تماس با کارشناس بعد از هوش مصنوعی',
]);
const values = Array.from(element.querySelectorAll('.kpi-value')).map((node) =>
node.textContent?.trim(),
);
expect(values).toEqual(['۱۲,۸۴۶', '۸,۴۱۲', '۲:۲۲', '۷,۱۵۶', '۱,۲۵۶']);
expect(element.querySelectorAll('.kpi-card').length).toBe(5);
expect(element.textContent).toContain('۶۵٪ از کل تماس‌ها');
});
it('renders the wallboard charts', () => {
const fixture = TestBed.createComponent(WallboardPage);
fixture.detectChanges();
const element: HTMLElement = fixture.nativeElement;
expect(titles(fixture)).toEqual([
'هوش مصنوعی در مقابل کارشناس',
'توزیع تماس‌ها در ساعات روز',
'روند فعالیت تماس‌ها',
]);
expect(element.querySelector('app-doughnut-chart')).toBeTruthy();
expect(element.querySelector('app-bar-chart')).toBeTruthy();
expect(element.querySelector('app-line-chart')).toBeTruthy();
});
});
+193
View File
@@ -0,0 +1,193 @@
import { ChangeDetectionStrategy, Component, computed, inject, signal, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { forkJoin } from 'rxjs';
import { WallboardService } from '../../services/wallboard/wallboard.service';
import { WallboardView } from '../../services/wallboard/wallboard.types';
import { BarChartComponent, BarChartItem } from '../../shared/ui/charts/bar-chart.component';
import { DoughnutChartComponent, DoughnutSegment } from '../../shared/ui/charts/doughnut-chart.component';
import { LineChartComponent, LinePoint } from '../../shared/ui/charts/line-chart.component';
import { CHART_COLORS, CHART_PALETTE } from '../../shared/utils/chart-palette';
import { formatCount, formatPercent, toPersianDigits } from '../../shared/utils/format.util';
/** One KPI tile on the wallboard; rendering stays fully data-driven. */
export interface WallboardKpiCard {
id: string;
label: string;
value: string;
hint: string;
icon: string;
color: string;
/** Share of the related total (0–100) rendered as a progress bar; null hides it. */
progress: number | null;
}
@Component({
selector: 'app-wallboard',
standalone: true,
imports: [CommonModule, BarChartComponent, DoughnutChartComponent, LineChartComponent],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './wallboard.page.html',
styleUrl: './wallboard.page.css',
})
export class WallboardPage implements OnInit {
private readonly wallboard = inject(WallboardService);
readonly loading = signal(true);
readonly loadError = signal(false);
readonly data = signal<WallboardView | null>(null);
readonly lastUpdated = signal<string>('—');
readonly kpis = computed<WallboardKpiCard[]>(() => {
const view = this.data();
if (!view) {
return [];
}
return this.buildKpiCards(view);
});
readonly periodLabel = computed(() => this.data()?.kpis.periodLabel ?? '');
readonly outcomes = computed<DoughnutSegment[]>(() => {
const outcomes = this.data()?.outcomes ?? [];
return outcomes.map((outcome, index) => ({
label: outcome.label,
value: outcome.value,
color: CHART_PALETTE[index % CHART_PALETTE.length],
}));
});
readonly activity = computed<LinePoint[]>(() => {
const points = this.data()?.activity ?? [];
return points.map((point) => ({ label: point.label, value: point.count }));
});
readonly hourly = computed<BarChartItem[]>(() => {
const buckets = this.data()?.hourly ?? [];
return buckets.map((bucket) => ({
label: bucket.label,
value: bucket.count,
color: CHART_COLORS.primary,
}));
});
readonly busiestHour = computed(() => {
const buckets = this.data()?.hourly ?? [];
if (buckets.length === 0) {
return null;
}
return buckets.reduce((peak, bucket) => (bucket.count > peak.count ? bucket : peak), buckets[0]);
});
ngOnInit(): void {
this.load();
}
load(): void {
this.loading.set(true);
this.loadError.set(false);
forkJoin({
kpis: this.wallboard.getKpis(),
outcomes: this.wallboard.getOutcomes(),
activity: this.wallboard.getActivity(),
hourly: this.wallboard.getHourlyDistribution(),
}).subscribe({
next: (data) => {
this.data.set(data);
this.loading.set(false);
this.lastUpdated.set(this.formatClock(new Date()));
},
error: () => {
this.data.set(null);
this.loading.set(false);
this.loadError.set(true);
},
});
}
retry(): void {
this.load();
}
refresh(): void {
this.load();
}
/** KPI tiles in display order, each with its own icon, accent colour and share bar. */
private buildKpiCards(view: WallboardView): WallboardKpiCard[] {
const { kpis } = view;
const aiShare = kpis.totalCalls > 0 ? (kpis.aiCalls / kpis.totalCalls) * 100 : 0;
const successRate = kpis.aiCalls > 0 ? (kpis.successfulAiCalls / kpis.aiCalls) * 100 : 0;
const transferRate = kpis.aiCalls > 0 ? (kpis.transferredToAgentCalls / kpis.aiCalls) * 100 : 0;
return [
{
id: 'total-calls',
label: 'تعداد کل تماس‌ها',
value: formatCount(kpis.totalCalls),
hint: `کل تماس‌های دریافتی در ${kpis.periodLabel}`,
icon: 'M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z',
color: CHART_COLORS.primary,
progress: null,
},
{
id: 'ai-calls',
label: 'تعداد تماس با هوش مصنوعی',
value: formatCount(kpis.aiCalls),
hint: `${formatPercent(aiShare)} از کل تماس‌ها`,
icon: 'M12 3l1.9 5.8a2 2 0 0 0 1.3 1.3L21 12l-5.8 1.9a2 2 0 0 0-1.3 1.3L12 21l-1.9-5.8a2 2 0 0 0-1.3-1.3L3 12l5.8-1.9a2 2 0 0 0 1.3-1.3z',
color: CHART_COLORS.ai,
progress: aiShare,
},
{
id: 'avg-ai-talk',
label: 'میانگین زمان صحبت با هوش مصنوعی',
value: this.formatDuration(kpis.avgAiTalkSeconds),
hint: `دقیقه و ثانیه — میانگین روی ${formatCount(kpis.aiCalls)} تماس`,
icon: 'M3.34 19a10 10 0 1 1 17.32 0M12 14l4-4',
color: CHART_COLORS.info,
progress: null,
},
{
id: 'successful-ai-calls',
label: 'تعداد تماس موفق با هوش مصنوعی',
value: formatCount(kpis.successfulAiCalls),
hint: `${formatPercent(successRate)} از تماس‌های هوش مصنوعی`,
icon: 'M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18M8.5 12.5l2.5 2.5 4.5-5',
color: CHART_COLORS.success,
progress: successRate,
},
{
id: 'transferred-to-agent',
label: 'تعداد تماس با کارشناس بعد از هوش مصنوعی',
value: formatCount(kpis.transferredToAgentCalls),
hint: `${formatPercent(transferRate)} از تماس‌های هوش مصنوعی`,
icon: 'M8 3 4 7l4 4M4 7h16M16 21l4-4-4-4M20 17H4',
color: CHART_COLORS.warning,
progress: transferRate,
},
];
}
/** 142 -> «۲:۲۲» (دقیقه:ثانیه) */
formatDuration(totalSeconds: number): string {
const minutes = Math.floor(totalSeconds / 60);
const seconds = Math.round(totalSeconds % 60);
return toPersianDigits(`${minutes}:${String(seconds).padStart(2, '0')}`);
}
formatCount(value: number): string {
return formatCount(value);
}
formatPercent(value: number): string {
return formatPercent(value);
}
private formatClock(date: Date): string {
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return toPersianDigits(`${hours}:${minutes}`);
}
}
+14 -1
View File
@@ -1,4 +1,9 @@
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { AuthService } from './auth.service';
@@ -6,7 +11,15 @@ describe('AuthService', () => {
let service: AuthService;
beforeEach(() => {
TestBed.configureTestingModule({});
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
],
});
service = TestBed.inject(AuthService);
});
+142 -38
View File
@@ -1,65 +1,169 @@
import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject, forkJoin, of } from 'rxjs';
import { tap, map, switchMap, catchError } from 'rxjs/operators';
import { Observable, BehaviorSubject, firstValueFrom, throwError } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
import { HttpErrorResponse } from '@angular/common/http';
import { HttpService } from '../http-request/http.service';
import { uuid } from '../../shared/utils/uuid';
interface ApiResult<T> {
hasError: boolean;
messages: string[];
result: T;
}
interface LoginResponse {
auth: boolean;
token: string;
export interface AuthUser {
id: string;
username: string;
role: string;
organization_id: string;
}
interface LoginResult extends ApiResult<LoginResponse> {
licenseValid?: boolean;
export interface LoginResponse {
user: AuthUser;
csrf_token: string;
expires_at: string;
}
export type CurrentUserResponse = LoginResponse;
/** All MVP routes live under `/api/v1` and are reached through the same-origin proxy. */
const API = 'api/v1';
@Injectable({
providedIn: 'root',
})
export class AuthService {
public currentUserSubject = new BehaviorSubject<string | null>(
localStorage.getItem('username'),
);
constructor(
private httpService: HttpService,
) {
let previousUser: string | null = this.currentUserSubject.value;
this.currentUserSubject.subscribe((username) => {
if (username !== previousUser) {
previousUser = username;
public currentUserSubject = new BehaviorSubject<AuthUser | null>(null);
/** CSRF token is kept in memory only (never persisted): it is re-read from `/me` after every reload. */
private csrfToken: string | null = null;
/** True once `/me` confirmed the identity for this page load (the cookie is the source of truth). */
private identityVerified = false;
constructor(private httpService: HttpService) {
// Restore the last known user for instant rendering; `ensureIdentity()` re-validates
// it against `/me` at bootstrap (the HttpOnly `rag_session` cookie is the real session).
const savedUser = localStorage.getItem('current_user');
if (savedUser) {
try {
this.currentUserSubject.next(JSON.parse(savedUser));
} catch {
// ignore corrupt data
}
});
}
}
login(credentials: {
username: string;
password: string;
rememberMe: boolean;
}): Observable<LoginResult> {
return this.httpService.post<LoginResponse>('users/login', credentials).pipe(
tap((response: ApiResult<LoginResponse>) => {
if (!response.hasError && response.result?.auth) {
localStorage.setItem('access_token', response.result.token);
localStorage.setItem('username', response.result.username);
this.currentUserSubject.next(response.result.username);
}
}): Observable<LoginResponse> {
return this.httpService.postRaw<LoginResponse>(`${API}/auth/login`, credentials, {
headers: this.correlationHeaders(),
}).pipe(
tap((response) => {
this.applyIdentity(response);
}),
catchError((err) => {
this.clearAuth();
return throwError(() => err);
}),
);
}
logout(): void {
localStorage.removeItem('access_token');
localStorage.removeItem('username');
this.currentUserSubject.next(null);
logout(): Observable<void> {
const headers: Record<string, string> = this.correlationHeaders();
if (this.csrfToken) {
headers['X-CSRF-Token'] = this.csrfToken;
}
// A02 has no body and returns 204 without a JSON payload.
return this.httpService.postRaw<void>(`${API}/auth/logout`, null, { headers }).pipe(
tap(() => {
this.clearAuth();
}),
catchError((err) => {
// Even when A02 fails, the local session is dropped so the UI shows the signed-out state.
this.clearAuth();
return throwError(() => err);
}),
);
}
getCurrentUser(): Observable<CurrentUserResponse> {
return this.httpService.getRaw<CurrentUserResponse>(`${API}/me`, {
headers: this.correlationHeaders(),
}).pipe(
tap((response) => {
this.applyIdentity(response);
}),
);
}
/** Per-request correlation id shared with the server's `X-Request-ID`. */
private correlationHeaders(): Record<string, string> {
return { 'X-Request-ID': uuid() };
}
/**
* Reads `/me` once per page load. After a reload this is the first call the app makes,
* so a restored user is only trusted when the server still accepts the session cookie.
* `401 AUTH_REQUIRED` clears the authenticated state; anything else keeps the cached user.
*/
async ensureIdentity(): Promise<boolean> {
if (this.identityVerified) return this.isAuthenticated();
try {
const response = await firstValueFrom(this.getCurrentUser());
this.identityVerified = true;
return !!response?.user;
} catch (err) {
const res = err as HttpErrorResponse | undefined;
const code = (res?.error as { error?: { code?: string } } | null)?.error?.code;
if (res?.status === 401 || code === 'AUTH_REQUIRED') {
// The cookie session is gone (expired/revoked): drop the authenticated state.
this.clearAuth();
}
return this.isAuthenticated();
}
}
isAuthenticated(): boolean {
return !!localStorage.getItem('access_token');
return !!this.currentUserSubject.value;
}
getCurrentUserValue(): AuthUser | null {
return this.currentUserSubject.value;
}
getCsrfToken(): string | null {
return this.csrfToken;
}
private applyIdentity(response: LoginResponse): void {
this.currentUserSubject.next(response.user);
this.csrfToken = response.csrf_token;
this.identityVerified = true;
localStorage.setItem('current_user', JSON.stringify(response.user));
}
private clearAuth(): void {
this.currentUserSubject.next(null);
this.csrfToken = null;
this.identityVerified = false;
localStorage.removeItem('current_user');
}
/** Persian message for a backend error envelope code (catalog §7 / handoff §10). */
static messageForError(err: unknown, fallback = 'خطا در ارتباط با سرور. لطفاً دوباره تلاش کنید.'): string {
const res = err as HttpErrorResponse | undefined;
const code = (res?.error as { error?: { code?: string; message?: string } } | null)?.error?.code;
switch (code) {
case 'INVALID_CREDENTIALS':
return 'نام کاربری یا رمز عبور نامعتبر است.';
case 'AUTH_REQUIRED':
return 'نشست شما منقضی شده است. دوباره وارد شوید.';
case 'CSRF_INVALID':
return 'نشست شما نامعتبر است. دوباره وارد شوید.';
case 'FORBIDDEN':
return 'دسترسی به این بخش مجاز نیست.';
case 'RATE_LIMITED':
return 'تلاش‌های بیش از حد مجاز. لطفاً بعداً تلاش کنید.';
case 'DEPENDENCY_UNAVAILABLE':
return 'سرویس موقتاً در دسترس نیست. لطفاً دوباره تلاش کنید.';
default:
if (!code && res && res.status === 0) return 'ارتباط با سرور برقرار نشد.';
return fallback;
}
}
}
@@ -0,0 +1,166 @@
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient, HttpEventType } from '@angular/common/http';
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
import { provideRouter } from '@angular/router';
import { provideAnimations } from '@angular/platform-browser/animations';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { DocumentsService } from './documents.service';
import { AuthService } from '../auth/auth.service';
describe('DocumentsService (backend handoff contract)', () => {
let service: DocumentsService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideHttpClientTesting(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
{ provide: AuthService, useValue: { getCsrfToken: () => 'csrf-abc' } },
],
});
service = TestBed.inject(DocumentsService);
httpMock = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
it('uses same-origin /api/v1 paths for every MVP endpoint', () => {
service.getConfiguration().subscribe();
const req = httpMock.expectOne('/api/v1/configuration');
expect(req.request.method).toBe('GET');
req.flush({});
service.getDocuments({ status: 'ready', is_active: true }).subscribe();
const list = httpMock.expectOne('/api/v1/documents?status=ready&is_active=true');
list.flush({ items: [], next_cursor: null, knowledge_revision: 1 });
service.getKnowledgeSelection().subscribe();
const selection = httpMock.expectOne('/api/v1/knowledge-selection');
selection.flush({ active_document_ids: [], revision: 1 });
});
it('sends the caller idempotency key for uploads and reuses FormData without manual Content-Type', () => {
const file = new File([new Uint8Array([1, 2, 3])], 'faq.pdf', { type: 'application/pdf' });
const progress: number[] = [];
service.uploadDocument(file, 'عنوان', (percent) => progress.push(percent), undefined, 'key-upload-1').subscribe();
const req = httpMock.expectOne('/api/v1/documents');
expect(req.request.method).toBe('POST');
expect(req.request.headers.get('Idempotency-Key')).toBe('key-upload-1');
expect(req.request.headers.get('X-CSRF-Token')).toBe('csrf-abc');
// The browser must own the multipart boundary.
expect(req.request.headers.get('Content-Type')).toBeNull();
expect((req.request.body as FormData).get('title')).toBe('عنوان');
req.event({ type: HttpEventType.UploadProgress, loaded: 3, total: 3 });
req.flush(
{ document_id: 'doc-1', job_id: 'job-1' },
{ status: 202, statusText: 'Accepted' },
);
expect(progress).toEqual([100]);
});
it('sends the same decision key on replay and forbids an empty note payload shape', () => {
service
.submitReviewDecision('doc-1', {
evidence_sha256: 'sha-1',
decision: 'approve',
checked: ['check-a'],
note: 'تأیید شد',
excluded_group_ids: [],
}, 'key-decision-1')
.subscribe();
const req = httpMock.expectOne('/api/v1/documents/doc-1/extraction-review/decisions');
expect(req.request.method).toBe('POST');
expect(req.request.headers.get('Idempotency-Key')).toBe('key-decision-1');
expect(req.request.body).toEqual({
evidence_sha256: 'sha-1',
decision: 'approve',
checked: ['check-a'],
note: 'تأیید شد',
excluded_group_ids: [],
});
req.flush({ decision_id: 'dec-1', review_state: 'pending' });
// Replaying the SAME key must hit the same URL with the same payload — the server
// deduplicates it (Idempotency-Replayed: true) instead of creating a second decision.
service
.submitReviewDecision(
'doc-1',
{
evidence_sha256: 'sha-1',
decision: 'approve',
checked: ['check-a'],
note: 'تأیید شد',
excluded_group_ids: [],
},
'key-decision-1',
)
.subscribe();
const replay = httpMock.expectOne('/api/v1/documents/doc-1/extraction-review/decisions');
expect(replay.request.headers.get('Idempotency-Key')).toBe('key-decision-1');
replay.flush({ decision_id: 'dec-1', review_state: 'pending' }, {
status: 200,
statusText: 'OK',
headers: { 'Idempotency-Replayed': 'true' },
} as never);
});
it('retries the same job through D04 with an explicit idempotency key', () => {
service.retryDocument('doc-1', 'key-retry-1').subscribe();
const req = httpMock.expectOne('/api/v1/documents/doc-1/retry');
expect(req.request.method).toBe('POST');
expect(req.request.headers.get('Idempotency-Key')).toBe('key-retry-1');
req.flush({ job_id: 'job-1', status: 'queued' }, { status: 202, statusText: 'Accepted' });
});
it('replaces the whole selection with a revision guard and no idempotency key (K02)', () => {
service.updateKnowledgeSelection({ expected_revision: 3, document_ids: ['doc-1', 'doc-2'] }).subscribe();
const req = httpMock.expectOne('/api/v1/knowledge-selection');
expect(req.request.method).toBe('PATCH');
expect(req.request.body).toEqual({ expected_revision: 3, document_ids: ['doc-1', 'doc-2'] });
// K02 is revision-controlled: no Idempotency-Key header.
expect(req.request.headers.get('Idempotency-Key')).toBeNull();
expect(req.request.headers.get('X-CSRF-Token')).toBe('csrf-abc');
req.flush({ revision: 4, active_document_ids: ['doc-1', 'doc-2'], conversations_invalidated: true });
});
it('surfaces the error envelope code and request id for correlation', () => {
let captured: { code: string; message: string; requestId?: string } = { code: '', message: '' };
service.updateKnowledgeSelection({ expected_revision: 9, document_ids: [] }).subscribe({
error: (err) => {
captured = DocumentsService.getErrorInfo(err);
},
});
httpMock.expectOne('/api/v1/knowledge-selection').flush(
{ error: { code: 'REVISION_CONFLICT', message: 'Request could not be completed.', request_id: 'corr-1', retryable: false } },
{ status: 409, statusText: 'Conflict', headers: { 'X-Request-ID': 'corr-1' } },
);
expect(captured.code).toBe('REVISION_CONFLICT');
expect(captured.requestId).toBe('corr-1');
expect(DocumentsService.statusForError(captured.code, captured.message)).toContain('همزمان');
});
it('maps contract error codes to Persian guidance', () => {
expect(DocumentsService.statusForError('DOCUMENT_NOT_READY', '')).toContain('آماده');
expect(DocumentsService.statusForError('EXTRACTION_REVIEW_PENDING', '')).toContain('بازبینی');
expect(DocumentsService.statusForError('REVIEW_STALE', '')).toContain('شواهد');
expect(DocumentsService.statusForError('CONTEXT_REVOKED', '')).toContain('باطل');
expect(DocumentsService.statusForError('RATE_LIMITED', '')).toContain('حد مجاز');
expect(DocumentsService.isPolling('processing')).toBe(true);
expect(DocumentsService.isPolling('ready')).toBe(false);
});
});
@@ -0,0 +1,245 @@
import { Injectable, inject } from '@angular/core';
import { HttpErrorResponse, HttpEventType, HttpHeaders, HttpParams } from '@angular/common/http';
import { map, filter, Observable, tap } from 'rxjs';
import { HttpService } from '../http-request/http.service';
import { AuthService } from '../auth/auth.service';
import { uuid } from '../../shared/utils/uuid';
import {
DocumentDetail,
DocumentListParams,
DocumentListResponse,
DocumentStatus,
DocumentUploadResult,
ErrorEnvelope,
ExtractionItem,
ExtractionReviewResponse,
KnowledgeSelection,
KnowledgeSelectionPatch,
KnowledgeSelectionResponse,
RetryResult,
ReviewDecisionRequest,
ReviewDecisionResponse,
SystemConfiguration,
} from './documents.types';
/** Base path for the documented MVP endpoints (`/api/v1/...`), served same-origin. */
const API = 'api/v1';
@Injectable({ providedIn: 'root' })
export class DocumentsService {
private readonly http = inject(HttpService);
private readonly auth = inject(AuthService);
/**
* Headers required for every state-changing MVP call: a fresh CSRF token
* (from the login/`/me` flow) and a per-request correlation id.
*/
private csrfHeaders(): Record<string, string> {
const headers: Record<string, string> = { 'X-Request-ID': uuid() };
const token = this.auth.getCsrfToken();
if (token) {
headers['X-CSRF-Token'] = token;
}
return headers;
}
/**
* Idempotent operations (D01 upload, D07 decisions, D04 retry) take the caller's key:
* an ambiguous failure (timeout / dropped connection) must replay the SAME key with the
* SAME payload — minting a new key would create a second document/decision/retry.
* `Idempotency-Replayed: true` on a successful replay confirms the server deduplicated it.
*/
private idempotencyHeaders(key: string): Record<string, string> {
return { ...this.csrfHeaders(), 'Idempotency-Key': key };
}
private onlyDefined(params: DocumentListParams): Record<string, string> {
const out: Record<string, string> = {};
if (params.limit != null) out['limit'] = String(params.limit);
if (params.cursor) out['cursor'] = params.cursor;
if (params.status) out['status'] = params.status;
if (params.is_active != null) out['is_active'] = String(params.is_active);
return out;
}
/** F01 — read-only capabilities used to configure upload validation. */
getConfiguration(): Observable<SystemConfiguration> {
return this.http.getRaw<SystemConfiguration>(`${API}/configuration`, { skipToast: true });
}
/** D02 — paginated document list. */
getDocuments(params: DocumentListParams = {}): Observable<DocumentListResponse> {
const query = new HttpParams({ fromObject: this.onlyDefined(params) });
return this.http.getRaw<DocumentListResponse>(`${API}/documents`, {
params: query,
skipToast: true,
});
}
/** D03 — single document detail (used for 2-second status polling). */
getDocument(id: string): Observable<DocumentDetail> {
return this.http.getRaw<DocumentDetail>(`${API}/documents/${encodeURIComponent(id)}`, {
skipToast: true,
});
}
/**
* D01 — upload a single document with live progress.
* @param idempotencyKey caller-owned key; replay the SAME key for an uncertain outcome.
*/
uploadDocument(
file: File,
title: string | undefined,
onProgress: (percent: number) => void,
signal?: AbortSignal,
idempotencyKey: string = uuid(),
): Observable<DocumentUploadResult> {
const form = new FormData();
form.append('file', file);
if (title) {
form.append('title', title);
}
return this.http
.uploadWithProgress<DocumentUploadResult>(`${API}/documents`, form, {
headers: this.idempotencyHeaders(idempotencyKey),
skipToast: true,
signal,
})
.pipe(
tap((event) => {
if (event.type === HttpEventType.UploadProgress && event.total) {
onProgress(Math.round((100 * event.loaded) / event.total));
}
}),
filter((event) => event.type === HttpEventType.Response),
map(
(event) =>
(event as import('@angular/common/http').HttpResponse<DocumentUploadResult>)
.body as DocumentUploadResult,
),
);
}
/** D07 — submit an extraction-review decision (approve/reject). */
submitReviewDecision(
documentId: string,
request: ReviewDecisionRequest,
idempotencyKey: string = uuid(),
): Observable<ReviewDecisionResponse> {
return this.http.postRaw<ReviewDecisionResponse>(
`${API}/documents/${encodeURIComponent(documentId)}/extraction-review/decisions`,
request,
{ headers: this.idempotencyHeaders(idempotencyKey), skipToast: true },
);
}
/** D06 — extraction-review evidence items. */
getExtractionReview(documentId: string, cursor?: string): Observable<ExtractionReviewResponse> {
const params: Record<string, string> = {};
if (cursor) {
params['cursor'] = cursor;
}
return this.http.getRaw<ExtractionReviewResponse>(
`${API}/documents/${encodeURIComponent(documentId)}/extraction-review`,
{ params, skipToast: true },
);
}
/** D04 — retry processing of a document. */
retryDocument(
documentId: string,
idempotencyKey: string = uuid(),
): Observable<RetryResult> {
return this.http.postRaw<RetryResult>(
`${API}/documents/${encodeURIComponent(documentId)}/retry`,
{},
{ headers: this.idempotencyHeaders(idempotencyKey), skipToast: true },
);
}
/** K01 — current active-knowledge selection (revision + active document ids). */
getKnowledgeSelection(): Observable<KnowledgeSelection> {
return this.http.getRaw<KnowledgeSelection>(`${API}/knowledge-selection`, { skipToast: true });
}
/**
* K02 — replace the whole active-knowledge selection. The full set is keyed by
* `expected_revision` (no Idempotency-Key): after a timeout or REVISION_CONFLICT the UI
* re-reads K01 first instead of blindly repeating the request.
*/
updateKnowledgeSelection(patch: KnowledgeSelectionPatch): Observable<KnowledgeSelectionResponse> {
return this.http.patchRaw<KnowledgeSelectionResponse>(`${API}/knowledge-selection`, patch, {
headers: this.csrfHeaders(),
skipToast: true,
});
}
/** Extract the standard error envelope from an HttpErrorResponse, if present. */
static getErrorInfo(error: unknown): { code: string; message: string; requestId?: string } {
const res = error as HttpErrorResponse | undefined;
const envelope = res?.error as ErrorEnvelope | undefined;
const code = envelope?.error?.code ?? (res?.status === 0 ? 'NETWORK' : 'UNKNOWN');
const message = envelope?.error?.message ?? res?.message ?? 'خطای ناشناخته سرور';
const requestId =
envelope?.error?.request_id ??
(res?.headers?.get?.('X-Request-ID') as string | undefined) ??
undefined;
return { code, message, requestId };
}
/** Map a backend error code to a user-facing Persian message (handoff §10 / catalog §7). */
static statusForError(code: string, fallback: string): string {
switch (code) {
case 'DOCUMENT_NOT_READY':
return 'فقط اسناد وضعیت آماده قابل فعال‌سازی هستند.';
case 'EXTRACTION_REVIEW_PENDING':
return 'قبل از تلاش مجدد، شواهد نیازمند بازبینی را تکمیل کنید.';
case 'REVISION_CONFLICT':
return 'لیست دانش همزمان توسط کاربر دیگری به‌روز شده است. صفحه را تازه‌سازی کنید.';
case 'IDEMPOTENCY_CONFLICT':
return 'این عملیات قبلاً با محتوای دیگری ثبت شده است.';
case 'REVIEW_STALE':
case 'REVIEW_ALREADY_DECIDED':
return 'شواهد بازبینی تغییر کرده است؛ موارد را دوباره خوانده و تصمیم بگیرید.';
case 'FILE_TOO_LARGE':
case 'PAYLOAD_TOO_LARGE':
return 'حجم فایل یا درخواست بیش از حد مجاز است.';
case 'UNSUPPORTED_FILE_TYPE':
return 'نوع فایل پشتیبانی نمی‌شود.';
case 'INVALID_FILE':
return 'فایل قابل پردازش نیست.';
case 'VALIDATION_ERROR':
return 'شکل درخواست نامعتبر است.';
case 'CONTEXT_REVOKED':
case 'CONVERSATION_STALE':
return 'مکالمه‌های صوتی قبلی به‌دلیل تغییر محتوای دانش باطل شده‌اند. گفتگوی جدیدی شروع کنید.';
case 'LIVE_SESSION_UNUSABLE':
return 'نشست صوتی بسته شده است. گفتگوی جدیدی شروع کنید.';
case 'RATE_LIMITED':
return 'تلاش‌های بیش از حد مجاز. لطفاً بعداً تلاش کنید.';
case 'CALIBRATION_REQUIRED':
case 'DEPENDENCY_UNAVAILABLE':
return 'سرویس موقتاً در دسترس نیست. لطفاً دوباره تلاش کنید.';
case 'AUTH_REQUIRED':
return 'ابتدا وارد سیستم شوید.';
case 'CSRF_INVALID':
return 'نشست شما نامعتبر است. دوباره وارد شوید.';
case 'FORBIDDEN':
return 'دسترسی به این عملیات مجاز نیست.';
case 'NETWORK':
return 'ارتباط با سرور برقرار نشد.';
default:
return fallback;
}
}
/** True if the backend status is a terminal state (no more polling). */
static isTerminal(status: DocumentStatus): boolean {
return status === 'ready' || status === 'failed';
}
/** Whether a status row still needs to be polled per D03. */
static isPolling(status: DocumentStatus): boolean {
return !DocumentsService.isTerminal(status);
}
}
@@ -0,0 +1,195 @@
/**
* Type definitions for the MVP document / knowledge-selection / extraction-review API.
* Source of truth: docs/backend-api-docs/mvp_ui_api_catalog.md
*
* These endpoints return *raw* JSON (not the ApiResult envelope used by the legacy
* HttpService envelope methods), so they are consumed through `getRaw`/`postRaw`/
* `patchRaw`/`uploadWithProgress` and errors are inspected via the standard
* `{ error: { code, message, request_id, retryable, details } }` envelope.
*/
/** Document processing lifecycle. */
export type DocumentStatus = 'queued' | 'processing' | 'ready' | 'failed';
/** Frozen-per-document OCR review policy state (D03). */
export type ReviewState = 'not_evaluated' | 'not_required' | 'pending' | 'approved' | 'rejected';
/** Extraction quality decision; never fabricate a human-approval claim from it. */
export type ExtractionQualityDecision = null | 'passed' | 'reviewed' | 'partially_reviewed';
export interface DocumentLocation {
page?: number | null;
section?: string | null;
}
export interface DocumentJobError {
code: string;
message: string;
request_id?: string;
retryable?: boolean;
details?: Record<string, unknown>;
}
export interface DocumentJob {
id: string;
status: string;
stage: string | null;
attempt_count: number;
retry_generation: number;
can_retry: boolean;
error: DocumentJobError | null;
}
/** A single document row as returned by `GET /documents` (D02). */
export interface DocumentListItem {
id: string;
title: string | null;
filename: string;
status: DocumentStatus;
is_active: boolean;
searchable: boolean;
chunk_count: number;
created_at: string;
job: DocumentJob;
/** Present on the detail/polling response (D03); absent from the base list. */
review_required?: boolean;
/** Frozen OCR policy of this document (D03); the UI has no toggle for it. */
ocr_review_required?: boolean;
review_state?: ReviewState;
extraction_quality_decision?: ExtractionQualityDecision;
}
/** `GET /documents` (D02) paginated result. */
export interface DocumentListResponse {
items: DocumentListItem[];
next_cursor: string | null;
knowledge_revision: number;
}
/** Query parameters accepted by `GET /documents`. */
export interface DocumentListParams {
limit?: number;
cursor?: string;
status?: DocumentStatus;
is_active?: boolean;
}
/** `GET /documents/{id}` (D03) — same as a list item plus the review flag. */
export interface DocumentDetail extends DocumentListItem {
review_required: boolean;
}
/** `POST /documents` (D01) accepted payload. */
export interface DocumentUploadResult {
document_id: string;
job_id: string;
status: DocumentStatus;
is_active: boolean;
searchable: boolean;
}
/** `POST /documents/{id}/retry` (D04) accepted payload. */
export interface RetryResult {
document_id: string;
job_id: string;
status: DocumentStatus;
retry_generation: number;
}
/** A single extraction block from `GET /documents/{id}/extraction-review` (D06). */
export interface ExtractionBlock {
block_id: string;
text: string;
group_id: string | null;
}
/** One reviewable evidence item from D06 (extraction or factual_corpus). */
export interface ExtractionItem {
evidence_sha256: string;
review_kind: string;
location?: DocumentLocation | null;
blocks: ExtractionBlock[];
required_checks: string[];
decision: 'approve' | 'reject' | null;
/** Authenticated preview URL from the server (may be null, e.g. factual evidence). */
preview_path: string | null;
}
/** `GET /documents/{id}/extraction-review` (D06). */
export interface ExtractionReviewResponse {
document_id: string;
status: DocumentStatus;
review_required: boolean;
items: ExtractionItem[];
next_cursor: string | null;
}
/** `POST /documents/{id}/extraction-review/decisions` (D07). */
export interface ReviewDecisionRequest {
evidence_sha256: string;
decision: 'approve' | 'reject';
checked: string[];
note?: string;
excluded_group_ids?: string[];
}
export interface ReviewDecisionResponse {
document_id: string;
evidence_sha256: string;
decision: 'approve' | 'reject';
review_required: boolean;
}
/** System configuration / capabilities from `GET /configuration` (F01). */
export interface SystemConfiguration {
revision: number;
assistant_name: string;
instruction: string;
capabilities: SystemCapabilities;
}
export interface SystemCapabilities {
text: boolean;
voice: boolean;
captions: boolean;
supported_upload_types: string[];
max_upload_bytes: number;
max_pdf_pages: number;
supported_structure_notes: string;
}
/** `GET /knowledge-selection` (K01). */
export interface KnowledgeSelection {
revision: number;
access_epoch: number;
document_ids: string[];
}
/** `PATCH /knowledge-selection` (K02) request / response. */
export interface KnowledgeSelectionPatch {
expected_revision: number;
document_ids: string[];
}
export interface KnowledgeSelectionResponse extends KnowledgeSelection {
conversations_invalidated: boolean;
}
/** Standard error envelope carried on a non-2xx response body. */
export interface ErrorEnvelope {
error: {
code: string;
message: string;
request_id?: string;
retryable?: boolean;
details?: Record<string, unknown>;
};
}
/** Persian labels for document processing status. */
export const DOCUMENT_STATUS_LABEL: Record<DocumentStatus, string> = {
queued: 'در صف پردازش',
processing: 'در حال پردازش',
ready: 'آماده',
failed: 'ناموفق',
};
@@ -1,4 +1,9 @@
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { HttpService } from './http.service';
@@ -6,7 +11,15 @@ describe('HttpService', () => {
let service: HttpService;
beforeEach(() => {
TestBed.configureTestingModule({});
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
],
});
service = TestBed.inject(HttpService);
});
+111 -7
View File
@@ -1,7 +1,13 @@
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import {
HttpClient,
HttpErrorResponse,
HttpHeaders,
HttpEvent,
HttpEventType,
} from '@angular/common/http';
import { Router } from '@angular/router';
import { catchError, Observable, throwError, map } from 'rxjs';
import { catchError, Observable, throwError, map, race } from 'rxjs';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrService } from 'ngx-toastr';
@@ -25,6 +31,8 @@ export interface HttpOptions {
cooldownMs?: number;
skipHasErrorCheck?: boolean;
headers?: Record<string, string>;
/** Optional AbortSignal forwarded to the underlying XMLHttpRequest. */
signal?: AbortSignal;
}
export const EVENT_STREAM_HEADERS = {
@@ -37,10 +45,21 @@ export const EVENT_STREAM_HEADERS = {
providedIn: 'root',
})
export class HttpService {
private readonly baseUrl = `${window.location.protocol}//${window.location.hostname}/api`;
public readonly backendUrl = `${window.location.protocol}//${window.location.hostname}/api`;
public readonly apiUrl = `${window.location.protocol}//${window.location.hostname}/api`;
public readonly imagesUrl = `${window.location.protocol}//${window.location.hostname}`;
/**
* Same-origin deployment: the browser talks to `/api/v1/...` on the UI origin and
* the dev-server proxy (proxy.conf.json) forwards `/api` — including WebSocket
* upgrades — to the backend. The `rag_session` cookie therefore stays same-origin
* and is sent automatically; no bearer token is used for the MVP endpoints.
*
* NOTE: the origin MUST stay empty (`''`). Pointing these at an absolute host
* (e.g. `http://192.168.180.151:8080`) turns every request cross-origin, and browsers
* refuse to send the session cookie cross-origin over plain HTTP — the backend
* then answers 401 AUTH_REQUIRED even though the user is logged in.
*/
private readonly baseUrl = '';
public readonly backendUrl = '';
public readonly apiUrl = '';
public readonly imagesUrl = '';
constructor(
private readonly http: HttpClient,
@@ -94,6 +113,13 @@ export class HttpService {
return throwError(() => new Error('Unauthorized'));
}
if (error.status === 429 && !skipToast) {
if (this.shouldDisplayMessage('تلاش‌های بیش از حد مجاز. لطفاً بعداً تلاش کنید.')) {
this.toast.warning('تلاش‌های بیش از حد مجاز. لطفاً بعداً تلاش کنید.');
}
return throwError(() => new Error('RATE_LIMITED'));
}
if (error.status === 422 && error.error && !skipToast) {
try {
const apiError = error.error as ApiResult<any>;
@@ -149,6 +175,7 @@ export class HttpService {
.get<ApiResult<T>>(url, {
headers,
params: options.params,
withCredentials: true,
})
.pipe(
map((response) => this.processResponse(response, options)),
@@ -185,7 +212,7 @@ export class HttpService {
...headers,
},
signal: controller.signal,
credentials: 'omit',
credentials: 'include',
})
.then((response) => {
if (!response.ok || !response.body) {
@@ -247,6 +274,7 @@ export class HttpService {
.post<ApiResult<T>>(url, data, {
headers: this.mergeHeaders(options.headers),
params: options.params,
withCredentials: true,
})
.pipe(
map((response) => this.processResponse(response, options)),
@@ -254,12 +282,85 @@ export class HttpService {
);
}
postRaw<T>(endpoint: string, data: any, options: HttpOptions = {}): Observable<T> {
const url = `${this.baseUrl}/${endpoint}`;
const headers = options.headers ? new HttpHeaders(options.headers) : new HttpHeaders();
return this.http.post<T>(url, data, {
headers,
params: options.params,
withCredentials: true,
});
}
/**
* Raw PATCH (no envelope processing, no bearer token): used by MVP endpoints
* such as `PATCH /knowledge-selection` whose auth is the `rag_session` cookie.
*/
patchRaw<T>(endpoint: string, data: any, options: HttpOptions = {}): Observable<T> {
const url = `${this.baseUrl}/${endpoint}`;
const headers = options.headers ? new HttpHeaders(options.headers) : new HttpHeaders();
return this.http
.patch<T>(url, data, { headers, params: options.params, withCredentials: true })
.pipe(catchError((err) => this.handleError(err, options.skipToast)));
}
/**
* Multipart upload that reports byte-level progress as `HttpEvent`s.
* Auth is the session cookie (same origin), so — like `postRaw`/`getRaw` — the
* bearer token is not injected; pass `X-CSRF-Token` / `Idempotency-Key` via `options.headers`.
* Cancellation is driven by racing the request against an `AbortSignal`-derived error;
* the race's teardown unsubscribes and aborts the in-flight XHR.
*/
uploadWithProgress<T>(
endpoint: string,
data: FormData,
options: HttpOptions = {},
): Observable<HttpEvent<T>> {
const url = `${this.baseUrl}/${endpoint}`;
const headers = options.headers ? new HttpHeaders(options.headers) : new HttpHeaders();
const http$ = this.http.post<T>(url, data, {
headers,
params: options.params,
reportProgress: true,
observe: 'events',
withCredentials: true,
});
if (!options.signal) {
return http$.pipe(catchError((err) => this.handleError(err, options.skipToast)));
}
const abort$ = new Observable<never>((subscriber) => {
if (options.signal!.aborted) {
subscriber.error(new HttpErrorResponse({ status: 0, statusText: 'Aborted', url }));
return;
}
const onAbort = () =>
subscriber.error(new HttpErrorResponse({ status: 0, statusText: 'Aborted', url }));
options.signal!.addEventListener('abort', onAbort);
return () => options.signal!.removeEventListener('abort', onAbort);
});
return race(http$, abort$).pipe(catchError((err) => this.handleError(err, options.skipToast)));
}
getRaw<T>(endpoint: string, options: HttpOptions = {}): Observable<T> {
const url = `${this.baseUrl}/${endpoint}`;
const headers = options.headers ? new HttpHeaders(options.headers) : new HttpHeaders();
return this.http.get<T>(url, {
headers,
params: options.params,
withCredentials: true,
});
}
put<T>(endpoint: string, data: any, options: HttpOptions = {}): Observable<ApiResult<T>> {
const url = `${this.baseUrl}/${endpoint}`;
return this.http
.put<ApiResult<T>>(url, data, {
headers: this.mergeHeaders(options.headers),
params: options.params,
withCredentials: true,
})
.pipe(
map((response) => this.processResponse(response, options)),
@@ -273,6 +374,7 @@ export class HttpService {
.patch<ApiResult<T>>(url, data, {
headers: this.mergeHeaders(options.headers),
params: options.params,
withCredentials: true,
})
.pipe(
map((response) => this.processResponse(response, options)),
@@ -286,6 +388,7 @@ export class HttpService {
.delete<ApiResult<T>>(url, {
headers: this.mergeHeaders(options.headers),
params: options.params,
withCredentials: true,
})
.pipe(
map((response) => this.processResponse(response, options)),
@@ -298,6 +401,7 @@ export class HttpService {
.get(url, {
headers: this.getHeaders(),
responseType: 'blob',
withCredentials: true,
})
.pipe(catchError((err) => this.handleError(err, false)));
}
@@ -0,0 +1,89 @@
import { Injectable } from '@angular/core';
export type MicrophoneErrorCode = 'unsupported' | 'denied' | 'unavailable' | 'unknown';
export class MicrophoneError extends Error {
constructor(readonly code: MicrophoneErrorCode, message?: string) {
super(message ?? code);
this.name = 'MicrophoneError';
}
}
/**
* Owns the microphone MediaStream. It does nothing except capture:
* the orb (audio level) and speech recognition consume it separately.
*/
@Injectable({ providedIn: 'root' })
export class MicrophoneService {
private stream: MediaStream | null = null;
private endedCleanup: (() => void) | null = null;
/** `mediaDevices` is undefined on non-secure (http) origins other than localhost. */
get isSupported(): boolean {
return typeof navigator !== 'undefined' && !!navigator.mediaDevices?.getUserMedia;
}
/**
* 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,
audio: MediaTrackConstraints | boolean = true,
): Promise<MediaStream> {
if (!this.isSupported) {
throw new MicrophoneError('unsupported');
}
this.release();
let stream: MediaStream;
try {
stream = await navigator.mediaDevices.getUserMedia({ audio });
} catch (err) {
throw this.mapError(err);
}
this.stream = stream;
const track = stream.getAudioTracks()[0];
if (track && onEnded) {
const handler = (): void => onEnded();
track.addEventListener('ended', handler);
this.endedCleanup = () => track.removeEventListener('ended', handler);
}
return stream;
}
/** Stops every track of the given stream (defaults to the current one). */
release(stream: MediaStream | null = this.stream): void {
if (!stream) return;
if (stream === this.stream) {
this.endedCleanup?.();
this.endedCleanup = null;
this.stream = null;
}
stream.getTracks().forEach((track) => track.stop());
}
private mapError(err: unknown): MicrophoneError {
const name = err instanceof DOMException ? err.name : '';
switch (name) {
case 'NotAllowedError':
case 'SecurityError':
case 'PermissionDeniedError':
return new MicrophoneError('denied');
case 'NotFoundError':
case 'DevicesNotFoundError':
case 'NotReadableError':
case 'TrackStartError':
case 'OverconstrainedError':
return new MicrophoneError('unavailable');
default:
return new MicrophoneError('unknown');
}
}
}
+88
View File
@@ -0,0 +1,88 @@
import {
AiChannelUsage,
AiPerformance,
CategoryShare,
QuestionSummary,
TopQuestion,
UsageTrendPoint,
} from './reports.types';
const TREND_DAYS = 30;
/** Deterministic pseudo-random source so mock data stays stable across reloads and tests. */
function seededNoise(seed: number): number {
const value = Math.sin(seed * 12.9898) * 43758.5453;
return Math.abs(value - Math.floor(value));
}
function buildTrend(): UsageTrendPoint[] {
const points: UsageTrendPoint[] = [];
const today = new Date();
for (let offset = TREND_DAYS - 1; offset >= 0; offset--) {
const date = new Date(today);
date.setDate(today.getDate() - offset);
const weekday = date.getDay();
const isWeekend = weekday === 4 || weekday === 5;
const noise = seededNoise(offset + 1);
// Recent campaign window lifts the last two weeks.
const campaign = offset <= 14 ? 9 : 0;
const base = isWeekend ? 34 : 58;
const count = Math.round(base + noise * 22 - (isWeekend ? 12 : 0) + campaign);
points.push({
label: date.toLocaleDateString('fa-IR', { day: 'numeric', month: 'long' }),
count,
});
}
return points;
}
export const MOCK_TOP_QUESTIONS: TopQuestion[] = [
{ id: 'q1', text: 'چگونه رمز عبور حساب کاربری خود را بازیابی کنم؟', count: 142, category: 'حساب کاربری' },
{ id: 'q2', text: 'ساعات کاری پشتیبانی در چه ساعتی است؟', count: 128, category: 'پشتیبانی' },
{ id: 'q3', text: 'برای دریافت فاکتور رسمی چگونه اقدام کنم؟', count: 97, category: 'پرداخت و فاکتور' },
{ id: 'q4', text: 'آیا ارسال به شهرستان‌ها امکان‌پذیر است؟', count: 88, category: 'سفارش و ارسال' },
{ id: 'q5', text: 'چگونه سفارش خود را پیگیری کنم؟', count: 76, category: 'سفارش و ارسال' },
{ id: 'q6', text: 'هزینه ارسال چگونه محاسبه می‌شود؟', count: 61, category: 'سفارش و ارسال' },
{ id: 'q7', text: 'شرایط مرجوع کردن کالا چیست؟', count: 54, category: 'پشتیبانی' },
{ id: 'q8', text: 'آیا امکان پرداخت اقساطی وجود دارد؟', count: 47, category: 'پرداخت و فاکتور' },
];
export const MOCK_QUESTION_SUMMARY: QuestionSummary = {
totalQuestions: 4802,
uniqueUsers: 1736,
aiAnswered: 4318,
escalatedToAgent: 484,
periodLabel: '۳۰ روز گذشته',
};
export const MOCK_CATEGORY_SHARES: CategoryShare[] = [
{ category: 'حساب کاربری', count: 1265 },
{ category: 'سفارش و ارسال', count: 1148 },
{ category: 'پرداخت و فاکتور', count: 862 },
{ category: 'پشتیبانی', count: 668 },
{ category: 'محصولات', count: 479 },
{ category: 'سایر', count: 380 },
];
export const MOCK_USAGE_TREND: UsageTrendPoint[] = buildTrend();
export const MOCK_AI_CHANNELS: AiChannelUsage[] = [
{ label: 'گفتگوی متنی', count: 3622 },
{ label: 'گفتگوی صوتی', count: 1180 },
];
export const MOCK_AI_PERFORMANCE: AiPerformance = {
totalResponses: 4802,
faqBasedResponses: 3553,
avgResponseSeconds: 1.8,
successRate: 91,
satisfactionRate: 87,
escalationRate: 10,
channels: MOCK_AI_CHANNELS,
};
@@ -0,0 +1,83 @@
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { firstValueFrom } from 'rxjs';
import { ReportsService } from './reports.service';
describe('ReportsService', () => {
let service: ReportsService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
],
});
service = TestBed.inject(ReportsService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('returns top questions ranked by frequency', async () => {
const questions = await firstValueFrom(service.getTopQuestions());
expect(questions.length).toBeGreaterThan(0);
const counts = questions.map((question) => question.count);
expect([...counts].sort((a, b) => b - a)).toEqual(counts);
});
it('returns a question summary whose parts stay within the total', async () => {
const summary = await firstValueFrom(service.getQuestionSummary());
expect(summary.totalQuestions).toBeGreaterThan(0);
expect(summary.aiAnswered + summary.escalatedToAgent).toBeLessThanOrEqual(
summary.totalQuestions,
);
});
it('returns category shares summing up to the total question count', async () => {
const categories = await firstValueFrom(service.getCategoryDistribution());
const summary = await firstValueFrom(service.getQuestionSummary());
const total = categories.reduce((sum, category) => sum + category.count, 0);
expect(total).toBe(summary.totalQuestions);
});
it('returns a 30 point usage trend with valid labels', async () => {
const trend = await firstValueFrom(service.getUsageTrend());
expect(trend).toHaveLength(30);
trend.forEach((point) => {
expect(point.label).toBeTruthy();
expect(point.count).toBeGreaterThan(0);
});
});
it('returns AI performance stats with bounded rates', async () => {
const performance = await firstValueFrom(service.getAiPerformance());
expect(performance.totalResponses).toBeGreaterThan(0);
expect(performance.channels.length).toBeGreaterThan(0);
expect(performance.successRate).toBeLessThanOrEqual(100);
expect(performance.satisfactionRate).toBeLessThanOrEqual(100);
});
it('returns a complete overview combining every report', async () => {
const overview = await firstValueFrom(service.getOverview());
expect(overview.topQuestions.length).toBeGreaterThan(0);
expect(overview.categories.length).toBeGreaterThan(0);
expect(overview.trend).toHaveLength(30);
expect(overview.summary.totalQuestions).toBeGreaterThan(0);
expect(overview.aiPerformance.totalResponses).toBeGreaterThan(0);
});
});
@@ -0,0 +1,72 @@
import { Injectable, inject } from '@angular/core';
import { map, Observable, of } from 'rxjs';
import { HttpService } from '../http-request/http.service';
import {
AiPerformance,
CategoryShare,
QuestionSummary,
ReportsView,
TopQuestion,
UsageTrendPoint,
} from './reports.types';
import {
MOCK_AI_PERFORMANCE,
MOCK_CATEGORY_SHARES,
MOCK_QUESTION_SUMMARY,
MOCK_TOP_QUESTIONS,
MOCK_USAGE_TREND,
} from './reports.mock';
@Injectable({
providedIn: 'root',
})
export class ReportsService {
private readonly http = inject(HttpService);
/** Flip to false once the backend report endpoints are deployed. */
private readonly useMockData = true;
getTopQuestions(limit = 8): Observable<TopQuestion[]> {
return this.request<TopQuestion[]>('reports/top-questions', { limit }, MOCK_TOP_QUESTIONS);
}
getQuestionSummary(): Observable<QuestionSummary> {
return this.request<QuestionSummary>('reports/questions-summary', {}, MOCK_QUESTION_SUMMARY);
}
getCategoryDistribution(): Observable<CategoryShare[]> {
return this.request<CategoryShare[]>(
'reports/questions-distribution',
{},
MOCK_CATEGORY_SHARES,
);
}
getUsageTrend(days = 30): Observable<UsageTrendPoint[]> {
return this.request<UsageTrendPoint[]>('reports/usage-trend', { days }, MOCK_USAGE_TREND);
}
getAiPerformance(): Observable<AiPerformance> {
return this.request<AiPerformance>('reports/ai-performance', {}, MOCK_AI_PERFORMANCE);
}
getOverview(): Observable<ReportsView> {
return this.request<ReportsView>('reports/overview', {}, {
topQuestions: MOCK_TOP_QUESTIONS,
summary: MOCK_QUESTION_SUMMARY,
categories: MOCK_CATEGORY_SHARES,
trend: MOCK_USAGE_TREND,
aiPerformance: MOCK_AI_PERFORMANCE,
});
}
private request<T>(endpoint: string, params: Record<string, unknown>, fallback: T): Observable<T> {
if (this.useMockData) {
return of(fallback);
}
return this.http
.get<T>(endpoint, { params, skipToast: true, skipHasErrorCheck: true })
.pipe(map((response) => response.result));
}
}
+47
View File
@@ -0,0 +1,47 @@
export interface TopQuestion {
id: string;
text: string;
count: number;
category: string;
}
export interface QuestionSummary {
totalQuestions: number;
uniqueUsers: number;
aiAnswered: number;
escalatedToAgent: number;
periodLabel: string;
}
export interface CategoryShare {
category: string;
count: number;
}
export interface UsageTrendPoint {
label: string;
count: number;
}
export interface AiChannelUsage {
label: string;
count: number;
}
export interface AiPerformance {
totalResponses: number;
faqBasedResponses: number;
avgResponseSeconds: number;
successRate: number;
satisfactionRate: number;
escalationRate: number;
channels: AiChannelUsage[];
}
export interface ReportsView {
topQuestions: TopQuestion[];
summary: QuestionSummary;
categories: CategoryShare[];
trend: UsageTrendPoint[];
aiPerformance: AiPerformance;
}
@@ -0,0 +1,337 @@
import { Injectable, NgZone, inject } from '@angular/core';
/* Minimal typings: SpeechRecognition is not part of TypeScript's lib.dom. */
interface SpeechRecognitionAlternativeLike {
transcript: string;
}
interface SpeechRecognitionResultLike {
readonly isFinal: boolean;
readonly length: number;
[index: number]: SpeechRecognitionAlternativeLike;
}
interface SpeechRecognitionEventLike {
readonly resultIndex: number;
readonly results: { readonly length: number; [index: number]: SpeechRecognitionResultLike };
}
interface SpeechRecognitionErrorEventLike {
readonly error: string;
}
interface SpeechRecognitionLike {
lang: string;
continuous: boolean;
interimResults: boolean;
maxAlternatives: number;
onresult: ((event: SpeechRecognitionEventLike) => void) | null;
onerror: ((event: SpeechRecognitionErrorEventLike) => void) | null;
onend: (() => void) | null;
onspeechend: (() => void) | null;
start(): void;
stop(): void;
abort(): void;
}
type SpeechRecognitionCtor = new () => SpeechRecognitionLike;
export const DEFAULT_SPEECH_LANGUAGE = 'fa-IR';
export type SpeechErrorKind =
| 'permission-denied'
| 'audio-capture'
| 'network'
| 'no-speech'
| 'language-not-supported'
| 'unsupported'
| 'unknown';
export interface SpeechTranscript {
/** Confirmed text for the whole session (never contains duplicates). */
final: string;
/** Text still being recognized; may change or disappear on the next event. */
interim: string;
}
export interface SpeechSessionHandlers {
onTranscript(transcript: SpeechTranscript): void;
onSpeechEnd?(): void;
/** Fatal errors only. The session is already over when this is called. */
onError(kind: SpeechErrorKind): void;
}
/** Silent restarts allowed (Chrome ends sessions after pauses) before reporting "no speech". */
const MAX_SILENT_RESTARTS = 4;
const RESTART_DELAY_MS = 250;
const STOP_TIMEOUT_MS = 1500;
@Injectable({ providedIn: 'root' })
export class SpeechRecognitionService {
private readonly ngZone = inject(NgZone);
private readonly ctor: SpeechRecognitionCtor | null = this.resolveCtor();
private recognition: SpeechRecognitionLike | null = null;
private handlers: SpeechSessionHandlers | null = null;
private lang = DEFAULT_SPEECH_LANGUAGE;
private running = false;
private finalText = '';
private interimText = '';
private silentRestarts = 0;
private restartTimer: ReturnType<typeof setTimeout> | null = null;
private stopTimer: ReturnType<typeof setTimeout> | null = null;
private stopResolver: ((text: string) => void) | null = null;
get isSupported(): boolean {
return this.ctor !== null;
}
/** Final + interim text right now. */
currentText(): string {
return this.join(this.finalText, this.interimText);
}
/** Starts a continuous session. Returns false if it could not be started. */
start(lang: string, handlers: SpeechSessionHandlers): boolean {
if (!this.ctor) return false;
this.abort();
this.lang = lang || DEFAULT_SPEECH_LANGUAGE;
this.handlers = handlers;
this.finalText = '';
this.interimText = '';
this.silentRestarts = 0;
this.running = true;
if (!this.startRecognition()) {
this.abort();
return false;
}
return true;
}
/**
* Stops listening and resolves with the confirmed text, including any
* interim text the engine had not finalized yet.
*/
stop(): Promise<string> {
this.clearRestartTimer();
this.running = false;
const recognition = this.recognition;
if (!recognition) {
return Promise.resolve(this.promoteInterim());
}
return new Promise<string>((resolve) => {
this.stopResolver = resolve;
this.stopTimer = setTimeout(() => this.resolveStop(true), STOP_TIMEOUT_MS);
try {
recognition.stop(); // late final results still arrive via onresult, then onend
} catch {
this.resolveStop(true);
}
});
}
/** Immediately terminates the session and discards callbacks. */
abort(): void {
this.running = false;
this.clearRestartTimer();
if (this.stopTimer) {
clearTimeout(this.stopTimer);
this.stopTimer = null;
}
const resolver = this.stopResolver;
this.stopResolver = null;
this.detachRecognition(true);
this.handlers = null;
resolver?.(this.promoteInterim());
}
dispose(): void {
this.abort();
}
// ---------------------------------------------------------------------------
private startRecognition(): boolean {
if (!this.ctor) return false;
const recognition = new this.ctor();
recognition.lang = this.lang;
recognition.continuous = true;
recognition.interimResults = true;
recognition.maxAlternatives = 1;
recognition.onresult = (event) => this.handleResult(event);
recognition.onerror = (event) => this.handleError(event);
recognition.onspeechend = () => this.emit((h) => h.onSpeechEnd?.());
recognition.onend = () => this.handleEnd();
this.recognition = recognition;
try {
recognition.start();
return true;
} catch {
this.recognition = null;
return false;
}
}
private handleResult(event: SpeechRecognitionEventLike): void {
// Entries before resultIndex were delivered (and finalized) in earlier events,
// so only entries from resultIndex onward are processed: no duplicated words.
let interim = '';
for (let i = event.resultIndex; i < event.results.length; i++) {
const result = event.results[i];
const text = (result[0]?.transcript ?? '').trim();
if (!text) continue;
if (result.isFinal) {
this.finalText = this.join(this.finalText, text);
} else {
interim = this.join(interim, text);
}
}
this.interimText = interim;
this.silentRestarts = 0;
this.emitTranscript();
}
private handleError(event: SpeechRecognitionErrorEventLike): void {
switch (event.error) {
case 'no-speech': // not fatal: onend decides whether to restart
case 'aborted':
return;
case 'not-allowed':
case 'service-not-allowed':
this.fail('permission-denied');
return;
case 'audio-capture':
this.fail('audio-capture');
return;
case 'network':
this.fail('network');
return;
case 'language-not-supported':
this.fail('language-not-supported');
return;
default:
this.fail('unknown');
}
}
private handleEnd(): void {
if (this.stopResolver) {
this.resolveStop(false);
return;
}
if (!this.running) return;
// The engine ended on its own (pause, timeout, ...): keep what we have and restart.
this.detachRecognition(false);
this.promoteInterim();
this.emitTranscript();
this.silentRestarts++;
if (this.silentRestarts > MAX_SILENT_RESTARTS) {
this.fail('no-speech');
return;
}
this.restartTimer = setTimeout(() => {
this.restartTimer = null;
if (this.running && !this.startRecognition()) {
this.fail('unknown');
}
}, RESTART_DELAY_MS);
}
private fail(kind: SpeechErrorKind): void {
const handlers = this.handlers;
this.running = false;
this.clearRestartTimer();
this.detachRecognition(true);
this.emitWith(handlers, (h) => h.onError(kind));
}
private resolveStop(abortEngine: boolean): void {
if (this.stopTimer) {
clearTimeout(this.stopTimer);
this.stopTimer = null;
}
const resolver = this.stopResolver;
this.stopResolver = null;
const text = this.promoteInterim();
this.detachRecognition(abortEngine);
resolver?.(text);
}
/** Commits interim text to final text (used when a session ends mid-phrase). */
private promoteInterim(): string {
if (this.interimText) {
this.finalText = this.join(this.finalText, this.interimText);
this.interimText = '';
}
return this.finalText;
}
private detachRecognition(abortEngine: boolean): void {
const recognition = this.recognition;
this.recognition = null;
if (!recognition) return;
recognition.onresult = null;
recognition.onerror = null;
recognition.onend = null;
recognition.onspeechend = null;
if (abortEngine) {
try {
recognition.abort();
} catch {
/* already stopped */
}
}
}
private clearRestartTimer(): void {
if (this.restartTimer) {
clearTimeout(this.restartTimer);
this.restartTimer = null;
}
}
private emitTranscript(): void {
const transcript: SpeechTranscript = { final: this.finalText, interim: this.interimText };
this.emit((h) => h.onTranscript(transcript));
}
private emit(fn: (handlers: SpeechSessionHandlers) => void): void {
this.emitWith(this.handlers, fn);
}
/** Speech events may fire outside Angular's zone; always hand results back inside it. */
private emitWith(
handlers: SpeechSessionHandlers | null,
fn: (handlers: SpeechSessionHandlers) => void,
): void {
if (!handlers) return;
this.ngZone.run(() => fn(handlers));
}
private join(a: string, b: string): string {
return a && b ? `${a} ${b}` : a || b;
}
private resolveCtor(): SpeechRecognitionCtor | null {
if (typeof window === 'undefined') return null;
const w = window as unknown as {
SpeechRecognition?: SpeechRecognitionCtor;
webkitSpeechRecognition?: SpeechRecognitionCtor;
};
return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null;
}
}
+14 -1
View File
@@ -1,4 +1,9 @@
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { ThemeService } from './theme.service';
@@ -6,7 +11,15 @@ describe('ThemeService', () => {
let service: ThemeService;
beforeEach(() => {
TestBed.configureTestingModule({});
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
],
});
service = TestBed.inject(ThemeService);
});
+2 -2
View File
@@ -21,7 +21,7 @@ export class ThemeService {
this.applyTheme('light');
}
this.httpService.get('users/get-dark-mode').subscribe({
this.httpService.get('users/get-dark-mode', { skipToast: true }).subscribe({
next: (res: any) => {
const isBackendDark = res.result.dark_mode;
const trueTheme = isBackendDark ? 'dark' : 'light';
@@ -41,7 +41,7 @@ export class ThemeService {
const payload = { dark_mode: isDark };
this.httpService.post('users/update-dark-mode', payload).subscribe({
this.httpService.post('users/update-dark-mode', payload, { skipToast: true }).subscribe({
next: () => {},
error: () => {}
});
@@ -0,0 +1,362 @@
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;
/**
* Renders the animated voice orb and derives an audio level from a MediaStream.
* It never requests the microphone itself: MicrophoneService owns the stream,
* this service only analyses it (attachStream / detachAudio).
*/
@Injectable({ providedIn: 'root' })
export class VoiceOrbService {
private readonly ngZone = inject(NgZone);
private readonly reducedMotion =
typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
private scene: THREE.Scene | null = null;
private camera: THREE.PerspectiveCamera | null = null;
private renderer: THREE.WebGLRenderer | null = null;
private orb: THREE.Mesh | null = null;
private orbGeometry: THREE.BufferGeometry | null = null;
private glowShell: THREE.Mesh | null = null;
private originalPositions: Float32Array | null = null;
private resizeObserver: ResizeObserver | null = null;
private animationId: number | null = null;
private audioContext: AudioContext | null = null;
private analyser: AnalyserNode | null = null;
private sourceNode: MediaStreamAudioSourceNode | null = null;
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.
*/
init(container: HTMLElement): boolean {
if (this.scene && this.renderer) {
if (this.renderer.domElement.parentNode !== container) {
container.appendChild(this.renderer.domElement);
}
this.resize(container);
return true;
}
const width = container.clientWidth || FALLBACK_SIZE;
const height = container.clientHeight || FALLBACK_SIZE;
let renderer: THREE.WebGLRenderer;
try {
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: 'high-performance',
});
} catch (err) {
console.warn('VoiceOrbService: WebGL is not available.', err);
return false;
}
this.renderer = renderer;
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height, false); // CSS controls the displayed size
renderer.setClearColor(0x000000, 0);
container.appendChild(renderer.domElement);
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 100);
this.camera.position.z = 4;
this.scene.add(new THREE.AmbientLight(0x404060, 2));
const pointLight1 = new THREE.PointLight(0x3b82f6, 12, 10);
pointLight1.position.set(0, 0, 3);
this.scene.add(pointLight1);
const pointLight2 = new THREE.PointLight(0x8b5cf6, 6, 10);
pointLight2.position.set(-2, 1, 2);
this.scene.add(pointLight2);
const pointLight3 = new THREE.PointLight(0x06b6d4, 4, 10);
pointLight3.position.set(2, -1, 2);
this.scene.add(pointLight3);
// Icosahedron geometry is non-indexed (faceted normals). Dropping normal/uv and
// merging vertices gives a shared-vertex mesh, so computeVertexNormals() is smooth.
let geometry: THREE.BufferGeometry = new THREE.IcosahedronGeometry(1, ORB_DETAIL);
geometry.deleteAttribute('normal');
geometry.deleteAttribute('uv');
geometry = mergeVertices(geometry, 1e-4);
geometry.computeVertexNormals();
this.orbGeometry = geometry;
this.originalPositions = new Float32Array(geometry.attributes['position'].array);
const orbMaterial = new THREE.MeshPhysicalMaterial({
color: 0x60a5fa,
emissive: 0x1e3a5f,
emissiveIntensity: 0.35,
roughness: 0.12,
metalness: 0.05,
clearcoat: 1,
clearcoatRoughness: 0.08,
});
this.orbMaterial = orbMaterial;
this.orb = new THREE.Mesh(geometry, orbMaterial);
this.scene.add(this.orb);
const glowMaterial = new THREE.MeshBasicMaterial({
color: 0x3b82f6,
transparent: true,
opacity: 0.07,
blending: THREE.AdditiveBlending,
side: THREE.BackSide,
depthWrite: false,
});
this.glowShell = new THREE.Mesh(new THREE.IcosahedronGeometry(1.18, 16), glowMaterial);
this.scene.add(this.glowShell);
this.observeResize(container);
this.renderer.render(this.scene, this.camera); // first frame, even before animation starts
return true;
}
resize(container: HTMLElement): void {
if (!this.renderer || !this.camera) return;
const width = container.clientWidth || FALLBACK_SIZE;
const height = container.clientHeight || FALLBACK_SIZE;
this.renderer.setSize(width, height, false);
this.camera.aspect = width / height;
this.camera.updateProjectionMatrix();
}
// ---- animation loop -------------------------------------------------------
startAnimation(): void {
if (this.animationId !== null || !this.renderer) return;
// The loop runs outside Angular so 60 frames/s never trigger change detection.
this.ngZone.runOutsideAngular(() => {
const animate = (): void => {
this.animationId = requestAnimationFrame(animate);
this.renderFrame();
};
animate();
});
}
stopAnimation(): void {
if (this.animationId !== null) {
cancelAnimationFrame(this.animationId);
this.animationId = null;
}
}
resetOrbGeometry(): void {
if (!this.orbGeometry || !this.originalPositions) return;
const positions = this.orbGeometry.attributes['position'];
positions.array.set(this.originalPositions);
positions.needsUpdate = true;
this.orbGeometry.computeVertexNormals();
this.smoothedLevel = 0;
}
// ---- audio ----------------------------------------------------------------
/** Starts analysing the stream. The stream stays owned (and stopped) by the caller. */
attachStream(stream: MediaStream): void {
this.detachAudio();
try {
this.audioContext = new AudioContext();
void this.audioContext.resume().catch(() => undefined);
this.sourceNode = this.audioContext.createMediaStreamSource(stream);
this.analyser = this.audioContext.createAnalyser();
this.analyser.fftSize = 256;
this.analyser.smoothingTimeConstant = 0.75;
this.sourceNode.connect(this.analyser);
this.audioData = new Uint8Array(this.analyser.frequencyBinCount);
} catch (err) {
// The orb keeps animating from time alone.
console.warn('VoiceOrbService: audio analysis unavailable.', err);
this.detachAudio();
}
}
/** Stops audio-reactive processing (does not stop the MediaStream tracks). */
detachAudio(): void {
this.sourceNode?.disconnect();
this.sourceNode = null;
this.analyser = null;
this.audioData = null;
this.smoothedLevel = 0;
if (this.audioContext && this.audioContext.state !== 'closed') {
this.audioContext.close().catch(() => undefined);
}
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 {
this.stopAnimation();
this.detachAudio();
this.resizeObserver?.disconnect();
this.resizeObserver = null;
[this.orb, this.glowShell].forEach((mesh) => {
if (!mesh) return;
mesh.geometry.dispose();
(Array.isArray(mesh.material) ? mesh.material : [mesh.material]).forEach((m) => m.dispose());
});
this.scene?.clear();
if (this.renderer) {
const canvas = this.renderer.domElement;
this.renderer.dispose();
canvas.parentNode?.removeChild(canvas);
}
this.scene = null;
this.camera = null;
this.renderer = null;
this.orb = null;
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 ------------------------------------------------------------
private observeResize(container: HTMLElement): void {
if (typeof ResizeObserver === 'undefined') return;
this.resizeObserver?.disconnect();
this.resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
const { width, height } = entry.contentRect;
if (width > 0 && height > 0 && this.renderer && this.camera) {
this.renderer.setSize(width, height, false);
this.camera.aspect = width / height;
this.camera.updateProjectionMatrix();
}
}
});
this.resizeObserver.observe(container);
}
private renderFrame(): void {
if (!this.scene || !this.camera || !this.renderer || !this.orb) return;
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);
if (this.glowShell) {
this.glowShell.scale.setScalar(1 + Math.sin(t * 1.5) * 0.025 + level * 0.06);
if (this.glowShell.material instanceof THREE.MeshBasicMaterial) {
this.glowShell.material.opacity = 0.05 + level * 0.18;
}
}
this.orb.scale.setScalar(1 + Math.sin(t * 2) * 0.018 + level * 0.07);
this.orb.rotation.y = t * 0.08;
this.orb.rotation.x = Math.sin(t * 0.15) * 0.1;
this.renderer.render(this.scene, this.camera);
}
private updateOrbGeometry(time: number, level: number): void {
if (!this.orbGeometry || !this.originalPositions) return;
const positions = this.orbGeometry.attributes['position'];
const original = this.originalPositions;
const amplitude = (this.reducedMotion ? 0.4 : 1) * (1 + level * 2.2);
const swell = level * 0.08;
for (let i = 0; i < positions.count; i++) {
const ox = original[i * 3];
const oy = original[i * 3 + 1];
const oz = original[i * 3 + 2];
const n1 =
Math.sin(ox * 3 + time * 1.2) * Math.cos(oy * 3 + time * 0.8) * Math.sin(oz * 3 + time * 1.5) * 0.06;
const n2 =
Math.sin(ox * 6 + time * 2.3) * Math.cos(oy * 6 + time * 1.7) * Math.sin(oz * 6 + time * 2.1) * 0.02;
const n3 = Math.cos(ox * 2 + time * 0.6) * Math.sin(oy * 2 + time * 1.1) * 0.015;
const k = 1 + (n1 + n2 + n3) * amplitude + swell;
positions.setXYZ(i, ox * k, oy * k, oz * k);
}
positions.needsUpdate = true;
this.orbGeometry.computeVertexNormals();
}
/** Fast attack, slow release: loud sounds are visible immediately but never jitter. */
private updateAudioLevel(): number {
const target = this.readAudioLevel();
const smoothing = target > this.smoothedLevel ? 0.35 : 0.08;
this.smoothedLevel += (target - this.smoothedLevel) * smoothing;
return this.smoothedLevel;
}
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);
// Voice band only (roughly 200 Hz – 9 kHz at 48 kHz sample rate).
const end = Math.min(48, this.audioData.length);
let sum = 0;
for (let i = 1; i < end; i++) sum += this.audioData[i];
const average = sum / (end - 1);
const gain = this.reducedMotion ? 0.5 : 1;
return Math.min(1, Math.max(0, (average - 8) / 110)) * gain;
}
}
@@ -0,0 +1,381 @@
import { describe, it, expect, vi } from 'vitest';
/**
* Loads the REAL public/assets/worklets/pcm-playback.worklet.js in a stubbed AudioWorklet
* global scope (no browser, no node builtins) and returns a processor instance. The worklet
* references the ambient `sampleRate`, `AudioWorkletProcessor` and `registerProcessor`
* globals; we inject them on `globalThis` before importing the module, then vary
* `globalThis.sampleRate` per instance to exercise every context rate deterministically
* (the class reads `sampleRate` at call time, not at module-eval time).
*/
interface Proc {
out: Array<{ type: string; audioRef?: string; playedMs?: number; consumedSamples?: number; discardedSamples?: number; contextRate?: number }>;
port: { onmessage: (e: { data: unknown }) => void };
count: number;
capacity: number;
queuedSource: number;
sourceCapacity: number;
refPlayedOut: Map<string, number>;
process: (inputs: unknown[][][], outputs: Float32Array[][]) => boolean;
}
class FakeAudioWorkletProcessor {
out: Array<{ type: string; audioRef?: string; playedMs?: number; consumedSamples?: number; discardedSamples?: number; contextRate?: number }> = [];
port: {
onmessage: ((e: { data: unknown }) => void) | null;
postMessage: (m: { type: string; audioRef?: string; playedMs?: number; consumedSamples?: number; discardedSamples?: number; contextRate?: number }) => void;
};
constructor() {
this.port = { onmessage: null, postMessage: (m) => this.out.push(m) };
}
}
let Registered: (new () => Proc) | null = null;
const ensureRegistered = async (): Promise<new () => Proc> => {
if (Registered) return Registered;
const g = globalThis as unknown as Record<string, unknown>;
g['AudioWorkletProcessor'] = FakeAudioWorkletProcessor;
g['registerProcessor'] = (_name: string, cls: new () => Proc) => {
Registered = cls;
};
// The worklet is plain JS with Web Audio ambient globals; silence the missing ambient types.
// @ts-expect-error - worklet has no type declarations
await import('../../../../public/assets/worklets/pcm-playback.worklet.js');
if (!Registered) throw new Error('worklet did not register a processor');
return Registered;
};
async function loadPlaybackProcessor(contextRate: number): Promise<Proc> {
const ctor = await ensureRegistered();
(globalThis as unknown as { sampleRate: number }).sampleRate = contextRate;
return new ctor();
}
/** A frame of 24 kHz wire PCM with a non-trivial ramp signal. */
function frame(sampleOffset: number, samples = 2400): Int16Array {
const pcm = new Int16Array(samples);
for (let i = 0; i < samples; i++) pcm[i] = ((sampleOffset + i) % 1000) - 500;
return pcm;
}
function push(proc: Proc, pcm: Int16Array, audioRef: string | null): void {
// The engine transfers the buffer; the worklet re-wraps it. Copy so the frame is reusable.
const copy = pcm.slice().buffer;
proc.port.onmessage({ data: { type: 'push', pcm: copy, sampleRate: 24000, audioRef } });
}
function clear(proc: Proc): void {
proc.port.onmessage({ data: { type: 'clear' } });
}
function flush(proc: Proc): void {
proc.port.onmessage({ data: { type: 'flush' } });
}
/** One render quantum: emit `samples` output slots and let process() consume/emit. */
function render(proc: Proc, samples = 128): void {
proc.process([[]], [[new Float32Array(samples)]]);
}
/** Drain everything currently queued (bounded, so a bug cannot hang the test). */
function drain(proc: Proc, quantum = 1024): void {
let renders = 0;
while (proc.count > 0 && renders < 100000) {
render(proc, quantum);
renders++;
}
}
const overflowCount = (proc: Proc): number => proc.out.filter((m) => m.type === 'overflow').length;
const idleCount = (proc: Proc): number => proc.out.filter((m) => m.type === 'idle').length;
const playedFor = (proc: Proc, ref: string): number =>
Math.max(0, ...proc.out.filter((m) => m.audioRef === ref).map((m) => m.playedMs ?? 0));
describe('pcm-playback.worklet', () => {
describe('bounded queue is rate-invariant (source units)', () => {
// 12 × 2400 source samples = 57,600 source bytes < the 96,000-byte bound: never overflow,
// whatever the context rate is. This is the exact reproduction that used to overflow at 48k.
for (const rate of [24000, 44100, 48000]) {
it(`admits 57,600 source bytes without overflow at a ${rate} Hz context`, async () => {
const proc = await loadPlaybackProcessor(rate);
for (let c = 0; c < 12; c++) push(proc, frame(c * 2400), 'aud-1');
expect(overflowCount(proc)).toBe(0);
expect(proc.queuedSource).toBe(12 * 2400); // 28,800 source samples admitted
expect(proc.queuedSource).toBeLessThanOrEqual(proc.sourceCapacity);
expect(proc.count).toBeLessThanOrEqual(proc.capacity); // never exceeds the ring
});
}
// At any context rate the SAME 96,000 source bytes (48,000 samples) fit, and the next
// source sample overflows — the bound is on SOURCE PCM, so it must not depend on rate.
for (const rate of [24000, 48000]) {
it(`overflows only past the 96,000-byte source bound at ${rate} Hz`, async () => {
const proc = await loadPlaybackProcessor(rate);
for (let c = 0; c < 20; c++) {
push(proc, frame(c * 2400), 'aud-1');
expect(proc.count).toBeLessThanOrEqual(proc.capacity);
}
expect(proc.queuedSource).toBe(20 * 2400); // exactly 48,000 source samples
expect(overflowCount(proc)).toBe(0);
push(proc, frame(20 * 2400), 'aud-1'); // one source sample past the bound
expect(overflowCount(proc)).toBe(1);
expect(proc.count).toBeLessThanOrEqual(proc.capacity); // ring never overwritten
});
}
});
it('posts exactly one overflow under sustained overload (genuine overload fails safely)', async () => {
const proc = await loadPlaybackProcessor(48000);
for (let c = 0; c < 50; c++) push(proc, frame(c * 2400), 'aud-1');
expect(overflowCount(proc)).toBe(1); // not one per rejected chunk
});
it('keeps queue and outstanding source bounded under continuous enqueue + consumption', async () => {
const proc = await loadPlaybackProcessor(48000);
let peakCount = 0;
let peakSource = 0;
// Model real time: push 20 ms frames (480 source samples) and consume ~2× that in output,
// so consumption outpaces production and the queue must stay near-empty (no overflow).
for (let turn = 0; turn < 300; turn++) {
push(proc, frame(turn * 480, 480), `aud-${turn % 3}`);
for (let i = 0; i < 4; i++) render(proc, 256); // 1024 output slots consumed
peakCount = Math.max(peakCount, proc.count);
peakSource = Math.max(peakSource, proc.queuedSource);
expect(proc.count).toBeLessThanOrEqual(proc.capacity);
}
expect(overflowCount(proc)).toBe(0);
expect(peakCount).toBeLessThanOrEqual(proc.capacity);
expect(peakSource).toBeLessThan(proc.sourceCapacity);
});
it.each([24000, 44100, 48000])('reports actual consumed samples at %i Hz without crediting a discarded tail', async (rate) => {
const proc = await loadPlaybackProcessor(rate);
push(proc, frame(0, 4800), 'aud-counted');
render(proc, 128);
clear(proc);
const reports = proc.out.filter((m) => m.type === 'progress');
expect(reports.length).toBeGreaterThan(0);
const final = reports.at(-1)!;
expect(final.contextRate).toBe(rate);
expect(final.consumedSamples).toBe(128);
expect(final.playedMs).toBe(Math.floor(128 * 1000 / rate));
expect(final.consumedSamples!).toBeLessThan(4800 * rate / 24000);
const discarded = proc.out.find((m) => m.type === 'discarded')!;
expect(discarded.discardedSamples! + final.consumedSamples!).toBe(Math.round(4800 * rate / 24000));
});
describe('exact consumed-sample progress', () => {
it('plays the 364800-byte incident fully before generation ends at 24 kHz', async () => {
const proc = await loadPlaybackProcessor(24000);
for (let chunk = 0; chunk < 38; chunk++) {
push(proc, frame(chunk * 4800, 4800), 'aud-incident');
drain(proc, 128);
}
// No audio_ended/flush: every native-rate sample can already be rendered.
expect(proc.refPlayedOut.get('aud-incident')).toBe(182400);
expect(playedFor(proc, 'aud-incident')).toBe(7600);
expect(proc.count).toBe(0);
expect(overflowCount(proc)).toBe(0);
});
it('renders native-rate PCM directly without an inserted leading sample', async () => {
const proc = await loadPlaybackProcessor(24000);
const pcm = frame(200, 4800);
push(proc, pcm, 'aud-1');
const output = new Float32Array(128);
proc.process([[]], [[output]]);
expect(Array.from(output)).toEqual(Array.from(pcm.slice(0, 128), (v) => v / 32768));
expect(proc.refPlayedOut.get('aud-1')).toBe(128);
});
for (const rate of [24000, 48000]) {
it(`reports 1001 ms after rendering every sample at ${rate} Hz`, async () => {
const proc = await loadPlaybackProcessor(rate);
push(proc, frame(0, 24024), 'aud-1');
flush(proc);
drain(proc);
expect(proc.refPlayedOut.get('aud-1')).toBe((rate * 1001) / 1000);
expect(playedFor(proc, 'aud-1')).toBe(1001);
const values = proc.out
.filter((m) => m.type === 'progress' && m.audioRef === 'aud-1')
.map((m) => m.playedMs ?? 0);
expect(values).toEqual([...values].sort((a, b) => a - b));
expect(values.every((ms) => ms <= 1001)).toBe(true);
});
}
});
describe('fractional resampling across chunk boundaries', () => {
// 6,000 source samples = 250 ms at 24 kHz. A linear resampler carries ~1 sample of latency
// across a boundary, so reported progress is within 1 ms of 250 — but it must never
// OVER-claim (>250) and must not depend on where the chunk boundary falls.
for (const rate of [24000, 44100, 48000]) {
it(`reports the same ~250 ms whether split or whole at ${rate} Hz`, async () => {
const oneChunk = await loadPlaybackProcessor(rate);
push(oneChunk, frame(0, 6000), 'aud-1');
drain(oneChunk);
const singleFinal = playedFor(oneChunk, 'aud-1');
const twoChunks = await loadPlaybackProcessor(rate);
push(twoChunks, frame(0, 3000), 'aud-1');
push(twoChunks, frame(3000, 3000), 'aud-1');
drain(twoChunks);
const splitFinal = playedFor(twoChunks, 'aud-1');
expect(singleFinal).toBeGreaterThanOrEqual(249);
expect(singleFinal).toBeLessThanOrEqual(250); // never claim an unheard millisecond
expect(splitFinal).toBeGreaterThanOrEqual(249);
expect(splitFinal).toBeLessThanOrEqual(250);
expect(Math.abs(singleFinal - splitFinal)).toBeLessThanOrEqual(1); // boundary is seamless
});
}
});
describe('end-of-turn draining (regression for premature session termination)', () => {
// The exact incident: 24,000 source samples at 24 kHz = 1000 ms. The resampler must emit
// all 24,000 outputs (main loop defers the final sample; flush() emits the tail) so fully
// drained playback reports exactly 1000 ms and leaves no phantom queued source sample.
it('drains 24,000 source samples at 24 kHz to exactly 1000 ms with no phantom', async () => {
const proc = await loadPlaybackProcessor(24000);
push(proc, frame(0, 24000), 'aud-1');
flush(proc); // audio_ended
drain(proc);
expect(playedFor(proc, 'aud-1')).toBe(1000);
expect(proc.queuedSource).toBe(0); // fully played audio must not retain a phantom sample
expect(proc.refPlayedOut.get('aud-1') ?? 0).toBeCloseTo(24000, 3);
});
it('emits a one-sample tail: a single source sample at 24 kHz reports 0 ms but drains clean', async () => {
const proc = await loadPlaybackProcessor(24000);
push(proc, frame(0, 1), 'aud-1');
flush(proc);
drain(proc);
expect(proc.queuedSource).toBe(0);
// 1 sample = 0.0417 ms → floor is 0, so playedFor is 0, but the sample is not stuck.
expect(playedFor(proc, 'aud-1')).toBe(0);
expect(overflowCount(proc)).toBe(0);
});
// 2,000 source samples at 24 kHz = 83.33 ms → must report 83 ms (floor), not 84, and drain.
it('reports non-integer-millisecond durations by flooring, never rounding up', async () => {
const proc = await loadPlaybackProcessor(24000);
push(proc, frame(0, 2000), 'aud-1');
flush(proc);
drain(proc);
expect(proc.queuedSource).toBe(0);
expect(playedFor(proc, 'aud-1')).toBe(83); // floor(2000/24000*1000) = 83, not 84
});
// Even 44.1k/48k contexts must retire the full source on flush (the backend breaks are
// computed from played source bytes, so a missing tail would look like a perpetual stall).
for (const rate of [44100, 48000]) {
it(`retires all source with no phantom at a ${rate} Hz context`, async () => {
const proc = await loadPlaybackProcessor(rate);
push(proc, frame(0, 24000), 'aud-1');
flush(proc);
drain(proc);
expect(proc.queuedSource).toBe(0);
// 24,000 source samples = 1000 ms regardless of the context/output rate.
expect(playedFor(proc, 'aud-1')).toBe(1000);
});
}
it('drains a final chunk smaller than the prebuffer threshold', async () => {
const proc = await loadPlaybackProcessor(24000); // prebuffer = 1920 output samples
// Two chunks: a large one that starts playback, then a tiny trailing chunk (< prebuffer)
// that must still be flushed out instead of being stuck below the prebuffer gate.
push(proc, frame(0, 4800), 'aud-1');
render(proc, 128); // started
push(proc, frame(4800, 400), 'aud-1'); // 400 samples < prebuffer
flush(proc);
drain(proc);
expect(proc.queuedSource).toBe(0);
// 5200 source samples = 216.66 ms → 216 ms.
expect(playedFor(proc, 'aud-1')).toBe(216);
});
it('credits a new ref its own audio even when it arrives while the prior ref still queued', async () => {
const proc = await loadPlaybackProcessor(24000);
push(proc, frame(0, 4800), 'aud-a'); // 200 ms
flush(proc); // aud-a generation ended → its tail is emitted
push(proc, frame(0, 24000), 'aud-b'); // arrives; aud-a still draining
flush(proc);
drain(proc);
expect(proc.queuedSource).toBe(0);
expect(playedFor(proc, 'aud-a')).toBe(200);
expect(playedFor(proc, 'aud-b')).toBe(1000);
});
});
describe('progress is accurate, monotonic and per audio_ref', () => {
it('credits each queued ref its own consumed source (never the next ref)', async () => {
const proc = await loadPlaybackProcessor(24000); // ratio 1 → 3,000 source ≈ 125 ms
push(proc, frame(0, 3000), 'aud-a');
push(proc, frame(3000, 3000), 'aud-b'); // arrives while 'aud-a' is still queued
// Consume only the first half: it must all be credited to 'aud-a', never 'aud-b'.
render(proc, 1024);
render(proc, 1024);
expect(proc.out.filter((m) => m.audioRef === 'aud-b')).toHaveLength(0); // not heard yet
const aValues = proc.out.filter((m) => m.audioRef === 'aud-a').map((m) => m.playedMs ?? 0);
expect(aValues).toEqual([...aValues].sort((x, y) => x - y)); // monotonic
drain(proc);
// Each ref consumed only its own ~3,000 OUTPUT samples (±1 sample of resampler lag),
// never the other ref's samples. The next-ref bug would credit 'aud-b' with 6,000.
expect(Math.abs((proc.refPlayedOut.get('aud-a') ?? 0) - 3000)).toBeLessThanOrEqual(1);
expect(Math.abs((proc.refPlayedOut.get('aud-b') ?? 0) - 3000)).toBeLessThanOrEqual(1);
const finalA = playedFor(proc, 'aud-a');
const finalB = playedFor(proc, 'aud-b');
expect(finalA).toBeGreaterThanOrEqual(124);
expect(finalA).toBeLessThanOrEqual(125);
expect(finalB).toBeLessThanOrEqual(125); // NOT 250: 'aud-a' samples were not credited to 'aud-b'
});
});
it('attributes discarded samples separately when two references share the queue', async () => {
const proc = await loadPlaybackProcessor(24000);
push(proc, frame(0, 3000), 'aud-a');
push(proc, frame(3000, 3000), 'aud-b');
render(proc, 128);
clear(proc);
const discarded = proc.out.filter((m) => m.type === 'discarded');
expect(discarded.find((m) => m.audioRef === 'aud-a')?.discardedSamples).toBe(2872);
expect(discarded.find((m) => m.audioRef === 'aud-b')?.discardedSamples).toBe(3000);
expect(proc.refPlayedOut.get('aud-a')).toBe(128);
expect(proc.refPlayedOut.get('aud-b') ?? 0).toBe(0);
});
describe('interruption and clear', () => {
it('clears the queue and reports only the source actually consumed', async () => {
const proc = await loadPlaybackProcessor(24000);
push(proc, frame(0, 3000), 'aud-a');
render(proc, 128); // started, consumes 128 source samples (~5 ms)
clear(proc);
expect(proc.count).toBe(0);
expect(proc.queuedSource).toBe(0);
// Final progress reflects what was actually heard (~5 ms), not the whole 3,000 queue.
const finals = proc.out.filter((m) => m.type === 'progress' && m.audioRef === 'aud-a');
expect(finals.at(-1)?.playedMs).toBe(5);
expect(proc.refPlayedOut.get('aud-a') ?? 0).toBeCloseTo(128, 5);
// A fresh ref plays normally after the interruption.
push(proc, frame(0, 3000), 'aud-b');
drain(proc);
expect(idleCount(proc)).toBe(1);
expect(playedFor(proc, 'aud-b')).toBeGreaterThanOrEqual(124);
expect(playedFor(proc, 'aud-b')).toBeLessThanOrEqual(125);
});
});
});
@@ -0,0 +1,268 @@
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { firstValueFrom, Observable } from 'rxjs';
import { uuid } from '../../shared/utils/uuid';
import { VOICE_STREAM_CONFIG, VoiceSessionStatus } from './voice-stream.types';
/**
* The voice helper's HTTP deadline: a client timeout never means the server rolled back.
* Generous on purpose — the UI runs against a remote backend through the dev-server proxy,
* and the first call after a reload pays the proxy connection setup.
*/
const REQUEST_DEADLINE_MS = 15000;
/** Error envelope from the contract: { 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 {
revision: number;
assistant_name: string;
instruction: string;
capabilities: {
text: boolean;
voice: boolean;
captions: boolean;
supported_upload_types?: string[];
max_upload_bytes?: number;
max_pdf_pages?: number;
};
}
export interface ConversationResponse {
id: string;
mode: 'voice';
title?: string;
status: string;
access_epoch?: number;
created_at?: string;
}
export interface VoiceSessionResponse {
session_id: string;
conversation_id: string;
status: string;
stream_path: string;
expires_at: string;
poll_url: string;
}
/** V02: status + safe diagnostics for a reserved/connected session. */
export interface VoiceSessionPollResponse extends VoiceSessionStatus {
recent_tool_results?: unknown[];
}
/**
* Thin client for the endpoints the live voice call needs (A03, F01, C01, V01, V02, V03, V04).
* Auth is the HttpOnly `rag_session` cookie (same-origin proxy); state-changing calls also need
* `X-CSRF-Token`. C01/V01 are idempotent through their JSON `client_request_id`, never headers.
*/
@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'), this.readOptions()));
}
/** 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()));
}
/** C01: only `mode: "voice"` exists in the MVP. `clientRequestId` makes replays return the same conversation. */
createConversation(csrf: string, title: string, clientRequestId: string): Promise<ConversationResponse> {
return this.send(
this.http.post<ConversationResponse>(
this.url('/conversations'),
{ client_request_id: clientRequestId, mode: 'voice', title },
this.writeOptions(csrf),
),
);
}
/** V01: reserves a live session; connect the WebSocket to the returned `stream_path`. */
createVoiceSession(
csrf: string,
conversationId: string,
clientRequestId: string,
): Promise<VoiceSessionResponse> {
return this.send(
this.http.post<VoiceSessionResponse>(
this.url('/voice/sessions'),
{ conversation_id: conversationId, client_request_id: clientRequestId },
this.writeOptions(csrf),
),
);
}
/** V02: status + safe diagnostics (no secrets). */
pollVoiceSession(csrf: string, sessionId: string): Promise<VoiceSessionPollResponse> {
return this.send(
this.http.get<VoiceSessionPollResponse>(
this.url(`/voice/sessions/${encodeURIComponent(sessionId)}`),
this.readOptions(),
),
);
}
/**
* V03: reconcile a reservation by its C01/V01 `client_request_id` — used after an
* ambiguous (timeout / network) reserve, or after a reload. Never opens a new provider
* connection: `null` means the attempt was never reserved.
*/
getVoiceSessionByRequest(csrf: string, clientRequestId: string): Promise<VoiceSessionResponse | null> {
return this.send(
this.http
.get<VoiceSessionResponse>(
this.url(`/voice/sessions/by-request/${encodeURIComponent(clientRequestId)}`),
this.readOptions(),
)
.pipe(this.mapNotFoundToNull()),
);
}
/** V04: closes the session explicitly (no body). */
async closeVoiceSession(csrf: string, sessionId: string): Promise<void> {
await this.send(
this.http.post<unknown>(
this.url(`/voice/sessions/${encodeURIComponent(sessionId)}/close`),
{},
this.writeOptions(csrf),
),
);
}
/** `wss://…` URL for a V01 `stream_path` (same origin as the UI). */
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 readOptions() {
return { withCredentials: true, headers: new HttpHeaders({ 'X-Request-ID': uuid() }) };
}
private writeOptions(csrf: string) {
return {
withCredentials: true,
headers: new HttpHeaders({
'X-CSRF-Token': csrf,
'X-Request-ID': uuid(),
}),
};
}
private mapNotFoundToNull<T>() {
return (source: Observable<T>): Observable<T | null> =>
new Observable<T | null>((observer) => {
const sub = source.subscribe({
next: (value) => observer.next(value),
error: (err: unknown) => {
if (err instanceof HttpErrorResponse && err.status === 404) observer.next(null);
else observer.error(err);
observer.complete();
},
complete: () => observer.complete(),
});
return () => sub.unsubscribe();
});
}
private async send<T>(request: Observable<T>): Promise<T> {
try {
return await firstValueFrom(this.withDeadline(request));
} catch (err) {
throw this.toApiError(err);
}
}
/**
* A deadline that never aborts the request.
*
* `race()` is not usable here: when the timer wins, `race` unsubscribes the loser, so the
* HttpClient would abort its XHR. An aborted XHR is reported by the browser as
* "(canceled)" — with no status code at all — which is exactly what was observed for
* `/api/v1/me`. It also makes a reserve ambiguous ("did the server create it?") instead of
* letting it settle, which defeats the V03 reconciliation this flow is built around.
*
* Here the request subscription is deliberately kept alive: the UI still gets the timeout,
* the XHR runs to completion, and a late response is simply discarded.
*/
private withDeadline<T>(request: Observable<T>): Observable<T> {
return new Observable<T>((observer) => {
let settled = false;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
observer.error(new VoiceApiError(0, 'TIMEOUT', 'request-deadline'));
}, REQUEST_DEADLINE_MS);
request.subscribe({
next: (value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
observer.next(value);
},
error: (err: unknown) => {
if (settled) return;
settled = true;
clearTimeout(timer);
observer.error(this.toApiError(err));
},
complete: () => {
if (settled) return;
settled = true;
clearTimeout(timer);
observer.complete();
},
});
// Only the timer is torn down: the in-flight request is left to finish naturally.
return () => clearTimeout(timer);
});
}
private toApiError(err: unknown): VoiceApiError {
if (err instanceof VoiceApiError) return err; // deadline / already-normalized error
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,278 @@
import { Injectable, NgZone, inject, isDevMode } from '@angular/core';
import { MicrophoneError, 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(audioRef?: string | null): void;
/** The microphone track ended unexpectedly. */
onMicEnded(): void;
/**
* Real playback progress for one server `audio_ref`: cumulative milliseconds computed
* from consumed samples (never a timer), reported ~4×/s and finally on interruption/stop.
*/
onPlaybackProgress(audioRef: string, playedMs: number): void;
/** The bounded playback queue filled: the session must fail safely (no silent PCM drop). */
onPlaybackOverflow(): 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 24 kHz frames → (service → transport)
* (transport → service) → PCM16 24 kHz 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();
// Preserve the specific engine error (unsupported vs worklet-failed); only a raw
// failure inside buildGraph is a generic worklet failure.
if (err instanceof MicrophoneError || err instanceof VoiceEngineError) throw err;
throw new VoiceEngineError('worklet-failed');
}
}
private async buildGraph(stream: MediaStream, handlers: VoiceEngineHandlers): Promise<void> {
const cfg = this.config;
// The wire format is fixed at 24 kHz mono PCM16. Request that context rate so the
// native path needs no conversion, but browsers MAY ignore the request — read the real
// `ctx.sampleRate` below and let the worklets resample to/from the wire rate when it
// differs. Never assume the requested rate (SKILLS.md §3.2).
const ctx = new AudioContext({ latencyHint: 'interactive', sampleRate: cfg.outputSampleRate });
this.ctx = ctx;
const startedAt = performance.now();
let captureFrames = 0;
let lastCaptureTrace = startedAt;
ctx.onstatechange = () => {
if (isDevMode()) console.info('Voice audio context state', {
state: ctx.state, contextRate: ctx.sampleRate,
elapsedMs: Math.floor(performance.now() - startedAt),
contextMs: Math.floor(ctx.currentTime * 1000),
});
};
// Explicitly reject an unusable context rate: a 0/NaN/non-finite rate cannot resample
// and must fail safely instead of silently producing no playback.
if (!Number.isFinite(ctx.sampleRate) || ctx.sampleRate < 8000 || ctx.sampleRate > 192000) {
throw new VoiceEngineError('unsupported');
}
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 }>) => {
captureFrames++;
const now = performance.now();
if (isDevMode() && now - lastCaptureTrace >= 1000) {
lastCaptureTrace = now;
console.info('Voice capture clock', {
captureFrames, state: ctx.state,
elapsedMs: Math.floor(now - startedAt),
contextMs: Math.floor(ctx.currentTime * 1000),
});
}
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; audioRef?: string; playedMs?: number; consumedSamples?: number; discardedSamples?: number; contextRate?: number }>,
) => {
switch (event.data?.type) {
case 'idle':
handlers.onPlaybackIdle(event.data.audioRef);
break;
case 'progress':
if (isDevMode()) console.info('Voice worklet consumption', { audioRef: event.data.audioRef, consumedSamples: event.data.consumedSamples, contextRate: event.data.contextRate });
if (event.data.audioRef) {
handlers.onPlaybackProgress(event.data.audioRef, event.data.playedMs ?? 0);
}
break;
case 'discarded':
if (isDevMode()) console.info('Voice worklet discarded samples', { audioRef: event.data.audioRef, discardedSamples: event.data.discardedSamples, contextRate: event.data.contextRate });
break;
case 'overflow':
handlers.onPlaybackOverflow();
break;
}
};
this.playback.onprocessorerror = () => {
console.error('Voice playback processor failed', { state: ctx.state });
};
this.capture.onprocessorerror = () => {
console.error('Voice capture processor failed', { state: ctx.state });
};
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);
this.logPipelineDiagnostics(ctx);
}
/**
* Bounded development diagnostics — one line per session, numbers only. Confirms the
* ACTUAL context rate/state (not the requested one) and that the playback graph is
* connected and running. Never logs audio, transcripts, cookies or credentials.
*/
private logPipelineDiagnostics(ctx: AudioContext): void {
const requested = this.config.outputSampleRate;
const resample = ctx.sampleRate === requested ? 'none' : 'worklet';
console.info(
`VoiceAudioEngine: ctx.sampleRate=${ctx.sampleRate}Hz (requested ${requested}Hz) ` +
`state=${ctx.state} playbackGraph=connected resample=${resample}`,
);
}
// ---- playback --------------------------------------------------------------
/** Queues a PCM16 mono chunk at config.outputSampleRate under its server `audio_ref`. */
enqueuePlayback(chunk: ArrayBuffer, audioRef: string | null): 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, audioRef },
[buffer],
);
}
/** Barge-in: drop all queued audio immediately (final progress is reported by the worklet). */
clearPlayback(): void {
this.playback?.port.postMessage({ type: 'clear' });
}
/** End of turn: play the remaining audio, then report idle. */
flushPlayback(audioRef?: string | null): void {
this.playback?.port.postMessage({ type: 'flush', audioRef });
}
// ---- 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;
this.capture.onprocessorerror = null;
}
if (this.playback) {
this.playback.port.onmessage = null;
this.playback.onprocessorerror = 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,152 @@
import { DOCUMENT } from '@angular/common';
import { Injectable, inject } from '@angular/core';
export type VoiceCueKind = 'ready' | 'end';
const CUE_ASSETS: Record<VoiceCueKind, string> = {
ready: 'assets/audio/voice-ready.wav',
end: 'assets/audio/voice-end.wav',
};
/**
* Plays the short reference cues extracted from the supplied recording.
*
* Unlike the previous synthesized version, this service plays the original
* recorded waveform. Do not add a convolver/reverb to it: the reference cue
* already contains its original tone and tail.
*/
@Injectable({ providedIn: 'root' })
export class VoiceCueService {
private readonly document = inject(DOCUMENT);
private ctx: AudioContext | null = null;
private readonly buffers = new Map<VoiceCueKind, AudioBuffer>();
private readonly pending = new Map<VoiceCueKind, Promise<AudioBuffer | null>>();
private enabled = true;
/** Disable or enable subsequent cues. */
setEnabled(on: boolean): void {
this.enabled = on;
}
/**
* Optional warm-up. Call once when the voice UI/component initializes,
* so fetching and decoding do not delay the first cue.
*/
async preload(): Promise<void> {
if (typeof AudioContext === 'undefined' || typeof fetch === 'undefined') {
return;
}
try {
const ctx = this.ensureContext();
await Promise.all([this.loadBuffer('ready', ctx), this.loadBuffer('end', ctx)]);
} catch {
// Preloading is best-effort; audio must never block the voice UI.
}
}
/** Play the recorded cue when the voice session is ready. */
playReady(): void {
void this.play('ready');
}
/** Play the recorded cue when the voice session ends. */
playEnd(): void {
void this.play('end');
}
private async play(kind: VoiceCueKind): Promise<void> {
if (!this.enabled || typeof AudioContext === 'undefined') {
return;
}
try {
const ctx = this.ensureContext();
// Request resume immediately, before awaiting fetch/decode, to preserve
// browser user activation when the call originates from a user gesture.
const resumePromise =
ctx.state === 'suspended' ? ctx.resume().catch(() => undefined) : Promise.resolve();
const bufferPromise = this.loadBuffer(kind, ctx);
const [buffer] = await Promise.all([bufferPromise, resumePromise]);
if (!buffer || ctx.state !== 'running') {
return;
}
const source = ctx.createBufferSource();
const output = ctx.createGain();
source.buffer = buffer;
output.gain.setValueAtTime(1, ctx.currentTime);
source.connect(output);
output.connect(ctx.destination);
source.onended = () => {
source.disconnect();
output.disconnect();
};
// A tiny scheduling lead avoids starting mid-render quantum.
source.start(ctx.currentTime + 0.01);
} catch {
// A cue is optional; never let audio playback break session handling.
}
}
private ensureContext(): AudioContext {
if (!this.ctx || this.ctx.state === 'closed') {
this.ctx = new AudioContext({ latencyHint: 'interactive' });
// AudioBuffers are decoded against a particular context. Rebuild them
// when that context is recreated.
this.buffers.clear();
this.pending.clear();
}
return this.ctx;
}
private loadBuffer(kind: VoiceCueKind, ctx: AudioContext): Promise<AudioBuffer | null> {
const cached = this.buffers.get(kind);
if (cached) {
return Promise.resolve(cached);
}
const inFlight = this.pending.get(kind);
if (inFlight) {
return inFlight;
}
const assetUrl = new URL(CUE_ASSETS[kind], this.document.baseURI).href;
const promise = fetch(assetUrl, { cache: 'force-cache' })
.then((response) => {
if (!response.ok) {
throw new Error(`Unable to load voice cue: ${response.status}`);
}
return response.arrayBuffer();
})
.then((bytes) => ctx.decodeAudioData(bytes))
.then((buffer) => {
if (this.ctx === ctx) {
this.buffers.set(kind, buffer);
}
return buffer;
})
.catch(() => {
// Let a later call retry if the asset was temporarily unavailable.
if (this.ctx === ctx) {
this.pending.delete(kind);
}
return null;
});
this.pending.set(kind, promise);
return promise;
}
}
@@ -0,0 +1,211 @@
import { describe, expect, it } from 'vitest';
import {
ANSWER_LIMITED_REASONS,
TRANSCRIPT_STATUSES,
VOICE_SERVER_EVENT_TYPES,
isApplicationReference,
parseVoiceServerEvent,
} from './voice-event.validator';
import { VoiceServerEvent } from './voice-stream.types';
const ANSWER_LIMITED: VoiceServerEvent = {
type: 'answer_limited',
turn_ref: 'live-turn-1',
reason: 'output_token_limit',
};
describe('voice-event.validator', () => {
describe('application references', () => {
it('accepts a non-empty bounded string reference', () => {
expect(isApplicationReference('live-turn-1')).toBe(true);
expect(isApplicationReference('a'.repeat(256))).toBe(true);
});
it('rejects missing, empty, wrong-typed or oversized references', () => {
expect(isApplicationReference('')).toBe(false);
expect(isApplicationReference(null)).toBe(false);
expect(isApplicationReference(undefined)).toBe(false);
expect(isApplicationReference(42)).toBe(false);
expect(isApplicationReference({})).toBe(false);
expect(isApplicationReference('a'.repeat(257))).toBe(false);
});
});
describe('answer_limited frames', () => {
it('parses a valid answer_limited frame and reaches the dispatcher shape', () => {
expect(parseVoiceServerEvent(JSON.stringify(ANSWER_LIMITED))).toEqual(ANSWER_LIMITED);
});
it('rejects an unknown reason (exactly output_token_limit is accepted)', () => {
expect(
parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, reason: 'output_length_limit' })),
).toBeNull();
expect(
parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, reason: 'token_limit' })),
).toBeNull();
expect(
parseVoiceServerEvent(JSON.stringify({ type: 'answer_limited', turn_ref: 't1' })),
).toBeNull();
});
it('rejects answer_limited without a valid turn_ref', () => {
expect(parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, turn_ref: '' }))).toBeNull();
expect(parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, turn_ref: 7 }))).toBeNull();
expect(
parseVoiceServerEvent('{"type":"answer_limited","reason":"output_token_limit"}'),
).toBeNull();
});
it('only advertises the contract reason and statuses', () => {
expect(ANSWER_LIMITED_REASONS).toEqual(['output_token_limit']);
expect(TRANSCRIPT_STATUSES).toEqual(['partial', 'completed', 'interrupted', 'limited']);
});
});
describe('transcript frames', () => {
it('accepts a limited assistant transcript', () => {
const frame = {
type: 'transcript',
turn_ref: 't1',
role: 'assistant',
text: 'پاسخ',
status: 'limited',
};
expect(parseVoiceServerEvent(JSON.stringify(frame))).toEqual(frame);
});
it('rejects a limited USER transcript (limited is assistant-only)', () => {
const frame = {
type: 'transcript',
turn_ref: 't1',
role: 'user',
text: 'ادامه بده',
status: 'limited',
};
expect(parseVoiceServerEvent(JSON.stringify(frame))).toBeNull();
});
it('accepts the existing (older backend) transcript statuses for both roles', () => {
for (const status of ['partial', 'completed', 'interrupted'] as const) {
for (const role of ['user', 'assistant'] as const) {
const frame = { type: 'transcript', turn_ref: 't1', role, text: 'متن', status };
expect(parseVoiceServerEvent(JSON.stringify(frame))).toEqual(frame);
}
}
});
it('rejects unknown statuses and malformed transcript fields', () => {
const base = { type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'متن' };
expect(parseVoiceServerEvent(JSON.stringify({ ...base, status: 'capped' }))).toBeNull();
expect(parseVoiceServerEvent(JSON.stringify({ ...base, status: 5 }))).toBeNull();
expect(
parseVoiceServerEvent(JSON.stringify({ ...base, status: 'limited', text: 3 })),
).toBeNull();
expect(
parseVoiceServerEvent(JSON.stringify({ ...base, status: 'limited', role: 'system' })),
).toBeNull();
expect(
parseVoiceServerEvent(JSON.stringify({ ...base, status: 'limited', turn_ref: '' })),
).toBeNull();
});
});
it('accepts bounded audio_ended sent_bytes and rejects malformed counters', () => {
const frame = { type: 'audio_ended', audio_ref: 'aud-1', turn_ref: 'turn-1', sent_bytes: 9600 };
expect(parseVoiceServerEvent(JSON.stringify(frame))).toEqual(frame);
for (const sent_bytes of [-1, 1.5, '9600', Number.MAX_SAFE_INTEGER + 1]) {
expect(parseVoiceServerEvent(JSON.stringify({ ...frame, sent_bytes }))).toBeNull();
}
});
describe('existing events keep passing (older backends)', () => {
it('accepts every known event type with a valid payload', () => {
const frames: VoiceServerEvent[] = [
{
type: 'session_ready',
session_id: 'ses-1',
input_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 },
output_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 },
},
{ type: 'user_speech_started', turn_ref: 'turn-1' },
{ type: 'transcript', turn_ref: 'turn-1', role: 'user', text: 'سلام', status: 'completed' },
{
type: 'sources',
turn_ref: 'turn-1',
sources: [
{ source_ref: 'src-1', document_id: 'doc-1', chunk_id: 'chunk-1', title: 'سند' },
],
},
{ type: 'audio_started', audio_ref: 'aud-1', turn_ref: 'turn-1' },
{ type: 'audio_ended', audio_ref: 'aud-1', turn_ref: 'turn-1' },
{ type: 'turn_interrupted', turn_ref: 'turn-1', cancelled_tool_call_ids: [] },
{
type: 'error',
turn_ref: 'turn-1',
error: { code: 'SEARCH_TIMEOUT', message: 'دیر شد', retryable: true },
},
];
for (const frame of frames) {
expect(parseVoiceServerEvent(JSON.stringify(frame))).toEqual(frame);
}
// The enforced allowlist: every type the transport accepts, and nothing else.
expect(VOICE_SERVER_EVENT_TYPES).toEqual([
'session_ready',
'user_speech_started',
'transcript',
'sources',
'audio_started',
'audio_ended',
'turn_interrupted',
'answer_limited',
'error',
]);
});
it('defaults a missing error retryable flag to false instead of dropping the frame', () => {
const parsed = parseVoiceServerEvent('{"type":"error","error":{"code":"X","message":"y"}}');
expect(parsed).toEqual({
type: 'error',
error: { code: 'X', message: 'y', retryable: false },
});
});
});
describe('allowlist and malformed input', () => {
it('drops unknown event types instead of forwarding them', () => {
expect(parseVoiceServerEvent('{"type":"response.create"}')).toBeNull();
expect(parseVoiceServerEvent('{"type":"continue"}')).toBeNull();
expect(
parseVoiceServerEvent(
'{"type":"answer_limited2","turn_ref":"t1","reason":"output_token_limit"}',
),
).toBeNull();
expect(parseVoiceServerEvent('{"type":42}')).toBeNull();
});
it('drops malformed JSON and non-object payloads', () => {
expect(parseVoiceServerEvent('not json')).toBeNull();
expect(parseVoiceServerEvent('')).toBeNull();
expect(parseVoiceServerEvent('null')).toBeNull();
expect(parseVoiceServerEvent('[]')).toBeNull();
expect(parseVoiceServerEvent('"transcript"')).toBeNull();
});
it('drops frames with a broken audio/session/interruption payload', () => {
expect(parseVoiceServerEvent('{"type":"audio_started"}')).toBeNull();
expect(parseVoiceServerEvent('{"type":"audio_started","audio_ref":""}')).toBeNull();
expect(
parseVoiceServerEvent(
'{"type":"turn_interrupted","turn_ref":"t1","cancelled_tool_call_ids":[1]}',
),
).toBeNull();
expect(
parseVoiceServerEvent(
'{"type":"session_ready","session_id":"s","input_audio":{"encoding":"pcm_s16le","sample_rate":24000,"channels":1}}',
),
).toBeNull();
expect(
parseVoiceServerEvent('{"type":"sources","turn_ref":"t1","sources":"none"}'),
).toBeNull();
});
});
});
@@ -0,0 +1,183 @@
import {
AnswerLimitedReason,
TranscriptStatus,
VoiceServerEvent,
VoiceServerEventType,
} from './voice-stream.types';
/**
* Runtime guards for the JSON frames that arrive on the voice stream.
*
* The transport used to hand every parsed object straight to the service. A frame with
* an unknown `type` then fell through the dispatcher silently, and a frame with a
* broken payload reached a handler that reads its fields. Every JSON frame now passes
* this explicit allowlist first: known types are checked field by field, unknown types
* and malformed payloads are DROPPED — never thrown, never re-interpreted, and never
* able to end a call. Dropping matches how malformed JSON was already treated, so no
* malformed frame can enter an error path or trigger cleanup.
*
* The guards mirror the contract in `VoiceServerEvent`; they do not invent protocol.
*/
export const VOICE_SERVER_EVENT_TYPES = [
'session_ready',
'user_speech_started',
'transcript',
'sources',
'audio_started',
'audio_ended',
'turn_interrupted',
'answer_limited',
'error',
] as const;
export const ANSWER_LIMITED_REASONS = ['output_token_limit'] as const;
export const TRANSCRIPT_STATUSES = ['partial', 'completed', 'interrupted', 'limited'] as const;
/**
* Compile-time alignment between the allowlists above and the wire unions in
* `voice-stream.types.ts`: a union member missing from an allowlist (or an allowlisted
* value with no union member) fails to compile here, so the transport can never
* silently start dropping a valid frame after a contract change.
*/
type Exactly<T extends true> = T;
export type AllowlistsAligned = [
Exactly<VoiceServerEventType extends (typeof VOICE_SERVER_EVENT_TYPES)[number] ? true : false>,
Exactly<(typeof VOICE_SERVER_EVENT_TYPES)[number] extends VoiceServerEventType ? true : false>,
Exactly<TranscriptStatus extends (typeof TRANSCRIPT_STATUSES)[number] ? true : false>,
Exactly<(typeof TRANSCRIPT_STATUSES)[number] extends TranscriptStatus ? true : false>,
Exactly<AnswerLimitedReason extends (typeof ANSWER_LIMITED_REASONS)[number] ? true : false>,
Exactly<(typeof ANSWER_LIMITED_REASONS)[number] extends AnswerLimitedReason ? true : false>,
];
/** Longest application reference accepted on the wire (session/turn/audio ids). */
const MAX_REFERENCE_LENGTH = 256;
/**
* An application reference issued by the backend (`session_id`, `turn_ref`, `audio_ref`,
* `source_ref`, …): a non-empty, length-bounded string. Anything else (number, null,
* empty string, oversized string) is not a reference and cannot correlate a frame.
*/
export function isApplicationReference(value: unknown): value is string {
return typeof value === 'string' && value.length > 0 && value.length <= MAX_REFERENCE_LENGTH;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isAudioFormat(value: unknown): boolean {
return (
isRecord(value) &&
typeof value['encoding'] === 'string' &&
typeof value['sample_rate'] === 'number' &&
typeof value['channels'] === 'number'
);
}
/** Only the fields the client actually reads are required; presentation is tolerant. */
function isVoiceSource(value: unknown): boolean {
return (
isRecord(value) &&
isApplicationReference(value['source_ref']) &&
isApplicationReference(value['chunk_id'])
);
}
function isVoiceServerEvent(value: unknown): value is VoiceServerEvent {
if (!isRecord(value)) return false;
// Allowlist: an unknown event type is dropped, never forwarded.
if (!VOICE_SERVER_EVENT_TYPES.includes(value['type'] as VoiceServerEventType)) return false;
switch (value['type']) {
case 'session_ready':
return (
isApplicationReference(value['session_id']) &&
isAudioFormat(value['input_audio']) &&
isAudioFormat(value['output_audio'])
);
case 'user_speech_started':
return isApplicationReference(value['turn_ref']);
case 'transcript':
return (
isApplicationReference(value['turn_ref']) &&
(value['role'] === 'user' || value['role'] === 'assistant') &&
typeof value['text'] === 'string' &&
TRANSCRIPT_STATUSES.includes(value['status'] as TranscriptStatus) &&
// `limited` is valid only for assistant transcripts.
(value['status'] !== 'limited' || value['role'] === 'assistant')
);
case 'sources':
return (
isApplicationReference(value['turn_ref']) &&
Array.isArray(value['sources']) &&
value['sources'].every(isVoiceSource)
);
case 'audio_started':
case 'audio_ended':
return (
isApplicationReference(value['audio_ref']) &&
(value['turn_ref'] === undefined || isApplicationReference(value['turn_ref'])) &&
(value['type'] !== 'audio_ended' ||
value['sent_bytes'] === undefined ||
(Number.isSafeInteger(value['sent_bytes']) && (value['sent_bytes'] as number) >= 0))
);
case 'turn_interrupted':
return (
isApplicationReference(value['turn_ref']) &&
(value['cancelled_tool_call_ids'] === undefined ||
(Array.isArray(value['cancelled_tool_call_ids']) &&
value['cancelled_tool_call_ids'].every(isApplicationReference)))
);
case 'answer_limited':
return (
isApplicationReference(value['turn_ref']) &&
ANSWER_LIMITED_REASONS.includes(value['reason'] as AnswerLimitedReason)
);
case 'error':
return (
isRecord(value['error']) &&
typeof value['error']['code'] === 'string' &&
typeof value['error']['message'] === 'string' &&
(value['error']['retryable'] === undefined ||
typeof value['error']['retryable'] === 'boolean') &&
(value['turn_ref'] === undefined || isApplicationReference(value['turn_ref'])) &&
(value['audio_ref'] === undefined || isApplicationReference(value['audio_ref']))
);
default:
// Defense in depth: unreachable while the allowlist above matches this switch,
// and it keeps a newly modeled-but-unhandled type from reaching the service.
return false;
}
}
/**
* Parse one JSON control frame from the wire.
*
* Returns the validated event, or `null` when the frame is malformed JSON, an unknown
* event type, or a known type with an invalid payload. A `null` result is dropped by
* the transport exactly like malformed JSON always was — it is not an error state.
*/
export function parseVoiceServerEvent(raw: string): VoiceServerEvent | null {
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
return null;
}
if (!isVoiceServerEvent(parsed)) return null;
if (parsed.type === 'error' && parsed.error.retryable === undefined) {
// A frame without the flag behaves like a non-retryable error, which is what the
// service's boolean read produced before validation existed.
return { ...parsed, error: { ...parsed.error, retryable: false } };
}
return parsed;
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,177 @@
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: docs/backend-api-docs/frontend-backend-connection-handoff.md (§7–§9)
// Audio is raw mono signed PCM16 little-endian at 24000 Hz in BOTH directions
// (no WAV header). The session id, stream path and refs always come from the server.
// ---------------------------------------------------------------------------
export interface VoiceSource {
source_ref: string;
document_id: string;
chunk_id: string;
title: string;
excerpt?: string;
/**
* Where the chunk lives in its document. `page` is `null` when the backend cannot
* attribute a page (it serializes the absence as JSON `null`, not as an omission).
*/
location?: { page?: number | null; section?: string } | null;
/** `false` = the excerpt is no longer valid and must be hidden, not kept on screen. */
available?: boolean;
}
export interface VoiceAudioFormat {
encoding: string;
sample_rate: number;
channels: number;
}
export type TranscriptStatus = 'partial' | 'completed' | 'interrupted' | 'limited';
/**
* Why an assistant answer was marked limited. The backend applies a conservative
* output-token budget (tool calls included); reaching it ends the GENERATION of the
* answer, not the session and not the playback of the audio already produced.
*/
export type AnswerLimitedReason = 'output_token_limit';
export type VoiceServerEvent =
| {
type: 'session_ready';
session_id: string;
input_audio: VoiceAudioFormat;
output_audio: VoiceAudioFormat;
}
| {
type: 'user_speech_started';
turn_ref: string;
}
| {
type: 'transcript';
turn_ref: string;
role: 'user' | 'assistant';
/**
* `partial` is a delta (append it); `completed` and `limited` are final
* snapshots (they replace the accumulated text). See
* `VoiceStreamService.mergeTranscriptText`.
*/
text: string;
status: TranscriptStatus;
}
| { type: 'sources'; turn_ref: string; tool_call_id?: string; sources: VoiceSource[] }
| { type: 'audio_started'; audio_ref: string; turn_ref?: string }
| { type: 'audio_ended'; audio_ref: string; turn_ref?: string; sent_bytes?: number }
| { type: 'turn_interrupted'; turn_ref: string; cancelled_tool_call_ids?: string[] }
/**
* The assistant answer hit the backend's output-token limit. This is an ANSWER
* state, not an error and not a session-lifecycle event: it does not stop or seal
* audio playback, does not close the session or the microphone, and does not ask
* for an automatic continuation — a genuine new user turn is required for more.
*/
| { type: 'answer_limited'; turn_ref: string; reason: AnswerLimitedReason }
| {
type: 'error';
turn_ref?: string;
audio_ref?: string;
error: { code: string; message: string; request_id?: string; retryable: boolean };
};
/** Every `type` discriminator of `VoiceServerEvent`. */
export type VoiceServerEventType = VoiceServerEvent['type'];
/**
* The only client→server JSON control message. `played_ms` is the cumulative real
* playback time of `audio_ref` (computed from samples actually consumed by the
* playback worklet — never an elapsed timer), and is sent again as the final
* interruption/stop report.
*/
export interface PlaybackProgressMessage {
type: 'playback_progress';
audio_ref: string;
played_ms: number;
}
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;
/**
* Assistant answer the server capped (output-token limit). The session and the
* playback of the produced audio stay usable; only the answer is limited.
*/
limited?: 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;
/**
* Machine-readable cause for logs/diagnostics, e.g. `ws close 1006 reason="…"`.
* The server's close code/reason says why the socket died; without it the only
* thing surfaced is a generic "disconnected" banner and the root cause is invisible.
*/
detail?: string;
}
/** V02/V03 polling shape (safe diagnostics only). */
export interface VoiceSessionStatus {
session_id: string;
status: string;
close_reason?: string | null;
expires_at?: 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: 24 kHz up and 24 kHz down, mono PCM16LE. */
inputSampleRate: number;
outputSampleRate: number;
frameMs: number;
connectTimeoutMs: number;
/** Fallback only for a limited response with no audio reference. */
settleMs: number;
/** Folder (relative to <base href>) holding the two *.worklet.js files, served from the UI origin. */
workletBasePath: string;
}
export const DEFAULT_VOICE_STREAM_CONFIG: VoiceStreamConfig = {
apiBase: '/api/v1',
apiOrigin: '',
inputSampleRate: 24000,
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,177 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { WebSocketVoiceTransport } from './voice-transport';
import { VoiceServerEvent } from './voice-stream.types';
/**
* Minimal fake WebSocket: captures the handlers the transport installs and lets the test
* deliver string control frames / binary audio frames exactly like a server would.
*/
class FakeWebSocket {
static readonly CONNECTING = 0;
static readonly OPEN = 1;
static readonly CLOSING = 2;
static readonly CLOSED = 3;
static instances: FakeWebSocket[] = [];
readyState = FakeWebSocket.OPEN;
binaryType: 'blob' | 'arraybuffer' = 'blob';
sent: unknown[] = [];
onopen: (() => void) | null = null;
onmessage: ((event: { data: unknown }) => void) | null = null;
onerror: (() => void) | null = null;
onclose: ((event: { code: number; reason: string; wasClean: boolean }) => void) | null = null;
constructor(public readonly url: string) {
FakeWebSocket.instances.push(this);
}
send(data: unknown): void {
this.sent.push(data);
}
close(): void {
this.readyState = FakeWebSocket.CLOSED;
}
// ---- test helpers ---------------------------------------------------------
/** The transport attaches its handlers inside connect(); simulate the open handshake. */
static async connectTransport(transport: WebSocketVoiceTransport): Promise<FakeWebSocket> {
const connected = transport.connect({
onEvent: vi.fn(),
onAudio: vi.fn(),
onClose: vi.fn(),
onOverflow: vi.fn(),
});
const ws = FakeWebSocket.instances.at(-1)!;
ws.onopen?.();
await connected;
return ws;
}
deliverText(payload: string): void {
this.onmessage?.({ data: payload });
}
deliverJson(payload: unknown): void {
this.deliverText(JSON.stringify(payload));
}
deliverAudio(bytes: ArrayBuffer): void {
this.onmessage?.({ data: bytes });
}
}
describe('WebSocketVoiceTransport (JSON frame parsing)', () => {
beforeEach(() => {
FakeWebSocket.instances = [];
vi.stubGlobal('WebSocket', FakeWebSocket);
});
const ANSWER_LIMITED_FRAME = {
type: 'answer_limited',
turn_ref: 'live-turn-1',
reason: 'output_token_limit',
};
it('parses a valid answer_limited frame and forwards it to the handlers', async () => {
const events: VoiceServerEvent[] = [];
const transport = new WebSocketVoiceTransport('wss://ui.local/stream', 1000);
const connected = transport.connect({
onEvent: (event) => events.push(event),
onAudio: vi.fn(),
onClose: vi.fn(),
onOverflow: vi.fn(),
});
const ws = FakeWebSocket.instances.at(-1)!;
ws.onopen?.();
await connected;
ws.deliverJson(ANSWER_LIMITED_FRAME);
expect(events).toEqual([ANSWER_LIMITED_FRAME]);
});
it('keeps forwarding the existing event types (older backends unaffected)', async () => {
const events: VoiceServerEvent[] = [];
const transport = new WebSocketVoiceTransport('wss://ui.local/stream', 1000);
const connected = transport.connect({
onEvent: (event) => events.push(event),
onAudio: vi.fn(),
onClose: vi.fn(),
onOverflow: vi.fn(),
});
const ws = FakeWebSocket.instances.at(-1)!;
ws.onopen?.();
await connected;
ws.deliverJson({ type: 'user_speech_started', turn_ref: 'live-turn-2' });
ws.deliverJson({ type: 'audio_started', audio_ref: 'live-audio-1' });
ws.deliverJson({
type: 'transcript',
turn_ref: 'live-turn-2',
role: 'assistant',
text: 'سلام',
status: 'partial',
});
expect(events.map((e) => e.type)).toEqual(['user_speech_started', 'audio_started', 'transcript']);
});
it('drops unknown and malformed frames without an error path or cleanup', async () => {
const events: VoiceServerEvent[] = [];
const onClose = vi.fn();
const onOverflow = vi.fn();
const transport = new WebSocketVoiceTransport('wss://ui.local/stream', 1000);
const connected = transport.connect({
onEvent: (event) => events.push(event),
onAudio: vi.fn(),
onClose,
onOverflow,
});
const ws = FakeWebSocket.instances.at(-1)!;
ws.onopen?.();
await connected;
ws.deliverText('not json');
ws.deliverJson({ type: 'response.create' });
ws.deliverJson({ type: 'answer_limited', turn_ref: 'live-turn-1', reason: 'other_limit' });
ws.deliverJson({ type: 'transcript', turn_ref: 't1', role: 'user', text: 'x', status: 'limited' });
ws.deliverJson({ type: 'audio_started', audio_ref: '' });
expect(events).toEqual([]); // nothing entered the service
expect(onClose).not.toHaveBeenCalled();
expect(onOverflow).not.toHaveBeenCalled();
expect(ws.readyState).toBe(FakeWebSocket.OPEN); // socket untouched
});
it('delivers binary audio frames as ArrayBuffers to onAudio', async () => {
const onAudio = vi.fn();
const transport = new WebSocketVoiceTransport('wss://ui.local/stream', 1000);
const connected = transport.connect({
onEvent: vi.fn(),
onAudio,
onClose: vi.fn(),
onOverflow: vi.fn(),
});
const ws = FakeWebSocket.instances.at(-1)!;
ws.onopen?.();
await connected;
const pcm = new ArrayBuffer(9600);
ws.deliverAudio(pcm);
expect(onAudio).toHaveBeenCalledWith(pcm);
});
it('sendControl only emits playback_progress (no fabricated continue/resume command)', async () => {
const transport = new WebSocketVoiceTransport('wss://ui.local/stream', 1000);
const ws = await FakeWebSocket.connectTransport(transport);
transport.sendControl({ type: 'playback_progress', audio_ref: 'live-audio-1', played_ms: 120 });
expect(ws.sent).toEqual([
JSON.stringify({ type: 'playback_progress', audio_ref: 'live-audio-1', played_ms: 120 }),
]);
});
});
@@ -0,0 +1,253 @@
import { InjectionToken, inject } from '@angular/core';
import { PlaybackProgressMessage, VOICE_STREAM_CONFIG, VoiceServerEvent } from './voice-stream.types';
import { parseVoiceServerEvent } from './voice-event.validator';
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;
/**
* A bounded queue filled up (capture send queue or socket backpressure). The call must
* end safely with a failure — silently dropping PCM and continuing is not allowed.
*/
onOverflow(which: 'send'): void;
}
export interface VoiceTransport {
connect(handlers: VoiceTransportHandlers): Promise<void>;
/** PCM16 mono 24 kHz frame, sample-aligned, at most MAX_MESSAGE_BYTES. */
sendAudio(frame: ArrayBuffer): void;
/** The only client→server JSON message (`playback_progress`). */
sendControl(message: PlaybackProgressMessage): void;
close(): void;
}
/** Maximum size of one binary frame on the wire (contract: 9600 bytes, sample-aligned). */
export const MAX_MESSAGE_BYTES = 9600;
/** Bounded capture queue: 96000 bytes / 100 messages. Filled capacity fails the call. */
const MAX_QUEUE_BYTES = 96000;
const MAX_QUEUE_MESSAGES = 100;
/**
* Plain WebSocket. Authentication is the `rag_session` cookie sent automatically on the
* handshake, so the page is served from the same origin as the API (same-origin `/api`
* proxy). The contract has exactly one client→server JSON message: `playback_progress`.
*
* Diagnostics: every control frame received is kept in a short ring buffer and dumped when
* the socket dies, so the server's last message — normally an `error` frame carrying the
* real cause — is in the console instead of leaving only a bare close code.
*/
export class WebSocketVoiceTransport implements VoiceTransport {
private ws: WebSocket | null = null;
private handlers: VoiceTransportHandlers | null = null;
private closedByClient = false;
/** Frames produced before the socket opens (or while backpressured). */
private sendQueue: ArrayBuffer[] = [];
private sendQueuedBytes = 0;
private sendQueuedMessages = 0;
/** Recent server control frames (newest last), replayed when the socket closes. */
private readonly recentFrames: string[] = [];
/** How many recent control frames to keep for a disconnect dump. */
private static readonly FRAME_TRACE_LIMIT = 12;
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;
this.handlers = handlers;
this.closedByClient = false;
let opened = false;
const timer = setTimeout(() => {
reject(new Error('connect-timeout'));
this.close();
}, this.connectTimeoutMs);
ws.onopen = () => {
opened = true;
clearTimeout(timer);
this.flushSendQueue();
resolve();
};
ws.onmessage = (event: MessageEvent) => {
if (typeof event.data === 'string') {
// Allowlist + field guards: an unknown type or a malformed payload is dropped
// here, exactly like malformed JSON always was — it never reaches the service,
// never enters an error path and never triggers cleanup.
const parsed = parseVoiceServerEvent(event.data);
if (!parsed) return;
this.traceFrame(parsed);
handlers.onEvent(parsed);
} else if (event.data instanceof ArrayBuffer) {
handlers.onAudio(event.data);
}
};
ws.onerror = () => {
if (!opened) {
clearTimeout(timer);
reject(new Error('connect-failed'));
return;
}
// After the handshake a bare Event carries no detail; the `onclose` that follows
// has the code/reason. Log it anyway so the disconnect sequence is visible in the
// console instead of looking like a silent socket death.
console.warn('WebSocketVoiceTransport: socket error after open');
};
ws.onclose = (event: CloseEvent) => {
clearTimeout(timer);
if (!opened) {
reject(new Error('connect-failed'));
return;
}
this.dropSendQueue();
if (!this.closedByClient) {
this.logDisconnect(event);
handlers.onClose({ clean: event.wasClean, code: event.code, reason: event.reason });
}
};
});
}
sendAudio(frame: ArrayBuffer): void {
const ws = this.ws;
if (!ws || this.closedByClient) return;
// Contract guards: every binary message is sample-aligned and bounded.
if (frame.byteLength === 0 || frame.byteLength % 2 !== 0 || frame.byteLength > MAX_MESSAGE_BYTES) {
return; // never emit an out-of-contract frame; the capture worklet guarantees this shape
}
if (ws.readyState === WebSocket.OPEN) {
ws.send(frame);
return;
}
if (ws.readyState !== WebSocket.CONNECTING) return;
this.sendQueuedBytes += frame.byteLength;
this.sendQueuedMessages += 1;
if (this.sendQueuedBytes > MAX_QUEUE_BYTES || this.sendQueuedMessages > MAX_QUEUE_MESSAGES) {
// Filled capacity is a safe failure, not a silent drop.
this.dropSendQueue();
const handlers = this.handlers;
this.close();
handlers?.onOverflow('send');
}
this.sendQueue.push(frame);
}
sendControl(message: PlaybackProgressMessage): void {
const ws = this.ws;
if (ws?.readyState === WebSocket.OPEN && !this.closedByClient) {
ws.send(JSON.stringify(message));
}
}
close(): void {
this.closedByClient = true;
this.dropSendQueue();
const ws = this.ws;
this.ws = null;
if (!ws) return;
ws.onmessage = null;
ws.onerror = null;
try {
ws.close(1000);
} catch {
/* already closed */
}
}
/**
* Keep a bounded trace of incoming control frames, and log an `error` frame verbatim —
* it is the server telling us why the call is about to end, and it is invisible unless
* something prints it.
*/
private traceFrame(event: VoiceServerEvent): void {
const type = event?.type;
if (type === 'error') {
console.warn('WebSocketVoiceTransport: server sent error frame', event);
this.recentFrames.push('error ' + WebSocketVoiceTransport.summarize(event));
} else {
this.recentFrames.push(WebSocketVoiceTransport.summarize(event));
}
if (this.recentFrames.length > WebSocketVoiceTransport.FRAME_TRACE_LIMIT) {
this.recentFrames.shift();
}
}
/**
* Everything the backend asks for when a disconnect is reported: the close code/reason
* plus the frames that led up to it, newest first.
*/
private logDisconnect(event: CloseEvent): void {
const frames = [...this.recentFrames].reverse();
console.warn(
`WebSocketVoiceTransport: socket closed — code=${event.code} ` +
`clean=${event.wasClean} reason="${event.reason}"` +
(frames.length ? `\n last server frames (newest first):\n ${frames.join('\n ')}` : ''),
);
}
/** One compact line per control frame; errors are printed in full by traceFrame. */
private static summarize(event: VoiceServerEvent): string {
const type = event?.type ?? 'unknown';
if (type === 'transcript') {
const t = event as { status?: string; text?: string };
return `transcript[${t.status ?? '?'}] ${(t.text ?? '').slice(0, 80)}`;
}
if (type === 'answer_limited') {
const a = event as { turn_ref?: string; reason?: string };
return `answer_limited ${a.turn_ref ?? ''} reason=${a.reason ?? ''}`.trim();
}
if (type === 'audio_started' || type === 'audio_ended') {
return `${type} ${(event as { audio_ref?: string }).audio_ref ?? ''}`.trim();
}
if (type === 'error') {
return JSON.stringify(event);
}
return type;
}
private flushSendQueue(): void {
const ws = this.ws;
const queue = this.sendQueue;
this.sendQueue = [];
this.sendQueuedBytes = 0;
this.sendQueuedMessages = 0;
if (!ws) return; // the onclose handler already runs for this socket
for (const frame of queue) {
if (ws.readyState !== WebSocket.OPEN) break;
ws.send(frame);
}
}
private dropSendQueue(): void {
this.sendQueue = [];
this.sendQueuedBytes = 0;
this.sendQueuedMessages = 0;
}
}
/** 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);
},
},
);
@@ -0,0 +1,87 @@
import {
CallActivityPoint,
CallOutcomeShare,
HourlyCallPoint,
WallboardKpis,
} from './wallboard.types';
const ACTIVITY_DAYS = 14;
const HOUR_BUCKETS: { hour: number; span: number }[] = [
{ hour: 8, span: 2 },
{ hour: 10, span: 2 },
{ hour: 12, span: 2 },
{ hour: 14, span: 2 },
{ hour: 16, span: 2 },
{ hour: 18, span: 2 },
{ hour: 20, span: 2 },
];
/** Deterministic pseudo-random source so mock data stays stable across reloads and tests. */
function seededNoise(seed: number): number {
const value = Math.sin(seed * 12.9898) * 43758.5453;
return Math.abs(value - Math.floor(value));
}
function buildActivity(): CallActivityPoint[] {
const points: CallActivityPoint[] = [];
const today = new Date();
for (let offset = ACTIVITY_DAYS - 1; offset >= 0; offset--) {
const date = new Date(today);
date.setDate(today.getDate() - offset);
const weekday = date.getDay();
const isWeekend = weekday === 4 || weekday === 5;
const noise = seededNoise(offset + 3);
// Lower weekend volume with a mild upward drift toward today.
const base = isWeekend ? 620 : 980;
const drift = (ACTIVITY_DAYS - offset) * 6;
points.push({
label: date.toLocaleDateString('fa-IR', { day: 'numeric', month: 'long' }),
count: Math.round(base + noise * 180 + drift),
});
}
return points;
}
function buildHourly(): HourlyCallPoint[] {
return HOUR_BUCKETS.map((bucket, index) => {
const noise = seededNoise(index + 11);
// Mid-day and late-afternoon peaks, quiet early morning.
const peak = bucket.hour <= 12 ? 1.35 : bucket.hour >= 18 ? 1.5 : 1.15;
return {
label: `${toPersianHour(bucket.hour)}–${toPersianHour(bucket.hour + bucket.span)}`,
count: Math.round((520 + noise * 260) * peak),
};
});
}
function toPersianHour(hour: number): string {
const persianDigits = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
return String(hour)
.padStart(2, '0')
.replace(/\d/g, (digit) => persianDigits[Number(digit)]);
}
export const MOCK_WALLBOARD_KPIS: WallboardKpis = {
totalCalls: 12846,
aiCalls: 8412,
avgAiTalkSeconds: 142,
successfulAiCalls: 7156,
transferredToAgentCalls: 1256,
periodLabel: 'امروز',
};
export const MOCK_CALL_OUTCOMES: CallOutcomeShare[] = [
{ id: 'ai', label: 'پاسخ‌گویی هوش مصنوعی', value: 7156 },
{ id: 'transfer', label: 'انتقال به کارشناس پس از هوش مصنوعی', value: 1256 },
{ id: 'direct-agent', label: 'تماس مستقیم با کارشناس', value: 4434 },
];
export const MOCK_CALL_ACTIVITY: CallActivityPoint[] = buildActivity();
export const MOCK_HOURLY_CALLS: HourlyCallPoint[] = buildHourly();
@@ -0,0 +1,77 @@
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
import { firstValueFrom } from 'rxjs';
import { WallboardService } from './wallboard.service';
describe('WallboardService', () => {
let service: WallboardService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideHttpClient(),
provideRouter([]),
provideAnimations(),
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
],
});
service = TestBed.inject(WallboardService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('returns KPIs with a consistent AI breakdown', async () => {
const kpis = await firstValueFrom(service.getKpis());
expect(kpis.totalCalls).toBeGreaterThan(0);
expect(kpis.aiCalls).toBeGreaterThan(0);
expect(kpis.aiCalls).toBeLessThanOrEqual(kpis.totalCalls);
expect(kpis.successfulAiCalls + kpis.transferredToAgentCalls).toBe(kpis.aiCalls);
expect(kpis.avgAiTalkSeconds).toBeGreaterThan(0);
});
it('returns outcome shares summing up to the total call count', async () => {
const outcomes = await firstValueFrom(service.getOutcomes());
const kpis = await firstValueFrom(service.getKpis());
const total = outcomes.reduce((sum, outcome) => sum + outcome.value, 0);
expect(outcomes.length).toBeGreaterThan(0);
expect(total).toBe(kpis.totalCalls);
});
it('returns a 14 point activity trend with valid labels', async () => {
const activity = await firstValueFrom(service.getActivity());
expect(activity).toHaveLength(14);
activity.forEach((point) => {
expect(point.label).toBeTruthy();
expect(point.count).toBeGreaterThan(0);
});
});
it('returns hourly buckets covering the whole working day', async () => {
const hourly = await firstValueFrom(service.getHourlyDistribution());
expect(hourly.length).toBeGreaterThan(0);
hourly.forEach((bucket) => {
expect(bucket.label).toMatch(/–/);
expect(bucket.count).toBeGreaterThan(0);
});
});
it('returns a complete overview combining every wallboard dataset', async () => {
const overview = await firstValueFrom(service.getOverview());
expect(overview.kpis.totalCalls).toBeGreaterThan(0);
expect(overview.outcomes.length).toBeGreaterThan(0);
expect(overview.activity).toHaveLength(14);
expect(overview.hourly.length).toBeGreaterThan(0);
});
});
@@ -0,0 +1,77 @@
import { Injectable, inject } from '@angular/core';
import { map, Observable, of } from 'rxjs';
import { HttpService } from '../http-request/http.service';
import {
CallActivityPoint,
CallOutcomeShare,
HourlyCallPoint,
WallboardKpis,
WallboardView,
} from './wallboard.types';
import {
MOCK_CALL_ACTIVITY,
MOCK_CALL_OUTCOMES,
MOCK_HOURLY_CALLS,
MOCK_WALLBOARD_KPIS,
} from './wallboard.mock';
/**
* Call center wallboard data source. The dashboard is read-only, so every
* endpoint is a plain GET that returns a ready-to-render view. While no
* wallboard endpoints exist on the backend, deterministic mock data keeps the
* dashboard fully explorable; flip `useMockData` to false (and align the
* endpoint paths) to consume the real API without touching the page.
*/
@Injectable({
providedIn: 'root',
})
export class WallboardService {
private readonly http = inject(HttpService);
/** Flip to false once the backend wallboard endpoints are deployed. */
private readonly useMockData = true;
getKpis(): Observable<WallboardKpis> {
return this.request<WallboardKpis>('wallboard/kpis', {}, MOCK_WALLBOARD_KPIS);
}
/** سهم روش‌های پاسخ‌گویی: هوش مصنوعی در مقابل کارشناس. */
getOutcomes(): Observable<CallOutcomeShare[]> {
return this.request<CallOutcomeShare[]>('wallboard/call-outcomes', {}, MOCK_CALL_OUTCOMES);
}
getActivity(days = 14): Observable<CallActivityPoint[]> {
return this.request<CallActivityPoint[]>(
'wallboard/call-activity',
{ days },
MOCK_CALL_ACTIVITY,
);
}
getHourlyDistribution(): Observable<HourlyCallPoint[]> {
return this.request<HourlyCallPoint[]>(
'wallboard/hourly-distribution',
{},
MOCK_HOURLY_CALLS,
);
}
getOverview(): Observable<WallboardView> {
return this.request<WallboardView>('wallboard/overview', {}, {
kpis: MOCK_WALLBOARD_KPIS,
outcomes: MOCK_CALL_OUTCOMES,
activity: MOCK_CALL_ACTIVITY,
hourly: MOCK_HOURLY_CALLS,
});
}
private request<T>(endpoint: string, params: Record<string, unknown>, fallback: T): Observable<T> {
if (this.useMockData) {
return of(fallback);
}
return this.http
.get<T>(endpoint, { params, skipToast: true, skipHasErrorCheck: true })
.pipe(map((response) => response.result));
}
}
@@ -0,0 +1,41 @@
/** KPI snapshot for the wallboard («والبورد») dashboard. */
export interface WallboardKpis {
/** کل تماس‌های دریافتی */
totalCalls: number;
/** تماس‌هایی که با هوش مصنوعی گفتگو شده‌اند */
aiCalls: number;
/** میانگین زمان صحبت کاربر با هوش مصنوعی (ثانیه) */
avgAiTalkSeconds: number;
/** تماس‌هایی که هوش مصنوعی با موفقیت به پایان رسانده است */
successfulAiCalls: number;
/** تماس‌هایی که پس از هوش مصنوعی به کارشناس transfer شده‌اند */
transferredToAgentCalls: number;
/** برچسب بازه زمانی گزارش */
periodLabel: string;
}
/** سهم هر روش پاسخ‌گویی از کل تماس‌ها (نمودار دایره‌ای هوش مصنوعی/کارشناس) */
export interface CallOutcomeShare {
id: string;
label: string;
value: number;
}
/** نقطه از روند فعالیت تماس‌ها در گذر زمان (نمودار خطی) */
export interface CallActivityPoint {
label: string;
count: number;
}
/** حجم تماس‌ها در هر بازه ساعتی (نمودار میله‌ای) */
export interface HourlyCallPoint {
label: string;
count: number;
}
export interface WallboardView {
kpis: WallboardKpis;
outcomes: CallOutcomeShare[];
activity: CallActivityPoint[];
hourly: HourlyCallPoint[];
}
+536
View File
@@ -0,0 +1,536 @@
/* Shared chrome for the symbolic demonstration pages:
«ارتباط با کال سنتر»، «بازخوانی تماس‌ها از کال سنتر» and «سوالات چت وب اپلیکیشن».
Each page component includes this file through styleUrls, so keep every selector
page-agnostic (prefix: demo-). Visual language mirrors the reports/wallboard pages. */
.demo-page {
min-height: 100%;
padding: 2.25rem 3rem 3.5rem;
display: flex;
flex-direction: column;
gap: 1.5rem;
animation: demoFadeIn 0.4s ease-out;
}
/* ---------- header ---------- */
.demo-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
}
.demo-title-group {
display: flex;
align-items: center;
gap: 0.875rem;
}
.demo-title-icon {
display: flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
border-radius: 0.875rem;
background: var(--color-primary);
color: #ffffff;
flex-shrink: 0;
}
.demo-title {
margin: 0;
font-size: 1.5rem;
font-weight: 700;
color: var(--text-primary);
line-height: 1.3;
}
.demo-subtitle {
margin: 0.15rem 0 0;
font-size: 0.8125rem;
color: var(--text-muted);
}
.demo-chip {
display: inline-flex;
align-items: center;
gap: 0.35rem;
padding: 0.45rem 0.9rem;
border-radius: 9999px;
border: 1px solid color-mix(in srgb, var(--color-warning) 45%, transparent);
background: color-mix(in srgb, var(--color-warning) 10%, transparent);
color: var(--color-warning);
font-size: 0.75rem;
font-weight: 500;
white-space: nowrap;
}
/* ---------- cards ---------- */
.demo-card {
padding: 1.25rem 1.4rem;
border: 1px solid var(--card-border);
border-radius: 1.25rem;
background: var(--card-bg);
box-shadow:
0 10px 40px rgba(0, 0, 0, 0.06),
0 2px 10px rgba(0, 0, 0, 0.03);
animation: demoFadeInUp 0.5s ease-out both;
}
.demo-card-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
flex-wrap: wrap;
margin-bottom: 1.1rem;
}
.demo-card-title {
margin: 0;
font-size: 1.0625rem;
font-weight: 600;
color: var(--text-primary);
}
.demo-card-description {
margin: 0.2rem 0 0;
font-size: 0.75rem;
color: var(--text-muted);
line-height: 1.7;
}
.demo-badge {
display: inline-flex;
align-items: center;
padding: 0.25rem 0.7rem;
border-radius: 9999px;
border: 1px solid color-mix(in srgb, var(--color-info) 40%, transparent);
background: color-mix(in srgb, var(--color-info) 10%, transparent);
color: var(--color-info);
font-size: 0.6875rem;
font-weight: 500;
white-space: nowrap;
}
/* ---------- notice (page intent) ---------- */
.demo-notice {
display: flex;
align-items: flex-start;
gap: 0.875rem;
border-color: color-mix(in srgb, var(--color-primary) 30%, var(--card-border));
}
.demo-notice-icon {
display: flex;
align-items: center;
justify-content: center;
width: 38px;
height: 38px;
border-radius: 0.75rem;
background: color-mix(in srgb, var(--color-primary) 12%, transparent);
color: var(--color-primary);
flex-shrink: 0;
}
.demo-notice h2 {
margin: 0 0 0.3rem;
font-size: 0.9375rem;
font-weight: 600;
color: var(--text-primary);
}
.demo-notice p {
margin: 0;
font-size: 0.8125rem;
color: var(--text-muted);
line-height: 1.8;
}
/* ---------- feature cards ---------- */
.demo-features {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 1rem;
}
.demo-feature {
display: flex;
flex-direction: column;
gap: 0.45rem;
padding: 1rem 1.1rem;
border: 1px solid var(--card-border);
border-radius: 1rem;
background: color-mix(in srgb, var(--sidebar-hover) 60%, transparent);
}
.demo-feature-icon {
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
border-radius: 0.65rem;
background: color-mix(in srgb, var(--color-primary) 12%, transparent);
color: var(--color-primary);
}
.demo-feature h3 {
margin: 0;
font-size: 0.8125rem;
font-weight: 600;
color: var(--text-primary);
}
.demo-feature p {
margin: 0;
font-size: 0.75rem;
color: var(--text-muted);
line-height: 1.7;
}
/* ---------- status pill ---------- */
.demo-status {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.3rem 0.75rem;
border-radius: 9999px;
font-size: 0.75rem;
font-weight: 500;
}
.demo-status::before {
content: '';
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
}
.demo-status--off {
background: color-mix(in srgb, var(--color-warning) 14%, transparent);
color: var(--color-warning);
}
.demo-status--on {
background: color-mix(in srgb, var(--color-success) 14%, transparent);
color: var(--color-success);
}
.demo-status-row {
display: flex;
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
}
/* ---------- symbolic form ---------- */
.demo-form-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 1rem 1.25rem;
}
.demo-field {
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.demo-field-label {
font-size: 0.8rem;
font-weight: 500;
color: var(--text-secondary);
}
.demo-field-input {
background: var(--color-input-bg);
color: var(--text-secondary);
border: 1px solid var(--color-input-border);
border-radius: 0.5rem;
padding: 0.5rem 0.75rem;
font-size: 0.875rem;
outline: none;
width: 100%;
box-sizing: border-box;
}
.demo-field-input[readonly] {
background: var(--surface-bg);
cursor: default;
opacity: 0.85;
}
.demo-field-hint {
font-size: 0.75rem;
color: var(--text-muted);
line-height: 1.6;
}
.demo-actions {
display: flex;
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
margin-top: 1.1rem;
}
.demo-hint {
font-size: 0.75rem;
color: var(--text-muted);
}
.demo-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.4rem;
border-radius: 0.5rem;
padding: 0.5rem 0.9rem;
font-size: 0.85rem;
font-weight: 500;
border: 1px solid transparent;
cursor: pointer;
transition:
background-color 0.2s,
border-color 0.2s,
color 0.2s;
}
.demo-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.demo-btn--primary {
background: var(--color-primary);
color: #ffffff;
}
.demo-btn--primary:hover:not(:disabled) {
background: color-mix(in srgb, var(--color-primary) 80%, #000);
}
.demo-btn--outline {
background: transparent;
border-color: var(--color-input-border);
color: var(--text-secondary);
}
.demo-btn--outline:hover:not(:disabled) {
background: color-mix(in srgb, var(--color-primary) 22%, #ffffff);
border-color: var(--color-primary);
color: var(--color-primary);
}
/* ---------- table (example data) ---------- */
.demo-table-wrapper {
overflow-x: auto;
border: 1px solid var(--card-border);
border-radius: 1rem;
}
.demo-table {
width: 100%;
border-collapse: separate;
border-spacing: 0;
font-size: 0.8125rem;
text-align: right;
}
.demo-table thead th {
padding: 0.7rem 1rem;
background: var(--sidebar-hover);
color: var(--text-secondary);
font-size: 0.75rem;
font-weight: 500;
white-space: nowrap;
border-bottom: 1px solid var(--card-border);
}
.demo-table tbody td {
padding: 0.7rem 1rem;
color: var(--text-secondary);
border-bottom: 1px solid var(--card-border);
white-space: nowrap;
}
.demo-table tbody tr:last-child td {
border-bottom: none;
}
.demo-table tbody tr:hover td {
background: color-mix(in srgb, var(--sidebar-hover) 45%, transparent);
}
/* ---------- question list (example data) ---------- */
.demo-list {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.demo-list-item {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
padding: 0.9rem 1.1rem;
border: 1px solid var(--card-border);
border-radius: 1rem;
background: color-mix(in srgb, var(--sidebar-hover) 45%, transparent);
}
.demo-question {
margin: 0 0 0.4rem;
font-size: 0.875rem;
font-weight: 500;
color: var(--text-primary);
line-height: 1.7;
}
.demo-meta {
display: flex;
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
font-size: 0.6875rem;
color: var(--text-muted);
}
.demo-tag {
display: inline-flex;
align-items: center;
padding: 0.15rem 0.6rem;
border-radius: 9999px;
font-size: 0.6875rem;
font-weight: 500;
}
.demo-tag--site {
background: color-mix(in srgb, var(--color-info) 12%, transparent);
color: var(--color-info);
}
.demo-tag--app {
background: color-mix(in srgb, var(--color-primary) 12%, transparent);
color: var(--color-primary);
}
.demo-tag--answered {
background: color-mix(in srgb, var(--color-success) 14%, transparent);
color: var(--color-success);
}
.demo-tag--pending {
background: color-mix(in srgb, var(--color-warning) 14%, transparent);
color: var(--color-warning);
}
.demo-tag--missed {
background: color-mix(in srgb, var(--color-danger) 14%, transparent);
color: var(--color-danger);
}
/* ---------- empty state ---------- */
.demo-empty {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.4rem;
padding: 2.5rem 1.5rem;
text-align: center;
color: var(--text-muted);
}
.demo-empty h3 {
margin: 0.4rem 0 0;
font-size: 0.9375rem;
font-weight: 600;
color: var(--text-primary);
}
.demo-empty p {
margin: 0;
font-size: 0.8125rem;
line-height: 1.8;
max-width: 42rem;
}
/* ---------- animations ---------- */
@keyframes demoFadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes demoFadeInUp {
from {
opacity: 0;
transform: translateY(16px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@media (prefers-reduced-motion: reduce) {
.demo-page,
.demo-card {
animation: none;
}
}
@media (max-width: 1400px) {
.demo-page {
padding: 1.75rem 2rem 3rem;
}
}
@media (max-width: 1024px) {
.demo-page {
padding: 1.5rem 1.75rem 2.75rem;
}
.demo-features {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.demo-form-grid {
grid-template-columns: minmax(0, 1fr);
}
}
@media (max-width: 640px) {
.demo-page {
padding: 1.25rem 1.25rem 2.25rem;
}
.demo-features {
grid-template-columns: minmax(0, 1fr);
}
}
:host-context([data-bs-theme='dark']) .demo-card {
box-shadow:
0 10px 40px rgba(0, 0, 0, 0.3),
0 2px 10px rgba(0, 0, 0, 0.2);
}
@@ -0,0 +1,587 @@
:host {
display: block;
}
.ai-chat-input-wrapper {
width: 100%;
max-width: 800px;
margin: 0 auto;
position: relative;
min-height: 72px;
transition: min-height 0.4s cubic-bezier(0.22, 1, 0.36, 1);
}
/* Height of the dictation view; the wrapper animates to it so the page never jumps. */
.ai-chat-input-wrapper.dictation-active {
min-height: 460px;
}
/* A live call replaces the composer: the call bar (rendered by the page) sits where the input was,
so the wrapper collapses instead of leaving an empty 72px box under it. */
.ai-chat-input-wrapper.stream-open {
min-height: 0;
}
/* Layers cross-fade */
.composer-layer,
.voice-layer {
transition: opacity 0.35s ease, transform 0.35s ease;
}
.composer-layer {
position: relative;
opacity: 1;
transform: translateY(0);
}
.voice-layer {
position: absolute;
inset: 0;
opacity: 0;
transform: translateY(10px) scale(0.98);
/* Never blocks the transcript underneath; the dictation view re-enables it. */
pointer-events: none;
/* The layer is inset:0 of a collapsed wrapper while dictation is not running, so the
dictation view inside it would overflow its box and add phantom height to the page
(visible as a gap under the composer + a Y scroll). Clipping keeps it out of layout.
It stays in the DOM (display is untouched) so the viewChild refs stay valid. */
overflow: hidden;
}
.ai-chat-input-wrapper.voice-active .composer-layer {
/* Out of the flow so the voice view takes the full height while it runs. */
position: absolute;
inset-inline: 0;
bottom: 0;
opacity: 0;
transform: translateY(10px);
pointer-events: none;
}
.ai-chat-input-wrapper.voice-active .voice-layer {
opacity: 1;
transform: translateY(0) scale(1);
}
/* ---------- Chat composer ---------- */
.chat-composer {
/* The composer lays itself out RTL explicitly: Plus on the right edge, Send on the left.
Icons are SVGs, so they are never mirrored by direction. */
direction: rtl;
display: flex;
align-items: center;
gap: 0.375rem;
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;
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);
}
.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;
border: none;
background: transparent;
color: var(--app-text);
font-family: inherit;
font-size: 0.9375rem;
line-height: 1.6;
resize: none;
outline: none;
text-align: right;
direction: rtl;
overflow-y: auto;
}
.composer-textarea::placeholder {
color: var(--muted);
text-align: right;
opacity: 0.8;
}
.composer-textarea:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.composer-textarea::-webkit-scrollbar {
width: 4px;
}
.composer-textarea::-webkit-scrollbar-thumb {
background: var(--muted);
border-radius: 9999px;
}
/* ---------- Action buttons ---------- */
.composer-btn {
display: flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
border: none;
border-radius: 50%;
background: transparent;
color: var(--muted);
cursor: pointer;
transition: background 0.2s ease, color 0.2s ease, transform 0.15s ease;
flex-shrink: 0;
user-select: none;
}
.composer-btn:hover:not(:disabled) {
background: var(--sidebar-hover);
color: var(--text-primary);
transform: scale(1.05);
}
.composer-btn:active:not(:disabled) {
transform: scale(0.95);
}
.composer-btn:disabled {
opacity: 0.35;
cursor: not-allowed;
}
.composer-btn:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
.send-btn {
background: var(--color-primary);
color: #ffffff;
}
.send-btn:hover:not(:disabled) {
background: #2563eb;
color: #ffffff;
}
/* Mic: waiting for the browser permission prompt */
.mic-btn.is-pending {
color: var(--color-primary);
animation: micPending 1.1s ease-in-out infinite;
}
/* Mic: voice transcription not available in this browser (stays clickable to explain why) */
.mic-btn.is-unsupported {
opacity: 0.45;
}
@keyframes micPending {
0%,
100% {
box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.35);
}
50% {
box-shadow: 0 0 0 6px rgba(59, 130, 246, 0);
}
}
/* ---------- Attachment menu ---------- */
.attachment-menu {
position: absolute;
bottom: calc(100% + 0.5rem);
right: 0.5rem;
min-width: 180px;
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);
overflow: hidden;
z-index: 50;
animation: menuFadeIn 0.15s ease;
}
.attachment-menu-item {
display: flex;
align-items: center;
gap: 0.625rem;
width: 100%;
padding: 0.625rem 1rem;
border: none;
background: transparent;
color: var(--text-secondary);
font-family: inherit;
font-size: 0.875rem;
text-align: right;
cursor: pointer;
transition: background 0.15s ease;
}
.attachment-menu-item:hover,
.attachment-menu-item:focus-visible {
background: var(--sidebar-hover);
color: var(--text-primary);
}
.attachment-menu-item:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: -2px;
}
@keyframes menuFadeIn {
from {
opacity: 0;
transform: translateY(4px) scale(0.97);
}
to {
opacity: 1;
transform: translateY(0) scale(1);
}
}
/* ---------- Notice (permission denied, unsupported browser, ...) ---------- */
.voice-notice {
direction: rtl;
display: flex;
align-items: center;
gap: 0.5rem;
margin-top: 0.625rem;
padding: 0.5rem 0.75rem;
border: 1px solid var(--surface-border);
border-radius: 0.875rem;
background: var(--surface-bg);
color: var(--text-secondary);
font-size: 0.8125rem;
line-height: 1.6;
animation: menuFadeIn 0.2s ease;
}
.voice-notice.is-error {
border-color: rgba(239, 68, 68, 0.45);
color: #dc2626;
}
.voice-notice-text {
flex: 1;
min-width: 0;
}
.voice-notice-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;
}
.voice-notice-close:hover {
background: var(--sidebar-hover);
}
.voice-notice-close:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 1px;
}
/* ---------- Voice mode ---------- */
.voice-mode {
direction: rtl;
box-sizing: border-box;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 1rem;
padding: 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);
/* Re-enabled on the view itself; the layer stays click-through for the transcript. */
pointer-events: auto;
}
.orb-container {
width: 220px;
height: 220px;
max-width: 100%;
position: relative;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.orb-container canvas {
display: block;
width: 100% !important;
height: 100% !important;
}
/* Shown only when WebGL is unavailable */
.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: orbFallbackPulse 2.4s ease-in-out infinite;
}
@keyframes orbFallbackPulse {
0%,
100% {
transform: scale(1);
}
50% {
transform: scale(1.06);
}
}
/* Recording indicator + status text */
.voice-status {
display: flex;
align-items: center;
gap: 0.5rem;
}
.rec-dot {
width: 10px;
height: 10px;
border-radius: 50%;
background: #ef4444;
flex-shrink: 0;
animation: recPulse 1.4s ease-in-out infinite;
}
.voice-status.is-speaking .rec-dot {
animation-duration: 0.7s;
}
@keyframes recPulse {
0%,
100% {
opacity: 1;
box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.5);
}
50% {
opacity: 0.7;
box-shadow: 0 0 0 6px rgba(239, 68, 68, 0);
}
}
.voice-mode-text {
font-size: 0.9375rem;
color: var(--text-secondary);
margin: 0;
text-align: center;
}
/* Live transcript preview (the textarea is updated at the same time) */
.voice-transcript {
box-sizing: border-box;
width: 100%;
max-width: 560px;
height: 3.25rem;
overflow-y: auto;
padding: 0.25rem 0.5rem;
color: var(--text-primary);
font-size: 0.9375rem;
line-height: 1.6;
text-align: right;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.t-interim,
.t-placeholder {
color: var(--muted);
}
.t-placeholder {
display: block;
text-align: center;
font-size: 0.875rem;
}
.voice-actions {
display: flex;
align-items: center;
justify-content: center;
gap: 0.625rem;
flex-wrap: wrap;
}
.voice-stop-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;
}
.voice-stop-btn:hover:not(:disabled) {
background: var(--sidebar-hover);
color: var(--text-primary);
transform: scale(1.03);
}
.voice-stop-btn.is-primary {
background: var(--color-primary);
border-color: var(--color-primary);
color: #ffffff;
}
.voice-stop-btn.is-primary:hover:not(:disabled) {
background: #2563eb;
border-color: #2563eb;
color: #ffffff;
}
.voice-stop-btn:active:not(:disabled) {
transform: scale(0.97);
}
.voice-stop-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.voice-stop-btn:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
/* ---------- Screen reader only ---------- */
.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;
}
/* ---------- Reduced motion ---------- */
@media (prefers-reduced-motion: reduce) {
.ai-chat-input-wrapper,
.composer-layer,
.voice-layer,
.chat-composer,
.composer-btn,
.voice-stop-btn,
.attachment-menu,
.voice-notice {
transition: none !important;
animation: none !important;
}
.rec-dot,
.orb-fallback,
.mic-btn.is-pending {
animation: none !important;
}
}
/* ---------- Mobile ---------- */
@media (max-width: 640px) {
.ai-chat-input-wrapper {
max-width: 100%;
}
.ai-chat-input-wrapper.dictation-active {
min-height: 410px;
}
.chat-composer {
gap: 0.25rem;
padding: 0.5rem 0.625rem;
border-radius: 1.25rem;
}
.composer-btn {
width: 32px;
height: 32px;
}
.composer-btn svg {
width: 18px;
height: 18px;
}
.composer-textarea {
/* 16px prevents iOS from zooming the page when the field is focused */
font-size: 1rem;
}
.voice-mode {
gap: 0.75rem;
padding: 1rem;
}
.orb-container {
width: 170px;
height: 170px;
}
.voice-stop-btn {
padding: 0.5rem 1rem;
}
.attachment-menu {
right: 0.25rem;
min-width: 160px;
}
}
/* ---------- Send icon ---------- */
.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;
}
}
@@ -0,0 +1,211 @@
<div
class="ai-chat-input-wrapper"
[class.voice-active]="anyVoiceActive()"
[class.dictation-active]="isVoiceMode()"
[class.stream-open]="streamOpen()"
[attr.data-voice-state]="voiceState()"
(keydown.escape)="onEscape()"
>
<!-- 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]="anyVoiceActive() ? '' : null">
<div class="chat-composer" #composer>
<button
#plusBtn
type="button"
class="composer-btn plus-btn"
(click)="toggleAttachmentMenu()"
aria-label="افزودن پیوست"
aria-haspopup="menu"
aria-controls="attachment-menu"
[attr.aria-expanded]="isAttachmentMenuOpen()"
>
<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 5v14M5 12h14" />
</svg>
</button>
<div class="composer-textarea-wrapper">
<textarea
#textarea
class="composer-textarea"
[placeholder]="placeholder()"
[disabled]="disabled()"
(input)="onTextareaInput()"
(keydown)="onKeyDown($event)"
rows="1"
dir="rtl"
aria-label="متن پیام"
></textarea>
</div>
<button
type="button"
class="composer-btn mic-btn"
[class.is-pending]="voiceState() === 'requesting-permission'"
[class.is-unsupported]="!voiceSupported"
[disabled]="disabled()"
[attr.aria-label]="micLabel()"
[attr.title]="micLabel()"
[attr.aria-pressed]="isVoiceMode()"
[attr.aria-busy]="voiceState() === 'requesting-permission'"
[attr.aria-disabled]="voiceSupported ? null : 'true'"
(click)="toggleVoiceMode()"
>
<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 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>
</button>
<button
type="button"
class="composer-btn send-btn"
[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()) {
<div
#attachmentMenu
id="attachment-menu"
class="attachment-menu"
role="menu"
aria-label="پیوست‌ها"
(keydown)="onMenuKeydown($event)"
>
@for (action of attachmentActions(); track action.id) {
<button
type="button"
class="attachment-menu-item"
role="menuitem"
(click)="selectAction(action)"
>
@switch (action.icon) {
@case ('image') {
<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">
<rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
<circle cx="8.5" cy="8.5" r="1.5" />
<polyline points="21 15 16 10 5 21" />
</svg>
}
@default {
<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="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z" />
<polyline points="14 2 14 8 20 8" />
</svg>
}
}
<span>{{ action.label }}</span>
</button>
}
</div>
}
<input
#fileInput
type="file"
class="sr-only"
tabindex="-1"
(change)="onFileChange($event)"
aria-hidden="true"
/>
</div>
@if (notice(); as n) {
<div
class="voice-notice"
[class.is-error]="n.kind === 'error'"
[attr.role]="n.kind === 'error' ? 'alert' : 'status'"
>
<span class="voice-notice-text">{{ n.text }}</span>
<button type="button" class="voice-notice-close" aria-label="بستن پیام" (click)="dismissNotice()">
<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>
<div
class="voice-layer"
[attr.inert]="anyVoiceActive() ? null : ''"
[attr.aria-hidden]="anyVoiceActive() ? null : 'true'"
>
@if (!streamOpen()) {
<div class="voice-mode" role="region" aria-label="حالت صوتی">
<div class="orb-container" #orbContainer aria-hidden="true">
@if (!orbAvailable()) {
<div class="orb-fallback"></div>
}
</div>
<div class="voice-status" [class.is-speaking]="voiceState() === 'transcribing'">
<span class="rec-dot" aria-hidden="true"></span>
<p class="voice-mode-text">{{ statusText() }}</p>
</div>
<div class="voice-transcript" #transcript dir="rtl">
@if (liveFinal() || liveInterim()) {
<span class="t-final">{{ liveFinal() }}</span>
@if (liveInterim()) {
<span class="t-interim"> {{ liveInterim() }}</span>
}
} @else {
<span class="t-placeholder">صحبت کنید؛ متن اینجا نمایش داده می‌شود</span>
}
</div>
<div class="voice-actions">
<button
type="button"
class="voice-stop-btn is-primary"
[disabled]="voiceState() === 'stopping'"
(click)="stopVoice(true)"
aria-label="پایان ضبط و ویرایش متن"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<rect x="6" y="6" width="12" height="12" rx="2" />
</svg>
<span>پایان و ویرایش</span>
</button>
<button
type="button"
class="voice-stop-btn"
[disabled]="voiceState() === 'stopping'"
(click)="stopVoice(false)"
aria-label="لغو ضبط و حذف متن گفتاری"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<line x1="18" x2="6" y1="6" y2="18" />
<line x1="6" x2="18" y1="6" y2="18" />
</svg>
<span>لغو</span>
</button>
</div>
</div>
}
</div>
</div>
@@ -0,0 +1,571 @@
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
ChangeDetectionStrategy,
Component,
ElementRef,
Injector,
OnDestroy,
afterNextRender,
computed,
effect,
inject,
input,
output,
signal,
viewChild,
} from '@angular/core';
import { MicrophoneError, MicrophoneService } from '../../../services/microphone/microphone.service';
import {
DEFAULT_SPEECH_LANGUAGE,
SpeechErrorKind,
SpeechRecognitionService,
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';
export type VoiceState =
| 'idle'
| 'requesting-permission'
| 'recording'
| 'transcribing'
| 'stopping'
| 'error';
export interface AttachmentAction {
id: string;
label: string;
icon: 'file' | 'image';
/** Value for the file input's `accept` attribute ('' = any file). */
accept: string;
}
interface Notice {
kind: 'error' | 'info';
text: string;
}
export const DEFAULT_ATTACHMENT_ACTIONS: readonly AttachmentAction[] = [
{ id: 'file', label: 'آپلود فایل', icon: 'file', accept: '' },
{ id: 'image', label: 'آپلود تصویر', icon: 'image', accept: 'image/*' },
];
const NOTICE_TIMEOUT_MS = 7000;
const MIC_ERRORS: Record<string, string> = {
unsupported: 'مرورگر شما از دسترسی به میکروفون پشتیبانی نمی‌کند (اتصال امن HTTPS لازم است).',
denied: 'دسترسی به میکروفون رد شد. اجازه‌ی دسترسی را در تنظیمات مرورگر فعال کنید.',
unavailable: 'میکروفونی پیدا نشد یا در حال استفاده‌ی برنامه‌ی دیگری است.',
unknown: 'دسترسی به میکروفون ممکن نشد. دوباره تلاش کنید.',
};
const SPEECH_ERRORS: Record<SpeechErrorKind, string> = {
'permission-denied': 'اجازه‌ی استفاده از تشخیص گفتار داده نشد. تنظیمات مرورگر را بررسی کنید.',
'audio-capture': 'میکروفون در دسترس نیست. اتصال آن را بررسی کنید.',
network: 'اتصال به سرویس تشخیص گفتار برقرار نشد. اینترنت خود را بررسی کنید.',
'no-speech': 'گفتاری شناسایی نشد. دوباره تلاش کنید.',
'language-not-supported': 'این زبان توسط تشخیص گفتار مرورگر پشتیبانی نمی‌شود.',
unsupported: 'تبدیل گفتار به متن در این مرورگر پشتیبانی نمی‌شود. از Chrome یا Edge استفاده کنید.',
unknown: 'تشخیص گفتار با خطا متوقف شد. دوباره تلاش کنید.',
};
@Component({
selector: 'app-ai-chat-input',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './ai-chat-input.component.html',
styleUrl: './ai-chat-input.component.css',
})
export class AiChatInputComponent implements OnDestroy {
private readonly injector = inject(Injector);
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>('پیام خود را بنویسید...');
readonly disabled = input<boolean>(false);
readonly hasMessages = input<boolean>(false);
/** Speech recognition language (BCP-47), e.g. 'fa-IR' or 'en-US'. */
readonly language = input<string>(DEFAULT_SPEECH_LANGUAGE);
readonly attachmentActions = input<readonly AttachmentAction[]>(DEFAULT_ATTACHMENT_ACTIONS);
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('');
readonly isAttachmentMenuOpen = signal(false);
readonly voiceState = signal<VoiceState>('idle');
readonly notice = signal<Notice | null>(null);
readonly liveFinal = signal('');
readonly liveInterim = signal('');
readonly orbAvailable = signal(true);
// Live voice call (voice-to-voice stream)
readonly streamOpen = this.voiceStream.isOpen;
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. */
readonly isVoiceMode = computed(() => {
const state = this.voiceState();
return state === 'recording' || state === 'transcribing' || state === 'stopping';
});
readonly statusText = computed(() => {
switch (this.voiceState()) {
case 'requesting-permission':
return 'در حال درخواست دسترسی به میکروفون...';
case 'recording':
return 'در حال گوش دادن...';
case 'transcribing':
return 'در حال تبدیل گفتار به متن...';
case 'stopping':
return 'در حال پایان دادن...';
case 'error':
return 'خطا در ضبط صدا';
default:
return '';
}
});
readonly micLabel = computed(() => {
if (!this.voiceSupported) return 'تبدیل گفتار به متن در این مرورگر پشتیبانی نمی‌شود';
switch (this.voiceState()) {
case 'requesting-permission':
return 'در حال درخواست دسترسی به میکروفون (برای لغو کلیک کنید)';
case 'recording':
case 'transcribing':
return 'توقف ضبط صدا';
default:
return 'شروع ضبط صدا';
}
});
// ---- view refs ------------------------------------------------------------
private readonly textareaRef = viewChild<ElementRef<HTMLTextAreaElement>>('textarea');
private readonly composerRef = viewChild<ElementRef<HTMLDivElement>>('composer');
private readonly fileInputRef = viewChild<ElementRef<HTMLInputElement>>('fileInput');
private readonly plusBtnRef = viewChild<ElementRef<HTMLButtonElement>>('plusBtn');
private readonly menuRef = viewChild<ElementRef<HTMLDivElement>>('attachmentMenu');
private readonly orbContainerRef = viewChild<ElementRef<HTMLDivElement>>('orbContainer');
private readonly transcriptRef = viewChild<ElementRef<HTMLDivElement>>('transcript');
// ---- internals ------------------------------------------------------------
/** Incremented whenever a voice session ends/cancels so stale async callbacks are ignored. */
private voiceSession = 0;
/** Textarea content when recording started; dictated text is appended to it. */
private baseText = '';
private noticeTimer: ReturnType<typeof setTimeout> | null = null;
constructor() {
// The outside-click listener only exists while the menu is open.
effect((onCleanup) => {
if (!this.isAttachmentMenuOpen()) return;
const onMouseDown = (event: MouseEvent): void => {
const target = event.target as Node;
if (this.composerRef()?.nativeElement.contains(target)) return;
this.closeAttachmentMenu();
};
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.focusTextarea();
});
}
ngOnDestroy(): void {
this.voiceSession++;
this.speech.dispose();
this.mic.release();
this.voiceStream.dispose();
this.voiceOrb.dispose();
this.clearNoticeTimer();
}
// ---- text input -----------------------------------------------------------
onTextareaInput(): void {
const textarea = this.textareaRef()?.nativeElement;
if (!textarea) return;
this.message.set(textarea.value);
this.autoResize(textarea);
}
onKeyDown(event: KeyboardEvent): void {
if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
event.preventDefault();
this.sendMessage();
}
}
sendMessage(): void {
const text = this.message().trim();
if (!text || this.disabled()) return;
this.messageSent.emit(text);
this.setTextareaValue('');
}
private setTextareaValue(value: string): void {
const textarea = this.textareaRef()?.nativeElement;
this.message.set(value);
if (!textarea) return;
textarea.value = value;
this.autoResize(textarea);
}
private autoResize(textarea: HTMLTextAreaElement): void {
textarea.style.height = 'auto';
textarea.style.height = Math.min(textarea.scrollHeight, 192) + 'px';
}
private focusTextarea(): void {
afterNextRender(
() => {
const textarea = this.textareaRef()?.nativeElement;
if (!textarea) return;
textarea.focus();
textarea.setSelectionRange(textarea.value.length, textarea.value.length);
},
{ injector: this.injector },
);
}
// ---- attachments ----------------------------------------------------------
toggleAttachmentMenu(): void {
const opening = !this.isAttachmentMenuOpen();
this.isAttachmentMenuOpen.set(opening);
if (opening) {
afterNextRender(
() => this.menuItems()[0]?.focus(),
{ injector: this.injector },
);
}
}
closeAttachmentMenu(): void {
this.isAttachmentMenuOpen.set(false);
}
selectAction(action: AttachmentAction): void {
const input = this.fileInputRef()?.nativeElement;
this.closeAttachmentMenu();
if (!input) return;
input.accept = action.accept;
input.click();
}
onFileChange(event: Event): void {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (file) {
this.fileSelected.emit(file);
}
input.value = '';
}
onMenuKeydown(event: KeyboardEvent): void {
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;
default:
return;
}
event.preventDefault();
items[next].focus();
}
private menuItems(): HTMLElement[] {
const menu = this.menuRef()?.nativeElement;
return menu ? Array.from(menu.querySelectorAll<HTMLElement>('[role="menuitem"]')) : [];
}
onEscape(): void {
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.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);
if (result.reason !== 'cancelled') {
this.showNotice({ kind: 'error', text: result.message });
}
}
}
// ---- voice: start ---------------------------------------------------------
async toggleVoiceMode(): Promise<void> {
switch (this.voiceState()) {
case 'recording':
case 'transcribing':
await this.stopVoice(true);
break;
case 'requesting-permission':
this.voiceSession++; // the pending permission request is released when it resolves
this.voiceState.set('idle');
break;
case 'stopping':
break;
default:
await this.startVoice();
}
}
private async startVoice(): Promise<void> {
if (this.disabled() || this.streamOpen()) return;
this.dismissNotice();
this.closeAttachmentMenu();
if (!this.mic.isSupported) {
this.failBeforeStart(MIC_ERRORS['unsupported']);
return;
}
if (!this.speech.isSupported) {
this.failBeforeStart(SPEECH_ERRORS.unsupported);
return;
}
const session = ++this.voiceSession;
this.voiceState.set('requesting-permission');
let stream: MediaStream;
try {
stream = await this.mic.request(() => this.onMicEnded(session));
} catch (err) {
if (session !== this.voiceSession) return; // cancelled while the prompt was open
const code = err instanceof MicrophoneError ? err.code : 'unknown';
this.failBeforeStart(MIC_ERRORS[code] ?? MIC_ERRORS['unknown']);
return;
}
if (session !== this.voiceSession) {
this.mic.release(stream); // user cancelled while the prompt was open
return;
}
this.baseText = this.message();
this.liveFinal.set('');
this.liveInterim.set('');
const started = this.speech.start(this.language(), {
onTranscript: (transcript) => this.onTranscript(transcript, session),
onSpeechEnd: () => this.onSpeechEnd(session),
onError: (kind) => this.onSpeechError(kind, session),
});
if (!started) {
this.mic.release(stream);
this.failBeforeStart(SPEECH_ERRORS.unknown);
return;
}
this.voiceState.set('recording');
this.voiceToggled.emit(true);
this.startOrb(stream);
}
private startOrb(stream: MediaStream): void {
const container = this.orbContainerRef()?.nativeElement;
if (!container) return;
const ready = this.voiceOrb.init(container);
this.orbAvailable.set(ready);
if (!ready) return; // CSS fallback orb is shown; recording still works
this.voiceOrb.resetOrbGeometry();
this.voiceOrb.attachStream(stream);
this.voiceOrb.startAnimation();
}
// ---- voice: events --------------------------------------------------------
private onTranscript(transcript: SpeechTranscript, session: number): void {
if (session !== this.voiceSession) return;
this.liveFinal.set(transcript.final);
this.liveInterim.set(transcript.interim);
this.setTextareaValue(this.composeText(transcript.final, transcript.interim));
const state = this.voiceState();
if (state === 'recording' || state === 'transcribing') {
this.voiceState.set(transcript.interim ? 'transcribing' : 'recording');
}
requestAnimationFrame(() => {
const el = this.transcriptRef()?.nativeElement;
if (el) el.scrollTop = el.scrollHeight;
});
}
private onSpeechEnd(session: number): void {
if (session === this.voiceSession && this.voiceState() === 'transcribing') {
this.voiceState.set('recording');
}
}
private onSpeechError(kind: SpeechErrorKind, session: number): void {
if (session !== this.voiceSession || !this.isListening()) return;
this.endSessionWithNotice({
kind: kind === 'no-speech' ? 'info' : 'error',
text: SPEECH_ERRORS[kind],
});
}
private onMicEnded(session: number): void {
if (session !== this.voiceSession || !this.isListening()) return;
this.endSessionWithNotice({ kind: 'error', text: MIC_ERRORS['unavailable'] });
}
// ---- voice: stop ----------------------------------------------------------
/**
* @param commit true keeps the dictated text in the textarea; false restores the
* text that was there before recording started.
*/
async stopVoice(commit: boolean): Promise<void> {
if (!this.isListening()) return;
this.voiceState.set('stopping');
const transcript = await this.speech.stop(); // flushes late final results
this.finishVoice(commit ? transcript : null);
}
private endSessionWithNotice(notice: Notice): void {
this.voiceState.set('stopping');
const transcript = this.speech.currentText();
this.speech.abort();
this.finishVoice(transcript, notice);
}
private finishVoice(transcript: string | null, notice?: Notice): void {
this.voiceSession++;
// Everything that could keep running is released here, on every exit path.
this.speech.abort();
this.voiceOrb.stopAnimation();
this.voiceOrb.detachAudio();
this.mic.release();
if (transcript === null) {
this.setTextareaValue(this.baseText);
} else {
this.setTextareaValue(this.composeText(transcript, ''));
}
this.liveFinal.set('');
this.liveInterim.set('');
this.voiceState.set(notice?.kind === 'error' ? 'error' : 'idle');
this.voiceToggled.emit(false);
if (notice) {
this.showNotice(notice);
} else if (transcript !== null && !transcript.trim()) {
this.showNotice({ kind: 'info', text: SPEECH_ERRORS['no-speech'] });
}
this.focusTextarea();
}
private failBeforeStart(text: string): void {
this.voiceState.set('error');
this.showNotice({ kind: 'error', text });
}
private isListening(): boolean {
const state = this.voiceState();
return state === 'recording' || state === 'transcribing';
}
// ---- helpers --------------------------------------------------------------
private composeText(final: string, interim: string): string {
const spoken = [final, interim].filter(Boolean).join(' ');
const base = this.baseText;
if (!base) return spoken;
if (!spoken) return base;
return /\s$/.test(base) ? base + spoken : `${base} ${spoken}`;
}
private showNotice(notice: Notice): void {
this.clearNoticeTimer();
this.notice.set(notice);
this.noticeTimer = setTimeout(() => this.dismissNotice(), NOTICE_TIMEOUT_MS);
}
dismissNotice(): void {
this.clearNoticeTimer();
this.notice.set(null);
if (this.voiceState() === 'error') {
this.voiceState.set('idle');
}
}
private clearNoticeTimer(): void {
if (this.noticeTimer) {
clearTimeout(this.noticeTimer);
this.noticeTimer = null;
}
}
}
@@ -0,0 +1,175 @@
.ai-model-card {
animation: fadeInUp 0.4s ease-out;
}
.ai-model-card-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
padding: 1rem 1.25rem 0.75rem;
border-bottom: 1px solid var(--surface-border);
}
.ai-model-badge {
font-size: 0.7rem;
font-weight: 600;
padding: 0.15rem 0.55rem;
border-radius: 9999px;
background: var(--color-warning)/15;
color: var(--color-warning);
}
.ai-model-badge.ai-model-badge--connected {
background: var(--color-success)/15;
color: var(--color-success);
}
.ai-model-body {
padding: 1rem 1.25rem;
}
.form-field {
display: flex;
flex-direction: column;
gap: 0.3rem;
}
.form-label {
font-size: 0.8rem;
font-weight: 500;
color: var(--text-secondary);
}
.form-required {
color: var(--color-danger);
}
.form-hint {
margin-top: 0.25rem;
font-size: 0.75rem;
}
.form-select {
appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%2364748b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 1rem center;
padding: 0.75rem 1rem;
padding-right: 2.75rem;
background-color: var(--color-input-bg);
color: var(--text-secondary);
border: 1px solid var(--color-input-border);
border-radius: 0.5rem;
font-size: 0.875rem;
outline: none;
transition: border-color 0.2s, box-shadow 0.2s;
}
.form-select:focus {
box-shadow: 0 0 0 3px var(--color-primary)/20;
}
.form-input {
background: var(--color-input-bg);
color: var(--text-secondary);
border: 1px solid var(--color-input-border);
border-radius: 0.5rem;
padding: 0.5rem 0.75rem;
font-size: 0.875rem;
outline: none;
transition: border-color 0.2s, box-shadow 0.2s;
width: 100%;
box-sizing: border-box;
}
.form-input:focus {
border-color: var(--color-primary);
box-shadow: 0 0 0 3px var(--color-primary)/20;
}
.form-input:disabled {
background: var(--surface-bg);
cursor: default;
opacity: 0.7;
}
.form-visibility-toggle {
position: absolute;
inset-inline-end: 0.5rem;
top: 50%;
translate: 0 -50%;
display: flex;
align-items: center;
justify-content: center;
width: 1.5rem;
height: 1.5rem;
border: none;
background: transparent;
color: var(--text-muted);
cursor: pointer;
border-radius: 0.375rem;
transition: color 0.2s;
}
.form-visibility-toggle:hover {
color: var(--text-primary);
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.4rem;
border-radius: 0.5rem;
padding: 0.5rem 0.9rem;
font-size: 0.85rem;
font-weight: 500;
border: 1px solid transparent;
cursor: pointer;
transition: background-color 0.2s, border-color 0.2s, color 0.2s;
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn--primary {
background: var(--color-primary);
color: #fff;
}
.btn--primary:hover:not(:disabled) {
background: color-mix(in srgb, var(--color-primary) 80%, #000);
}
.btn--primary:active:not(:disabled) {
background: color-mix(in srgb, var(--color-primary) 70%, #000);
}
.btn--outline {
background: transparent;
border-color: var(--color-input-border);
color: var(--text-secondary);
}
.btn--outline:hover:not(:disabled) {
background: color-mix(in srgb, var(--color-primary) 22%, #ffffff);
border-color: var(--color-primary);
color: var(--color-primary);
}
:host-context([data-bs-theme="dark"]) .btn--outline:hover:not(:disabled) {
background: color-mix(in srgb, var(--color-primary) 30%, #171717);
}
.ai-model-actions {
direction: ltr;
}
@media (prefers-reduced-motion: reduce) {
.ai-model-card,
.ai-model-card-header {
animation-duration: 0.01ms !important;
}
}
@@ -0,0 +1,328 @@
import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
import { CommonModule } from '@angular/common';
export type AiProvider = 'openai' | 'gemini' | 'local';
export type AiTask = 'text' | 'embedding' | 'ocr' | 'stt' | 'tts' | 'dialogue';
export interface AiModelConfig {
provider: AiProvider;
model: string;
apiKey: string;
apiKeyVisible: boolean;
serviceUrl: string;
}
interface ProviderOption {
value: AiProvider;
label: string;
needsApiKey: boolean;
}
interface ModelOption {
value: string;
label: string;
}
/**
* Reusable, self-contained configuration card for one AI model class (text /
* embedding / OCR). All state lives in the parent (passed in as a signal-backed
* config object + `@Output`); this component is intentionally "dumb": it emits
* every user change so three instances stay fully independent, and it never
* pretends to persist anything — there is no documented backend for model
* configuration, so the Save / Test buttons surface a clear "not connected"
* status instead of simulating success.
*/
@Component({
selector: 'app-ai-model-config-card',
standalone: true,
imports: [CommonModule],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="ai-model-card settings-card">
<header class="ai-model-card-header">
<h3 class="text-base font-medium text-[var(--text-primary)]">{{ title() }}</h3>
<span class="ai-model-badge" [class.ai-model-badge--connected]="connected()">{{
connected() ? 'متصل' : 'متصل نشده'
}}</span>
</header>
<div class="ai-model-body space-y-4">
<!-- Provider -->
<div class="form-field">
<label class="form-label">ارائه‌دهنده</label>
<select
class="form-select w-full"
[value]="config().provider"
(change)="onProviderChange($any($event.target).value)"
>
@for (provider of providers(); track provider.value) {
<option [value]="provider.value">{{ provider.label }}</option>
}
</select>
</div>
<!-- Model -->
<div class="form-field">
<label class="form-label">مدل</label>
<select
class="form-select w-full"
[value]="config().model"
(change)="onModelChange($any($event.target).value)"
>
@for (model of modelsForProvider(); track model.value) {
<option [value]="model.value">{{ model.label }}</option>
}
</select>
</div>
<!-- API key -->
<div class="form-field">
<label class="form-label">
کلید API
@if (apiKeyRequired()) {
<span class="form-required" aria-hidden="true">*</span>
}
</label>
<div class="relative">
<input
[type]="config().apiKeyVisible ? 'text' : 'password'"
class="form-input w-full pe-10"
[placeholder]="apiKeyPlaceholder()"
[value]="config().apiKey"
(input)="onApiKeyChange($any($event.target).value)"
autocomplete="off"
[attr.aria-label]="apiKeyAriaLabel()"
/>
<button
type="button"
class="form-visibility-toggle"
[attr.aria-label]="config().apiKeyVisible ? 'پنهان کن' : 'نمایش بده'"
(click)="toggleApiKeyVisibility()"
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
@if (config().apiKeyVisible) {
<!-- Eye Off: API key is visible -->
<path d="M10.58 10.58a2 2 0 0 0 2.83 2.83" />
<path
d="M16.68 16.68A10.7 10.7 0 0 1 12 17.75c-5 0-8.27-3.11-10-5.75a1.8 1.8 0 0 1 0-2A11.8 11.8 0 0 1 5.32 6.33"
/>
<path
d="M9.88 5.08A10.7 10.7 0 0 1 12 4.75c5 0 8.27 3.11 10 5.75a1.8 1.8 0 0 1 0 2 11.8 11.8 0 0 1-1.82 2.32"
/>
<line x1="2" y1="2" x2="22" y2="22" />
} @else {
<!-- Eye: API key is hidden -->
<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z" />
<circle cx="12" cy="12" r="3" />
}
</svg>
</button>
</div>
<div class="form-hint">
@if (connected() && config().apiKey) {
<span class="text-[var(--text-muted)]"
>تنظیم شده — مقدار فعلی نمایش داده نمی‌شود</span
>
} @else {
<span class="text-[var(--text-muted)]"
>کلید در حافظه نگهداری می‌شود و ذخیره نمی‌شود</span
>
}
</div>
</div>
<!-- Service URL -->
<div class="form-field">
<label class="form-label">آدرس سرویس</label>
<input
type="url"
class="form-input w-full"
[value]="config().serviceUrl"
(input)="onServiceUrlChange($any($event.target).value)"
[disabled]="!serviceUrlEditable()"
[attr.aria-label]="'آدرس سرویس ' + title()"
/>
@if (!serviceUrlEditable()) {
<span class="text-[var(--text-muted)] mt-1 text-xs"
>آدرس استاندارد {{ config().provider === 'local' ? 'سرویس محلی' : 'سرویس' }} به‌صورت
پیش‌فرض به کار می‌رود</span
>
}
</div>
<!-- Actions -->
<div class="ai-model-actions flex gap-2 pt-2">
<button type="button" class="btn btn--primary flex-1" (click)="save.emit()">
ذخیره تنظیمات
</button>
<button type="button" class="btn btn--outline flex-1" (click)="testConnection.emit()">
بررسی اتصال
</button>
</div>
</div>
</div>
`,
styleUrl: './ai-model-config-card.component.css',
})
export class AiModelConfigCardComponent {
readonly title = input.required<string>();
readonly task = input.required<AiTask>();
readonly config = input.required<AiModelConfig>();
/** True when a provider API key has genuinely been persisted by the backend. */
readonly connected = input<boolean>(false);
readonly configChange = output<AiModelConfig>();
readonly save = output<void>();
readonly testConnection = output<void>();
readonly providers = computed(() => PROVIDERS_BY_TASK[this.task()]);
readonly modelsForProvider = computed(() => {
const models = MODELS_BY_TASK[this.task()]?.[this.config().provider];
return models ?? [{ value: '', label: 'مدلی یافت نشد' }];
});
readonly apiKeyRequired = computed(() => PROVIDERS[this.config().provider]?.needsApiKey ?? false);
readonly serviceUrlEditable = computed(() => this.config().provider === 'local');
private emitChange(patch: Partial<AiModelConfig>): void {
this.configChange.emit({ ...this.config(), ...patch });
}
onProviderChange(value: string): void {
const next = value as AiProvider;
const defaults = DEFAULT_CONFIG_FOR[next];
this.emitChange({
provider: next,
model: defaults.model,
serviceUrl: defaults.serviceUrl,
});
}
onModelChange(value: string): void {
this.emitChange({ model: value });
}
onApiKeyChange(value: string): void {
this.emitChange({ apiKey: value, apiKeyVisible: this.config().apiKeyVisible });
}
toggleApiKeyVisibility(): void {
this.emitChange({ apiKeyVisible: !this.config().apiKeyVisible });
}
onServiceUrlChange(value: string): void {
this.emitChange({ serviceUrl: value });
}
apiKeyPlaceholder(): string {
return this.apiKeyRequired() ? 'کلید API خود را وارد کنید' : 'اختیاری';
}
apiKeyAriaLabel(): string {
return this.config().apiKeyVisible ? 'کلید API (قابل رؤیت)' : 'کلید API (مخفی)';
}
}
const PROVIDERS: Record<AiProvider, ProviderOption> = {
openai: { value: 'openai', label: 'OpenAI', needsApiKey: true },
gemini: { value: 'gemini', label: 'Gemini', needsApiKey: true },
local: { value: 'local', label: 'Local', needsApiKey: false },
};
/** Provider option shown for the self-hosted «مدل‌های داخلی». */
const INTERNAL_PROVIDER: ProviderOption = {
value: 'local',
label: 'سرویس داخلی',
needsApiKey: false,
};
const PROVIDCERS_BY_TASK_FALLBACK: Record<AiTask, ProviderOption[]> = {
text: [PROVIDERS.openai, PROVIDERS.gemini, PROVIDERS.local],
embedding: [PROVIDERS.openai, PROVIDERS.gemini, PROVIDERS.local],
ocr: [PROVIDERS.openai, PROVIDERS.gemini, PROVIDERS.local],
// «مدل‌های داخلی» run on the organization's own infrastructure, so the only
// provider option is the internal service endpoint.
stt: [INTERNAL_PROVIDER],
tts: [INTERNAL_PROVIDER],
dialogue: [INTERNAL_PROVIDER],
};
const PROVIDERS_BY_TASK: Record<AiTask, ProviderOption[]> = PROVIDCERS_BY_TASK_FALLBACK;
const DEFAULT_CONFIG_FOR: Record<AiProvider, { model: string; serviceUrl: string }> = {
openai: { model: '', serviceUrl: 'https://api.openai.com/v1' },
gemini: { model: '', serviceUrl: 'https://generativelanguage.googleapis.com/v1' },
local: { model: '', serviceUrl: 'http://localhost:8000' },
};
const MODEL_OPTION = (value: string, label: string): ModelOption => ({ value, label });
const MODELS_BY_TASK: Record<AiTask, Partial<Record<AiProvider, ModelOption[]>>> = {
text: {
openai: [
MODEL_OPTION('gpt-4o', 'GPT-4o'),
MODEL_OPTION('gpt-4o-mini', 'GPT-4o mini'),
MODEL_OPTION('gpt-4-turbo', 'GPT-4 Turbo'),
MODEL_OPTION('gpt-3.5-turbo', 'GPT-3.5 Turbo'),
],
gemini: [
MODEL_OPTION('gemini-2.0-flash', 'Gemini 2.0 Flash'),
MODEL_OPTION('gemini-2.5-pro', 'Gemini 2.5 Pro'),
MODEL_OPTION('gemini-1.5-flash', 'Gemini 1.5 Flash'),
MODEL_OPTION('gemini-1.5-pro', 'Gemini 1.5 Pro'),
],
local: [MODEL_OPTION('', 'سفارشی')],
},
embedding: {
openai: [
MODEL_OPTION('text-embedding-3-small', 'text-embedding-3-small'),
MODEL_OPTION('text-embedding-3-large', 'text-embedding-3-large'),
MODEL_OPTION('text-embedding-ada-002', 'text-embedding-ada-002'),
],
gemini: [MODEL_OPTION('text-embedding-004', 'text-embedding-004')],
local: [MODEL_OPTION('', 'سفارشی')],
},
ocr: {
openai: [
MODEL_OPTION('gpt-4o', 'GPT-4o (چشم‌پوشی)'),
MODEL_OPTION('gpt-4o-mini', 'GPT-4o mini (چشم‌پوشی)'),
],
gemini: [
MODEL_OPTION('gemini-1.5-pro', 'Gemini 1.5 Pro (چشم‌پوشی)'),
MODEL_OPTION('gemini-2.0-flash', 'Gemini 2.0 Flash (چشم‌پوشی)'),
],
local: [MODEL_OPTION('', 'سفارشی')],
},
// «مدل‌های داخلی» — self-hosted speech and dialogue models of the call center.
stt: {
local: [
MODEL_OPTION('whisper-large-v3', 'Whisper Large v3'),
MODEL_OPTION('parrotnet-v2', 'ParrotNet v2 (فارسی)'),
MODEL_OPTION('fastconformer-fa', 'FastConformer فارسی'),
],
},
tts: {
local: [
MODEL_OPTION('xtts-v2', 'Coqui XTTS v2'),
MODEL_OPTION('vits-fa', 'VITS فارسی'),
MODEL_OPTION('piper-fa', 'Piper فارسی'),
],
},
dialogue: {
local: [
MODEL_OPTION('llama-3.1-70b', 'Llama 3.1 70B'),
MODEL_OPTION('dorna-8b', 'Dorna 8B (پارسی)'),
MODEL_OPTION('qwen2.5-72b', 'Qwen2.5 72B'),
],
},
};
@@ -0,0 +1,137 @@
.bar-chart {
display: flex;
flex-direction: column;
gap: 1.1rem;
margin: 0;
padding: 0;
list-style: none;
}
.bar-row {
position: relative;
}
.bar-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 0.75rem;
margin-bottom: 0.4rem;
}
.bar-label {
font-size: 0.8125rem;
color: var(--text-secondary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.bar-metrics {
display: flex;
align-items: baseline;
gap: 0.5rem;
flex-shrink: 0;
}
.bar-value {
font-size: 0.8125rem;
font-weight: 600;
color: var(--text-primary);
}
.bar-share {
font-size: 0.6875rem;
color: var(--text-muted);
}
.bar-track {
position: relative;
height: 12px;
border-radius: 9999px;
background: var(--bar-track-bg, rgba(100, 116, 139, 0.16));
cursor: default;
}
.bar-fill {
height: 100%;
border-radius: 9999px;
background: var(--bar-color);
transform-origin: right center;
animation: barGrow 0.7s cubic-bezier(0.22, 1, 0.36, 1) both;
}
.bar-tooltip {
position: absolute;
bottom: calc(100% + 8px);
z-index: 20;
display: flex;
flex-direction: column;
gap: 0.15rem;
min-width: max-content;
max-width: 260px;
padding: 0.55rem 0.75rem;
border: 1px solid var(--card-border);
border-radius: 0.75rem;
background: var(--surface-bg);
box-shadow: 0 12px 32px rgba(15, 23, 42, 0.18);
transform: translateX(50%);
pointer-events: none;
animation: fadeIn 0.15s ease-out;
}
.bar-tooltip-title {
font-size: 0.8125rem;
font-weight: 600;
color: var(--text-primary);
line-height: 1.5;
}
.bar-tooltip-row {
font-size: 0.75rem;
color: var(--text-secondary);
}
.bar-tooltip-hint {
font-size: 0.6875rem;
color: var(--text-muted);
}
.chart-empty {
padding: 2.5rem 1rem;
text-align: center;
font-size: 0.875rem;
color: var(--text-muted);
}
@keyframes barGrow {
from {
transform: scaleX(0);
}
to {
transform: scaleX(1);
}
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@media (prefers-reduced-motion: reduce) {
.bar-fill {
animation: none;
}
}
:host-context([data-bs-theme='dark']) .bar-track {
background: rgba(148, 163, 184, 0.22);
}
:host-context([data-bs-theme='dark']) .bar-tooltip {
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.5);
}
@@ -0,0 +1,42 @@
@if (items().length) {
<ul class="bar-chart" role="list" [attr.aria-label]="ariaLabel()">
@for (item of items(); track item.label; let index = $index) {
<li class="bar-row">
<div class="bar-head">
<span class="bar-label" [title]="item.label">{{ item.label }}</span>
<span class="bar-metrics">
<span class="bar-value">{{ format(item.value) }}</span>
<span class="bar-share">{{ share(item.value) }}</span>
</span>
</div>
<div
class="bar-track"
[style.--bar-color]="item.color"
(mouseenter)="onTrackMove(index, $event)"
(mousemove)="onTrackMove(index, $event)"
(mouseleave)="onTrackLeave()"
>
<div class="bar-fill" [style.width]="barWidth(item.value)"></div>
</div>
@if (activeIndex() === index) {
<div
class="bar-tooltip"
role="tooltip"
[style.inset-inline-start]="tooltipX() + 'px'"
>
<strong class="bar-tooltip-title">{{ item.label }}</strong>
<span class="bar-tooltip-row">تعداد: {{ format(item.value) }}</span>
<span class="bar-tooltip-row">سهم: {{ share(item.value) }}</span>
@if (item.hint) {
<span class="bar-tooltip-hint">{{ item.hint }}</span>
}
</div>
}
</li>
}
</ul>
} @else {
<p class="chart-empty">{{ emptyText() }}</p>
}
@@ -0,0 +1,57 @@
import { ChangeDetectionStrategy, Component, computed, input, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { formatCount, formatPercent } from '../../utils/format.util';
export interface BarChartItem {
label: string;
value: number;
color: string;
hint?: string;
}
@Component({
selector: 'app-bar-chart',
standalone: true,
imports: [CommonModule],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './bar-chart.component.html',
styleUrl: './bar-chart.component.css',
})
export class BarChartComponent {
readonly items = input.required<BarChartItem[]>();
readonly valueSuffix = input<string>('');
readonly emptyText = input<string>('داده‌ای برای نمایش نیست');
readonly ariaLabel = input<string>('نمودار میله‌ای');
readonly activeIndex = signal<number | null>(null);
readonly tooltipX = signal(0);
readonly total = computed(() => this.items().reduce((sum, item) => sum + item.value, 0));
readonly max = computed(() => {
const values = this.items().map((item) => item.value);
return values.length ? Math.max(...values) : 0;
});
barWidth(value: number): string {
return this.max() > 0 ? `${(value / this.max()) * 100}%` : '0%';
}
share(value: number): string {
return this.total() > 0 ? formatPercent((value / this.total()) * 100) : '۰٪';
}
format(value: number): string {
return `${formatCount(value)}${this.valueSuffix()}`;
}
onTrackMove(index: number, event: MouseEvent): void {
const track = event.currentTarget as HTMLElement;
const rect = track.getBoundingClientRect();
this.tooltipX.set(event.clientX - rect.left);
this.activeIndex.set(index);
}
onTrackLeave(): void {
this.activeIndex.set(null);
}
}

Some files were not shown because too many files have changed in this diff Show More