Commit Graph
353 Commits
Author SHA1 Message Date
Dushnilin 1a1fd7f4c3 fix(settings): add Ollama & LM Studio to CBI settings tab options and make API key optional for local LLMs 2026-08-11 22:27:57 +03:00
Dushnilin 5db8ed7889 feat(ai-doctor): add dynamic endpoint placeholders and optional API key hint for Ollama and LM Studio 2026-08-11 22:11:48 +03:00
Dushnilin 40e185c143 i18n: actualize translation pot and po files for 1.2.74 2026-08-11 22:01:21 +03:00
Dushnilin da199c236a feat(ai-doctor): super-upgrade with Live Stepper, Root Cause Graph, Smart Fix Badges, Deep Log Inspection & Local LLM Presets 2026-08-11 22:00:20 +03:00
Dushnilin bc8a60fc73 fix(ui): hide legacy doctor repair button and make AI Doctor always clickable 2026-08-11 21:35:27 +03:00
Dushnilin 15a4f8962e fix(ui): add close and copy buttons to AI Doctor modal footer 2026-08-11 20:15:50 +03:00
Dushnilin ee44f21d77 fix(ui): remove duplicate commit sha formatting in header 2026-08-11 19:47:41 +03:00
Dushnilin 999686fea3 fix(ui): display short commit SHA next to Tachyon version in UI and constants 2026-08-11 19:06:00 +03:00
Dushnilin be5f41a52e feat(ai-stack-2026): add OpenAPI 3.0.3 schema, Telegram /ai_doctor & /fix integration, AI language selector, and log deduplication
- Agent REST API (agent_api.uc): Added GET /openapi.json returning OpenAPI 3.0.3 spec for ChatGPT Custom GPTs, N8N, Dify, and LLM Agents
- AI Doctor (runtime.uc): Added compress_log_snippet() for deduplicating repeated log entries and ai_doctor_lang support (ru/en prompt selection)
- Telegram Bot (telegram.uc): Added /ai_doctor and /fix commands with Inline Keyboards for instant quick-fix execution
- Settings (renderAdvancedSettings.ts, settings.js): Added AI Doctor Language selector (ru/en)
- Documentation: Updated README.md and README.en.md with 2026 AI features
2026-08-11 16:10:31 +03:00
Dushnilin 6dd085b777 feat(ai-doctor): supercharge AI Doctor with multi-fix, log context, history, and 13 quick fix codes
Backend (runtime.uc, agent_api.uc, tachyon CLI):
- Enrich AI Doctor LLM context with Watchdog state (OOM, streaks, active repairs) and last 15 critical log lines
- Support multi-fix parsing (quick_fixes array) and comma-separated FIX tags
- Add persistent history saving to /tmp/ai_doctor_last.json and ai_doctor_last endpoint
- Expand quick fix codes from 9 to 13 (added clear_dns_cache, update_subscriptions, reset_firewall, restart_network)
- Implement apply_quick_fix CLI command and REST API endpoint

Frontend (fe-app-tachyon, LuCI main.js):
- Add AI Doctor action button in Diagnostics tab
- Add shell methods aiDoctor, aiDoctorLast, applyQuickFix
- Render AI Doctor modal with Multi-Fix buttons and 'Fix All' option
- Integrate toast notifications and state updates
2026-08-11 16:06:19 +03:00
Dushnilin 1e365a1f9b refactor(ai-doctor): replace model dropdown with free-text input
Simpler UX: user types any model name directly.
Placeholder shows the provider default so field can stay empty.
2026-08-11 12:40:23 +03:00
Dushnilin 3d48a22e3c feat(ai-doctor): add model selection per provider
Backend (runtime.uc):
- query_llm() accepts model_override (5th param), falls back to provider default
- ai_doctor() reads ai_doctor_model from UCI and passes to query_llm

Frontend (renderAdvancedSettings.ts):
- aiDoctorModel state field (type / init / load / save)
- Model dropdown per provider with sensible defaults:
  openai: gpt-4o-mini(default)/gpt-4o/gpt-4.1-mini/gpt-4.1/o4-mini
  anthropic: claude-3-5-haiku(default)/claude-3-5-sonnet/claude-3-7-sonnet
  deepseek: deepseek-chat(default)/deepseek-reasoner
  custom: free-text input
- Switching provider resets model to '' (use new provider default)

