Commit Graph
87 Commits
Author SHA1 Message Date
Dushnilin 7375e26b44 fix(qos): harmonize SQM and CAKE cooperation, resolve bufferbloat degradation 2026-09-14 17:03:45 +03:00
Dushnilin d72d3de706 fix(updates): hoist reload_singbox_after_list_update and persist compiled rulesets to /etc/tachyon/rulesets 2026-09-12 18:24:50 +03:00
Dushnilin 0bec2f6f86 fix: resolve -1ms latency display, diagnostic outbounds check timeout, country.is fallback, and docker AGH false positive
- Fix -1ms badge and green coloring in dashboard sections when node latency check fails or returns -1
- Handle Clash API group delay responses properly in dashboard single and batch latency tests
- Target active outbound node in diagnostics outbounds check instead of group tag to prevent router timeout
- Add nslookup fallback in country.uc resolve_service_host and retain system DNS resolution
- Ensure flag emoji country deduction acts as fallback in URLTest groups when exclude_countries is specified
- Ignore processes in container network namespaces when diagnosing system port 53 / DNS conflicts for AdGuardHome
- Bump fe-app-tachyon version to 1.3.25 and rebuild LuCI bundle
2026-09-11 23:53:41 +03:00
Dushnilin f987e88d23 fix(wan_monitor,dns): eliminate invalid regex group in resolve_domain and harden wan monitor locking
- Replace invalid POSIX non-capturing group in diagnostics/runtime.uc with standard POSIX ERE pattern.
- Harden 99-tachyon-wan-monitor with stale PID directory lock cleanup and dynamic badwan_reload_delay support.
- Make is_cloudflare_shared_cidr in core/ip.uc case-insensitive.
- Add default wan to badwan_monitored_interfaces in settings.js.
2026-09-11 23:16:22 +03:00
Dushnilin 0ea1c73832 fix: sanitize Discord community subnets and resolve WAN monitor hotplug spam (fixes #50, #51)
- Fix #50: Discord community subnets hijacking Cloudflare Anycast traffic:
  * Filter broad Cloudflare shared subnets (104.16.0.0/12, 172.64.0.0/13, etc.) for Discord preset in generator_routes.uc, nft/apply.uc, and updates.uc.
  * Add tachyon resolve_domain CLI and runtime.uc helper for DNS queries with rpcd ACL support.
  * Update LuCI Routing Rule Tracer to resolve queried domains against section subnets/CIDRs (including community subnets) and show shared CDN/Anycast warnings.
  * Add unit tests in tests/community_subnets_sanitization.sh.

- Fix #51: Telegram bot spamming WAN up/down notifications on hotplug:
  * Check enable_badwan_interface_monitoring, telegram.enabled, and badwan_monitored_interfaces list in 99-tachyon-wan-monitor.
  * Add background debounce with atomic directory locking and ubus interface status verification.
  * Implement state transition tracking to only notify on actual UP->DOWN and DOWN->UP changes without duplicates.
  * Preserve retry_start_on_wan_up behavior on ifup.
  * Add comprehensive integration test suite in tests/wan_monitor_hotplug.sh.
2026-09-11 23:07:10 +03:00
Dushnilin 94708d8251 fix: resolve MAC routing crash in sing-box, fallback dashboard on secondary nodes, and unify dashboard naming 2026-09-11 20:34:18 +03:00
Dushnilin 26431f50d3 feat: per-section MAC/DNS exclusions, boot latency sweep, WDTT/OlcRTC providers, DNS hijack socket collision fix
Features:
- Per-Section MAC Exclusions: nft, generator_routes, section.js, i18n
- Per-Section Routed DNS: connections, generator_routes, nft, validator,
  types.ts, section.js, state.uc, reload.uc
- Boot Latency Sweep: ui.uc latency boot sweep with fixture dispatchers
- WDTT provider: full backend (common, validator, runtime), sing-box
  outbound, diagnostics, component install, updater, i18n, section.js UI
- OlcRTC provider: full backend (common, validator, runtime), sing-box
  outbound, diagnostics, component install, updater, i18n, section.js UI
- WireGuard-over-TURN tunnel (WDTT) and TCP-over-WebRTC tunnel (OlcRTC)
  as sidecar processes with local SOCKS5, routed through sing-box outbound

Bug fixes:
- route.uc: restrict hijack-dns to local DNS inbounds only (dns-in,
  source-dns-in, dns-health-*) — fixes socket collision between sing-box
  and dnsmasq on port 53 via SO_REUSEADDR transparent write-back sockets
- runtime.uc: add Port 53 socket collision diagnostic with auto-fix
  (sing-box restart to clear parasitic UNCONN sockets with Recv-Q)
- runtime.uc: add dnsmasq dns_redirect check with auto-fix — disables
  firewall4 DNAT that causes TProxy to rewrite destination to router :53
- failover.uc: add wdtt/olcrtc to failover candidate actions
- telegram.uc: show WDTT/OlcRTC installed status in /info

Tests: 135/155 shell + 591/591 frontend
2026-09-11 18:04:03 +03:00
Dushnilin a254cfc8b6 fix(components): robust version installation and updates across Docker, APK v3 and OPKG
- fix(updater): support single release JSON object for specific tag queries and unblock prereleases on explicit selection
- fix(action): replace wget --header with -U for uclient-fetch compatibility on OpenWrt 23.05
- fix(action): make package list updates best-effort to prevent failures on snapshot kmod feeds
- fix(action): add offline/corrupt extract fallbacks (apk extract and opkg data.tar.gz) for kernel dependency mismatch
- fix(action): ensure /var/lock and /tmp/run directories exist before opkg/procd operations
- fix(action): fix fallback asset URL pattern for remittor zapret releases
- fix(packages): add binary presence and --version detection fallbacks for zapret, zapret2, byedpi, sing-box
- fix(byedpi): support direct apk list parsing for installed package version
- fix(state): include schedule, profile, and guest_mode in reload state signatures
- fix(imports): fix missing command_status_from_args, write_json, and remove_file imports
- fix(updates): extract meaningful ucode errors and strip trailing caret lines
2026-09-10 19:38:26 +03:00
Dushnilin 0f6561ad57 fix(migration,dns,ui): restore domain suffix matching, fix comma split, bypass AdGuardHome on 53, and support AWG detours 2026-09-10 09:43:00 +03:00
Dushnilin 142fff6b4a fix: zapret2 strategy args, snapshot restore output leak, and opkg update lock handling
- providers/zapret2/common.uc: import core.common and declare as_string helper to resolve type error during zapret2 strategy argument preparation.
- service/snapshot.uc: redirect command output to /dev/null in command_success_from_args to prevent stdout leakage breaking LuCI JSON parsing on snapshot restore.
- settings.js: robustly parse JSON from snapshot command output using regex delimiter.
- components/action.uc: add --force-depends to opkg install arguments, detect opkg lock contention and retry with backoff, and log non-zero exit stdout as warning.
- providers/nfqueue/runtime.uc: ensure standalone services are cleanly stopped and disabled before starting Tachyon-managed runtime.
- section.js, generator_routes.uc, apply.uc: add community_subnets option to conditionally include community CIDRs in routing and nftables.
2026-09-09 11:55:12 +03:00
Dushnilin 394c717bf9 fix(diagnostics): prevent sing-box listening ports check failure when IPv6 is disabled 2026-09-07 17:27:29 +03:00
Dushnilin e8c1d9d382 feat: стабильность подписок, порог DNS failover, прямой порт прокси и TorrServer Direct
- subscription: детерминированная сортировка аутбаундов при расчете сигнатуры кэша (защита от перезапусков при shuffle)
- dns: порог последовательных ошибок dns_failover_failure_threshold (защита от флаппинга)
- singbox: выделенный direct_bypass inbound (mixed port 2080) для прямого выхода устройств в обход TPROXY
- torrserver: автоматический bypass cgroups v2 services/torrserver прямо в WAN
- zapret: нормализация устаревших параметров conntrack --ctrack-timeouts
- ui: интеграция управления службами TorrServer Direct и Direct Proxy в LuCI
- tests: новые тесты subscription_order_independence и direct_bypass_torrserver
2026-09-06 21:19:42 +03:00
Dushnilin 547d4aa6ba fix(cli): защита аргументов ucode от перестановок опций GNU getopt
- Добавлен разделитель '--' перед модулем в run_spec (/usr/bin/tachyon) и module_args (diagnostics/runtime.uc), чтобы аргументы стратегий не интерпретировались как флаги ucode
- В tests/cli_entrypoint.sh передан безопасный аргумент strategy_dummy
2026-09-06 09:44:00 +03:00
Dushnilin e9cf4744f3 fix(byedpi): исправление валидации стратегий ByeDPI и сохранение в веб-интерфейсе LuCI
- Зарегистрирована команда validate_byedpi_strategy_json в command_spec CLI (/usr/bin/tachyon)
- Добавлена функция validate_byedpi_strategy_json и режим validate-byedpi-strategy-json в diagnostics/runtime.uc с вызовом providers/byedpi/validator.uc
- Исправлена ошибка 'Unexpected token U' в LuCI, из-за которой отменялось сохранение стратегии ByeDPI в UCI и сбрасывалось на дефолтное значение
- Добавлены тесты CLI-валидации стратегий в tests/byedpi_validator.sh
2026-09-06 09:33:02 +03:00
Dushnilin 11925e7ec5 fix(updates): resolve tag commit SHA and format build fingerprints; fix telegram, watchdog and logs 2026-09-05 23:52:16 +03:00
Dushnilin dbe6eb013c fix(perf): eliminate 50k hosts DNS rules CPU lockup, optimize UI polling & memory limits 2026-09-05 00:14:51 +03:00
Dushnilin 4cd96902b5 fix: component version picker persistence & installation, dashboard render performance (1.3.20) 2026-09-04 22:44:24 +03:00
Dushnilin 0cfc351d5a fix: restore zapret2 worker startup, fast doctor check, and dnsmasq sync (1.3.20) 2026-09-04 16:47:08 +03:00
Dushnilin e901f9d41a fix: zapret2 startup, dnsmasq fakeip rebind protection, dns detour routes (1.3.19) 2026-09-04 13:56:48 +03:00
Dushnilin b3358f77a3 fix(stability): optimize Go memory tiers, prevent nftables degradation deadlock, harden NTP & process supervision
- singbox/runtime.uc: add dynamic 4-tier GOMEMLIMIT and GOGC limits based on RAM, enforce /etc/tachyon/mem_scale, and install managed init script across all binary variants
- service/event_controller.uc: guard probe_nftables() with recovery_bypass and native_internet_restored checks to prevent 5-minute network drop deadlock
- service/watchdog.uc: reduce Telegram worker heartbeat timeout from 900s to 300s and add nslookup fallback to Zero-RTT prefetcher
- diagnostics/runtime.uc & service/lifecycle.uc: use direct-IP NTP pool to eliminate circular DNS/TLS deadlocks, and step clock forward on cold boot if RTC desynced
- service/failover.uc & diagnostics/runtime.uc: flush conntrack states on proxy group switch so client connections immediately migrate
2026-09-03 06:13:30 +03:00
Dushnilin c432220af5 feat(updates): добавить локальный бэкап и оффлайн-откат компонентов 2026-09-01 12:24:58 +03:00
Dushnilin 706b35328c feat(ruleset): auto-assign download_detour for remote rulesets & add watchdog self-heal for ruleset DNS stalls 2026-08-30 21:22:23 +03:00
Dushnilin dfb32722bf release: 1.3.8 - OpenWrt network interfaces for WARP generator, DoH doctor URL normalization & doctor lock fixes 2026-08-30 20:05:16 +03:00
Dushnilin 16ffc9f91f fix(diagnostics): check both ca-certificates.crt and ca-bundle.crt paths
On apk-based OpenWrt the file is ca-certificates.crt, not ca-bundle.crt.
Check both paths so the CA bundle detection works on opkg and apk.
2026-08-28 10:41:32 +03:00
Dushnilin 1a314147a9 fix(ai-doctor): debug-логирование LLM запросов + HTTP-Referer для OpenRouter
- Добавлен warn-вывод при ошибках LLM: статус curl,/raw response, отсутствие
  choices — теперь видно в logread почему AI Chat молча отдаёт оффлайн
- Добавлены HTTP-Referer и X-Title заголовки для OpenRouter (рекомендация
  провайдера для rate-limit ranking)
2026-08-27 17:54:27 +03:00
Dushnilin 2c6a1a7343 feat(tailscale): watchdog нативного режима и панель пиров тейлнета
- watchdog: проверка native-секции в slow-тире, авторестарт демона после 2 сбоев, TG-алерт раз в час
- AI Doctor: узел Tailscale (готов/не установлен/упал) только при настроенном native
- провайдер: режим peers — парсинг status --json через per-section socket
- RPC get_tailscale_status/get_tailscale_peers/tailscale_restart
- дашборд: карточка Tailscale (состояние, IP роутера, до 5 пиров с онлайн-статусом)
2026-08-26 13:43:23 +03:00
Dushnilin 7f0b085a07 feat(tailscale): нативный режим tailscaled и компонент Tailscale
- новый компонент Tailscale: установка пакета из фида, карточка в Обновлениях
- режим native для секций Tailscale: системный tailscaled вместо sing-box endpoint
- доступ к тейлнету с LAN без клиента: маршруты 100.64.0.0/10 и MagicDNS через dnsmasq
- masquerade и exit-node (opt-in) с обходом tproxy по зарезервированной маске
- validator: требование tailscaled и auth-key для native; bypass-правила в mangle
- тесты: генерация конфига, смоук рантайма с моками, обновлена сигнатура состояния
2026-08-26 11:30:52 +03:00
Dushnilin 77e8cdaad0 feat: AI доктор — 5 багфиксов + Telegram кнопка
Багфиксы:
- rag.uc: исправлен порядок аргументов push() — RAG-эмбеддинги снова строятся
- fix_uci_config: правильный путь бэкапа (/etc/backup/tachyon_config + fallback)
- apply_quick_fix: честные exit codes для всех 23 фиксов
- doctor(): прокидывается busy flag в JSON-вывод
- diagnose_json: строится из checks[] вместо парсинга эмодзи из текста

UI:
- Кнопка Telegram канал (https://t.me/tachyon_proxy) на странице диагностики

Тесты:
- 5 новых проверок в ai_doctor_local.sh (uci_backup, exit codes, busy, structured checks, rag push)
2026-08-25 21:37:15 +03:00
Dushnilin c3172dd82d refactor: remove hardcoded port 4534 — dynamic port from config
- Added get_mixed_port() to core/common.uc (reads sing-box config.json)
- agent_api.uc, api.uc: use common.get_mixed_port()
- warp_generator.uc: use config port instead of hardcoded fallback
- watchdog.uc: use mixed_ports_from_config() for Clash API calls
- runtime.uc: dynamic port in conflict checks and proxy probe
2026-08-25 15:46:03 +03:00
Dushnilin 0241e1898f feat(doctor): честный вердикт по мёртвым WireGuard/AWG-туннелям
Жалобы вида «AWG не работает» (#39, #42) почти всегда означают: конфиг
секции применён корректно, но пир не отвечает (сервер лежит, провайдер
режет UDP до эндпоинта). Раньше доктор об этом молчал, и виноватым
выглядел Tachyon.

Новый чек 6c сканирует свежий лог ядра на ошибки outbound/wireguard
(operation timed out / handshake timeout): при свидетельствах мёртвого
туннеля - явный вердикт «проблема вне Tachyon» с подсказкой проверить
сервер и UDP-порт у провайдера. Если wireguard-трафика в логе нет вовсе,
чек не выдаёт ни одной строки - без шума для пользователей без AWG.
2026-08-22 10:46:36 +03:00
Dushnilin ca21eb2202 feat(doctor): новые проверки и журнал исходов диагностики
Пять проверок, которых раньше не было, все read-only:

- место на диске: /tmp и overlay при >=90% молча ломают запись кэша,
  загрузку подписок и коммиты конфигов
- системные часы: неверный год валит все TLS-соединения (DoH, подписки,
  LLM API) после холодной загрузки без NTP
- наличие ca-bundle: HTTPS-проверки падают с SSL-ошибками без пакета;
  код уже ссылался на него в вердиктах, но не проверял
- конфликты порта 53: другой DNS-демон на :53 конкурирует с dnsmasq и даёт
  плавающие сбои резолвинга
- возраст кэша подписки: sing-box может гонять трафик через списки узлов
  многодневной давности, хотя сам URL подписки доступен

Плюс журнал исходов (/tmp/tachyon_doctor_history.json, максимум 50 записей):
повторные сбои за 24 часа помечаются как повторяющиеся, а не как уникальный
инцидент.
2026-08-21 19:24:20 +03:00
Dushnilin 7d222fbfe1 feat(doctor): диагностика в dry-run по умолчанию, ремонты по явному запросу
Доктор мутировал систему при каждом диагностическом запуске: отключал
rebind protection dnsmasq, делал kill -9 процессу на портах 4534/9090,
стирал syslog во время OOM-аудита и подменял resolv.conf на 1.1.1.1 как
побочный эффект "проверки".

- run_doctor_checks() теперь только диагностирует в dry-run: каждая мутация
  идёт через обёртки doc_set/doc_commit/doc_run/doc_unlink, которые
  записывают планируемое действие и сообщают "WILL FIX (doctor --fix)";
  ремонты выполняются только через "tachyon doctor --fix" или repair=true
- recovery-проверки (сервис остановлен) следуют тому же правилу
- параллельные запуски доктора из LuCI, Telegram и cron сериализуются
  mkdir-локом со взятием устаревшего лока через 15 минут тишины
- трекер применённых фиксов пишется атомарно (tmp+mv)
- OOM-проверка больше не стирает logread (это форензика) и атрибутирует
  kill именно sing-box
- ai_doctor прогонял весь набор проверок дважды (внутри local_rule_doctor и
  напрямую); результаты считаются один раз и переиспользуются
- curl к LLM/Clash/подпискам получили connect + total таймауты, зависший
  эндпоинт больше не подвешивает доктора
2026-08-21 19:20:05 +03:00
Dushnilin 421a4fd796 feat: add RAG (Retrieval-Augmented Generation) for AI Doctor
New files:
- tools/rag_build_index.sh: build-time ingestion pipeline
  Chunks docs/knowledge-base/*.md into 2000-char chunks with 200-char overlap
  Produces rag_index.json (39 chunks, ~74KB) for runtime embedding
- tachyon/files/usr/lib/diagnostics/rag.uc: runtime RAG module
  Embeds chunks via same LLM provider API (OpenAI-compatible /v1/embeddings)
  Cosine similarity search, top-3 retrieval, 24h cache in /tmp
  Graceful fallback if embedding API unavailable
- tachyon/files/usr/lib/tachyon/rag_index.json: pre-built chunk index

Modified files:
- runtime.uc: integrated RAG into ai_doctor() function
  Retrieves relevant docs based on user query or diagnostic context
  Injects 'Relevant Documentation' section into LLM prompt
- renderAdvancedSettings.ts: added 'Enable RAG' toggle in AI Doctor settings
- tachyon config: added enable_rag option (default '1')
- build.sh: added rag_build_index.sh step

Architecture:
- Provider-agnostic: uses same API key/provider as LLM for embeddings
- Embedding model: text-embedding-3-small (OpenAI), nomic-embed-text (Ollama),
  local-model (LMStudio), deepseek-embedding (DeepSeek)
- Cache: embeddings cached in /tmp/tachyon_rag_embeddings.json (24h TTL)
- Fallback: if embedding fails, AI Doctor works without RAG (as before)
- 39 chunks from 14 docs, ~66K chars, cosine search <1ms

623 tests pass (101 backend + 522 frontend)
2026-08-20 10:27:56 +03:00
Dushnilin 1137e96b0d de-AI phase 3: inline redundant variables and null checks
TypeScript:
- getDashboardSections.ts: value === undefined || value === null -> value == null
- renderAdvancedSettings.ts: remove redundant Boolean() on boolean

ucode (10 inlined variables):
- helpers.uc: inline trailing_dot
- runtime.uc: inline ping_ok, enable_watchdog
- nft/apply.uc: inline rtmtu_ok, qos_enabled
- byedpi/runtime.uc: inline matched
- api.uc: inline deleted, added
- subscription.uc: inline has_source_markers
- watchdog.uc: inline is_healthy

522 frontend tests pass
2026-08-19 22:38:26 +03:00
Dushnilin 4094a41b5d de-AI: remove AI comments and boolean theater across TypeScript + ucode 2026-08-19 18:15:35 +03:00
Dushnilin 0964b79171 fix(ai-chat): fix AI Chat and Assistant to work with LM Studio
- Fix response parsing: check report field, not just message
- Pass user query text to LLM instead of ignoring it
- Append user question to diagnostic prompt with system context
- Increase timeout to 120s for LM Studio responses
- Add command_status_from_args to core/common.uc exports

Closes #38
2026-08-19 15:57:42 +03:00
Dushnilin c35380200f fix(tailscale, ai): исправить скрытие полей Tailscale-сервера и добавить готовый пресет провайдера OpenRouter 2026-08-17 11:18:36 +03:00
Dushnilin 528bc7b9db feat(doctor): расширенная офлайн-диагностика (NTP, conntrack, deadlock, MTU) и аварийный возврат интернета 2026-08-15 17:18:23 +03:00
Dushnilin 4dd882f276 fix(core): объявление default_gateway_exists до wan_has_ip и видимость URLTest по умолчанию 2026-08-15 16:06:22 +03:00
Dushnilin e02e9169d4 fix(core): исправление forward-reference в AI Doctor и фильтрации селектора 2026-08-15 16:02:31 +03:00
Dushnilin 85ae733787 feat(doctor): расширенная локальная диагностика DPI, нод, конфликтов и фикс зависимостей CI 2026-08-15 15:58:40 +03:00
Dushnilin d81d9fd077 fix(ci): fix forward function declaration in runtime.uc and harden tests for multi-call coreutils/alpine 2026-08-15 12:28:49 +03:00
Dushnilin e0828eb53a fix(diagnostics): fix false-positive sing-box DNS check on busybox nslookup and auto-fetch LAN clients in support report 2026-08-15 12:12:59 +03:00
Dushnilin 6fdf24723e fix(diagnostics): use core.uci for WAN interface detection instead of shell uci 2026-08-15 10:58:20 +03:00
Dushnilin 57c04c71e8 feat(doctor): add 1-click anonymized support report and LAN device inspector 2026-08-15 10:05:09 +03:00
Dushnilin c8d02a917e Улучшение ИИ-Доктора: экспертная скриптовая система диагностики и самовосстановления 2026-08-15 09:48:40 +03:00
Dushnilin b9c0f72518 fix(doctor): вернуть require core.common и порядок функций в runtime.uc 2026-08-14 17:30:39 +03:00
Dushnilin 455c67c0a7 fix(diagnostic): install servicecheck_profiles.json + guard doctor/ai_doctor (#33)
Makefile was missing the install rule for servicecheck_profiles.json — the community service probe profiles were never copied to /usr/share/tachyon/ on the router, so Service Health Check had zero targets to probe and showed an empty modal.
2026-08-14 16:06:48 +03:00
Dushnilin 7bd373c392 fix(diagnostics): убрать крокозябры в Глобальной проверке и разорвать цикл повторных фиксов AI Doctor (issue #31) 2026-08-14 09:31:31 +03:00
Dushnilin b099b26a68 feat(doctor): режим восстановления при остановленном сервисе и реальная верификация AI Doctor 2026-08-13 21:59:54 +03:00