Files
cc-switch/tests/lib/managedAccountUsage.test.ts
e6fd4accd2 feat(codebuddy): add CodeBuddy Code support with official account switching (#8758)
* feat(codebuddy): add CodeBuddy Code custom model management

Add Tencent CodeBuddy Code (app id `codebuddy`) as an additive app. Each
provider is one entry of ~/.codebuddy/models.json (the provider key is the
model id; CODEBUDDY_CONFIG_DIR is honored). Other models, availableModels and
unknown keys are preserved, the file is written atomically with 600
permissions, a new model is appended to a non-empty availableModels, and the
default model selected in settings.json cannot be removed. models.json must
stay strict JSON because CodeBuddy ignores the whole file otherwise.

Global prompts are written to CODEBUDDY.md. The form offers Chat Completions
and Responses protocols, token limits and capability flags, with DeepSeek,
Xiaomi MiMo and LongCat presets from their CodeBuddy guides.

MCP and Skills sync are not wired yet: they need enabled_codebuddy columns
(a schema change), so CodeBuddy's own MCP config and skills directory are
never written. Sessions, usage import and local routing are not supported.

* style(codebuddy): align provider form with shared form components

Build the CodeBuddy form from the same parts as the Kimi, MiniMax Code and
Pi forms: ApiKeySection (get-key link, partner hint), EndpointField for the
url, ModelInputWithFetch so the model id can be picked from the endpoint's
/models list, Checkbox capability rows, REQUIRED_LABEL asterisks, the
`grid grid-cols-2 gap-3` field pairs, numeric token inputs and the shared
preset category labels.

Reuse providerForm.apiEndpoint, drop the now unused CodeBuddy-specific URL
and API key strings, and word the remaining copy like the other apps'
(duplicate/locked ID hints, capability names, empty state). Translate the
Turkish strings that were left in English.

Show CodeBuddy with its own icon (from lobe-icons) instead of the Tencent
logo, and label it "CodeBuddy Code" in the app config like the sidebar.

* style(codebuddy): match the WorkBuddy field order and vendor label

API key now comes before the request URL (as in WorkBuddy and the
OpenCode-style forms), the API format and vendor fields take a full row
each, and the vendor field uses the same label as WorkBuddy.

* style(codebuddy): lay out the provider editor like Kimi, Pi and OpenCode

The model is now a single Kimi-style row (expand arrow, model ID, display
name) under a models heading with a "?" hint; token limits and
capabilities (now switches) live in the expanded details. Fields follow
the Kimi order (API format, API key, URL, vendor label), the API format
menu shows readable protocol names, and the model-list fetch moves to
the models heading with a dropdown beside the model ID.

The model ID is still the card key: editable with fetch on create,
locked on edit, with the duplicate and whitespace checks kept below the
row. The display name column is the models.json name, i.e. the same
value as the Name field. Picking a fetched model fills blank token
limits and turns on image/reasoning from presets and models.dev.

Labels duplicated by opencode keys are removed from all locales.

* style(codebuddy): reuse the Kimi capability labels like WorkBuddy

Tool use / image input / thinking now come from kimi.capabilities, so the
three OpenAI-compatible model editors share one wording. The duplicate
codebuddy.supports* keys are removed from all locales.

* style(codebuddy): match Kimi's model row columns

The display name column is optional in Kimi's header, so drop its
asterisk, and keep a delete-column-wide gap at the end of the row so the
model ID and display name line up with Kimi's rows.

* feat(codebuddy): add enabled_codebuddy MCP and Skill flags (schema v23)

Schema v22 -> v23 adds `enabled_codebuddy BOOLEAN NOT NULL DEFAULT 0` to
mcp_servers and skills, in both the create statements and the migration.
McpApps / SkillApps gain a `codebuddy` field mapped by the DAOs, and MCP
deep links accept `codebuddy`. Projection into CodeBuddy's own files
follows in the next commits.

Migration tests cover a fresh database and upgrades from v22 (a minimal
table and a full v22 schema), keeping existing flags and defaulting the
new column to disabled.

* feat(codebuddy): sync MCP servers to CodeBuddy Code's user config

CodeBuddy reads exactly one user-scope MCP file: the first that exists of
<config>/.mcp.json, <config>/mcp.json (deprecated) and ~/.codebuddy.json
(legacy), without merging, and `codebuddy mcp add -s user` writes to the
same file (verified in the 2.164 CLI and the docs). CC Switch follows the
same rule, so an existing mcp.json keeps being used instead of a new
.mcp.json shadowing the user's servers. CODEBUDDY_CONFIG_DIR is honored.

Entries are written with an explicit type (stdio / http / sse); native
fields such as defer_loading and tools, disabledMcpServers, the legacy
file's projects map and the user's own servers are preserved. Writes are
atomic and roll back with the database. CodeBuddy accepts JSONC, but like
models.json a file with comments or trailing commas is never rewritten;
import still reads it and maps disabledMcpServers to a disabled flag.

The MCP panel and form get a CodeBuddy Code column.

* feat(codebuddy): include CodeBuddy Code in unified Skill sync

Skills are now projected into ~/.codebuddy/skills (CODEBUDDY_CONFIG_DIR
aware) like any other app, replacing the previous exclusion. As with Kimi
and Qwen, the directory is protected as a native one: unselected entries
installed outside CC Switch are never removed, and enabling a skill over a
foreign directory with the same name is refused without touching files or
flags. The Skills panel and import dialog show CodeBuddy Code.

* feat(codebuddy): browse CodeBuddy Code sessions and import their usage

Sessions are read from <config>/projects/<sanitized cwd>/<sessionId>.jsonl.
The reader shows user and assistant messages, reasoning as thinking blocks,
function calls paired with their results, and per-request model/token
meta; injected user messages (providerData.isMeta, e.g. task reminders) and
bookkeeping events are hidden. Titles come from ai-title, else the first
prompt, else the first reply (teammate sessions start from a channel
message). Resume uses `codebuddy --resume <id>` with CODEBUDDY_CONFIG_DIR
carried over. Deletion is refused like Kimi / Qwen / MCode: background
jobs, teammates and file history refer to the transcript, and CodeBuddy
has no command that removes one consistently.

Usage import records one request per (messageId, stepSeq): the step's
usage sits on the assistant message, or on its first function call when
the step only calls tools. Main and subagents/*.jsonl transcripts are
read incrementally by byte offset with permanent dedup receipts.
rawUsage.prompt_tokens includes cache hits, so rows store fresh input
(prompt - cache read - cache write) with cache read/write kept apart;
completion_tokens already includes thinking tokens. The usage page and
session filter list CodeBuddy Code.

* docs(readme): mark CodeBuddy Code MCP, Skills, sessions and usage as supported

* style(codebuddy): use the monochrome CodeBuddy mark

The colour tile stood out next to the other app icons; the monochrome
lobe-icons mark follows currentColor like most of them.

* fix(codebuddy): drop the custom-local: prefix from session model ids

CodeBuddy records custom models as custom-local:<id> in requestModelId, so
usage rows showed the prefixed id and never matched a price. Strip any
custom-*: prefix so sessions and usage use the configured model id.

* refactor(codebuddy): drop the API format menu, target Chat Completions only

Custom CodeBuddy models only need OpenAI Chat Completions. The endpoint
hint, placeholder and model-list base now assume the full
/chat/completions URL. An existing entry's api field is no longer edited
by the form but is kept on save and stays visible in the JSON editor.

* feat(codebuddy): collect and switch CodeBuddy Code official accounts

CodeBuddy keeps one global sign-in in
CodeBuddyExtension/Data/Public/auth/Tencent-Cloud.coding-copilot.info.
CC Switch now keeps a private copy of each account (codebuddy_accounts.json,
0600, not synced), keyed by account.uid + auth.domain, and exposes it as
the codebuddy_oauth provider of the generic auth_* commands.

- Accounts are added by collecting the current sign-in, or by opening a
  terminal running codebuddy for /login and collecting the file once it
  turns into a new account or session. No OAuth of our own.
- Switching takes the shared proper-lockfile style directory lock, pulls
  the live file back into its copy first (CodeBuddy refreshes tokens
  itself), writes the target via temp file + fsync + rename at 0600,
  drops the logged-out marker and reads the file back to verify.
- Unrecognized content such as WorkBuddy's $wbEncrypted envelope is
  stashed byte-for-byte and never overwritten.
- Removing an account only drops CC Switch's copy.

* feat(codebuddy): manage CodeBuddy accounts in the Auth Center

A CodeBuddy Code group in the Auth Center lists saved official accounts
(nickname, China / international site, UID), collects the signed-in
account, opens a terminal for /login and picks the new sign-in up
automatically, and switches the active account. Running CodeBuddy sessions
follow the switch on their own.

* fix(codebuddy): launch the login terminal with the resolved codebuddy path

A stale version-manager shim (mise reported 'codebuddy is not a valid
shim') made the terminal login fail even with CodeBuddy installed. Resolve
the executable through the tool search paths, preferring a real install over
shims, and put its directory first on PATH so the node shebang resolves to
the same install.

* feat(codebuddy): query plan and credits for CodeBuddy accounts

New codebuddy_account_quota command returns an account's plan name and
this cycle's credits (total / remaining / used). It uses the access token
in that account's saved copy, after absorbing the live sign-in file, and
makes a single read-only query against the account's own site
(auth.domain): POST /billing/meter/get-user-resource-summary for personal
accounts, POST /v2/billing/meter/get-enterprise-user-usage for enterprise
ones, with the same Authorization / X-User-Id / X-Domain / X-Product
headers CodeBuddy sends.

Tokens are never refreshed: an expired access or refresh token, or a 401,
comes back as refresh_pending / expired instead. Only known CodeBuddy
domains get a token, nothing about credentials is logged, requests time
out after 10 seconds, and successful results are cached per account for
5 minutes unless forced.

* feat(codebuddy): show plan and credits on Auth Center account rows

Each CodeBuddy account row now carries the same quota column as Codex and
Antigravity accounts: the plan name, a credits bar and the remaining (or
used, per the quota display setting) credits, with the full breakdown on
hover. Expired or not-yet-renewed tokens show why the quota is missing;
the refresh button skips the backend cache. Strings added for zh, zh-TW,
en, ja and tr.

* feat(codebuddy): official sign-in cards bind an account and never enter models.json

- codebuddy_config: is_official_provider / official_account_id (authBinding codebuddy_oauth)
- ProviderService: add/update/save skip live writes for official cards; switch and
  remove-from-live reject them; delete only drops the row; validation skipped
- write_live_snapshot refuses official cards as a last guard
- new command codebuddy_account_switch_provider: switch CodeBuddy's sign-in to the
  account bound on an official card (reuses switch_to)

* feat(codebuddy): switch official accounts from CodeBuddy official sign-in cards

- new preset "CodeBuddy Official Sign-in" (category official): the form picks one
  collected account (site, plan and credits, in-use mark), can sign in through the
  terminal or collect the current sign-in, and binds it in meta.authBinding
  (codebuddy_oauth); the card name defaults to the account name
- provider list: official cards get their own single-choice section with an
  In use status or a Switch button; a removed / expired / unbound account disables
  Switch with the reason; custom model cards keep Add / Remove
- card shows the bound account and its credits, or asks to choose again when the
  account was removed
- locales for zh / zh-TW / en / ja / tr

* feat(codebuddy): Auth Center manages CodeBuddy accounts, switching moves to the provider list

- drop the Switch item from the CodeBuddy group (ManagedAccountsGroup.onSetDefault
  becomes optional); keep collect, terminal sign-in, remove, nickname, credits and
  the CodeBuddy-in-use mark
- help text points to the CodeBuddy official sign-in card; expired note no longer
  talks about switching; remove the unused switchTo / switched strings

* feat(codebuddy): sign in to a new account while CodeBuddy is already signed in

- starting a terminal sign-in collects the current login, then (under the
  shared directory lock) writes CodeBuddy's logout marker atomically with an
  ISO timestamp, so the CLI goes straight to its sign-in screen; the
  credential file is never touched and no server endpoint is called
- cancelling the sign-in (or timing out, or starting another one) removes the
  marker only if it is still the one CC Switch wrote; if the lock is held the
  flow is kept so the restore can be retried
- no lock or marker when CodeBuddy is not signed in, already signed out, or
  holds an unrecognized (WorkBuddy-encrypted) file
- tests in temp dirs: marker written, credentials untouched, restore removes
  only our marker, lock blocks both write and restore

* feat(codebuddy): official sign-in cards join Added / Available with one added at a time

- no separate official section: the card whose account CodeBuddy is signed in
  to sits in Added, every other official card in Available
- Add on an official card switches CodeBuddy to its account (switch_to, same
  rules); the previous card drops back to Available automatically
- Remove on the added official card is disabled with a hint (CodeBuddy only
  holds one sign-in; add another official card to switch), it never signs out
- removed / expired / unbound accounts keep Add disabled with the reason;
  official cards still never reach models.json, model cards are unchanged

* feat(codebuddy): sign in to a new account from the official card form and the Auth Center

- shared useCodebuddyLogin: when CodeBuddy is signed in, Sign in to new account
  first confirms the side effect (running sessions show as signed out until the
  new sign-in finishes), then starts the terminal sign-in; when not signed in
  it opens the terminal directly
- while waiting, Restore original sign-in cancels the flow and the backend
  removes its logout marker; hidden once the new account is detected
- the official card form selects the account the sign-in landed on
  (useManagedAuth gains onLoginComplete and an awaitable cancel)
- Auth Center Add account / Sign in again use the same flow
- locales zh / zh-TW / en / ja / tr; drop the unused Switch / Official sign-in
  section strings

* refactor(codebuddy): drop Remove all accounts from the Auth Center group

CodeBuddy accounts are removed one at a time; the group menu and the
backend remove-all path are gone.

* test(codebuddy): wait for the card name to follow the new sign-in

* feat(codebuddy): manage the CodeBuddy Code CLI from the Apps page backend

- codebuddy joins VALID_TOOLS: version probe, npm registry latest version,
  install (npm i -g @tencent-ai/codebuddy-code@latest) and uninstall via
  the npm package table
- update runs `codebuddy update || <npm fallback>` on POSIX and Windows:
  the CLI's updater never prompts, pins npm to the running copy's prefix,
  handles pnpm / bun / native builds, and exits 1 when it cannot update
- anchored update: npm installs chain to the sibling npm; a native build
  outside node_modules uses `<bin> update` alone

* feat(codebuddy): CodeBuddy Code row on the Apps page

- the row follows Antigravity CLI, matching the sidebar order, with
  install / update / uninstall and the show-in-sidebar switch
- one-click install commands and the manual npm uninstall command
- tests: row order, update and install of CodeBuddy Code, hiding it from the
  sidebar, and keeping it on when it is the last visible app

* test(codebuddy): account for Oh My Pi in the Apps and session filters

Oh My Pi now sits right before CodeBuddy Code on the Apps page, and the
session app filter gains a 13th source.

* fix(codebuddy): handle the note quota state added on main

* fix(codebuddy): keep CodeBuddy adds serialized under the native provider lock

#9098 moved the per-app lock out of the add path into lock_native_provider_operations, which only lists MCode, Kimi and DSH. CodeBuddy shares the user-chosen key check, so add it to the list to keep adds, edits, deletes and list refreshes serialized.

* feat(i18n): add Korean and Russian CodeBuddy translations

Translate the 58 CodeBuddy keys for ko and ru so locale parity holds after
merging main, and move the Turkish CodeBuddy keys to their en.json positions.

* fix(codebuddy): do not offer Duplicate on CodeBuddy cards

A CodeBuddy card's key is the models.json model id sent upstream and is
locked in the editor, so a duplicated "<id>-copy" card was written to
models.json as a model the upstream does not serve and could only be
deleted. Hide Duplicate on CodeBuddy model and official sign-in cards and
guard handleDuplicateProvider for any other caller.

* fix(codebuddy): reset fetched models when the API type or preset changes

The fetched model list was already dropped and in-flight requests
invalidated when the URL or API key changed; also key the reset on the
api field and the selected preset, and cover the reset and the stale
response with tests.

* fix(codebuddy): re-sign-in, usage query, sub-agent usage, MCP enable and stale logout marker

- Auth Center re-sign-in on a CodeBuddy account runs a normal terminal sign-in
  instead of being rejected as targeted re-authentication; capture replaces
  the old copy by uid + site.
- Usage query on model cards reads the entry's url / apiKey, dropping the
  trailing /chat/completions on both the frontend and the backend resolver.
- Sub-agent transcripts are attributed to the parent session, so the session
  reader header includes their tokens and cost.
- Enabling an MCP server in CC Switch also drops its id from the native
  disabledMcpServers list, so CodeBuddy actually loads it.
- The logout marker written for a terminal sign-in is recorded on disk; on
  startup a marker that is still ours is removed, restoring the previous
  sign-in after CC Switch quit mid-login.

* docs(readme): list CodeBuddy Code in zh-TW, ko, tr and ru; drop unrelated test formatting

* test(msw): answer codebuddy_account_live in the shared handlers

Since #9578 a request without a handler fails the test. Auth Center's
CodeBuddy section reads the local login as soon as it opens, which the Kimi
and DeepSeek dialog tests now hit.

* chore(codebuddy): follow upstream app caps and knip rules

Declare the new plugins capability as false for CodeBuddy, and drop the
default exports of CodebuddyAccountSection and CodebuddyOfficialAccountField:
both are imported by name and knip flags the default as a duplicate.

* fix(codebuddy): skip unreadable stored rows when importing native MCP servers

Since #9767 get_all_mcp_servers() fails on any unreadable row, so one
corrupt or newer-version server would make the CodeBuddy import (and the
import from all apps) fail. Read the rows like the other importers and
skip an unreadable id instead of re-creating it.

Also cover the CodeBuddy id aliases in the stream check app id test.

* fix(codebuddy): official preset subtitle, managed account usage tracking, and refresh-all quota

---------

Co-authored-by: allenxu09 <s23372.xu@stu.scie.com.cn>
Co-authored-by: funkpopo <funkpopoisme@gmail.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-11-24 00:11:02 -08:00

216 lines
6.0 KiB
TypeScript

import { describe, expect, it } from "vitest";
import type { Provider } from "@/types";
import {
findManagedAccountUsers,
groupUsersByApp,
} from "@/lib/managedAccountUsage";
const provider = (
id: string,
extra: Partial<Provider> = {},
settingsConfig: Record<string, unknown> = {},
): Provider =>
({
id,
name: id,
settingsConfig,
...extra,
}) as Provider;
const byId = (...list: Provider[]) =>
Object.fromEntries(list.map((p) => [p.id, p]));
describe("findManagedAccountUsers", () => {
const claude = byId(
// 指定了 a1
provider("bound-a1", {
meta: {
providerType: "github_copilot",
authBinding: {
source: "managed_account",
authProvider: "github_copilot",
accountId: "a1",
},
},
}),
// 旧字段 githubAccountId 指定了 a2
provider("legacy-a2", {
meta: { providerType: "github_copilot", githubAccountId: "a2" },
}),
// 没指定:跟着默认账号
provider("follows-default", { meta: { providerType: "github_copilot" } }),
// 没写 providerType 的旧卡按地址认
provider(
"by-url",
{},
{ env: { ANTHROPIC_BASE_URL: "https://api.githubcopilot.com" } },
),
// 别的服务
provider("xai", { meta: { providerType: "xai_oauth" } }),
// 普通供应商
provider("plain", {}, { env: { ANTHROPIC_BASE_URL: "https://x.test" } }),
);
it("counts bound providers and default followers for the default account", () => {
const users = findManagedAccountUsers("github_copilot", ["a1"], "a1", {
claude,
});
expect(users.map((u) => [u.providerId, u.viaDefault])).toEqual([
["bound-a1", false],
["follows-default", true],
["by-url", true],
]);
});
it("counts only bound providers for a non-default account", () => {
const users = findManagedAccountUsers("github_copilot", ["a2"], "a1", {
claude,
});
expect(users.map((u) => u.providerId)).toEqual(["legacy-a2"]);
});
it("collects every provider when removing all accounts", () => {
const users = findManagedAccountUsers(
"github_copilot",
["a1", "a2"],
"a1",
{ claude },
);
expect(users.map((u) => u.providerId)).toEqual([
"bound-a1",
"legacy-a2",
"follows-default",
"by-url",
]);
});
it("finds bound Grok cards without counting the CLI's own login", () => {
const grokbuild = byId(
provider("grok-bound", {
category: "official",
meta: {
authBinding: {
source: "managed_account",
authProvider: "xai_oauth",
accountId: "x1",
},
},
}),
provider("grok-cli", { category: "official" }),
);
const users = findManagedAccountUsers("xai_oauth", ["x1"], "x1", {
grokbuild,
});
expect(users.map((u) => [u.appId, u.providerId, u.viaDefault])).toEqual([
["grokbuild", "grok-bound", false],
]);
expect(groupUsersByApp(users)).toEqual([
{ appId: "grokbuild", names: ["grok-bound"] },
]);
});
it("does not count an unbound Codex official card (it uses Codex's own login)", () => {
const codex = byId(
provider(
"codex-official",
{ category: "official", meta: { providerType: "codex_oauth" } },
{ auth: {}, config: "" },
),
provider(
"codex-managed",
{
category: "official",
meta: {
providerType: "codex_oauth",
authBinding: {
source: "managed_account",
authProvider: "codex_oauth",
accountId: "c1",
},
},
},
{ auth: {}, config: "" },
),
);
const desktop = byId(
provider("desktop-chatgpt", { meta: { providerType: "codex_oauth" } }),
);
const users = findManagedAccountUsers("codex_oauth", ["c1"], "c1", {
codex,
"claude-desktop": desktop,
});
expect(users.map((u) => [u.appId, u.providerId])).toEqual([
["claude-desktop", "desktop-chatgpt"],
["codex", "codex-managed"],
]);
expect(groupUsersByApp(users)).toEqual([
{ appId: "claude-desktop", names: ["desktop-chatgpt"] },
{ appId: "codex", names: ["codex-managed"] },
]);
});
});
describe("findManagedAccountUsers — WorkBuddy", () => {
it("counts official sign-in cards bound to the account, never via default", () => {
const card = (id: string, accountId: string) =>
provider(id, {
category: "official",
meta: {
authBinding: {
source: "managed_account",
authProvider: "workbuddy_account",
accountId,
},
},
});
const workbuddy = byId(
card("wb-a", "u-1"),
card("wb-b", "u-2"),
provider("custom"),
);
const users = findManagedAccountUsers("workbuddy_account", ["u-1"], "u-1", {
workbuddy,
});
expect(users.map((u) => [u.appId, u.providerId, u.viaDefault])).toEqual([
["workbuddy", "wb-a", false],
]);
expect(groupUsersByApp(users)).toEqual([
{ appId: "workbuddy", names: ["wb-a"] },
]);
});
});
describe("findManagedAccountUsers — CodeBuddy", () => {
it("counts official sign-in cards bound to the account, never via default", () => {
const card = (id: string, accountId: string) =>
provider(id, {
category: "official",
meta: {
authBinding: {
source: "managed_account",
authProvider: "codebuddy_oauth",
accountId,
},
},
});
const codebuddy = byId(
card("cb-a", "100@www.codebuddy.cn"),
card("cb-b", "200@www.codebuddy.ai"),
provider("custom"),
);
const users = findManagedAccountUsers(
"codebuddy_oauth",
["100@www.codebuddy.cn"],
"100@www.codebuddy.cn",
{ codebuddy },
);
expect(users.map((u) => [u.appId, u.providerId, u.viaDefault])).toEqual([
["codebuddy", "cb-a", false],
]);
expect(groupUsersByApp(users)).toEqual([
{ appId: "codebuddy", names: ["cb-a"] },
]);
});
});