Legacy LuCI (settings.js):
- ai_doctor_model Value field with placeholder '(provider default)'
2026-08-11 12:37:31 +03:00
Dushnilin 7ad428ddc8 refactor(watchdog): оптимизация и устранение дублирования кода
- watchdog: удалён дублирующий check_tachyon_cli_running(), везде используется controller.check_tachyon_cli_running()
- watchdog: smart_detect_process_pending использует controller.proxy_port() вместо повторного парсинга config.json
- watchdog: удалена однострочная обёртка is_dns_dead() — заменена is_dns_working() напрямую
- watchdog: heal_proxy_connectivity требует streak >= 2 перед очисткой cache.db — устраняет ложные ночные уведомления при кратких просадках прокси-ноды
- event_controller: push_history переведён на slice() вместо ручного цикла
- event_controller: direct_ok использует тот же check_url что и proxy check — корректность при кастомном ai_proxy_health_url
- event_controller: добавлен subscription_fail_streak — одиночный таймаут сети больше не триггерит Telegram
- telegram: tg_request больше не создаёт временные файлы в /tmp — JSON передаётся напрямую через curl -d, устранена утечка tg_payload_*.json при kill процесса
- telegram: worker() при старте удаляет оставшиеся tg_payload_*.json от предыдущих сессий
- tests: исправлен шаблон mktemp в background_spawn_fds.sh — busybox не поддерживает двойное расширение (.XXXXXX.uc)
2026-08-11 08:47:47 +03:00
Dushnilin 8be248f9fd fix(ui): непрерывная индикация анимации на кнопке обновления без мигания
- При получении 'Another component action is already running' или сетевого
  RPC-сбоя спиннер на нажатой кнопке больше не сбрасывается сразу.
- Добавлено повторное связывание (fallback lookups) с 800ms задержкой, чтобы
  бэкенд успевал прописать запущенный job в state до снятия индикатора.
- При отслеживании запущенного задания теперь учитываются любые фоновые
  акшны для того же компонента.
2026-08-10 21:38:46 +03:00
Dushnilin dd3546f29a fix(updates): предотвратить ложный сброс индикации загрузки при переустановке одинаковых версий
- В waitComponentActionJob добавлен минимальный порог ожидания (10с)
  перед срабатыванием fallback проверки версии Tachyon. При same-release
  обновлениях (одинаковый номер версии, но новый SHA) совпадение версии
  больше не приводит к мгновенному (за 1с) снятию спиннера loading, пока
  бэкенд на самом деле только скачивает и ставит пакет.
- Расширен список транзиентных RPC ошибок (isTransientRpcError) для
  надежного перешивания перезапуска uhttpd/rpcd/ubus во время переустановки.
- Увеличен COMPONENT_ACTION_TRANSIENT_RPC_GRACE_MS до 60с.
2026-08-10 21:30:03 +03:00
Dushnilin 5cbbd0f661 fix(ui): suppress 'Already running' and DNS retry toasts
Lock contention ('Another component action is already running') is an
expected transient state — user clicked a button while a previous action
was still in flight. Showing [error] toast confuses users into thinking
something broke. Filter it from the log watcher notification pipeline.

