Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
88 commits
Select commit Hold shift + click to select a range
41ebfa5
feat(cost-control): Implement backend diagnostics and optimizer servi…
dreamwing Feb 28, 2026
91524e2
feat: integrate Cost Control Center UI and backend
dreamwing Feb 28, 2026
da08d54
fix(tokens): add cacheWrite calculation to match OpenClaw formula
dreamwing Mar 1, 2026
0edf0be
feat(diagnostics): calculate dynamic savings for prompt caching and v…
dreamwing Mar 1, 2026
3f66a66
fix(frontend): remove HTML stat placeholders and wire true dynamic co…
dreamwing Mar 1, 2026
7b98c07
fix(diagnostics): add legacy fallback support for stats.cost.total st…
dreamwing Mar 1, 2026
58e4ab0
fix(diagnostics): calculate heartbeat cost dynamically based on tasks…
dreamwing Mar 1, 2026
6542d92
fix(ci): resolve linting warnings and update integration tests for He…
dreamwing Mar 1, 2026
05246f3
refactor: comprehensive code review fixes — precise calculations, sec…
dreamwing Mar 1, 2026
9e92b1d
feat(A02): multi-interval heartbeat selector with per-option cost cal…
dreamwing Mar 1, 2026
a45e8e6
feat(A02): add 6h/12h/24h interval options for heavy heartbeat users
dreamwing Mar 1, 2026
6cbae63
feat(ux): layered copy system, config diff preview, history undo, enh…
dreamwing Mar 1, 2026
c25b5cf
feat: helpText tooltips, custom thresholds, verbose API, cache hit ra…
dreamwing Mar 1, 2026
96bcb87
feat: complete UX persona analysis items 8-13
dreamwing Mar 1, 2026
9505fdb
feat: granular Skill idle detection (D04) with per-skill mtime grouping
dreamwing Mar 1, 2026
6450a91
fix: D04 scan correct Skills directory (~/.openclaw/skills/)
dreamwing Mar 1, 2026
9e90afb
fix: D04 matches OpenClaw source for Skill directory resolution
dreamwing Mar 1, 2026
6314c2a
fix: align OpenClaw home and config directory resolution with source
dreamwing Mar 1, 2026
ac265c0
fix: align token cost logic with OpenClaw source (P1-P4)
dreamwing Mar 1, 2026
d414549
Merge remote-tracking branch 'origin/master' into feature/cost-contro…
dreamwing Mar 1, 2026
ff0c248
refactor: unify path detection logic into pure utility
dreamwing Mar 1, 2026
7df9e2d
test: add coverage for new features
dreamwing Mar 1, 2026
35c0f9e
fix: remove unused os imports to resolve CI lint failure
dreamwing Mar 1, 2026
49fce5a
fix: resolve failing D03 diagnostic unit test and add ci-watch script
dreamwing Mar 1, 2026
9b742ac
chore: separate CI and release scripts from business scripts
dreamwing Mar 2, 2026
e96a140
chore: add npm push script and git pw alias for ci-watch
dreamwing Mar 2, 2026
92f5a2a
fix: code review fixes — extract safeCompare, sanitize backupPath, un…
dreamwing Mar 3, 2026
99314dd
docs: update Cloudflare tunnel instructions and add permanent route m…
dreamwing Mar 5, 2026
bdf8548
fix: restore bottom navigation tabs visibility
dreamwing Mar 5, 2026
03d6fec
fix: restructure tokens page layout to match prototype
dreamwing Mar 5, 2026
1f8a455
fix: prevent horizontal scrollbar on tokens page
dreamwing Mar 5, 2026
34534a6
fix: sync external trigger styles with prototype
dreamwing Mar 5, 2026
302561e
fix: restore bottom-nav fixed positioning
dreamwing Mar 5, 2026
18e8ef4
fix: add border to card-front matching master's .card style
dreamwing Mar 5, 2026
3992926
fix: restore Token Economy card background to match master
dreamwing Mar 5, 2026
34b21e6
fix: prevent optimizer content from hiding behind bottom tabs
dreamwing Mar 5, 2026
47040cf
fix: remove hardcoded prototype placeholders from optimizer
dreamwing Mar 5, 2026
40b2d42
feat(auth): add hyperlink to ClawBridge.app in login footer
dreamwing Mar 5, 2026
dc9be8d
style(tokens): use CSS grid for flip container to fix Optimizer scrol…
dreamwing Mar 5, 2026
9fbdfa5
fix(optimizer): calculate savings for quiet skills and gracefully han…
dreamwing Mar 5, 2026
7a78c68
feat(ui): remove internal action IDs from displaying in optimizer items
dreamwing Mar 5, 2026
c9d8fa0
feat(optimizer): make action help(? icons) interactive with clickable…
dreamwing Mar 5, 2026
c1ea57b
fix(optimizer): force cache-busting for diagnostics and properly coun…
dreamwing Mar 5, 2026
184a7eb
feat(optimizer): add analogy-based help texts and make protection tag…
dreamwing Mar 5, 2026
c72d5e5
Merge branch 'master' into feature/cost-control-center
dreamwing Mar 6, 2026
87b0a68
Merge branch 'feature/cost-control-center' of https://github.com/drea…
dreamwing Mar 6, 2026
d59288d
feat(tokens): optimize analysis report with WebSocket events, state t…
dreamwing Mar 9, 2026
be9a214
docs: add cost control center documentation and update READMEs
dreamwing Mar 9, 2026
dcba678
docs: add Chinese version of cost control center documentation
dreamwing Mar 9, 2026
bae9de3
docs: add docker changes to unreleased changelog
dreamwing Mar 10, 2026
c2cba39
fix(cost-control): tighten optimizer safety and advisory flow
dreamwing Mar 11, 2026
4a8cbfa
test(cost-control): add local acceptance harness
dreamwing Mar 12, 2026
fa2041f
fix(cost-control): harden local acceptance flow
dreamwing Mar 12, 2026
2fa8a6f
fix(cost-control): allow optimize requests without meta
dreamwing Mar 12, 2026
9fbc8c1
docs(cost-control): record local acceptance baseline
dreamwing Mar 13, 2026
bf85e9a
Fix optimizer skill symlink handling and caching advice
github-actions[bot] Mar 14, 2026
96fdd35
Fix dashboard merge conflicts and cache hit bindings
github-actions[bot] Mar 14, 2026
c74d06c
Adjust diagnostics budget handling and defaults
github-actions[bot] Mar 14, 2026
5810e64
Remove unsupported budget restore key
github-actions[bot] Mar 14, 2026
b870812
Make local cost-control sandbox start from clean config
github-actions[bot] Mar 14, 2026
002bfa4
Merge origin/master into feature/cost-control-center
github-actions[bot] Mar 14, 2026
296aed8
Fix optimizer flip card and heartbeat defaults
github-actions[bot] Mar 14, 2026
a7b805e
Fix optimizer error fallback message
github-actions[bot] Mar 14, 2026
a3f1df0
Make A09 concise marker idempotent
github-actions[bot] Mar 14, 2026
82f07eb
Harden memory rendering and idle threshold parsing
github-actions[bot] Mar 14, 2026
eb0052b
Restore optimization snapshots and escape job paths
github-actions[bot] Mar 14, 2026
dd61af0
feat: implement cost control center dashboard and growth database
dreamwinglet Mar 14, 2026
82f1800
chore: remove growth_db logic (migrated to website repo)
dreamwinglet Mar 14, 2026
63ad42f
feat(diagnostics): robust multi-agent heartbeat detection and max sav…
dreamwinglet Mar 14, 2026
cb9b985
feat(optimizer): add Skip button and persistent ignore list for recom…
dreamwinglet Mar 14, 2026
0671105
feat(optimizer): move skip reset to list views and add granular resto…
dreamwinglet Mar 15, 2026
3ecd139
fix(dashboard): add versioning to assets and optimize success view re…
dreamwinglet Mar 15, 2026
a260305
docs(diagnostics): translate all helpText strings to English
dreamwinglet Mar 15, 2026
a5c468c
docs(diagnostics): upgrade all recommendation titles to professional …
dreamwinglet Mar 15, 2026
2c11f26
docs(diagnostics): revert to user-friendly plain titles while keeping…
dreamwinglet Mar 15, 2026
42ce72d
docs(diagnostics): sync plain titles with user provided table
dreamwinglet Mar 15, 2026
6984b5b
feat(dashboard): finalize skip/restore logic and enhance timeline det…
dreamwinglet Mar 15, 2026
7e3399a
fix: clean local optimizer state and repair dashboard defaults
github-actions[bot] Mar 15, 2026
690bfcd
fix: address PR 23 review feedback
github-actions[bot] Mar 15, 2026
21ebb81
fix: clear diagnostics lint issues
github-actions[bot] Mar 15, 2026
ac1f2f9
fix: address latest PR 23 review comments
github-actions[bot] Mar 15, 2026
f8f75a8
fix: improve skip feedback in optimizer
github-actions[bot] Mar 15, 2026
f3f2087
feat: improve optimizer feedback and history
github-actions[bot] Mar 15, 2026
592e224
fix: address latest optimizer review feedback
github-actions[bot] Mar 15, 2026
4cd60cf
fix: clarify history undo availability
github-actions[bot] Mar 15, 2026
8551f60
fix: tighten optimizer diagnostics handling
github-actions[bot] Mar 15, 2026
98a38e9
fix: harden optimizer websocket flows
github-actions[bot] Mar 15, 2026
8fed6a7
fix: address latest PR 23 review comments
github-actions[bot] Mar 16, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions .github/scripts/ci-watch.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#!/bin/bash
# ci-watch.sh: Re-check GitHub Actions CI build until it completes and reports success.
# Usage: ./scripts/ci-watch.sh [branch]

