5 Commits
Author SHA1 Message Date
CangShui 61aa053816 feat: add foreground monitor command with live status + recent logs
- serve now periodically writes account-pool state (active/cooldown/
  disabled, cooldown until, token expiry) to workbuddy-status.json,
  refreshed every 3s and immediately on cooldown/disable/refresh events
- new 'monitor' command runs in foreground: refreshes a live panel of
  all accounts (usable/cooldown/expired + reasons) every N seconds,
  optionally showing recent logs via journalctl (-journal) or a log
  file (-logfile)
- statusSnapshotFile excluded from git via .gitignore
- unit tests for tailLines and status snapshot states
2026-09-04 09:36:51 +08:00
CangShui 86b70baf29 feat: print loaded credential file list at end of startup banner
- After the per-account status block, print a summary line listing all
  loaded credential files (e.g. '已加载凭据文件 (2): workbuddy.json,
  workbuddy2.json') so the count is visible even when journalctl/
  systemctl truncates the earlier log lines
2026-09-04 08:48:21 +08:00
CangShui 0484db4b3a feat: show all accounts with full status in serve startup banner
- Startup banner now prints every account's complete status (nickname,
  UID, enterprise, domain, cooldown state, token validity, expiry)
  instead of a single-line summary
- Extracted shared formatAccountStatus() used by both status command
  and serve startup output, keeping them consistent
- Shows disabled accounts with reason and re-login hint at startup
2026-09-04 08:42:03 +08:00
CangShui 9fcd99f152 feat: auto-discover all workbuddy*.json in working directory
- When neither -auth nor -auth-dir is specified, scan the working
  directory for all workbuddy*.json files and build the account pool
  from them (multi-account without any flags)
- Example: /opt/workbuddy-gateway with workbuddy.json + workbuddy2.json
  is automatically loaded as a 2-account pool under systemd
- loadDisabledMarkers also auto-discovers *.json.disabled markers
- Fallback to default workbuddy.json when no credential files found
- Unit tests for auto-discovery and fallback behavior
2026-09-04 08:13:38 +08:00
CangShui 818d0c223e feat: auto-disable accounts on expired/revoked auth
- Detect auth failure (HTTP 401/403, invalid token, login expired)
  during token refresh and upstream requests
- Disable the account from round-robin scheduling immediately,
  delete its credential file, and write a persistent .disabled marker
- status/runServe console shows disabled accounts with reason and
  re-login command; re-login clears the marker and restores scheduling
- Background refresher skips disabled accounts; refresh command reports
  skipped count
- Unit tests for auth-failure detection, disabled skip, marker
  persistence/restore/clear