Also suppress DNS retry debug lines (issue #24 retry logs) from showing
as error toasts.

Added tests for both suppressed patterns.
2026-08-10 21:01:21 +03:00
Dushnilin c930c15dc3 feat(ai): добавить поддержку Anthropic Claude API в AI Doctor
- В query_llm (runtime.uc) добавлена интеграция с Anthropic Messages API (https://api.anthropic.com/v1/messages) с заголовком x-api-key
- В настройки Settings и Dashboard добавлен выпадающий выбор провайдера 'Anthropic (Claude API)'
- Добавлен русский перевод для опций AI Doctor
2026-08-10 19:16:19 +03:00
Dushnilin a15490c67d i18n: добавить русский перевод для AI Agent REST API в PO файлы 2026-08-10 19:14:41 +03:00
Dushnilin 1171cee9fd feat(ui): добавить управление токеном AI Agent REST API в LuCI
- В Advanced Settings (Dashboard) добавлен новый блок 'AI Agent REST API (12 Endpoints)'
- Позволяет просматривать, изменять и генерировать Bearer Auth Token (agent_api_token) для REST API из веб-интерфейса
- Сохраняет токен в UCI (tachyon.settings.agent_api_token)
2026-08-10 19:11:48 +03:00
Dushnilin e67e8c0984 fix(package): исключить воркеры обновления из зачистки процессов при апгрейде
- kill_matching_command и цикл зачистки fd/1000 прокси в package.uc теперь пропускют процессы ucode (action.uc / updates.uc) и их предков, предотвращая выбивание воркера обновлений по SIGKILL во время prerm
- isTransientRpcError теперь учитывает 'failed to execute' в качестве транзиентной ошибки RPC при перезапуске rpcd / служб во время обновления
2026-08-10 18:57:19 +03:00
Dushnilin b11780dec3 fix: ждать TCP-готовности proxy перед загрузкой отложенных подписок
run_deferred_subscription_bootstrap теперь после проверки что процесс
sing-box запущен дополнительно проверяет что proxy-порт реально принимает
соединения (до 10x3s).

Без этого: если порт не готов в момент вызова — fallback на прямой
download, что провалится для URL доступных только через proxy.
При неудаче через 30s запускается retry worker (поведение сохранено).

Также: get_subscription_download_proxy_address делает одиночную проверку
порта — retry worker является safety net для edge cases.
2026-08-10 18:27:38 +03:00
Dushnilin f5929d24f8 fix: дождаться готовности proxy перед загрузкой подписок и списков
При обновлении sing-box Tachyon перезапускается, запускает sing-box
и сразу пытался загрузить списки/подписки через proxy 127.0.0.1:4534,
но sing-box ещё не принял соединения на этом порту.

Исправления:
- updates.uc: dns_probe_passed теперь проверяет TCP-доступность proxy
  вместо немедленного return true; ждёт до 30s (10 попыток по 3s)
- updates.uc: download_to_file при неудаче через proxy делает fallback
  на прямой download с bootstrap DNS 8.8.8.8/1.1.1.1
- cache.uc: get_subscription_download_proxy_address проверяет что proxy-порт
  реально принимает соединения, иначе переходит на прямой download
- cache.uc: download_subscription использует bootstrap DNS при прямом
  скачивании подписок (когда proxy недоступен или не настроен)
2026-08-10 18:10:36 +03:00
Dushnilin 6379361d40 chore: поднять версию до 1.2.67 2026-08-10 14:17:33 +03:00
Dushnilin 7def6e556f i18n: fix Russian-source translation keys in AmneziaWG .conf import
section.js had 10 _() calls with Russian strings as keys instead of English.
This is a i18n antipattern: source keys must be language-neutral (English).

Changes:
- section.js: replace 10 Russian msgids with English equivalents
  - 'Загрузить конфиг .conf' -> 'Load .conf config'
  - 'Импортировать настройки AmneziaWG из файла .conf' -> 'Import AmneziaWG settings from .conf file'
  - 'Загрузить .conf' -> 'Load .conf'
  - 'Ошибка' (3x) -> 'Error' (reuses existing key)
  - 'Выберите файл с расширением .conf' -> 'Select a file with .conf extension'
  - 'Не удалось разобрать файл:' -> 'Failed to parse file:'
  - 'Загружено!' -> 'Loaded!'
  - 'Готово' -> 'Done'
  - 'Конфиг AmneziaWG успешно загружен!' -> 'AmneziaWG config loaded successfully!'
  - 'Ошибка чтения' -> 'Read error'

- tachyon.ru.po: add RU translations for 9 new English keys
- calls.json / tachyon.pot / tachyon.po: regenerated via locales:actualize

Result: 1108/1108 translated (no orphaned Russian-source entries)
2026-08-10 14:00:35 +03:00
Dushnilin 92f1b4e991 i18n: complete RU translations — 1109/1109 (was 1030/1109)
Translated 79 missing strings:
- 15 country names (Belarus, China, Finland, France, Germany, Japan,
  Kazakhstan, Netherlands, Russia, Singapore, Sweden, Turkey,
  Ukraine, United Kingdom, United States)
- TUIC URL validation errors (14 strings)
- UI general: Cancel, Conflict, Error, Fixed, Issues, Success, etc.
- Protocol abbreviations kept as-is: DNS, HTTP, MTU, RDP, SSH, TLS
- Doctor/watchdog: 'Doctor failed', 'Doctor repair', 'No issues found'
- WARP: registration detour, proxy, skip TLS cert, country code
- Hosts file descriptions, URL validation message
- Monitoring & Analytics, Optimization, Protection sections
- Checking… and Generating… (Unicode ellipsis U+2026 variants)
- Russian-source keys: 'Ошибка', 'Не удалось разобрать файл:'

Distributed to luci-app-tachyon/po/ via npm run locales:actualize
2026-08-10 13:53:23 +03:00
Dushnilin 940bf6554c fix(i18n): синхронизация упакованного русского каталога с source-локалью 2026-08-09 22:37:36 +03:00
Dushnilin af2d07b056 fix(updates): установка пересобранных релизов в рамках одного тега
opkg считает пакет уже установленным при равенстве версий, поэтому
пересборка под тем же тегом молча не применялась: задание завершалось
успехом, билд оставался старым. Добавлен --force-reinstall в
pkg_install_files_command (opkg) и в install.sh; apk не тронут, он
всегда пишет переданный файл.

Детект пересборки больше не зависит только от SHA, которого нет в
релизах старше f974e4a0: добавлен отпечаток билда по published_at и
метаданным ipk-ассета, решение вынесено в tachyon_build_differs с
префиксным сравнением SHA разной длины. Отпечаток установленного
билда пишется в state-файл и попадает в extra.

Telegram уведомляет о пересборках: check_notified_updates пропускает
outdated_same_release, дедуп идёт по версии и SHA, текст показывает
короткие SHA вместо пары одинаковых версий.

Кэш проверки обновлений сохраняет current_sha из результата действия
вместо безусловного latest, иначе неудачная установка выглядела как
"актуально".

Фронт пересобран из TS, ручная правка main.js снята. Добавлен
describeSameReleaseBuild с фолбэк-текстом, когда SHA недоступен.
2026-08-09 16:57:10 +03:00
Dushnilin 8f3abe5e7b fix(fe): автозавершение ожидания для действия reinstall при переустановке 2026-08-09 15:40:54 +03:00
Dushnilin 676ee2041b fix: prerm stop-before-rt_tables, BusyBox awk, js-yaml vuln
- service/package.uc: call INIT_PATH stop before process-killing in
  prerm_cleanup so the routing table entry is still visible when the
  service shuts down (fixes test: 'prerm must stop Tachyon before
  removing its routing table name')
- service/package.uc: replace awk regex with | alternation and \/
  escaping with grep -E / grep -F; BusyBox awk does not support |
  in regex literals and silently mishandles \/ — fixes awk syntax
  errors in CI (both prerm_cleanup and postinst_restore)
- fe-app-tachyon: pin js-yaml to ^5.2.1 via overrides to fix the
  quadratic O(n^2) !!omap resolution DoS (same root cause as
  CVE-2026-59870 / GHSA-724g-mxrg-4qvm, never backported to 3.x/4.x)
- fe-app-tachyon: npm audit fix for brace-expansion and nanoid vulns
2026-08-09 12:34:58 +03:00
Dushnilin 3d84d96e49 feat(ui): display short commit SHA alongside release version across LuCI UI 2026-08-09 08:50:38 +03:00
Dushnilin d6860d8a15 fix(fe): исправить типизацию fetchHostnames и обновить бандл LuCI 2026-08-08 13:00:17 +03:00
Dushnilin 769598390d fix(ui): dynamic Sing-box repository globe link based on installed variant (shtorm-7/Leadaxe/SagerNet) 2026-08-06 22:07:38 +03:00
Dushnilin 89ae37ea4b fix(ci): synchronize PO catalogs, fix DNS action UI, state aggregate signature, and uci array parsing 2026-08-06 16:39:53 +03:00
Dushnilin 39b253bd66 fix(diagnostic): use serviceStatus for zapret/zapret2/byedpi outbound checks instead of Clash API latency probe 2026-08-06 15:00:19 +03:00
Dushnilin 7125e1a48e feat: карточки сервисов на дашборде + секция Hosts в правилах + скрытие вкладки Conditions для Hosts
Дашборд:
- Добавлены карточки статуса Zapret, Zapret2, ByeDpi на панель мониторинга
- Показывают статус (работает/остановлен), количество перезапусков, предупреждения
- Баг: API возвращает boolean а не число — исправлено сравнение

Секция Hosts:
- Перенесены опции hosts из глобальных настроек в отдельный тип секции (action=hosts)
- Опции: пользовательские DNS записи, удалённые списки хостов, автообновление, интервал
- Миграция: автоматический перенос глобальных настроек hosts в секцию
- Вкладка «Условия» скрыта для секций типа Hosts (hosts записи применяются глобально)
- Возвращена кнопка «Import Hosts File» с модальным окном загрузки из файла
- Убраны неиспользуемые опции из settings.js (~280 строк)

Локализация:
- Переведены 6 новых строк для превью импорта hosts
2026-08-06 14:16:18 +03:00
Dushnilin 4d4bdb16d0 fix: watchdog rpcd FD leak heal + updates show outdated_same_release
- watchdog: add ai_heal_rpcd() - monitors rpcd file descriptor count,
  restarts rpcd when FD count exceeds 512 (threshold of 1024 limit).
  Prevents LuCI from showing all services as 'stopped' due to FD exhaustion
  when rpcd can no longer fork to execute /usr/bin/tachyon commands.
  Runs on every watchdog health audit cycle (~15s).

- watchdog: move safe_reload_firewall() definition before ai_heal_nftables()
  and ai_heal_qos() to fix 'left-hand side is not a function' error.
  ucode does not hoist function declarations.

- updates: show Update button for outdated_same_release status (same version
  number but different commit SHA). Previously the button was hidden when
  current_version == latest_version even if SHAs differed.
2026-08-04 22:57:39 +03:00
Dushnilin ff627cfb52 fix: FD-cascade при reinstall + SHA версии в UI + тип outdated_same_release
- action.uc: killall logread перед restart_tachyon_after_successful_change,
  предотвращает FD-каскад при reinstall/update (orphan logread pipe FD)
- action.uc: current_sha/latest_sha в ответе check_update для Tachyon
- updates.uc: SHA пробрасывается через кэш проверки обновлений
- fe/types.ts: outdated_same_release добавлен в union статусов,
  поля current_sha/latest_sha в ComponentActionResult,
  AI Watchdog поля в ConfigSection (pre-existing TS2339 fix)
- fe/store.service.ts: outdated_same_release и SHA в состоянии updatesChecks
- fe/initController.ts: рендер SHA hash-badge для outdated_same_release,
  setCheckResult принимает SHA, applyCachedCheckResults/handleCheckResult обновлены
- fe/styles.ts: .sha-info — monospace badge для отображения коммит-хешей
2026-08-04 16:03:07 +03:00
Dushnilin a3de505a9a chore: switch zapret2 repo to Dushnilin/zapret2-openwrt 2026-08-04 14:04:29 +03:00
Dushnilin ea40ce1e93 fix: upgrade postcss 8.5.20 → 8.5.23 (GHSA-6g55-p6wh-862q)
Arbitrary .map file read via untrusted sourceMappingURL when from is
unset. Added npm overrides to force postcss@8.5.23 across all transitive
deps (tsup, vitest→vite).
2026-08-04 09:12:20 +03:00
Dushnilin 22a236e5d1 feat: commit-level version tracking for same-release updates
Backend:
- constants.uc: add TACHYON_COMMIT_SHA constant (placeholder __COMPILED_COMMIT_SHA__)
- build.sh: capture git rev-parse HEAD and sed-replace commit SHA placeholder
- Makefile: same commit SHA sed replacement for OpenWrt builds
- action.uc: modify check_tachyon() to compare installed commit SHA with
  target_commitish from GitHub release, new status 'outdated_same_release'
- action.uc: reuse release_json for both version and commit SHA extraction
- updater.uc: add release_commit_sha helper to extract target_commitish
- updates.uc: extend cacheable status to include outdated_same_release

Frontend:
- main.js: handle outdated_same_release status in renderComponentCard
- main.js: include outdated_same_release in shouldShowInstallAfterCheck
- main.js: include outdated_same_release in applyCachedCheckResults

i18n:
- Add 'Update is available for current release' and 'Update is available
  for current release:' to .pot and .ru.po files

78 tests pass.
2026-08-03 21:35:06 +03:00
Dushnilin 1e1f19d7b4 telegram bot: 12 новых фич + updates panel: кнопки GitHub репозиториев 2026-08-02 10:41:04 +03:00
Dushnilin 1c535dd1b9 fix: исправлены переводы описаний AI Watchdog в LuCI settings.js 2026-08-01 17:11:23 +03:00
Dushnilin 0a3ef0dff2 feat: AI Watchdog — 11 новых фич с полной настройкой из LuCI 2026-08-01 14:41:59 +03:00
Dushnilin 3752439895 Tachyon Doctor: новые проверки, авто-фиксы, расширенный AI Doctor 2026-08-01 09:24:44 +03:00
Dushnilin bc04794b73 feat: DoQ в UI + динамическая фильтрация DNS серверов по протоколу (UDP/DoT/DoH/DoQ) 2026-07-31 18:41:58 +03:00
Dushnilin ac1ff6bbb7 fix: кнопки активны после обновления + перевод Reinstall → Переустановить 2026-07-31 18:15:28 +03:00
Dushnilin ac209457d7 feat: кнопка Переустановить для Tachyon на странице обновлений 2026-07-31 17:34:11 +03:00
Dushnilin 448267335b feat: добавлена поддержка TUIC протокола и DNS over QUIC (DoQ) с ECH 2026-07-31 16:49:55 +03:00
Dushnilin 7757ceae6a feat: implement WebRTC Leak Protection and Strict DNS DoQ Enforcer 2026-07-30 21:43:56 +03:00
Dushnilin af620a2f45 fix: исправление резолвинга пакета zapret2 для роутеров и поиск релизов 2026-07-30 17:52:16 +03:00