BRANCH=${1:-$(git rev-parse --abbrev-ref HEAD)}

echo "👀 Watching recent CI run for branch: $BRANCH..."

while true; do
# Fetch latest run ID and status using GitHub CLI for lint-and-test workflow
OUTPUT=$(gh run list --branch "$BRANCH" --limit 1 --json status,conclusion --jq '.[0]')

if [ -z "$OUTPUT" ] || [ "$OUTPUT" == "null" ]; then
echo "⚠️ No workflows found for branch $BRANCH."
exit 1
fi

STATUS=$(echo "$OUTPUT" | jq -r '.status')
CONCLUSION=$(echo "$OUTPUT" | jq -r '.conclusion')

if [ "$STATUS" == "completed" ] || [ "$STATUS" == "" ]; then
if [ "$CONCLUSION" == "success" ]; then
echo "✅ CI Build Succeeded for branch $BRANCH."
exit 0
else
echo "❌ CI Build Failed (Conclusion: $CONCLUSION) for branch $BRANCH."
echo "Please fix the failing tests or lint errors and push again."
exit 1
fi
else
echo "⏳ CI Build Status: $STATUS... retrying in 10s"
sleep 10
fi
done
File renamed without changes.
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,4 @@ jobs:
- name: Run Release Script
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: node scripts/release.mjs ${{ inputs.type }}
run: node .github/scripts/release.mjs ${{ inputs.type }}
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ cloudflared