2026-09-04 04:12:11 +08:00
4 changed files with 1101 additions and 104 deletions
+3
View File
@@ -5,6 +5,9 @@ dist/workbuddy.json
dist/*.json
last-*.json
*.json.bak
*.json.disabled
.workbuddy-*.json
workbuddy-status.json
# 本地编译产物
workbuddy-gateway.exe
+98 -6
View File
@@ -9,6 +9,7 @@
- **纯 CLI 控制**:终端内嵌 ASCII 二维码,微信 / 企业微信扫码登录;`status` / `refresh` / `serve` 子命令完成全部管理。
- **多账号池 + 轮询负载均衡**:支持同时挂载多个 CodeBuddy 账号(`-auth` 逗号分隔或 `-auth-dir` 目录),请求按轮询(round-robin)均匀分配到各账号,保持多账号额度使用一致。
- **429 频率限制自动冷却**:任一账号触发上游频率限制(HTTP 429 / code 6004)时,自动解析消息中的重置时间(如 `将在 2026-09-04 07:48:15 UTC+8 重置`),将该账号屏蔽至重置时间;冷却期间自动改用其他账号代偿,冷却到期自动恢复。
- **授权失效自动禁用**:账号授权过期、被撤销或令牌刷新失败(HTTP 401/403 / invalid token / 登录已过期)时,自动将该账号**禁止调度并删除凭据文件**,同时写入持久化失效标记;`status` / 启动日志会明确提示该账号失效原因与重新登录命令,重新 `login` 后自动恢复调度。
- **后台自动续期**:运行期间每 5 分钟检查所有账号 Token,距过期不足 15 分钟自动刷新并持久化回各自凭据文件。
- **OpenAI 兼容协议**:`POST /v1/chat/completions`(SSE 流式 + 非流式聚合)、`GET /v1/models`、`GET /health`。
- **深度思考透传规则**:仅当客户端显式请求 `reasoning_effort` 时转发;绝不强制注入,避免触发上游内容安全策略。
@@ -60,13 +61,19 @@ workbuddy-gateway serve -api-key sk-localsecret
### 配置多个账号
网关支持同时挂载多个 CodeBuddy 账号,请求按**轮询(round-robin)**方式均匀分发,保持各账号额度消耗一致。两种配置方式:
网关支持同时挂载多个 CodeBuddy 账号,请求按**轮询(round-robin)**方式均匀分发,保持各账号额度消耗一致。三种配置方式:
```bash
# 方式一:-auth 逗号分隔多个凭据文件
# 方式一(推荐):自动发现 — 把多个凭据文件放进工作目录即可,无需任何参数
# 网关启动时自动加载当前目录下所有 workbuddy*.json(如 workbuddy.json、workbuddy2.json…)
cd /opt/workbuddy-gateway
workbuddy-gateway serve -addr 0.0.0.0 -port 8317
# 启动日志会显示: 已就绪账号池: 2 个账号 (有效 2, 失效 0)
# 方式二:-auth 逗号分隔多个凭据文件
workbuddy-gateway serve -auth workbuddy.json,workbuddy-2.json,workbuddy-3.json
# 方式二:-auth-dir 指定凭据目录(自动加载目录下所有 workbuddy*.json)
# 方式三:-auth-dir 指定凭据目录(自动加载目录下所有 workbuddy*.json)
mkdir -p auths
workbuddy-gateway login -auth auths/workbuddy-1.json # 依次为每个账号扫码登录
workbuddy-gateway login -auth auths/workbuddy-2.json
@@ -91,12 +98,86 @@ workbuddy-gateway status
workbuddy-gateway refresh
```
### 授权失效自动禁用
当账号出现以下任一情况时,网关会**自动禁用该账号调度并删除其凭据文件**:
- 令牌刷新失败且返回授权类错误(HTTP 401/403、`invalid token`、`unauthorized`、`登录已过期` 等);
- 上游请求返回 401/403(token 被撤销或已过期);
- 凭据缺少 RefreshToken 且已无法刷新。
处理流程:
1. 将该账号标记为 **❌ 授权失效**,立即移出轮询调度;
2. **删除对应的凭据文件**(如 `workbuddy.json`),并写入持久化失效标记(`workbuddy.json.disabled`);
3. 控制台(`status` / 启动日志 / 运行日志)明确显示失效原因,并给出重新登录命令;
4. 失效期间其余账号正常代偿;**重新执行 login 后自动清除失效标记并恢复调度**。
```bash
# 查看失效账号与原因
workbuddy-gateway status
# 输出示例:
# --- 账号 #1 ---
# 凭据文件: workbuddy-2.json
# 用户昵称: tester
# 用户 UID: uid-xxx
# 账号状态: ❌ 授权失效(禁止调度)
# 失效原因: 令牌刷新失败 (HTTP 401): invalid token
# 处理建议: ⚠️ 凭据文件已删除,请重新执行: workbuddy-gateway login -auth workbuddy-2.json
# 失效账号重新登录后自动恢复
workbuddy-gateway login -auth workbuddy-2.json
workbuddy-gateway status # 该账号恢复为 ✅ 可用
```
### 与单账号模式的兼容性
- 不传 `-auth` 时默认使用 `./workbuddy.json`,行为与旧版完全一致;
- 不传 `-auth` / `-auth-dir` 时,自动发现当前工作目录下所有 `workbuddy*.json`;目录中只有一个凭据文件时行为与旧版完全一致;
- 只有一个账号时,请求始终使用该账号,429 冷却逻辑同样生效(冷却期间请求将返回 429 提示);
- 账号之间使用独立的串行锁:同一账号请求严格排队,不同账号可并行,兼顾风控与吞吐。
## 前台实时监控 (monitor)
网关以 systemd / 后台方式运行时,可用 **`monitor` 命令在前台实时查看所有账号的最新状态与最近日志**(Ctrl+C 退出):
```bash
# 基本用法:每 3 秒刷新展示账号池状态(可用/冷却/失效 + Token 有效期)
cd /opt/workbuddy-gateway # 必须与 serve 同一工作目录(读取 workbuddy-status.json)
workbuddy-gateway monitor
# 自定义刷新间隔(秒)
workbuddy-gateway monitor -interval 2
# 同时展示 systemd 服务最近日志(Linux)
workbuddy-gateway monitor -journal workbuddy-gateway
# 或展示指定日志文件最近内容
workbuddy-gateway monitor -logfile /var/log/workbuddy-gateway.log
# 控制每次展示的日志行数
workbuddy-gateway monitor -journal workbuddy-gateway -lines 8
```
展示内容(实时刷新):
```text
================ WorkBuddy 实时监控 ================
按 Ctrl+C 退出 | 状态文件: workbuddy-status.json
---------------------------------------------------------------
🕐 更新时间: 2026-09-04 09:35:12
📊 账号池: 共 2 个 | ✅ 可用 1 | 🔒 冷却 1 | ❌ 失效 0
#1 workbuddy.json (Abandon)
✅ 可用 | Token 有效期至: 09-10 20:43
#2 workbuddy2.json (啊水)
🔒 冷却中 至 09-05 01:57 (剩余 16h)
原因: 您的使用量已超出频率限制...
📜 最近日志 (journalctl -u workbuddy-gateway):
9月 04 09:34:31 ... [Cooldown] 账号 workbuddy2.json 触发频率限制...
---------------------------------------------------------------
```
> 原理:`serve` 后台每 3 秒(及状态变化时)将账号池实时状态原子写入同目录 `workbuddy-status.json`,`monitor` 前台读取该文件并周期刷新展示;日志通过 `journalctl` 或日志文件补充展示。
## 客户端接入
网关启动后服务地址为 `http://127.0.0.1:8317/v1`。
@@ -197,8 +278,18 @@ sudo mkdir -p /opt/workbuddy-gateway
sudo cp workbuddy-gateway /opt/workbuddy-gateway/ # 对应架构的二进制
# 首次登录(会生成 workbuddy.json)
sudo /opt/workbuddy-gateway/workbuddy-gateway login
# 登录第二个账号(可选):生成 workbuddy2.json
sudo /opt/workbuddy-gateway/workbuddy-gateway login -auth /opt/workbuddy-gateway/workbuddy2.json
```
> 💡 **多账号自动发现**:服务通过 `WorkingDirectory` 固定在 `/opt/workbuddy-gateway`,
> 无需修改 ExecStart——把多个凭据文件(`workbuddy.json`、`workbuddy2.json`…)放进该目录,
> 重启服务即自动加载全部账号组成轮询池。确认方式:
> ```bash
> sudo journalctl -u workbuddy-gateway | grep 账号池
> # 输出示例: 已就绪账号池: 2 个账号 (有效 2, 失效 0)
> ```
启用并启动服务:
```bash
@@ -267,8 +358,9 @@ ExecStart=/opt/workbuddy-gateway/workbuddy-gateway serve -addr 0.0.0.0 -port 831
## 命令行速查
```
命令: serve | login | status | refresh | version | help
选项: -addr <ip> · -port <port> · -auth <path> · -api-key <key> · -proxy <url> · -verbose
命令: serve | login | status | refresh | monitor | version | help
选项: -addr <ip> · -port <port> · -auth <path> · -auth-dir <dir> · -api-key <key> · -proxy <url> · -verbose
monitor: -interval <sec> · -journal <svc> · -logfile <path> · -lines <n>
```
## 从源码构建
+695 -98
View File
File diff suppressed because it is too large Load Diff
+305
View File
@@ -1,6 +1,8 @@
package main
import (
"encoding/json"
"os"
"testing"
"time"
)
@@ -116,3 +118,306 @@ func TestNextAccountCooldownExpiry(t *testing.T) {
}
t.Logf("expired cooldown recovers, selected %s", a.Path)
}
// 验证授权失效识别(401/403 / invalid token / 登录过期等)
func TestIsAuthFailure(t *testing.T) {
cases := []struct {
status int
body string
want bool
}{
{401, "{}", true},
{403, "{}", true},
{400, `{"msg":"invalid token"}`, true},
{400, "unauthorized", true},
{400, "登录已过期", true},
{400, "登录失效,请重新登录", true},
{400, "some other error", false},
{429, "频率限制", false},
{500, "{}", false},
}
for _, c := range cases {
if got := isAuthFailure(c.status, c.body); got != c.want {
t.Errorf("isAuthFailure(%d, %q) = %v, want %v", c.status, c.body, got, c.want)
}
}
}
// 验证轮询跳过已失效(Disabled)账号
func TestNextAccountSkipsDisabled(t *testing.T) {
accountMu.Lock()
accounts = []*Account{
{Path: "a.json", Auth: &StoredAuth{}, Disabled: true, DisabledReason: "revoked"},
{Path: "b.json", Auth: &StoredAuth{}},
}
rrIndex = 0
accountMu.Unlock()
a, _ := nextAccount()
if a.Path != "b.json" {
t.Fatalf("expected b.json (only non-disabled), got %s", a.Path)
}
t.Logf("disabled skip works, selected %s", a.Path)
}
// 验证全部失效时返回错误并提示重新登录
func TestNextAccountAllDisabled(t *testing.T) {
accountMu.Lock()
accounts = []*Account{
{Path: "a.json", Auth: &StoredAuth{}, Disabled: true, DisabledReason: "expired"},
{Path: "b.json", Auth: &StoredAuth{}, Disabled: true, DisabledReason: "revoked"},
}
rrIndex = 0
accountMu.Unlock()
_, err := nextAccount()
if err == nil {
t.Fatal("expected error when all accounts disabled")
}
t.Logf("all-disabled error: %v", err)
}
// 验证 disableAccount:标记失效、删除凭据文件、写入失效标记文件
func TestDisableAccount(t *testing.T) {
dir := t.TempDir()
authPath := dir + "/workbuddy-test.json"
// 写一个假的凭据文件
if err := os.WriteFile(authPath, []byte(`{"auth":{"accessToken":"x"}}`), 0600); err != nil {
t.Fatal(err)
}
acc := &Account{Path: authPath, Auth: &StoredAuth{
Auth: StoredTokens{AccessToken: "x"},
Account: StoredAccount{Nickname: "tester", UID: "uid-1"},
}}
disableAccount(acc, "令牌刷新失败 (HTTP 401): invalid token")
accountMu.Lock()
disabled := acc.Disabled
reason := acc.DisabledReason
accountMu.Unlock()
if !disabled {
t.Fatal("account should be marked disabled")
}
if reason == "" {
t.Fatal("disabled reason should be recorded")
}
// 凭据文件应被删除
if _, err := os.Stat(authPath); !os.IsNotExist(err) {
t.Fatalf("credential file should be deleted, stat err=%v", err)
}
// 失效标记文件应存在
if _, err := os.Stat(markerPath(authPath)); err != nil {
t.Fatalf("marker file should exist: %v", err)
}
t.Logf("disableAccount works: disabled=%v reason=%q", disabled, reason)
}
// 验证失效标记文件可被恢复为失效账号(Auth 为 nil),并提示重新登录
func TestLoadDisabledMarkers(t *testing.T) {
dir := t.TempDir()
authPath := dir + "/workbuddy-test.json"
// 构造失效标记文件
marker := disabledMarker{
Path: authPath,
Reason: "授权失效(令牌刷新失败 HTTP 401)",
DisabledAt: time.Now().Unix(),
Nickname: "tester",
UID: "uid-1",
}
data, _ := json.Marshal(marker)
if err := os.WriteFile(markerPath(authPath), data, 0600); err != nil {
t.Fatal(err)
}
// 模拟 -auth 显式指定该路径
oldAuthFile := cfg.AuthFile
oldAuthDir := cfg.AuthDir
oldAuthExplicit := cfg.AuthExplicit
defer func() {
cfg.AuthFile = oldAuthFile
cfg.AuthDir = oldAuthDir
cfg.AuthExplicit = oldAuthExplicit
}()
cfg.AuthFile = authPath
cfg.AuthDir = ""
cfg.AuthExplicit = true
accounts = nil
loadDisabledMarkers()
if len(accounts) != 1 {
t.Fatalf("expected 1 disabled account, got %d", len(accounts))
}
acc := accounts[0]
if !acc.Disabled || acc.Auth != nil {
t.Fatalf("expected disabled account with nil Auth, got disabled=%v authNil=%v", acc.Disabled, acc.Auth == nil)
}
if acc.Nickname != "tester" || acc.UID != "uid-1" {
t.Fatalf("marker nickname/uid not restored: %+v", acc)
}
t.Logf("loadDisabledMarkers restores: %s (nickname=%s)", acc.Path, acc.Nickname)
}
// 验证登录成功后清除失效标记
func TestClearDisabledMarker(t *testing.T) {
dir := t.TempDir()
authPath := dir + "/workbuddy-test.json"
marker := disabledMarker{Path: authPath, Reason: "revoked"}
data, _ := json.Marshal(marker)
if err := os.WriteFile(markerPath(authPath), data, 0600); err != nil {
t.Fatal(err)
}
clearDisabledMarker(authPath)
if _, err := os.Stat(markerPath(authPath)); !os.IsNotExist(err) {
t.Fatalf("marker file should be removed, stat err=%v", err)
}
t.Log("clearDisabledMarker works")
}
// 验证自动发现模式:未指定 -auth/-auth-dir 时,扫描当前目录下所有 workbuddy*.json
func TestCollectConfiguredAuthPathsAutoDiscover(t *testing.T) {
oldDir, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
defer os.Chdir(oldDir)
dir := t.TempDir()
if err := os.Chdir(dir); err != nil {
t.Fatal(err)
}
// 模拟目录内多个凭据文件 + 非凭据文件 + 失效标记
for _, name := range []string{"workbuddy.json", "workbuddy2.json", "workbuddy-3.json", "other.json", "workbuddy.json.disabled"} {
if err := os.WriteFile(name, []byte(`{"auth":{"accessToken":"x"}}`), 0600); err != nil {
t.Fatal(err)
}
}
oldAuthFile := cfg.AuthFile
oldAuthDir := cfg.AuthDir
oldAuthExplicit := cfg.AuthExplicit
defer func() {
cfg.AuthFile = oldAuthFile
cfg.AuthDir = oldAuthDir
cfg.AuthExplicit = oldAuthExplicit
}()
cfg.AuthFile = "workbuddy.json"
cfg.AuthDir = ""
cfg.AuthExplicit = false
paths := collectConfiguredAuthPaths()
if len(paths) != 3 {
t.Fatalf("expected 3 workbuddy json files, got %d: %v", len(paths), paths)
}
want := []string{"workbuddy-3.json", "workbuddy.json", "workbuddy2.json"} // sort.Strings 排序结果
for i, p := range want {
if paths[i] != p {
t.Fatalf("paths[%d] = %s, want %s (all: %v)", i, paths[i], p, paths)
}
}
t.Logf("auto-discover paths: %v", paths)
}
// 验证自动发现模式:目录内没有任何凭据文件时回退到默认路径
func TestCollectConfiguredAuthPathsAutoDiscoverFallback(t *testing.T) {
oldDir, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
defer os.Chdir(oldDir)
dir := t.TempDir()
if err := os.Chdir(dir); err != nil {
t.Fatal(err)
}
// 目录为空
oldAuthFile := cfg.AuthFile
oldAuthDir := cfg.AuthDir
oldAuthExplicit := cfg.AuthExplicit
defer func() {
cfg.AuthFile = oldAuthFile
cfg.AuthDir = oldAuthDir
cfg.AuthExplicit = oldAuthExplicit
}()
cfg.AuthFile = "workbuddy.json"
cfg.AuthDir = ""
cfg.AuthExplicit = false
paths := collectConfiguredAuthPaths()
if len(paths) != 1 || paths[0] != "workbuddy.json" {
t.Fatalf("expected fallback to default workbuddy.json, got %v", paths)
}
t.Logf("fallback path: %v", paths)
}
// 验证 tailLines 读取文件末尾 N 行
func TestTailLines(t *testing.T) {
dir := t.TempDir()
f := dir + "/test.log"
content := "line1\nline2\nline3\nline4\nline5\n"
if err := os.WriteFile(f, []byte(content), 0600); err != nil {
t.Fatal(err)
}
lines, err := tailLines(f, 2)
if err != nil {
t.Fatal(err)
}
if len(lines) != 2 || lines[0] != "line4" || lines[1] != "line5" {
t.Fatalf("tailLines got %v", lines)
}
t.Logf("tailLines(2) = %v", lines)
}
// 验证状态快照写入:含 active / cooldown / disabled 三种状态
func TestWriteStatusSnapshot(t *testing.T) {
oldDir, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
defer os.Chdir(oldDir)
dir := t.TempDir()
if err := os.Chdir(dir); err != nil {
t.Fatal(err)
}
accountMu.Lock()
accounts = []*Account{
{Path: "a.json", Auth: &StoredAuth{
Auth: StoredTokens{AccessToken: "x", ExpiresAt: time.Now().Add(time.Hour).Unix()},
Account: StoredAccount{Nickname: "alice", UID: "u1"},
}},
{Path: "b.json", Auth: &StoredAuth{
Auth: StoredTokens{AccessToken: "x", ExpiresAt: time.Now().Add(time.Hour).Unix()},
Account: StoredAccount{Nickname: "bob", UID: "u2"},
}, CooldownUntil: time.Now().Add(30 * time.Minute), CooldownMsg: "频率限制"},
{Path: "c.json", Disabled: true, DisabledReason: "revoked", Nickname: "carol", UID: "u3"},
}
accountMu.Unlock()
writeStatusSnapshot()
data, err := os.ReadFile(statusSnapshotFile)
if err != nil {
t.Fatal(err)
}
var snap statusSnapshot
if err := json.Unmarshal(data, &snap); err != nil {
t.Fatal(err)
}
if len(snap.Accounts) != 3 {
t.Fatalf("expected 3 accounts in snapshot, got %d", len(snap.Accounts))
}
states := map[string]bool{}
for _, a := range snap.Accounts {
states[a.State] = true
}
if !states["active"] || !states["cooldown"] || !states["disabled"] {
t.Fatalf("expected all three states in snapshot, got %v", states)
}
t.Logf("snapshot states: %v", states)
}