Self-hosted API quota & token limit tracker with live dashboard, 7-day history charts, and ntfy alerts.
๐ฌ๐ง English ยท ๐ฉ๐ช Deutsch
--- ## Overview **TokenWatch** is a self-hosted web application for monitoring AI API quotas and rate-limit windows across multiple providers in one dark-themed dashboard. It polls external provider APIs, accepts webhook pushes from a local Antigravity Language Server sync script, stores historical usage snapshots in PostgreSQL, displays interactive 7-day charts, and sends automated push alerts via **ntfy** when usage thresholds are reached. ### Architecture ```text +-----------------------------------+ POST /api/webhook/antigravity | Windows Host (Antigravity IDE) | -------------------------------------+ | Push-AntigravityQuota.ps1 | | | -> tokenwatch-sync.js | v +-----------------------------------+ +------------------------------+ | TokenWatch Server (Express) | +-----------------------------------+ REST API (30 min | Port 3000 | | External APIs | cron + live fetch) | - Static UI (public/) | | - POE (current_balance) | <-------------------> | - /api/quotas | | - MiniMax (coding_plan/remains) | | - /api/history | +-----------------------------------+ +--------------+---------------+ | +----------------------------+----------------------------+ v v +------------------------------+ +------------------------------+ | PostgreSQL Database | | ntfy Server | | - quotas (history) | | Alert threshold notifications| | - antigravity_latest (JSONB) | +------------------------------+ +------------------------------+ ``` --- ## Features - **Multi-Provider Quota Tracking**: - **POE**: Tracks remaining point balance against a `2,500,000` cap, daily refresh (`75,000`), expiring points, days until cap, points used today (calculated against the first UTC snapshot of the day), and a live UTC midnight refresh countdown. - **MiniMax**: Tracks `MiniMax (5h)` and `MiniMax (Weekly)` usage percentages (`model_name === 'general'`) with live reset countdowns. - **Antigravity (AG)**: Tracks 5 separate quota buckets via webhook push (`AG Gemini (5h)`, `AG Gemini (Weekly)`, `AG Claude (5h)`, `AG Claude (Weekly)`, `AG Gemini 4 Argon (Weekly)`), including individual reset timestamps (`Heute`, `Morgen`, or weekday + countdown). - **Persistent Antigravity State**: Incoming Antigravity webhook payloads are saved into the `antigravity_latest` PostgreSQL table (`JSONB`) and automatically restored on server startup. - **Automated Cron Snapshots & ntfy Alerts**: Every 30 minutes (`*/30 * * * *`), `node-cron` fetches all quotas, records them in PostgreSQL, and sends an `ntfy` notification (`Title: TokenWatch Alert`, `Tags: warning,robot`) when the configured threshold (`ALERT_THRESHOLD_PERCENT`, default `80`) is crossed. - **7-Day History Chart**: Interactive Chart.js line chart grouping snapshots into 5-minute intervals for `AG Gemini (5h)`, `AG Claude (5h)`, `POE`, and `MiniMax (5h)`. - **6 Selectable Progress Bar Themes**: Switch live between `Standard`, `Pac-Man`, `Battery`, `Nyan Cat`, `Matrix`, and `Lava` themes (also dynamically updates Chart.js dataset colors). - **Confetti Milestone**: Triggers a `canvas-confetti` celebration and displays `LIMIT REACHED!` (for non-POE providers) when a quota reaches `100%`. - **Windows Antigravity Sync & Debug Tools**: Includes `tokenwatch-sync.js`, `Push-AntigravityQuota.ps1` (Task Scheduler-ready), and cross-platform `fetch-quota.js` for inspecting raw local Language Server quota responses. --- ## How It Works & Tech Stack ### Internal Workflow 1. **Server Startup (`src/server.ts`)**: Initializes Express on `0.0.0.0:3000`, serves static assets from `public/`, initializes the PostgreSQL tables (`quotas` and `antigravity_latest`) via `initDb()`, and restores cached Antigravity quotas via `initAntigravityFromDb()`. 2. **Quota Polling (`src/services/providers.ts`)**: - `fetchPoeQuota()` queries `https://api.poe.com/usage/current_balance`. - `fetchMinimaxQuota()` queries `https://api.minimax.io/v1/api/openplatform/coding_plan/remains`. - `fetchAntigravityQuota()` reads the in-memory `antigravityCache` populated by `POST /api/webhook/antigravity` or restored from PostgreSQL. 3. **Alerting Logic (`src/cron.ts` & `src/services/ntfy.ts`)**: - For **POE** (where `percentage` represents *remaining* quota), an alert is triggered when `percentage <= (100 - ALERT_THRESHOLD_PERCENT)` (default `<= 20%` remaining). - For **MiniMax** and **Antigravity** (where `percentage` represents *used* quota), an alert is triggered when `percentage >= ALERT_THRESHOLD_PERCENT` (default `>= 80%` used). 4. **Local Antigravity Sync (`tokenwatch-sync.js`)**: Discovers running `language_server*` processes via PowerShell (`Get-CimInstance Win32_Process`), extracts `--csrf_token` and `--extension_server_port`, scans localhost listening ports (`Get-NetTCPConnection` with `netstat -ano` fallback), calls `POST /exa.language_server_pb.LanguageServerService/RetrieveUserQuotaSummary`, and forwards the parsed buckets to `/api/webhook/antigravity`. ### Tech Stack & Ports | Component | Technology / Version | Details | | :--- | :--- | :--- | | Runtime | Node.js 24 (`node:24-alpine`) | CommonJS TypeScript build (`tsc` -> `dist/`) | | Backend | Express `^5.2.1`, TypeScript `^7.0.2` | REST API + static file server | | Scheduler | `node-cron` `^4.6.0` | Runs every 30 minutes (`*/30 * * * *`) | | HTTP Client | `axios` `^1.20.0` | Provider API calls & ntfy alerts | | Database | PostgreSQL (`postgres:15-alpine`, `pg` `^8.23.0`) | Tables: `quotas`, `antigravity_latest` | | Frontend | Vanilla HTML/CSS/JS, Chart.js, `canvas-confetti` | Served from `public/` | | Default Port | `3000` (Container) / `3500` (Jannik-Cloud host bind) | Configurable via `PORT` | --- ## Prerequisites & Installation ### Prerequisites - **Local Development**: Node.js (v20+ / v24 recommended), npm, and a running PostgreSQL instance. - **Docker Deployment**: Docker and Docker Compose. - **Antigravity Local Sync (Optional)**: Windows host with Antigravity IDE running, Node.js, and PowerShell. ### Local Installation 1. Clone the repository: ```bash git clone https://git.orfel.de/Jannik/TokenWatch.git cd TokenWatch ``` 2. Install dependencies: ```bash npm install ``` 3. Create your environment file from `.env.example`: ```bash cp .env.example .env ``` Edit `.env` with your PostgreSQL credentials, `NTFY_URL`, and API keys. 4. Run in development mode (using `tsx`) or build for production: ```bash # Development npm run dev # Production build & start npm run build npm start ``` ### Docker Compose Setup Start TokenWatch together with PostgreSQL (`postgres:15-alpine`): ```bash cp .env.example .env # Edit .env with your credentials and API keys docker compose up -d ``` The dashboard will be available at `http://localhost:3000`. ### Jannik-Cloud Production Deployment A ready-to-use deployment template is provided in [`deployment-template/`](deployment-template/README.md): 1. Copy the contents of `deployment-template/` into `services/tokenwatch/` in your `Jannik-Cloud` repository. 2. Run `bash generate-env.sh` inside `services/tokenwatch/` to generate random PostgreSQL credentials and optionally encrypt `.env` to `.env.age` (using `keys/age-public-key.txt`). 3. Add your provider API keys (`POE_API_KEY`, `MINIMAX_API_KEY`, etc.) as needed. 4. The included `tokenwatch.caddy` configures reverse proxying for `tw.orfel.de`, `token.orfel.de`, and `tokenwatch.orfel.de` to `tokenwatch:3000`, while `docker-compose.yml` binds `127.0.0.1:3500:3000` on the external `jannik-cloud-net` network. 5. Note: `.github/workflows/docker.yml` also defines a GitHub Actions workflow that builds and pushes `ghcr.io/