# Data & Logs
data/logs/
data/backups/
data/token_stats/
data/last_id.txt
data/optimizer.skip.json
dashboard.log
*.log

Expand All @@ -31,3 +33,8 @@ test_*.js
# Test coverage reports
coverage/
.nyc_output/

# Local cost-control acceptance artifacts
tests/cost-control/local/.backup/
tests/cost-control/local/.reports/
tests/cost-control/local/.sandbox/
7 changes: 4 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added
- Docker image support: added `Dockerfile`, `.dockerignore`, and CI workflow for automatic image publishing to GitHub Container Registry (#24)
- Docker usage instructions in README

## [1.1.4] - 2026-03-13

### Fixed
Expand All @@ -25,9 +29,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed
- propagate --token and other CLI args from install.sh to setup.sh (PR #26)



## [1.1.2] - 2026-03-01

### Fixed
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
* **📱 Mobile-First Dashboard**: Optimized for phone screens. View logs, stats, and controls without squinting.
* **🧠 Live Activity Feed**: Watch your agent "think" and execute tools in real-time. Features intelligent parallel logging (no missed background tasks) and deduplication.
* **💰 Token Economy**: Track daily/monthly LLM costs and usage trends. Know exactly where your money goes.
* **🔍 [Cost Control Center](docs/cost-control-center.md)**: 10 automated diagnostics that scan your usage, calculate savings, and let you apply optimizations with one tap. Cut API costs by 30–90%.
* **📜 Memory Timeline**: Browse your agent's daily journals and long-term memory evolution.
* **🚀 Mission Control**: Trigger cron jobs, restart services, or kill runaway scripts directly from the UI.
* **⚡ Zero-Config Remote**:
Expand Down
1 change: 1 addition & 0 deletions README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
* **📱 移动端优先**: 专为手机屏幕优化的 UI,随时随地查看日志和状态,无需缩放。
* **🧠 实时动态 (Live Activity)**: 像看朋友圈一样查看 Agent 的“思考”和“工具调用”。支持并行日志捕获(不会漏掉后台脚本)和智能去重。
* **💰 Token 经济学**: 精确追踪每日/每月的 LLM 成本和 Token 用量趋势。拒绝账单刺客。
* **🔍 [成本控制中心](docs/cost-control-center_CN.md)**: 10 项自动化诊断,扫描使用数据、计算节省空间,一键应用优化。可降低 API 成本 30–90%。
* **📜 记忆时间轴**: 浏览 Agent 的每日日志和长期记忆演变。
* **🚀 任务控制台**: 查看 Cron 定时任务状态,并支持从手机端手动触发脚本、重启服务或终止进程。
* **⚡ 零门槛远程**:
Expand Down
11 changes: 11 additions & 0 deletions data/diagnostics.config.json.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"D01_modelCostRatio": 0.5,
"D06_cacheHitRateMin": 0.10,
"D06_cacheableRatio": 0.80,
"D09_outputRatioThreshold": 0.10,
"D09_minOutputTokens": 1000,
"D09_reductionFactor": 0.30,
"D05_thinkingProportion": 0.40,
"D05_reductionRatio": 0.75,
"D04_idleDaysThreshold": 7
}
69 changes: 69 additions & 0 deletions docs/cost-control-center.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Cost Control Center

The **Cost Control Center** is a built-in diagnostic engine that analyzes your OpenClaw agent's token usage and provides actionable recommendations to reduce API costs.

## Features

### Token Monitoring Dashboard
- **Today's Cost** — live running total
- **Grand Total** — cumulative cost since installation
- **30-Day Forecast** — projected monthly spend based on recent patterns
- **Top Models** — cost breakdown by model
- **7-Day Histogram** — daily cost chart with drill-down

### Diagnostic Scanner (10 Rules)

| ID | Diagnostic | Description |
|----|-----------|-------------|
| A01 | Model Downgrade | Detects premium models used for routine tasks; suggests cheaper alternatives |
| A02 | Heartbeat Optimization | Calculates hidden heartbeat polling costs; offers tiered intervals |
| A03 | Session Reset Waste | Flags excessive session resets that waste context tokens |
| A04 | Idle Skill Detection | Finds unused skills that bloat system prompts |
| A05 | Thinking Overhead | Measures extended reasoning costs; recommends minimal mode |
| A06 | Prompt Caching | Detects missing cache config; enables 90% input savings |
| A07 | Compaction Safeguard | Prevents runaway costs from unbounded context growth |
| A08 | Local Ollama Routing | Routes simple requests to local models *(planned)* |
| A09 | Output Verbosity | Detects verbose output; adds concise directive |
| A10 | Multi-Model Routing | Cost-aware routing by task complexity *(planned)* |

### One-Tap Optimizer
- **Apply** button on every recommendation
- Automatic configuration backup before changes
- Instant **Undo/Rollback** to restore previous settings
- Full optimization history in `data/logs/optimizations.jsonl`

## API Endpoints

```
GET /api/diagnostics — Run all diagnostic checks, returns actions with savings
POST /api/optimize/:id — Apply a specific optimization (A01–A10)
```

## How It Works

1. The **DiagnosticsEngine** reads your JSONL usage logs and current configuration.
2. Each diagnostic rule calculates potential savings based on your *actual* data.
3. Results are displayed in the dashboard with dollar amounts and configuration diffs.
4. Tapping **Apply** triggers the **OptimizerService**, which:
- Backs up the current config to `data/backups/`
- Writes the optimized setting
- Logs the action to `data/logs/optimizations.jsonl`

## Files

```
src/services/diagnostics.js — 10 diagnostic rules (A01–A10)
src/services/optimizer.js — Apply/backup/rollback engine
src/services/pricing.js — 340+ model pricing database
src/routes/diagnostics.js — GET /api/diagnostics
src/routes/optimize.js — POST /api/optimize/:id
public/js/dashboard.js — Frontend rendering
```

## Credits

The 10 diagnostic rules were inspired by a community analysis of common OpenClaw cost pitfalls by [@li9292](https://x.com/li9292/status/2025081922410443243).

## Learn More

See the full series on [clawbridge.app/solutions](https://clawbridge.app/solutions) — 12 articles covering each diagnostic in depth.
58 changes: 58 additions & 0 deletions docs/cost-control-center_CN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# 成本控制中心 (Cost Control Center)

**成本控制中心**是一个内置的诊断引擎,它可以分析您的 OpenClaw Agent 的 Token 使用情况,并提供可操作的建议以降低 API 成本。

## 核心功能

### Token 经济学仪表盘
- **今日成本** — 实时运行总额
- **累计总额** — 自安装以来的累计成本
- **30 天预测** — 基于近期消耗模式预测的月度支出
- **热门模型** — 按模型进行成本细分
- **7 日历史柱状图** — 每日成本图表及详情点击查看

### 自动化诊断 (10 项规则)

| ID | 诊断项 | 说明 |
|----|-----------|-------------|
| A01 | 模型降级 (Model Downgrade) | 检测是否可以将简单的任务分配给更便宜的模型,并一键切换 |
| A02 | 心跳优化 (Heartbeat Optimization) | 计算无用“心跳”产生的费用,提供分级心跳间隔建议 |
| A03 | 丢弃上下文浪费 (Session Reset Waste) | 识别由于过于频繁重置 Session 导致的系统提示词重复加载浪费 |
| A04 | 冗余技能清理 (Idle Skill Detection) | 找到那些不常用但一直在消耗 Input Token 的技能指令 |
| A05 | 思考 Token 过载 (Thinking Overhead) | 评估扩展思考模式的成本,建议在简单任务中使用精简模式 |
| A06 | 提示词缓存 (Prompt Caching) | 检测是否未开启缓存,开启后可节省高达 90% 的 Input 成本 |
| A07 | 上下文紧缩防护 (Compaction Safeguard) | 防止由于对话过长导致的上下文费用超出预期 |
| A08 | 本地模型路由 (Local Ollama Routing) | 将简单的请求/心跳路由到本地免费模型 *(开发中)* |
| A09 | 回复精简 (Output Verbosity) | 检测由于回复过长导致的费用浪费,通过指令减少废话 |
| A10 | 多模型路由 (Multi-Model Routing) | 根据任务复杂度自动分发到不同价格的模型 *(开发中)* |

### 一键优化引擎
- 每项诊断建议旁都有 **【Apply】** 按钮。
- 修改前自动备份当前配置到 `data/backups/`。
- 支持一键 **【Undo/Rollback】**,秒级恢复之前的设置。
- 完整的优化日志记录在 `data/logs/optimizations.jsonl` 中。

## API 接口

```
GET /api/diagnostics — 运行所有诊断检查,返回建议的操作及预计节省的金额
POST /api/optimize/:id — 应用特定的优化操作 (A01–A10)
```

## 工作原理

1. **诊断引擎 (DiagnosticsEngine)** 读取您的 JSONL 使用日志和当前配置。
2. 每个诊断规则会根据您的**实际数据**计算潜在的节省金额。
3. 结果显示在前端仪表盘,包含具体的金额和配置差异 (diff)。
4. 点击“应用”触发 **优化服务 (OptimizerService)**:
- 备份当前配置。
- 写入优化后的设置。
- 记录操作记录。

## 鸣谢

这 10 项诊断规则的灵感来源于 [@li9292](https://x.com/li9292/status/2025081922410443243) 对 OpenClaw 常见成本痛点的总结。

## 深入了解

查看官网上的详细系列文章:[clawbridge.app/solutions](https://clawbridge.app/solutions) —— 深入讲解每项诊断的原理与实测数据。
12 changes: 8 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,27 @@ const { PORT, TUNNEL_TOKEN, LOG_DIR } = require('./src/config');
const app = require('./src/app');
const { setupWebSocket } = require('./src/websocket');
const { checkSystemStatus } = require('./src/services/monitor');
const { runAnalyzer } = require('./src/services/analyzer');
const { runAnalyzer, setWss } = require('./src/services/analyzer');
const { WORKSPACE_DIR } = require('./src/services/openclaw');
const tunnel = require('./tunnel');
const disableAnalyzer = process.env.COST_CONTROL_SKIP_ANALYZER === 'true';

// --- Create Server ---
const server = createServer(app);
const wss = new WebSocketServer({ server });

// --- WebSocket ---
setupWebSocket(wss);
setWss(wss);

// --- Background Tasks ---
setInterval(() => {
checkSystemStatus(() => {});
checkSystemStatus(() => { });
}, 3000);
runAnalyzer();
setInterval(runAnalyzer, 60 * 60 * 1000);
if (!disableAnalyzer) {
runAnalyzer();
setInterval(runAnalyzer, 60 * 60 * 1000);
}

// --- Startup ---
async function main() {
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"@octokit/rest": "^22.0.1",
"eslint": "^8.57.1",
"google-translate-api-x": "^10.7.2",
"jest": "^29.0.0",
"jest": "^29.7.0",
"prettier": "^3.0.0",
"semver": "^7.7.4",
"supertest": "^7.0.0"
Expand Down
Binary file modified public/app-icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading