16 Commits
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
57 changed files with 5141 additions and 1039 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.
+5 -7
View File
@@ -26,22 +26,20 @@
"output": "assets" "output": "assets"
} }
], ],
"styles": [ "styles": ["node_modules/ngx-toastr/toastr.css", "src/styles.css"]
"src/styles.css"
]
}, },
"configurations": { "configurations": {
"production": { "production": {
"budgets": [ "budgets": [
{ {
"type": "initial", "type": "initial",
"maximumWarning": "1.5MB", "maximumWarning": "2MB",
"maximumError": "2MB" "maximumError": "3MB"
}, },
{ {
"type": "anyComponentStyle", "type": "anyComponentStyle",
"maximumWarning": "8kB", "maximumWarning": "20kB",
"maximumError": "12kB" "maximumError": "30kB"
} }
], ],
"outputHashing": "all" "outputHashing": "all"
+129 -62
View File
@@ -21,6 +21,7 @@
"@popperjs/core": "^2.11.8", "@popperjs/core": "^2.11.8",
"ag-grid-angular": "^36.2.0", "ag-grid-angular": "^36.2.0",
"ag-grid-community": "^36.2.0", "ag-grid-community": "^36.2.0",
"moment-jalaali": "^0.10.5",
"ngx-toastr": "^14.3.0", "ngx-toastr": "^14.3.0",
"papaparse": "^5.7.0", "papaparse": "^5.7.0",
"rxjs": "~7.8.0", "rxjs": "~7.8.0",
@@ -34,6 +35,8 @@
"@playwright/test": "^1.63.0", "@playwright/test": "^1.63.0",
"@tailwindcss/postcss": "^4.3.3", "@tailwindcss/postcss": "^4.3.3",
"@types/audioworklet": "^0.0.100", "@types/audioworklet": "^0.0.100",
"@types/moment": "^2.11.29",
"@types/moment-jalaali": "^0.7.9",
"@types/papaparse": "^5.5.2", "@types/papaparse": "^5.5.2",
"@types/three": "^0.186.0", "@types/three": "^0.186.0",
"jsdom": "^30.1.2", "jsdom": "^30.1.2",
@@ -541,7 +544,6 @@
"version": "20.3.33", "version": "20.3.33",
"resolved": "https://registry.npmjs.org/@angular/compiler-cli/-/compiler-cli-20.3.33.tgz", "resolved": "https://registry.npmjs.org/@angular/compiler-cli/-/compiler-cli-20.3.33.tgz",
"integrity": "sha512-NKE4N4ssXysHLJQ7xVqvAv/yf3JfJxaFz5H+Ue+EnYToAmTxXe7uyt2MPRIydef/H63n7O9uphVp5P5GkRxVuA==", "integrity": "sha512-NKE4N4ssXysHLJQ7xVqvAv/yf3JfJxaFz5H+Ue+EnYToAmTxXe7uyt2MPRIydef/H63n7O9uphVp5P5GkRxVuA==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@babel/core": "7.29.7", "@babel/core": "7.29.7",
@@ -613,6 +615,31 @@
"rxjs": "^6.5.3 || ^7.4.0" "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": { "node_modules/@angular/platform-browser": {
"version": "20.3.33", "version": "20.3.33",
"resolved": "https://registry.npmjs.org/@angular/platform-browser/-/platform-browser-20.3.33.tgz", "resolved": "https://registry.npmjs.org/@angular/platform-browser/-/platform-browser-20.3.33.tgz",
@@ -710,7 +737,6 @@
"version": "7.29.7", "version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
"integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@babel/helper-validator-identifier": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7",
@@ -725,7 +751,6 @@
"version": "7.29.7", "version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz",
"integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=6.9.0" "node": ">=6.9.0"
@@ -735,7 +760,6 @@
"version": "7.29.7", "version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz",
"integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@babel/code-frame": "^7.29.7", "@babel/code-frame": "^7.29.7",
@@ -766,14 +790,12 @@
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
"integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/@babel/core/node_modules/semver": { "node_modules/@babel/core/node_modules/semver": {
"version": "6.3.1", "version": "6.3.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
"integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"license": "ISC", "license": "ISC",
"bin": { "bin": {
"semver": "bin/semver.js" "semver": "bin/semver.js"
@@ -783,7 +805,6 @@
"version": "7.29.8", "version": "7.29.8",
"resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz", "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz",
"integrity": "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==", "integrity": "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@babel/parser": "^7.29.8", "@babel/parser": "^7.29.8",
@@ -813,7 +834,6 @@
"version": "7.29.7", "version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz",
"integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@babel/compat-data": "^7.29.7", "@babel/compat-data": "^7.29.7",
@@ -830,7 +850,6 @@
"version": "6.3.1", "version": "6.3.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
"integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"license": "ISC", "license": "ISC",
"bin": { "bin": {
"semver": "bin/semver.js" "semver": "bin/semver.js"
@@ -840,7 +859,6 @@
"version": "7.29.7", "version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz",
"integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=6.9.0" "node": ">=6.9.0"
@@ -850,7 +868,6 @@
"version": "7.29.7", "version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz",
"integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@babel/traverse": "^7.29.7", "@babel/traverse": "^7.29.7",
@@ -864,7 +881,6 @@
"version": "7.29.7", "version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz",
"integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@babel/helper-module-imports": "^7.29.7", "@babel/helper-module-imports": "^7.29.7",
@@ -895,7 +911,6 @@
"version": "7.29.7", "version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
"integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=6.9.0" "node": ">=6.9.0"
@@ -905,7 +920,6 @@
"version": "7.29.7", "version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
"integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=6.9.0" "node": ">=6.9.0"
@@ -915,7 +929,6 @@
"version": "7.29.7", "version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz",
"integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=6.9.0" "node": ">=6.9.0"
@@ -925,7 +938,6 @@
"version": "7.29.7", "version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz", "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz",
"integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==", "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@babel/template": "^7.29.7", "@babel/template": "^7.29.7",
@@ -939,7 +951,6 @@
"version": "7.29.9", "version": "7.29.9",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz", "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz",
"integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==", "integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@babel/types": "^7.29.8" "@babel/types": "^7.29.8"
@@ -955,7 +966,6 @@
"version": "7.29.7", "version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz",
"integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@babel/code-frame": "^7.29.7", "@babel/code-frame": "^7.29.7",
@@ -970,7 +980,6 @@
"version": "7.29.8", "version": "7.29.8",
"resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.8.tgz", "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.8.tgz",
"integrity": "sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==", "integrity": "sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@babel/code-frame": "^7.29.7", "@babel/code-frame": "^7.29.7",
@@ -989,7 +998,6 @@
"version": "7.29.8", "version": "7.29.8",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz", "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz",
"integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==", "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@babel/helper-string-parser": "^7.29.7", "@babel/helper-string-parser": "^7.29.7",
@@ -2019,7 +2027,6 @@
"version": "0.3.13", "version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
"integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/sourcemap-codec": "^1.5.0",
@@ -2030,7 +2037,6 @@
"version": "2.3.5", "version": "2.3.5",
"resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",
"integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/gen-mapping": "^0.3.5",
@@ -2041,7 +2047,6 @@
"version": "3.1.2", "version": "3.1.2",
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
"integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=6.0.0" "node": ">=6.0.0"
@@ -2051,14 +2056,12 @@
"version": "1.6.0", "version": "1.6.0",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
"integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/@jridgewell/trace-mapping": { "node_modules/@jridgewell/trace-mapping": {
"version": "0.3.31", "version": "0.3.31",
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
"integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/resolve-uri": "^3.1.0",
@@ -4100,6 +4103,51 @@
"dev": true, "dev": true,
"license": "Apache-2.0" "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": { "node_modules/@types/chai": {
"version": "5.2.3", "version": "5.2.3",
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
@@ -4125,6 +4173,23 @@
"dev": true, "dev": true,
"license": "MIT" "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": { "node_modules/@types/node": {
"version": "26.6.4", "version": "26.6.4",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.4.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.4.tgz",
@@ -4460,7 +4525,6 @@
"version": "6.4.0", "version": "6.4.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz",
"integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==", "integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=12" "node": ">=12"
@@ -4473,7 +4537,6 @@
"version": "6.2.3", "version": "6.2.3",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
"integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=12" "node": ">=12"
@@ -4496,7 +4559,6 @@
"version": "2.11.27", "version": "2.11.27",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.27.tgz", "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.27.tgz",
"integrity": "sha512-ElY12DaROGuan+lMmZ8Cvo/ZUbXPe7Enc/9VU/b1T3Kp4dwytRcNdR8DoSJN5SNJT/CuvcCA0DHDVmMOCePdRQ==", "integrity": "sha512-ElY12DaROGuan+lMmZ8Cvo/ZUbXPe7Enc/9VU/b1T3Kp4dwytRcNdR8DoSJN5SNJT/CuvcCA0DHDVmMOCePdRQ==",
"dev": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"bin": { "bin": {
"baseline-browser-mapping": "dist/cli.cjs" "baseline-browser-mapping": "dist/cli.cjs"
@@ -4585,7 +4647,6 @@
"version": "4.29.3", "version": "4.29.3",
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.3.tgz", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.3.tgz",
"integrity": "sha512-1R4kiYKXGViqEN0CnoDrXc1StD9niAwu+j2dukWzrD4bJgsD4lDmEp0CRbc6E/vYJIfTHwPmwyaKtVSudICdPA==", "integrity": "sha512-1R4kiYKXGViqEN0CnoDrXc1StD9niAwu+j2dukWzrD4bJgsD4lDmEp0CRbc6E/vYJIfTHwPmwyaKtVSudICdPA==",
"dev": true,
"funding": [ "funding": [
{ {
"type": "opencollective", "type": "opencollective",
@@ -4766,7 +4827,6 @@
"version": "1.0.30001814", "version": "1.0.30001814",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001814.tgz", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001814.tgz",
"integrity": "sha512-/Uaf1lAzr59XcMpW0o96WoEfr+VXK2OX4U9AgFoiSHsVJ4HppnIFUjtYzsyDH2+tgANaQb2/oxYGwCPapN1FpA==", "integrity": "sha512-/Uaf1lAzr59XcMpW0o96WoEfr+VXK2OX4U9AgFoiSHsVJ4HppnIFUjtYzsyDH2+tgANaQb2/oxYGwCPapN1FpA==",
"dev": true,
"funding": [ "funding": [
{ {
"type": "opencollective", "type": "opencollective",
@@ -4834,7 +4894,6 @@
"version": "4.0.3", "version": "4.0.3",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz",
"integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"readdirp": "^4.0.1" "readdirp": "^4.0.1"
@@ -4916,7 +4975,6 @@
"version": "9.0.1", "version": "9.0.1",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz", "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz",
"integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==", "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==",
"dev": true,
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"string-width": "^7.2.0", "string-width": "^7.2.0",
@@ -4931,7 +4989,6 @@
"version": "9.0.2", "version": "9.0.2",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",
"integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"ansi-styles": "^6.2.1", "ansi-styles": "^6.2.1",
@@ -5000,7 +5057,6 @@
"version": "1.9.0", "version": "1.9.0",
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz",
"integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==", "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/cookie": { "node_modules/cookie": {
@@ -5118,7 +5174,6 @@
"version": "4.4.3", "version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"ms": "^2.1.3" "ms": "^2.1.3"
@@ -5254,14 +5309,12 @@
"version": "1.5.444", "version": "1.5.444",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.444.tgz", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.444.tgz",
"integrity": "sha512-5ss/uJfoDYDHT0lfJzT6FbcskIzROIOPf0BbbFkGcvDzoJU7i//9GDrwwIHQVmIsrAGiF3ihpADBRIsrEFt1rQ==", "integrity": "sha512-5ss/uJfoDYDHT0lfJzT6FbcskIzROIOPf0BbbFkGcvDzoJU7i//9GDrwwIHQVmIsrAGiF3ihpADBRIsrEFt1rQ==",
"dev": true,
"license": "ISC" "license": "ISC"
}, },
"node_modules/emoji-regex": { "node_modules/emoji-regex": {
"version": "10.6.0", "version": "10.6.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",
"integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/encodeurl": { "node_modules/encodeurl": {
@@ -5410,7 +5463,6 @@
"version": "3.2.0", "version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
"integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=6" "node": ">=6"
@@ -5575,7 +5627,6 @@
"version": "6.5.0", "version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=12.0.0" "node": ">=12.0.0"
@@ -5680,7 +5731,6 @@
"version": "1.0.0-beta.2", "version": "1.0.0-beta.2",
"resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
"integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=6.9.0" "node": ">=6.9.0"
@@ -5690,7 +5740,6 @@
"version": "2.0.5", "version": "2.0.5",
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
"dev": true,
"license": "ISC", "license": "ISC",
"engines": { "engines": {
"node": "6.* || 8.* || >= 10.*" "node": "6.* || 8.* || >= 10.*"
@@ -5700,7 +5749,6 @@
"version": "1.7.0", "version": "1.7.0",
"resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz", "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz",
"integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==", "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=18" "node": ">=18"
@@ -6177,6 +6225,12 @@
"node": ">=10" "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": { "node_modules/jiti": {
"version": "2.7.0", "version": "2.7.0",
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",
@@ -6201,7 +6255,6 @@
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/jsdom": { "node_modules/jsdom": {
@@ -6268,7 +6321,6 @@
"version": "3.1.0", "version": "3.1.0",
"resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",
"integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==",
"dev": true,
"license": "MIT", "license": "MIT",
"bin": { "bin": {
"jsesc": "bin/jsesc" "jsesc": "bin/jsesc"
@@ -6305,7 +6357,6 @@
"version": "2.2.3", "version": "2.2.3",
"resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
"integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
"dev": true,
"license": "MIT", "license": "MIT",
"bin": { "bin": {
"json5": "lib/cli.js" "json5": "lib/cli.js"
@@ -6775,7 +6826,6 @@
"version": "5.1.1", "version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
"integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
"dev": true,
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"yallist": "^3.0.2" "yallist": "^3.0.2"
@@ -7049,6 +7099,38 @@
"node": ">= 18" "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": { "node_modules/mrmime": {
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz", "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz",
@@ -7063,7 +7145,6 @@
"version": "2.1.3", "version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/msgpackr": { "node_modules/msgpackr": {
@@ -7263,7 +7344,6 @@
"version": "2.0.57", "version": "2.0.57",
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.57.tgz", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.57.tgz",
"integrity": "sha512-kQK9LGGFiHtrWiNhZtA7Qbw17AQz+dmsEKODRIVTXA9+e5MS/2gZEBhYJt13GrAz5/IOZKddH/0Z3TP/Zgo+yw==", "integrity": "sha512-kQK9LGGFiHtrWiNhZtA7Qbw17AQz+dmsEKODRIVTXA9+e5MS/2gZEBhYJt13GrAz5/IOZKddH/0Z3TP/Zgo+yw==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=18" "node": ">=18"
@@ -7726,14 +7806,12 @@
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
"dev": true,
"license": "ISC" "license": "ISC"
}, },
"node_modules/picomatch": { "node_modules/picomatch": {
"version": "4.0.4", "version": "4.0.4",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=12" "node": ">=12"
@@ -8004,7 +8082,6 @@
"version": "4.1.2", "version": "4.1.2",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",
"integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">= 14.18.0" "node": ">= 14.18.0"
@@ -8018,7 +8095,6 @@
"version": "0.2.2", "version": "0.2.2",
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
"integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",
"dev": true,
"license": "Apache-2.0" "license": "Apache-2.0"
}, },
"node_modules/require-from-string": { "node_modules/require-from-string": {
@@ -8192,7 +8268,6 @@
"version": "7.7.2", "version": "7.7.2",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz", "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz",
"integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==", "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==",
"dev": true,
"license": "ISC", "license": "ISC",
"bin": { "bin": {
"semver": "bin/semver.js" "semver": "bin/semver.js"
@@ -8570,7 +8645,6 @@
"version": "7.2.0", "version": "7.2.0",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",
"integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"emoji-regex": "^10.3.0", "emoji-regex": "^10.3.0",
@@ -8588,7 +8662,6 @@
"version": "7.2.0", "version": "7.2.0",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",
"integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"ansi-regex": "^6.2.2" "ansi-regex": "^6.2.2"
@@ -8705,7 +8778,6 @@
"version": "0.2.14", "version": "0.2.14",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz",
"integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==", "integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"fdir": "^6.4.4", "fdir": "^6.4.4",
@@ -8872,7 +8944,7 @@
"version": "5.9.3", "version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true, "devOptional": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"bin": { "bin": {
"tsc": "bin/tsc", "tsc": "bin/tsc",
@@ -8913,7 +8985,6 @@
"version": "1.3.3", "version": "1.3.3",
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.3.tgz", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.3.tgz",
"integrity": "sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==", "integrity": "sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==",
"dev": true,
"funding": [ "funding": [
{ {
"type": "opencollective", "type": "opencollective",
@@ -9365,7 +9436,6 @@
"version": "5.0.8", "version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
"integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
"dev": true,
"license": "ISC", "license": "ISC",
"engines": { "engines": {
"node": ">=10" "node": ">=10"
@@ -9375,14 +9445,12 @@
"version": "3.1.1", "version": "3.1.1",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
"integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",
"dev": true,
"license": "ISC" "license": "ISC"
}, },
"node_modules/yargs": { "node_modules/yargs": {
"version": "18.0.0", "version": "18.0.0",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-18.0.0.tgz", "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.0.0.tgz",
"integrity": "sha512-4UEqdc2RYGHZc7Doyqkrqiln3p9X2DZVxaGbwhn2pi7MrRagKaOcIKe8L3OxYcbhXLgLFUS3zAYuQjKBQgmuNg==", "integrity": "sha512-4UEqdc2RYGHZc7Doyqkrqiln3p9X2DZVxaGbwhn2pi7MrRagKaOcIKe8L3OxYcbhXLgLFUS3zAYuQjKBQgmuNg==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"cliui": "^9.0.1", "cliui": "^9.0.1",
@@ -9400,7 +9468,6 @@
"version": "22.0.0", "version": "22.0.0",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz", "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz",
"integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==", "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==",
"dev": true,
"license": "ISC", "license": "ISC",
"engines": { "engines": {
"node": "^20.19.0 || ^22.12.0 || >=23" "node": "^20.19.0 || ^22.12.0 || >=23"
+3
View File
@@ -35,6 +35,7 @@
"@popperjs/core": "^2.11.8", "@popperjs/core": "^2.11.8",
"ag-grid-angular": "^36.2.0", "ag-grid-angular": "^36.2.0",
"ag-grid-community": "^36.2.0", "ag-grid-community": "^36.2.0",
"moment-jalaali": "^0.10.5",
"ngx-toastr": "^14.3.0", "ngx-toastr": "^14.3.0",
"papaparse": "^5.7.0", "papaparse": "^5.7.0",
"rxjs": "~7.8.0", "rxjs": "~7.8.0",
@@ -48,6 +49,8 @@
"@playwright/test": "^1.63.0", "@playwright/test": "^1.63.0",
"@tailwindcss/postcss": "^4.3.3", "@tailwindcss/postcss": "^4.3.3",
"@types/audioworklet": "^0.0.100", "@types/audioworklet": "^0.0.100",
"@types/moment": "^2.11.29",
"@types/moment-jalaali": "^0.7.9",
"@types/papaparse": "^5.5.2", "@types/papaparse": "^5.5.2",
"@types/three": "^0.186.0", "@types/three": "^0.186.0",
"jsdom": "^30.1.2", "jsdom": "^30.1.2",
+9 -2
View File
@@ -1,7 +1,14 @@
{ {
"/api": { "/api": {
"target": "http://127.0.0.1:8080", "target": "http://192.168.180.151:8080",
"secure": false,
"changeOrigin": true,
"ws": true, "ws": true,
"changeOrigin": false "logLevel": "debug"
},
"/users": {
"target": "http://192.168.180.151:8080",
"secure": false,
"changeOrigin": true
} }
} }
Binary file not shown.
Binary file not shown.
+219 -54
View File
@@ -1,105 +1,242 @@
/** /**
* Streaming PCM16 playback (contract: 24 kHz mono PCM16LE output, no WAV header). * Streaming PCM16 playback (contract: 24 kHz mono PCM16LE output, no WAV header).
* *
* Bounded playout queue: at most BOUND_SAMPLES (96,000 bytes) of source audio is admitted. * Bounded playout queue. The cap is on OUTSTANDING SOURCE PCM — BOUND_BYTES (96,000 bytes
* When it fills, the processor reports `overflow` and the call must fail safely — PCM is * = 48,000 source samples ≈ 2 s at 24 kHz mono PCM16) — and each stage uses ONE unit
* never silently dropped to keep the same context alive. * 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.
* *
* Real playback progress: `played_ms` is computed from the source samples actually * End-of-turn tail: the resample loop keeps the window's last sample as `prev` (for
* consumed by `process()` per audio_ref (never an elapsed timer), kept cumulative per ref * cross-chunk continuity) and only emits it at the start of the NEXT chunk. At the final
* and reported roughly 4×/s, on ref changes, and on clear/flush/idle — so the main thread * chunk there is no next chunk, so without an explicit flush the last source sample is never
* can send the contract's `playback_progress` control message. * 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 } * Messages in: { type: 'push', pcm: ArrayBuffer (Int16 mono), sampleRate, audioRef }
* { type: 'clear' } barge-in: drop everything immediately * { type: 'clear' } barge-in: drop everything immediately
* { type: 'flush' } end of turn: play what is left, then report 'idle' * { type: 'flush', audioRef } end of turn: emit the tail, play what is left, then idle
* Messages out: { type: 'progress', audioRef, playedMs } * Messages out: { type: 'progress', audioRef, playedMs }
* { type: 'idle' } buffer ran dry after playing * { type: 'idle', audioRef } buffer ran dry after playing
* { type: 'overflow' } bounded queue filled — caller fails the session safely * { type: 'overflow' } bounded queue filled — caller fails the session safely
*/ */
const BOUND_BYTES = 96000; // contract cap for the playback queue 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; const REPORT_INTERVAL_MS = 250;
class PcmPlaybackProcessor extends AudioWorkletProcessor { class PcmPlaybackProcessor extends AudioWorkletProcessor {
constructor() { constructor() {
super(); super();
this.capacity = Math.floor(BOUND_BYTES / 2); // source samples (PCM16) 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.buf = new Float32Array(this.capacity);
this.r = 0; this.r = 0;
this.w = 0; this.w = 0;
this.count = 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.prebuffer = Math.floor(sampleRate * 0.08); // jitter buffer before (re)starting
this.started = false; this.started = false;
this.prev = 0; this.prev = 0;
this.pos = 1; this.pos = 1;
this.ratio = 1; // source samples per output sample, set per push // End-of-turn tail accounting (per turn, reset on flush/clear). `admittedSrc` +
this.currentRef = null; // `emittedOut` let flush() emit the exact OUTPUT count for all admitted source; the last
this.refPlayedSamples = new Map(); // cumulative consumed source samples per audio_ref // chunk window is retained so the tail can be interpolated correctly.
this.unreportedSamples = 0; 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.overflowPosted = false;
this.port.onmessage = (e) => { this.port.onmessage = (e) => {
const m = e.data; const m = e.data;
if (!m) return; if (!m) return;
if (m.type === 'push') this.push(new Int16Array(m.pcm), m.sampleRate, m.audioRef || null); 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 === 'clear') this.clear();
else if (m.type === 'flush') this.flush(); 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() { 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.r = this.w = this.count = 0;
this.queuedSource = 0;
this.refQueue.length = 0;
this.started = false; this.started = false;
this.prev = 0; this.prev = 0;
this.pos = 1; this.pos = 1;
this.reportProgress(true); // final report for the interrupted ref // 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() { flush(audioRef = this.pendingRef) {
this.finalizeTail(); // emit the deferred tail so every admitted sample becomes output
if (this.count === 0) { if (this.count === 0) {
this.started = false; this.started = false;
this.reportProgress(true); this.reportFinal();
this.port.postMessage({ type: 'idle' }); this.port.postMessage({ type: 'idle', audioRef: audioRef || this.pendingRef });
} else { } else {
this.started = true; // short tail: do not wait for the prebuffer this.started = true; // play the remaining audio + tail without waiting for the prebuffer
} }
} }
/**
* End-of-turn tail: emit the OUTPUT samples for every admitted SOURCE sample that the push
* loop deferred (it keeps the window's last sample as `prev` for cross-chunk continuity and
* only emits it at the start of the next chunk). Continuing the interpolation past the last
* sample — holding its value — produces real output so fully played audio leaves queued
* source at zero and played_ms reflects the true duration (never fabricated upward).
*/
finalizeTail() {
const src = this.windowSrc;
const n = this.windowN;
if (src && n > 0) {
const target = Math.round(this.admittedSrc / this.ratio); // exact OUTPUT count for the turn
let pos = n + this.pos; // continue from where the push loop stopped (abs. in this window)
while (this.emittedOut < target) {
const base = Math.min(Math.floor(pos), n);
const frac = Math.min(1, Math.max(0, pos - base));
const a = src[base];
const b = src[Math.min(base + 1, n)]; // clamp: hold the last sample past the boundary
this.write(a * (1 - frac) + b * frac);
this.creditQueue(1); // the emitted tail belongs to the current (last) ref
this.emittedOut++;
pos += this.ratio;
}
}
// Each turn is an independent signal: reset the resampler for the next one.
this.admittedSrc = 0;
this.emittedOut = 0;
this.windowSrc = null;
this.windowN = 0;
this.pos = 1;
this.prev = 0;
}
push(int16, srcRate, audioRef) { push(int16, srcRate, audioRef) {
const n = int16.length; const n = int16.length;
if (!n) return; if (!n) return;
// Bounded queue: admitting this chunk past the cap is a safe failure, not a silent drop. const ratio = srcRate / sampleRate; // SOURCE samples per OUTPUT sample
if (this.count + n > this.capacity) { this.configure(ratio);
if (!this.overflowPosted) {
this.overflowPosted = true; // OUTPUT samples this chunk's main loop will add — an upper bound on the exact count.
this.port.postMessage({ type: 'overflow' }); 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; return;
} }
this.ratio = srcRate / sampleRate; // source samples per output sample
const src = new Float32Array(n + 1); const src = new Float32Array(n + 1);
src[0] = this.prev; src[0] = this.prev;
for (let i = 0; i < n; i++) src[i + 1] = int16[i] / 32768; for (let i = 0; i < n; i++) src[i + 1] = int16[i] / 32768;
// Retain this window so flush() can emit the deferred tail correctly.
this.windowSrc = src;
this.windowN = n;
let pos = this.pos; let pos = this.pos;
let mainOut = 0;
while (pos < n) { while (pos < n) {
const i = Math.floor(pos); const i = Math.floor(pos);
const frac = pos - i; const frac = pos - i;
this.write(src[i] * (1 - frac) + src[i + 1] * frac); this.write(src[i] * (1 - frac) + src[i + 1] * frac);
mainOut++;
pos += this.ratio; pos += this.ratio;
} }
this.prev = src[n]; this.prev = src[n];
this.pos = pos - n; this.pos = pos - n;
this.emittedOut += mainOut;
this.pendingRef = audioRef;
this.creditQueue(mainOut); // attribute this chunk's OUTPUT to its audio_ref
}
if (audioRef !== this.currentRef) { /** Adds `out` OUTPUT samples to the current ref's span (merging consecutive same-ref pushes). */
this.reportProgress(true); // final report for the ref that just ended creditQueue(out) {
this.currentRef = audioRef; const ref = this.pendingRef;
this.reportProgress(true); 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) { 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.buf[this.w] = v;
this.w = (this.w + 1) % this.capacity; this.w = (this.w + 1) % this.capacity;
this.count++; this.count++;
@@ -123,21 +260,17 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
ch0[i] = 0; ch0[i] = 0;
} }
} }
if (this.currentRef && played > 0) { if (played > 0) {
// Convert consumed output samples back to contract (source) samples. this.queuedSource = Math.max(0, this.queuedSource - played * this.ratio); // OUTPUT→SOURCE
const consumed = played * this.ratio; this.consumeSpans(played);
const ref = this.currentRef; this.reportCadence();
this.refPlayedSamples.set(ref, (this.refPlayedSamples.get(ref) ?? 0) + consumed);
this.unreportedSamples += consumed;
const srcRate = this.ratio * sampleRate;
if ((this.unreportedSamples / srcRate) * 1000 >= REPORT_INTERVAL_MS) {
this.reportProgress(false);
}
} }
if (this.count === 0) { if (this.count === 0) {
// Ring drained: nothing is outstanding, so no phantom source remains for this turn.
this.queuedSource = 0;
this.started = false; this.started = false;
this.reportProgress(true); this.reportFinal();
this.port.postMessage({ type: 'idle' }); this.port.postMessage({ type: 'idle', audioRef: this.pendingRef });
} }
} else { } else {
ch0.fill(0); ch0.fill(0);
@@ -147,15 +280,47 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
return true; return true;
} }
reportProgress(force) { /** Draw `played` OUTPUT samples off the front of the ref FIFO, crediting each ref. */
this.unreportedSamples = 0; consumeSpans(played) {
const ref = this.currentRef; while (played > 0 && this.refQueue.length) {
if (!ref) return; const span = this.refQueue[0];
const srcRate = this.ratio * sampleRate; const take = played < span.out ? played : span.out;
const playedSamples = this.refPlayedSamples.get(ref) ?? 0; span.out -= take;
const playedMs = Math.max(0, Math.round((playedSamples / srcRate) * 1000)); played -= take;
if (playedMs <= 0) return; // nothing has actually been heard for this ref yet this.refPlayedOut.set(span.ref, (this.refPlayedOut.get(span.ref) ?? 0) + take);
this.port.postMessage({ type: 'progress', audioRef: ref, playedMs }); 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 });
} }
} }
+63 -10
View File
@@ -1,12 +1,49 @@
import { ApplicationConfig, provideBrowserGlobalErrorListeners, provideZonelessChangeDetection, APP_INITIALIZER } from '@angular/core'; import {
ApplicationConfig,
provideBrowserGlobalErrorListeners,
provideZonelessChangeDetection,
APP_INITIALIZER,
importProvidersFrom,
ApplicationRef,
Injector,
NgZone,
} from '@angular/core';
import { provideRouter } from '@angular/router'; import { provideRouter } from '@angular/router';
import { provideAnimations } from '@angular/platform-browser/animations'; import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http'; 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 { routes } from './app.routes';
import { AuthService } from './services/auth/auth.service'; 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` * 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 * before the first route activates; a 401 drops the authenticated state so the
@@ -23,18 +60,34 @@ export const appConfig: ApplicationConfig = {
provideRouter(routes), provideRouter(routes),
provideAnimations(), provideAnimations(),
provideHttpClient(), provideHttpClient(),
// Registers ngx-toastr's Toast component + TOAST_CONFIG.
importProvidersFrom(
ToastrModule.forRoot({
timeOut: 4000,
positionClass: 'toast-bottom-left',
preventDuplicates: true,
}),
),
{
// 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, provide: APP_INITIALIZER,
useFactory: initializeAuth, useFactory: initializeAuth,
deps: [AuthService], deps: [AuthService],
multi: true, multi: true,
}, },
{ ],
provide: TOAST_CONFIG,
useValue: {
default: DefaultGlobalConfig,
config: {}
}
}
]
}; };
+2 -2
View File
@@ -32,7 +32,7 @@ export const routes: Routes = [
}, },
{ {
path: '', path: '',
title: 'دستیار هوشمند', title: 'دستیار هوش مصنوعی',
component: HomePage, component: HomePage,
canActivate: [authGuard], canActivate: [authGuard],
}, },
@@ -68,7 +68,7 @@ export const routes: Routes = [
}, },
{ {
path: 'chat-questions', path: 'chat-questions',
title: 'سوالات چت سایت و اپلیکیشن', title: 'سوالات چت وب اپلیکیشن',
component: ChatQuestionsPage, component: ChatQuestionsPage,
canActivate: [authGuard], canActivate: [authGuard],
}, },
+6 -2
View File
@@ -21,9 +21,13 @@ const BASE_NAV_ITEMS: NavItem[] = [
label: 'بازخوانی تماس‌ها از کال سنتر', label: 'بازخوانی تماس‌ها از کال سنتر',
route: '/call-center/calls', route: '/call-center/calls',
}, },
{ icon: 'M7.9 20A9 9 0 1 0 4 16.1L2 22Z', label: 'سوالات چت سایت و اپلیکیشن', route: '/chat-questions' },
{ {
icon: 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37.996.608 2.296.07 2.573-1.066zM15 12a3 3 0 11-6 0 0 3 3 0 016 0z', 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: 'تنظیمات', label: 'تنظیمات',
route: '/settings', route: '/settings',
}, },
@@ -65,7 +65,7 @@ export class CallCenterPage {
}, },
{ {
id: 'sync', id: 'sync',
icon: 'M21 12A9 9 0 0 0 6.6 7.5l-3 3m0 0 3 3-3-3Z', 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: 'همگام‌سازی وضعیت کارشناسان', title: 'همگام‌سازی وضعیت کارشناسان',
description: description:
'حاضر بودن، مرخصی و خارج‌شدن کارشناسان بین برنامه و سامانه کال سنتر همگام می‌شود.', 'حاضر بودن، مرخصی و خارج‌شدن کارشناسان بین برنامه و سامانه کال سنتر همگام می‌شود.',
@@ -1,4 +1,4 @@
/* Page-specific styles for «سوالات چت سایت و اپلیکیشن» (shared chrome: shared/styles/demo-page.css) */ /* Page-specific styles for «سوالات چت وب اپلیکیشن» (shared chrome: shared/styles/demo-page.css) */
.demo-list-main { .demo-list-main {
flex: 1 1 22rem; flex: 1 1 22rem;
@@ -16,8 +16,8 @@
</svg> </svg>
</span> </span>
<div> <div>
<h1 class="demo-title">سوالات چت سایت و اپلیکیشن</h1> <h1 class="demo-title">سوالات چت وب اپلیکیشن</h1>
<p class="demo-subtitle">پرسش‌های ثبت‌شده در چت سایت و اپلیکیشن موبایل</p> <p class="demo-subtitle">پرسش‌های ثبت‌شده در چت وب اپلیکیشن </p>
</div> </div>
</div> </div>
<span class="demo-chip">نمایشی</span> <span class="demo-chip">نمایشی</span>
@@ -42,7 +42,7 @@
<div> <div>
<h2>این بخش هنوز فعال نیست</h2> <h2>این بخش هنوز فعال نیست</h2>
<p> <p>
این صفحه پرسش‌هایی را که کاربران در چت سایت یا اپلیکیشن موبایل ثبت کرده‌اند نمایش می‌دهد. در این صفحه پرسش‌هایی را که کاربران در چت وب اپلیکیشن ثبت کرده‌اند نمایش می‌دهد. در
فاز جاری این کانال‌ها به برنامه متصل نیستند و موارد زیر صرفاً نمونه هستند؛ پس از اتصال، فاز جاری این کانال‌ها به برنامه متصل نیستند و موارد زیر صرفاً نمونه هستند؛ پس از اتصال،
پرسش‌های بی‌پاسخ در این صفحه برای بررسی و افزودن به پایگاه دانش نمایش داده می‌شوند. پرسش‌های بی‌پاسخ در این صفحه برای بررسی و افزودن به پایگاه دانش نمایش داده می‌شوند.
</p> </p>
@@ -53,9 +53,7 @@
<div class="demo-card-header"> <div class="demo-card-header">
<div> <div>
<h2 class="demo-card-title">نمونه پرسش‌های چت</h2> <h2 class="demo-card-title">نمونه پرسش‌های چت</h2>
<p class="demo-card-description"> <p class="demo-card-description">پرسش‌های دریافتی به همراه منبع ثبت و وضعیت پاسخ‌گویی.</p>
پرسش‌های دریافتی به همراه منبع ثبت و وضعیت پاسخ‌گویی.
</p>
</div> </div>
<span class="demo-badge">داده نمونه</span> <span class="demo-badge">داده نمونه</span>
</div> </div>
@@ -66,10 +64,11 @@
<div class="demo-list-main"> <div class="demo-list-main">
<p class="demo-question">{{ item.question }}</p> <p class="demo-question">{{ item.question }}</p>
<div class="demo-meta"> <div class="demo-meta">
<span class="demo-tag" [class.demo-tag--site]="item.sourceKind === 'site'" [class.demo-tag--app]="item.sourceKind === 'app'"> <span
{{ item.source }} class="demo-tag"
</span> [class.demo-tag--answered]="item.statusKind === 'answered'"
<span class="demo-tag" [class.demo-tag--answered]="item.statusKind === 'answered'" [class.demo-tag--pending]="item.statusKind === 'pending'"> [class.demo-tag--pending]="item.statusKind === 'pending'"
>
{{ item.status }} {{ item.status }}
</span> </span>
<span>{{ item.date }}</span> <span>{{ item.date }}</span>
@@ -98,8 +97,8 @@
</svg> </svg>
<h3>پرسشی از چت ثبت نشده است</h3> <h3>پرسشی از چت ثبت نشده است</h3>
<p> <p>
پس از اتصال چت سایت و اپلیکیشن موبایل، پرسش‌های جدید کاربران به‌صورت خودکار در این صفحه نمایش پس از اتصال چت سایت و اپلیکیشن موبایل، پرسش‌های جدید کاربران به‌صورت خودکار در این صفحه
داده می‌شود تا برای آن‌ها پاسخ ثبت شود. نمایش داده می‌شود تا برای آن‌ها پاسخ ثبت شود.
</p> </p>
</div> </div>
</section> </section>
@@ -30,7 +30,7 @@ describe('ChatQuestionsPage', () => {
fixture.detectChanges(); fixture.detectChanges();
const element: HTMLElement = fixture.nativeElement; const element: HTMLElement = fixture.nativeElement;
expect(element.querySelector('.demo-title')?.textContent?.trim()).toBe('سوالات چت سایت و اپلیکیشن'); expect(element.querySelector('.demo-title')?.textContent?.trim()).toBe('سوالات چت وب اپلیکیشن');
expect(element.textContent).toContain('این بخش هنوز فعال نیست'); expect(element.textContent).toContain('این بخش هنوز فعال نیست');
expect(element.textContent).toContain('داده نمونه'); expect(element.textContent).toContain('داده نمونه');
@@ -5,7 +5,6 @@ interface ExampleQuestion {
id: string; id: string;
question: string; question: string;
source: string; source: string;
sourceKind: 'site' | 'app';
status: string; status: string;
statusKind: 'answered' | 'pending'; statusKind: 'answered' | 'pending';
date: string; date: string;
@@ -29,7 +28,6 @@ export class ChatQuestionsPage {
id: 'q-1', id: 'q-1',
question: 'برای ایمپورت محصولات جدید چه مراحلی را باید طی کنم؟', question: 'برای ایمپورت محصولات جدید چه مراحلی را باید طی کنم؟',
source: 'سایت', source: 'سایت',
sourceKind: 'site',
status: 'پاسخ داده شده', status: 'پاسخ داده شده',
statusKind: 'answered', statusKind: 'answered',
date: '۱۴ مهر ۱۴۰۴', date: '۱۴ مهر ۱۴۰۴',
@@ -38,7 +36,6 @@ export class ChatQuestionsPage {
id: 'q-2', id: 'q-2',
question: 'هزینه ارسال به شهرستان‌ها چگونه محاسبه می‌شود؟', question: 'هزینه ارسال به شهرستان‌ها چگونه محاسبه می‌شود؟',
source: 'اپلیکیشن', source: 'اپلیکیشن',
sourceKind: 'app',
status: 'در انتظار پاسخ', status: 'در انتظار پاسخ',
statusKind: 'pending', statusKind: 'pending',
date: '۱۴ مهر ۱۴۰۴', date: '۱۴ مهر ۱۴۰۴',
@@ -47,7 +44,6 @@ export class ChatQuestionsPage {
id: 'q-3', id: 'q-3',
question: 'آیا امکان لغو سفارش پس از پرداخت وجود دارد؟', question: 'آیا امکان لغو سفارش پس از پرداخت وجود دارد؟',
source: 'سایت', source: 'سایت',
sourceKind: 'site',
status: 'پاسخ داده شده', status: 'پاسخ داده شده',
statusKind: 'answered', statusKind: 'answered',
date: '۱۳ مهر ۱۴۰۴', date: '۱۳ مهر ۱۴۰۴',
+198 -122
View File
@@ -1,33 +1,21 @@
/* -------------------------------------------------------------------------- /* ==========================================================================
Home page — Claude-style chat column Layout: .home-page > .chat-column > ( .transcript-list + .composer )
Structure: - Landing (no conversation): greeting + composer are centered as one group.
.home-page - Conversation: the greeting collapses, the transcript list grows to fill the
.chat-column column (it is the only scroller) and the composer sits at the bottom.
.transcript-list (flex: 1, scroll) ========================================================================== */
.composer (pinned bottom of column)
Two layouts, CSS-only, driven by [class.has-conversation]:
- empty state column hugs its content and centers (logo + composer as a group)
- conversation column is exactly one viewport tall, transcript scrolls inside it
-------------------------------------------------------------------------- */
/* The host defaults to `display: inline`, which adds a line-box strut under the
full-height column and pushes the page into Y overflow. Block removes it. */
:host {
display: block;
min-height: 0;
}
.home-page { .home-page {
position: relative;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: center; height: 100dvh;
min-height: 100dvh; min-height: 100dvh;
box-sizing: border-box; box-sizing: border-box;
padding: 0; overflow: hidden;
position: relative; background:
/* Flat page color; every decorative glow lives in ::below so it can fade out as one. */ radial-gradient(ellipse 50% 40% at 50% 45%, rgba(59, 130, 246, 0.1), transparent 70%),
background: var(--app-bg); var(--app-bg);
} }
.home-page::before { .home-page::before {
@@ -35,91 +23,38 @@
position: absolute; position: absolute;
inset: 0; inset: 0;
background: background:
radial-gradient(ellipse 50% 40% at 50% 45%, rgba(59, 130, 246, 0.1), transparent 70%),
radial-gradient(circle at 50% 40%, rgba(59, 130, 246, 0.07), transparent 55%), radial-gradient(circle at 50% 40%, rgba(59, 130, 246, 0.07), transparent 55%),
radial-gradient(circle at 35% 55%, rgba(99, 102, 241, 0.05), transparent 50%), radial-gradient(circle at 35% 55%, rgba(99, 102, 241, 0.05), transparent 50%),
radial-gradient(circle at 65% 50%, rgba(59, 130, 246, 0.04), transparent 45%); radial-gradient(circle at 65% 50%, rgba(59, 130, 246, 0.04), transparent 45%);
pointer-events: none; pointer-events: none;
z-index: 0; z-index: 0;
transition: opacity 0.35s ease; transition: opacity 0.5s ease;
}
.home-page.has-conversation {
background: var(--app-bg);
} }
/* Conversation open (messages or voice call): the bluish glow disappears completely. */
.home-page.has-conversation::before { .home-page.has-conversation::before {
opacity: 0; opacity: 0;
} }
/* ---- Chat column (Claude: one continuous column) ---- */ /* ---------- Logo (landing only) ---------- */
.chat-column { .home-header {
position: relative; position: absolute;
top: 2rem;
left: 50%;
transform: translateX(-50%);
z-index: 1; z-index: 1;
display: flex;
flex-direction: column;
width: 100%;
max-width: 800px;
/* Auto height + viewport floor: grows only if the empty group cannot fit (then the
shell scrolls) instead of clipping. */
height: auto;
min-height: 100dvh;
box-sizing: border-box;
}
/* Conversation: the column is exactly one viewport tall so the composer stays pinned
and only the transcript area scrolls. `overflow` keeps any stray child box from
propagating phantom height to the page. */
.home-page.has-conversation .chat-column {
height: 100dvh;
overflow: hidden;
}
/* Empty state: the column stops stretching, so the empty content and the composer are
centered together in the viewport instead of the composer being pinned to the bottom. */
.home-page:not(.has-conversation) .chat-column {
justify-content: center;
}
.home-page:not(.has-conversation) .transcript-list {
flex: 0 0 auto;
overflow: visible;
}
.home-page:not(.has-conversation) .empty-state {
flex: 0 0 auto;
}
/* ---- Transcript list (scrollable body) ---- */
.transcript-list {
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
overflow-x: hidden;
/* Hide the scrollbar, keep wheel / trackpad / touch scrolling */
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* legacy Edge */
scroll-behavior: smooth;
display: flex;
flex-direction: column;
/* Space so last message clears the composer */
padding: 1.25rem 1rem 0.5rem;
box-sizing: border-box;
}
.transcript-list::-webkit-scrollbar {
display: none; /* Chrome, Safari, Edge */
width: 0;
height: 0;
}
/* Empty state centered in the transcript area */
.empty-state {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center; text-align: center;
padding: 2rem 1rem; opacity: 1;
min-height: 0; transition: opacity 0.35s ease, transform 0.35s ease;
}
.home-page.has-conversation .home-header {
opacity: 0;
transform: translateX(-50%) translateY(-8px);
pointer-events: none;
} }
.home-icon-wrapper { .home-icon-wrapper {
@@ -141,9 +76,44 @@
display: block; display: block;
} }
/* ---------- chat column ---------- */
.chat-column {
position: relative;
z-index: 1;
flex: 1 1 auto;
min-height: 0;
width: 100%;
display: flex;
flex-direction: column;
justify-content: center; /* landing: greeting + composer centered together */
}
.home-page.has-conversation .chat-column {
justify-content: flex-start;
}
/* ---------- greeting (typed title) ---------- */
.home-greeting {
flex: none;
box-sizing: border-box;
max-height: 8rem;
padding: 0 1rem;
overflow: hidden;
opacity: 1;
transition:
max-height 0.5s cubic-bezier(0.22, 1, 0.36, 1),
opacity 0.3s ease;
}
.home-page.has-conversation .home-greeting {
max-height: 0;
opacity: 0;
pointer-events: none;
}
.home-title { .home-title {
width: 100%; width: 100%;
margin: 0; margin: 0 0 1rem;
display: flex; display: flex;
align-items: center; align-items: center;
@@ -182,56 +152,144 @@
45% { 45% {
opacity: 1; opacity: 1;
} }
46%, 46%,
100% { 100% {
opacity: 0; opacity: 0;
} }
} }
/* Voice panel becomes the transcript body — no extra card chrome */ /* ---------- transcript list (the page's only scroller) ---------- */
.chat-transcript-body { .transcript-list {
display: block; flex: 0 1 auto;
flex: 1 1 auto;
min-height: 0; min-height: 0;
width: 100%; overflow-x: hidden;
overflow-y: auto;
overscroll-behavior: contain;
transition: flex-grow 0.5s cubic-bezier(0.22, 1, 0.36, 1);
} }
/* ---- Composer (pinned bottom of the chat column) ---- */ .home-page.has-conversation .transcript-list {
.composer { flex-grow: 1;
flex-shrink: 0; }
width: 100%;
padding: 0.75rem 1rem 1.25rem; .transcript-list::-webkit-scrollbar {
width: 6px;
}
.transcript-list::-webkit-scrollbar-thumb {
background: var(--muted);
border-radius: 9999px;
}
/* Same width as the composer so text and input line up */
.transcript-inner {
box-sizing: border-box; box-sizing: border-box;
background: transparent; display: flex;
/* Subtle top fade so messages don't collide with the input */ flex-direction: column;
position: relative; width: 100%;
max-width: 800px;
min-height: 100%;
margin: 0 auto;
padding: 0 1rem;
} }
.home-page.has-conversation .transcript-inner {
padding: 1.5rem 1rem 1rem;
}
.transcript-empty {
margin: auto;
font-size: 0.875rem;
color: var(--muted);
text-align: center;
}
/* ---------- composer (call bar + chat input) ---------- */
.composer {
position: relative;
z-index: 2;
flex: none;
box-sizing: border-box;
padding: 0 1rem 1rem;
}
.home-page.has-conversation .composer {
padding-bottom: calc(1rem + env(safe-area-inset-bottom, 0px));
}
/* Transcript text fades out under the composer instead of being cut off */
.composer::before { .composer::before {
content: ''; content: '';
position: absolute; position: absolute;
left: 0; inset-inline: 0;
right: 0;
bottom: 100%; bottom: 100%;
height: 1.5rem; height: 1.5rem;
pointer-events: none;
background: linear-gradient(to top, var(--app-bg), transparent); background: linear-gradient(to top, var(--app-bg), transparent);
pointer-events: none;
opacity: 0; opacity: 0;
transition: opacity 0.25s ease; transition: opacity 0.3s ease;
} }
.home-page.has-conversation .composer::before { .home-page.has-conversation .composer::before {
opacity: 1; opacity: 1;
} }
/* ---- Responsive ---- */ .composer > :not(.jump-to-latest) {
@media (max-width: 640px) { max-width: 800px;
.transcript-list { margin-inline: auto;
padding: 1rem 0.75rem 0.5rem;
} }
.composer { .home-call-dock {
padding: 0.5rem 0.75rem 1rem; margin-bottom: 0.5rem;
}
/* ---------- jump to latest ---------- */
.jump-to-latest {
position: absolute;
bottom: calc(100% + 0.5rem);
left: 50%;
transform: translateX(-50%);
display: inline-flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
border: 1px solid var(--surface-border);
border-radius: 50%;
background: var(--surface-bg);
color: var(--text-secondary);
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.12);
cursor: pointer;
animation: jumpIn 0.2s ease;
transition: background 0.2s ease, color 0.2s ease;
}
.jump-to-latest:hover {
background: var(--sidebar-hover);
color: var(--text-primary);
}
.jump-to-latest:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
@keyframes jumpIn {
from {
opacity: 0;
transform: translateX(-50%) translateY(6px);
}
to {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
}
/* ---------- responsive ---------- */
@media (max-width: 640px) {
.home-header {
top: 1.25rem;
} }
.home-icon-wrapper { .home-icon-wrapper {
@@ -243,15 +301,33 @@
.home-title { .home-title {
font-size: 1.375rem; font-size: 1.375rem;
} }
.composer {
padding: 0 0.75rem 0.75rem;
}
.home-page.has-conversation .composer {
padding-bottom: calc(0.75rem + env(safe-area-inset-bottom, 0px));
}
.transcript-inner {
padding-inline: 0.75rem;
}
.home-page.has-conversation .transcript-inner {
padding: 1rem 0.75rem 0.75rem;
}
} }
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
.home-page, .home-page,
.home-page::before, .home-page::before,
.home-header,
.home-greeting,
.transcript-list, .transcript-list,
.composer::before { .composer::before,
.jump-to-latest {
transition: none !important; transition: none !important;
animation: none !important; animation: none !important;
scroll-behavior: auto !important;
} }
} }
+47 -32
View File
@@ -1,52 +1,67 @@
<div <div class="home-page" [class.has-conversation]="hasConversation()">
class="home-page"
[class.has-conversation]="hasConversation()" <!-- Brand logo: shown only on the empty landing state -->
> <div class="home-header" aria-hidden="true">
<!-- Claude-style chat column: transcript list + composer in one continuous column --> <div class="home-icon-wrapper">
<div class="chat-column" role="main"> <img class="home-logo" [src]="logoSrc()" alt="Raymand" />
<!-- Transcript list (scrollable). Empty state or live/ended voice transcript. --> </div>
</div>
<!-- chat column: transcript list on top, composer docked at the bottom -->
<div class="chat-column">
<div class="home-greeting" [attr.aria-hidden]="hasConversation() ? 'true' : null">
<h1 class="home-title">
<span class="home-title-text">{{ streamedText() }}</span>
<span class="cursor" [class.cursor-hidden]="!isStreaming()" aria-hidden="true"></span>
</h1>
</div>
<!-- transcript list: the only scrolling region of the page -->
<div <div
class="transcript-list" class="transcript-list"
#transcriptScroller #transcriptList
role="log" role="log"
aria-label="متن گفتگو" aria-label="متن گفتگو"
aria-live="polite" aria-live="polite"
aria-relevant="additions" aria-relevant="additions"
(scroll)="onTranscriptScroll()"
> >
@if (!hasConversation()) { <div class="transcript-inner">
<!-- Empty state: logo + typing title (Claude empty chat feel) --> @if (callOpen() && voiceMessages().length === 0) {
<div class="empty-state"> <p class="transcript-empty">صحبت کنید؛ گفتگو اینجا نمایش داده می‌شود</p>
<div class="home-icon-wrapper">
<img
class="home-logo"
[src]="logoSrc()"
alt="Raymand"
/>
</div>
<h1 class="home-title">
<span class="home-title-text">{{ streamedText() }}</span>
<span
class="cursor"
[class.cursor-hidden]="!isStreaming()"
aria-hidden="true"
></span>
</h1>
</div>
} @else if (voiceHasTranscript()) {
<!-- Voice stream fills the transcript list (no separate card chrome) -->
<app-voice-stream-panel class="chat-transcript-body" />
} }
<app-voice-transcript [messages]="voiceMessages()" />
</div>
</div> </div>
<!-- Composer: always at the bottom of the same column (Claude pattern) --> <!-- composer: call bar (while a call runs) + the chat input -->
<div class="composer"> <div class="composer">
@if (jumpVisible()) {
<button
type="button"
class="jump-to-latest"
aria-label="رفتن به آخرین پیام"
(click)="scrollToLatest()"
>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M12 5v14M5 12l7 7 7-7" />
</svg>
</button>
}
@if (callDockMounted()) {
<app-voice-stream-panel class="home-call-dock" />
}
<app-ai-chat-input <app-ai-chat-input
data-chat-input
placeholder="پیام خود را بنویسید..." placeholder="پیام خود را بنویسید..."
[hasMessages]="hasConversation()"
(messageSent)="onMessageSent($event)" (messageSent)="onMessageSent($event)"
(fileSelected)="onFileSelected($event)" (fileSelected)="onFileSelected($event)"
(voiceToggled)="onVoiceToggled($event)" (voiceToggled)="onVoiceToggled($event)"
/> />
</div> </div>
</div> </div>
</div> </div>
+100 -21
View File
@@ -1,20 +1,24 @@
import { import {
ChangeDetectionStrategy, ChangeDetectionStrategy,
Component, Component,
ElementRef,
OnDestroy,
OnInit,
computed,
effect,
inject, inject,
signal, signal,
computed, viewChild,
OnInit,
OnDestroy,
} from '@angular/core'; } from '@angular/core';
import { CommonModule } from '@angular/common'; import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';
import { AiChatInputComponent } from '../../shared/ui/ai-chat-input/ai-chat-input.component';
import { VoiceStreamPanelComponent } from '../../shared/ui/voice-stream-panel/voice-stream-panel.component';
import { VoiceStreamService } from '../../services/voice-stream/voice-stream.service';
import { Router, NavigationEnd } from '@angular/router'; import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators'; import { filter } from 'rxjs/operators';
import { ThemeService } from '../../services/theme/theme.service';
import { Subscription } from 'rxjs'; import { Subscription } from 'rxjs';
import { AiChatInputComponent } from '../../shared/ui/ai-chat-input/ai-chat-input.component';
import { VoiceStreamPanelComponent } from '../../shared/ui/voice-stream-panel/voice-stream-panel.component';
import { VoiceTranscriptComponent } from '../../shared/ui/voice-transcript/voice-transcript.component';
import { VoiceStreamService } from '../../services/voice-stream/voice-stream.service';
import { ThemeService } from '../../services/theme/theme.service';
const HOME_TITLES = [ const HOME_TITLES = [
'چه چیزی می‌خواهید بدانید؟', 'چه چیزی می‌خواهید بدانید؟',
@@ -24,15 +28,20 @@ const HOME_TITLES = [
'سوالتان را مطرح کنید، پاسخ می‌دهم...', 'سوالتان را مطرح کنید، پاسخ می‌دهم...',
'بپرسید؛ با هم به پاسخ می‌رسیم...', 'بپرسید؛ با هم به پاسخ می‌رسیم...',
'هر سوالی در ذهن دارید، بپرسید...', 'هر سوالی در ذهن دارید، بپرسید...',
'دنبال یک پاسخ دقیق هستید؟...', 'دنبال یک پاسخ دقیق هستید؟',
'سوالتان را همین‌جا مطرح کنید...', 'سوالتان را همین‌جا مطرح کنید...',
'آماده‌ام به سوالتان پاسخ بدهم...', 'آماده‌ام به سوالتان پاسخ بدهم...',
]; ];
/** Keeps the call bar mounted this long after the call ends so it can fade/collapse out (matches the CSS). */
const CALL_DOCK_EXIT_MS = 400;
/** Within this distance of the bottom the list keeps following new text. */
const STICK_TO_BOTTOM_PX = 80;
@Component({ @Component({
selector: 'app-home', selector: 'app-home',
standalone: true, standalone: true,
imports: [CommonModule, AiChatInputComponent, VoiceStreamPanelComponent], imports: [AiChatInputComponent, VoiceStreamPanelComponent, VoiceTranscriptComponent],
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './home.page.html', templateUrl: './home.page.html',
styleUrl: './home.page.css', styleUrl: './home.page.css',
@@ -47,26 +56,29 @@ export class HomePage implements OnInit, OnDestroy {
readonly logoSrc = () => readonly logoSrc = () =>
this.isDarkMode() ? 'assets/images/RaymandLogo.png' : 'assets/images/login.png'; this.isDarkMode() ? 'assets/images/RaymandLogo.png' : 'assets/images/login.png';
// ---- conversation state ---------------------------------------------------
readonly hasMessages = signal(false); readonly hasMessages = signal(false);
readonly callOpen = this.voiceStream.isOpen;
readonly voiceMessages = this.voiceStream.messages;
/** /** Anything on screen that belongs in the chat column: text sent, a live call, or a finished call's transcript. */
* Conversation owns the layout when there is a live voice call, readonly hasConversation = computed(
* leftover voice transcript, or text messages — same idea as Claude's () => this.hasMessages() || this.callOpen() || this.voiceMessages().length > 0,
* chat column switching from empty state to transcript list.
*/
readonly voiceHasTranscript = computed(
() => this.voiceStream.isOpen() || this.voiceStream.messages().length > 0,
); );
readonly hasConversation = computed(() => this.hasMessages() || this.voiceHasTranscript()); /** The call bar stays mounted briefly after the call ends so it can animate out. */
readonly callDockMounted = signal(false);
/** @deprecated use hasConversation — kept for any external bindings */ readonly jumpVisible = signal(false);
readonly voicePanelVisible = this.hasConversation;
// ---- title typing ---------------------------------------------------------
readonly homeTitle = signal(''); readonly homeTitle = signal('');
readonly streamedText = signal(''); readonly streamedText = signal('');
readonly isStreaming = signal(false); readonly isStreaming = signal(false);
private readonly listRef = viewChild<ElementRef<HTMLElement>>('transcriptList');
private stickToBottom = true;
private scrollFrame: number | null = null;
private dockTimer: ReturnType<typeof setTimeout> | null = null;
private typingTimer: ReturnType<typeof setTimeout> | null = null; private typingTimer: ReturnType<typeof setTimeout> | null = null;
private routerSubscription?: Subscription; private routerSubscription?: Subscription;
@@ -79,6 +91,28 @@ export class HomePage implements OnInit, OnDestroy {
this.setRandomTitle(); this.setRandomTitle();
} }
}); });
// Mount the call bar when a call starts; unmount it after the exit animation.
toObservable(this.callOpen)
.pipe(takeUntilDestroyed())
.subscribe((open) => {
this.clearDockTimer();
if (open) {
this.callDockMounted.set(true);
} else if (this.callDockMounted()) {
this.dockTimer = setTimeout(() => {
this.dockTimer = null;
this.callDockMounted.set(false);
}, CALL_DOCK_EXIT_MS);
}
});
// Follow new transcript text, unless the user scrolled up to read.
effect(() => {
this.voiceMessages();
this.callOpen();
if (this.stickToBottom) this.scheduleScrollToBottom();
});
} }
ngOnInit(): void { ngOnInit(): void {
@@ -87,9 +121,48 @@ export class HomePage implements OnInit, OnDestroy {
ngOnDestroy(): void { ngOnDestroy(): void {
this.stopTyping(); this.stopTyping();
this.clearDockTimer();
if (this.scrollFrame !== null) cancelAnimationFrame(this.scrollFrame);
this.routerSubscription?.unsubscribe(); this.routerSubscription?.unsubscribe();
} }
// ---- transcript list scrolling -------------------------------------------
onTranscriptScroll(): void {
const el = this.listRef()?.nativeElement;
if (!el) return;
const distance = el.scrollHeight - el.scrollTop - el.clientHeight;
this.stickToBottom = distance < STICK_TO_BOTTOM_PX;
this.jumpVisible.set(!this.stickToBottom && this.hasConversation());
}
scrollToLatest(): void {
this.stickToBottom = true;
this.jumpVisible.set(false);
this.listRef()?.nativeElement.scrollTo({
top: this.listRef()!.nativeElement.scrollHeight,
behavior: 'smooth',
});
}
private scheduleScrollToBottom(): void {
if (this.scrollFrame !== null) return;
this.scrollFrame = requestAnimationFrame(() => {
this.scrollFrame = null;
const el = this.listRef()?.nativeElement;
if (el) el.scrollTo({ top: el.scrollHeight, behavior: 'instant' });
});
}
private clearDockTimer(): void {
if (this.dockTimer !== null) {
clearTimeout(this.dockTimer);
this.dockTimer = null;
}
}
// ---- title typing (unchanged) ---------------------------------------------
private setRandomTitle(): void { private setRandomTitle(): void {
this.stopTyping(); this.stopTyping();
@@ -115,9 +188,12 @@ export class HomePage implements OnInit, OnDestroy {
} }
index++; index++;
this.streamedText.set(text.substring(0, index)); this.streamedText.set(text.substring(0, index));
// Slightly random timing makes it feel more natural
const delay = 16 + Math.random() * 8; const delay = 16 + Math.random() * 8;
this.typingTimer = setTimeout(typeNextCharacter, delay); this.typingTimer = setTimeout(typeNextCharacter, delay);
}; };
@@ -129,9 +205,12 @@ export class HomePage implements OnInit, OnDestroy {
clearTimeout(this.typingTimer); clearTimeout(this.typingTimer);
this.typingTimer = null; this.typingTimer = null;
} }
this.isStreaming.set(false); this.isStreaming.set(false);
} }
// ---- composer events ------------------------------------------------------
onMessageSent(message: string): void { onMessageSent(message: string): void {
this.hasMessages.set(true); this.hasMessages.set(true);
console.log('Message sent:', message); console.log('Message sent:', message);
+94 -1
View File
@@ -208,6 +208,10 @@
background-color: color-mix(in srgb, var(--color-primary) 78%, #000); background-color: color-mix(in srgb, var(--color-primary) 78%, #000);
} }
.file-remove-btn:hover{
cursor: pointer;
}
@keyframes fadeInDown { @keyframes fadeInDown {
from { opacity: 0; transform: translateY(-10px); } from { opacity: 0; transform: translateY(-10px); }
to { opacity: 1; transform: translateY(0); } to { opacity: 1; transform: translateY(0); }
@@ -262,11 +266,20 @@
flex-direction: column; flex-direction: column;
} }
.tab-divider {
display: none;
}
.tab-btn { .tab-btn {
justify-content: flex-start; justify-content: flex-start;
padding: 1rem; padding: 1rem;
} }
.tab-btn span {
white-space: normal;
text-align: right;
}
.tab-btn .tab-indicator { .tab-btn .tab-indicator {
display: none; display: none;
} }
@@ -419,6 +432,50 @@
} }
.documents-table-wrapper { .documents-table-wrapper {
border: 1px solid var(--color-card-border); 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 { .documents-table {
border-collapse: separate; border-collapse: separate;
@@ -427,9 +484,12 @@
.documents-table th, .documents-table th,
.documents-table td { .documents-table td {
padding: 0.6rem 0.75rem; padding: 0.6rem 0.75rem;
text-align: right; /* Every column — labels and row content alike — is centred in the RTL table. */
text-align: center;
vertical-align: top; vertical-align: top;
border-bottom: 1px solid var(--color-card-border); 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 { .documents-table thead th {
background: var(--sidebar-hover); background: var(--sidebar-hover);
@@ -441,6 +501,26 @@
border-bottom: none; 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 badges */
.status-queued { .status-queued {
background: var(--color-warning)/15; background: var(--color-warning)/15;
@@ -458,6 +538,15 @@
background: var(--color-danger)/15; background: var(--color-danger)/15;
color: var(--color-danger); 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, .status-dot,
.dot-queued, .dot-queued,
.dot-processing, .dot-processing,
@@ -544,6 +633,10 @@
padding: 1rem 1.25rem; padding: 1rem 1.25rem;
border-bottom: 1px solid var(--color-card-border); 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 { .review-modal-body {
padding: 1.25rem; padding: 1.25rem;
overflow-y: auto; overflow-y: auto;
+298 -66
View File
@@ -69,6 +69,37 @@
></span> ></span>
} }
</button> </button>
<div class="tab-divider w-px h-6 bg-black/25"></div>
<button
type="button"
class="tab-btn flex-1 flex items-center justify-center gap-2 px-4 py-3 text-sm font-medium text-[var(--text-muted)] transition-all duration-200 hover:text-[var(--text-primary)] relative"
[class.tab-active]="activeTab() === 'models'"
(click)="selectTab('models')"
role="tab"
[attr.aria-selected]="activeTab() === 'models'"
>
<svg
class="w-4 h-4 transition-colors duration-200"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z" />
<path d="M19 10v2a7 7 0 0 1-14 0v-2" />
<line x1="12" x2="12" y1="19" y2="22" />
</svg>
<span>تنظیمات مدل‌های هوش مصنوعی</span>
@if (activeTab() === 'models') {
<span
class="tab-indicator absolute bottom-0 left-1/2 -translate-x-1/2 w-6 h-0.5 bg-primary rounded-full"
></span>
}
</button>
</nav> </nav>
<div class="settings-content p-6"> <div class="settings-content p-6">
@@ -313,13 +344,16 @@
type="button" type="button"
class="file-remove-btn p-1 text-[var(--text-muted)] rounded transition-colors hover:text-[var(--color-primary)]" class="file-remove-btn p-1 text-[var(--text-muted)] rounded transition-colors hover:text-[var(--color-primary)]"
(click)="retryUpload($index)" (click)="retryUpload($index)"
aria-label="دوباره‌سعی آپلود" aria-label="تلاش مجدد آپلود"
title="دوباره‌سعی" title="تلاش مجدد"
> >
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" <svg class="w-4 h-4" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke="currentColor" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round"> stroke-linejoin="round">
<path d="M21 12A9 9 0 0 0 6.6 7.5l-3 3m0 0 3 3-3-3Z" /> <path d="M20 7v5h-5" />
<path d="M4 17v-5h5" />
<path d="M5.6 9a7 7 0 0 1 11.55-2.6L20 12" />
<path d="M4 12l2.85 5.6A7 7 0 0 0 18.4 15" />
</svg> </svg>
</button> </button>
} }
@@ -332,11 +366,19 @@
<div class="documents-section mt-8"> <div class="documents-section mt-8">
@if (!isAdmin()) { @if (!isAdmin()) {
<div class="documents-locked flex flex-col items-center justify-center gap-3 py-10 text-center"> <div class="documents-locked flex flex-col items-center justify-center gap-3 py-10 text-center">
<svg class="w-10 h-10 text-[var(--text-muted)]" viewBox="0 0 24 24" fill="none" <svg
stroke="currentColor" stroke-width="1.5" stroke-linecap="round" class="w-5 h-5 text-primary"
stroke-linejoin="round"> viewBox="0 0 24 24"
<path d="M12 1.75v20.5" /> fill="none"
<path d="M4.25 12h15.5" /> stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14 2 14 8 20 8" />
<line x1="8" y1="13" x2="16" y2="13" />
<line x1="8" y1="17" x2="16" y2="17" />
</svg> </svg>
<p class="text-sm text-[var(--text-secondary)]">مدیریت و لیست اسناد فقط برای ادمین‌ها در دسترس است.</p> <p class="text-sm text-[var(--text-secondary)]">مدیریت و لیست اسناد فقط برای ادمین‌ها در دسترس است.</p>
</div> </div>
@@ -356,7 +398,8 @@
> >
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /> <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<polyline points="14 2 14 8 20 8" /> <polyline points="14 2 14 8 20 8" />
<polyline points="14 8 20 8 20 14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h8z" /> <line x1="8" y1="13" x2="16" y2="13" />
<line x1="8" y1="17" x2="16" y2="17" />
</svg> </svg>
اسناد آپلود شده اسناد آپلود شده
</h2> </h2>
@@ -367,10 +410,17 @@
@if (documentsLoading() && documents().length === 0) { @if (documentsLoading() && documents().length === 0) {
<div class="documents-loading flex items-center justify-center gap-2 py-10 text-[var(--text-muted)]"> <div class="documents-loading flex items-center justify-center gap-2 py-10 text-[var(--text-muted)]">
<svg class="w-5 h-5 animate-spin" viewBox="0 0 24 24" fill="none" stroke="currentColor" <svg
stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> class="w-5 h-5 animate-spin"
<line x1="12" y1="5" x2="12" y2="19" /> viewBox="0 0 24 24"
<path d="M19 12a7 7 0 1 1-14 0a7 7 0 0 1 14 0z" /> fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
aria-hidden="true"
>
<circle cx="12" cy="12" r="9" stroke-opacity="0.2" />
<path d="M21 12a9 9 0 0 0-9-9" />
</svg> </svg>
<span>در حال بارگذاری اسناد...</span> <span>در حال بارگذاری اسناد...</span>
</div> </div>
@@ -385,11 +435,11 @@
</div> </div>
} }
@if (documents().length > 0) { @if (documents().length > 0 || hasActiveFilters()) {
<div class="documents-filters mb-3 flex items-center justify-between gap-2"> <div class="documents-filters mb-3 flex items-center justify-between gap-2">
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<select <select
class="form-select bg-[var(--input-bg)] text-[var(--text-secondary)] border border-[var(--input-border)] rounded-lg px-3 py-1.5 text-xs min-w-[130px] cursor-pointer" class="form-select bg-[var(--color-input-bg)] text-[var(--text-secondary)] border border-[var(--color-input-border)] rounded-lg px-3 py-1.5 text-xs min-w-[130px] cursor-pointer"
[value]="activeFilter()" [value]="activeFilter()"
(change)="activeFilter.set($any($event.target).value); applyDocumentFilters()" (change)="activeFilter.set($any($event.target).value); applyDocumentFilters()"
> >
@@ -406,21 +456,58 @@
</label> </label>
<span class="text-xs text-[var(--text-muted)]">فقط فعال</span> <span class="text-xs text-[var(--text-muted)]">فقط فعال</span>
</div> </div>
<button type="button" class="btn btn--outline" (click)="refreshDocuments()" [disabled]="documentsLoading()"> <button
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" type="button"
stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> class="btn btn--outline"
<path d="M3 12a9 9 0 0 1 9-9a9 9 0 1 1 0 18a9 9 0 0 1 0-18z" /> (click)="refreshDocuments()"
<path d="M12 8v4l2 2" /> [disabled]="documentsLoading()"
[attr.aria-busy]="documentsLoading()"
>
@if (documentsLoading()) {
<svg
class="w-4 h-4 animate-spin"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
aria-hidden="true"
>
<circle cx="12" cy="12" r="9" stroke-opacity="0.2" />
<path d="M21 12a9 9 0 0 0-9-9" />
</svg> </svg>
<span>به‌روزرسانی</span> } @else {
<svg
class="w-4 h-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M20 7v5h-5" />
<path d="M4 17v-5h5" />
<path d="M5.6 9a7 7 0 0 1 11.55-2.6L20 12" />
<path d="M4 12l2.85 5.6A7 7 0 0 0 18.4 15" />
</svg>
}
<span>{{ documentsLoading() ? 'در حال به‌روزرسانی…' : 'به‌روزرسانی' }}</span>
</button> </button>
</div> </div>
<div class="documents-table-wrapper overflow-x-auto rounded-xl border border-[var(--color-card-border)] bg-[var(--card-bg)]"> <div class="documents-table-wrapper rounded-xl border border-[var(--color-card-border)] bg-[var(--card-bg)]">
<table class="documents-table min-w-full text-sm text-right"> <table class="documents-table w-full table-fixed text-sm text-right">
<colgroup>
<col class="w-[24%]" />
<col class="w-[17%]" />
<col class="w-[9%]" />
<col class="w-[16%]" />
<col class="w-[14%]" />
<col class="w-[20%]" />
</colgroup>
<thead class="bg-[var(--sidebar-hover)]"> <thead class="bg-[var(--sidebar-hover)]">
<tr> <tr>
<th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">نام فایل</th>
<th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">عنوان سند</th> <th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">عنوان سند</th>
<th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">وضعیت پردازش</th> <th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">وضعیت پردازش</th>
<th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">تعداد بخش‌ها</th> <th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">تعداد بخش‌ها</th>
@@ -433,11 +520,9 @@
@for (doc of documents(); track doc.id) { @for (doc of documents(); track doc.id) {
<tr class="table-row-animate"> <tr class="table-row-animate">
<td class="px-3 py-2.5 align-top"> <td class="px-3 py-2.5 align-top">
<span class="text-sm text-[var(--text-secondary)] truncate block max-w-[14rem]" <span class="text-sm text-[var(--text-secondary)] truncate block" title="{{ doc.title ?? '' }}">{{
>{{ doc.filename }}</span> doc.title ?? '—'
</td> }}</span>
<td class="px-3 py-2.5 align-top">
<span class="text-sm text-[var(--text-secondary)]">{{ doc.title ?? '—' }}</span>
</td> </td>
<td class="px-3 py-2.5 align-top"> <td class="px-3 py-2.5 align-top">
<span <span
@@ -468,15 +553,20 @@
<td class="px-3 py-2.5 align-top"> <td class="px-3 py-2.5 align-top">
<span class="text-sm text-[var(--text-muted)]">{{ formatDateTime(doc.created_at) }}</span> <span class="text-sm text-[var(--text-muted)]">{{ formatDateTime(doc.created_at) }}</span>
</td> </td>
<td class="px-3 py-2.5 align-top min-w-[11rem]"> <td class="px-3 py-2.5 align-top">
@if (doc.status === 'ready' && !isReviewNeeded(doc) && isAdmin()) { @if (doc.status === 'ready' && !isReviewNeeded(doc) && isAdmin()) {
@if (togglingDocId() === doc.id) { @if (togglingDocId() === doc.id) {
<div class="flex items-center gap-1.5 text-xs text-[var(--text-muted)]"> <div class="flex items-center justify-center gap-1.5 text-xs text-[var(--text-muted)]">
<svg class="w-3 h-3 animate-spin" viewBox="0 0 24 24" fill="none" <svg
stroke="currentColor" stroke-width="2" stroke-linecap="round" class="w-3 h-3 animate-spin"
stroke-linejoin="round"> viewBox="0 0 24 24"
<line x1="12" y1="5" x2="12" y2="19" /> fill="none"
<path d="M19 12a7 7 0 0 1-14 0a7 7 0 0 1 14 0z" /> stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
>
<circle cx="12" cy="12" r="9" stroke-opacity="0.2" />
<path d="M21 12a9 9 0 0 0-9-9" />
</svg> </svg>
<span>در حال به‌روزرسانی</span> <span>در حال به‌روزرسانی</span>
</div> </div>
@@ -493,14 +583,14 @@
} @else { } @else {
<span <span
class="text-xs" class="text-xs"
[class.text-[var(--color-success)]="doc.is_active" [class.status-ready]="doc.is_active"
[class.text-[var(--text-muted)]="!doc.is_active" [class.status-failed]="!doc.is_active"
>{{ doc.is_active ? 'فعال' : 'غیرفعال' }}</span >{{ doc.is_active ? 'فعال' : 'غیرفعال' }}</span
> >
} }
</td> </td>
<td class="px-3 py-2.5 align-top"> <td class="px-3 py-2.5 align-top">
<div class="flex items-center gap-1.5"> <div class="documents-actions flex items-center gap-1.5">
@if (isReviewNeeded(doc) && doc.status === 'failed') { @if (isReviewNeeded(doc) && doc.status === 'failed') {
<button <button
type="button" type="button"
@@ -508,11 +598,17 @@
[disabled]="reviewingDocId() === doc.id" [disabled]="reviewingDocId() === doc.id"
(click)="openReview(doc)" (click)="openReview(doc)"
> >
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" <svg
stroke="currentColor" stroke-width="2" stroke-linecap="round" class="w-4 h-4"
stroke-linejoin="round"> viewBox="0 0 24 24"
<path d="M2 12s9-7 19-7c2.6 0 4.5 2 4.5 4.5S23.6 19 21 19s-4.5-2.5-4.5-4.5S17.4 7 9 7" /> fill="none"
<path d="M2 12s9 7 19 7c2.6 0 4.5-2 4.5-4.5S23.6 7 21 7s-4.5 2.5-4.5 4.5S16.6 17 21 17" /> stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<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" /> <circle cx="12" cy="12" r="3" />
</svg> </svg>
<span>بازبینی سند</span> <span>بازبینی سند</span>
@@ -524,29 +620,73 @@
class="btn btn--outline" class="btn btn--outline"
(click)="retryDocument(doc)" (click)="retryDocument(doc)"
> >
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" <svg
stroke="currentColor" stroke-width="2" stroke-linecap="round" class="w-4 h-4"
stroke-linejoin="round"> viewBox="0 0 24 24"
<path d="M21 12A9 9 0 0 0 6.6 7.5l-3 3m0 0 3 3-3-3Z" /> fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M20 7v5h-5" />
<path d="M4 17v-5h5" />
<path d="M5.6 9a7 7 0 0 1 11.55-2.6L20 12" />
<path d="M4 12l2.85 5.6A7 7 0 0 0 18.4 15" />
</svg> </svg>
<span>دوباره‌سعی</span> <span>تلاش‌مجدد</span>
</button> </button>
} }
<button
type="button"
class="file-remove-btn p-2 text-[var(--text-muted)] rounded-lg transition-all duration-200 hover:text-red-400 hover:bg-red-400/10 hover:scale-110 shrink-0"
[attr.aria-label]="'حذف سند ' + (doc.title ?? doc.filename)"
title="حذف سند"
(click)="removeDocument(doc)"
>
<svg
class="w-4 h-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M3 6h18" />
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" />
<path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
<line x1="10" y1="11" x2="10" y2="17" />
<line x1="14" y1="11" x2="14" y2="17" />
</svg>
</button>
</div> </div>
</td> </td>
</tr> </tr>
} @empty {
@if (!documentsLoading()) {
<tr>
<td
colspan="6"
class="px-3 py-10 text-center text-sm text-[var(--text-muted)]"
>
هیچ سندی با فیلتر انتخاب‌شده مطابقت ندارد.
</td>
</tr>
}
} }
</tbody> </tbody>
</table> </table>
</div> </div>
@if (!hasMoreDocuments() && !documentsLoading()) { @if (documents().length > 0 && !hasMoreDocuments() && !documentsLoading()) {
<p class="text-xs text-[var(--text-muted)] text-center mt-3"> <p class="text-xs text-[var(--text-muted)] text-center mt-3">
{{ documents().length }} سند ثبت شده {{ documents().length }} سند ثبت شده
</p> </p>
} }
@if (hasMoreDocuments() && !documentsLoading()) { @if (documents().length > 0 && hasMoreDocuments() && !documentsLoading()) {
<div class="documents-pagination mt-3 text-center"> <div class="documents-pagination mt-3 text-center">
<button type="button" class="btn btn--outline" (click)="loadMoreDocuments()"> <button type="button" class="btn btn--outline" (click)="loadMoreDocuments()">
بیشتر بارگذاری بیشتر بارگذاری
@@ -595,11 +735,17 @@
<div class="review-modal-body"> <div class="review-modal-body">
@if (reviewLoading()) { @if (reviewLoading()) {
<div class="review-loading flex items-center justify-center gap-2 py-8 text-[var(--text-muted)]"> <div class="review-loading flex items-center justify-center gap-2 py-8 text-[var(--text-muted)]">
<svg class="w-5 h-5 animate-spin" viewBox="0 0 24 24" fill="none" <svg
stroke="currentColor" stroke-width="2" stroke-linecap="round" class="w-5 h-5 animate-spin"
stroke-linejoin="round"> viewBox="0 0 24 24"
<line x1="12" y1="5" x2="12" y2="19" /> fill="none"
<path d="M19 12a7 7 0 0 1-14 0a7 7 0 0 1 14 0z" /> stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
aria-hidden="true"
>
<circle cx="12" cy="12" r="9" stroke-opacity="0.2" />
<path d="M21 12a9 9 0 0 0-9-9" />
</svg> </svg>
<span>در حال بارگذاری شواهد...</span> <span>در حال بارگذاری شواهد...</span>
</div> </div>
@@ -742,11 +888,22 @@
<footer class="review-modal-footer border-t border-[var(--color-card-border)] p-3 flex justify-end gap-2"> <footer class="review-modal-footer border-t border-[var(--color-card-border)] p-3 flex justify-end gap-2">
@if (canRetryAfterReview()) { @if (canRetryAfterReview()) {
<button type="button" class="btn btn--primary" (click)="finishReviewAndRetry()"> <button type="button" class="btn btn--primary" (click)="finishReviewAndRetry()">
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" <svg
stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> class="w-4 h-4"
<path d="M21 12A9 9 0 0 0 6.6 7.5l-3 3m0 0 3 3-3-3Z" /> viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M3 2v6h6" />
<path d="M21 12a9 9 0 0 0-15-6.7L3 8" />
<path d="M21 22v-6h-6" />
<path d="M3 12a9 9 0 0 0 15 6.7L21 16" />
</svg> </svg>
<span>بستن و دوباره‌سعی پردازش</span> <span>بستن و تلاش مجدد پردازش</span>
</button> </button>
} }
<button type="button" class="btn btn--outline" (click)="closeReview()"> <button type="button" class="btn btn--outline" (click)="closeReview()">
@@ -756,6 +913,57 @@
</div> </div>
</div> </div>
} }
<!-- Remove-document confirmation -->
@if (deletingDoc(); as doc) {
<div class="review-backdrop" (click)="cancelDelete()">
<div
class="review-modal review-modal--sm"
(click)="onReviewModalClick($event)"
role="alertdialog"
aria-modal="true"
aria-label="حذف سند"
>
<header class="review-modal-header">
<h3 class="text-lg font-semibold text-[var(--text-primary)]">حذف سند</h3>
<button
type="button"
class="file-remove-btn p-1 text-[var(--text-muted)]"
(click)="cancelDelete()"
aria-label="بستن"
>
<svg
class="w-4 h-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<line x1="18" y1="6" x2="6" y2="18" />
<line x1="6" y1="6" x2="18" y2="18" />
</svg>
</button>
</header>
<div class="review-modal-body">
<p class="text-sm text-[var(--text-secondary)]">
آیا از حذف سند «{{ doc.title ?? doc.filename }}» مطمئن هستید؟ این عملیات قابل بازگشت نیست.
</p>
</div>
<footer
class="review-modal-footer border-t border-[var(--color-card-border)] p-3 flex justify-end gap-2"
>
<button type="button" class="btn btn--outline" (click)="cancelDelete()">
<span>انصراف</span>
</button>
<button type="button" class="btn btn--primary" (click)="confirmDeleteDocument()">
<span>حذف سند</span>
</button>
</footer>
</div>
</div>
}
</section> </section>
} }
@@ -809,7 +1017,7 @@
<span class="text-xs text-[var(--text-muted)] block mt-0.5"> <span class="text-xs text-[var(--text-muted)] block mt-0.5">
در صورت فعال بودن، محتوای استخراج‌شده از اسناد باید توسط ادمین بازبینی و تأیید شود. در صورت فعال بودن، محتوای استخراج‌شده از اسناد باید توسط ادمین بازبینی و تأیید شود.
</span> </span>
<span class="text-xs text-[var(--color-warning)] mt-0.5">پیش‌نویس — ذخیره‌سازی در فاز MVP پشتیبانی نمی‌شود</span> <!-- <span class="text-xs text-[var(--color-warning)] mt-0.5">پیش‌نویس — ذخیره‌سازی در فاز MVP پشتیبانی نمی‌شود</span> -->
</div> </div>
<div class="setting-control shrink-0"> <div class="setting-control shrink-0">
<label class="toggle-switch" [class.toggle-active]="ocrAdminApproval()"> <label class="toggle-switch" [class.toggle-active]="ocrAdminApproval()">
@@ -818,10 +1026,34 @@
</label> </label>
</div> </div>
</div> </div>
<div
class="setting-item flex items-center justify-between gap-4 p-4 bg-[var(--card-bg)] rounded-xl shadow-[0_2px_8px_rgba(0,0,0,0.04)] transition-all duration-200 hover:shadow-[0_4px_16px_rgba(0,0,0,0.08)] hover:-translate-y-0.5"
>
<div class="setting-info flex flex-col gap-1 min-w-0">
<label class="text-sm font-medium text-[var(--text-secondary)] cursor-pointer">
نیاز به تأیید ادمین برای اسناد FAQ
</label>
<span class="text-xs text-[var(--text-muted)] block mt-0.5">
در صورت فعال بودن، محتوای استخراج‌شده از اسناد FAQ باید توسط ادمین بازبینی و تأیید شود.
</span>
</div>
<div class="setting-control shrink-0">
<label class="toggle-switch" [class.toggle-active]="faqAdminApproval()">
<input type="checkbox" [checked]="faqAdminApproval()" (change)="toggleFaqApproval()" />
<span class="toggle-slider"></span>
</label>
</div>
</div>
</div> </div>
<div class="mt-8"> </section>
<h3 class="text-lg font-semibold text-[var(--text-primary)] mb-4 flex items-center gap-2"> }
@if (activeTab() === 'models') {
<section class="models-section animate-fade-in">
<div class="section-header mb-6">
<h2 class="text-xl font-semibold text-[var(--text-primary)] mb-1 flex items-center gap-2">
<svg class="w-5 h-5 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor" <svg class="w-5 h-5 text-primary" viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z" /> <path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z" />
@@ -829,10 +1061,11 @@
<line x1="12" x2="12" y1="19" y2="22" /> <line x1="12" x2="12" y1="19" y2="22" />
</svg> </svg>
تنظیمات مدل‌های هوش مصنوعی تنظیمات مدل‌های هوش مصنوعی
</h3> </h2>
<p class="text-xs text-[var(--text-muted)] mb-4"> <p class="text-sm text-[var(--text-muted)]">
هر کارت به‌صورت مستقل پیکربندی می‌شود. در فاز MVP، این تنظیمات در حافظه نگهداری می‌شوند و به سرور ارسال نمی‌شوند. هر کارت به‌صورت مستقل پیکربندی می‌شود. در فاز MVP، این تنظیمات در حافظه نگهداری می‌شوند و به سرور ارسال نمی‌شوند.
</p> </p>
</div>
<div class="ai-models-grid grid grid-cols-1 lg:grid-cols-2 gap-6"> <div class="ai-models-grid grid grid-cols-1 lg:grid-cols-2 gap-6">
<app-ai-model-config-card <app-ai-model-config-card
@@ -865,7 +1098,6 @@
(testConnection)="testModelConnection('ocr')" (testConnection)="testModelConnection('ocr')"
></app-ai-model-config-card> ></app-ai-model-config-card>
</div> </div>
</div>
<div class="mt-8"> <div class="mt-8">
<h3 class="text-lg font-semibold text-[var(--text-primary)] mb-4 flex items-center gap-2"> <h3 class="text-lg font-semibold text-[var(--text-primary)] mb-4 flex items-center gap-2">
@@ -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();
});
});
+52 -21
View File
@@ -14,12 +14,13 @@ import { ThemeService } from '../../services/theme/theme.service';
import { DocumentsService } from '../../services/documents/documents.service'; import { DocumentsService } from '../../services/documents/documents.service';
import { AuthService } from '../../services/auth/auth.service'; import { AuthService } from '../../services/auth/auth.service';
import { HttpService } from '../../services/http-request/http.service'; import { HttpService } from '../../services/http-request/http.service';
import { uuid } from '../../shared/utils/uuid';
import { import {
AiModelConfigCardComponent, AiModelConfigCardComponent,
AiModelConfig, AiModelConfig,
AiTask, AiTask,
} from '../../shared/ui/ai-model-config-card/ai-model-config-card.component'; } from '../../shared/ui/ai-model-config-card/ai-model-config-card.component';
import { toPersianDigits } from '../../shared/utils/format.util'; import { formatJalaliDateTime, toPersianDigits } from '../../shared/utils/format.util';
import { import {
DocumentDetail, DocumentDetail,
DocumentListItem, DocumentListItem,
@@ -35,7 +36,7 @@ import {
DOCUMENT_STATUS_LABEL, DOCUMENT_STATUS_LABEL,
} from '../../services/documents/documents.types'; } from '../../services/documents/documents.types';
type TabId = 'faq' | 'app'; type TabId = 'faq' | 'app' | 'models';
type UploadStatus = 'uploading' | 'done' | 'error'; type UploadStatus = 'uploading' | 'done' | 'error';
interface UploadTask { interface UploadTask {
@@ -151,6 +152,7 @@ export class SettingsPage implements OnInit, OnDestroy {
readonly tabs: { id: TabId; label: string }[] = [ readonly tabs: { id: TabId; label: string }[] = [
{ id: 'faq', label: 'آپلود FAQ' }, { id: 'faq', label: 'آپلود FAQ' },
{ id: 'app', label: 'تنظیمات برنامه' }, { id: 'app', label: 'تنظیمات برنامه' },
{ id: 'models', label: 'تنظیمات مدل‌های هوش مصنوعی' },
]; ];
readonly activeTab = signal<TabId>('faq'); readonly activeTab = signal<TabId>('faq');
@@ -202,6 +204,13 @@ export class SettingsPage implements OnInit, OnDestroy {
readonly activeFilter = signal<DocumentStatus | 'all'>('all'); readonly activeFilter = signal<DocumentStatus | 'all'>('all');
readonly activeOnly = signal<boolean>(false); readonly activeOnly = signal<boolean>(false);
/**
* True when a document filter (status other than "all", or active-only) is applied. Keeps
* the filter controls + table shell visible even when the filter matches zero rows, so the
* user can change/reset the filter instead of the whole panel vanishing.
*/
readonly hasActiveFilters = computed(() => this.activeFilter() !== 'all' || this.activeOnly());
readonly hasActiveDocuments = computed(() => this.documents().some((d) => d.is_active)); readonly hasActiveDocuments = computed(() => this.documents().some((d) => d.is_active));
readonly currentUserRole = computed<'admin' | 'user' | null>(() => { readonly currentUserRole = computed<'admin' | 'user' | null>(() => {
@@ -233,6 +242,8 @@ export class SettingsPage implements OnInit, OnDestroy {
// ---- knowledge selection (K01/K02) ---- // ---- knowledge selection (K01/K02) ----
readonly knowledgeSelection = signal<KnowledgeSelection | null>(null); readonly knowledgeSelection = signal<KnowledgeSelection | null>(null);
readonly togglingDocId = signal<string | null>(null); readonly togglingDocId = signal<string | null>(null);
/** Document awaiting remove confirmation (non-null while the confirm modal is open). */
readonly deletingDoc = signal<DocumentListItem | null>(null);
// ---- extraction review modal (D06/D07) ---- // ---- extraction review modal (D06/D07) ----
readonly reviewingDocId = signal<string | null>(null); readonly reviewingDocId = signal<string | null>(null);
@@ -248,6 +259,7 @@ export class SettingsPage implements OnInit, OnDestroy {
readonly notificationsEnabled = signal(true); readonly notificationsEnabled = signal(true);
readonly isDarkMode = this.themeService.isDarkMode; readonly isDarkMode = this.themeService.isDarkMode;
readonly ocrAdminApproval = signal(false); readonly ocrAdminApproval = signal(false);
readonly faqAdminApproval = signal(false);
readonly textModelConfig = signal<AiModelConfig>(DEFAULT_MODEL_CONFIG.text); readonly textModelConfig = signal<AiModelConfig>(DEFAULT_MODEL_CONFIG.text);
readonly embeddingModelConfig = signal<AiModelConfig>(DEFAULT_MODEL_CONFIG.embedding); readonly embeddingModelConfig = signal<AiModelConfig>(DEFAULT_MODEL_CONFIG.embedding);
@@ -347,21 +359,9 @@ export class SettingsPage implements OnInit, OnDestroy {
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
} }
/** تاریخ آپلود به صورت تاریخ و ساعت جلالی */
formatDateTime(iso: string): string { formatDateTime(iso: string): string {
try { return formatJalaliDateTime(iso);
const d = new Date(iso);
if (Number.isNaN(d.getTime())) {
return '—';
}
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
const hh = String(d.getHours()).padStart(2, '0');
const mm = String(d.getMinutes()).padStart(2, '0');
return toPersianDigits(`${y}/${m}/${day} ${hh}:${mm}`);
} catch {
return '—';
}
} }
get fileCount(): number { get fileCount(): number {
@@ -435,7 +435,7 @@ export class SettingsPage implements OnInit, OnDestroy {
progress: 0, progress: 0,
status: 'uploading', status: 'uploading',
error: null, error: null,
idempotencyKey: crypto.randomUUID(), idempotencyKey: uuid(),
}); });
} }
} }
@@ -932,7 +932,7 @@ export class SettingsPage implements OnInit, OnDestroy {
checked: [], checked: [],
note: '', note: '',
excludedGroupIds: [], excludedGroupIds: [],
idempotencyKey: crypto.randomUUID(), idempotencyKey: uuid(),
}; };
} }
} }
@@ -1024,7 +1024,7 @@ export class SettingsPage implements OnInit, OnDestroy {
this.toastr.warning('هنوز شواهد بازبینی تکمیل نشده‌اند.'); this.toastr.warning('هنوز شواهد بازبینی تکمیل نشده‌اند.');
return; return;
} }
const key = this.retryKeys.get(doc.id) ?? crypto.randomUUID(); const key = this.retryKeys.get(doc.id) ?? uuid();
this.retryKeys.set(doc.id, key); this.retryKeys.set(doc.id, key);
this.documentsService.retryDocument(doc.id, key).subscribe({ this.documentsService.retryDocument(doc.id, key).subscribe({
next: () => { next: () => {
@@ -1052,7 +1052,7 @@ export class SettingsPage implements OnInit, OnDestroy {
checked: [], checked: [],
note: '', note: '',
excludedGroupIds: [], excludedGroupIds: [],
idempotencyKey: crypto.randomUUID(), idempotencyKey: uuid(),
} }
); );
} }
@@ -1170,7 +1170,7 @@ export class SettingsPage implements OnInit, OnDestroy {
this.toastr.warning('سند در حال حاضر قابل تلاش مجدد نیست.'); this.toastr.warning('سند در حال حاضر قابل تلاش مجدد نیست.');
return; return;
} }
const key = this.retryKeys.get(doc.id) ?? crypto.randomUUID(); const key = this.retryKeys.get(doc.id) ?? uuid();
this.retryKeys.set(doc.id, key); this.retryKeys.set(doc.id, key);
this.documentsService.retryDocument(doc.id, key).subscribe({ this.documentsService.retryDocument(doc.id, key).subscribe({
next: (res: RetryResult) => { next: (res: RetryResult) => {
@@ -1191,6 +1191,32 @@ export class SettingsPage implements OnInit, OnDestroy {
}); });
} }
/**
* Open the remove confirmation for a document. Deletion itself is a destructive,
* epoch-changing action the backend MVP does not expose, so it is confirmed here before the
* (still stubbed) removal runs in `confirmDeleteDocument()`.
*/
removeDocument(doc: DocumentListItem): void {
this.deletingDoc.set(doc);
}
/** Dismiss the remove confirmation without deleting. */
cancelDelete(): void {
this.deletingDoc.set(null);
}
/**
* Confirmed removal. The backend MVP has no document-deletion endpoint (removing an active
* document also revokes its excerpts and can invalidate live voice sessions), so — like the
* other not-yet-implemented actions — this closes the dialog and surfaces an informative
* notice instead of calling an unsupported route. No data is deleted and no call is made.
*/
confirmDeleteDocument(): void {
const doc = this.deletingDoc();
this.deletingDoc.set(null);
if (doc) this.toastr.info(`حذف سند «${doc.title ?? doc.filename}» در فاز MVP پشتیبانی نمی‌شود.`);
}
/** Server-provided preview URL (authenticated via the session cookie); null = no preview. */ /** Server-provided preview URL (authenticated via the session cookie); null = no preview. */
previewImageUrl(item: ExtractionItem): string | null { previewImageUrl(item: ExtractionItem): string | null {
const path = item.preview_path; const path = item.preview_path;
@@ -1231,6 +1257,11 @@ export class SettingsPage implements OnInit, OnDestroy {
this.toastr.info('ذخیره‌سازی سیاست بازبینی OCR در فاز MVP پشتیبانی نمی‌شود.'); this.toastr.info('ذخیره‌سازی سیاست بازبینی OCR در فاز MVP پشتیبانی نمی‌شود.');
} }
toggleFaqApproval(): void {
this.faqAdminApproval.set(!this.faqAdminApproval());
this.toastr.info('ذخیره‌سازی سیاست بازبینی FAQ در فاز MVP پشتیبانی نمی‌شود.');
}
toggleDarkMode(): void { toggleDarkMode(): void {
this.themeService.toggleDarkMode(); this.themeService.toggleDarkMode();
} }
+2 -1
View File
@@ -39,7 +39,8 @@
stroke-linecap="round" stroke-linecap="round"
stroke-linejoin="round" stroke-linejoin="round"
> >
<path d="M21 12A9 9 0 0 0 6.6 7.5l-3 3m0 0 3 3-3-3Z" /> <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> </svg>
<span>به‌روزرسانی</span> <span>به‌روزرسانی</span>
</button> </button>
+2 -1
View File
@@ -3,6 +3,7 @@ import { Observable, BehaviorSubject, firstValueFrom, throwError } from 'rxjs';
import { tap, catchError } from 'rxjs/operators'; import { tap, catchError } from 'rxjs/operators';
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import { HttpService } from '../http-request/http.service'; import { HttpService } from '../http-request/http.service';
import { uuid } from '../../shared/utils/uuid';
export interface AuthUser { export interface AuthUser {
id: string; id: string;
@@ -92,7 +93,7 @@ export class AuthService {
/** Per-request correlation id shared with the server's `X-Request-ID`. */ /** Per-request correlation id shared with the server's `X-Request-ID`. */
private correlationHeaders(): Record<string, string> { private correlationHeaders(): Record<string, string> {
return { 'X-Request-ID': crypto.randomUUID() }; return { 'X-Request-ID': uuid() };
} }
/** /**
@@ -3,6 +3,7 @@ import { HttpErrorResponse, HttpEventType, HttpHeaders, HttpParams } from '@angu
import { map, filter, Observable, tap } from 'rxjs'; import { map, filter, Observable, tap } from 'rxjs';
import { HttpService } from '../http-request/http.service'; import { HttpService } from '../http-request/http.service';
import { AuthService } from '../auth/auth.service'; import { AuthService } from '../auth/auth.service';
import { uuid } from '../../shared/utils/uuid';
import { import {
DocumentDetail, DocumentDetail,
DocumentListParams, DocumentListParams,
@@ -34,7 +35,7 @@ export class DocumentsService {
* (from the login/`/me` flow) and a per-request correlation id. * (from the login/`/me` flow) and a per-request correlation id.
*/ */
private csrfHeaders(): Record<string, string> { private csrfHeaders(): Record<string, string> {
const headers: Record<string, string> = { 'X-Request-ID': crypto.randomUUID() }; const headers: Record<string, string> = { 'X-Request-ID': uuid() };
const token = this.auth.getCsrfToken(); const token = this.auth.getCsrfToken();
if (token) { if (token) {
headers['X-CSRF-Token'] = token; headers['X-CSRF-Token'] = token;
@@ -91,7 +92,7 @@ export class DocumentsService {
title: string | undefined, title: string | undefined,
onProgress: (percent: number) => void, onProgress: (percent: number) => void,
signal?: AbortSignal, signal?: AbortSignal,
idempotencyKey: string = crypto.randomUUID(), idempotencyKey: string = uuid(),
): Observable<DocumentUploadResult> { ): Observable<DocumentUploadResult> {
const form = new FormData(); const form = new FormData();
form.append('file', file); form.append('file', file);
@@ -123,7 +124,7 @@ export class DocumentsService {
submitReviewDecision( submitReviewDecision(
documentId: string, documentId: string,
request: ReviewDecisionRequest, request: ReviewDecisionRequest,
idempotencyKey: string = crypto.randomUUID(), idempotencyKey: string = uuid(),
): Observable<ReviewDecisionResponse> { ): Observable<ReviewDecisionResponse> {
return this.http.postRaw<ReviewDecisionResponse>( return this.http.postRaw<ReviewDecisionResponse>(
`${API}/documents/${encodeURIComponent(documentId)}/extraction-review/decisions`, `${API}/documents/${encodeURIComponent(documentId)}/extraction-review/decisions`,
@@ -147,7 +148,7 @@ export class DocumentsService {
/** D04 — retry processing of a document. */ /** D04 — retry processing of a document. */
retryDocument( retryDocument(
documentId: string, documentId: string,
idempotencyKey: string = crypto.randomUUID(), idempotencyKey: string = uuid(),
): Observable<RetryResult> { ): Observable<RetryResult> {
return this.http.postRaw<RetryResult>( return this.http.postRaw<RetryResult>(
`${API}/documents/${encodeURIComponent(documentId)}/retry`, `${API}/documents/${encodeURIComponent(documentId)}/retry`,
+20 -6
View File
@@ -50,11 +50,16 @@ export class HttpService {
* the dev-server proxy (proxy.conf.json) forwards `/api` — including WebSocket * the dev-server proxy (proxy.conf.json) forwards `/api` — including WebSocket
* upgrades — to the backend. The `rag_session` cookie therefore stays same-origin * 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. * 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 = 'http://10.0.8.51:1321'; private readonly baseUrl = '';
public readonly backendUrl = 'http://10.0.8.51:1321'; public readonly backendUrl = '';
public readonly apiUrl = 'http://10.0.8.51:1321'; public readonly apiUrl = '';
public readonly imagesUrl = 'http://10.0.8.51:1321'; public readonly imagesUrl = '';
constructor( constructor(
private readonly http: HttpClient, private readonly http: HttpClient,
@@ -170,6 +175,7 @@ export class HttpService {
.get<ApiResult<T>>(url, { .get<ApiResult<T>>(url, {
headers, headers,
params: options.params, params: options.params,
withCredentials: true,
}) })
.pipe( .pipe(
map((response) => this.processResponse(response, options)), map((response) => this.processResponse(response, options)),
@@ -206,7 +212,7 @@ export class HttpService {
...headers, ...headers,
}, },
signal: controller.signal, signal: controller.signal,
credentials: 'same-origin', credentials: 'include',
}) })
.then((response) => { .then((response) => {
if (!response.ok || !response.body) { if (!response.ok || !response.body) {
@@ -268,6 +274,7 @@ export class HttpService {
.post<ApiResult<T>>(url, data, { .post<ApiResult<T>>(url, data, {
headers: this.mergeHeaders(options.headers), headers: this.mergeHeaders(options.headers),
params: options.params, params: options.params,
withCredentials: true,
}) })
.pipe( .pipe(
map((response) => this.processResponse(response, options)), map((response) => this.processResponse(response, options)),
@@ -281,6 +288,7 @@ export class HttpService {
return this.http.post<T>(url, data, { return this.http.post<T>(url, data, {
headers, headers,
params: options.params, params: options.params,
withCredentials: true,
}); });
} }
@@ -292,7 +300,7 @@ export class HttpService {
const url = `${this.baseUrl}/${endpoint}`; const url = `${this.baseUrl}/${endpoint}`;
const headers = options.headers ? new HttpHeaders(options.headers) : new HttpHeaders(); const headers = options.headers ? new HttpHeaders(options.headers) : new HttpHeaders();
return this.http return this.http
.patch<T>(url, data, { headers, params: options.params }) .patch<T>(url, data, { headers, params: options.params, withCredentials: true })
.pipe(catchError((err) => this.handleError(err, options.skipToast))); .pipe(catchError((err) => this.handleError(err, options.skipToast)));
} }
@@ -315,6 +323,7 @@ export class HttpService {
params: options.params, params: options.params,
reportProgress: true, reportProgress: true,
observe: 'events', observe: 'events',
withCredentials: true,
}); });
if (!options.signal) { if (!options.signal) {
@@ -341,6 +350,7 @@ export class HttpService {
return this.http.get<T>(url, { return this.http.get<T>(url, {
headers, headers,
params: options.params, params: options.params,
withCredentials: true,
}); });
} }
@@ -350,6 +360,7 @@ export class HttpService {
.put<ApiResult<T>>(url, data, { .put<ApiResult<T>>(url, data, {
headers: this.mergeHeaders(options.headers), headers: this.mergeHeaders(options.headers),
params: options.params, params: options.params,
withCredentials: true,
}) })
.pipe( .pipe(
map((response) => this.processResponse(response, options)), map((response) => this.processResponse(response, options)),
@@ -363,6 +374,7 @@ export class HttpService {
.patch<ApiResult<T>>(url, data, { .patch<ApiResult<T>>(url, data, {
headers: this.mergeHeaders(options.headers), headers: this.mergeHeaders(options.headers),
params: options.params, params: options.params,
withCredentials: true,
}) })
.pipe( .pipe(
map((response) => this.processResponse(response, options)), map((response) => this.processResponse(response, options)),
@@ -376,6 +388,7 @@ export class HttpService {
.delete<ApiResult<T>>(url, { .delete<ApiResult<T>>(url, {
headers: this.mergeHeaders(options.headers), headers: this.mergeHeaders(options.headers),
params: options.params, params: options.params,
withCredentials: true,
}) })
.pipe( .pipe(
map((response) => this.processResponse(response, options)), map((response) => this.processResponse(response, options)),
@@ -388,6 +401,7 @@ export class HttpService {
.get(url, { .get(url, {
headers: this.getHeaders(), headers: this.getHeaders(),
responseType: 'blob', responseType: 'blob',
withCredentials: true,
}) })
.pipe(catchError((err) => this.handleError(err, false))); .pipe(catchError((err) => this.handleError(err, false)));
} }
@@ -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);
});
});
});
@@ -1,11 +1,15 @@
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Injectable, inject } from '@angular/core'; import { Injectable, inject } from '@angular/core';
import { firstValueFrom, race, throwError, Observable } from 'rxjs'; import { firstValueFrom, Observable } from 'rxjs';
import { delay } from 'rxjs/operators'; import { uuid } from '../../shared/utils/uuid';
import { VOICE_STREAM_CONFIG, VoiceSessionStatus } from './voice-stream.types'; import { VOICE_STREAM_CONFIG, VoiceSessionStatus } from './voice-stream.types';
/** The voice helper's HTTP deadline: a client timeout never means the server rolled back. */ /**
const REQUEST_DEADLINE_MS = 5000; * 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 } }. */ /** Error envelope from the contract: { error: { code, message, request_id, retryable, details } }. */
export class VoiceApiError extends Error { export class VoiceApiError extends Error {
@@ -162,7 +166,7 @@ export class VoiceApiService {
} }
private readOptions() { private readOptions() {
return { withCredentials: true, headers: new HttpHeaders({ 'X-Request-ID': crypto.randomUUID() }) }; return { withCredentials: true, headers: new HttpHeaders({ 'X-Request-ID': uuid() }) };
} }
private writeOptions(csrf: string) { private writeOptions(csrf: string) {
@@ -170,7 +174,7 @@ export class VoiceApiService {
withCredentials: true, withCredentials: true,
headers: new HttpHeaders({ headers: new HttpHeaders({
'X-CSRF-Token': csrf, 'X-CSRF-Token': csrf,
'X-Request-ID': crypto.randomUUID(), 'X-Request-ID': uuid(),
}), }),
}; };
} }
@@ -199,14 +203,52 @@ export class VoiceApiService {
} }
} }
/** A short deadline keeps the UI responsive; the caller reconciles the uncertain outcome. */ /**
* 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> { private withDeadline<T>(request: Observable<T>): Observable<T> {
return race( return new Observable<T>((observer) => {
request, let settled = false;
throwError(() => new VoiceApiError(0, 'TIMEOUT', 'request-deadline')).pipe(
delay(REQUEST_DEADLINE_MS), 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 { private toApiError(err: unknown): VoiceApiError {
@@ -1,12 +1,12 @@
import { Injectable, NgZone, inject } from '@angular/core'; import { Injectable, NgZone, inject, isDevMode } from '@angular/core';
import { MicrophoneService } from '../microphone/microphone.service'; import { MicrophoneError, MicrophoneService } from '../microphone/microphone.service';
import { VOICE_STREAM_CONFIG } from './voice-stream.types'; import { VOICE_STREAM_CONFIG } from './voice-stream.types';
export interface VoiceEngineHandlers { export interface VoiceEngineHandlers {
/** One PCM16 frame (config.inputSampleRate, config.frameMs). Runs outside Angular's zone. */ /** One PCM16 frame (config.inputSampleRate, config.frameMs). Runs outside Angular's zone. */
onFrame(pcm: ArrayBuffer, rms: number): void; onFrame(pcm: ArrayBuffer, rms: number): void;
/** The playback buffer ran dry (or `flushPlayback()` found it empty). */ /** The playback buffer ran dry (or `flushPlayback()` found it empty). */
onPlaybackIdle(): void; onPlaybackIdle(audioRef?: string | null): void;
/** The microphone track ended unexpectedly. */ /** The microphone track ended unexpectedly. */
onMicEnded(): void; onMicEnded(): void;
/** /**
@@ -72,14 +72,37 @@ export class VoiceAudioEngine {
await this.ngZone.runOutsideAngular(() => this.buildGraph(stream, handlers)); await this.ngZone.runOutsideAngular(() => this.buildGraph(stream, handlers));
} catch (err) { } catch (err) {
this.stop(); this.stop();
throw err instanceof Error && err.name === 'MicrophoneError' ? err : new VoiceEngineError('worklet-failed'); // 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> { private async buildGraph(stream: MediaStream, handlers: VoiceEngineHandlers): Promise<void> {
const cfg = this.config; const cfg = this.config;
const ctx = new AudioContext({ latencyHint: 'interactive' }); // 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; 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(/\/$/, ''); const base = cfg.workletBasePath.replace(/\/$/, '');
await ctx.audioWorklet.addModule(`${base}/pcm-capture.worklet.js`); await ctx.audioWorklet.addModule(`${base}/pcm-capture.worklet.js`);
@@ -98,6 +121,16 @@ export class VoiceAudioEngine {
}, },
}); });
this.capture.port.onmessage = (event: MessageEvent<{ pcm: ArrayBuffer; rms: number }>) => { 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; this.inputRms = event.data.rms;
handlers.onFrame(event.data.pcm, event.data.rms); handlers.onFrame(event.data.pcm, event.data.rms);
}; };
@@ -114,28 +147,54 @@ export class VoiceAudioEngine {
outputChannelCount: [1], outputChannelCount: [1],
}); });
this.playback.port.onmessage = ( this.playback.port.onmessage = (
event: MessageEvent<{ type: string; audioRef?: string; playedMs?: number }>, event: MessageEvent<{ type: string; audioRef?: string; playedMs?: number; consumedSamples?: number; discardedSamples?: number; contextRate?: number }>,
) => { ) => {
switch (event.data?.type) { switch (event.data?.type) {
case 'idle': case 'idle':
handlers.onPlaybackIdle(); handlers.onPlaybackIdle(event.data.audioRef);
break; break;
case 'progress': 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) { if (event.data.audioRef) {
handlers.onPlaybackProgress(event.data.audioRef, event.data.playedMs ?? 0); handlers.onPlaybackProgress(event.data.audioRef, event.data.playedMs ?? 0);
} }
break; 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': case 'overflow':
handlers.onPlaybackOverflow(); handlers.onPlaybackOverflow();
break; 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 = ctx.createAnalyser();
this.analyser.fftSize = 1024; this.analyser.fftSize = 1024;
this.analyser.smoothingTimeConstant = 0.6; this.analyser.smoothingTimeConstant = 0.6;
this.analyserData = new Uint8Array(this.analyser.fftSize); this.analyserData = new Uint8Array(this.analyser.fftSize);
this.playback.connect(this.analyser); this.playback.connect(this.analyser);
this.analyser.connect(ctx.destination); 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 -------------------------------------------------------------- // ---- playback --------------------------------------------------------------
@@ -156,8 +215,8 @@ export class VoiceAudioEngine {
} }
/** End of turn: play the remaining audio, then report idle. */ /** End of turn: play the remaining audio, then report idle. */
flushPlayback(): void { flushPlayback(audioRef?: string | null): void {
this.playback?.port.postMessage({ type: 'flush' }); this.playback?.port.postMessage({ type: 'flush', audioRef });
} }
// ---- mic / meters ---------------------------------------------------------- // ---- mic / meters ----------------------------------------------------------
@@ -186,8 +245,14 @@ export class VoiceAudioEngine {
// ---- cleanup --------------------------------------------------------------- // ---- cleanup ---------------------------------------------------------------
stop(): void { stop(): void {
if (this.capture) this.capture.port.onmessage = null; if (this.capture) {
if (this.playback) this.playback.port.onmessage = null; 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.source?.disconnect();
this.capture?.disconnect(); this.capture?.disconnect();
@@ -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;
}
@@ -10,7 +10,11 @@ import { VoiceStreamService } from './voice-stream.service';
import { VOICE_TRANSPORT_FACTORY, VoiceTransport, VoiceTransportHandlers } from './voice-transport'; import { VOICE_TRANSPORT_FACTORY, VoiceTransport, VoiceTransportHandlers } from './voice-transport';
import { PlaybackProgressMessage, VoiceServerEvent } from './voice-stream.types'; import { PlaybackProgressMessage, VoiceServerEvent } from './voice-stream.types';
const ME = { user: { id: 'u1', username: 'admin', role: 'admin', organization_id: 'o1' }, csrf_token: 'csrf-1', expires_at: 'later' }; const ME = {
user: { id: 'u1', username: 'admin', role: 'admin', organization_id: 'o1' },
csrf_token: 'csrf-1',
expires_at: 'later',
};
const CONFIG = { const CONFIG = {
revision: 1, revision: 1,
assistant_name: 'دستیار', assistant_name: 'دستیار',
@@ -33,9 +37,22 @@ const READY_EVENT: VoiceServerEvent = {
output_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 }, output_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 },
}; };
const OVERFLOW_MESSAGE = 'حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو به‌طور ایمن پایان یافت.';
const SEND_OVERFLOW_MESSAGE =
'حجم صدای ارسالی از محدودهٔ مجاز گذشت و گفتگو به‌طور ایمن پایان یافت.';
/** Flush pending microtasks/timers so the service reaches a stable await point. */ /** Flush pending microtasks/timers so the service reaches a stable await point. */
const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 5)); const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 5));
type Mock = ReturnType<typeof vi.fn>;
type TransportMock = Omit<VoiceTransport, 'connect' | 'sendAudio' | 'sendControl' | 'close'> & {
handlers: VoiceTransportHandlers | null;
connect: Mock;
sendAudio: Mock;
sendControl: Mock;
close: Mock;
};
describe('VoiceStreamService (backend handoff contract)', () => { describe('VoiceStreamService (backend handoff contract)', () => {
let service: VoiceStreamService; let service: VoiceStreamService;
let api: { let api: {
@@ -51,12 +68,19 @@ describe('VoiceStreamService (backend handoff contract)', () => {
let engineHandlers: VoiceEngineHandlers | null; let engineHandlers: VoiceEngineHandlers | null;
let transportHandlers: VoiceTransportHandlers | null; let transportHandlers: VoiceTransportHandlers | null;
let controls: PlaybackProgressMessage[]; let controls: PlaybackProgressMessage[];
let transportMock: TransportMock;
let engineStop: ReturnType<typeof vi.fn>;
let engineFlush: Mock;
let engineClear: Mock;
beforeEach(() => { beforeEach(() => {
sessionStorage.clear(); sessionStorage.clear();
engineHandlers = null; engineHandlers = null;
transportHandlers = null; transportHandlers = null;
controls = []; controls = [];
engineStop = vi.fn();
engineFlush = vi.fn();
engineClear = vi.fn();
api = { api = {
me: vi.fn().mockResolvedValue(ME), me: vi.fn().mockResolvedValue(ME),
@@ -69,7 +93,7 @@ describe('VoiceStreamService (backend handoff contract)', () => {
streamUrl: vi.fn().mockReturnValue('wss://ui.local/api/v1/voice/sessions/ses-1/stream'), streamUrl: vi.fn().mockReturnValue('wss://ui.local/api/v1/voice/sessions/ses-1/stream'),
}; };
const transportMock: VoiceTransport & { handlers: VoiceTransportHandlers | null } = { transportMock = {
handlers: null, handlers: null,
connect: vi.fn().mockImplementation((handlers: VoiceTransportHandlers) => { connect: vi.fn().mockImplementation((handlers: VoiceTransportHandlers) => {
transportHandlers = handlers; transportHandlers = handlers;
@@ -77,7 +101,9 @@ describe('VoiceStreamService (backend handoff contract)', () => {
return Promise.resolve(); return Promise.resolve();
}), }),
sendAudio: vi.fn(), sendAudio: vi.fn(),
sendControl: vi.fn().mockImplementation((message: PlaybackProgressMessage) => controls.push(message)), sendControl: vi
.fn()
.mockImplementation((message: PlaybackProgressMessage) => controls.push(message)),
close: vi.fn(), close: vi.fn(),
}; };
@@ -95,11 +121,11 @@ describe('VoiceStreamService (backend handoff contract)', () => {
engineHandlers = handlers; engineHandlers = handlers;
return Promise.resolve(); return Promise.resolve();
}), }),
stop: vi.fn(), stop: engineStop,
setMuted: vi.fn(), setMuted: vi.fn(),
enqueuePlayback: vi.fn(), enqueuePlayback: vi.fn(),
clearPlayback: vi.fn(), clearPlayback: engineClear,
flushPlayback: vi.fn(), flushPlayback: engineFlush,
inputLevel: () => 0, inputLevel: () => 0,
outputLevel: () => 0, outputLevel: () => 0,
}, },
@@ -119,7 +145,9 @@ describe('VoiceStreamService (backend handoff contract)', () => {
} }
function firstEndedError(): Promise<string | undefined> { function firstEndedError(): Promise<string | undefined> {
return new Promise((resolve) => service.sessionEnded$.pipe(first()).subscribe((end) => resolve(end.error))); return new Promise((resolve) =>
service.sessionEnded$.pipe(first()).subscribe((end) => resolve(end.error)),
);
} }
it('creates conversation then voice session with two separate client request ids', async () => { it('creates conversation then voice session with two separate client request ids', async () => {
@@ -147,7 +175,11 @@ describe('VoiceStreamService (backend handoff contract)', () => {
output_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 }, output_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 },
}); });
const result = await started; const result = await started;
expect(result).toEqual({ ok: false, reason: 'connect', message: 'فرمت صدای سرور با برنامه سازگار نیست.' }); expect(result).toEqual({
ok: false,
reason: 'connect',
message: 'فرمت صدای سرور با برنامه سازگار نیست.',
});
}); });
it('reconciles an ambiguous V01 through V03 instead of creating a second session', async () => { it('reconciles an ambiguous V01 through V03 instead of creating a second session', async () => {
@@ -207,7 +239,13 @@ describe('VoiceStreamService (backend handoff contract)', () => {
it('reports the final real played progress when the turn is interrupted', async () => { it('reports the final real played progress when the turn is interrupted', async () => {
await startConnected(); await startConnected();
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 'turn-1', role: 'assistant', text: 'پاسخ', status: 'partial' }); transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'پاسخ',
status: 'partial',
});
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-2' }); transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-2' });
engineHandlers?.onPlaybackProgress('aud-2', 300); engineHandlers?.onPlaybackProgress('aud-2', 300);
controls = []; controls = [];
@@ -216,9 +254,7 @@ describe('VoiceStreamService (backend handoff contract)', () => {
// The worklet answers `clear` with its final cumulative report for the ref. // The worklet answers `clear` with its final cumulative report for the ref.
engineHandlers?.onPlaybackProgress('aud-2', 780); engineHandlers?.onPlaybackProgress('aud-2', 780);
expect(controls).toEqual([ expect(controls).toEqual([{ type: 'playback_progress', audio_ref: 'aud-2', played_ms: 780 }]);
{ type: 'playback_progress', audio_ref: 'aud-2', played_ms: 780 },
]);
expect(service.messages().find((m) => m.id === 'turn-1:assistant')?.interrupted).toBe(true); expect(service.messages().find((m) => m.id === 'turn-1:assistant')?.interrupted).toBe(true);
}); });
@@ -228,10 +264,155 @@ describe('VoiceStreamService (backend handoff contract)', () => {
engineHandlers?.onPlaybackOverflow(); engineHandlers?.onPlaybackOverflow();
expect(await ended).toBe('حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو به‌طور ایمن پایان یافت.'); expect(await ended).toBe(OVERFLOW_MESSAGE);
expect(service.connection()).toBe('disconnected'); expect(service.connection()).toBe('disconnected');
}); });
it('uses a distinct message for capture/send overflow vs playback overflow', async () => {
await startConnected();
const ended = firstEndedError();
transportHandlers?.onOverflow('send');
expect(await ended).toBe(SEND_OVERFLOW_MESSAGE);
expect(await ended).not.toBe(OVERFLOW_MESSAGE);
expect(service.connection()).toBe('disconnected');
});
it('concurrent overflow + socket close + Stop send one /close and one teardown', async () => {
await startConnected();
const ended = firstEndedError();
// Several end triggers race for the same session (the reported live failure).
engineHandlers?.onPlaybackOverflow(); // 1st → overflow error
engineHandlers?.onPlaybackOverflow(); // duplicate
transportHandlers?.onClose({ clean: false, code: 1006, reason: '' }); // socket close
service.end(); // manual Stop
expect(await ended).toBe(OVERFLOW_MESSAGE); // first meaningful error preserved
expect(api.closeVoiceSession).toHaveBeenCalledTimes(1); // V04 sent exactly once
expect(transportMock.close).toHaveBeenCalledTimes(1); // socket released once
expect(engineStop).toHaveBeenCalledTimes(1); // audio graph released once
expect(service.connection()).toBe('disconnected');
});
it('releases local resources even when V04 /close fails', async () => {
await startConnected();
api.closeVoiceSession.mockRejectedValueOnce(new Error('V04 boom'));
await service.close();
expect(api.closeVoiceSession).toHaveBeenCalledTimes(1);
expect(transportMock.close).toHaveBeenCalledTimes(1);
expect(engineStop).toHaveBeenCalledTimes(1);
expect(service.connection()).toBe('disconnected');
expect(sessionStorage.getItem('voice_creation_attempt')).toBeNull();
});
it('ignores stale callbacks: an old session cannot close or affect a new one', async () => {
await startConnected(); // session A
await service.close();
api.closeVoiceSession.mockClear();
engineStop.mockClear();
transportMock.close.mockClear();
// Late callbacks captured for session A arrive after A already ended.
engineHandlers?.onPlaybackOverflow();
transportHandlers?.onClose({ clean: false, code: 1006, reason: '' });
await flush();
expect(api.closeVoiceSession).not.toHaveBeenCalled();
expect(service.connection()).toBe('disconnected');
// A brand-new session is independent and closes exactly once on its own.
await startConnected(); // session B
expect(service.connection()).toBe('connected');
api.closeVoiceSession.mockClear();
await service.close();
expect(api.closeVoiceSession).toHaveBeenCalledTimes(1);
});
it('keeps listening closed across an open-audio underrun and ignores a stale seal', async () => {
await startConnected();
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1', turn_ref: 'turn-1' });
transportHandlers?.onAudio(new ArrayBuffer(9600));
engineHandlers?.onPlaybackIdle('aud-1');
vi.useFakeTimers();
try {
vi.advanceTimersByTime(2000);
} finally {
vi.useRealTimers();
}
expect(service.state()).toBe('SPEAKING');
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'complete text',
status: 'completed',
});
engineHandlers?.onPlaybackIdle('aud-1');
transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'stale', turn_ref: 'turn-0' });
expect(service.state()).toBe('SPEAKING');
expect(engineFlush).not.toHaveBeenCalled();
transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'aud-1', turn_ref: 'turn-1' });
engineHandlers?.onPlaybackIdle('stale');
expect(service.state()).toBe('SPEAKING');
engineHandlers?.onPlaybackIdle('aud-1');
expect(service.state()).toBe('LISTENING');
});
it('does not reset received bytes on a duplicate audio start', async () => {
await startConnected();
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1', turn_ref: 'turn-1' });
transportHandlers?.onAudio(new ArrayBuffer(9600));
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1', turn_ref: 'turn-1' });
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
transportHandlers?.onEvent({
type: 'audio_ended',
audio_ref: 'aud-1',
turn_ref: 'turn-1',
sent_bytes: 9600,
});
expect(warn).not.toHaveBeenCalledWith('Voice audio delivery mismatch', expect.anything());
} finally {
warn.mockRestore();
}
});
it('drains on audio_ended so the ref reaches its true final progress (not solely on transcript)', async () => {
await startConnected();
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' });
// A `completed` transcript that arrives BEFORE audio_ended must NOT flush the queue: the
// audio is still streaming, so finalizing the tail now would be premature.
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: '…',
status: 'completed',
});
expect(engineFlush).not.toHaveBeenCalled();
// audio_ended (generation complete) drives the drain: the worklet emits the deferred
// tail and plays out, so playback progress retires the whole ref before the backend's
// stall timeout — this is the fix for the premature LIVE_BUFFER_OVERFLOW termination.
transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'aud-1' });
expect(engineFlush).toHaveBeenCalledTimes(1);
// A duplicate final transcript does not flush the sealed reference again.
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: '…',
status: 'completed',
});
expect(engineFlush).toHaveBeenCalledTimes(1);
});
it('requires a fresh conversation after CONTEXT_REVOKED and drops the old attempt', async () => { it('requires a fresh conversation after CONTEXT_REVOKED and drops the old attempt', async () => {
await startConnected(); await startConnected();
const ended = firstEndedError(); const ended = firstEndedError();
@@ -241,7 +422,9 @@ describe('VoiceStreamService (backend handoff contract)', () => {
error: { code: 'CONTEXT_REVOKED', message: 'context revoked', retryable: false }, error: { code: 'CONTEXT_REVOKED', message: 'context revoked', retryable: false },
}); });
expect(await ended).toBe('محتوای دانش تغییر کرده و مکالمهٔ قبلی دیگر معتبر نیست. گفتگوی جدیدی شروع کنید.'); expect(await ended).toBe(
'محتوای دانش تغییر کرده و مکالمهٔ قبلی دیگر معتبر نیست. گفتگوی جدیدی شروع کنید.',
);
expect(sessionStorage.getItem('voice_creation_attempt')).toBeNull(); expect(sessionStorage.getItem('voice_creation_attempt')).toBeNull();
expect(service.connection()).toBe('disconnected'); expect(service.connection()).toBe('disconnected');
}); });
@@ -284,15 +467,122 @@ describe('VoiceStreamService (backend handoff contract)', () => {
it('marks partial then completed transcripts final', async () => { it('marks partial then completed transcripts final', async () => {
await startConnected(); await startConnected();
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'سلام', status: 'partial' }); transportHandlers?.onEvent({
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'سلام و خوب', status: 'partial' }); type: 'transcript',
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'سلام و خوب', status: 'completed' }); turn_ref: 't1',
role: 'assistant',
text: 'سلام',
status: 'partial',
});
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 't1',
role: 'assistant',
text: 'سلام و خوب',
status: 'partial',
});
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 't1',
role: 'assistant',
text: 'سلام و خوب',
status: 'completed',
});
const assistant = service.messages().find((m) => m.id === 't1:assistant'); const assistant = service.messages().find((m) => m.id === 't1:assistant');
expect(assistant?.text).toBe('سلام و خوب'); expect(assistant?.text).toBe('سلام و خوب');
expect(assistant?.final).toBe(true); expect(assistant?.final).toBe(true);
}); });
it('orders a user request above its AI response even when the assistant transcript arrives first', async () => {
await startConnected();
// The server streams assistant partials before the user transcript for the same turn.
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'پاسخ فارسی',
status: 'partial',
});
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'user',
text: 'سلام',
status: 'completed',
});
const list = service.messages();
const userIndex = list.findIndex((m) => m.id === 'turn-1:user');
const assistantIndex = list.findIndex((m) => m.id === 'turn-1:assistant');
expect(userIndex).toBeGreaterThanOrEqual(0);
expect(assistantIndex).toBeGreaterThan(userIndex);
});
it('keeps user→assistant order and stable turn order across turns', async () => {
await startConnected();
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 't1',
role: 'user',
text: 'سوال ۱',
status: 'completed',
});
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 't1',
role: 'assistant',
text: 'پاسخ ۱',
status: 'completed',
});
// turn 2's assistant lands before its user transcript
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 't2',
role: 'assistant',
text: 'پاسخ ۲',
status: 'partial',
});
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 't2',
role: 'user',
text: 'سوال ۲',
status: 'completed',
});
expect(service.messages().map((m) => m.id)).toEqual([
't1:user',
't1:assistant',
't2:user',
't2:assistant',
]);
});
it('keeps the user request above a sources-only assistant bubble of the same turn', async () => {
await startConnected();
// A `sources` frame can create the assistant bubble before the user transcript arrives.
transportHandlers?.onEvent({
type: 'sources',
turn_ref: 't1',
sources: [
{ source_ref: 's1', document_id: 'd1', chunk_id: 'c1', title: 'سند', excerpt: 'بند' },
],
});
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 't1',
role: 'user',
text: 'سلام',
status: 'completed',
});
expect(service.messages().map((m) => m.id)).toEqual(['t1:user', 't1:assistant']);
});
it('closes the reservation (V04) when the call ends on user request', async () => { it('closes the reservation (V04) when the call ends on user request', async () => {
await startConnected(); await startConnected();
await service.close(); await service.close();
@@ -301,4 +591,480 @@ describe('VoiceStreamService (backend handoff contract)', () => {
expect(sessionStorage.getItem('voice_creation_attempt')).toBeNull(); expect(sessionStorage.getItem('voice_creation_attempt')).toBeNull();
expect(service.connection()).toBe('disconnected'); expect(service.connection()).toBe('disconnected');
}); });
describe('bounded answers (answer_limited)', () => {
const MARKER: VoiceServerEvent = {
type: 'answer_limited',
turn_ref: 'turn-1',
reason: 'output_token_limit',
};
it('keeps the marker as bounded metadata when it arrives before any transcript text', async () => {
await startConnected();
transportHandlers?.onEvent(MARKER);
// No transcript text is invented for the answer.
expect(service.messages()).toEqual([]);
expect(service.connection()).toBe('connected');
expect(service.state()).toBe('LISTENING');
});
it('attaches the marker to the row when the first transcript lands after it', async () => {
await startConnected();
transportHandlers?.onEvent(MARKER); // marker first, no text yet
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'پاسخ ',
status: 'partial',
});
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'پاسخ نهایی',
status: 'limited',
});
const assistant = service.messages().find((m) => m.id === 'turn-1:assistant');
expect(assistant?.text).toBe('پاسخ نهایی'); // final snapshot replaces the partial text
expect(assistant?.limited).toBe(true);
expect(assistant?.final).toBe(true);
});
it('keeps exact text and limited status when the limited transcript arrives before the marker', async () => {
await startConnected();
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'پاسخ کامل',
status: 'limited',
});
expect(service.messages()[0].limited).toBe(true); // the transcript alone marks the answer
transportHandlers?.onEvent(MARKER);
const assistant = service.messages().find((m) => m.id === 'turn-1:assistant');
expect(assistant?.text).toBe('پاسخ کامل');
expect(assistant?.limited).toBe(true);
});
it('treats repeated answer_limited markers as idempotent (no duplicate rows or notices)', async () => {
await startConnected();
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'پاسخ',
status: 'limited',
});
const before = service.messages();
transportHandlers?.onEvent(MARKER);
transportHandlers?.onEvent(MARKER);
transportHandlers?.onEvent(MARKER);
expect(service.messages()).toHaveLength(1);
expect(service.messages()).toBe(before); // no state write at all → no re-announcement
expect(service.messages()[0].text).toBe('پاسخ');
expect(service.streamError()).toBeNull(); // informational, never an error banner
expect(service.connection()).toBe('connected');
});
it('preserves repeated legitimate partial words (no content-based dedup)', async () => {
await startConnected();
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 't1',
role: 'assistant',
text: 'بله',
status: 'partial',
});
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 't1',
role: 'assistant',
text: ' بله',
status: 'partial',
});
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 't1',
role: 'assistant',
text: ' بله',
status: 'partial',
});
expect(service.messages()[0].text).toBe('بله بله بله');
});
it('does not downgrade a limited answer on delayed completed/partial events', async () => {
await startConnected();
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 't1',
role: 'assistant',
text: 'پاسخ محدود',
status: 'limited',
});
// Delayed frames for the same turn arrive after the final snapshot.
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 't1',
role: 'assistant',
text: 'پاسخ کامل‌تر',
status: 'completed',
});
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 't1',
role: 'assistant',
text: ' ادامه',
status: 'partial',
});
const assistant = service.messages().find((m) => m.id === 't1:assistant');
expect(assistant?.limited).toBe(true); // never reverts to completed/partial
expect(assistant?.final).toBe(true);
expect(assistant?.text).toBe('پاسخ کامل‌تر'); // the late partial did not extend it
});
it('lets turn_interrupted take precedence over limited and blocks late text', async () => {
await startConnected();
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'پاسخ ',
status: 'partial',
});
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'پاسخ نهایی',
status: 'limited',
});
transportHandlers?.onEvent(MARKER);
engineClear.mockClear();
transportHandlers?.onEvent({ type: 'turn_interrupted', turn_ref: 'turn-1' });
const assistant = service.messages().find((m) => m.id === 'turn-1:assistant');
expect(assistant?.interrupted).toBe(true); // interruption wins over the limited state
expect(engineClear).toHaveBeenCalledTimes(1); // the existing barge-in flush still runs
// Late assistant text cannot restore the interrupted answer.
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'متن دیرکرده',
status: 'limited',
});
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'ادامه',
status: 'partial',
});
const after = service.messages().find((m) => m.id === 'turn-1:assistant');
expect(after?.text).toBe('پاسخ نهایی');
expect(after?.interrupted).toBe(true);
});
it('does not mark an already interrupted answer as limited', async () => {
await startConnected();
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'پاسخ',
status: 'partial',
});
transportHandlers?.onEvent({ type: 'turn_interrupted', turn_ref: 'turn-1' });
transportHandlers?.onEvent(MARKER);
const assistant = service.messages().find((m) => m.id === 'turn-1:assistant');
expect(assistant?.interrupted).toBe(true);
expect(assistant?.limited).toBeFalsy();
});
it('does not mark a sources-only row of an interrupted turn as limited', async () => {
await startConnected();
// The turn is capped, then cut off before any transcript row exists, then its
// sources arrive: the row must not be presented as a limited answer.
transportHandlers?.onEvent(MARKER);
transportHandlers?.onEvent({ type: 'turn_interrupted', turn_ref: 'turn-1' });
transportHandlers?.onEvent({
type: 'sources',
turn_ref: 'turn-1',
sources: [{ source_ref: 'src-1', document_id: 'doc-1', chunk_id: 'chunk-1', title: 'سند' }],
});
const assistant = service.messages().find((m) => m.id === 'turn-1:assistant');
expect(assistant?.limited).toBeFalsy();
expect(assistant?.sources).toHaveLength(1);
});
it('keeps a delayed user transcript attached to its own turn, independent of assistant status', async () => {
await startConnected();
transportHandlers?.onEvent({ type: 'user_speech_started', turn_ref: 'turn-1' });
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'پاسخ اول',
status: 'limited',
});
// Turn 2 starts before turn 1's user transcript is finalized.
transportHandlers?.onEvent({ type: 'user_speech_started', turn_ref: 'turn-2' });
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-2',
role: 'assistant',
text: 'پاسخ دوم',
status: 'partial',
});
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'user',
text: 'سوال اول',
status: 'completed',
});
const list = service.messages();
expect(list.map((m) => m.id)).toEqual([
'turn-1:user',
'turn-1:assistant',
'turn-2:assistant',
]);
expect(list.find((m) => m.id === 'turn-1:user')?.text).toBe('سوال اول');
expect(list.find((m) => m.id === 'turn-1:user')?.limited).toBeFalsy();
expect(list.find((m) => m.id === 'turn-1:assistant')?.limited).toBe(true);
expect(list.find((m) => m.id === 'turn-2:assistant')?.limited).toBeFalsy();
});
it('cannot let an old session marker contaminate a new session', async () => {
await startConnected(); // session A
transportHandlers?.onEvent({
type: 'answer_limited',
turn_ref: 'shared-turn',
reason: 'output_token_limit',
});
await service.close();
await startConnected(); // session B
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'shared-turn',
role: 'assistant',
text: 'پاسخ تازه',
status: 'partial',
});
const assistant = service.messages().find((m) => m.id === 'shared-turn:assistant');
expect(assistant?.text).toBe('پاسخ تازه');
expect(assistant?.limited).toBeFalsy(); // session A's metadata did not leak
});
it('does not stop capture, close the socket, flush audio or reset playback progress', async () => {
await startConnected();
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' });
engineHandlers?.onPlaybackProgress('aud-1', 120);
controls = [];
engineFlush.mockClear();
engineClear.mockClear();
engineStop.mockClear();
transportMock.close.mockClear();
transportHandlers?.onEvent(MARKER);
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'پاسخ',
status: 'limited',
});
expect(engineFlush).not.toHaveBeenCalled(); // no flush/mute of playback
expect(engineClear).not.toHaveBeenCalled();
expect(engineStop).not.toHaveBeenCalled(); // microphone keeps capturing
expect(transportMock.close).not.toHaveBeenCalled(); // socket stays open
expect(api.closeVoiceSession).not.toHaveBeenCalled(); // no backend close request
expect(service.connection()).toBe('connected');
expect(service.state()).toBe('LISTENING');
// Capture keeps flowing and playback progress keeps being reported.
engineHandlers?.onFrame(new ArrayBuffer(9600), 0.5);
expect(transportMock.sendAudio).toHaveBeenCalledTimes(1);
engineHandlers?.onPlaybackProgress('aud-1', 300);
expect(controls).toEqual([{ type: 'playback_progress', audio_ref: 'aud-1', played_ms: 300 }]);
});
it('keeps buffered audio playing after the marker; audio_ended only seals generation', async () => {
await startConnected();
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' });
transportHandlers?.onAudio(new ArrayBuffer(9600)); // real binary audio
expect(service.state()).toBe('SPEAKING');
engineHandlers?.onPlaybackProgress('aud-1', 100);
controls = [];
engineFlush.mockClear();
transportHandlers?.onEvent(MARKER);
// Still playing: state unchanged, no flush, no clear, audio keeps arriving.
expect(service.state()).toBe('SPEAKING');
expect(engineFlush).not.toHaveBeenCalled();
expect(engineClear).not.toHaveBeenCalled();
transportHandlers?.onAudio(new ArrayBuffer(9600));
expect(engineStop).not.toHaveBeenCalled();
// audio_ended seals GENERATION (drain) — it is not actual playback completion:
// progress keeps being reported from what the worklet really plays.
transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'aud-1' });
expect(engineFlush).toHaveBeenCalledTimes(1);
expect(service.state()).toBe('SPEAKING');
engineHandlers?.onPlaybackProgress('aud-1', 400);
expect(controls).toEqual([{ type: 'playback_progress', audio_ref: 'aud-1', played_ms: 400 }]);
// The turn only finishes when playback actually drains.
vi.useFakeTimers();
try {
engineHandlers?.onPlaybackIdle();
vi.advanceTimersByTime(900); // no completed transcript for this limited turn → settle
} finally {
vi.useRealTimers();
}
expect(service.state()).toBe('LISTENING');
});
it('does not leave the UI thinking when a limited answer produces no audio', async () => {
await startConnected();
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'user',
text: 'سوال',
status: 'completed',
});
expect(service.state()).toBe('PROCESSING');
// The marker lands while no audio is outstanding at all.
vi.useFakeTimers();
try {
transportHandlers?.onEvent(MARKER);
vi.advanceTimersByTime(900); // the bounded settle fallback
} finally {
vi.useRealTimers();
}
expect(service.state()).toBe('LISTENING'); // usable again, session alive
expect(service.connection()).toBe('connected');
// The user can immediately speak a genuine continuation ("ادامه بده").
engineHandlers?.onFrame(new ArrayBuffer(9600), 0.5);
expect(transportMock.sendAudio).toHaveBeenCalledTimes(1);
});
it('reports the real final played progress when a limited answer is interrupted', async () => {
await startConnected();
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'پاسخ',
status: 'limited',
});
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-2' });
engineHandlers?.onPlaybackProgress('aud-2', 300);
controls = [];
transportHandlers?.onEvent({ type: 'turn_interrupted', turn_ref: 'turn-1' });
// The worklet answers `clear` with its final cumulative report for the ref.
engineHandlers?.onPlaybackProgress('aud-2', 780);
expect(controls).toEqual([{ type: 'playback_progress', audio_ref: 'aud-2', played_ms: 780 }]);
});
it('never auto-continues, fabricates a control message or recreates the session', async () => {
await startConnected();
controls = [];
transportHandlers?.onEvent(MARKER);
expect(controls).toEqual([]); // no continue/resume/response.create text command
expect(api.createVoiceSession).toHaveBeenCalledTimes(1); // no second reservation
expect(transportMock.connect).toHaveBeenCalledTimes(1); // no second socket
expect(api.closeVoiceSession).not.toHaveBeenCalled(); // no close request either
expect(service.connection()).toBe('connected'); // the session stays usable
});
it('still fails safely on a genuine error frame after a limited answer', async () => {
await startConnected();
const ended = firstEndedError();
transportHandlers?.onEvent(MARKER);
transportHandlers?.onEvent({
type: 'error',
error: { code: 'LIVE_BUFFER_OVERFLOW', message: 'overflow', retryable: false },
});
expect(await ended).toBe('overflow'); // a fatal error is NOT reinterpreted as limited
expect(api.closeVoiceSession).toHaveBeenCalledTimes(1);
expect(service.connection()).toBe('disconnected');
});
it('still fails safely on a real playback overflow after a limited answer', async () => {
await startConnected();
const ended = firstEndedError();
transportHandlers?.onEvent(MARKER);
engineHandlers?.onPlaybackOverflow();
expect(await ended).toBe(OVERFLOW_MESSAGE);
expect(service.connection()).toBe('disconnected');
});
it('keeps the ordinary completed-answer flow of an older backend intact', async () => {
await startConnected();
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' });
transportHandlers?.onAudio(new ArrayBuffer(9600));
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'پاسخ کامل',
status: 'completed',
});
transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'aud-1' });
const assistant = service.messages().find((m) => m.id === 'turn-1:assistant');
expect(assistant?.text).toBe('پاسخ کامل');
expect(assistant?.limited).toBeFalsy();
expect(assistant?.final).toBe(true);
expect(engineFlush).toHaveBeenCalledTimes(1);
engineHandlers?.onPlaybackIdle();
expect(service.state()).toBe('LISTENING'); // completed turns finish immediately
});
});
}); });
@@ -1,6 +1,7 @@
import { Injectable, NgZone, computed, inject, signal } from '@angular/core'; import { Injectable, NgZone, computed, inject, isDevMode, signal } from '@angular/core';
import { Subject } from 'rxjs'; import { Subject } from 'rxjs';
import { MicrophoneError } from '../microphone/microphone.service'; import { MicrophoneError } from '../microphone/microphone.service';
import { uuid } from '../../shared/utils/uuid';
import { VoiceApiError, VoiceApiService, VoiceSessionResponse } from './voice-api.service'; import { VoiceApiError, VoiceApiService, VoiceSessionResponse } from './voice-api.service';
import { VoiceAudioEngine, VoiceEngineError } from './voice-audio-engine.service'; import { VoiceAudioEngine, VoiceEngineError } from './voice-audio-engine.service';
import { VOICE_TRANSPORT_FACTORY, VoiceTransport } from './voice-transport'; import { VOICE_TRANSPORT_FACTORY, VoiceTransport } from './voice-transport';
@@ -12,6 +13,7 @@ import {
VoiceSessionEnd, VoiceSessionEnd,
VoiceStreamState, VoiceStreamState,
} from './voice-stream.types'; } from './voice-stream.types';
import { VoiceCueService } from './voice-cue.service';
export type VoiceStartFailure = export type VoiceStartFailure =
| 'cancelled' | 'cancelled'
@@ -25,15 +27,38 @@ export type VoiceStartFailure =
| 'overflow'; | 'overflow';
export type VoiceStartResult = export type VoiceStartResult =
| { ok: true } { ok: true } | { ok: false; reason: VoiceStartFailure; message: string };
| { ok: false; reason: VoiceStartFailure; message: string };
type TranscriptEvent = Extract<VoiceServerEvent, { type: 'transcript' }>; type TranscriptEvent = Extract<VoiceServerEvent, { type: 'transcript' }>;
type SourcesEvent = Extract<VoiceServerEvent, { type: 'sources' }>; type SourcesEvent = Extract<VoiceServerEvent, { type: 'sources' }>;
type ErrorEvent = Extract<VoiceServerEvent, { type: 'error' }>; type ErrorEvent = Extract<VoiceServerEvent, { type: 'error' }>;
/**
* Options for the single per-session cleanup (`teardown`). One cleanup runs per session and
* is shared by overflow, server error, socket close, manual Stop, unmount and start aborts.
*/
interface TeardownOptions {
/** User-facing (Persian) failure message carried on sessionEnded$. */
error?: string;
/** Machine-readable cause (e.g. `ws close 1006`) carried on sessionEnded$. */
detail?: string;
/**
* Intentional stop: final progress → V04 → release, the order the contract requires.
* `false` (default) releases local resources immediately and sends V04 best-effort —
* used for unmount / start-abort / page-leave, where instant release matters more.
*/
ordered?: boolean;
/** Send V04 /close for this session (default true). */
closeRemote?: boolean;
/** Emit sessionEnded$ if the call reached connected (default true). */
emitEnded?: boolean;
/** Keep the persisted creation attempt (ambiguous reserve / page-leave). Default false. */
keepAttempt?: boolean;
}
const MESSAGES = { const MESSAGES = {
unsupported: 'گفتگوی صوتی در این مرورگر پشتیبانی نمی‌شود (اتصال امن HTTPS و مرورگر جدید لازم است).', unsupported:
'گفتگوی صوتی در این مرورگر پشتیبانی نمی‌شود (اتصال امن HTTPS و مرورگر جدید لازم است).',
micDenied: 'دسترسی به میکروفون رد شد. اجازه‌ی دسترسی را در تنظیمات مرورگر فعال کنید.', micDenied: 'دسترسی به میکروفون رد شد. اجازه‌ی دسترسی را در تنظیمات مرورگر فعال کنید.',
micUnavailable: 'میکروفونی پیدا نشد یا در حال استفاده‌ی برنامه‌ی دیگری است.', micUnavailable: 'میکروفونی پیدا نشد یا در حال استفاده‌ی برنامه‌ی دیگری است.',
micLost: 'اتصال میکروفون قطع شد و گفتگو پایان یافت.', micLost: 'اتصال میکروفون قطع شد و گفتگو پایان یافت.',
@@ -47,6 +72,7 @@ const MESSAGES = {
connect: 'اتصال به سرور صوتی برقرار نشد. دوباره تلاش کنید.', connect: 'اتصال به سرور صوتی برقرار نشد. دوباره تلاش کنید.',
badFormat: 'فرمت صدای سرور با برنامه سازگار نیست.', badFormat: 'فرمت صدای سرور با برنامه سازگار نیست.',
overflow: 'حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو به‌طور ایمن پایان یافت.', overflow: 'حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو به‌طور ایمن پایان یافت.',
sendOverflow: 'حجم صدای ارسالی از محدودهٔ مجاز گذشت و گفتگو به‌طور ایمن پایان یافت.',
disconnected: 'ارتباط با سرور قطع شد و گفتگو پایان یافت.', disconnected: 'ارتباط با سرور قطع شد و گفتگو پایان یافت.',
server: 'سرور گفتگوی صوتی با خطا مواجه شد.', server: 'سرور گفتگوی صوتی با خطا مواجه شد.',
contextRevoked: 'محتوای دانش تغییر کرده و مکالمهٔ قبلی دیگر معتبر نیست. گفتگوی جدیدی شروع کنید.', contextRevoked: 'محتوای دانش تغییر کرده و مکالمهٔ قبلی دیگر معتبر نیست. گفتگوی جدیدی شروع کنید.',
@@ -60,13 +86,23 @@ const INTERRUPTED_FLASH_MS = 150;
const ERROR_BANNER_MS = 6000; const ERROR_BANNER_MS = 6000;
/** Longest wait for the worklet's final playback report when closing a call. */ /** Longest wait for the worklet's final playback report when closing a call. */
const FINAL_PROGRESS_WAIT_MS = 300; const FINAL_PROGRESS_WAIT_MS = 300;
/** Longest wait for V04 /close before releasing local resources anyway (the POST keeps running). */
const CLOSE_WAIT_MS = 3000;
/**
* Bounded per-turn answer-state memory (turns the server marked `answer_limited`, and
* turns it interrupted). A marker can arrive before its transcript row exists, so the
* record must survive until the row lands — but a long call must not grow it forever,
* so the oldest entries are dropped past this cap.
*/
const TURN_STATE_MEMORY = 50;
/** /**
* One live voice call against the backend handoff contract (§7–§9): * One live voice call against the backend handoff contract (§7–§9):
* *
* mic ─▶ engine ─▶ PCM16 24 kHz frames ─▶ WSS ─▶ server * mic ─▶ engine ─▶ PCM16 24 kHz frames ─▶ WSS ─▶ server
* server ─▶ session_ready / user_speech_started / transcript / sources / * server ─▶ session_ready / user_speech_started / transcript / sources /
* audio_started / audio_ended / turn_interrupted / error (JSON) * audio_started / audio_ended / turn_interrupted / answer_limited /
* error (JSON)
* ─▶ PCM16 24 kHz audio (binary) ─▶ engine playback * ─▶ PCM16 24 kHz audio (binary) ─▶ engine playback
* client ─▶ playback_progress (the only JSON control message, cumulative played_ms) * client ─▶ playback_progress (the only JSON control message, cumulative played_ms)
* *
@@ -89,6 +125,7 @@ export class VoiceStreamService {
private readonly api = inject(VoiceApiService); private readonly api = inject(VoiceApiService);
private readonly config = inject(VOICE_STREAM_CONFIG); private readonly config = inject(VOICE_STREAM_CONFIG);
private readonly createTransport = inject(VOICE_TRANSPORT_FACTORY); private readonly createTransport = inject(VOICE_TRANSPORT_FACTORY);
private readonly cues = inject(VoiceCueService);
readonly state = signal<VoiceStreamState>('IDLE'); readonly state = signal<VoiceStreamState>('IDLE');
readonly connection = signal<VoiceConnection>('disconnected'); readonly connection = signal<VoiceConnection>('disconnected');
@@ -106,9 +143,13 @@ export class VoiceStreamService {
private transport: VoiceTransport | null = null; private transport: VoiceTransport | null = null;
private remote: { sessionId: string; conversationId: string; csrf: string } | null = null; private remote: { sessionId: string; conversationId: string; csrf: string } | null = null;
/** Single-flight guard: at most one cleanup runs per active session (one /close each). */
private cleanupPromise: Promise<void> | null = null;
private session = 0; private session = 0;
private streaming = false; private streaming = false;
private turnEnded = false; private traceStarted = performance.now();
private underrunStarted: number | null = null;
private audioGenerationDone = false; // server finished sending this audio_ref's frames
private interruptTimer: ReturnType<typeof setTimeout> | null = null; private interruptTimer: ReturnType<typeof setTimeout> | null = null;
private settleTimer: ReturnType<typeof setTimeout> | null = null; private settleTimer: ReturnType<typeof setTimeout> | null = null;
private errorTimer: ReturnType<typeof setTimeout> | null = null; private errorTimer: ReturnType<typeof setTimeout> | null = null;
@@ -124,7 +165,15 @@ export class VoiceStreamService {
/** Latest cumulative played_ms actually consumed by the worklet, per server audio_ref. */ /** Latest cumulative played_ms actually consumed by the worklet, per server audio_ref. */
private readonly playedMsByRef = new Map<string, number>(); private readonly playedMsByRef = new Map<string, number>();
private currentAudioRef: string | null = null; private currentAudioRef: string | null = null;
private readonly seenAudioRefs = new Set<string>();
private currentAudioTurnRef: string | null = null;
private currentAudioReceivedBytes = 0;
private currentAudioSentBytes: number | null = null;
private progressWaiters: Array<() => void> = []; private progressWaiters: Array<() => void> = [];
/** Turns whose answer the server marked limited (bounded; marker may precede its row). */
private readonly limitedTurns = new Set<string>();
/** Turns the server interrupted (bounded; late assistant text must not restore them). */
private readonly interruptedTurns = new Set<string>();
constructor() { constructor() {
this.attempt = loadPersistedAttempt(); this.attempt = loadPersistedAttempt();
@@ -144,15 +193,23 @@ export class VoiceStreamService {
if (!this.isSupported) return this.failure('unsupported', MESSAGES.unsupported); if (!this.isSupported) return this.failure('unsupported', MESSAGES.unsupported);
const session = ++this.session; const session = ++this.session;
this.traceStarted = performance.now();
this.underrunStarted = null;
const stale = (): boolean => session !== this.session; const stale = (): boolean => session !== this.session;
this.messages.set([]); this.messages.set([]);
this.muted.set(false); this.muted.set(false);
this.clearError(); this.clearError();
this.cleanupPromise = null;
this.resetTurnFlags(); this.resetTurnFlags();
// Per-session answer state: a new session can never inherit the previous one's
// limited/interrupted turn markers.
this.limitedTurns.clear();
this.interruptedTurns.clear();
this.lastConversationId = null; this.lastConversationId = null;
this.currentAudioRef = null; this.currentAudioRef = null;
this.playedMsByRef.clear(); this.playedMsByRef.clear();
this.seenAudioRefs.clear();
this.state.set('IDLE'); this.state.set('IDLE');
this.connection.set('connecting'); this.connection.set('connecting');
@@ -164,11 +221,12 @@ export class VoiceStreamService {
try { try {
await this.engine.start({ await this.engine.start({
onFrame: (pcm) => this.onMicFrame(pcm), onFrame: (pcm) => this.onMicFrame(pcm),
onPlaybackIdle: () => this.ngZone.run(() => this.onPlaybackIdle()), onPlaybackIdle: (audioRef) => this.ngZone.run(() => this.onPlaybackIdle(audioRef)),
onMicEnded: () => this.ngZone.run(() => this.failSession(MESSAGES.micLost, session)), onMicEnded: () => this.ngZone.run(() => this.failSession(MESSAGES.micLost, session)),
onPlaybackProgress: (audioRef, playedMs) => onPlaybackProgress: (audioRef, playedMs) =>
this.ngZone.run(() => this.onPlaybackProgress(audioRef, playedMs)), this.ngZone.run(() => this.onPlaybackProgress(audioRef, playedMs)),
onPlaybackOverflow: () => this.ngZone.run(() => this.failSession(MESSAGES.overflow, session)), onPlaybackOverflow: () =>
this.ngZone.run(() => this.failSession(MESSAGES.overflow, session)),
}); });
} catch (err) { } catch (err) {
return this.abortStart(session, this.mapEngineError(err)); return this.abortStart(session, this.mapEngineError(err));
@@ -221,8 +279,19 @@ export class VoiceStreamService {
transport.connect({ transport.connect({
onEvent: (event) => this.ngZone.run(() => this.onServerEvent(event, session)), onEvent: (event) => this.ngZone.run(() => this.onServerEvent(event, session)),
onAudio: (chunk) => this.onServerAudio(chunk, session), onAudio: (chunk) => this.onServerAudio(chunk, session),
onClose: () => this.ngZone.run(() => this.failSession(MESSAGES.disconnected, session)), onClose: (info) =>
onOverflow: () => this.ngZone.run(() => this.failSession(MESSAGES.overflow, session)), this.ngZone.run(() =>
this.failSession(MESSAGES.disconnected, session, this.describeSocketClose(info)),
),
onOverflow: (which) =>
this.ngZone.run(() =>
// Playback queue overflow and capture/send overflow are different faults with
// different causes; give each its own message instead of one shared string.
this.failSession(
which === 'send' ? MESSAGES.sendOverflow : MESSAGES.overflow,
session,
),
),
}), }),
); );
} catch { } catch {
@@ -253,6 +322,8 @@ export class VoiceStreamService {
this.connection.set('connected'); this.connection.set('connected');
this.state.set('LISTENING'); this.state.set('LISTENING');
this.streaming = true; this.streaming = true;
// "You can speak now" — once per session, not per turn (a turn cue would be noise).
this.cues.playReady();
return { ok: true }; return { ok: true };
} }
@@ -262,39 +333,21 @@ export class VoiceStreamService {
} }
/** /**
* Intentional close: final playback progress for the active audio_ref, then V04, and * Intentional close: routes through the single per-session cleanup so final progress →
* only then the socket/audio teardown — the order required by the contract. * V04 /close → release happens exactly once and in the order the contract requires.
* Concurrent callers (overflow / error / socket close / another Stop) reuse the same
* cleanup and cannot send a second /close or a second teardown.
*/ */
async close(options: { error?: string } = {}): Promise<void> { async close(options: { error?: string; detail?: string } = {}): Promise<void> {
if (!this.isOpen()) { // Idle with no cleanup in flight: nothing to close. A persisted creation attempt from
// Idle: nothing to close. A persisted creation attempt from an ambiguous reserve // an ambiguous reserve outcome is kept so the next start() reconciles it, not duplicates.
// outcome is kept so the next start() reconciles it instead of duplicating it. if (this.connection() === 'disconnected' && !this.cleanupPromise) return;
return; await this.teardown({
} ordered: true,
const remote = this.remote; closeRemote: true,
// 1) final, worklet-computed playback progress for the ref that is still playing error: options.error,
await this.reportFinalProgress(); detail: options.detail,
// 2) V04 before the transport closes });
if (remote) {
try {
await this.api.closeVoiceSession(remote.csrf, remote.sessionId);
} catch {
/* the session may already be closed/expired (e.g. 409 LIVE_SESSION_UNUSABLE) */
}
}
// 3) release mic, worklets, AudioContext and the WebSocket
const wasConnected = this.connection() === 'connected';
const conversationId = this.remote?.conversationId ?? this.lastConversationId;
// Invalidate pending async work BEFORE resolving the session_ready waiter, so a
// start() still waiting sees a cancelled session instead of a connect failure.
this.session++;
this.rejectReady();
this.finalizeAll();
const messages = this.messages();
this.teardown();
if (wasConnected) {
this.sessionEnded$.next({ conversationId, messages, error: options.error });
}
} }
/** /**
@@ -322,7 +375,10 @@ export class VoiceStreamService {
if (this.isOpen() || this.attempt !== attempt) return true; if (this.isOpen() || this.attempt !== attempt) return true;
let sessionId = attempt.sessionId; let sessionId = attempt.sessionId;
if (!sessionId) { if (!sessionId) {
const existing = await this.api.getVoiceSessionByRequest(me.csrf_token, attempt.sessionRequestId); const existing = await this.api.getVoiceSessionByRequest(
me.csrf_token,
attempt.sessionRequestId,
);
sessionId = existing?.session_id ?? null; sessionId = existing?.session_id ?? null;
} }
if (this.isOpen() || this.attempt !== attempt) return true; if (this.isOpen() || this.attempt !== attempt) return true;
@@ -366,7 +422,7 @@ export class VoiceStreamService {
dispose(): void { dispose(): void {
this.rejectReady(); this.rejectReady();
if (!this.isOpen()) return; // keep an ambiguous attempt for reconciliation if (!this.isOpen()) return; // keep an ambiguous attempt for reconciliation
this.teardown(); void this.teardown({ ordered: false, closeRemote: true, emitEnded: false });
} }
// ---- audio from the microphone (outside the zone) -------------------------- // ---- audio from the microphone (outside the zone) --------------------------
@@ -379,7 +435,15 @@ export class VoiceStreamService {
private onServerAudio(chunk: ArrayBuffer, session: number): void { private onServerAudio(chunk: ArrayBuffer, session: number): void {
if (session !== this.session || !this.streaming) return; if (session !== this.session || !this.streaming) return;
if (this.underrunStarted !== null) {
this.audioTrace('underrun_resumed', { gapMs: Math.floor(performance.now() - this.underrunStarted) });
this.underrunStarted = null;
}
const chunkBytes = chunk.byteLength; // transfer to the worklet detaches this buffer
this.currentAudioReceivedBytes += chunkBytes;
this.audioTrace('audio_received', { chunkBytes });
this.engine.enqueuePlayback(chunk, this.currentAudioRef); this.engine.enqueuePlayback(chunk, this.currentAudioRef);
this.audioTrace('audio_enqueued', { chunkBytes });
this.clearSettleTimer(); this.clearSettleTimer();
if (this.state() !== 'SPEAKING') { if (this.state() !== 'SPEAKING') {
@@ -399,6 +463,7 @@ export class VoiceStreamService {
if (playedMs <= 0) return; if (playedMs <= 0) return;
// Keep the latest cumulative value per ref; the final report is sent from here too. // Keep the latest cumulative value per ref; the final report is sent from here too.
this.playedMsByRef.set(audioRef, playedMs); this.playedMsByRef.set(audioRef, playedMs);
if (audioRef === this.currentAudioRef) this.audioTrace('playback_progress', { playedMs });
this.sendPlaybackProgress(audioRef, playedMs); this.sendPlaybackProgress(audioRef, playedMs);
this.resolveProgressWaiters(); this.resolveProgressWaiters();
} }
@@ -422,6 +487,7 @@ export class VoiceStreamService {
const transport = this.transport; const transport = this.transport;
if (!ref || !transport || this.connection() !== 'connected') return Promise.resolve(); if (!ref || !transport || this.connection() !== 'connected') return Promise.resolve();
this.audioTrace('clear_session_end');
this.engine.clearPlayback(); // worklet answers with its final cumulative report this.engine.clearPlayback(); // worklet answers with its final cumulative report
return new Promise<void>((resolve) => { return new Promise<void>((resolve) => {
const done = (): void => { const done = (): void => {
@@ -472,18 +538,55 @@ export class VoiceStreamService {
break; break;
case 'audio_started': case 'audio_started':
if (
this.seenAudioRefs.has(event.audio_ref) ||
(event.turn_ref && this.interruptedTurns.has(event.turn_ref))
)
break;
this.seenAudioRefs.add(event.audio_ref);
this.currentAudioRef = event.audio_ref; this.currentAudioRef = event.audio_ref;
this.currentAudioTurnRef = event.turn_ref ?? null;
this.currentAudioReceivedBytes = 0;
this.currentAudioSentBytes = null;
this.audioGenerationDone = false; // frames for this ref are now streaming in
this.clearSettleTimer();
break; break;
case 'audio_ended': case 'audio_ended':
// Generation ended; the ref's audio may still be playing — its final progress is // Generation finished: emit the worklet's deferred tail and drain what is buffered so
// reported when the queue drains or the turn is interrupted. // the ref's FINAL playback progress reaches its true duration (no phantom outstanding
// sample the backend would read as a stall). This drives the drain on generation
// completion, cooperating with — not depending solely on — the completed transcript.
if (
event.audio_ref !== this.currentAudioRef ||
this.audioGenerationDone ||
(event.turn_ref &&
this.currentAudioTurnRef &&
event.turn_ref !== this.currentAudioTurnRef)
)
break;
this.audioGenerationDone = true;
this.currentAudioSentBytes = event.sent_bytes ?? null;
if (event.sent_bytes !== undefined && event.sent_bytes !== this.currentAudioReceivedBytes) {
console.warn('Voice audio delivery mismatch', {
sentBytes: event.sent_bytes,
receivedBytes: this.currentAudioReceivedBytes,
});
}
this.audioTrace('flush_audio_ended');
this.engine.flushPlayback(this.currentAudioRef);
break; break;
case 'turn_interrupted': case 'turn_interrupted':
this.onTurnInterrupted(event.turn_ref); this.onTurnInterrupted(event.turn_ref);
break; break;
case 'answer_limited':
// Answer state only — see onAnswerLimited: no cleanup, no socket/mic/playback
// side effects, no automatic continuation.
this.onAnswerLimited(event.turn_ref);
break;
case 'error': case 'error':
this.onServerError(event, session); this.onServerError(event, session);
break; break;
@@ -506,17 +609,61 @@ export class VoiceStreamService {
return; return;
} }
if (event.status === 'completed') { if (event.status === 'completed') return;
// All text for this turn is out. Play what is buffered, then return to LISTENING.
this.turnEnded = true; if (event.status === 'limited') {
this.engine.flushPlayback(); // An answer state, not a playback or session event: the limited transcript does
// NOT seal the audio reference, so generated audio keeps playing until audio_ended
// and the real queue drain finish it. Only the "thinking" state needs a bounded
// fallback, for a limited answer that produced no audio to drain.
this.scheduleLimitedSettle();
} }
} }
/**
* `answer_limited`: the assistant answer reached the backend's output-token limit.
*
* This is an ANSWER state — not an error and not a session-lifecycle event. It must
* not close or reconnect the socket, stop the microphone, flush or mute playback,
* reset `audio_ref`/`played_ms`, mark the session failed, mark playback finished, ask
* the backend to close, or request another answer automatically. The audio already
* generated keeps playing; the user asks for more ("ادامه بده") as a genuine new
* microphone turn.
*/
private onAnswerLimited(turnRef: string): void {
this.rememberLimitedTurn(turnRef);
this.markLimited(turnRef);
this.scheduleLimitedSettle();
}
/**
* Never leave the UI permanently "thinking" after a limited answer: when audio is
* queued the state is SPEAKING and the normal drain path returns to LISTENING, but a
* limited answer can arrive with no outstanding audio at all — then schedule the same
* bounded settle the drain path uses.
*/
private scheduleLimitedSettle(): void {
if (this.state() !== 'PROCESSING' || this.currentAudioRef || this.settleTimer) return;
this.settleTimer = setTimeout(() => {
this.settleTimer = null;
if (this.state() === 'PROCESSING') this.finishTurn();
}, this.config.settleMs);
}
/** Server-side barge-in: the user spoke over the assistant. */ /** Server-side barge-in: the user spoke over the assistant. */
private onTurnInterrupted(turnRef: string): void { private onTurnInterrupted(turnRef: string): void {
if (this.currentAudioTurnRef && this.currentAudioTurnRef !== turnRef) {
this.markInterrupted(turnRef);
return;
}
this.audioTrace('clear_interruption');
this.underrunStarted = null;
this.engine.clearPlayback(); // the worklet posts the final progress for the active ref this.engine.clearPlayback(); // the worklet posts the final progress for the active ref
this.turnEnded = false; if (!this.currentAudioTurnRef || this.currentAudioTurnRef === turnRef) {
this.currentAudioRef = null;
this.currentAudioTurnRef = null;
this.audioGenerationDone = false;
}
this.clearSettleTimer(); this.clearSettleTimer();
this.markInterrupted(turnRef); this.markInterrupted(turnRef);
@@ -533,7 +680,10 @@ export class VoiceStreamService {
private onServerError(event: ErrorEvent, session: number): void { private onServerError(event: ErrorEvent, session: number): void {
const { message, retryable, code } = event.error; const { message, retryable, code } = event.error;
console.warn('VoiceStreamService: server error', code, event.error.request_id); // The server's `error` frame is the direct cause of a session ending here: below it
// drives failSession → V04 /close. `code` + `request_id` alone hide the message and
// any extra details, so log the whole frame.
console.warn('VoiceStreamService: server error frame', event.error);
// The old conversation/session is no longer usable: the user must start a fresh one // The old conversation/session is no longer usable: the user must start a fresh one
// (Gemini interruption can also require ending the session entirely). // (Gemini interruption can also require ending the session entirely).
@@ -547,13 +697,14 @@ export class VoiceStreamService {
} }
if (!retryable) { if (!retryable) {
this.failSession(message || MESSAGES.server, session); this.failSession(message || MESSAGES.server, session, `server error ${code}`);
return; return;
} }
// The session survives a retryable failure (e.g. SEARCH_TIMEOUT): drop the failed turn and keep listening. // The session survives a retryable failure (e.g. SEARCH_TIMEOUT): drop the failed turn and keep listening.
this.audioTrace('clear_retryable_error');
this.underrunStarted = null;
this.engine.clearPlayback(); this.engine.clearPlayback();
this.turnEnded = false;
this.clearSettleTimer(); this.clearSettleTimer();
this.finalizeAssistant(); this.finalizeAssistant();
if (this.state() === 'PROCESSING' || this.state() === 'SPEAKING') this.state.set('LISTENING'); if (this.state() === 'PROCESSING' || this.state() === 'SPEAKING') this.state.set('LISTENING');
@@ -562,79 +713,117 @@ export class VoiceStreamService {
// ---- end of an assistant turn ---------------------------------------------- // ---- end of an assistant turn ----------------------------------------------
private onPlaybackIdle(): void { /** Numeric browser timeline; backend timestamps use a different clock. */
const state = this.state(); private audioTrace(stage: string, counters: Record<string, number> = {}): void {
if (state !== 'SPEAKING' && state !== 'PROCESSING') return; if (!isDevMode()) return;
console.info('Voice audio trace', {
stage,
sessionId: this.remote?.sessionId,
turnRef: this.currentAudioTurnRef,
audioRef: this.currentAudioRef,
elapsedMs: Math.floor(performance.now() - this.traceStarted),
receivedBytes: this.currentAudioReceivedBytes,
sentBytes: this.currentAudioSentBytes,
...counters,
});
}
if (this.turnEnded) { private onPlaybackIdle(audioRef?: string | null): void {
if (audioRef && audioRef !== this.currentAudioRef) return;
if (this.state() !== 'SPEAKING' && this.state() !== 'PROCESSING') return;
if (!this.audioGenerationDone && this.currentAudioRef && this.underrunStarted === null) {
this.underrunStarted = performance.now();
this.audioTrace('underrun_started');
}
// A dry queue while generation is open is an underrun, not the end of a turn.
if (this.audioGenerationDone && this.currentAudioRef) {
const sent = this.currentAudioSentBytes;
const playedMs = this.playedMsByRef.get(this.currentAudioRef) ?? 0;
// played_ms is floored; less than one millisecond (48 bytes) may remain in that unit.
if (sent !== null && Math.abs(sent - playedMs * 48) >= 48) {
console.warn('Voice audio playback mismatch', { sentBytes: sent, playedMs });
}
this.audioTrace('audio_drained', { playedMs });
this.finishTurn(); this.finishTurn();
} else if (state === 'SPEAKING') {
// The buffer drained but no `completed` transcript arrived (yet). If no more audio comes, the turn is over.
this.clearSettleTimer();
this.settleTimer = setTimeout(() => {
this.settleTimer = null;
if (this.state() === 'SPEAKING') this.finishTurn();
}, this.config.settleMs);
} }
} }
private finishTurn(): void { private finishTurn(): void {
this.turnEnded = false; this.underrunStarted = null;
this.audioGenerationDone = false;
this.currentAudioRef = null;
this.currentAudioTurnRef = null;
this.clearSettleTimer(); this.clearSettleTimer();
this.finalizeAssistant();
this.state.set('LISTENING'); this.state.set('LISTENING');
} }
// ---- transcript ------------------------------------------------------------ // ---- transcript ------------------------------------------------------------
private upsertTranscript(event: TranscriptEvent): void { private upsertTranscript(event: TranscriptEvent): void {
const id = `${event.turn_ref}:${event.role}`; const id = `${event.turn_ref}:${event.role}`;
const final = event.status !== 'partial'; const final = event.status !== 'partial';
const interrupted = event.status === 'interrupted'; const interrupted = event.status === 'interrupted';
const limited = event.status === 'limited';
// `limited` is valid only for assistant rows (the transport rejects the rest), and a
// user transcript of a limited turn stays a plain user row.
const attachLimited =
event.role === 'assistant' && !interrupted && (limited || this.isLimitedTurn(event.turn_ref));
// A turn the server already interrupted cannot be restored by late assistant text
// (partial, completed or limited). The interrupted transcript itself still passes:
// it carries the final text of the cut-off answer.
if (event.role === 'assistant' && !interrupted && this.interruptedTurns.has(event.turn_ref)) {
return;
}
this.messages.update((list) => { this.messages.update((list) => {
const index = list.findIndex((m) => m.id === id); const index = list.findIndex((m) => m.id === id);
if (index === -1) { if (index === -1) {
if (!event.text.trim()) return list; // A `limited` transcript is kept even with empty text: the row carries the
return [ // answer state and the UI shows the unavailable-text presentation for it —
...list, // spoken text is never manufactured.
{ if (!event.text.trim() && !limited) return list;
return this.insertTranscript(list, {
id, id,
turnRef: event.turn_ref, turnRef: event.turn_ref,
role: event.role, role: event.role,
text: event.text, text: event.text,
final, final,
interrupted: interrupted || undefined, interrupted: interrupted || undefined,
}, limited: attachLimited || undefined,
]; });
} }
const current = list[index]; const current = list[index];
if (current.interrupted && !interrupted) return list; // late partial for a cut-off message if (current.interrupted && !interrupted) return list; // late partial for a cut-off message
// A late `partial` must not extend an answer that is already final (completed or
// limited): the answer would silently revert to growing partial text.
if (current.final && event.status === 'partial' && event.role === 'assistant') return list;
const copy = [...list]; const copy = [...list];
copy[index] = { copy[index] = {
...current, ...current,
text: this.mergeTranscriptText(current.text, event), text: this.mergeTranscriptText(current.text, event),
final: current.final || final, final: current.final || final,
interrupted: current.interrupted || interrupted || undefined, interrupted: current.interrupted || interrupted || undefined,
// Monotonic: once an answer is limited, a delayed completed/partial transcript
// cannot downgrade it back.
limited: current.limited || attachLimited || undefined,
}; };
return copy; return copy;
}); });
} }
/** /**
* The contract does not say whether a `partial` carries the full text so far or only the new fragment, * Transcript text semantics (contract):
* so both are handled: * - `partial` is a DELTA: it is appended as-is, with its own spacing. Identical
* - `completed` with text → the final full text replaces whatever was accumulated * deltas are legitimately repeated words and are never deduplicated by content.
* - text that starts with what we already have → cumulative, replace * - `completed` and `limited` are FINAL SNAPSHOTS: they replace the accumulated
* - anything else → a fragment, append as-is (fragments carry their own spacing) * text exactly, so the last partial accumulation is never kept alongside them.
*/ */
private mergeTranscriptText(previous: string, event: TranscriptEvent): string { private mergeTranscriptText(previous: string, event: TranscriptEvent): string {
const next = event.text; const next = event.text;
if (!next) return previous; if (!next) return previous;
if (!previous || event.status === 'completed') return next; if (event.status === 'partial') return previous + next;
if (next.startsWith(previous)) return next; return next;
return previous + next;
} }
private upsertSources(event: SourcesEvent): void { private upsertSources(event: SourcesEvent): void {
@@ -643,7 +832,17 @@ export class VoiceStreamService {
const index = list.findIndex((m) => m.id === id); const index = list.findIndex((m) => m.id === id);
const current: VoiceMessage = const current: VoiceMessage =
index === -1 index === -1
? { id, turnRef: event.turn_ref, role: 'assistant', text: '', final: false } ? {
id,
turnRef: event.turn_ref,
role: 'assistant',
text: '',
final: false,
// A sources row for a turn the server already marked limited shows the
// limited indication with the unavailable-text presentation — unless the
// turn was interrupted, which takes precedence.
limited: this.isLimitedTurn(event.turn_ref) || undefined,
}
: list[index]; : list[index];
const sources = [...(current.sources ?? [])]; const sources = [...(current.sources ?? [])];
@@ -659,24 +858,102 @@ export class VoiceStreamService {
} }
const next = { ...current, sources }; const next = { ...current, sources };
if (index === -1) return [...list, next]; if (index === -1) return this.insertTranscript(list, next);
const copy = [...list]; const copy = [...list];
copy[index] = next; copy[index] = next;
return copy; return copy;
}); });
} }
/**
* Inserts a new transcript bubble so the invariant always holds: WITHIN a turn the user
* request precedes the AI response, and turns keep their first-seen order. This matters when
* an assistant partial/response for a turn arrives before that turn's user transcript (the
* server streams transcripts per role and does not guarantee the user text lands first) —
* a plain append would then show the AI answer above the user's question.
*/
private insertTranscript(list: VoiceMessage[], message: VoiceMessage): VoiceMessage[] {
const roleRank = message.role === 'user' ? 0 : 1;
// Stable turn order = the order turns first appear in the current list; a turn we have
// not seen yet sorts after all existing ones.
const turns: string[] = [];
for (const m of list) if (!turns.includes(m.turnRef)) turns.push(m.turnRef);
const turnRank = turns.includes(message.turnRef)
? turns.indexOf(message.turnRef)
: turns.length;
for (let i = 0; i < list.length; i++) {
const existingTurn = turns.indexOf(list[i].turnRef);
const existingRank = list[i].role === 'user' ? 0 : 1;
const comesAfter =
existingTurn > turnRank || (existingTurn === turnRank && existingRank > roleRank);
if (comesAfter) return [...list.slice(0, i), message, ...list.slice(i)];
}
return [...list, message];
}
private markInterrupted(turnRef: string): void { private markInterrupted(turnRef: string): void {
this.rememberInterruptedTurn(turnRef);
const id = `${turnRef}:assistant`; const id = `${turnRef}:assistant`;
this.messages.update((list) => { this.messages.update((list) => {
const index = list.findIndex((m) => m.id === id); const index = list.findIndex((m) => m.id === id);
if (index === -1 || list[index].interrupted) return list; if (index === -1 || list[index].interrupted) return list;
const copy = [...list]; const copy = [...list];
// Interruption takes precedence over a limited marker on the same answer: the row
// is presented as cut off, not as a completed-capped answer.
copy[index] = { ...copy[index], final: true, interrupted: true }; copy[index] = { ...copy[index], final: true, interrupted: true };
return copy; return copy;
}); });
} }
/**
* Flag the assistant answer of `turnRef` as limited. When the row does not exist yet
* (the marker arrived before any transcript text) the bounded `limitedTurns` record
* carries the state until the row is created — no text is ever invented here.
*/
private markLimited(turnRef: string): void {
const id = `${turnRef}:assistant`;
this.messages.update((list) => {
const index = list.findIndex((m) => m.id === id);
// No row yet (the bounded record carries the state), already limited, or
// interrupted (interruption takes precedence): nothing to change.
if (index === -1 || list[index].limited || list[index].interrupted) return list;
const copy = [...list];
copy[index] = { ...copy[index], limited: true };
return copy;
});
}
/**
* Whether the server marked `turnRef`'s answer limited. Interrupted turns answer
* `false`: the interruption takes precedence over the limited state everywhere this
* predicate is used (transcript rows, sources rows and the marker application), so
* the answer is always presented as cut off rather than capped.
*/
private isLimitedTurn(turnRef: string): boolean {
return this.limitedTurns.has(turnRef) && !this.interruptedTurns.has(turnRef);
}
/** Bounded memory of limited turns; repeated markers are idempotent. */
private rememberLimitedTurn(turnRef: string): void {
this.limitedTurns.add(turnRef);
this.evictOldest(this.limitedTurns);
}
/** Bounded memory of interrupted turns, so late assistant text cannot restore them. */
private rememberInterruptedTurn(turnRef: string): void {
this.interruptedTurns.add(turnRef);
this.evictOldest(this.interruptedTurns);
}
private evictOldest(turns: Set<string>): void {
while (turns.size > TURN_STATE_MEMORY) {
const oldest = turns.values().next().value;
if (oldest === undefined) break;
turns.delete(oldest);
}
}
private finalizeAssistant(): void { private finalizeAssistant(): void {
this.messages.update((list) => this.messages.update((list) =>
list.some((m) => m.role === 'assistant' && !m.final) list.some((m) => m.role === 'assistant' && !m.final)
@@ -693,11 +970,29 @@ export class VoiceStreamService {
// ---- lifecycle ------------------------------------------------------------- // ---- lifecycle -------------------------------------------------------------
private failSession(message: string, session: number): void { /**
* The `CloseEvent` on the WebSocket carries the server's code and reason. Dropping it
* (as this handler used to) leaves a generic "disconnected" banner and no clue why the
* stream died, so the cause of an early disconnect cannot be diagnosed at all.
*
* Codes that matter in practice: 1000 = server ended the call normally, 1006 = the
* connection dropped with no close frame (proxy/network), 1008/1009 = policy violation
* (the server rejected a frame we sent), 1011 = server-side error.
*/
private describeSocketClose(info: { clean: boolean; code: number; reason: string }): string {
const reason = info.reason ? ` reason="${info.reason}"` : '';
const detail = `ws close ${info.code}${info.clean ? ' (clean)' : ''}${reason}`;
console.warn(`VoiceStreamService: socket closed — ${detail}`);
return detail;
}
private failSession(message: string, session: number, detail?: string): void {
if (session !== this.session || !this.isOpen()) return; if (session !== this.session || !this.isOpen()) return;
// `close()` performs the ordered teardown (final progress → V04 → transport) and // `close()` runs the ordered single-flight cleanup (final progress → V04 → release)
// emits sessionEnded$ exactly once, carrying the failure message. // and emits sessionEnded$ exactly once, carrying the first meaningful failure. The
void this.close({ error: message }); // `session`/isOpen guard above drops stale callbacks so an old session never ends a
// newer one.
void this.close({ error: message, detail });
} }
private abortStart( private abortStart(
@@ -705,44 +1000,145 @@ export class VoiceStreamService {
failure: { reason: VoiceStartFailure; message: string }, failure: { reason: VoiceStartFailure; message: string },
keepAttempt = false, keepAttempt = false,
): VoiceStartResult { ): VoiceStartResult {
if (session === this.session) this.teardown({ keepAttempt }); // Start-only failure: release immediately (unmount-style) and best-effort V04 for any
// reservation that was made. Keep the attempt when it was an ambiguous reserve so the
// next start() reconciles it with the same ids instead of duplicating.
if (session === this.session)
void this.teardown({ ordered: false, closeRemote: true, keepAttempt });
return this.failure(failure.reason, failure.message); return this.failure(failure.reason, failure.message);
} }
/** Releases every resource; idempotent. Invalidates all pending async work via `session`. */ /**
private teardown(options: { keepAttempt?: boolean } = {}): void { * The ONE cleanup per session. Every end path funnels through here: overflow, server
this.session++; * error, socket close, manual Stop, unmount, page-leave and start-abort. It is
* single-flight (`cleanupPromise`) so concurrent triggers share one pass — one /close and
* one resource release — and it marks the session stopping before any await, so stale
* callbacks cannot end a newer session.
*/
private teardown(options: TeardownOptions = {}): Promise<void> {
const existing = this.cleanupPromise;
if (existing) return existing; // a cleanup for the active session is already running
const promise = this.performTeardown(this.session, options).finally(() => {
if (this.cleanupPromise === promise) this.cleanupPromise = null;
});
this.cleanupPromise = promise;
return promise;
}
private async performTeardown(session: number, options: TeardownOptions): Promise<void> {
const wasConnected = this.connection() === 'connected';
const conversationId = this.remote?.conversationId ?? this.lastConversationId;
const remote = this.remote;
const superseded = (): boolean => this.session !== session + 1;
// Stop admitting new media BEFORE any await.
this.streaming = false; this.streaming = false;
// "Call finished" — once per connected session, before local resources (including the
// engine AudioContext) are released; every end path funnels through this single-flight
// cleanup, so ordered and unordered teardown both trigger it exactly once.
if (wasConnected) {
this.cues.playEnd();
}
const release = (): void => {
// A newer session may have taken over during an await: never touch its resources.
if (superseded()) return;
this.releaseLocal(options);
};
/** Drop all pending async work and supersede this session, so late callbacks are stale. */
const invalidate = (): void => {
if (this.session === session) this.session = session + 1;
this.resetTurnFlags(); this.resetTurnFlags();
this.clearSettleTimer(); this.rejectReady();
this.clearError();
this.resolveProgressWaiters(); this.resolveProgressWaiters();
this.currentAudioRef = null; this.clearSettleTimer();
if (this.interruptTimer) { if (this.interruptTimer) {
clearTimeout(this.interruptTimer); clearTimeout(this.interruptTimer);
this.interruptTimer = null; this.interruptTimer = null;
} }
this.currentAudioRef = null;
// The markers describe this session's turns only: drop them so a later session
// starts clean even if a late frame slipped through.
this.limitedTurns.clear();
this.interruptedTurns.clear();
};
if (options.ordered) {
try {
// 1) final playback progress (bounded) — still needs ref + connected transport.
await this.reportFinalProgress();
// 2) supersede the session, then V04 /close (bounded), then 3) release.
invalidate();
if (options.closeRemote !== false && remote) {
await this.withTimeout(
this.api.closeVoiceSession(remote.csrf, remote.sessionId),
CLOSE_WAIT_MS,
);
}
} catch {
/* the session may already be closed/expired (e.g. 409 LIVE_SESSION_UNUSABLE) */
} finally {
if (options.ordered) this.finalizeAll();
release();
}
} else {
// Unmount / start-abort / page-leave: invalidate + release immediately, then send V04
// best-effort in the background (it may not finish while the page is unloading).
invalidate();
release();
if (options.closeRemote !== false && remote) {
this.api.closeVoiceSession(remote.csrf, remote.sessionId).catch(() => {
/* already closed / expired: nothing to do */
});
}
}
if (options.ordered && options.emitEnded !== false && wasConnected && !superseded()) {
this.sessionEnded$.next({
conversationId,
messages: this.messages(),
error: options.error,
detail: options.detail,
});
}
}
/** Cancellable wait: resolve when `work` settles or after `ms`, whichever is first. The underlying request is left to finish. */
private withTimeout<T>(work: Promise<T>, ms: number): Promise<T | undefined> {
let timer: ReturnType<typeof setTimeout> | undefined;
const timedOut = new Promise<undefined>((resolve) => {
timer = setTimeout(() => resolve(undefined), ms);
});
return Promise.race([work.catch((): undefined => undefined), timedOut]).finally(() =>
clearTimeout(timer),
);
}
/** Release mic, worklets, AudioContext, socket and timers. Runs even if V04 failed. */
private releaseLocal(options: TeardownOptions): void {
const transport = this.transport; const transport = this.transport;
this.transport = null; this.transport = null;
transport?.close(); transport?.close();
this.engine.stop(); this.engine.stop();
// The reservation is over: drop the attempt so the next start() mints fresh request ids —
// unless an ambiguous reserve failure still needs the same ids replayed/reconciled.
const remote = this.remote;
this.remote = null; this.remote = null;
this.streaming = false;
// The reservation is over: drop the attempt so the next start() mints fresh request ids —
// unless an ambiguous reserve / page-leave still needs the same ids replayed/reconciled.
if (!options.keepAttempt) { if (!options.keepAttempt) {
this.attempt = null; this.attempt = null;
clearPersistedAttempt(); clearPersistedAttempt();
} }
if (remote) this.closeRemote(remote);
this.clearError();
this.connection.set('disconnected'); this.connection.set('disconnected');
this.state.set('IDLE'); this.state.set('IDLE');
this.muted.set(false); this.muted.set(false);
} }
/** Best-effort one-off V04 for a reservation produced by a start() that was just superseded. */
private closeRemote(remote: { sessionId: string; csrf: string }): void { private closeRemote(remote: { sessionId: string; csrf: string }): void {
this.api.closeVoiceSession(remote.csrf, remote.sessionId).catch(() => { this.api.closeVoiceSession(remote.csrf, remote.sessionId).catch(() => {
/* already closed / expired (e.g. 409 LIVE_SESSION_UNUSABLE): nothing to do */ /* already closed / expired (e.g. 409 LIVE_SESSION_UNUSABLE): nothing to do */
@@ -751,23 +1147,13 @@ export class VoiceStreamService {
private onPageLeave = (): void => { private onPageLeave = (): void => {
if (!this.isOpen()) return; if (!this.isOpen()) return;
const transport = this.transport;
const remote = this.remote;
this.session++;
this.streaming = false;
this.transport = null;
transport?.close();
this.engine.stop();
this.remote = null;
if (remote) this.closeRemote(remote);
// The attempt id/path stay in sessionStorage on purpose: the next page load reconciles // The attempt id/path stay in sessionStorage on purpose: the next page load reconciles
// it with V02/V03 (V04 may not complete while unloading) before anything else. // it with V02/V03 (V04 may not complete while unloading) before anything else.
this.connection.set('disconnected'); void this.teardown({ ordered: false, closeRemote: true, keepAttempt: true, emitEnded: false });
this.state.set('IDLE');
}; };
private resetTurnFlags(): void { private resetTurnFlags(): void {
this.turnEnded = false; this.audioGenerationDone = false;
} }
private clearSettleTimer(): void { private clearSettleTimer(): void {
@@ -919,7 +1305,8 @@ export class VoiceStreamService {
private mapEngineError(err: unknown): { reason: VoiceStartFailure; message: string } { private mapEngineError(err: unknown): { reason: VoiceStartFailure; message: string } {
if (err instanceof MicrophoneError) { if (err instanceof MicrophoneError) {
if (err.code === 'unsupported') return { reason: 'unsupported', message: MESSAGES.unsupported }; if (err.code === 'unsupported')
return { reason: 'unsupported', message: MESSAGES.unsupported };
return { return {
reason: 'mic', reason: 'mic',
message: err.code === 'denied' ? MESSAGES.micDenied : MESSAGES.micUnavailable, message: err.code === 'denied' ? MESSAGES.micDenied : MESSAGES.micUnavailable,
@@ -977,8 +1364,8 @@ const ATTEMPT_STORAGE_KEY = 'voice_creation_attempt';
function newCreationAttempt(): VoiceCreationAttempt { function newCreationAttempt(): VoiceCreationAttempt {
return { return {
conversationRequestId: crypto.randomUUID(), conversationRequestId: uuid(),
sessionRequestId: crypto.randomUUID(), sessionRequestId: uuid(),
conversationId: null, conversationId: null,
sessionId: null, sessionId: null,
streamPath: null, streamPath: null,
@@ -23,7 +23,11 @@ export interface VoiceSource {
chunk_id: string; chunk_id: string;
title: string; title: string;
excerpt?: string; excerpt?: string;
location?: { page?: number; section?: string } | null; /**
* 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. */ /** `false` = the excerpt is no longer valid and must be hidden, not kept on screen. */
available?: boolean; available?: boolean;
} }
@@ -34,7 +38,14 @@ export interface VoiceAudioFormat {
channels: number; channels: number;
} }
export type TranscriptStatus = 'partial' | 'completed' | 'interrupted'; 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 = export type VoiceServerEvent =
| { | {
@@ -52,16 +63,24 @@ export type VoiceServerEvent =
turn_ref: string; turn_ref: string;
role: 'user' | 'assistant'; role: 'user' | 'assistant';
/** /**
* Full text so far OR a new fragment: the contract does not say which, so * `partial` is a delta (append it); `completed` and `limited` are final
* `VoiceStreamService.mergeTranscriptText` accepts both (`completed` always carries the final text). * snapshots (they replace the accumulated text). See
* `VoiceStreamService.mergeTranscriptText`.
*/ */
text: string; text: string;
status: TranscriptStatus; status: TranscriptStatus;
} }
| { type: 'sources'; turn_ref: string; tool_call_id?: string; sources: VoiceSource[] } | { type: 'sources'; turn_ref: string; tool_call_id?: string; sources: VoiceSource[] }
| { type: 'audio_started'; audio_ref: string; turn_ref?: string } | { type: 'audio_started'; audio_ref: string; turn_ref?: string }
| { type: 'audio_ended'; 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[] } | { 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'; type: 'error';
turn_ref?: string; turn_ref?: string;
@@ -69,6 +88,9 @@ export type VoiceServerEvent =
error: { code: string; message: string; request_id?: string; retryable: boolean }; 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 * 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 time of `audio_ref` (computed from samples actually consumed by the
@@ -91,6 +113,11 @@ export interface VoiceMessage {
final: boolean; final: boolean;
/** assistant message cut short by the user speaking over it */ /** assistant message cut short by the user speaking over it */
interrupted?: boolean; 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 */ /** retrieved documents that back this answer */
sources?: VoiceSource[]; sources?: VoiceSource[];
} }
@@ -100,6 +127,12 @@ export interface VoiceSessionEnd {
messages: VoiceMessage[]; messages: VoiceMessage[];
/** User-facing (Persian) message when the session ended because of a failure. */ /** User-facing (Persian) message when the session ended because of a failure. */
error?: string; 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). */ /** V02/V03 polling shape (safe diagnostics only). */
@@ -120,7 +153,7 @@ export interface VoiceStreamConfig {
outputSampleRate: number; outputSampleRate: number;
frameMs: number; frameMs: number;
connectTimeoutMs: number; connectTimeoutMs: number;
/** After playback drains without a `completed` assistant transcript, wait this long, then return to LISTENING. */ /** Fallback only for a limited response with no audio reference. */
settleMs: number; settleMs: number;
/** Folder (relative to <base href>) holding the two *.worklet.js files, served from the UI origin. */ /** Folder (relative to <base href>) holding the two *.worklet.js files, served from the UI origin. */
workletBasePath: string; workletBasePath: string;
@@ -128,7 +161,7 @@ export interface VoiceStreamConfig {
export const DEFAULT_VOICE_STREAM_CONFIG: VoiceStreamConfig = { export const DEFAULT_VOICE_STREAM_CONFIG: VoiceStreamConfig = {
apiBase: '/api/v1', apiBase: '/api/v1',
apiOrigin: 'http://10.0.8.51:1322', apiOrigin: '',
inputSampleRate: 24000, inputSampleRate: 24000,
outputSampleRate: 24000, outputSampleRate: 24000,
frameMs: 20, frameMs: 20,
@@ -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 }),
]);
});
});
@@ -1,5 +1,6 @@
import { InjectionToken, inject } from '@angular/core'; import { InjectionToken, inject } from '@angular/core';
import { PlaybackProgressMessage, VOICE_STREAM_CONFIG, VoiceServerEvent } from './voice-stream.types'; import { PlaybackProgressMessage, VOICE_STREAM_CONFIG, VoiceServerEvent } from './voice-stream.types';
import { parseVoiceServerEvent } from './voice-event.validator';
export interface VoiceTransportHandlers { export interface VoiceTransportHandlers {
onEvent(event: VoiceServerEvent): void; onEvent(event: VoiceServerEvent): void;
@@ -32,6 +33,10 @@ const MAX_QUEUE_MESSAGES = 100;
* Plain WebSocket. Authentication is the `rag_session` cookie sent automatically on the * 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` * 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`. * 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 { export class WebSocketVoiceTransport implements VoiceTransport {
private ws: WebSocket | null = null; private ws: WebSocket | null = null;
@@ -41,6 +46,11 @@ export class WebSocketVoiceTransport implements VoiceTransport {
private sendQueue: ArrayBuffer[] = []; private sendQueue: ArrayBuffer[] = [];
private sendQueuedBytes = 0; private sendQueuedBytes = 0;
private sendQueuedMessages = 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( constructor(
private readonly url: string, private readonly url: string,
@@ -70,11 +80,13 @@ export class WebSocketVoiceTransport implements VoiceTransport {
ws.onmessage = (event: MessageEvent) => { ws.onmessage = (event: MessageEvent) => {
if (typeof event.data === 'string') { if (typeof event.data === 'string') {
try { // Allowlist + field guards: an unknown type or a malformed payload is dropped
handlers.onEvent(JSON.parse(event.data) as VoiceServerEvent); // here, exactly like malformed JSON always was — it never reaches the service,
} catch { // never enters an error path and never triggers cleanup.
/* ignore malformed control frames */ const parsed = parseVoiceServerEvent(event.data);
} if (!parsed) return;
this.traceFrame(parsed);
handlers.onEvent(parsed);
} else if (event.data instanceof ArrayBuffer) { } else if (event.data instanceof ArrayBuffer) {
handlers.onAudio(event.data); handlers.onAudio(event.data);
} }
@@ -84,7 +96,12 @@ export class WebSocketVoiceTransport implements VoiceTransport {
if (!opened) { if (!opened) {
clearTimeout(timer); clearTimeout(timer);
reject(new Error('connect-failed')); 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) => { ws.onclose = (event: CloseEvent) => {
@@ -95,6 +112,7 @@ export class WebSocketVoiceTransport implements VoiceTransport {
} }
this.dropSendQueue(); this.dropSendQueue();
if (!this.closedByClient) { if (!this.closedByClient) {
this.logDisconnect(event);
handlers.onClose({ clean: event.wasClean, code: event.code, reason: event.reason }); handlers.onClose({ clean: event.wasClean, code: event.code, reason: event.reason });
} }
}; };
@@ -150,6 +168,58 @@ export class WebSocketVoiceTransport implements VoiceTransport {
} }
} }
/**
* 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 { private flushSendQueue(): void {
const ws = this.ws; const ws = this.ws;
const queue = this.sendQueue; const queue = this.sendQueue;
+11 -4
View File
@@ -1,5 +1,5 @@
/* Shared chrome for the symbolic demonstration pages: /* Shared chrome for the symbolic demonstration pages:
«ارتباط با کال سنتر»، «بازخوانی تماس‌ها از کال سنتر» and «سوالات چت سایت و اپلیکیشن». «ارتباط با کال سنتر»، «بازخوانی تماس‌ها از کال سنتر» and «سوالات چت وب اپلیکیشن».
Each page component includes this file through styleUrls, so keep every selector Each page component includes this file through styleUrls, so keep every selector
page-agnostic (prefix: demo-). Visual language mirrors the reports/wallboard pages. */ page-agnostic (prefix: demo-). Visual language mirrors the reports/wallboard pages. */
@@ -75,7 +75,9 @@
border: 1px solid var(--card-border); border: 1px solid var(--card-border);
border-radius: 1.25rem; border-radius: 1.25rem;
background: var(--card-bg); background: var(--card-bg);
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.06), 0 2px 10px rgba(0, 0, 0, 0.03); 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; animation: demoFadeInUp 0.5s ease-out both;
} }
@@ -298,7 +300,10 @@
font-weight: 500; font-weight: 500;
border: 1px solid transparent; border: 1px solid transparent;
cursor: pointer; cursor: pointer;
transition: background-color 0.2s, border-color 0.2s, color 0.2s; transition:
background-color 0.2s,
border-color 0.2s,
color 0.2s;
} }
.demo-btn:disabled { .demo-btn:disabled {
@@ -525,5 +530,7 @@
} }
:host-context([data-bs-theme='dark']) .demo-card { :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); box-shadow:
0 10px 40px rgba(0, 0, 0, 0.3),
0 2px 10px rgba(0, 0, 0, 0.2);
} }
@@ -16,6 +16,12 @@
min-height: 460px; min-height: 460px;
} }
/* A live call replaces the composer: the call bar (rendered by the page) sits where the input was,
so the wrapper collapses instead of leaving an empty 72px box under it. */
.ai-chat-input-wrapper.stream-open {
min-height: 0;
}
/* Layers cross-fade */ /* Layers cross-fade */
.composer-layer, .composer-layer,
.voice-layer { .voice-layer {
@@ -57,14 +63,6 @@
transform: translateY(0) scale(1); transform: translateY(0) scale(1);
} }
:host-context(.has-messages) {
position: fixed;
bottom: 0;
left: 0;
right: 0;
z-index: 10;
}
/* ---------- Chat composer ---------- */ /* ---------- Chat composer ---------- */
.chat-composer { .chat-composer {
/* The composer lays itself out RTL explicitly: Plus on the right edge, Send on the left. /* The composer lays itself out RTL explicitly: Plus on the right edge, Send on the left.
@@ -128,7 +126,6 @@
} }
.composer-textarea::-webkit-scrollbar-thumb { .composer-textarea::-webkit-scrollbar-thumb {
background: var(--muted); background: var(--muted);
border: none;
border-radius: 9999px; border-radius: 9999px;
} }
@@ -2,6 +2,7 @@
class="ai-chat-input-wrapper" class="ai-chat-input-wrapper"
[class.voice-active]="anyVoiceActive()" [class.voice-active]="anyVoiceActive()"
[class.dictation-active]="isVoiceMode()" [class.dictation-active]="isVoiceMode()"
[class.stream-open]="streamOpen()"
[attr.data-voice-state]="voiceState()" [attr.data-voice-state]="voiceState()"
(keydown.escape)="onEscape()" (keydown.escape)="onEscape()"
> >
@@ -54,9 +54,9 @@
appearance: none; 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-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-repeat: no-repeat;
background-position: right 0.75rem center; background-position: right 1rem center;
padding-right: 2.5rem; padding: 0.75rem 1rem;
padding-left: 0.75rem; padding-right: 2.75rem;
background-color: var(--color-input-bg); background-color: var(--color-input-bg);
color: var(--text-secondary); color: var(--text-secondary);
border: 1px solid var(--color-input-border); border: 1px solid var(--color-input-border);
@@ -95,7 +95,7 @@
.form-visibility-toggle { .form-visibility-toggle {
position: absolute; position: absolute;
inset-inline-start: 0.5rem; inset-inline-end: 0.5rem;
top: 50%; top: 50%;
translate: 0 -50%; translate: 0 -50%;
display: flex; display: flex;
@@ -41,8 +41,9 @@ interface ModelOption {
<div class="ai-model-card settings-card"> <div class="ai-model-card settings-card">
<header class="ai-model-card-header"> <header class="ai-model-card-header">
<h3 class="text-base font-medium text-[var(--text-primary)]">{{ title() }}</h3> <h3 class="text-base font-medium text-[var(--text-primary)]">{{ title() }}</h3>
<span class="ai-model-badge" [class.ai-model-badge--connected]="connected()" <span class="ai-model-badge" [class.ai-model-badge--connected]="connected()">{{
>{{ connected() ? 'متصل' : 'متصل نشده' }}</span> connected() ? 'متصل' : 'متصل نشده'
}}</span>
</header> </header>
<div class="ai-model-body space-y-4"> <div class="ai-model-body space-y-4">
@@ -78,7 +79,9 @@ interface ModelOption {
<div class="form-field"> <div class="form-field">
<label class="form-label"> <label class="form-label">
کلید API کلید API
@if (apiKeyRequired()) { <span class="form-required" aria-hidden="true">*</span> } @if (apiKeyRequired()) {
<span class="form-required" aria-hidden="true">*</span>
}
</label> </label>
<div class="relative"> <div class="relative">
<input <input
@@ -96,25 +99,42 @@ interface ModelOption {
[attr.aria-label]="config().apiKeyVisible ? 'پنهان کن' : 'نمایش بده'" [attr.aria-label]="config().apiKeyVisible ? 'پنهان کن' : 'نمایش بده'"
(click)="toggleApiKeyVisibility()" (click)="toggleApiKeyVisibility()"
> >
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" <svg
stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
@if (config().apiKeyVisible) { @if (config().apiKeyVisible) {
<path d="M1 1l22 22M10.5 10.5A2.5 2.5 0 0 0 13.5 13.5M9.9 9.9L4.15 18.5A9.92 9.92 0 0 1 1 12 11.5 11.5 0 0 1 9.9 9.9Zm10.2 10.2A11.5 11.5 0 0 0 23 12a11.5 11.5 0 0 1-3.35-7.75l2.1-2.1A11.33 11.33 0 0 1 23 12a11.5 11.5 0 0 0-3.35 7.75Z" /> <!-- Eye Off: API key is visible -->
<circle cx="12" cy="12" r="1" /> <path d="M10.58 10.58a2 2 0 0 0 2.83 2.83" />
<line x1="1" y1="1" x2="23" y2="23" /> <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 { } @else {
<path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7-11-7-11-7z" /> <!-- 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" /> <circle cx="12" cy="12" r="3" />
<line x1="12" y1="1" x2="12" y2="12.01" />
} }
</svg> </svg>
</button> </button>
</div> </div>
<div class="form-hint"> <div class="form-hint">
@if (connected() && config().apiKey) { @if (connected() && config().apiKey) {
<span class="text-[var(--text-muted)]">تنظیم شده — مقدار فعلی نمایش داده نمی‌شود</span> <span class="text-[var(--text-muted)]"
>تنظیم شده — مقدار فعلی نمایش داده نمی‌شود</span
>
} @else { } @else {
<span class="text-[var(--text-muted)]">کلید در حافظه نگهداری می‌شود و ذخیره نمی‌شود</span> <span class="text-[var(--text-muted)]"
>کلید در حافظه نگهداری می‌شود و ذخیره نمی‌شود</span
>
} }
</div> </div>
</div> </div>
@@ -131,14 +151,21 @@ interface ModelOption {
[attr.aria-label]="'آدرس سرویس ' + title()" [attr.aria-label]="'آدرس سرویس ' + title()"
/> />
@if (!serviceUrlEditable()) { @if (!serviceUrlEditable()) {
<span class="text-[var(--text-muted)] mt-1 text-xs">آدرس استاندارد {{ config().provider === 'local' ? 'سرویس محلی' : 'سرویس' }} به‌صورت پیش‌فرض به کار می‌رود</span> <span class="text-[var(--text-muted)] mt-1 text-xs"
>آدرس استاندارد {{ config().provider === 'local' ? 'سرویس محلی' : 'سرویس' }} به‌صورت
پیش‌فرض به کار می‌رود</span
>
} }
</div> </div>
<!-- Actions --> <!-- Actions -->
<div class="ai-model-actions flex gap-2 pt-2"> <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--primary flex-1" (click)="save.emit()">
<button type="button" class="btn btn--outline flex-1" (click)="testConnection.emit()">بررسی اتصال</button> ذخیره تنظیمات
</button>
<button type="button" class="btn btn--outline flex-1" (click)="testConnection.emit()">
بررسی اتصال
</button>
</div> </div>
</div> </div>
</div> </div>
@@ -240,10 +267,7 @@ const DEFAULT_CONFIG_FOR: Record<AiProvider, { model: string; serviceUrl: string
const MODEL_OPTION = (value: string, label: string): ModelOption => ({ value, label }); const MODEL_OPTION = (value: string, label: string): ModelOption => ({ value, label });
const MODELS_BY_TASK: Record< const MODELS_BY_TASK: Record<AiTask, Partial<Record<AiProvider, ModelOption[]>>> = {
AiTask,
Partial<Record<AiProvider, ModelOption[]>>
> = {
text: { text: {
openai: [ openai: [
MODEL_OPTION('gpt-4o', 'GPT-4o'), MODEL_OPTION('gpt-4o', 'GPT-4o'),
+118 -46
View File
@@ -7,11 +7,14 @@
background: var(--sidebar-bg); background: var(--sidebar-bg);
color: var(--sidebar-text); color: var(--sidebar-text);
transform: translateX(0); transform: translateX(0);
transition: width 0.3s ease; /* The width transition drives the whole expansion; text reveal is gated by the
matching delay below so labels never reflow mid-flight. */
transition: width 0.35s cubic-bezier(0.4, 0, 0.2, 1);
z-index: 40; z-index: 40;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
border-left: 1px solid var(--sidebar-border); border-left: 1px solid var(--sidebar-border);
overflow: hidden;
} }
.sidebar.open { .sidebar.open {
@@ -30,6 +33,52 @@
overflow: hidden; overflow: hidden;
} }
/* Sidebar width animation: 0.35s. Text must not appear until the sidebar is wide
enough to hold the label on one line, so every label fades in only AFTER the
width transition finishes (delay = full duration) and fades out immediately
when collapsing. This prevents Persian text from wrapping vertically. */
:root {
--sidebar-expand-duration: 0.35s;
--sidebar-collapse-duration: 0.15s;
}
/* Scoped to `.sidebar`: the account menu is a CDK overlay rendered outside the sidebar
DOM, so unscoping these selectors would hide the username inside the dropdown too. */
.sidebar .nav-label,
.sidebar .history-text,
.sidebar .history-header .history-title,
.sidebar .user-info,
.sidebar .theme-toggle span {
max-width: 0;
opacity: 0;
overflow: hidden;
white-space: nowrap;
transform: translateX(-8px);
/* Fast fade OUT when collapsing — no delay on the way in. */
transition:
max-width var(--sidebar-collapse-duration) ease-in,
opacity var(--sidebar-collapse-duration) ease-in,
transform var(--sidebar-collapse-duration) ease-in;
}
/* Expanded state: the sidebar has finished growing, so the label can fade in.
`max-width: 100%` lets it occupy only the remaining space next to the icon
(never forcing a second line), and the delay guarantees the width is already
sufficient before the text becomes visible. */
.sidebar.open .nav-label,
.sidebar.open .history-text,
.sidebar.open .history-header .history-title,
.sidebar.open .user-info,
.sidebar.open .theme-toggle span {
max-width: 100%;
opacity: 1;
transform: translateX(0);
transition:
max-width var(--sidebar-expand-duration) ease-out var(--sidebar-expand-duration),
opacity var(--sidebar-expand-duration) ease-out var(--sidebar-expand-duration),
transform var(--sidebar-expand-duration) ease-out var(--sidebar-expand-duration);
}
.sidebar-top { .sidebar-top {
padding: 0.75rem; padding: 0.75rem;
display: flex; display: flex;
@@ -67,16 +116,19 @@
.sidebar:not(.open) .sidebar-logo-link { .sidebar:not(.open) .sidebar-logo-link {
justify-content: center; justify-content: center;
width: 100%; width: 40px;
height: 40px;
margin: 0 auto;
} }
.sidebar:not(.open) .sidebar-logo { .sidebar:not(.open) .sidebar-logo {
height: 36px; height: 28px;
} }
/* Keep the logo in the same 40px column as the nav items. */
.sidebar:not(.open) .sidebar-header { .sidebar:not(.open) .sidebar-header {
justify-content: center; justify-content: center;
padding: 0.5rem 0.25rem; padding: 0.5rem 0;
} }
.sidebar:not(.open) .close-btn { .sidebar:not(.open) .close-btn {
@@ -181,6 +233,8 @@
font-size: 0.875rem; font-size: 0.875rem;
font-weight: 500; font-weight: 500;
transition: background 0.2s; transition: background 0.2s;
/* Keep the icon and label on one line regardless of sidebar width. */
min-width: 0;
} }
.nav-item:hover { .nav-item:hover {
@@ -193,17 +247,28 @@
font-weight: 500; font-weight: 500;
} }
/* Collapsed rail (72px): a fixed 40px item column centred in the rail, so every icon
lines up with the others and with the logo/avatar above it. */
.sidebar:not(.open) .sidebar-top {
padding: 0.75rem 1rem;
align-items: center;
}
.sidebar:not(.open) .nav-item { .sidebar:not(.open) .nav-item {
justify-content: center; justify-content: center;
padding: 0.75rem 0; gap: 0;
width: 40px;
height: 40px;
padding: 0;
margin: 0 auto;
box-sizing: border-box;
} }
.sidebar:not(.open) .nav-item svg { .sidebar:not(.open) .nav-item .nav-icon {
margin: 0; flex-shrink: 0;
} display: flex;
align-items: center;
.sidebar:not(.open) .nav-label { justify-content: center;
display: none;
} }
.sidebar-divider { .sidebar-divider {
@@ -213,7 +278,8 @@
} }
.sidebar:not(.open) .sidebar-divider { .sidebar:not(.open) .sidebar-divider {
margin: 0 0.5rem; /* Same 40px column inset (16px each side of the 72px rail). */
margin: 0 1rem;
} }
.sidebar-bottom { .sidebar-bottom {
@@ -229,15 +295,6 @@
display: none; display: none;
} }
.history-header {
padding: 0.25rem 0.5rem;
font-size: 0.75rem;
font-weight: 500;
color: var(--sidebar-muted);
text-transform: uppercase;
letter-spacing: 0.05em;
}
.sidebar:not(.open) .history-header { .sidebar:not(.open) .history-header {
display: none; display: none;
} }
@@ -277,6 +334,23 @@
margin: 0; margin: 0;
} }
/* The whole lower section collapses with the sidebar; its labels animate via
the shared width/opacity transition defined earlier. */
.sidebar:not(.open) .history-header {
justify-content: center;
}
.history-header {
display: flex;
padding: 0.25rem 0.5rem;
font-size: 0.75rem;
font-weight: 500;
color: var(--sidebar-muted);
text-transform: uppercase;
letter-spacing: 0.05em;
min-width: 0;
}
.history-icon { .history-icon {
flex-shrink: 0; flex-shrink: 0;
opacity: 0.7; opacity: 0.7;
@@ -286,10 +360,7 @@
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;
} min-width: 0;
.sidebar:not(.open) .history-text {
display: none;
} }
.history-empty { .history-empty {
@@ -304,10 +375,6 @@
text-align: center; text-align: center;
} }
.sidebar:not(.open) .history-empty {
display: none;
}
.history-empty-icon { .history-empty-icon {
opacity: 0.5; opacity: 0.5;
margin-bottom: 0.25rem; margin-bottom: 0.25rem;
@@ -324,25 +391,20 @@
.sidebar:not(.open) .sidebar-footer { .sidebar:not(.open) .sidebar-footer {
align-items: center; align-items: center;
padding: 0.5rem; padding: 0.75rem 1rem;
margin-top: auto; margin-top: auto;
} }
.sidebar:not(.open) .user-info {
display: none;
}
.sidebar:not(.open) .user-profile { .sidebar:not(.open) .user-profile {
width: 56px; width: 40px;
height: 56px; height: 40px;
padding: 0; padding: 0;
gap: 0;
border-radius: 50%; border-radius: 50%;
justify-content: center; justify-content: center;
} }
.sidebar:not(.open) .theme-toggle span { /* Theme-toggle label animates with the shared transition instead of display:none. */
display: none;
}
.user-profile { .user-profile {
display: flex; display: flex;
@@ -356,6 +418,7 @@
color: var(--sidebar-text); color: var(--sidebar-text);
text-align: start; text-align: start;
cursor: pointer; cursor: pointer;
min-width: 0;
} }
.user-profile:hover, .user-profile:hover,
@@ -383,10 +446,16 @@
.account-menu-header { .account-menu-header {
display: flex; display: flex;
align-items: center; align-items: center;
/* dir="rtl" on .account-menu already lays children right→left, so the default
`row` order puts the avatar on the right and the name beside it to the left. */
gap: 0.5rem; gap: 0.5rem;
padding: 0.5rem; padding: 0.5rem;
} }
.account-menu-header .user-info {
text-align: start;
}
.account-menu-divider { .account-menu-divider {
height: 1px; height: 1px;
margin: 0.375rem 0.5rem; margin: 0.375rem 0.5rem;
@@ -396,6 +465,7 @@
.account-menu-item { .account-menu-item {
display: flex; display: flex;
align-items: center; align-items: center;
/* justify-content: space-between; */
gap: 0.75rem; gap: 0.75rem;
width: 100%; width: 100%;
padding: 0.625rem 0.75rem; padding: 0.625rem 0.75rem;
@@ -436,6 +506,7 @@
flex-direction: column; flex-direction: column;
gap: 0.125rem; gap: 0.125rem;
overflow: hidden; overflow: hidden;
min-width: 0;
} }
.user-name { .user-name {
@@ -479,9 +550,7 @@
margin: 0; margin: 0;
} }
.sidebar:not(.open) .claim-btn span { /* Label collapse is handled by the shared width/opacity transition. */
display: none;
}
.theme-toggle { .theme-toggle {
display: flex; display: flex;
@@ -504,17 +573,20 @@
} }
.sidebar:not(.open) .theme-toggle { .sidebar:not(.open) .theme-toggle {
width: 56px; width: 40px;
height: 56px; height: 40px;
padding: 0; padding: 0;
gap: 0;
border-radius: 0.5rem; border-radius: 0.5rem;
justify-content: center; justify-content: center;
} }
.sidebar:not(.open) .theme-toggle svg { .sidebar:not(.open) .theme-toggle svg {
margin: 0; margin: 0;
flex-shrink: 0;
} }
.sidebar:not(.open) .theme-toggle span { /* Collapsed rail: the avatar text must not stretch the 40px column. */
display: none; .sidebar:not(.open) .user-avatar {
flex-shrink: 0;
} }
@@ -44,6 +44,7 @@
fill="none" fill="none"
stroke="currentColor" stroke="currentColor"
stroke-width="2" stroke-width="2"
class="nav-icon"
> >
<path [attr.d]="item.icon" /> <path [attr.d]="item.icon" />
</svg> </svg>
@@ -116,13 +117,14 @@
</div> </div>
</button> </button>
<ng-template #accountMenu> <ng-template #accountMenu>
<div class="account-menu" cdkMenu aria-label="Account menu" dir="ltr"> <div class="account-menu" cdkMenu aria-label="Account menu" dir="rtl">
<div class="account-menu-header"> <div class="account-menu-header">
<div class="user-avatar">{{ userInitials() }}</div> <div class="user-avatar">{{ userInitials() }}</div>
<div class="user-info"> <div class="user-info">
<span class="user-name">{{ userName() }}</span> <span class="user-name">{{ userName() }}</span>
</div> </div>
</div> </div>
<!--
<div class="account-menu-divider" role="separator"></div> <div class="account-menu-divider" role="separator"></div>
<button type="button" class="account-menu-item" cdkMenuItem (cdkMenuItemTriggered)="profileClick.emit()"> <button type="button" class="account-menu-item" cdkMenuItem (cdkMenuItemTriggered)="profileClick.emit()">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
@@ -132,12 +134,13 @@
</svg> </svg>
<span>Profile</span> <span>Profile</span>
</button> </button>
-->
<div class="account-menu-divider" role="separator"></div> <div class="account-menu-divider" role="separator"></div>
<button type="button" class="account-menu-item" cdkMenuItem (cdkMenuItemTriggered)="logoutClick.emit()"> <button type="button" class="account-menu-item" cdkMenuItem (cdkMenuItemTriggered)="logoutClick.emit()">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9" /> <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9" />
</svg> </svg>
<span>Log out</span> <span>خروج</span>
</button> </button>
</div> </div>
</ng-template> </ng-template>
@@ -21,7 +21,7 @@ export interface ChatHistoryItem {
imports: [CommonModule, RouterModule, CdkMenuModule], imports: [CommonModule, RouterModule, CdkMenuModule],
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './sidebar.component.html', templateUrl: './sidebar.component.html',
styleUrl: './sidebar.component.css' styleUrl: './sidebar.component.css',
}) })
export class SidebarComponent { export class SidebarComponent {
private readonly themeService = inject(ThemeService); private readonly themeService = inject(ThemeService);
@@ -56,11 +56,11 @@ export class SidebarComponent {
}, },
{ {
icon: 'M7.9 20A9 9 0 1 0 4 16.1L2 22Z', icon: 'M7.9 20A9 9 0 1 0 4 16.1L2 22Z',
label: 'سوالات چت سایت و اپلیکیشن', label: 'سوالات چت وب اپلیکیشن',
route: '/chat-questions', route: '/chat-questions',
}, },
{ {
icon: 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.573-1.066zM15 12a3 3 0 11-6 0 3 3 0 016 0z', 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: 'تنظیمات', label: 'تنظیمات',
route: '/settings', route: '/settings',
}, },
@@ -69,7 +69,8 @@ export class SidebarComponent {
readonly close = output<void>(); readonly close = output<void>();
readonly navClick = output<void>(); readonly navClick = output<void>();
readonly open = output<void>(); readonly open = output<void>();
readonly profileClick = output<void>(); // Profile page is disabled; the account-menu entry is commented out in the template.
// readonly profileClick = output<void>();
readonly logoutClick = output<void>(); readonly logoutClick = output<void>();
readonly userInitials = computed(() => { readonly userInitials = computed(() => {
@@ -1,47 +1,52 @@
/* Host collapses its row to 0 when the call ends, so the composer never jumps when the bar is removed. */
:host { :host {
display: block; display: grid;
min-height: 0; grid-template-rows: 1fr;
height: 100%; opacity: 1;
animation: dockIn 0.35s cubic-bezier(0.22, 1, 0.36, 1);
transition:
grid-template-rows 0.35s cubic-bezier(0.22, 1, 0.36, 1),
opacity 0.3s ease,
margin 0.35s ease;
} }
.stream-panel { :host(.is-ended) {
--footer-h: 3.5rem; grid-template-rows: 0fr;
--orb-zone: 7.25rem; opacity: 0;
--orb-gap: 0.75rem; margin-bottom: 0 !important;
--reserve: calc(var(--footer-h) + var(--orb-gap) + var(--orb-zone) + var(--orb-gap)); pointer-events: none;
}
position: relative; .call-dock {
display: flex; direction: rtl;
flex-direction: column;
box-sizing: border-box; box-sizing: border-box;
min-height: 0; min-height: 0;
height: 100%;
direction: rtl;
background: transparent; /* was surface card */
border: none; /* removed card border */
border-radius: 0;
box-shadow: none; /* removed card shadow */
overflow: hidden; overflow: hidden;
background: var(--surface-bg);
border: 1px solid var(--surface-border);
border-radius: 1.25rem;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.03);
} }
/* ---------- Orb layer (behind the transcript) ---------- */ :host(.is-ended) .call-dock {
.stream-orb-layer { border-color: transparent;
position: absolute; box-shadow: none;
bottom: calc(var(--footer-h) + var(--orb-gap)); }
left: 50%;
transform: translateX(-50%); .dock-row {
z-index: 1;
display: flex; display: flex;
flex-direction: column;
align-items: center; align-items: center;
gap: 0.5rem; gap: 0.75rem;
transition: opacity 0.45s ease, transform 0.45s ease; padding: 0.5rem 0.75rem;
} }
/* ---------- Orb ---------- */
/* The canvas is larger than the bar is tall (negative margin) so the orb and its glow are not tiny. */
.orb-container { .orb-container {
width: 88px; width: 96px;
height: 88px; height: 96px;
max-width: 100%; margin-block: -20px;
margin-inline: -14px;
flex-shrink: 0; flex-shrink: 0;
display: flex; display: flex;
align-items: center; align-items: center;
@@ -56,11 +61,11 @@
/* Shown only when WebGL is unavailable */ /* Shown only when WebGL is unavailable */
.orb-fallback { .orb-fallback {
width: 70%; width: 55%;
height: 70%; height: 55%;
border-radius: 50%; border-radius: 50%;
background: radial-gradient(circle at 35% 30%, #93c5fd, #3b82f6 55%, #1e3a5f); background: radial-gradient(circle at 35% 30%, #93c5fd, #3b82f6 55%, #1e3a5f);
box-shadow: 0 0 40px rgba(59, 130, 246, 0.35); box-shadow: 0 0 24px rgba(59, 130, 246, 0.35);
animation: fallbackPulse 2.4s ease-in-out infinite; animation: fallbackPulse 2.4s ease-in-out infinite;
} }
@@ -70,12 +75,14 @@
transform: scale(1); transform: scale(1);
} }
50% { 50% {
transform: scale(1.06); transform: scale(1.08);
} }
} }
/* ---------- Status ---------- */ /* ---------- Status ---------- */
.stream-status { .dock-info {
flex: 1;
min-width: 0;
display: flex; display: flex;
align-items: center; align-items: center;
gap: 0.5rem; gap: 0.5rem;
@@ -83,9 +90,12 @@
.status-text { .status-text {
margin: 0; margin: 0;
font-size: 0.8125rem; min-width: 0;
font-size: 0.875rem;
color: var(--text-secondary); color: var(--text-secondary);
text-align: center; white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
} }
.status-dot { .status-dot {
@@ -97,22 +107,22 @@
transition: background 0.3s ease; transition: background 0.3s ease;
} }
.stream-status[data-state='LISTENING'] .status-dot { .status-dot[data-state='LISTENING'] {
background: #22c55e; background: #22c55e;
animation: dotPulse 1.6s ease-in-out infinite; animation: dotPulse 1.6s ease-in-out infinite;
} }
.stream-status[data-state='PROCESSING'] .status-dot { .status-dot[data-state='PROCESSING'] {
background: #818cf8; background: #818cf8;
animation: dotPulse 0.9s ease-in-out infinite; animation: dotPulse 0.9s ease-in-out infinite;
} }
.stream-status[data-state='SPEAKING'] .status-dot { .status-dot[data-state='SPEAKING'] {
background: #a78bfa; background: #a78bfa;
animation: dotPulse 0.7s ease-in-out infinite; animation: dotPulse 0.7s ease-in-out infinite;
} }
.stream-status[data-state='INTERRUPTED'] .status-dot { .status-dot[data-state='INTERRUPTED'] {
background: #f59e0b; background: #f59e0b;
} }
@@ -128,56 +138,91 @@
} }
} }
/* ---------- Transcript (overlaid on top of the orb) ---------- */ /* ---------- Controls ---------- */
.stream-transcript { .dock-actions {
position: relative;
z-index: 2;
flex: 1;
min-height: 0;
width: 100%;
max-width: 680px;
margin: 0 auto;
overflow-y: auto;
/* Hide the scrollbar, keep wheel / trackpad / touch scrolling */
scrollbar-width: none; /* Firefox */
-ms-overflow-style: none; /* legacy Edge */
padding: 1rem 0.75rem var(--reserve);
scroll-behavior: smooth;
transition: padding-bottom 0.45s ease;
}
.stream-transcript::-webkit-scrollbar {
display: none; /* Chrome, Safari, Edge */
width: 0;
height: 0;
}
/* ---------- Retryable server error ---------- */
.stream-error {
position: absolute;
bottom: calc(var(--footer-h) + 0.5rem);
left: 50%;
transform: translateX(-50%);
z-index: 3;
display: flex; display: flex;
align-items: center; align-items: center;
gap: 0.5rem; gap: 0.5rem;
width: min(100% - 1.5rem, 640px); flex-shrink: 0;
box-sizing: border-box; }
padding: 0.5rem 0.75rem;
.dock-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.375rem;
height: 40px;
min-width: 40px;
padding: 0 0.75rem;
border: 1px solid var(--surface-border);
border-radius: 9999px;
background: var(--surface-bg);
color: var(--text-secondary);
font-family: inherit;
font-size: 0.875rem;
cursor: pointer;
transition: background 0.2s ease, color 0.2s ease, border-color 0.2s ease, transform 0.15s ease;
user-select: none;
}
.dock-btn:hover:not(:disabled) {
background: var(--sidebar-hover);
color: var(--text-primary);
transform: scale(1.04);
}
.dock-btn:active:not(:disabled) {
transform: scale(0.96);
}
.dock-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.dock-btn:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
.dock-btn.is-active {
background: rgba(239, 68, 68, 0.1);
border-color: rgba(239, 68, 68, 0.5);
color: #dc2626;
}
.dock-btn.is-end {
background: #ef4444;
border-color: #ef4444;
color: #ffffff;
}
.dock-btn.is-end:hover:not(:disabled) {
background: #dc2626;
border-color: #dc2626;
color: #ffffff;
}
/* ---------- Retryable server error (second row inside the bar) ---------- */
.dock-error {
display: flex;
align-items: center;
gap: 0.5rem;
margin: 0 0.75rem 0.5rem;
padding: 0.375rem 0.625rem;
border: 1px solid rgba(239, 68, 68, 0.45); border: 1px solid rgba(239, 68, 68, 0.45);
border-radius: 0.875rem; border-radius: 0.75rem;
color: #dc2626; color: #dc2626;
font-size: 0.8125rem; font-size: 0.8125rem;
line-height: 1.6; line-height: 1.6;
} }
.stream-error span { .dock-error span {
flex: 1; flex: 1;
min-width: 0; min-width: 0;
} }
.stream-error-close { .dock-error-close {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
@@ -191,112 +236,20 @@
flex-shrink: 0; flex-shrink: 0;
} }
.stream-error-close:focus-visible { .dock-error-close:focus-visible {
outline: 2px solid var(--color-primary); outline: 2px solid var(--color-primary);
outline-offset: 1px; outline-offset: 1px;
} }
/* ---------- Controls ---------- */ @keyframes dockIn {
.stream-footer { from {
position: absolute;
bottom: 0;
left: 0;
right: 0;
z-index: 3;
display: flex;
align-items: center;
justify-content: center;
padding-bottom: 0.25rem;
transition: opacity 0.45s ease, transform 0.45s ease;
}
.stream-actions {
display: flex;
align-items: center;
justify-content: center;
gap: 0.625rem;
flex-wrap: wrap;
}
.stream-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
padding: 0.625rem 1.25rem;
border: 1px solid var(--surface-border);
border-radius: 9999px;
background: var(--surface-bg);
color: var(--text-secondary);
font-family: inherit;
font-size: 0.875rem;
cursor: pointer;
transition: background 0.2s ease, color 0.2s ease, border-color 0.2s ease, transform 0.15s ease;
user-select: none;
}
.stream-btn:hover:not(:disabled) {
background: var(--sidebar-hover);
color: var(--text-primary);
transform: scale(1.03);
}
.stream-btn:active:not(:disabled) {
transform: scale(0.97);
}
.stream-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.stream-btn:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
.stream-btn.is-active {
background: rgba(239, 68, 68, 0.1);
border-color: rgba(239, 68, 68, 0.5);
color: #dc2626;
}
.stream-btn.is-end {
background: #ef4444;
border-color: #ef4444;
color: #ffffff;
}
.stream-btn.is-end:hover:not(:disabled) {
background: #dc2626;
border-color: #dc2626;
color: #ffffff;
}
/* ---------- Ended: orb + controls fade out, transcript stays ---------- */
/* The orb + footer reserve only exists while the call is live; collapsing it stops the
bottom padding from forcing the panel (and the chat column) taller than the viewport. */
.stream-panel.is-ended {
--reserve: 0rem;
}
.stream-panel.is-ended .stream-orb-layer {
opacity: 0;
transform: translateX(-50%) translateY(14px) scale(0.9);
pointer-events: none;
}
.stream-panel.is-ended .stream-footer {
opacity: 0; opacity: 0;
transform: translateY(10px); transform: translateY(10px);
pointer-events: none;
} }
to {
/* The transcript keeps the full height of the chat column: no max-height, so it never opacity: 1;
collapses into a short nested scroll box — scrolling stays on the full-height area. */ transform: translateY(0);
.stream-panel.is-ended .stream-transcript { }
padding: 1rem 0.75rem;
} }
.sr-only { .sr-only {
@@ -312,31 +265,34 @@
} }
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
:host,
.status-dot, .status-dot,
.orb-fallback, .orb-fallback,
.stream-btn, .dock-btn {
.stream-orb-layer,
.stream-footer,
.stream-transcript {
animation: none !important; animation: none !important;
transition: none !important; transition: none !important;
scroll-behavior: auto !important;
} }
} }
@media (max-width: 640px) { @media (max-width: 640px) {
.stream-panel { .dock-row {
--footer-h: 3.25rem; gap: 0.5rem;
--orb-zone: 6rem; padding: 0.375rem 0.625rem;
--orb-gap: 0.5rem;
} }
.orb-container { .orb-container {
width: 68px; width: 84px;
height: 68px; height: 84px;
margin-block: -16px;
margin-inline: -12px;
} }
.stream-btn { .dock-btn-label {
padding: 0.5rem 1rem; display: none;
}
.dock-btn.is-end {
padding: 0;
width: 40px;
} }
} }
@@ -1,55 +1,27 @@
<div <div
class="stream-panel" class="call-dock"
role="region" role="region"
aria-label="گفتگوی صوتی" aria-label="گفتگوی صوتی"
[class.is-ended]="ended()"
[attr.data-state]="state()" [attr.data-state]="state()"
> >
<div class="sr-only" role="status" aria-live="polite">{{ statusText() }}</div> <div class="sr-only" role="status" aria-live="polite">{{ statusText() }}</div>
<!-- Orb layer: behind the transcript, anchored just above the controls --> <div class="dock-row">
<div class="stream-orb-layer" aria-hidden="true"> <div class="orb-container" #orbContainer aria-hidden="true">
<div class="orb-container" #orbContainer>
@if (!orbAvailable()) { @if (!orbAvailable()) {
<div class="orb-fallback"></div> <div class="orb-fallback"></div>
} }
</div> </div>
<div class="stream-status" [attr.data-state]="state()">
<span class="status-dot" aria-hidden="true"></span> <div class="dock-info" aria-hidden="true">
<p class="status-text">{{ statusText() }}</p> <span class="status-dot" [attr.data-state]="state()"></span>
</div> <p class="status-text" [attr.title]="statusText()">{{ statusText() }}</p>
</div> </div>
<!-- Transcript: overlaid on top of the orb, keeps streaming while the call runs --> <div class="dock-actions">
<div
class="stream-transcript"
#scroller
role="log"
aria-label="متن گفتگو"
aria-live="polite"
aria-relevant="additions"
>
<app-voice-transcript [messages]="messages()" />
</div>
@if (streamError(); as errorText) {
<div class="stream-error" role="alert">
<span>{{ errorText }}</span>
<button type="button" class="stream-error-close" aria-label="بستن پیام" (click)="dismissError()">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<line x1="18" x2="6" y1="6" y2="18" />
<line x1="6" x2="18" y1="6" y2="18" />
</svg>
</button>
</div>
}
<!-- Controls: fade out together with the orb when the call ends -->
<div class="stream-footer">
<div class="stream-actions">
<button <button
type="button" type="button"
class="stream-btn" class="dock-btn"
[class.is-active]="muted()" [class.is-active]="muted()"
[attr.aria-pressed]="muted()" [attr.aria-pressed]="muted()"
[attr.aria-label]="muteLabel()" [attr.aria-label]="muteLabel()"
@@ -73,16 +45,27 @@
<line x1="12" x2="12" y1="19" y2="22" /> <line x1="12" x2="12" y1="19" y2="22" />
</svg> </svg>
} }
<span>{{ muted() ? 'فعال‌سازی' : 'بی‌صدا' }}</span>
</button> </button>
<button type="button" class="stream-btn is-end" aria-label="پایان گفتگوی صوتی" (click)="endCall()"> <button type="button" class="dock-btn is-end" aria-label="پایان گفتگوی صوتی" (click)="endCall()">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<line x1="18" x2="6" y1="6" y2="18" /> <line x1="18" x2="6" y1="6" y2="18" />
<line x1="6" x2="18" y1="6" y2="18" /> <line x1="6" x2="18" y1="6" y2="18" />
</svg> </svg>
<span>پایان گفتگو</span> <span class="dock-btn-label">پایان</span>
</button> </button>
</div> </div>
</div> </div>
@if (streamError(); as errorText) {
<div class="dock-error" role="alert">
<span>{{ errorText }}</span>
<button type="button" class="dock-error-close" aria-label="بستن پیام" (click)="dismissError()">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<line x1="18" x2="6" y1="6" y2="18" />
<line x1="6" x2="18" y1="6" y2="18" />
</svg>
</button>
</div>
}
</div> </div>
@@ -13,7 +13,6 @@ import {
import { OrbMode, VoiceOrbService } from '../../../services/voice-orb/voice-orb.service'; import { OrbMode, VoiceOrbService } from '../../../services/voice-orb/voice-orb.service';
import { VoiceStreamService } from '../../../services/voice-stream/voice-stream.service'; import { VoiceStreamService } from '../../../services/voice-stream/voice-stream.service';
import { VoiceStreamState } from '../../../services/voice-stream/voice-stream.types'; import { VoiceStreamState } from '../../../services/voice-stream/voice-stream.types';
import { VoiceTranscriptComponent } from '../voice-transcript/voice-transcript.component';
const ORB_MODE: Record<VoiceStreamState, OrbMode> = { const ORB_MODE: Record<VoiceStreamState, OrbMode> = {
IDLE: 'listening', IDLE: 'listening',
@@ -23,12 +22,16 @@ const ORB_MODE: Record<VoiceStreamState, OrbMode> = {
SPEAKING: 'speaking', SPEAKING: 'speaking',
}; };
/** Live call view: orb behind an overlaid running transcript, mute / end controls. */ /**
* Compact call bar that sits right above the chat input while a voice call runs:
* orb + status on one side, mute / end on the other. The transcript is NOT part of it;
* the home page's transcript list renders the messages.
*/
@Component({ @Component({
selector: 'app-voice-stream-panel', selector: 'app-voice-stream-panel',
standalone: true, standalone: true,
imports: [VoiceTranscriptComponent],
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
host: { '[class.is-ended]': 'ended()' },
templateUrl: './voice-stream-panel.component.html', templateUrl: './voice-stream-panel.component.html',
styleUrl: './voice-stream-panel.component.css', styleUrl: './voice-stream-panel.component.css',
}) })
@@ -38,15 +41,13 @@ export class VoiceStreamPanelComponent implements AfterViewInit, OnDestroy {
readonly state = this.voice.state; readonly state = this.voice.state;
readonly connection = this.voice.connection; readonly connection = this.voice.connection;
readonly messages = this.voice.messages;
readonly muted = this.voice.muted; readonly muted = this.voice.muted;
readonly streamError = this.voice.streamError; readonly streamError = this.voice.streamError;
readonly orbAvailable = signal(true); readonly orbAvailable = signal(true);
/** The call is over: the orb and controls fade out, the transcript stays. */ /** The call is over: the bar fades and collapses (the host drops it shortly after). */
readonly ended = computed(() => this.connection() === 'disconnected'); readonly ended = computed(() => this.connection() === 'disconnected');
private readonly orbContainer = viewChild.required<ElementRef<HTMLDivElement>>('orbContainer'); private readonly orbContainer = viewChild.required<ElementRef<HTMLDivElement>>('orbContainer');
private readonly scroller = viewChild<ElementRef<HTMLDivElement>>('scroller');
private orbRunning = false; private orbRunning = false;
readonly statusText = computed(() => { readonly statusText = computed(() => {
@@ -73,16 +74,7 @@ export class VoiceStreamPanelComponent implements AfterViewInit, OnDestroy {
constructor() { constructor() {
effect(() => this.orb.setMode(ORB_MODE[this.state()])); effect(() => this.orb.setMode(ORB_MODE[this.state()]));
// Keep the newest message in view as text streams in. // The orb animates only while a call is live.
effect(() => {
this.messages();
requestAnimationFrame(() => {
const el = this.scroller()?.nativeElement;
if (el) el.scrollTop = el.scrollHeight;
});
});
// The orb animates only while a call is live; it fades out (and stops) when the call ends.
effect(() => { effect(() => {
if (this.ended()) { if (this.ended()) {
this.orb.stopAnimation(); this.orb.stopAnimation();
@@ -48,12 +48,43 @@
opacity: 0.8; opacity: 0.8;
} }
.bubble.is-limited {
/* informational answer state: a quiet accent, never an error treatment */
border-inline-start: 2px solid var(--color-primary);
padding-inline-start: 0.5rem;
}
.bubble-tag { .bubble-tag {
margin-inline-start: 0.375rem; margin-inline-start: 0.375rem;
font-size: 0.75rem; font-size: 0.75rem;
opacity: 0.7; opacity: 0.7;
} }
.bubble-tag.is-limited {
color: var(--color-primary);
font-weight: 600;
opacity: 1;
}
.bubble-footer {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 0.125rem;
margin-top: 0.25rem;
}
.bubble-help {
font-size: 0.75rem;
line-height: 1.6;
color: var(--muted);
}
.bubble-text.is-missing {
color: var(--muted);
font-style: italic;
}
@keyframes bubbleIn { @keyframes bubbleIn {
from { from {
opacity: 0; opacity: 0;
@@ -77,7 +108,7 @@
.source-chip { .source-chip {
display: flex; display: flex;
align-items: baseline; align-items: flex-start;
gap: 0.375rem; gap: 0.375rem;
padding: 0.25rem 0.5rem; padding: 0.25rem 0.5rem;
border: 1px solid var(--surface-border); border: 1px solid var(--surface-border);
@@ -85,7 +116,7 @@
background: var(--surface-bg); background: var(--surface-bg);
color: var(--text-secondary); color: var(--text-secondary);
font-size: 0.75rem; font-size: 0.75rem;
line-height: 1.5; line-height: 1.6;
} }
.source-chip.is-unavailable { .source-chip.is-unavailable {
@@ -103,8 +134,18 @@
font-weight: 600; font-weight: 600;
} }
/* The excerpt is the chip's content, shown complete with the provider's own line
breaks — it is the retrieved answer text the user asked to see as the source. */
.source-label {
flex: 1 1 auto;
min-width: 0;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.transcript-empty { .transcript-empty {
margin: auto; margin: auto;
margin-bottom:10px;
font-size: 0.875rem; font-size: 0.875rem;
color: var(--muted); color: var(--muted);
text-align: center; text-align: center;
@@ -5,13 +5,23 @@
[class.is-user]="message.role === 'user'" [class.is-user]="message.role === 'user'"
[class.is-partial]="!message.final" [class.is-partial]="!message.final"
[class.is-interrupted]="message.interrupted" [class.is-interrupted]="message.interrupted"
[class.is-limited]="message.limited && !message.interrupted"
dir="rtl" dir="rtl"
> >
@if (message.text) { @if (message.text) {
<span class="bubble-text">{{ message.text }}</span> <span class="bubble-text">{{ message.text }}</span>
} @else if (message.limited && !message.interrupted) {
<!-- A limited answer with no transcript text: never manufacture spoken text. -->
<span class="bubble-text is-missing">متن این پاسخ در دسترس نیست</span>
} }
@if (message.interrupted) { @if (message.interrupted) {
<span class="bubble-tag">(قطع شد)</span> <span class="bubble-tag">(قطع شد)</span>
} @else if (message.limited) {
<!-- Informational answer state: the answer is limited, not a failure and not complete. -->
<span class="bubble-footer">
<span class="bubble-tag is-limited">پاسخ محدود شده</span>
<span class="bubble-help">برای توضیح بیشتر بگویید «ادامه بده».</span>
</span>
} }
@if (message.sources?.length) { @if (message.sources?.length) {
<ul class="source-list" aria-label="منابع پاسخ"> <ul class="source-list" aria-label="منابع پاسخ">
@@ -19,7 +29,7 @@
<li <li
class="source-chip" class="source-chip"
[class.is-unavailable]="source.available === false" [class.is-unavailable]="source.available === false"
[attr.title]="source.excerpt ?? null" [attr.title]="sourceTooltip(source)"
> >
<span class="source-ref">{{ source.source_ref }}</span> <span class="source-ref">{{ source.source_ref }}</span>
<span class="source-label">{{ sourceLabel(source) }}</span> <span class="source-label">{{ sourceLabel(source) }}</span>
@@ -0,0 +1,234 @@
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { VoiceTranscriptComponent } from './voice-transcript.component';
import { VoiceMessage, VoiceSource } from '../../../services/voice-stream/voice-stream.types';
const LIMITED_LABEL = 'پاسخ محدود شده';
const LIMITED_HELP = 'برای توضیح بیشتر بگویید «ادامه بده».';
const UNAVAILABLE_TEXT = 'متن این پاسخ در دسترس نیست';
function message(overrides: Partial<VoiceMessage>): VoiceMessage {
return {
id: 'turn-1:assistant',
turnRef: 'turn-1',
role: 'assistant',
text: 'پاسخ',
final: true,
...overrides,
};
}
async function render(messages: VoiceMessage[]): Promise<HTMLElement> {
const fixture = TestBed.createComponent(VoiceTranscriptComponent);
fixture.componentRef.setInput('messages', messages);
fixture.detectChanges();
await fixture.whenStable();
return fixture.nativeElement as HTMLElement;
}
describe('VoiceTranscriptComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [VoiceTranscriptComponent],
providers: [provideZonelessChangeDetection()],
}).compileComponents();
});
it('shows the limited indication with the continuation help next to the transcript text', async () => {
const element = await render([message({ limited: true })]);
expect(element.textContent).toContain('پاسخ'); // the available transcript stays visible
expect(element.textContent).toContain(LIMITED_LABEL);
expect(element.textContent).toContain(LIMITED_HELP);
// The help text is a separate indication, never appended to the provider transcript.
const text = element.querySelector('.bubble-text')?.textContent ?? '';
expect(text).toBe('پاسخ');
expect(text).not.toContain(LIMITED_HELP);
});
it('shows the unavailable-text presentation when a limited answer has no transcript text', async () => {
const element = await render([message({ text: '', limited: true })]);
expect(element.textContent).toContain(UNAVAILABLE_TEXT);
expect(element.textContent).toContain(LIMITED_LABEL);
expect(element.textContent).toContain(LIMITED_HELP);
});
it('keeps the sources of a limited answer visible', async () => {
const element = await render([
message({
limited: true,
sources: [
{
source_ref: 'S1',
document_id: 'doc-1',
chunk_id: 'chunk-1',
title: 'سند آزمون',
excerpt: 'بانک سؤالات و پاسخ‌های سامانه هوش مصنوعی تلفنی',
location: { page: null, section: 'docx/paragraph/1 | docx/table/1/row/1/cell/1' },
},
],
}),
]);
expect(element.querySelectorAll('.source-chip')).toHaveLength(1);
expect(element.textContent).toContain(LIMITED_LABEL);
});
it('shows the excerpt instead of the document section path', async () => {
const source: VoiceSource = {
source_ref: 'S1',
document_id: 'doc-1',
chunk_id: 'chunk-1',
title: 'document.docx',
excerpt: 'ساعت کاری شرکت از شنبه تا چهارشنبه است',
location: { page: null, section: 'docx/paragraph/1 | docx/table/1/row/1/cell/1' },
};
const element = await render([message({ sources: [source] })]);
const label = element.querySelector('.source-label')?.textContent ?? '';
expect(label).toContain('ساعت کاری شرکت از شنبه تا چهارشنبه است');
expect(label).not.toContain('docx/table/1/row/1/cell/1');
expect(label).not.toContain('document.docx'); // the filename is not the chip label
});
it('keeps the full excerpt and the document details in the hover tooltip', async () => {
const source: VoiceSource = {
source_ref: 'S1',
document_id: 'doc-1',
chunk_id: 'chunk-1',
title: 'document.docx',
excerpt: 'سؤال: ساعت کاری؟\nپاسخ: ۸ تا ۱۳',
location: { page: 3, section: 'docx/paragraph/1' },
};
const element = await render([message({ sources: [source] })]);
const tooltip = element.querySelector('.source-chip')?.getAttribute('title') ?? '';
expect(tooltip).toContain('document.docx');
expect(tooltip).toContain('docx/paragraph/1');
expect(tooltip).toContain('صفحه 3');
expect(tooltip).toContain('سؤال: ساعت کاری؟\nپاسخ: ۸ تا ۱۳');
});
it('shows a single-paragraph excerpt completely with its line breaks', async () => {
const excerpt =
'بانک سؤالات و پاسخ‌های سامانه هوش مصنوعی تلفنی: ساعت کاری شرکت از شنبه تا چهارشنبه است';
const source: VoiceSource = {
source_ref: 'S1',
document_id: 'doc-1',
chunk_id: 'chunk-1',
title: 'document.docx',
excerpt,
};
const element = await render([message({ sources: [source] })]);
const label = element.querySelector<HTMLElement>('.source-label');
// a single paragraph is not summarized: the full text is rendered…
expect(label?.textContent).toBe(excerpt);
// …and wraps instead of being clipped to one line
const style = getComputedStyle(label!);
expect(style.whiteSpace).toBe('pre-wrap');
expect(style.textOverflow).not.toBe('ellipsis');
});
it('summarizes a multi-paragraph excerpt to its first paragraph with an ellipsis', async () => {
const source: VoiceSource = {
source_ref: 'S1',
document_id: 'doc-1',
chunk_id: 'chunk-1',
title: 'document.docx',
excerpt:
'بانک سؤالات و پاسخ‌های سامانه هوش مصنوعی تلفنی\nسؤال: ساعت کاری شرکت چنده؟\nپاسخ: ۸ تا ۱۳',
};
const element = await render([message({ sources: [source] })]);
const label = element.querySelector('.source-label')?.textContent ?? '';
expect(label).toBe('بانک سؤالات و پاسخ‌های سامانه هوش مصنوعی تلفنی …');
expect(label).not.toContain('سؤال: ساعت کاری');
expect(label).not.toContain('پاسخ: ۸ تا ۱۳');
// the complete excerpt stays available in the hover tooltip
expect(element.querySelector('.source-chip')?.getAttribute('title')).toContain('پاسخ: ۸ تا ۱۳');
});
it('treats blank-line-separated paragraphs as multiple paragraphs', async () => {
const source: VoiceSource = {
source_ref: 'S1',
document_id: 'doc-1',
chunk_id: 'chunk-1',
title: 'document.docx',
excerpt: 'پاراگراف اول\n\nپاراگراف دوم',
};
const element = await render([message({ sources: [source] })]);
const label = element.querySelector('.source-label')?.textContent ?? '';
expect(label).toBe('پاراگراف اول …');
expect(label).not.toContain('پاراگراف دوم');
});
it('trims the excerpt so trailing wire newlines do not add empty lines', async () => {
const source: VoiceSource = {
source_ref: 'S1',
document_id: 'doc-1',
chunk_id: 'chunk-1',
title: 'document.docx',
excerpt: 'پاسخ: ۸ تا ۱۳\n',
};
const element = await render([message({ sources: [source] })]);
expect(element.querySelector('.source-label')?.textContent).toBe('پاسخ: ۸ تا ۱۳');
});
it('falls back to the document title for sources the server marks unavailable', async () => {
const element = await render([
message({
sources: [
{
source_ref: 'S1',
document_id: 'doc-1',
chunk_id: 'chunk-1',
title: 'document.docx',
excerpt: 'متن منقضی‌شده',
available: false,
},
],
}),
]);
const chip = element.querySelector('.source-chip');
expect(chip?.classList.contains('is-unavailable')).toBe(true);
expect(chip?.querySelector('.source-label')?.textContent).toBe('document.docx');
expect(chip?.querySelector('.source-label')?.textContent).not.toContain('متن منقضی‌شده');
// The revoked excerpt stays hidden in the tooltip too.
expect(chip?.getAttribute('title')).not.toContain('متن منقضی‌شده');
expect(chip?.getAttribute('title')).toContain('document.docx');
});
it('presents an interrupted answer as interrupted, not as limited', async () => {
const element = await render([
message({ limited: true, interrupted: true, text: 'پاسخ قطع‌شده' }),
]);
expect(element.textContent).toContain('(قطع شد)');
expect(element.textContent).not.toContain(LIMITED_LABEL);
expect(element.textContent).not.toContain(LIMITED_HELP);
});
it('never applies the limited indication to user rows or ordinary answers', async () => {
const element = await render([
message({ id: 'turn-1:user', turnRef: 'turn-1', role: 'user', text: 'ادامه بده' }),
message({ id: 'turn-2:assistant', turnRef: 'turn-2', text: 'پاسخ عادی' }),
]);
expect(element.textContent).not.toContain(LIMITED_LABEL);
expect(element.textContent).toContain('ادامه بده');
expect(element.textContent).toContain('پاسخ عادی');
});
it('renders the limited indication in an RTL bubble', async () => {
const element = await render([message({ limited: true })]);
const bubble = element.querySelector('.bubble');
expect(bubble?.getAttribute('dir')).toBe('rtl');
expect(bubble?.classList.contains('is-limited')).toBe(true);
});
});
@@ -12,11 +12,42 @@ import { VoiceMessage, VoiceSource } from '../../../services/voice-stream/voice-
export class VoiceTranscriptComponent { export class VoiceTranscriptComponent {
readonly messages = input.required<VoiceMessage[]>(); readonly messages = input.required<VoiceMessage[]>();
/** "عنوان — صفحه ۱، بند ۲" */ /**
* Compact chip label: the excerpt's first paragraph, followed by an ellipsis when the
* chunk holds more paragraphs. The document's internal `location.section` path (e.g.
* "docx/table/1/row/1/cell/1") is document structure, not content, so it is not shown
* in the chip (it stays in the hover tooltip, along with the complete excerpt). Sources
* the server marks unavailable keep their excerpt hidden and fall back to the title.
*/
sourceLabel(source: VoiceSource): string { sourceLabel(source: VoiceSource): string {
if (source.available !== false) {
const excerpt = source.excerpt?.trim();
if (excerpt) {
// Paragraph breaks (single or repeated newlines) separate the excerpt into
// paragraphs; only the first one is summarized into the chip.
const paragraphs = excerpt
.split(/\r?\n+/)
.map((paragraph) => paragraph.trim())
.filter(Boolean);
const first = paragraphs[0];
if (first) return paragraphs.length > 1 ? `${first} …` : first;
}
}
return source.title || source.document_id;
}
/** Hover tooltip: document, location and the complete, untruncated excerpt. */
sourceTooltip(source: VoiceSource): string {
const parts: string[] = []; const parts: string[] = [];
if (source.title) parts.push(source.title);
if (source.location?.page != null) parts.push(`صفحه ${source.location.page}`); if (source.location?.page != null) parts.push(`صفحه ${source.location.page}`);
if (source.location?.section) parts.push(source.location.section); if (source.location?.section) parts.push(source.location.section);
return parts.length ? `${source.title} — ${parts.join('، ')}` : source.title; // Same hidden-excerpt rule as the chip label: a source the server marks unavailable
// has revoked text, so it is not surfaced here either.
if (source.available !== false) {
const excerpt = source.excerpt?.trim();
if (excerpt) parts.push(excerpt);
}
return parts.join('\n');
} }
} }
+11
View File
@@ -1,3 +1,5 @@
import moment from 'moment-jalaali';
const PERSIAN_DIGITS = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹']; const PERSIAN_DIGITS = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
export function toPersianDigits(value: string | number): string { export function toPersianDigits(value: string | number): string {
@@ -18,3 +20,12 @@ export function formatDecimal(value: number, fractionDigits = 1): string {
export function formatPercent(value: number): string { export function formatPercent(value: number): string {
return `${toPersianDigits(Math.round(value))}٪`; return `${toPersianDigits(Math.round(value))}٪`;
} }
/** 2026-10-10 -> «۱۴۰۵/۰۷/۱۸ ۱۰:۲۵» */
export function formatJalaliDateTime(value: string | Date): string {
const date = typeof value === 'string' ? new Date(value) : value;
if (Number.isNaN(date.getTime())) {
return '—';
}
return toPersianDigits(moment(date).format('jYYYY/jMM/jDD HH:mm'));
}
+45
View File
@@ -0,0 +1,45 @@
/**
* UUID generation that works outside secure contexts.
*
* `crypto.randomUUID()` only exists in secure contexts (HTTPS or `localhost`). It is
* unavailable on plain-HTTP origins — common for internal/LAN deployments — and calling
* it there throws `TypeError: crypto.randomUUID is not a function`, which took down
* login entirely. Every id the frontend mints per request (`X-Request-ID`,
* `Idempotency-Key`, `client_request_id`) therefore goes through here.
*/
/**
* RFC 4122 v4 UUID.
*
* Prefers `crypto.randomUUID()`, then `crypto.getRandomValues()` (available in every
* context, and what `randomUUID` itself is built on), and only then `Math.random()` —
* ids stay unique per request in all cases.
*/
export function uuid(): string {
const c: Crypto | undefined = typeof crypto !== 'undefined' ? crypto : undefined;
if (typeof c?.randomUUID === 'function') return c.randomUUID();
if (typeof c?.getRandomValues === 'function') {
const bytes = new Uint8Array(16);
c.getRandomValues(bytes);
// Version 4 (random) + RFC 4122 variant bits.
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex: string[] = [];
for (let i = 0; i < 16; i++) {
hex.push(bytes[i].toString(16).padStart(2, '0'));
}
return (
`${hex.slice(0, 4).join('')}-${hex.slice(4, 6).join('')}-` +
`${hex.slice(6, 8).join('')}-${hex.slice(8, 10).join('')}-${hex.slice(10, 16).join('')}`
);
}
// Last resort: no Web Crypto at all. Not cryptographically strong, but still unique.
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (ch) => {
const r = (Math.random() * 16) | 0;
return (ch === 'x' ? r : (r & 0x3) | 0x8).toString(16);
});
}
+1 -1
View File
@@ -2,7 +2,7 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<title>FaqChatbot</title> <title>دستیار هوش مصنوعی</title>
<base href="/"> <base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico"> <link rel="icon" type="image/x-icon" href="favicon.ico">
+8
View File
@@ -21,6 +21,7 @@
} }
:root { :root {
color-scheme: light;
--app-bg: #f8fafc; --app-bg: #f8fafc;
--app-text: #122033; --app-text: #122033;
--sidebar-bg: #f8fafc; --sidebar-bg: #f8fafc;
@@ -52,6 +53,7 @@
} }
[data-bs-theme="dark"] { [data-bs-theme="dark"] {
color-scheme: dark;
--app-bg: #212121; --app-bg: #212121;
--app-text: #ececec; --app-text: #ececec;
--sidebar-bg: #171717; --sidebar-bg: #171717;
@@ -128,6 +130,12 @@
background-color: var(--scrollbar-track); background-color: var(--scrollbar-track);
} }
select option,
select optgroup {
background-color: var(--color-input-bg);
color: var(--color-text-secondary);
}
body { body {
direction: rtl; direction: rtl;
font-family: "Lahze", sans-serif; font-family: "Lahze", sans-serif;