diff --git a/README.md b/README.md
index e78828f85..8b7fa44cb 100644
--- a/README.md
+++ b/README.md
@@ -367,9 +367,9 @@ You can run the Termix server on a VPS instead of inside your own network. If Te
## Telemetry
-Termix sends a small anonymous ping once a day so I can see how many instances are running and which features get used. It contains a random instance ID, how many users and hosts you have, the app version, and which features (terminal, file manager, tunnels, docker, etc.) were used in the last 24 hours. It never contains usernames, hostnames, IP addresses, credentials, or anything else that identifies you or your servers.
+Termix sends a small anonymous report once a day so I can see how many instances are running and which features get used. It contains a random instance ID, the app version, and how many users and hosts you have. It can also include your platform (OS, architecture, Node.js version, database type, and whether you run Docker, the desktop app or a plain server), how often each kind of tab was opened and how many SSH logins happened, and which built-in features are running. It never contains usernames, hostnames, IP addresses, credentials, or anything else that identifies you or your servers.
-It is on by default. Turn it off in Admin Settings under General, or set `ENABLE_TELEMETRY=false` before you ever start Termix.
+It is on by default. Turn it off, or choose what it includes, in Admin Settings under Usage Statistics, where you can also preview the exact report. Each user can leave out their own feature usage in their profile. Setting `ENABLE_TELEMETRY=false` turns it off and locks the switch.
diff --git a/docker/Dockerfile b/docker/Dockerfile
index 03b9df7a4..a91347d93 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -114,8 +114,7 @@ ENV DATA_DIR=/app/data \
OPKSSH_SHA256_AMD64=$OPKSSH_SHA256_AMD64 \
OPKSSH_SHA256_ARM64=$OPKSSH_SHA256_ARM64 \
PORT=8080 \
- NODE_ENV=production \
- POSTHOG_API_KEY=phc_xM8UznirsFxUkGE68gH4jzeqevf4kh76wGw7Ci7hH2dd
+ NODE_ENV=production
RUN apt-get update && apt-get install -y nginx gettext-base openssl ca-certificates gosu wget && \
update-ca-certificates && \
diff --git a/docker/bundled-plugins.json b/docker/bundled-plugins.json
index f30efb015..2728154af 100644
--- a/docker/bundled-plugins.json
+++ b/docker/bundled-plugins.json
@@ -92,6 +92,10 @@
"id": "tailscale",
"source": "workspace"
},
+ {
+ "id": "telemetry",
+ "source": "workspace"
+ },
{
"id": "termix-identity",
"source": "workspace"
diff --git a/docs/readme/README-AR.md b/docs/readme/README-AR.md
index dc65b8bc3..50dd79058 100644
--- a/docs/readme/README-AR.md
+++ b/docs/readme/README-AR.md
@@ -372,9 +372,9 @@ termix ssh 1
## بيانات الاستخدام
-يرسل Termix إشارة صغيرة مجهولة مرة واحدة يوميًا، لأعرف عدد النسخ العاملة والميزات المستخدمة فعلًا. تحتوي على معرّف عشوائي للنسخة، وعدد المستخدمين والمضيفات لديك، وإصدار التطبيق، والميزات التي استُخدمت خلال آخر 24 ساعة (الطرفية ومدير الملفات والأنفاق وdocker وغيرها). ولا تحتوي أبدًا على أسماء مستخدمين أو أسماء مضيفات أو عناوين IP أو بيانات دخول أو أي شيء يعرّف بك أو بخوادمك.
+يرسل Termix تقريرًا صغيرًا مجهول الهوية مرة واحدة يوميًا حتى أعرف عدد النسخ العاملة والميزات المستخدمة. يحتوي على معرّف عشوائي للنسخة، وإصدار التطبيق، وعدد المستخدمين والأجهزة لديك. ويمكن أن يتضمن أيضًا منصتك (نظام التشغيل، والمعمارية، وإصدار Node.js، ونوع قاعدة البيانات، وهل تستخدم Docker أو تطبيق سطح المكتب أو خادمًا عاديًا)، وعدد مرات فتح كل نوع من التبويبات وعدد عمليات تسجيل الدخول عبر SSH، والميزات المدمجة التي تعمل. لا يحتوي أبدًا على أسماء المستخدمين أو أسماء الأجهزة أو عناوين IP أو بيانات الدخول أو أي شيء آخر يعرّف بك أو بخوادمك.
-وهي مفعّلة افتراضيًا. يمكنك إيقافها من إعدادات المسؤول ضمن قسم عام، أو ضبط `ENABLE_TELEMETRY=false` قبل تشغيل Termix أصلًا.
+وهي مفعّلة افتراضيًا. يمكنك إيقافها أو اختيار ما تتضمنه من إعدادات المسؤول ضمن قسم Usage Statistics، وهناك يمكنك أيضًا معاينة التقرير كما سيُرسل تمامًا. ويمكن لكل مستخدم استبعاد استخدامه الشخصي للميزات من ملفه الشخصي. ضبط `ENABLE_TELEMETRY=false` يوقفها ويقفل المفتاح.
diff --git a/docs/readme/README-CN.md b/docs/readme/README-CN.md
index 0a70d4fcb..4a2f33d70 100644
--- a/docs/readme/README-CN.md
+++ b/docs/readme/README-CN.md
@@ -366,9 +366,9 @@ termix ssh 1
## 遥测
-Termix 每天会发送一次匿名的小型统计信息,让我了解有多少实例在运行、哪些功能被用到。内容包括一个随机的实例 ID、你有多少用户和主机、应用版本,以及过去 24 小时内使用了哪些功能(终端、文件管理器、隧道、Docker 等)。它绝不包含用户名、主机名、IP 地址、凭据,或任何能识别你和你服务器的信息。
+Termix 每天会发送一次匿名的小型报告,让我知道有多少实例在运行、哪些功能被使用。报告包含一个随机的实例 ID、应用版本,以及你的用户数和主机数。它还可以包含你的平台信息(操作系统、架构、Node.js 版本、数据库类型,以及你是用 Docker、桌面应用还是普通服务器运行)、每种标签页被打开的次数和 SSH 登录次数,以及正在运行的内置功能。它绝不会包含用户名、主机名、IP 地址、凭据或任何能识别你或你的服务器的信息。
-该功能默认开启。你可以在管理设置的"通用"中关闭它,或者在启动 Termix 之前设置 `ENABLE_TELEMETRY=false`。
+该功能默认开启。你可以在管理设置的"Usage Statistics"中关闭它或选择要包含的内容,还可以在那里预览将要发送的完整报告。每个用户都可以在个人资料中排除自己的功能使用数据。设置 `ENABLE_TELEMETRY=false` 会关闭它并锁定开关。
diff --git a/docs/readme/README-DE.md b/docs/readme/README-DE.md
index 54b03d9f2..1155c9a4b 100644
--- a/docs/readme/README-DE.md
+++ b/docs/readme/README-DE.md
@@ -367,9 +367,9 @@ Du kannst den Termix-Server auf einem VPS laufen lassen statt im eigenen Netz. L
## Telemetrie
-Termix schickt einmal am Tag ein kleines anonymes Signal, damit ich sehen kann, wie viele Instanzen laufen und welche Funktionen genutzt werden. Enthalten sind eine zufällige Instanz-ID, wie viele Benutzer und Hosts du hast, die App-Version und welche Funktionen (Terminal, Dateimanager, Tunnel, Docker usw.) in den letzten 24 Stunden benutzt wurden. Niemals enthalten sind Benutzernamen, Hostnamen, IP-Adressen, Zugangsdaten oder irgendetwas anderes, das dich oder deine Server identifiziert.
+Termix schickt einmal am Tag einen kleinen anonymen Bericht, damit ich sehe, wie viele Instanzen laufen und welche Funktionen genutzt werden. Er enthält eine zufällige Instanz-ID, die App-Version und wie viele Benutzer und Hosts du hast. Er kann außerdem deine Plattform enthalten (Betriebssystem, Architektur, Node.js-Version, Datenbanktyp und ob du Docker, die Desktop-App oder einen normalen Server nutzt), wie oft jede Art von Tab geöffnet wurde und wie viele SSH-Logins es gab, sowie welche eingebauten Funktionen laufen. Er enthält nie Benutzernamen, Hostnamen, IP-Adressen, Zugangsdaten oder sonst etwas, das dich oder deine Server erkennbar macht.
-Es ist standardmäßig an. Schalte es in den Administrationseinstellungen unter Allgemein aus oder setze `ENABLE_TELEMETRY=false`, bevor du Termix überhaupt startest.
+Es ist standardmäßig an. Schalte es in den Administrationseinstellungen unter Usage Statistics aus oder wähle dort, was gesendet wird. Dort kannst du dir auch den genauen Bericht vorab ansehen. Jeder Benutzer kann seine eigene Funktionsnutzung in seinem Profil ausschließen. `ENABLE_TELEMETRY=false` schaltet es aus und sperrt den Schalter.
diff --git a/docs/readme/README-ES.md b/docs/readme/README-ES.md
index 7ebe5b5cc..d59a642f6 100644
--- a/docs/readme/README-ES.md
+++ b/docs/readme/README-ES.md
@@ -367,9 +367,9 @@ Puedes ejecutar el servidor de Termix en un VPS en lugar de dentro de tu propia
## Telemetría
-Termix envía una vez al día un pequeño aviso anónimo para que pueda ver cuántas instancias hay funcionando y qué funciones se usan. Contiene un identificador de instancia aleatorio, cuántos usuarios y hosts tienes, la versión de la aplicación y qué funciones (terminal, gestor de archivos, túneles, docker, etc.) se han usado en las últimas 24 horas. Nunca contiene nombres de usuario, nombres de host, direcciones IP, credenciales ni nada que te identifique a ti o a tus servidores.
+Termix envía una vez al día un pequeño informe anónimo para que pueda ver cuántas instancias hay funcionando y qué funciones se usan. Incluye un ID de instancia aleatorio, la versión de la app y cuántos usuarios y hosts tienes. También puede incluir tu plataforma (sistema operativo, arquitectura, versión de Node.js, tipo de base de datos y si usas Docker, la app de escritorio o un servidor normal), cuántas veces se abrió cada tipo de pestaña y cuántos inicios de sesión SSH hubo, y qué funciones integradas están activas. Nunca incluye nombres de usuario, nombres de host, direcciones IP, credenciales ni nada que te identifique a ti o a tus servidores.
-Viene activado. Puedes desactivarlo en los ajustes de administración, en General, o poner `ENABLE_TELEMETRY=false` antes incluso de arrancar Termix.
+Viene activado. Puedes desactivarlo o elegir qué incluye en los ajustes de administración, en Usage Statistics, donde también puedes ver el informe exacto antes de enviarlo. Cada usuario puede excluir su propio uso de funciones desde su perfil. Poner `ENABLE_TELEMETRY=false` lo desactiva y bloquea el interruptor.
diff --git a/docs/readme/README-FR.md b/docs/readme/README-FR.md
index 0f45d9057..f99b2997e 100644
--- a/docs/readme/README-FR.md
+++ b/docs/readme/README-FR.md
@@ -365,9 +365,9 @@ Vous pouvez faire tourner le serveur Termix sur un VPS plutôt que dans votre pr
## Télémétrie
-Termix envoie une fois par jour un petit signal anonyme, pour que je puisse voir combien d'instances tournent et quelles fonctionnalités servent vraiment. Il contient un identifiant d'instance aléatoire, le nombre d'utilisateurs et d'hôtes, la version de l'application et les fonctionnalités utilisées ces dernières 24 heures (terminal, gestionnaire de fichiers, tunnels, docker, etc.). Il ne contient jamais de noms d'utilisateur, de noms d'hôtes, d'adresses IP, d'identifiants ni quoi que ce soit qui puisse vous identifier, vous ou vos serveurs.
+Termix envoie une fois par jour un petit rapport anonyme, pour que je puisse voir combien d'instances tournent et quelles fonctionnalités sont utilisées. Il contient un identifiant d'instance aléatoire, la version de l'application et le nombre d'utilisateurs et d'hôtes. Il peut aussi inclure votre plateforme (système, architecture, version de Node.js, type de base de données, et si vous utilisez Docker, l'application de bureau ou un simple serveur), combien de fois chaque type d'onglet a été ouvert et combien de connexions SSH ont eu lieu, ainsi que les fonctionnalités intégrées actives. Il ne contient jamais de noms d'utilisateur, de noms d'hôte, d'adresses IP, d'identifiants ni quoi que ce soit qui permette de vous identifier, vous ou vos serveurs.
-C'est activé par défaut. Désactivez-le dans les paramètres d'administration, section Général, ou définissez `ENABLE_TELEMETRY=false` avant même de démarrer Termix.
+C'est activé par défaut. Désactivez-le ou choisissez ce qu'il contient dans les paramètres d'administration, section Usage Statistics, où vous pouvez aussi voir le rapport exact avant l'envoi. Chaque utilisateur peut exclure sa propre utilisation dans son profil. Définir `ENABLE_TELEMETRY=false` le désactive et verrouille l'interrupteur.
diff --git a/docs/readme/README-HI.md b/docs/readme/README-HI.md
index beb832bb1..aea110a31 100644
--- a/docs/readme/README-HI.md
+++ b/docs/readme/README-HI.md
@@ -372,9 +372,9 @@ termix ssh 1
## टेलीमेट्री
-Termix दिन में एक बार एक छोटा सा गुमनाम संकेत भेजता है, ताकि मुझे पता चले कि कितने इंस्टेंस चल रहे हैं और कौन सी सुविधाएँ सच में इस्तेमाल होती हैं। इसमें एक बेतरतीब इंस्टेंस आईडी, आपके पास कितने उपयोगकर्ता और होस्ट हैं, ऐप का संस्करण, और पिछले 24 घंटे में इस्तेमाल हुई सुविधाएँ (टर्मिनल, फ़ाइल मैनेजर, टनल, docker आदि) होती हैं। इसमें कभी भी उपयोगकर्ता नाम, होस्ट नाम, IP पते, क्रेडेंशियल या ऐसी कोई चीज़ नहीं होती जो आपकी या आपके सर्वर की पहचान बताए।
+Termix दिन में एक बार एक छोटी गुमनाम रिपोर्ट भेजता है ताकि मैं देख सकूं कि कितने इंस्टेंस चल रहे हैं और कौन से फ़ीचर इस्तेमाल हो रहे हैं। इसमें एक रैंडम इंस्टेंस ID, ऐप का वर्शन, और आपके यूज़र्स और होस्ट्स की संख्या होती है। इसमें आपका प्लेटफ़ॉर्म (OS, आर्किटेक्चर, Node.js वर्शन, डेटाबेस का प्रकार, और आप Docker, डेस्कटॉप ऐप या सामान्य सर्वर इस्तेमाल करते हैं), हर तरह का टैब कितनी बार खोला गया और कितने SSH लॉगिन हुए, और कौन से बिल्ट-इन फ़ीचर चल रहे हैं, यह भी हो सकता है। इसमें कभी भी यूज़रनेम, होस्टनेम, IP पते, क्रेडेंशियल या ऐसी कोई चीज़ नहीं होती जिससे आपकी या आपके सर्वर की पहचान हो।
-यह डिफ़ॉल्ट रूप से चालू रहता है। इसे एडमिन सेटिंग्स में सामान्य के अंतर्गत बंद करें, या Termix शुरू करने से पहले ही `ENABLE_TELEMETRY=false` सेट कर दें।
+यह डिफ़ॉल्ट रूप से चालू रहता है। इसे एडमिन सेटिंग्स में Usage Statistics के अंतर्गत बंद करें या चुनें कि इसमें क्या शामिल हो, और वहीं भेजी जाने वाली रिपोर्ट पहले से देख भी सकते हैं। हर यूज़र अपनी प्रोफ़ाइल में अपना फ़ीचर इस्तेमाल हटा सकता है। `ENABLE_TELEMETRY=false` सेट करने से यह बंद हो जाता है और स्विच लॉक हो जाता है।
diff --git a/docs/readme/README-IT.md b/docs/readme/README-IT.md
index 430bf70f5..d67e120af 100644
--- a/docs/readme/README-IT.md
+++ b/docs/readme/README-IT.md
@@ -367,9 +367,9 @@ Puoi far girare il server Termix su un VPS invece che dentro la tua rete. Se Ter
## Telemetria
-Termix invia una volta al giorno un piccolo segnale anonimo, così posso vedere quante istanze sono attive e quali funzionalità vengono usate davvero. Contiene un ID istanza casuale, quanti utenti e host hai, la versione dell'app e quali funzionalità (terminale, gestore file, tunnel, docker, ecc.) sono state usate nelle ultime 24 ore. Non contiene mai nomi utente, nomi host, indirizzi IP, credenziali o qualsiasi altra cosa che identifichi te o i tuoi server.
+Termix invia una volta al giorno un piccolo report anonimo, così posso vedere quante istanze sono attive e quali funzioni vengono usate. Contiene un ID di istanza casuale, la versione dell'app e quanti utenti e host hai. Può includere anche la tua piattaforma (sistema operativo, architettura, versione di Node.js, tipo di database e se usi Docker, l'app desktop o un server normale), quante volte è stato aperto ogni tipo di scheda e quanti login SSH ci sono stati, e quali funzioni integrate sono attive. Non contiene mai nomi utente, nomi host, indirizzi IP, credenziali o altro che identifichi te o i tuoi server.
-È attivo di base. Puoi spegnerlo nelle impostazioni di amministrazione, sezione Generale, oppure impostare `ENABLE_TELEMETRY=false` prima ancora di avviare Termix.
+È attivo di base. Puoi spegnerlo o scegliere cosa include nelle impostazioni di amministrazione, sezione Usage Statistics, dove puoi anche vedere il report esatto prima dell'invio. Ogni utente può escludere il proprio uso delle funzioni dal suo profilo. Impostare `ENABLE_TELEMETRY=false` lo spegne e blocca l'interruttore.
diff --git a/docs/readme/README-JA.md b/docs/readme/README-JA.md
index 4ffbc7298..c0ec71279 100644
--- a/docs/readme/README-JA.md
+++ b/docs/readme/README-JA.md
@@ -367,9 +367,9 @@ Termix のサーバーは自分のネットワーク内ではなく、VPS で動
## テレメトリー
-Termix は 1 日 1 回、匿名の小さなデータを送ります。どれくらいのインスタンスが動いていて、どの機能が使われているかを把握するためのものです。含まれるのはランダムなインスタンス ID、ユーザーとホストの数、アプリのバージョン、直近 24 時間に使われた機能(ターミナル、ファイルマネージャー、トンネル、Docker など)だけです。ユーザー名、ホスト名、IP アドレス、認証情報など、あなたやサーバーを特定できるものは一切含まれません。
+Termix は 1 日に 1 回、小さな匿名レポートを送信します。これで、どれだけのインスタンスが動いていて、どの機能が使われているかを把握しています。内容はランダムなインスタンス ID、アプリのバージョン、ユーザー数とホスト数です。さらに、プラットフォーム(OS、アーキテクチャ、Node.js のバージョン、データベースの種類、Docker・デスクトップアプリ・通常のサーバーのどれで動いているか)、各種タブが開かれた回数と SSH ログイン数、動作中の組み込み機能を含めることもできます。ユーザー名、ホスト名、IP アドレス、認証情報など、あなたやサーバーを特定できる情報は一切含みません。
-初期状態では有効です。管理設定の「一般」から止められますし、Termix を起動する前に `ENABLE_TELEMETRY=false` を設定しておくこともできます。
+初期状態では有効です。管理設定の「Usage Statistics」から止めたり、含める内容を選んだりでき、送信されるレポートをそのまま事前に確認することもできます。各ユーザーはプロフィールで自分の機能利用データを除外できます。`ENABLE_TELEMETRY=false` を設定すると無効になり、スイッチもロックされます。
diff --git a/docs/readme/README-KO.md b/docs/readme/README-KO.md
index 4dd2fee68..e359b0746 100644
--- a/docs/readme/README-KO.md
+++ b/docs/readme/README-KO.md
@@ -365,9 +365,9 @@ Termix 서버는 집 안 네트워크가 아니라 VPS에서 돌릴 수도 있
## 텔레메트리
-Termix는 하루에 한 번 익명의 작은 데이터를 보냅니다. 인스턴스가 얼마나 돌아가는지, 어떤 기능이 쓰이는지 파악하기 위한 것입니다. 여기에는 무작위 인스턴스 ID, 사용자와 호스트 수, 앱 버전, 최근 24시간 동안 쓴 기능(터미널, 파일 관리자, 터널, Docker 등)만 들어갑니다. 사용자 이름과 호스트 이름, IP 주소, 자격 증명처럼 나나 내 서버를 알아볼 수 있는 것은 전혀 담기지 않습니다.
+Termix는 하루에 한 번 작은 익명 보고서를 보내서 몇 개의 인스턴스가 실행 중이고 어떤 기능이 쓰이는지 알 수 있게 합니다. 보고서에는 무작위 인스턴스 ID, 앱 버전, 사용자 수와 호스트 수가 들어 있습니다. 또한 플랫폼 정보(OS, 아키텍처, Node.js 버전, 데이터베이스 종류, Docker·데스크톱 앱·일반 서버 중 무엇으로 실행하는지), 탭 종류별로 열린 횟수와 SSH 로그인 수, 실행 중인 내장 기능도 포함될 수 있습니다. 사용자 이름, 호스트 이름, IP 주소, 자격 증명 등 당신이나 서버를 식별할 수 있는 정보는 절대 포함되지 않습니다.
-기본으로 켜져 있습니다. 관리 설정의 일반에서 끄거나, Termix를 시작하기 전에 `ENABLE_TELEMETRY=false`를 지정하면 됩니다.
+기본으로 켜져 있습니다. 관리 설정의 Usage Statistics에서 끄거나 포함할 내용을 고를 수 있고, 보낼 보고서를 미리 그대로 볼 수도 있습니다. 각 사용자는 자신의 프로필에서 본인의 기능 사용 기록을 뺄 수 있습니다. `ENABLE_TELEMETRY=false`를 지정하면 꺼지고 스위치가 잠깁니다.
diff --git a/docs/readme/README-PT.md b/docs/readme/README-PT.md
index fadc2a749..f76761a48 100644
--- a/docs/readme/README-PT.md
+++ b/docs/readme/README-PT.md
@@ -363,9 +363,9 @@ A [GINERNET](https://docs.termix.site/install/ginernet) patrocina o Termix, e a
## Telemetria
-O Termix manda uma vez por dia um pequeno sinal anônimo, para eu saber quantas instâncias estão rodando e quais funcionalidades são usadas. Ele contém um ID de instância aleatório, quantos usuários e hosts tu tens, a versão do aplicativo e quais funcionalidades (terminal, gerenciador de arquivos, túneis, docker, etc.) foram usadas nas últimas 24 horas. Nunca contém nomes de usuário, nomes de host, endereços IP, credenciais ou qualquer coisa que identifique ti ou os teus servidores.
+O Termix envia uma vez por dia um pequeno relatório anónimo, para eu ver quantas instâncias estão a correr e que funcionalidades são usadas. Contém um ID de instância aleatório, a versão da app e quantos utilizadores e hosts tens. Também pode incluir a tua plataforma (sistema operativo, arquitetura, versão do Node.js, tipo de base de dados e se usas Docker, a app de desktop ou um servidor normal), quantas vezes cada tipo de separador foi aberto e quantos logins SSH houve, e que funcionalidades integradas estão ativas. Nunca contém nomes de utilizador, nomes de host, endereços IP, credenciais ou qualquer outra coisa que te identifique a ti ou aos teus servidores.
-Vem ligado por padrão. Podes desligar nas configurações de administração, em Geral, ou definir `ENABLE_TELEMETRY=false` antes mesmo de iniciar o Termix.
+Vem ligado por padrão. Podes desligar ou escolher o que inclui nas configurações de administração, em Usage Statistics, onde também podes ver o relatório exato antes de ser enviado. Cada utilizador pode excluir o seu próprio uso de funcionalidades no perfil. Definir `ENABLE_TELEMETRY=false` desliga-o e bloqueia o interruptor.
diff --git a/docs/readme/README-RU.md b/docs/readme/README-RU.md
index 06296821a..6be533190 100644
--- a/docs/readme/README-RU.md
+++ b/docs/readme/README-RU.md
@@ -363,9 +363,9 @@ termix ssh 1
## Телеметрия
-Termix раз в сутки отправляет небольшой анонимный сигнал, чтобы я понимал, сколько установок работает и какими возможностями действительно пользуются. В нём есть случайный идентификатор установки, число пользователей и хостов, версия приложения и то, какие возможности (терминал, файловый менеджер, туннели, docker и прочее) использовались за последние 24 часа. В нём никогда нет имён пользователей, имён хостов, IP-адресов, учётных данных и ничего другого, что указывало бы на вас или ваши серверы.
+Раз в день Termix отправляет небольшой анонимный отчёт, чтобы я видел, сколько установок работает и какими функциями пользуются. В нём есть случайный ID установки, версия приложения и количество пользователей и хостов. Он также может включать вашу платформу (ОС, архитектуру, версию Node.js, тип базы данных и то, как запущен Termix: в Docker, как настольное приложение или как обычный сервер), сколько раз открывались вкладки каждого типа и сколько было входов по SSH, а также какие встроенные функции работают. В нём никогда нет имён пользователей, имён хостов, IP-адресов, учётных данных или чего-либо ещё, что может указать на вас или ваши серверы.
-По умолчанию он включён. Выключить можно в настройках администратора в разделе «Общие» или задать `ENABLE_TELEMETRY=false` ещё до первого запуска Termix.
+По умолчанию он включён. Выключить его или выбрать, что в него входит, можно в настройках администратора в разделе Usage Statistics, там же можно заранее посмотреть точный отчёт. Каждый пользователь может исключить своё использование функций в своём профиле. `ENABLE_TELEMETRY=false` выключает его и блокирует переключатель.
diff --git a/docs/readme/README-TR.md b/docs/readme/README-TR.md
index 35a118987..3b10c0bb1 100644
--- a/docs/readme/README-TR.md
+++ b/docs/readme/README-TR.md
@@ -363,9 +363,9 @@ Termix sunucusunu kendi ağınız yerine bir VPS üzerinde de çalıştırabilir
## Telemetri
-Termix günde bir kez küçük ve anonim bir sinyal gönderir; böylece kaç kurulumun çalıştığını ve hangi özelliklerin kullanıldığını görebiliyorum. İçinde rastgele bir kurulum kimliği, kaç kullanıcı ve sunucunuz olduğu, uygulama sürümü ve son 24 saatte hangi özelliklerin (terminal, dosya yöneticisi, tüneller, docker vb.) kullanıldığı yer alır. İçinde asla kullanıcı adları, sunucu adları, IP adresleri, kimlik bilgileri ya da sizi veya sunucularınızı tanımlayan başka bir şey bulunmaz.
+Termix, kaç kurulumun çalıştığını ve hangi özelliklerin kullanıldığını görebilmem için günde bir kez küçük ve anonim bir rapor gönderir. Raporda rastgele bir kurulum kimliği, uygulama sürümü ve kaç kullanıcı ile sunucunuz olduğu bulunur. Ayrıca platformunuzu (işletim sistemi, mimari, Node.js sürümü, veritabanı türü ve Docker, masaüstü uygulaması ya da normal bir sunucu kullanıp kullanmadığınız), her sekme türünün kaç kez açıldığını ve kaç SSH girişi yapıldığını, hangi yerleşik özelliklerin çalıştığını da içerebilir. Kullanıcı adları, sunucu adları, IP adresleri, kimlik bilgileri ya da sizi veya sunucularınızı tanıtacak hiçbir şey asla gönderilmez.
-Varsayılan olarak açıktır. Yönetici ayarlarında Genel bölümünden kapatabilir ya da Termix'i hiç başlatmadan önce `ENABLE_TELEMETRY=false` tanımlayabilirsiniz.
+Varsayılan olarak açıktır. Yönetici ayarlarında Usage Statistics bölümünden kapatabilir veya neleri içereceğini seçebilir, gönderilecek raporu olduğu gibi önizleyebilirsiniz. Her kullanıcı kendi özellik kullanımını profilinden hariç tutabilir. `ENABLE_TELEMETRY=false` tanımlamak onu kapatır ve anahtarı kilitler.
diff --git a/docs/readme/README-VI.md b/docs/readme/README-VI.md
index c16803e69..beb822aad 100644
--- a/docs/readme/README-VI.md
+++ b/docs/readme/README-VI.md
@@ -363,9 +363,9 @@ Bạn có thể chạy máy chủ Termix trên VPS thay vì trong mạng của m
## Dữ liệu sử dụng
-Termix gửi một tín hiệu nhỏ ẩn danh mỗi ngày một lần, để tôi biết có bao nhiêu bản đang chạy và tính năng nào thực sự được dùng. Nó gồm một mã bản cài ngẫu nhiên, số người dùng và máy chủ bạn có, phiên bản ứng dụng, và những tính năng (terminal, trình quản lý tệp, tunnel, docker, v.v.) đã dùng trong 24 giờ qua. Nó không bao giờ chứa tên người dùng, tên máy chủ, địa chỉ IP, thông tin đăng nhập hay bất cứ thứ gì nhận dạng bạn hoặc máy chủ của bạn.
+Mỗi ngày một lần, Termix gửi một báo cáo ẩn danh nhỏ để tôi biết có bao nhiêu bản cài đặt đang chạy và tính năng nào được dùng. Báo cáo gồm một ID ngẫu nhiên của bản cài đặt, phiên bản ứng dụng, và số người dùng cùng số máy chủ của bạn. Nó cũng có thể gồm nền tảng của bạn (hệ điều hành, kiến trúc, phiên bản Node.js, loại cơ sở dữ liệu, và bạn chạy bằng Docker, ứng dụng máy tính hay máy chủ thường), số lần mỗi loại tab được mở và số lần đăng nhập SSH, cùng các tính năng tích hợp đang chạy. Nó không bao giờ chứa tên người dùng, tên máy chủ, địa chỉ IP, thông tin đăng nhập hay bất cứ thứ gì có thể nhận ra bạn hoặc máy chủ của bạn.
-Mặc định là bật. Bạn tắt nó trong phần Cài đặt quản trị, mục Chung, hoặc đặt `ENABLE_TELEMETRY=false` trước cả khi khởi động Termix.
+Mặc định là bật. Bạn có thể tắt hoặc chọn nội dung gửi đi trong phần Cài đặt quản trị, mục Usage Statistics, và xem trước chính xác báo cáo sẽ được gửi. Mỗi người dùng có thể loại phần sử dụng tính năng của riêng mình trong hồ sơ. Đặt `ENABLE_TELEMETRY=false` sẽ tắt nó và khóa công tắc.
diff --git a/package-lock.json b/package-lock.json
index 00e24da3b..e6f1bb7f1 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -7021,6 +7021,10 @@
"resolved": "plugins/tailscale",
"link": true
},
+ "node_modules/@termix-plugin/telemetry": {
+ "resolved": "plugins/telemetry",
+ "link": true
+ },
"node_modules/@termix-plugin/termix-identity": {
"resolved": "plugins/termix-identity",
"link": true
@@ -19277,6 +19281,29 @@
"ssh2": "^1.17.0"
}
},
+ "plugins/telemetry": {
+ "name": "@termix-plugin/telemetry",
+ "version": "1.0.0",
+ "dependencies": {
+ "drizzle-orm": "^0.45.2"
+ },
+ "devDependencies": {
+ "@termix/plugin-sdk": "^1.0.0",
+ "@testing-library/dom": "^10.4.2",
+ "@testing-library/react": "^16.3.3",
+ "@types/node": "^26.2.0",
+ "@types/react": "^19.2.18",
+ "@types/react-dom": "^19.2.4",
+ "jsdom": "^30.0.1",
+ "vitest": "^4.1.11"
+ },
+ "peerDependencies": {
+ "@termix/plugin-sdk": "^1.0.0",
+ "express": "^5.2.1",
+ "react": "^19.2.8",
+ "sonner": "^2.0.8"
+ }
+ },
"plugins/termix-identity": {
"name": "@termix-plugin/termix-identity",
"version": "1.0.0",
diff --git a/packages/plugin-sdk/src/backend.ts b/packages/plugin-sdk/src/backend.ts
index ecbe2e4cc..d012d966b 100644
--- a/packages/plugin-sdk/src/backend.ts
+++ b/packages/plugin-sdk/src/backend.ts
@@ -1958,6 +1958,20 @@ export interface PluginSystem {
registerTlsRenewer: () => Promise<() => void>;
}
+/** One installed plugin as ctx.plugins.list reports it. */
+export interface PluginSummary {
+ id: string;
+ version: string;
+ source: "bundled" | "user";
+ /** "active" when running; anything else means it is not. */
+ state: string;
+}
+
+/** The installed plugins. Needs plugins:read. */
+export interface PluginPlugins {
+ list: () => Promise;
+}
+
export interface PluginContext {
readonly pluginId: string;
readonly manifest: PluginManifest;
@@ -1999,6 +2013,8 @@ export interface PluginContext {
readonly process: PluginProcess;
/** The server certificate. Needs system:tls. */
readonly system: PluginSystem;
+ /** The installed plugins and whether each runs. Needs plugins:read. */
+ readonly plugins: PluginPlugins;
/**
* Runs `fn` with `userId` as the acting user, for background work that has
diff --git a/packages/plugin-sdk/src/capabilities.ts b/packages/plugin-sdk/src/capabilities.ts
index 662278056..58f7cb93e 100644
--- a/packages/plugin-sdk/src/capabilities.ts
+++ b/packages/plugin-sdk/src/capabilities.ts
@@ -68,6 +68,7 @@ export const CAPABILITY_CATALOG: readonly CapabilityInfo[] = [
entry("files:own", "low"),
entry("secrets:own", "low"),
entry("settings:read-core", "low"),
+ entry("plugins:read", "low"),
entry("ui:surface", "low"),
] as const;
diff --git a/packages/plugin-sdk/src/testing.ts b/packages/plugin-sdk/src/testing.ts
index 67b041562..3f5daf2d4 100644
--- a/packages/plugin-sdk/src/testing.ts
+++ b/packages/plugin-sdk/src/testing.ts
@@ -78,6 +78,7 @@ import type {
PluginBinarySpec,
PluginTlsCertificateInfo,
PluginTlsStatus,
+ PluginSummary,
PluginKeyboardInteractiveHandler,
PluginProcessHandle,
PluginProcessOptions,
@@ -152,6 +153,8 @@ export interface FakeContextOptions {
* from registerTlsRenewer calls.
*/
tlsStatus?: Omit;
+ /** What ctx.plugins.list answers. Default: only this plugin, active. */
+ installedPlugins?: PluginSummary[];
/**
* Checks a ctx.system.writeTlsCertificate call. Throw to reject the pair.
* Without it every pair is accepted and described with placeholder info.
@@ -1233,6 +1236,18 @@ export function createFakeContext(
},
},
+ plugins: {
+ list: async () =>
+ options.installedPlugins ?? [
+ {
+ id: pluginId,
+ version: "1.0.0",
+ source: "bundled",
+ state: "active",
+ },
+ ],
+ },
+
system: {
tlsStatus: async () => {
tls.calls.push("tlsStatus");
@@ -1416,6 +1431,8 @@ export interface MockContextOptions {
/** See FakeContextOptions. */
tlsStatus?: FakeContextOptions["tlsStatus"];
/** See FakeContextOptions. */
+ installedPlugins?: FakeContextOptions["installedPlugins"];
+ /** See FakeContextOptions. */
validateTls?: FakeContextOptions["validateTls"];
/** See FakeContextOptions. */
refuseEnrollment?: string;
@@ -1441,7 +1458,7 @@ export interface MockPluginContext extends FakePluginContext {
* topic outside the plugin's own namespace, settings:read-core on
* ctx.settings.readCore, ssh:connect plus credentials:use on ctx.ssh,
* notify:send on ctx.notify (notify:hub on serve), network:outbound on ctx.fetch, process:spawn on
- * ctx.process, system:tls on ctx.system, and auth:provide on ctx.auth. Reading a plugin's own settings is deliberately
+ * ctx.process, system:tls on ctx.system, plugins:read on ctx.plugins, and auth:provide on ctx.auth. Reading a plugin's own settings is deliberately
* ungated. As the SDK grows a member, add its gate here in the same shape.
*/
export function createMockCtx(
@@ -1472,6 +1489,7 @@ export function createMockCtx(
fetch: options.fetch,
process: options.process,
tlsStatus: options.tlsStatus,
+ installedPlugins: options.installedPlugins,
validateTls: options.validateTls,
refuseEnrollment: options.refuseEnrollment,
baseUrl: options.baseUrl,
@@ -1838,6 +1856,13 @@ export function createMockCtx(
},
},
+ plugins: {
+ list: async () => {
+ require("plugins:read");
+ return ctx.plugins.list();
+ },
+ },
+
system: {
tlsStatus: async () => {
require("system:tls");
diff --git a/plugins/telemetry/CHANGELOG.md b/plugins/telemetry/CHANGELOG.md
new file mode 100644
index 000000000..dc39a5321
--- /dev/null
+++ b/plugins/telemetry/CHANGELOG.md
@@ -0,0 +1,7 @@
+# Changelog
+
+## 1.0.0
+
+First release, bundled with Termix 2.9.0.
+
+Moves the daily anonymous usage report out of Termix core. Adds platform info, feature usage counts and the list of running features, each with its own switch, a per-user opt-out, a preview of the exact report and a button to send it now.
diff --git a/plugins/telemetry/README.md b/plugins/telemetry/README.md
new file mode 100644
index 000000000..effefb226
--- /dev/null
+++ b/plugins/telemetry/README.md
@@ -0,0 +1,29 @@
+# Usage Statistics
+
+Sends a small anonymous report once a day so the Termix developers can see how many instances run and which features get used.
+
+## What is sent
+
+Always, while it is on:
+
+- A random instance ID, the Termix version, and how many users and hosts exist.
+
+Each of these has its own switch in Admin Settings > Usage Statistics:
+
+- Platform info: operating system, CPU architecture, Node.js version, database type, and whether Termix runs in Docker, the desktop app or as a plain server.
+- Feature usage: how many times each kind of tab was opened, plus SSH logins and host connections, since the last report.
+- Installed features: the ids of the running built-in features.
+
+It never sends usernames, hostnames, IP addresses, credentials or anything else that identifies you or your servers. Admins can preview the exact report before it is sent.
+
+## Turning it off
+
+- Admin Settings > Usage Statistics > Share anonymous usage statistics.
+- Each user can leave their own feature usage out in User Profile > Usage Statistics.
+- `ENABLE_TELEMETRY=false` turns it off and locks the switch. `ENABLE_TELEMETRY=true` locks it on.
+
+## Environment
+
+- `ENABLE_TELEMETRY`: `true` or `false` overrides the admin switch.
+- `POSTHOG_API_KEY`: the PostHog project key. Defaults to the Termix project.
+- `POSTHOG_HOST`: the PostHog host. Defaults to `https://us.i.posthog.com`.
diff --git a/plugins/telemetry/locales/en.json b/plugins/telemetry/locales/en.json
new file mode 100644
index 000000000..83a0016c0
--- /dev/null
+++ b/plugins/telemetry/locales/en.json
@@ -0,0 +1,58 @@
+{
+ "permissions": {
+ "manage": {
+ "title": "Manage usage statistics",
+ "description": "See what usage statistics are sent, send them now and reset the instance ID."
+ }
+ },
+ "settings": {
+ "enabled": {
+ "label": "Share anonymous usage statistics",
+ "description": "Sends a small anonymous summary once a day to help improve Termix. It never includes usernames, hostnames, IP addresses or credentials."
+ },
+ "includePlatform": {
+ "label": "Include platform info",
+ "description": "The operating system, CPU architecture, Node.js version, database type and how Termix is installed (Docker, desktop app or server)."
+ },
+ "includeFeatureUsage": {
+ "label": "Include feature usage",
+ "description": "How many times each kind of tab was opened and how many SSH logins happened since the last report. Users can turn off their own part in their profile."
+ },
+ "includePlugins": {
+ "label": "Include installed features",
+ "description": "Which built-in features are installed and running."
+ },
+ "instanceId": {
+ "label": "Instance ID"
+ },
+ "shareFeatureUsage": {
+ "label": "Include my feature usage",
+ "description": "Counts which kinds of tabs you open in the anonymous usage statistics. Nothing about you or your hosts is sent."
+ }
+ },
+ "status": {
+ "title": "Status",
+ "on": "Sharing usage statistics once a day",
+ "off": "Not sharing usage statistics",
+ "lockedOn": "Turned on by the ENABLE_TELEMETRY environment variable. Change it there.",
+ "lockedOff": "Turned off by the ENABLE_TELEMETRY environment variable. Change it there.",
+ "instanceId": "Instance ID: {{id}}",
+ "noInstanceId": "No instance ID yet",
+ "lastSent": "Last sent {{date}}",
+ "neverSent": "Not sent yet",
+ "nextSend": "Next report due {{date}}",
+ "lastError": "Last attempt failed: {{error}}",
+ "preview": "Preview report",
+ "sendNow": "Send now",
+ "sending": "Sending...",
+ "sent": "Usage statistics sent",
+ "notSent": "Usage statistics are turned off, nothing was sent",
+ "resetId": "Reset instance ID",
+ "resetIdConfirm": "Reset the instance ID? Future reports will look like a new install.",
+ "resetIdDone": "Instance ID reset",
+ "previewTitle": "Next report",
+ "previewDescription": "This is exactly what would be sent right now.",
+ "close": "Close",
+ "loadFailed": "Could not load the usage statistics status"
+ }
+}
diff --git a/plugins/telemetry/manifest.json b/plugins/telemetry/manifest.json
new file mode 100644
index 000000000..c20ec8236
--- /dev/null
+++ b/plugins/telemetry/manifest.json
@@ -0,0 +1,97 @@
+{
+ "id": "telemetry",
+ "name": "Usage Statistics",
+ "version": "1.0.0",
+ "description": "Sends an anonymous daily summary of how Termix is used, to help decide what to work on next.",
+ "author": {
+ "name": "Termix"
+ },
+ "license": "MIT",
+ "repository": "https://github.com/Termix-SSH/Termix",
+ "category": "Monitoring",
+ "icon": "ChartNoAxesColumn",
+ "engine": {
+ "termix": ">=2.9.0",
+ "api": "1"
+ },
+ "capabilities": [
+ "db:core-refs",
+ "network:outbound",
+ "network:serve",
+ "events:core",
+ "db:own",
+ "kv:own",
+ "plugins:read",
+ "ui:surface"
+ ],
+ "contributes": {
+ "permissions": [
+ {
+ "name": "manage",
+ "titleKey": "permissions.manage.title",
+ "descriptionKey": "permissions.manage.description",
+ "defaultRoles": ["admin"]
+ }
+ ],
+ "settings": {
+ "admin": [
+ {
+ "key": "status",
+ "type": "custom",
+ "component": "status",
+ "permission": "manage"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "labelKey": "settings.enabled.label",
+ "descriptionKey": "settings.enabled.description",
+ "default": true
+ },
+ {
+ "key": "includePlatform",
+ "type": "boolean",
+ "labelKey": "settings.includePlatform.label",
+ "descriptionKey": "settings.includePlatform.description",
+ "requires": "enabled",
+ "default": true
+ },
+ {
+ "key": "includeFeatureUsage",
+ "type": "boolean",
+ "labelKey": "settings.includeFeatureUsage.label",
+ "descriptionKey": "settings.includeFeatureUsage.description",
+ "requires": "enabled",
+ "default": true
+ },
+ {
+ "key": "includePlugins",
+ "type": "boolean",
+ "labelKey": "settings.includePlugins.label",
+ "descriptionKey": "settings.includePlugins.description",
+ "requires": "enabled",
+ "default": true
+ },
+ {
+ "key": "instanceId",
+ "type": "string",
+ "labelKey": "settings.instanceId.label",
+ "hidden": true,
+ "default": ""
+ }
+ ],
+ "user": [
+ {
+ "key": "shareFeatureUsage",
+ "type": "boolean",
+ "labelKey": "settings.shareFeatureUsage.label",
+ "descriptionKey": "settings.shareFeatureUsage.description",
+ "default": true
+ }
+ ]
+ }
+ },
+ "locales": "locales",
+ "platforms": ["linux", "win32", "darwin"],
+ "desktop": "server"
+}
diff --git a/plugins/telemetry/package.json b/plugins/telemetry/package.json
new file mode 100644
index 000000000..a228cdb63
--- /dev/null
+++ b/plugins/telemetry/package.json
@@ -0,0 +1,31 @@
+{
+ "name": "@termix-plugin/telemetry",
+ "private": true,
+ "version": "1.0.0",
+ "type": "module",
+ "scripts": {
+ "build": "termix-plugin build",
+ "test": "termix-plugin test",
+ "typecheck": "tsc -p .",
+ "validate": "termix-plugin validate"
+ },
+ "dependencies": {
+ "drizzle-orm": "^0.45.2"
+ },
+ "devDependencies": {
+ "@termix/plugin-sdk": "^1.0.0",
+ "@testing-library/dom": "^10.4.2",
+ "@testing-library/react": "^16.3.3",
+ "@types/node": "^26.2.0",
+ "@types/react": "^19.2.18",
+ "@types/react-dom": "^19.2.4",
+ "jsdom": "^30.0.1",
+ "vitest": "^4.1.11"
+ },
+ "peerDependencies": {
+ "@termix/plugin-sdk": "^1.0.0",
+ "express": "^5.2.1",
+ "react": "^19.2.8",
+ "sonner": "^2.0.8"
+ }
+}
diff --git a/plugins/telemetry/src/backend/collect.ts b/plugins/telemetry/src/backend/collect.ts
new file mode 100644
index 000000000..c3da23e1d
--- /dev/null
+++ b/plugins/telemetry/src/backend/collect.ts
@@ -0,0 +1,140 @@
+import fs from "node:fs";
+import { randomUUID } from "node:crypto";
+import { sql } from "drizzle-orm";
+import type { PluginContext } from "@termix/plugin-sdk/backend";
+import { envOverride } from "./config.js";
+import { usageProperty, type UsageCounts, type UsageStore } from "./usage.js";
+
+/* eslint-disable @typescript-eslint/no-explicit-any */
+// ctx.db hands back the server's own drizzle handle and tables, untyped.
+type Table = any;
+type Drizzle = any;
+/* eslint-enable @typescript-eslint/no-explicit-any */
+
+export interface TelemetrySettings {
+ enabled: boolean;
+ includePlatform: boolean;
+ includeFeatureUsage: boolean;
+ includePlugins: boolean;
+ instanceId: string;
+}
+
+export interface TelemetryPayload {
+ event: "instance_heartbeat";
+ distinct_id: string;
+ properties: Record;
+}
+
+type Env = Record;
+
+export async function readSettings(
+ ctx: PluginContext,
+): Promise {
+ const all = await ctx.settings.getAll("admin");
+ return {
+ enabled: all.enabled !== false,
+ includePlatform: all.includePlatform !== false,
+ includeFeatureUsage: all.includeFeatureUsage !== false,
+ includePlugins: all.includePlugins !== false,
+ instanceId: typeof all.instanceId === "string" ? all.instanceId : "",
+ };
+}
+
+/** The env variable decides when set, the admin switch otherwise. */
+export function isEnabled(settings: TelemetrySettings, env?: Env): boolean {
+ return envOverride(env) ?? settings.enabled;
+}
+
+/**
+ * Made on first use rather than on activate, so the boot copy of a 2.8
+ * instance id is never shadowed by a new one.
+ */
+export async function ensureInstanceId(ctx: PluginContext): Promise {
+ const existing = await ctx.settings.get("instanceId");
+ if (existing) return existing;
+ const id = randomUUID();
+ await ctx.settings.set("instanceId", id);
+ return id;
+}
+
+export function detectDeployment(
+ env: Env = process.env,
+ exists: (path: string) => boolean = fs.existsSync,
+): "desktop" | "docker" | "server" {
+ if (env.ELECTRON_EMBEDDED === "true") return "desktop";
+ if (exists("/.dockerenv")) return "docker";
+ return "server";
+}
+
+async function countRows(ctx: PluginContext): Promise<{
+ userCount: number;
+ hostCount: number;
+}> {
+ const { users, hosts } = await ctx.db.refs<{ users: Table; hosts: Table }>();
+ const db = await ctx.db.client();
+ const count = async (table: Table) => {
+ const rows = await db.select({ count: sql`count(*)` }).from(table);
+ return Number(rows[0]?.count ?? 0);
+ };
+ const [userCount, hostCount] = await Promise.all([
+ count(users),
+ count(hosts),
+ ]);
+ return { userCount, hostCount };
+}
+
+export interface BuiltPayload {
+ payload: TelemetryPayload;
+ /** The counts the payload carries, to subtract once it is sent. */
+ usage: UsageCounts;
+}
+
+export async function buildPayload(
+ ctx: PluginContext,
+ usage: UsageStore,
+ env: Env = process.env,
+): Promise {
+ const settings = await readSettings(ctx);
+ const distinctId = await ensureInstanceId(ctx);
+ const { userCount, hostCount } = await countRows(ctx);
+
+ const properties: Record = {
+ version: env.VERSION || "unknown",
+ user_count: userCount,
+ host_count: hostCount,
+ };
+
+ if (settings.includePlatform) {
+ properties.os = process.platform;
+ properties.arch = process.arch;
+ properties.node_version = process.versions.node;
+ properties.db_dialect = ctx.db.dialect;
+ properties.deployment = detectDeployment(env);
+ }
+
+ let carried: UsageCounts = {};
+ if (settings.includeFeatureUsage) {
+ carried = await usage.read();
+ for (const [name, count] of Object.entries(carried)) {
+ properties[usageProperty(name)] = count;
+ }
+ }
+
+ if (settings.includePlugins) {
+ const running = (await ctx.plugins.list())
+ .filter((plugin) => plugin.state === "active")
+ .map((plugin) => plugin.id)
+ .sort();
+ properties.plugins_enabled = running;
+ properties.plugin_count = running.length;
+ }
+
+ return {
+ payload: {
+ event: "instance_heartbeat",
+ distinct_id: distinctId,
+ properties,
+ },
+ usage: carried,
+ };
+}
diff --git a/plugins/telemetry/src/backend/config.ts b/plugins/telemetry/src/backend/config.ts
new file mode 100644
index 000000000..9af9b307e
--- /dev/null
+++ b/plugins/telemetry/src/backend/config.ts
@@ -0,0 +1,26 @@
+/** Public project key. Only lets a client send events, never read them. */
+export const DEFAULT_POSTHOG_API_KEY =
+ "phc_xM8UznirsFxUkGE68gH4jzeqevf4kh76wGw7Ci7hH2dd";
+export const DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com";
+
+type Env = Record;
+
+/** ENABLE_TELEMETRY wins over the admin setting when set. */
+export function envOverride(env: Env = process.env): boolean | null {
+ const value = env.ENABLE_TELEMETRY?.trim().toLowerCase();
+ if (!value) return null;
+ return value === "true";
+}
+
+export function posthogConfig(env: Env = process.env): {
+ apiKey: string;
+ host: string;
+} {
+ return {
+ apiKey: env.POSTHOG_API_KEY?.trim() || DEFAULT_POSTHOG_API_KEY,
+ host: (env.POSTHOG_HOST?.trim() || DEFAULT_POSTHOG_HOST).replace(
+ /\/+$/,
+ "",
+ ),
+ };
+}
diff --git a/plugins/telemetry/src/backend/index.ts b/plugins/telemetry/src/backend/index.ts
new file mode 100644
index 000000000..edca3ac28
--- /dev/null
+++ b/plugins/telemetry/src/backend/index.ts
@@ -0,0 +1,65 @@
+import type { Router } from "express";
+import type { PluginContext } from "@termix/plugin-sdk/backend";
+import { envOverride } from "./config.js";
+import { isEnabled, readSettings } from "./collect.js";
+import { CHECK_INTERVAL_MS, createReporter } from "./reporter.js";
+import { registerRoutes } from "./routes.js";
+import { createUsageStore } from "./usage.js";
+
+/** First check a few minutes after boot, once core's boot copies ran. */
+const FIRST_CHECK_DELAY_MS = 3 * 60 * 1000;
+
+type Env = Record;
+
+export async function activateWith(ctx: PluginContext, env: Env) {
+ const usage = createUsageStore(ctx.kv);
+ const reporter = createReporter(ctx, usage, env);
+
+ const check = async () => {
+ try {
+ await reporter.send();
+ } catch {
+ // Logged by the reporter; the next check tries again.
+ }
+ };
+ ctx.schedule.after(FIRST_CHECK_DELAY_MS, check);
+ ctx.schedule.every(CHECK_INTERVAL_MS, check);
+
+ const countEvent = (feature: string) => async () => {
+ const settings = await readSettings(ctx);
+ if (isEnabled(settings, env) && settings.includeFeatureUsage) {
+ await usage.add({ [feature]: 1 });
+ }
+ };
+ const onLogin = countEvent("ssh_login");
+ const onConnected = countEvent("host_connected");
+ ctx.events.on("host.login", () => void onLogin().catch(() => undefined));
+ ctx.events.on("host.session.status", (payload) => {
+ if ((payload as { online?: boolean } | null)?.online) {
+ void onConnected().catch(() => undefined);
+ }
+ });
+
+ ctx.settings.onValidate("admin", async (values) => {
+ const locked = envOverride(env);
+ if (locked === null || values.enabled === undefined) return;
+ const stored = (await ctx.settings.get("enabled")) !== false;
+ if (values.enabled !== stored) {
+ return {
+ enabled:
+ "This is set by the ENABLE_TELEMETRY environment variable and cannot be changed here.",
+ };
+ }
+ });
+
+ registerRoutes(ctx, ctx.http.router(), reporter, usage, env);
+ return { reporter, usage };
+}
+
+export async function activate(ctx: PluginContext) {
+ await activateWith(ctx, process.env);
+}
+
+export async function deactivate() {
+ // Everything above was registered through ctx and is disposed by core.
+}
diff --git a/plugins/telemetry/src/backend/reporter.ts b/plugins/telemetry/src/backend/reporter.ts
new file mode 100644
index 000000000..ddb857773
--- /dev/null
+++ b/plugins/telemetry/src/backend/reporter.ts
@@ -0,0 +1,117 @@
+import { randomUUID } from "node:crypto";
+import type { PluginContext } from "@termix/plugin-sdk/backend";
+import { envOverride, posthogConfig } from "./config.js";
+import { buildPayload, isEnabled, readSettings } from "./collect.js";
+import type { UsageStore } from "./usage.js";
+
+export const REPORT_INTERVAL_MS = 24 * 60 * 60 * 1000;
+/** Checked hourly, so a restart never skips or doubles a day. */
+export const CHECK_INTERVAL_MS = 60 * 60 * 1000;
+
+const STATE_KEY = "state";
+
+export interface ReporterState {
+ lastSentAt: string | null;
+ lastAttemptAt: string | null;
+ lastError: string | null;
+}
+
+export type SendResult =
+ { sent: true } | { sent: false; reason: "disabled" | "not-due" };
+
+type Env = Record;
+
+export function createReporter(
+ ctx: PluginContext,
+ usage: UsageStore,
+ env: Env = process.env,
+ now: () => number = Date.now,
+) {
+ async function state(): Promise {
+ const stored = (await ctx.kv.get(STATE_KEY)) as
+ Partial | undefined;
+ return {
+ lastSentAt: stored?.lastSentAt ?? null,
+ lastAttemptAt: stored?.lastAttemptAt ?? null,
+ lastError: stored?.lastError ?? null,
+ };
+ }
+
+ async function saveState(patch: Partial) {
+ await ctx.kv.set(STATE_KEY, { ...(await state()), ...patch });
+ }
+
+ async function nextDueAt(): Promise {
+ const { lastSentAt } = await state();
+ if (!lastSentAt) return null;
+ return new Date(Date.parse(lastSentAt) + REPORT_INTERVAL_MS).toISOString();
+ }
+
+ async function send(options: { force?: boolean } = {}): Promise {
+ if (!isEnabled(await readSettings(ctx), env)) {
+ return { sent: false, reason: "disabled" };
+ }
+ if (!options.force) {
+ const due = await nextDueAt();
+ if (due && Date.parse(due) > now()) {
+ return { sent: false, reason: "not-due" };
+ }
+ }
+
+ const attemptAt = new Date(now()).toISOString();
+ const { apiKey, host } = posthogConfig(env);
+ try {
+ const { payload, usage: carried } = await buildPayload(ctx, usage, env);
+ const response = await ctx.fetch(`${host}/capture/`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ api_key: apiKey, ...payload }),
+ timeoutMs: 10_000,
+ });
+ if (!response.ok) {
+ throw new Error(`PostHog answered ${response.status}`);
+ }
+ await usage.subtract(carried);
+ await saveState({
+ lastSentAt: attemptAt,
+ lastAttemptAt: attemptAt,
+ lastError: null,
+ });
+ ctx.log.info("Sent daily usage statistics");
+ return { sent: true };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ await saveState({ lastAttemptAt: attemptAt, lastError: message });
+ ctx.log.warn(`Could not send usage statistics: ${message}`);
+ throw error;
+ }
+ }
+
+ return {
+ state,
+ send,
+
+ async status() {
+ const settings = await readSettings(ctx);
+ return {
+ enabled: isEnabled(settings, env),
+ locked: envOverride(env) !== null,
+ instanceId: settings.instanceId || null,
+ nextDueAt: await nextDueAt(),
+ ...(await state()),
+ };
+ },
+
+ async preview() {
+ return (await buildPayload(ctx, usage, env)).payload;
+ },
+
+ async resetInstanceId(): Promise {
+ const id = randomUUID();
+ await ctx.settings.set("instanceId", id);
+ return id;
+ },
+ };
+}
+
+export type Reporter = ReturnType;
diff --git a/plugins/telemetry/src/backend/routes.ts b/plugins/telemetry/src/backend/routes.ts
new file mode 100644
index 000000000..d593d9ddd
--- /dev/null
+++ b/plugins/telemetry/src/backend/routes.ts
@@ -0,0 +1,148 @@
+import type { Request, RequestHandler, Response, Router } from "express";
+import type { PluginContext } from "@termix/plugin-sdk/backend";
+import { isEnabled, readSettings } from "./collect.js";
+import type { Reporter } from "./reporter.js";
+import { sanitizeUsage, type UsageStore } from "./usage.js";
+
+/** Whether the signed-in user's feature usage should be counted. */
+export async function shouldTrackUser(
+ ctx: PluginContext,
+ userId: string | undefined,
+ env?: Record,
+): Promise {
+ if (!userId) return false;
+ const settings = await readSettings(ctx);
+ if (!isEnabled(settings, env) || !settings.includeFeatureUsage) return false;
+ return (await ctx.settings.getUser(userId, "shareFeatureUsage")) !== false;
+}
+
+export function registerRoutes(
+ ctx: PluginContext,
+ router: Router,
+ reporter: Reporter,
+ usage: UsageStore,
+ env?: Record,
+): void {
+ const manage = ctx.rbac.require("manage") as unknown as RequestHandler;
+
+ /**
+ * @openapi
+ * /plugin-api/telemetry/status:
+ * get:
+ * summary: Usage statistics status
+ * description: Whether usage statistics are sent, whether ENABLE_TELEMETRY locks that, the instance ID and the last attempt.
+ * tags: [Usage Statistics]
+ * responses:
+ * 200:
+ * description: Status.
+ * 403:
+ * description: Missing the telemetry.manage permission.
+ */
+ router.get("/status", manage, async (_req: Request, res: Response) => {
+ res.json(await reporter.status());
+ });
+
+ /**
+ * @openapi
+ * /plugin-api/telemetry/preview:
+ * get:
+ * summary: Preview the next report
+ * description: The exact event that would be sent right now, without the API key.
+ * tags: [Usage Statistics]
+ * responses:
+ * 200:
+ * description: The event.
+ * 403:
+ * description: Missing the telemetry.manage permission.
+ */
+ router.get("/preview", manage, async (_req: Request, res: Response) => {
+ res.json(await reporter.preview());
+ });
+
+ /**
+ * @openapi
+ * /plugin-api/telemetry/send:
+ * post:
+ * summary: Send usage statistics now
+ * description: Sends the report straight away. Does nothing while usage statistics are turned off.
+ * tags: [Usage Statistics]
+ * responses:
+ * 200:
+ * description: Whether a report was sent.
+ * 403:
+ * description: Missing the telemetry.manage permission.
+ * 502:
+ * description: The report could not be delivered.
+ */
+ router.post("/send", manage, async (_req: Request, res: Response) => {
+ try {
+ res.json(await reporter.send({ force: true }));
+ } catch (error) {
+ res.status(502).json({
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ });
+
+ /**
+ * @openapi
+ * /plugin-api/telemetry/reset-id:
+ * post:
+ * summary: Reset the instance ID
+ * description: Picks a new random instance ID, so later reports look like a new install.
+ * tags: [Usage Statistics]
+ * responses:
+ * 200:
+ * description: The new ID.
+ * 403:
+ * description: Missing the telemetry.manage permission.
+ */
+ router.post("/reset-id", manage, async (_req: Request, res: Response) => {
+ res.json({ instanceId: await reporter.resetInstanceId() });
+ });
+
+ /**
+ * @openapi
+ * /plugin-api/telemetry/usage/config:
+ * get:
+ * summary: Whether to count this user's feature usage
+ * description: False when usage statistics or feature usage are off, or the user turned off their own part.
+ * tags: [Usage Statistics]
+ * responses:
+ * 200:
+ * description: "{ track: boolean }"
+ */
+ router.get("/usage/config", async (_req: Request, res: Response) => {
+ res.json({ track: await shouldTrackUser(ctx, ctx.currentActor(), env) });
+ });
+
+ /**
+ * @openapi
+ * /plugin-api/telemetry/usage:
+ * post:
+ * summary: Add feature usage counts
+ * description: Counts from the signed-in user's browser, added to the next report. Ignored when this user is not counted. Names and counts are checked and capped.
+ * tags: [Usage Statistics]
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * features:
+ * type: object
+ * additionalProperties:
+ * type: integer
+ * responses:
+ * 204:
+ * description: Recorded or ignored.
+ */
+ router.post("/usage", async (req: Request, res: Response) => {
+ if (await shouldTrackUser(ctx, ctx.currentActor(), env)) {
+ const counts = sanitizeUsage(req.body?.features);
+ if (Object.keys(counts).length > 0) await usage.add(counts);
+ }
+ res.status(204).end();
+ });
+}
diff --git a/plugins/telemetry/src/backend/usage.ts b/plugins/telemetry/src/backend/usage.ts
new file mode 100644
index 000000000..f2c436dc1
--- /dev/null
+++ b/plugins/telemetry/src/backend/usage.ts
@@ -0,0 +1,75 @@
+import type { PluginKeyValue } from "@termix/plugin-sdk/backend";
+
+const USAGE_KEY = "usage";
+const FEATURE_NAME = /^[a-z][a-z0-9_.-]{0,63}$/;
+export const MAX_FEATURES = 100;
+const MAX_COUNT = 100_000;
+
+export type UsageCounts = Record;
+
+/** Keeps valid names with positive whole counts, capped. */
+export function sanitizeUsage(input: unknown): UsageCounts {
+ const clean: UsageCounts = {};
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
+ return clean;
+ }
+ for (const [name, raw] of Object.entries(input)) {
+ if (!FEATURE_NAME.test(name)) continue;
+ const count = Math.floor(Number(raw));
+ if (!Number.isFinite(count) || count <= 0) continue;
+ clean[name] = Math.min(count, MAX_COUNT);
+ if (Object.keys(clean).length >= MAX_FEATURES) break;
+ }
+ return clean;
+}
+
+export function createUsageStore(kv: PluginKeyValue) {
+ // One write at a time, so two requests never drop each other's counts.
+ let queue: Promise = Promise.resolve();
+ const serial = (fn: () => Promise): Promise => {
+ const next = queue.then(fn, fn);
+ queue = next.catch(() => undefined);
+ return next;
+ };
+
+ const read = async (): Promise =>
+ sanitizeUsage(await kv.get(USAGE_KEY));
+
+ return {
+ read,
+
+ add: (counts: UsageCounts) =>
+ serial(async () => {
+ const current = await read();
+ for (const [name, count] of Object.entries(sanitizeUsage(counts))) {
+ if (
+ !(name in current) &&
+ Object.keys(current).length >= MAX_FEATURES
+ ) {
+ continue;
+ }
+ current[name] = Math.min((current[name] ?? 0) + count, MAX_COUNT);
+ }
+ await kv.set(USAGE_KEY, current);
+ }),
+
+ /** Drops what a successful report already carried. */
+ subtract: (sent: UsageCounts) =>
+ serial(async () => {
+ const current = await read();
+ for (const [name, count] of Object.entries(sent)) {
+ const left = (current[name] ?? 0) - count;
+ if (left > 0) current[name] = left;
+ else delete current[name];
+ }
+ await kv.set(USAGE_KEY, current);
+ }),
+ };
+}
+
+export type UsageStore = ReturnType;
+
+/** PostHog property name for a feature: used_tab_terminal. */
+export function usageProperty(name: string): string {
+ return `used_${name.replace(/[.-]/g, "_")}`;
+}
diff --git a/plugins/telemetry/src/frontend/TelemetryStatusSetting.tsx b/plugins/telemetry/src/frontend/TelemetryStatusSetting.tsx
new file mode 100644
index 000000000..1be24dd08
--- /dev/null
+++ b/plugins/telemetry/src/frontend/TelemetryStatusSetting.tsx
@@ -0,0 +1,191 @@
+import { useCallback, useEffect, useState } from "react";
+import { toast } from "sonner";
+import {
+ usePluginApi,
+ useTranslation,
+ type SettingsComponentProps,
+} from "@termix/plugin-sdk/frontend";
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ useConfirmation,
+} from "@termix/plugin-sdk/ui";
+
+export interface TelemetryStatus {
+ enabled: boolean;
+ locked: boolean;
+ instanceId: string | null;
+ lastSentAt: string | null;
+ lastAttemptAt: string | null;
+ lastError: string | null;
+ nextDueAt: string | null;
+}
+
+function errorMessage(error: unknown): string {
+ const data = (error as { response?: { data?: { error?: string } } })?.response
+ ?.data;
+ if (data?.error) return data.error;
+ return error instanceof Error ? error.message : String(error);
+}
+
+export function TelemetryStatusSetting({ running }: SettingsComponentProps) {
+ const { t } = useTranslation();
+ const api = usePluginApi();
+ const { confirmWithToast } = useConfirmation();
+ const [status, setStatus] = useState(null);
+ const [sending, setSending] = useState(false);
+ const [preview, setPreview] = useState(null);
+
+ const load = useCallback(async () => {
+ try {
+ const { data } = await api.get("/status");
+ setStatus(data);
+ } catch {
+ setStatus(null);
+ toast.error(t("status.loadFailed"));
+ }
+ }, [api, t]);
+
+ useEffect(() => {
+ if (running) void load();
+ }, [running, load]);
+
+ async function sendNow() {
+ setSending(true);
+ try {
+ const { data } = await api.post<{ sent: boolean }>("/send");
+ if (data.sent) toast.success(t("status.sent"));
+ else toast.info(t("status.notSent"));
+ } catch (error) {
+ toast.error(errorMessage(error));
+ } finally {
+ setSending(false);
+ await load();
+ }
+ }
+
+ async function showPreview() {
+ try {
+ const { data } = await api.get("/preview");
+ setPreview(data);
+ } catch (error) {
+ toast.error(errorMessage(error));
+ }
+ }
+
+ function resetId() {
+ void confirmWithToast(t("status.resetIdConfirm"), async () => {
+ try {
+ await api.post("/reset-id");
+ toast.success(t("status.resetIdDone"));
+ await load();
+ } catch (error) {
+ toast.error(errorMessage(error));
+ }
+ });
+ }
+
+ let summary = t("status.off");
+ if (status?.locked) {
+ summary = status.enabled ? t("status.lockedOn") : t("status.lockedOff");
+ } else if (status?.enabled) {
+ summary = t("status.on");
+ }
+
+ const muted = "text-[10px] text-muted-foreground";
+
+ return (
+