diff --git a/.kilo/skills/ponytail/SKILL.md b/.kilo/skills/ponytail/SKILL.md
new file mode 100644
index 0000000..069d745
--- /dev/null
+++ b/.kilo/skills/ponytail/SKILL.md
@@ -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?** ` ` 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.
diff --git a/package-lock.json b/package-lock.json
index bc4c4d9..ea0d976 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -21,6 +21,7 @@
"@popperjs/core": "^2.11.8",
"ag-grid-angular": "^36.2.0",
"ag-grid-community": "^36.2.0",
+ "moment-jalaali": "^0.10.5",
"ngx-toastr": "^14.3.0",
"papaparse": "^5.7.0",
"rxjs": "~7.8.0",
@@ -34,6 +35,8 @@
"@playwright/test": "^1.63.0",
"@tailwindcss/postcss": "^4.3.3",
"@types/audioworklet": "^0.0.100",
+ "@types/moment": "^2.11.29",
+ "@types/moment-jalaali": "^0.7.9",
"@types/papaparse": "^5.5.2",
"@types/three": "^0.186.0",
"jsdom": "^30.1.2",
@@ -541,7 +544,6 @@
"version": "20.3.33",
"resolved": "https://registry.npmjs.org/@angular/compiler-cli/-/compiler-cli-20.3.33.tgz",
"integrity": "sha512-NKE4N4ssXysHLJQ7xVqvAv/yf3JfJxaFz5H+Ue+EnYToAmTxXe7uyt2MPRIydef/H63n7O9uphVp5P5GkRxVuA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"@babel/core": "7.29.7",
@@ -613,6 +615,31 @@
"rxjs": "^6.5.3 || ^7.4.0"
}
},
+ "node_modules/@angular/localize": {
+ "version": "20.3.33",
+ "resolved": "https://registry.npmjs.org/@angular/localize/-/localize-20.3.33.tgz",
+ "integrity": "sha512-2Rr23xegscTKOwSNJE4O/vqpK+owLPH6Z7MojctI/cIcu5RSE7RVw/r9Hs5XS4fhr81yHRWp/jRFQzzm3i6F4g==",
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "@babel/core": "7.29.7",
+ "@types/babel__core": "7.20.5",
+ "tinyglobby": "^0.2.12",
+ "yargs": "^18.0.0"
+ },
+ "bin": {
+ "localize-extract": "tools/bundles/src/extract/cli.js",
+ "localize-migrate": "tools/bundles/src/migrate/cli.js",
+ "localize-translate": "tools/bundles/src/translate/cli.js"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ },
+ "peerDependencies": {
+ "@angular/compiler": "20.3.33",
+ "@angular/compiler-cli": "20.3.33"
+ }
+ },
"node_modules/@angular/platform-browser": {
"version": "20.3.33",
"resolved": "https://registry.npmjs.org/@angular/platform-browser/-/platform-browser-20.3.33.tgz",
@@ -710,7 +737,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
"integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==",
- "dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-validator-identifier": "^7.29.7",
@@ -725,7 +751,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz",
"integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
@@ -735,7 +760,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz",
"integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"@babel/code-frame": "^7.29.7",
@@ -766,14 +790,12 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
"integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
- "dev": true,
"license": "MIT"
},
"node_modules/@babel/core/node_modules/semver": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
"integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
- "dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
@@ -783,7 +805,6 @@
"version": "7.29.8",
"resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz",
"integrity": "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==",
- "dev": true,
"license": "MIT",
"dependencies": {
"@babel/parser": "^7.29.8",
@@ -813,7 +834,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz",
"integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==",
- "dev": true,
"license": "MIT",
"dependencies": {
"@babel/compat-data": "^7.29.7",
@@ -830,7 +850,6 @@
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
"integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
- "dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
@@ -840,7 +859,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz",
"integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
@@ -850,7 +868,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz",
"integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==",
- "dev": true,
"license": "MIT",
"dependencies": {
"@babel/traverse": "^7.29.7",
@@ -864,7 +881,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz",
"integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==",
- "dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-module-imports": "^7.29.7",
@@ -895,7 +911,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
"integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
@@ -905,7 +920,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
"integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
@@ -915,7 +929,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz",
"integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
@@ -925,7 +938,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz",
"integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==",
- "dev": true,
"license": "MIT",
"dependencies": {
"@babel/template": "^7.29.7",
@@ -939,7 +951,6 @@
"version": "7.29.9",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz",
"integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"@babel/types": "^7.29.8"
@@ -955,7 +966,6 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz",
"integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==",
- "dev": true,
"license": "MIT",
"dependencies": {
"@babel/code-frame": "^7.29.7",
@@ -970,7 +980,6 @@
"version": "7.29.8",
"resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.8.tgz",
"integrity": "sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==",
- "dev": true,
"license": "MIT",
"dependencies": {
"@babel/code-frame": "^7.29.7",
@@ -989,7 +998,6 @@
"version": "7.29.8",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz",
"integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==",
- "dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-string-parser": "^7.29.7",
@@ -2019,7 +2027,6 @@
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
"integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.0",
@@ -2030,7 +2037,6 @@
"version": "2.3.5",
"resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",
"integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
- "dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/gen-mapping": "^0.3.5",
@@ -2041,7 +2047,6 @@
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
"integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=6.0.0"
@@ -2051,14 +2056,12 @@
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
"integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
- "dev": true,
"license": "MIT"
},
"node_modules/@jridgewell/trace-mapping": {
"version": "0.3.31",
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
"integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
- "dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/resolve-uri": "^3.1.0",
@@ -4100,6 +4103,51 @@
"dev": true,
"license": "Apache-2.0"
},
+ "node_modules/@types/babel__core": {
+ "version": "7.20.5",
+ "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
+ "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==",
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "@babel/parser": "^7.20.7",
+ "@babel/types": "^7.20.7",
+ "@types/babel__generator": "*",
+ "@types/babel__template": "*",
+ "@types/babel__traverse": "*"
+ }
+ },
+ "node_modules/@types/babel__generator": {
+ "version": "7.27.0",
+ "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz",
+ "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==",
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "@babel/types": "^7.0.0"
+ }
+ },
+ "node_modules/@types/babel__template": {
+ "version": "7.4.4",
+ "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz",
+ "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==",
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "@babel/parser": "^7.1.0",
+ "@babel/types": "^7.0.0"
+ }
+ },
+ "node_modules/@types/babel__traverse": {
+ "version": "7.28.0",
+ "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz",
+ "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==",
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "@babel/types": "^7.28.2"
+ }
+ },
"node_modules/@types/chai": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
@@ -4125,6 +4173,23 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/moment": {
+ "version": "2.11.29",
+ "resolved": "https://registry.npmjs.org/@types/moment/-/moment-2.11.29.tgz",
+ "integrity": "sha512-D5WIgbLYQzvgfsDnBhZFSTnt/BjGPOE+Jsh3k1BYYijJAkrn7ceeLvU4jtjKKXXuXN42O3ARlU4D/P9ezbQYFA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/moment-jalaali": {
+ "version": "0.7.9",
+ "resolved": "https://registry.npmjs.org/@types/moment-jalaali/-/moment-jalaali-0.7.9.tgz",
+ "integrity": "sha512-gsDOoAzRnCfQTbfdlUrCvX6R0wIto6CvwfvV2C3j4qJLK+DEiTK8Rl/xlOCBO9C6qeUfX8oyZ2UfjnXJTOvHSA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "moment": ">=2.14.0"
+ }
+ },
"node_modules/@types/node": {
"version": "26.6.4",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.4.tgz",
@@ -4460,7 +4525,6 @@
"version": "6.4.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz",
"integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
@@ -4473,7 +4537,6 @@
"version": "6.2.3",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
"integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
@@ -4496,7 +4559,6 @@
"version": "2.11.27",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.27.tgz",
"integrity": "sha512-ElY12DaROGuan+lMmZ8Cvo/ZUbXPe7Enc/9VU/b1T3Kp4dwytRcNdR8DoSJN5SNJT/CuvcCA0DHDVmMOCePdRQ==",
- "dev": true,
"license": "Apache-2.0",
"bin": {
"baseline-browser-mapping": "dist/cli.cjs"
@@ -4585,7 +4647,6 @@
"version": "4.29.3",
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.3.tgz",
"integrity": "sha512-1R4kiYKXGViqEN0CnoDrXc1StD9niAwu+j2dukWzrD4bJgsD4lDmEp0CRbc6E/vYJIfTHwPmwyaKtVSudICdPA==",
- "dev": true,
"funding": [
{
"type": "opencollective",
@@ -4766,7 +4827,6 @@
"version": "1.0.30001814",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001814.tgz",
"integrity": "sha512-/Uaf1lAzr59XcMpW0o96WoEfr+VXK2OX4U9AgFoiSHsVJ4HppnIFUjtYzsyDH2+tgANaQb2/oxYGwCPapN1FpA==",
- "dev": true,
"funding": [
{
"type": "opencollective",
@@ -4834,7 +4894,6 @@
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz",
"integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"readdirp": "^4.0.1"
@@ -4916,7 +4975,6 @@
"version": "9.0.1",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz",
"integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==",
- "dev": true,
"license": "ISC",
"dependencies": {
"string-width": "^7.2.0",
@@ -4931,7 +4989,6 @@
"version": "9.0.2",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",
"integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",
- "dev": true,
"license": "MIT",
"dependencies": {
"ansi-styles": "^6.2.1",
@@ -5000,7 +5057,6 @@
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz",
"integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==",
- "dev": true,
"license": "MIT"
},
"node_modules/cookie": {
@@ -5118,7 +5174,6 @@
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
@@ -5254,14 +5309,12 @@
"version": "1.5.444",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.444.tgz",
"integrity": "sha512-5ss/uJfoDYDHT0lfJzT6FbcskIzROIOPf0BbbFkGcvDzoJU7i//9GDrwwIHQVmIsrAGiF3ihpADBRIsrEFt1rQ==",
- "dev": true,
"license": "ISC"
},
"node_modules/emoji-regex": {
"version": "10.6.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",
"integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",
- "dev": true,
"license": "MIT"
},
"node_modules/encodeurl": {
@@ -5410,7 +5463,6 @@
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
"integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -5575,7 +5627,6 @@
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=12.0.0"
@@ -5680,7 +5731,6 @@
"version": "1.0.0-beta.2",
"resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
"integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
@@ -5690,7 +5740,6 @@
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
- "dev": true,
"license": "ISC",
"engines": {
"node": "6.* || 8.* || >= 10.*"
@@ -5700,7 +5749,6 @@
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz",
"integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
@@ -6177,6 +6225,12 @@
"node": ">=10"
}
},
+ "node_modules/jalaali-js": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/jalaali-js/-/jalaali-js-1.2.8.tgz",
+ "integrity": "sha512-Jl/EwY84JwjW2wsWqeU4pNd22VNQ7EkjI36bDuLw31wH98WQW4fPjD0+mG7cdCK+Y8D6s9R3zLiQ3LaKu6bD8A==",
+ "license": "MIT"
+ },
"node_modules/jiti": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",
@@ -6201,7 +6255,6 @@
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
- "dev": true,
"license": "MIT"
},
"node_modules/jsdom": {
@@ -6268,7 +6321,6 @@
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",
"integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==",
- "dev": true,
"license": "MIT",
"bin": {
"jsesc": "bin/jsesc"
@@ -6305,7 +6357,6 @@
"version": "2.2.3",
"resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
"integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
- "dev": true,
"license": "MIT",
"bin": {
"json5": "lib/cli.js"
@@ -6775,7 +6826,6 @@
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
"integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
- "dev": true,
"license": "ISC",
"dependencies": {
"yallist": "^3.0.2"
@@ -7049,6 +7099,38 @@
"node": ">= 18"
}
},
+ "node_modules/moment": {
+ "version": "2.31.0",
+ "resolved": "https://registry.npmjs.org/moment/-/moment-2.31.0.tgz",
+ "integrity": "sha512-0acOTfMiWOheYS4eoWb80yYMb/JLvVv9SHbs2PehaDzfUG0Bw855SKyk0IKTnPGa5+U2bmi3W68l1+sGLX/pvw==",
+ "license": "MIT",
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/moment-jalaali": {
+ "version": "0.10.5",
+ "resolved": "https://registry.npmjs.org/moment-jalaali/-/moment-jalaali-0.10.5.tgz",
+ "integrity": "sha512-Xp0FsC0+jWG89/xcOrL880f97Tq7197P3saoMAqSIaF8vKr4Atr9XKtIOREGHTLUjOzJksfTHhQgxMgUJQupuw==",
+ "license": "MIT",
+ "dependencies": {
+ "jalaali-js": "^1.2.8",
+ "moment": "^2.30.1",
+ "moment-timezone": "^0.6.2"
+ }
+ },
+ "node_modules/moment-timezone": {
+ "version": "0.6.5",
+ "resolved": "https://registry.npmjs.org/moment-timezone/-/moment-timezone-0.6.5.tgz",
+ "integrity": "sha512-KKzZAxGv2Qx4cnk6eSlvf4C+DLFW52vmMY5MN7UARY7GONbozkutylQG3DrrtmLCTXdQ5XZrqao9cI16bLFzXA==",
+ "license": "MIT",
+ "dependencies": {
+ "moment": "^2.29.4"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
"node_modules/mrmime": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz",
@@ -7063,7 +7145,6 @@
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
- "dev": true,
"license": "MIT"
},
"node_modules/msgpackr": {
@@ -7263,7 +7344,6 @@
"version": "2.0.57",
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.57.tgz",
"integrity": "sha512-kQK9LGGFiHtrWiNhZtA7Qbw17AQz+dmsEKODRIVTXA9+e5MS/2gZEBhYJt13GrAz5/IOZKddH/0Z3TP/Zgo+yw==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
@@ -7726,14 +7806,12 @@
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
- "dev": true,
"license": "ISC"
},
"node_modules/picomatch": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
@@ -8004,7 +8082,6 @@
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",
"integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==",
- "dev": true,
"license": "MIT",
"engines": {
"node": ">= 14.18.0"
@@ -8018,7 +8095,6 @@
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
"integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",
- "dev": true,
"license": "Apache-2.0"
},
"node_modules/require-from-string": {
@@ -8192,7 +8268,6 @@
"version": "7.7.2",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz",
"integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==",
- "dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
@@ -8570,7 +8645,6 @@
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",
"integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",
- "dev": true,
"license": "MIT",
"dependencies": {
"emoji-regex": "^10.3.0",
@@ -8588,7 +8662,6 @@
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",
"integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",
- "dev": true,
"license": "MIT",
"dependencies": {
"ansi-regex": "^6.2.2"
@@ -8705,7 +8778,6 @@
"version": "0.2.14",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz",
"integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==",
- "dev": true,
"license": "MIT",
"dependencies": {
"fdir": "^6.4.4",
@@ -8872,7 +8944,7 @@
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
- "dev": true,
+ "devOptional": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
@@ -8913,7 +8985,6 @@
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.3.tgz",
"integrity": "sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==",
- "dev": true,
"funding": [
{
"type": "opencollective",
@@ -9365,7 +9436,6 @@
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
"integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
- "dev": true,
"license": "ISC",
"engines": {
"node": ">=10"
@@ -9375,14 +9445,12 @@
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
"integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",
- "dev": true,
"license": "ISC"
},
"node_modules/yargs": {
"version": "18.0.0",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-18.0.0.tgz",
"integrity": "sha512-4UEqdc2RYGHZc7Doyqkrqiln3p9X2DZVxaGbwhn2pi7MrRagKaOcIKe8L3OxYcbhXLgLFUS3zAYuQjKBQgmuNg==",
- "dev": true,
"license": "MIT",
"dependencies": {
"cliui": "^9.0.1",
@@ -9400,7 +9468,6 @@
"version": "22.0.0",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz",
"integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==",
- "dev": true,
"license": "ISC",
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=23"
diff --git a/package.json b/package.json
index d33b21f..a68b280 100644
--- a/package.json
+++ b/package.json
@@ -35,6 +35,7 @@
"@popperjs/core": "^2.11.8",
"ag-grid-angular": "^36.2.0",
"ag-grid-community": "^36.2.0",
+ "moment-jalaali": "^0.10.5",
"ngx-toastr": "^14.3.0",
"papaparse": "^5.7.0",
"rxjs": "~7.8.0",
@@ -48,6 +49,8 @@
"@playwright/test": "^1.63.0",
"@tailwindcss/postcss": "^4.3.3",
"@types/audioworklet": "^0.0.100",
+ "@types/moment": "^2.11.29",
+ "@types/moment-jalaali": "^0.7.9",
"@types/papaparse": "^5.5.2",
"@types/three": "^0.186.0",
"jsdom": "^30.1.2",
diff --git a/proxy.conf.json b/proxy.conf.json
index 3c6fb54..607df9e 100644
--- a/proxy.conf.json
+++ b/proxy.conf.json
@@ -1,7 +1,14 @@
{
"/api": {
- "target": "http://127.0.0.1:8080",
+ "target": "http://10.2.8.3:8080",
+ "secure": false,
+ "changeOrigin": true,
"ws": true,
- "changeOrigin": false
+ "logLevel": "debug"
+ },
+ "/users": {
+ "target": "http://10.2.8.3:8080",
+ "secure": false,
+ "changeOrigin": true
}
}
diff --git a/public/assets/worklets/pcm-playback.worklet.js b/public/assets/worklets/pcm-playback.worklet.js
index 596676a..8e09667 100644
--- a/public/assets/worklets/pcm-playback.worklet.js
+++ b/public/assets/worklets/pcm-playback.worklet.js
@@ -1,40 +1,57 @@
/**
* 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.
- * When it fills, the processor reports `overflow` and the call must fail safely — PCM is
- * never silently dropped to keep the same context alive.
+ * Bounded playout queue. The cap is on OUTSTANDING SOURCE PCM — BOUND_BYTES (96,000 bytes
+ * = 48,000 source samples ≈ 2 s at 24 kHz mono PCM16) — and each stage uses ONE unit
+ * consistently:
+ * admission + progress are booked in SOURCE samples (the contract/wire unit);
+ * the ring stores the RESAMPLED OUTPUT samples the AudioContext actually consumes.
+ * 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
- * consumed by `process()` per audio_ref (never an elapsed timer), kept cumulative per ref
- * and reported roughly 4×/s, on ref changes, and on clear/flush/idle — so the main thread
- * can send the contract's `playback_progress` control message.
+ * Real playback progress: played_ms for a server audio_ref is the cumulative SOURCE
+ * samples of THAT ref actually consumed by process(), never a timer. Queued audio keeps
+ * its own audio_ref when a different ref arrives (a FIFO of per-ref source spans), so
+ * progress is never credited to the wrong turn. Reported ~4×/s, on ref completion, and on
+ * clear/flush/idle, so the main thread can send the contract's playback_progress message.
*
* Messages in: { type: 'push', pcm: ArrayBuffer (Int16 mono), sampleRate, audioRef }
* { type: 'clear' } barge-in: drop everything immediately
* { type: 'flush' } end of turn: play what is left, then report 'idle'
* Messages out: { type: 'progress', audioRef, playedMs }
- * { type: 'idle' } buffer ran dry after playing
+ * { type: 'idle' } buffer ran dry after playing
* { 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;
class PcmPlaybackProcessor extends AudioWorkletProcessor {
constructor() {
super();
- this.capacity = Math.floor(BOUND_BYTES / 2); // source samples (PCM16)
+ this.sourceCapacity = Math.floor(BOUND_BYTES / 2); // 48,000 SOURCE samples (the admission bound)
+ this.ratio = 1; // SOURCE samples per OUTPUT sample (resolved on first push)
+ this.sized = false; // true once the output ring matches the real context rate
+ this.capacity = this.sourceCapacity; // OUTPUT slots currently allocated (grows for upsampling)
this.buf = new Float32Array(this.capacity);
this.r = 0;
this.w = 0;
- this.count = 0;
+ this.count = 0; // OUTPUT samples currently queued
+ this.queuedSource = 0; // SOURCE samples currently queued (the admission bound unit)
this.prebuffer = Math.floor(sampleRate * 0.08); // jitter buffer before (re)starting
this.started = false;
this.prev = 0;
this.pos = 1;
- this.ratio = 1; // source samples per output sample, set per push
- this.currentRef = null;
- this.refPlayedSamples = new Map(); // cumulative consumed source samples per audio_ref
+ // Per-audio_ref attribution. `refQueue` keeps the still-queued SOURCE span of each ref
+ // (merged per ref so it stays ≤ the number of turns); `refPlayedSamples` keeps each
+ // ref's cumulative consumed source. Together they tie queued audio to its own ref and
+ // keep progress cumulative and correct across ref changes.
+ this.refQueue = []; // [{ ref, src }] src = remaining SOURCE samples of that ref
+ this.refPlayedSamples = new Map();
+ this.playingRef = null; // ref currently being consumed / reported
this.unreportedSamples = 0;
this.overflowPosted = false;
this.port.onmessage = (e) => {
@@ -46,18 +63,36 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
};
}
+ /** Resolve the source→output ratio and size the output ring to hold the source bound. */
+ configure(ratio) {
+ if (this.sized && ratio === this.ratio) return;
+ this.ratio = ratio > 0 ? ratio : 1;
+ const need = Math.ceil(this.sourceCapacity / this.ratio) + RESAMPLE_MARGIN;
+ // Only grow while the ring is empty (first push): never drop queued audio.
+ if (need > this.capacity && this.count === 0) {
+ this.capacity = need;
+ this.buf = new Float32Array(this.capacity);
+ this.r = 0;
+ this.w = 0;
+ }
+ this.sized = true;
+ }
+
clear() {
+ this.reportFinal(); // final cumulative report for the interrupted ref
this.r = this.w = this.count = 0;
+ this.queuedSource = 0;
+ this.refQueue.length = 0;
this.started = false;
this.prev = 0;
this.pos = 1;
- this.reportProgress(true); // final report for the interrupted ref
+ this.playingRef = null;
}
flush() {
if (this.count === 0) {
this.started = false;
- this.reportProgress(true);
+ this.reportFinal();
this.port.postMessage({ type: 'idle' });
} else {
this.started = true; // short tail: do not wait for the prebuffer
@@ -68,16 +103,26 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
const n = int16.length;
if (!n) return;
- // Bounded queue: admitting this chunk past the cap is a safe failure, not a silent drop.
- if (this.count + n > this.capacity) {
- if (!this.overflowPosted) {
- this.overflowPosted = true;
- this.port.postMessage({ type: 'overflow' });
- }
- return;
- }
+ const ratio = srcRate / sampleRate; // SOURCE samples per OUTPUT sample
+ this.configure(ratio);
+
+ // OUTPUT samples this chunk will add — the exact count the resample loop performs.
+ const produced = 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;
+
+ // Keep the audio_ref of the queued source span so consumption is credited correctly
+ // even when the next ref arrives while this one is still playing.
+ const last = this.refQueue[this.refQueue.length - 1];
+ if (last && last.ref === audioRef) last.src += n;
+ else this.refQueue.push({ ref: audioRef, src: n });
- this.ratio = srcRate / sampleRate; // source samples per output sample
const src = new Float32Array(n + 1);
src[0] = this.prev;
for (let i = 0; i < n; i++) src[i + 1] = int16[i] / 32768;
@@ -91,15 +136,19 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
}
this.prev = src[n];
this.pos = pos - n;
+ }
- if (audioRef !== this.currentRef) {
- this.reportProgress(true); // final report for the ref that just ended
- this.currentRef = audioRef;
- this.reportProgress(true);
+ overflow() {
+ if (!this.overflowPosted) {
+ this.overflowPosted = true;
+ this.port.postMessage({ type: 'overflow' });
}
}
write(v) {
+ // Defense in depth: admission already reserves the room, so this never discards in
+ // normal flow — but it guarantees the ring is never overwritten nor exceeds capacity.
+ if (this.count >= this.capacity) return;
this.buf[this.w] = v;
this.w = (this.w + 1) % this.capacity;
this.count++;
@@ -123,20 +172,15 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
ch0[i] = 0;
}
}
- if (this.currentRef && played > 0) {
- // Convert consumed output samples back to contract (source) samples.
- const consumed = played * this.ratio;
- const ref = this.currentRef;
- 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 (played > 0) {
+ const consumedSource = played * this.ratio; // OUTPUT played → SOURCE consumed
+ this.queuedSource = Math.max(0, this.queuedSource - consumedSource);
+ this.consumeSpans(consumedSource);
+ this.reportCadence();
}
if (this.count === 0) {
this.started = false;
- this.reportProgress(true);
+ this.reportFinal();
this.port.postMessage({ type: 'idle' });
}
} else {
@@ -147,14 +191,49 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
return true;
}
- reportProgress(force) {
+ /** Draw `amount` SOURCE samples off the front of the ref FIFO, crediting each ref. */
+ consumeSpans(amount) {
+ while (amount > 1e-6 && this.refQueue.length) {
+ const span = this.refQueue[0];
+ const take = amount < span.src ? amount : span.src;
+ span.src -= take;
+ amount -= take;
+ this.creditRef(span.ref, take);
+ if (span.src <= 1e-6) {
+ this.refQueue.shift();
+ this.postProgress(span.ref); // ref finished: post its final cumulative before the next ref
+ }
+ }
+ }
+
+ creditRef(ref, sourceSamples) {
+ this.refPlayedSamples.set(ref, (this.refPlayedSamples.get(ref) ?? 0) + sourceSamples);
+ this.playingRef = ref;
+ this.unreportedSamples += sourceSamples;
+ }
+
+ /** Final cumulative report for the ref currently playing (interruption / drain / clear). */
+ reportFinal() {
this.unreportedSamples = 0;
- const ref = this.currentRef;
- if (!ref) return;
+ if (!this.playingRef) return;
+ this.postProgress(this.playingRef);
+ }
+
+ /** Cadence report for the ref currently playing (~REPORT_INTERVAL_MS of consumed source). */
+ reportCadence() {
+ if (!this.playingRef) return;
const srcRate = this.ratio * sampleRate;
+ if ((this.unreportedSamples / srcRate) * 1000 >= REPORT_INTERVAL_MS) {
+ this.reportFinal();
+ }
+ }
+
+ postProgress(ref) {
const playedSamples = this.refPlayedSamples.get(ref) ?? 0;
- const playedMs = Math.max(0, Math.round((playedSamples / srcRate) * 1000));
- if (playedMs <= 0) return; // nothing has actually been heard for this ref yet
+ const srcRate = this.ratio * sampleRate;
+ // floor: never claims an unheard millisecond; monotonic because it is cumulative.
+ const playedMs = Math.floor((playedSamples / srcRate) * 1000);
+ if (playedMs <= 0) return;
this.port.postMessage({ type: 'progress', audioRef: ref, playedMs });
}
}
diff --git a/src/app/app.routes.ts b/src/app/app.routes.ts
index 5d2cfe7..5ac1f9c 100644
--- a/src/app/app.routes.ts
+++ b/src/app/app.routes.ts
@@ -32,7 +32,7 @@ export const routes: Routes = [
},
{
path: '',
- title: 'دستیار هوشمند',
+ title: 'دستیار هوش مصنوعی',
component: HomePage,
canActivate: [authGuard],
},
@@ -68,7 +68,7 @@ export const routes: Routes = [
},
{
path: 'chat-questions',
- title: 'سوالات چت سایت و اپلیکیشن',
+ title: 'سوالات چت وب اپلیکیشن',
component: ChatQuestionsPage,
canActivate: [authGuard],
},
diff --git a/src/app/layout/layout.component.ts b/src/app/layout/layout.component.ts
index 8151fd0..09455f6 100644
--- a/src/app/layout/layout.component.ts
+++ b/src/app/layout/layout.component.ts
@@ -21,9 +21,13 @@ const BASE_NAV_ITEMS: NavItem[] = [
label: 'بازخوانی تماسها از کال سنتر',
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: 'تنظیمات',
route: '/settings',
},
diff --git a/src/app/pages/call-center/call-center.page.ts b/src/app/pages/call-center/call-center.page.ts
index 63f0066..8b1e898 100644
--- a/src/app/pages/call-center/call-center.page.ts
+++ b/src/app/pages/call-center/call-center.page.ts
@@ -63,12 +63,12 @@ export class CallCenterPage {
description:
'تماسهایی که هوش مصنوعی نتوانسته پاسخ دهد، به همراه سابقه گفتگو به کارشناس ارجاع میشود.',
},
- {
- id: 'sync',
- icon: 'M21 12A9 9 0 0 0 6.6 7.5l-3 3m0 0 3 3-3-3Z',
- title: 'همگامسازی وضعیت کارشناسان',
- description:
- 'حاضر بودن، مرخصی و خارجشدن کارشناسان بین برنامه و سامانه کال سنتر همگام میشود.',
- },
+ {
+ id: 'sync',
+ icon: 'M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8M21 3v5h-5M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16M8 16H3v5',
+ title: 'همگامسازی وضعیت کارشناسان',
+ description:
+ 'حاضر بودن، مرخصی و خارجشدن کارشناسان بین برنامه و سامانه کال سنتر همگام میشود.',
+},
];
}
diff --git a/src/app/pages/chat-questions/chat-questions.page.css b/src/app/pages/chat-questions/chat-questions.page.css
index 9e32c8f..f301e2f 100644
--- a/src/app/pages/chat-questions/chat-questions.page.css
+++ b/src/app/pages/chat-questions/chat-questions.page.css
@@ -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 {
flex: 1 1 22rem;
diff --git a/src/app/pages/chat-questions/chat-questions.page.html b/src/app/pages/chat-questions/chat-questions.page.html
index 66429fe..b4286d4 100644
--- a/src/app/pages/chat-questions/chat-questions.page.html
+++ b/src/app/pages/chat-questions/chat-questions.page.html
@@ -16,8 +16,8 @@
-
سوالات چت سایت و اپلیکیشن
-
پرسشهای ثبتشده در چت سایت و اپلیکیشن موبایل
+
سوالات چت وب اپلیکیشن
+
پرسشهای ثبتشده در چت وب اپلیکیشن
نمایشی
@@ -53,9 +53,7 @@
@@ -66,10 +64,18 @@
{{ item.question }}
diff --git a/src/app/pages/chat-questions/chat-questions.page.spec.ts b/src/app/pages/chat-questions/chat-questions.page.spec.ts
index 87d2fb7..18bf8ab 100644
--- a/src/app/pages/chat-questions/chat-questions.page.spec.ts
+++ b/src/app/pages/chat-questions/chat-questions.page.spec.ts
@@ -30,7 +30,7 @@ describe('ChatQuestionsPage', () => {
fixture.detectChanges();
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('داده نمونه');
diff --git a/src/app/pages/settings/settings.page.css b/src/app/pages/settings/settings.page.css
index 3a29009..64cc985 100644
--- a/src/app/pages/settings/settings.page.css
+++ b/src/app/pages/settings/settings.page.css
@@ -261,11 +261,20 @@
.settings-tabs {
flex-direction: column;
}
-
+
+ .tab-divider {
+ display: none;
+ }
+
.tab-btn {
justify-content: flex-start;
padding: 1rem;
}
+
+ .tab-btn span {
+ white-space: normal;
+ text-align: right;
+ }
.tab-btn .tab-indicator {
display: none;
@@ -458,6 +467,15 @@
background: var(--color-danger)/15;
color: var(--color-danger);
}
+
+/* Plain text colours for the document active flag (no badge background). */
+.doc-active {
+ color: var(--color-success);
+}
+
+.doc-inactive {
+ color: var(--text-muted);
+}
.status-dot,
.dot-queued,
.dot-processing,
diff --git a/src/app/pages/settings/settings.page.html b/src/app/pages/settings/settings.page.html
index 74ee65e..11a7a82 100644
--- a/src/app/pages/settings/settings.page.html
+++ b/src/app/pages/settings/settings.page.html
@@ -69,6 +69,37 @@
>
}
+
+
+
+
+
+
+
+
+
+ تنظیمات مدلهای هوش مصنوعی
+ @if (activeTab() === 'models') {
+
+ }
+
@@ -313,13 +344,16 @@
type="button"
class="file-remove-btn p-1 text-[var(--text-muted)] rounded transition-colors hover:text-[var(--color-primary)]"
(click)="retryUpload($index)"
- aria-label="دوبارهسعی آپلود"
- title="دوبارهسعی"
+ aria-label="تلاش مجدد آپلود"
+ title="تلاش مجدد"
>
-
+
+
+
+
}
@@ -332,12 +366,20 @@
@if (!isAdmin()) {
-
-
-
-
+
+
+
+
+
+
مدیریت و لیست اسناد فقط برای ادمینها در دسترس است.
}
@@ -346,18 +388,19 @@
}
@if (documentsError() && documents().length === 0) {
@@ -389,7 +439,7 @@
@@ -407,11 +457,20 @@
فقط فعال
-
-
-
-
+
+
+
+
+
+
بهروزرسانی
@@ -472,12 +531,17 @@
@if (doc.status === 'ready' && !isReviewNeeded(doc) && isAdmin()) {
@if (togglingDocId() === doc.id) {
-
-
-
-
+
+
+
+
در حال بهروزرسانی
} @else {
@@ -493,8 +557,8 @@
} @else {
{{ doc.is_active ? 'فعال' : 'غیرفعال' }}
}
@@ -508,13 +572,19 @@
[disabled]="reviewingDocId() === doc.id"
(click)="openReview(doc)"
>
-
-
-
-
-
+
+
+
+
بازبینی سند
}
@@ -524,12 +594,21 @@
class="btn btn--outline"
(click)="retryDocument(doc)"
>
-
-
+
+
+
+
+
- دوبارهسعی
+ تلاشمجدد
}
@@ -595,12 +674,18 @@
@if (reviewLoading()) {
-
-
-
-
+
+
+
+
در حال بارگذاری شواهد...
}
@@ -742,11 +827,22 @@
@@ -820,8 +916,13 @@
-
-
+
+ }
+
+ @if (activeTab() === 'models') {
+
+
-
diff --git a/src/app/pages/settings/settings.page.ts b/src/app/pages/settings/settings.page.ts
index 190a69f..929768c 100644
--- a/src/app/pages/settings/settings.page.ts
+++ b/src/app/pages/settings/settings.page.ts
@@ -19,7 +19,7 @@ import {
AiModelConfig,
AiTask,
} 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 {
DocumentDetail,
DocumentListItem,
@@ -35,7 +35,7 @@ import {
DOCUMENT_STATUS_LABEL,
} from '../../services/documents/documents.types';
-type TabId = 'faq' | 'app';
+type TabId = 'faq' | 'app' | 'models';
type UploadStatus = 'uploading' | 'done' | 'error';
interface UploadTask {
@@ -151,6 +151,7 @@ export class SettingsPage implements OnInit, OnDestroy {
readonly tabs: { id: TabId; label: string }[] = [
{ id: 'faq', label: 'آپلود FAQ' },
{ id: 'app', label: 'تنظیمات برنامه' },
+ { id: 'models', label: 'تنظیمات مدلهای هوش مصنوعی' },
];
readonly activeTab = signal
('faq');
@@ -347,21 +348,9 @@ export class SettingsPage implements OnInit, OnDestroy {
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
+ /** تاریخ آپلود به صورت تاریخ و ساعت جلالی */
formatDateTime(iso: string): string {
- try {
- 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 '—';
- }
+ return formatJalaliDateTime(iso);
}
get fileCount(): number {
diff --git a/src/app/pages/wallboard/wallboard.page.html b/src/app/pages/wallboard/wallboard.page.html
index 4361202..d54d889 100644
--- a/src/app/pages/wallboard/wallboard.page.html
+++ b/src/app/pages/wallboard/wallboard.page.html
@@ -39,7 +39,8 @@
stroke-linecap="round"
stroke-linejoin="round"
>
-
+
+
بهروزرسانی
diff --git a/src/app/services/http-request/http.service.ts b/src/app/services/http-request/http.service.ts
index 819c5d4..6658226 100644
--- a/src/app/services/http-request/http.service.ts
+++ b/src/app/services/http-request/http.service.ts
@@ -50,11 +50,16 @@ export class HttpService {
* the dev-server proxy (proxy.conf.json) forwards `/api` — including WebSocket
* upgrades — to the backend. The `rag_session` cookie therefore stays same-origin
* and is sent automatically; no bearer token is used for the MVP endpoints.
+ *
+ * NOTE: the origin MUST stay empty (`''`). Pointing these at an absolute host
+ * (e.g. `http://10.2.8.3: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';
- public readonly backendUrl = 'http://10.0.8.51:1321';
- public readonly apiUrl = 'http://10.0.8.51:1321';
- public readonly imagesUrl = 'http://10.0.8.51:1321';
+ private readonly baseUrl = '';
+ public readonly backendUrl = '';
+ public readonly apiUrl = '';
+ public readonly imagesUrl = '';
constructor(
private readonly http: HttpClient,
@@ -170,6 +175,7 @@ export class HttpService {
.get>(url, {
headers,
params: options.params,
+ withCredentials: true,
})
.pipe(
map((response) => this.processResponse(response, options)),
@@ -206,7 +212,7 @@ export class HttpService {
...headers,
},
signal: controller.signal,
- credentials: 'same-origin',
+ credentials: 'include',
})
.then((response) => {
if (!response.ok || !response.body) {
@@ -268,6 +274,7 @@ export class HttpService {
.post>(url, data, {
headers: this.mergeHeaders(options.headers),
params: options.params,
+ withCredentials: true,
})
.pipe(
map((response) => this.processResponse(response, options)),
@@ -281,6 +288,7 @@ export class HttpService {
return this.http.post(url, data, {
headers,
params: options.params,
+ withCredentials: true,
});
}
@@ -292,7 +300,7 @@ export class HttpService {
const url = `${this.baseUrl}/${endpoint}`;
const headers = options.headers ? new HttpHeaders(options.headers) : new HttpHeaders();
return this.http
- .patch(url, data, { headers, params: options.params })
+ .patch(url, data, { headers, params: options.params, withCredentials: true })
.pipe(catchError((err) => this.handleError(err, options.skipToast)));
}
@@ -315,6 +323,7 @@ export class HttpService {
params: options.params,
reportProgress: true,
observe: 'events',
+ withCredentials: true,
});
if (!options.signal) {
@@ -341,6 +350,7 @@ export class HttpService {
return this.http.get(url, {
headers,
params: options.params,
+ withCredentials: true,
});
}
@@ -350,6 +360,7 @@ export class HttpService {
.put>(url, data, {
headers: this.mergeHeaders(options.headers),
params: options.params,
+ withCredentials: true,
})
.pipe(
map((response) => this.processResponse(response, options)),
@@ -363,6 +374,7 @@ export class HttpService {
.patch>(url, data, {
headers: this.mergeHeaders(options.headers),
params: options.params,
+ withCredentials: true,
})
.pipe(
map((response) => this.processResponse(response, options)),
@@ -376,6 +388,7 @@ export class HttpService {
.delete>(url, {
headers: this.mergeHeaders(options.headers),
params: options.params,
+ withCredentials: true,
})
.pipe(
map((response) => this.processResponse(response, options)),
@@ -388,6 +401,7 @@ export class HttpService {
.get(url, {
headers: this.getHeaders(),
responseType: 'blob',
+ withCredentials: true,
})
.pipe(catchError((err) => this.handleError(err, false)));
}
diff --git a/src/app/services/voice-stream/pcm-playback.worklet.spec.ts b/src/app/services/voice-stream/pcm-playback.worklet.spec.ts
new file mode 100644
index 0000000..99b490e
--- /dev/null
+++ b/src/app/services/voice-stream/pcm-playback.worklet.spec.ts
@@ -0,0 +1,225 @@
+import { describe, it, 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 }>;
+ port: { onmessage: (e: { data: unknown }) => void };
+ count: number;
+ capacity: number;
+ queuedSource: number;
+ sourceCapacity: number;
+ refPlayedSamples: Map;
+ process: (inputs: unknown[][][], outputs: Float32Array[][]) => boolean;
+}
+
+class FakeAudioWorkletProcessor {
+ out: Array<{ type: string; audioRef?: string; playedMs?: number }> = [];
+ port: {
+ onmessage: ((e: { data: unknown }) => void) | null;
+ postMessage: (m: { type: string; audioRef?: string; playedMs?: number }) => void;
+ };
+ constructor() {
+ this.port = { onmessage: null, postMessage: (m) => this.out.push(m) };
+ }
+}
+
+let Registered: (new () => Proc) | null = null;
+const ensureRegistered = async (): Promise Proc> => {
+ if (Registered) return Registered;
+ const g = globalThis as unknown as Record;
+ 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 {
+ 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' } });
+}
+
+/** 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);
+ });
+
+ 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('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 source samples (±1 sample of resampler lag),
+ // never the other ref's samples. The next-ref bug would credit 'aud-b' with 6,000.
+ expect(Math.abs((proc.refPlayedSamples.get('aud-a') ?? 0) - 3000)).toBeLessThanOrEqual(1);
+ expect(Math.abs((proc.refPlayedSamples.get('aud-b') ?? 0) - 3000)).toBeLessThanOrEqual(1);
+ 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'
+ });
+ });
+
+ 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.refPlayedSamples.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);
+ });
+ });
+});
diff --git a/src/app/services/voice-stream/voice-api.service.ts b/src/app/services/voice-stream/voice-api.service.ts
index bd7f1d4..98731fc 100644
--- a/src/app/services/voice-stream/voice-api.service.ts
+++ b/src/app/services/voice-stream/voice-api.service.ts
@@ -1,11 +1,14 @@
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
-import { firstValueFrom, race, throwError, Observable } from 'rxjs';
-import { delay } from 'rxjs/operators';
+import { firstValueFrom, Observable } from 'rxjs';
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 } }. */
export class VoiceApiError extends Error {
@@ -199,14 +202,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(request: Observable): Observable {
- return race(
- request,
- throwError(() => new VoiceApiError(0, 'TIMEOUT', 'request-deadline')).pipe(
- delay(REQUEST_DEADLINE_MS),
- ),
- );
+ return new Observable((observer) => {
+ let settled = false;
+
+ const timer = setTimeout(() => {
+ if (settled) return;
+ settled = true;
+ observer.error(new VoiceApiError(0, 'TIMEOUT', 'request-deadline'));
+ }, REQUEST_DEADLINE_MS);
+
+ request.subscribe({
+ next: (value) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ observer.next(value);
+ },
+ error: (err: unknown) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ observer.error(this.toApiError(err));
+ },
+ complete: () => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ observer.complete();
+ },
+ });
+
+ // Only the timer is torn down: the in-flight request is left to finish naturally.
+ return () => clearTimeout(timer);
+ });
}
private toApiError(err: unknown): VoiceApiError {
diff --git a/src/app/services/voice-stream/voice-audio-engine.service.ts b/src/app/services/voice-stream/voice-audio-engine.service.ts
index 1efb930..c1b01b4 100644
--- a/src/app/services/voice-stream/voice-audio-engine.service.ts
+++ b/src/app/services/voice-stream/voice-audio-engine.service.ts
@@ -1,5 +1,5 @@
import { Injectable, NgZone, inject } from '@angular/core';
-import { MicrophoneService } from '../microphone/microphone.service';
+import { MicrophoneError, MicrophoneService } from '../microphone/microphone.service';
import { VOICE_STREAM_CONFIG } from './voice-stream.types';
export interface VoiceEngineHandlers {
@@ -72,15 +72,28 @@ export class VoiceAudioEngine {
await this.ngZone.runOutsideAngular(() => this.buildGraph(stream, handlers));
} catch (err) {
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 {
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;
+ // Explicitly reject an unusable context rate: a 0/NaN/non-finite rate cannot resample
+ // and must fail safely instead of silently producing no playback.
+ if (!Number.isFinite(ctx.sampleRate) || ctx.sampleRate < 8000 || ctx.sampleRate > 192000) {
+ throw new VoiceEngineError('unsupported');
+ }
+
const base = cfg.workletBasePath.replace(/\/$/, '');
await ctx.audioWorklet.addModule(`${base}/pcm-capture.worklet.js`);
await ctx.audioWorklet.addModule(`${base}/pcm-playback.worklet.js`);
@@ -136,6 +149,22 @@ export class VoiceAudioEngine {
this.analyserData = new Uint8Array(this.analyser.fftSize);
this.playback.connect(this.analyser);
this.analyser.connect(ctx.destination);
+
+ this.logPipelineDiagnostics(ctx);
+ }
+
+ /**
+ * Bounded development diagnostics — one line per session, numbers only. Confirms the
+ * ACTUAL context rate/state (not the requested one) and that the playback graph is
+ * connected and running. Never logs audio, transcripts, cookies or credentials.
+ */
+ private logPipelineDiagnostics(ctx: AudioContext): void {
+ const requested = this.config.outputSampleRate;
+ const resample = ctx.sampleRate === requested ? 'none' : 'worklet';
+ console.info(
+ `VoiceAudioEngine: ctx.sampleRate=${ctx.sampleRate}Hz (requested ${requested}Hz) ` +
+ `state=${ctx.state} playbackGraph=connected resample=${resample}`,
+ );
}
// ---- playback --------------------------------------------------------------
diff --git a/src/app/services/voice-stream/voice-stream.service.spec.ts b/src/app/services/voice-stream/voice-stream.service.spec.ts
index 5fbc057..6cebb29 100644
--- a/src/app/services/voice-stream/voice-stream.service.spec.ts
+++ b/src/app/services/voice-stream/voice-stream.service.spec.ts
@@ -33,9 +33,21 @@ const READY_EVENT: VoiceServerEvent = {
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. */
const flush = (): Promise => new Promise((resolve) => setTimeout(resolve, 5));
+type Mock = ReturnType;
+type TransportMock = Omit & {
+ handlers: VoiceTransportHandlers | null;
+ connect: Mock;
+ sendAudio: Mock;
+ sendControl: Mock;
+ close: Mock;
+};
+
describe('VoiceStreamService (backend handoff contract)', () => {
let service: VoiceStreamService;
let api: {
@@ -51,12 +63,15 @@ describe('VoiceStreamService (backend handoff contract)', () => {
let engineHandlers: VoiceEngineHandlers | null;
let transportHandlers: VoiceTransportHandlers | null;
let controls: PlaybackProgressMessage[];
+ let transportMock: TransportMock;
+ let engineStop: ReturnType;
beforeEach(() => {
sessionStorage.clear();
engineHandlers = null;
transportHandlers = null;
controls = [];
+ engineStop = vi.fn();
api = {
me: vi.fn().mockResolvedValue(ME),
@@ -69,7 +84,7 @@ describe('VoiceStreamService (backend handoff contract)', () => {
streamUrl: vi.fn().mockReturnValue('wss://ui.local/api/v1/voice/sessions/ses-1/stream'),
};
- const transportMock: VoiceTransport & { handlers: VoiceTransportHandlers | null } = {
+ transportMock = {
handlers: null,
connect: vi.fn().mockImplementation((handlers: VoiceTransportHandlers) => {
transportHandlers = handlers;
@@ -95,7 +110,7 @@ describe('VoiceStreamService (backend handoff contract)', () => {
engineHandlers = handlers;
return Promise.resolve();
}),
- stop: vi.fn(),
+ stop: engineStop,
setMuted: vi.fn(),
enqueuePlayback: vi.fn(),
clearPlayback: vi.fn(),
@@ -228,10 +243,73 @@ describe('VoiceStreamService (backend handoff contract)', () => {
engineHandlers?.onPlaybackOverflow();
- expect(await ended).toBe('حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو بهطور ایمن پایان یافت.');
+ expect(await ended).toBe(OVERFLOW_MESSAGE);
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('requires a fresh conversation after CONTEXT_REVOKED and drops the old attempt', async () => {
await startConnected();
const ended = firstEndedError();
diff --git a/src/app/services/voice-stream/voice-stream.service.ts b/src/app/services/voice-stream/voice-stream.service.ts
index bbda972..7cceef8 100644
--- a/src/app/services/voice-stream/voice-stream.service.ts
+++ b/src/app/services/voice-stream/voice-stream.service.ts
@@ -32,6 +32,29 @@ type TranscriptEvent = Extract;
type SourcesEvent = Extract;
type ErrorEvent = Extract;
+/**
+ * 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 = {
unsupported: 'گفتگوی صوتی در این مرورگر پشتیبانی نمیشود (اتصال امن HTTPS و مرورگر جدید لازم است).',
micDenied: 'دسترسی به میکروفون رد شد. اجازهی دسترسی را در تنظیمات مرورگر فعال کنید.',
@@ -47,6 +70,7 @@ const MESSAGES = {
connect: 'اتصال به سرور صوتی برقرار نشد. دوباره تلاش کنید.',
badFormat: 'فرمت صدای سرور با برنامه سازگار نیست.',
overflow: 'حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو بهطور ایمن پایان یافت.',
+ sendOverflow: 'حجم صدای ارسالی از محدودهٔ مجاز گذشت و گفتگو بهطور ایمن پایان یافت.',
disconnected: 'ارتباط با سرور قطع شد و گفتگو پایان یافت.',
server: 'سرور گفتگوی صوتی با خطا مواجه شد.',
contextRevoked: 'محتوای دانش تغییر کرده و مکالمهٔ قبلی دیگر معتبر نیست. گفتگوی جدیدی شروع کنید.',
@@ -60,6 +84,8 @@ const INTERRUPTED_FLASH_MS = 150;
const ERROR_BANNER_MS = 6000;
/** Longest wait for the worklet's final playback report when closing a call. */
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;
/**
* One live voice call against the backend handoff contract (§7–§9):
@@ -106,6 +132,8 @@ export class VoiceStreamService {
private transport: VoiceTransport | 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 | null = null;
private session = 0;
private streaming = false;
private turnEnded = false;
@@ -149,6 +177,7 @@ export class VoiceStreamService {
this.messages.set([]);
this.muted.set(false);
this.clearError();
+ this.cleanupPromise = null;
this.resetTurnFlags();
this.lastConversationId = null;
this.currentAudioRef = null;
@@ -221,8 +250,14 @@ export class VoiceStreamService {
transport.connect({
onEvent: (event) => this.ngZone.run(() => this.onServerEvent(event, session)),
onAudio: (chunk) => this.onServerAudio(chunk, session),
- onClose: () => this.ngZone.run(() => this.failSession(MESSAGES.disconnected, session)),
- onOverflow: () => this.ngZone.run(() => this.failSession(MESSAGES.overflow, session)),
+ onClose: (info) =>
+ 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 {
@@ -262,39 +297,21 @@ export class VoiceStreamService {
}
/**
- * Intentional close: final playback progress for the active audio_ref, then V04, and
- * only then the socket/audio teardown — the order required by the contract.
+ * Intentional close: routes through the single per-session cleanup so final progress →
+ * 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 {
- if (!this.isOpen()) {
- // Idle: nothing to close. A persisted creation attempt from an ambiguous reserve
- // outcome is kept so the next start() reconciles it instead of duplicating it.
- return;
- }
- const remote = this.remote;
- // 1) final, worklet-computed playback progress for the ref that is still playing
- await this.reportFinalProgress();
- // 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 });
- }
+ async close(options: { error?: string; detail?: string } = {}): Promise {
+ // Idle with no cleanup in flight: nothing to close. A persisted creation attempt from
+ // an ambiguous reserve outcome is kept so the next start() reconciles it, not duplicates.
+ if (this.connection() === 'disconnected' && !this.cleanupPromise) return;
+ await this.teardown({
+ ordered: true,
+ closeRemote: true,
+ error: options.error,
+ detail: options.detail,
+ });
}
/**
@@ -366,7 +383,7 @@ export class VoiceStreamService {
dispose(): void {
this.rejectReady();
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) --------------------------
@@ -533,7 +550,10 @@ export class VoiceStreamService {
private onServerError(event: ErrorEvent, session: number): void {
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
// (Gemini interruption can also require ending the session entirely).
@@ -547,7 +567,7 @@ export class VoiceStreamService {
}
if (!retryable) {
- this.failSession(message || MESSAGES.server, session);
+ this.failSession(message || MESSAGES.server, session, `server error ${code}`);
return;
}
@@ -693,11 +713,29 @@ export class VoiceStreamService {
// ---- 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;
- // `close()` performs the ordered teardown (final progress → V04 → transport) and
- // emits sessionEnded$ exactly once, carrying the failure message.
- void this.close({ error: message });
+ // `close()` runs the ordered single-flight cleanup (final progress → V04 → release)
+ // and emits sessionEnded$ exactly once, carrying the first meaningful failure. The
+ // `session`/isOpen guard above drops stale callbacks so an old session never ends a
+ // newer one.
+ void this.close({ error: message, detail });
}
private abortStart(
@@ -705,44 +743,130 @@ export class VoiceStreamService {
failure: { reason: VoiceStartFailure; message: string },
keepAttempt = false,
): 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);
}
- /** Releases every resource; idempotent. Invalidates all pending async work via `session`. */
- private teardown(options: { keepAttempt?: boolean } = {}): void {
- this.session++;
+ /**
+ * The ONE cleanup per session. Every end path funnels through here: overflow, server
+ * 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 {
+ 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 {
+ 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.resetTurnFlags();
- this.clearSettleTimer();
- this.clearError();
- this.resolveProgressWaiters();
- this.currentAudioRef = null;
- if (this.interruptTimer) {
- clearTimeout(this.interruptTimer);
- this.interruptTimer = null;
+
+ 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.rejectReady();
+ this.resolveProgressWaiters();
+ this.clearSettleTimer();
+ if (this.interruptTimer) {
+ clearTimeout(this.interruptTimer);
+ this.interruptTimer = null;
+ }
+ this.currentAudioRef = null;
+ };
+
+ 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(work: Promise, ms: number): Promise {
+ let timer: ReturnType | undefined;
+ const timedOut = new Promise((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;
this.transport = null;
transport?.close();
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.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) {
this.attempt = null;
clearPersistedAttempt();
}
- if (remote) this.closeRemote(remote);
+ this.clearError();
this.connection.set('disconnected');
this.state.set('IDLE');
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 {
this.api.closeVoiceSession(remote.csrf, remote.sessionId).catch(() => {
/* already closed / expired (e.g. 409 LIVE_SESSION_UNUSABLE): nothing to do */
@@ -751,19 +875,9 @@ export class VoiceStreamService {
private onPageLeave = (): void => {
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
// it with V02/V03 (V04 may not complete while unloading) before anything else.
- this.connection.set('disconnected');
- this.state.set('IDLE');
+ void this.teardown({ ordered: false, closeRemote: true, keepAttempt: true, emitEnded: false });
};
private resetTurnFlags(): void {
diff --git a/src/app/services/voice-stream/voice-stream.types.ts b/src/app/services/voice-stream/voice-stream.types.ts
index 30f3ed1..679f538 100644
--- a/src/app/services/voice-stream/voice-stream.types.ts
+++ b/src/app/services/voice-stream/voice-stream.types.ts
@@ -100,6 +100,12 @@ export interface VoiceSessionEnd {
messages: VoiceMessage[];
/** User-facing (Persian) message when the session ended because of a failure. */
error?: string;
+ /**
+ * Machine-readable cause for logs/diagnostics, e.g. `ws close 1006 reason="…"`.
+ * The server's close code/reason says why the socket died; without it the only
+ * thing surfaced is a generic "disconnected" banner and the root cause is invisible.
+ */
+ detail?: string;
}
/** V02/V03 polling shape (safe diagnostics only). */
@@ -128,7 +134,7 @@ export interface VoiceStreamConfig {
export const DEFAULT_VOICE_STREAM_CONFIG: VoiceStreamConfig = {
apiBase: '/api/v1',
- apiOrigin: 'http://10.0.8.51:1322',
+ apiOrigin: '',
inputSampleRate: 24000,
outputSampleRate: 24000,
frameMs: 20,
diff --git a/src/app/services/voice-stream/voice-transport.ts b/src/app/services/voice-stream/voice-transport.ts
index 06e465d..23638be 100644
--- a/src/app/services/voice-stream/voice-transport.ts
+++ b/src/app/services/voice-stream/voice-transport.ts
@@ -32,6 +32,10 @@ const MAX_QUEUE_MESSAGES = 100;
* Plain WebSocket. Authentication is the `rag_session` cookie sent automatically on the
* handshake, so the page is served from the same origin as the API (same-origin `/api`
* proxy). The contract has exactly one client→server JSON message: `playback_progress`.
+ *
+ * Diagnostics: every control frame received is kept in a short ring buffer and dumped when
+ * the socket dies, so the server's last message — normally an `error` frame carrying the
+ * real cause — is in the console instead of leaving only a bare close code.
*/
export class WebSocketVoiceTransport implements VoiceTransport {
private ws: WebSocket | null = null;
@@ -41,6 +45,11 @@ export class WebSocketVoiceTransport implements VoiceTransport {
private sendQueue: ArrayBuffer[] = [];
private sendQueuedBytes = 0;
private sendQueuedMessages = 0;
+ /** Recent server control frames (newest last), replayed when the socket closes. */
+ private readonly recentFrames: string[] = [];
+
+ /** How many recent control frames to keep for a disconnect dump. */
+ private static readonly FRAME_TRACE_LIMIT = 12;
constructor(
private readonly url: string,
@@ -70,11 +79,15 @@ export class WebSocketVoiceTransport implements VoiceTransport {
ws.onmessage = (event: MessageEvent) => {
if (typeof event.data === 'string') {
+ let parsed: VoiceServerEvent | null = null;
try {
- handlers.onEvent(JSON.parse(event.data) as VoiceServerEvent);
+ parsed = JSON.parse(event.data) as VoiceServerEvent;
} catch {
/* ignore malformed control frames */
+ return;
}
+ this.traceFrame(parsed);
+ handlers.onEvent(parsed);
} else if (event.data instanceof ArrayBuffer) {
handlers.onAudio(event.data);
}
@@ -84,7 +97,12 @@ export class WebSocketVoiceTransport implements VoiceTransport {
if (!opened) {
clearTimeout(timer);
reject(new Error('connect-failed'));
+ return;
}
+ // After the handshake a bare Event carries no detail; the `onclose` that follows
+ // has the code/reason. Log it anyway so the disconnect sequence is visible in the
+ // console instead of looking like a silent socket death.
+ console.warn('WebSocketVoiceTransport: socket error after open');
};
ws.onclose = (event: CloseEvent) => {
@@ -95,6 +113,7 @@ export class WebSocketVoiceTransport implements VoiceTransport {
}
this.dropSendQueue();
if (!this.closedByClient) {
+ this.logDisconnect(event);
handlers.onClose({ clean: event.wasClean, code: event.code, reason: event.reason });
}
};
@@ -150,6 +169,54 @@ 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 === 'audio_started' || type === 'audio_ended') {
+ return `${type} ${(event as { audio_ref?: string }).audio_ref ?? ''}`.trim();
+ }
+ if (type === 'error') {
+ return JSON.stringify(event);
+ }
+ return type;
+ }
+
private flushSendQueue(): void {
const ws = this.ws;
const queue = this.sendQueue;
diff --git a/src/app/shared/styles/demo-page.css b/src/app/shared/styles/demo-page.css
index 541124d..1316d8c 100644
--- a/src/app/shared/styles/demo-page.css
+++ b/src/app/shared/styles/demo-page.css
@@ -1,5 +1,5 @@
/* Shared chrome for the symbolic demonstration pages:
- «ارتباط با کال سنتر»، «بازخوانی تماسها از کال سنتر» and «سوالات چت سایت و اپلیکیشن».
+ «ارتباط با کال سنتر»، «بازخوانی تماسها از کال سنتر» and «سوالات چت وب اپلیکیشن».
Each page component includes this file through styleUrls, so keep every selector
page-agnostic (prefix: demo-). Visual language mirrors the reports/wallboard pages. */
@@ -75,7 +75,9 @@
border: 1px solid var(--card-border);
border-radius: 1.25rem;
background: var(--card-bg);
- box-shadow: 0 10px 40px rgba(0, 0, 0, 0.06), 0 2px 10px rgba(0, 0, 0, 0.03);
+ 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;
}
@@ -298,7 +300,10 @@
font-weight: 500;
border: 1px solid transparent;
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 {
@@ -525,5 +530,7 @@
}
: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);
}
diff --git a/src/app/shared/ui/ai-model-config-card/ai-model-config-card.component.css b/src/app/shared/ui/ai-model-config-card/ai-model-config-card.component.css
index d70d1f6..27a9b51 100644
--- a/src/app/shared/ui/ai-model-config-card/ai-model-config-card.component.css
+++ b/src/app/shared/ui/ai-model-config-card/ai-model-config-card.component.css
@@ -54,9 +54,9 @@
appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%2364748b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
background-repeat: no-repeat;
- background-position: right 0.75rem center;
- padding-right: 2.5rem;
- padding-left: 0.75rem;
+ background-position: right 1rem center;
+ padding: 0.75rem 1rem;
+ padding-right: 2.75rem;
background-color: var(--color-input-bg);
color: var(--text-secondary);
border: 1px solid var(--color-input-border);
@@ -95,7 +95,7 @@
.form-visibility-toggle {
position: absolute;
- inset-inline-start: 0.5rem;
+ inset-inline-end: 0.5rem;
top: 50%;
translate: 0 -50%;
display: flex;
diff --git a/src/app/shared/ui/ai-model-config-card/ai-model-config-card.component.ts b/src/app/shared/ui/ai-model-config-card/ai-model-config-card.component.ts
index a6fdebd..584b9f0 100644
--- a/src/app/shared/ui/ai-model-config-card/ai-model-config-card.component.ts
+++ b/src/app/shared/ui/ai-model-config-card/ai-model-config-card.component.ts
@@ -41,44 +41,47 @@ interface ModelOption {
ارائهدهنده
-
- @for (provider of providers(); track provider.value) {
- {{ provider.label }}
- }
-
+
+ @for (provider of providers(); track provider.value) {
+ {{ provider.label }}
+ }
+
مدل
-
- @for (model of modelsForProvider(); track model.value) {
- {{ model.label }}
- }
-
+
+ @for (model of modelsForProvider(); track model.value) {
+ {{ model.label }}
+ }
+
@@ -131,14 +151,21 @@ interface ModelOption {
[attr.aria-label]="'آدرس سرویس ' + title()"
/>
@if (!serviceUrlEditable()) {
-
آدرس استاندارد {{ config().provider === 'local' ? 'سرویس محلی' : 'سرویس' }} بهصورت پیشفرض به کار میرود
+
آدرس استاندارد {{ config().provider === 'local' ? 'سرویس محلی' : 'سرویس' }} بهصورت
+ پیشفرض به کار میرود
}
- ذخیره تنظیمات
- بررسی اتصال
+
+ ذخیره تنظیمات
+
+
+ بررسی اتصال
+
@@ -240,10 +267,7 @@ const DEFAULT_CONFIG_FOR: Record ({ value, label });
-const MODELS_BY_TASK: Record<
- AiTask,
- Partial>
-> = {
+const MODELS_BY_TASK: Record>> = {
text: {
openai: [
MODEL_OPTION('gpt-4o', 'GPT-4o'),
diff --git a/src/app/shared/ui/sidebar/sidebar.component.ts b/src/app/shared/ui/sidebar/sidebar.component.ts
index aa49e8b..4e35a4f 100644
--- a/src/app/shared/ui/sidebar/sidebar.component.ts
+++ b/src/app/shared/ui/sidebar/sidebar.component.ts
@@ -21,7 +21,7 @@ export interface ChatHistoryItem {
imports: [CommonModule, RouterModule, CdkMenuModule],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './sidebar.component.html',
- styleUrl: './sidebar.component.css'
+ styleUrl: './sidebar.component.css',
})
export class SidebarComponent {
private readonly themeService = inject(ThemeService);
@@ -56,11 +56,11 @@ export class SidebarComponent {
},
{
icon: 'M7.9 20A9 9 0 1 0 4 16.1L2 22Z',
- label: 'سوالات چت سایت و اپلیکیشن',
+ 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.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: 'تنظیمات',
route: '/settings',
},
diff --git a/src/app/shared/utils/format.util.ts b/src/app/shared/utils/format.util.ts
index 80b9231..92ff7a9 100644
--- a/src/app/shared/utils/format.util.ts
+++ b/src/app/shared/utils/format.util.ts
@@ -1,3 +1,5 @@
+import moment from 'moment-jalaali';
+
const PERSIAN_DIGITS = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
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 {
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'));
+}
diff --git a/src/index.html b/src/index.html
index 0a14ad5..7826c72 100644
--- a/src/index.html
+++ b/src/index.html
@@ -2,7 +2,7 @@
- FaqChatbot
+ دستیار هوش مصنوعی
diff --git a/src/styles.css b/src/styles.css
index 456bf21..d282d5e 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -21,6 +21,7 @@
}
:root {
+ color-scheme: light;
--app-bg: #f8fafc;
--app-text: #122033;
--sidebar-bg: #f8fafc;
@@ -52,6 +53,7 @@
}
[data-bs-theme="dark"] {
+ color-scheme: dark;
--app-bg: #212121;
--app-text: #ececec;
--sidebar-bg: #171717;
@@ -128,6 +130,12 @@
background-color: var(--scrollbar-track);
}
+select option,
+select optgroup {
+ background-color: var(--color-input-bg);
+ color: var(--color-text-secondary);
+}
+
body {
direction: rtl;
font-family: "Lahze", sans-serif;