From c2fd48782b63bcc0d2b9cf6030ecdaf26d86fd3e Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 13 Nov 2026 12:18:23 +0800 Subject: [PATCH] Put back what 1f05c311d took out of main by mistake 1f05c311d was committed with its worktree's older tree on top of a fresh origin/main (git reset --soft), so beside the memory fix it undid every file 610ae1f54..c1312ac15 changed (45 files: key balance, import links, project subagents, uninstall, site, LESSONS.md and more). This commit restores each of them to c1312ac15 byte for byte; the tree is now c1312ac15 plus the memory fix alone (git diff --stat c1312ac15 HEAD: the 4 files of the fix). --- LESSONS.md | 6 + build/darwin/Info.plist | 4 + docs/subsystems/library.md | 2 +- docs/subsystems/providers-accounts.md | 2 +- internal/agent/pimagpie.go | 4 +- internal/cli/key_balance_cli.go | 2 +- internal/cli/key_balance_cli_test.go | 9 + internal/cli/providers_cli.go | 2 +- internal/gui/assets/i18n.js | 8 + internal/gui/assets/keybalance.js | 6 +- internal/gui/assets/plugins/library/client.js | 57 +++- internal/gui/assets/plugins/library/i18n.js | 36 ++ .../gui/assets/plugins/library/library.css | 4 + internal/gui/importlink.go | 8 +- internal/gui/importlink_test.go | 8 + internal/gui/library.go | 2 + internal/gui/scheme_linux.go | 41 ++- internal/gui/scheme_linux_test.go | 76 ++++- internal/gui/scheme_other.go | 2 +- internal/gui/scheme_windows.go | 38 ++- internal/gui/tests/key-own-balance.test.cjs | 27 +- internal/gui/tests/library-plugins.test.cjs | 15 +- internal/gui/tests/project-subagents.test.cjs | 125 +++++++ internal/library/project_scope.go | 20 +- internal/library/project_subagents.go | 213 ++++++++++++ internal/library/project_subagents_test.go | 188 +++++++++++ internal/library/projects.go | 32 +- internal/library/subagents.go | 3 + internal/library/sync.go | 4 +- internal/provider/importccswitch.go | 312 ++++++++++++++++++ internal/provider/importccswitch_test.go | 167 ++++++++++ internal/provider/importurl.go | 16 +- internal/provider/key_balance_own.go | 33 +- internal/provider/key_balance_own_test.go | 58 +++- internal/provider/testdata/ccswitch_links.txt | 14 + internal/uninstall/system_linux.go | 24 +- internal/uninstall/system_windows.go | 13 +- internal/usage/heat_digest_disk.go | 195 +++++++++++ internal/usage/heat_digest_disk_test.go | 97 ++++++ internal/usage/heat_disk.go | 12 +- site/files.js | 42 ++- site/files.test.mjs | 39 +++ site/public/docs/import.html | 1 + site/public/docs/ja/import.html | 1 + site/public/docs/zh/import.html | 1 + site/public/install.sh | 10 + site/public/llms-full.txt | 2 + 47 files changed, 1892 insertions(+), 89 deletions(-) create mode 100644 internal/gui/tests/project-subagents.test.cjs create mode 100644 internal/library/project_subagents.go create mode 100644 internal/library/project_subagents_test.go create mode 100644 internal/provider/importccswitch.go create mode 100644 internal/provider/importccswitch_test.go create mode 100644 internal/provider/testdata/ccswitch_links.txt create mode 100644 internal/usage/heat_digest_disk.go create mode 100644 internal/usage/heat_digest_disk_test.go diff --git a/LESSONS.md b/LESSONS.md index 42057d4e1..65006f90b 100644 --- a/LESSONS.md +++ b/LESSONS.md @@ -1308,6 +1308,12 @@ each one. - A record that points elsewhere: 2f34649a6's body is "Run: see push notes", and 8f82e08b4's "(see below)" has nothing below it; neither says whether what it ran passed. A pointer is not a record (10-14). + - The eager-regexp guard, red twice more: 1ca2c62c4 (catalog, fixed + in 19fd0dfb8) and d52e2feaf (agent, whose record is one -run in + ./internal/agent; fixed in 6a506e283). TestNoEagerPackageRegexps + lives in the root package, so a run of the changed package never + reaches it. A new package-level regexp is lazyre.New, and `go test + .` runs beside the package's own. - **Done right on 10-17.** The retire stack (0f1666b38 to de671719a) diffed staticcheck's U1000 against its base for dead code, b98f906b1 was red on the old code for an own-account gap, and 8 subscriptions diff --git a/build/darwin/Info.plist b/build/darwin/Info.plist index 62296b9c2..8cd2090b3 100644 --- a/build/darwin/Info.plist +++ b/build/darwin/Info.plist @@ -20,6 +20,10 @@ CFBundleURLNamecom.yetone.magpie.import CFBundleURLSchemesmagpie + + CFBundleURLNamecom.yetone.magpie.ccswitch + CFBundleURLSchemesccswitch + NSHumanReadableCopyrightyetone diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 6ff302355..62e689286 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -22,7 +22,7 @@ Pi's extensions and packages. | Targets | `Targets` lists the detected agents (`agent.Detected`), a folder an agent shares with its vendor's other app when only that app is here (`agent.SharedHere`: the Cursor editor's `~/.cursor`, whose `mcp.json` and skills it reads, listed as Cursor; `TestCursorEditorAloneKeepsItsLibraryRow`), plus apps like Claude Desktop, with where each keeps its instructions file (and an `Override` it reads instead), its MCP file and its skills folder. An agent whose CLI is gone (`CLIMissing`: an uninstall that left the folder behind, #2177, #2254) is no target: it is given nothing it can't read. One that isn't a target but still has skills, servers or hooks magpie gave it (in `Applied`, or listed in an item's `Agents`) is held (`held`, a `Target` with `Gone`): a sync takes edits from its copies and then only takes out of it (`syncSkills`, `syncMCP` and `syncHooks` give a gone target nothing new), and `Read` lists it with `gone: true` while it has any. On a row, an agent's profiles (`hermes#name`, `omp#name`, `claude#name`, `qwenpaw#id`, WSL ones included) are one chip with a count, when an agent has more than one (`profileChip` in plugins/library/client.js, Yanzhongixuy on X: about twenty identical Hermes glyphs on every skill row); a click opens the app menu to pick profiles singly, and All still means every profile (`library-profile-chip.test.cjs`). A repository's, part's or pick's heading folds them the same way (`groupChips` sets `change.rows`; its chip is half lit when a profile has some of the skills), and the profiles chip takes part in the row's fan like any other (`[data-members]` in library.css), so the hand stays in line (Yanzhongixuy on X, 0.1.3926; `library-profile-group.test.cjs`). The page shows a gone agent's chip only on the rows of what it has, lit, so a click takes it out (`withGone` in plugins/library/client.js), leaves it out of All, the per-agent How sheet and every picker, and lists it in By agent as Not installed here with Turn all on off (@jiahao_jayden on X: an uninstalled WorkBuddy was on every skill's row; `TestGoneAgentListedToTakeOut`, `library-gone-agents.test.cjs`). On a Mac WorkBuddy and WorkBuddy AI are detected by their apps' bundle ids (`com.tencent.workbuddy.mac`, `com.workbuddy.workbuddy-ai`, `macBundle`), not by `~/.workbuddy`, which an uninstall leaves and magpie itself writes into (`TestWorkBuddyOnMacIsItsApp`); off a Mac the folder still counts. `everyTarget` keeps it for the guards that refuse an agent's own places: a project folder whose skills folder or MCP file is the agent's, and an instruction set kept in its instructions file. An agent in a running WSL distro has its places under the distro's home (`wslTargetOf`): Claude Code, Codex, Pi, OmO, Gemini CLI, Antigravity CLI, Crush, Cline, CodeBuddy Code, Kimi Code and Goose each by its own rule, never reading this machine's variables (Kimi Code's and Goose's shared `~/.agents/skills` there isn't given), Pi's MCP file chosen by `piMCP` as on this machine from the version the distro's `pi --version` gave its probe (`InstalledVersion`) and the distro's npm folders (`wslPiRoots`; leokon on Discord: only the Windows Pi was offered MCP servers, `TestWSLPiMCP`, `TestWSLMCPSiblings`), and every agent that keeps all of them in its own folder (Hermes Agent, omp, OpenCode, Droid and the rest of `ownFolder`, #1323) by the same rule as on this machine, its MCP file marked as WSL's so a Windows program isn't given to it. A place below a folder the distro has as a link is opened where the link leads (`wslOpen`, agent-wiring's WSL folders that are links, #4502); a link the distro couldn't resolve gives that agent one `wsl` problem and nothing is written to it (`TestWSLFolderIsALinkToC`, `TestWSLFolderLinkUnresolved`). An agent a plugin adds (`a.Plugin`) has the places its plugin's `agent.library` names (`pluginTarget`): an instructions file, an MCP file in one of `agentplug.MCPFormats` (each the `mcpFormat` of the agent it is named for, `pluginMCP`) and a skills folder, `~` and `$VAR` expanded as its config is; one that names none is no target. Before, a plugin's agent got models and keys only. Every built-in agent is a target or is in `noLibrary` with why: OpenBot was added with neither and was in no picker (SSNQT on X), so `TestEveryAgentInLibrary` fails a new agent until it gets one (34 were in no picker when it landed, listed there under #5897). | [`targets.go`](../../internal/library/targets.go) | | Stopped WSL distro | A stopped distro's agents are no targets: opening their files would start the distro, or the read fails (#3896). While a distro runs, `keepShape` keeps each agent's places and what its MCP file takes in `wsl.json` (`agent.WSLKeep`, key `library:`). While it is stopped, `Read` lists its agents from that (`asleepView`, `asleep: `), ticks as library.json has them; one magpie never saw there is listed only on the rows that name it, as `unseen`, its ticks not shown (cybercaius on Discord: the MCP page knew a distro's agents only once WSL had started). A tick on a stopped agent is kept in library.json as any is (`Takes` accepts one with a known shape; `serversAgents` judges it by `shape.reaches`), nothing is written and nothing in the distro runs; `Woken`, from `KeepLinked`'s loop (and the app's start-up sync), syncs when a distro the library names is seen go from stopped to running (`wsl.exe -l --running`, which starts nothing). The page greys a stopped agent's chip, says so in its tooltip and in one line per distro (`.lib-asleep`); an unseen chip is `aria-disabled` and kept by every click on its row (`keptOf`). The CLI says the same on stderr (`AsleepIn`). Queued, not a start button: a start costs the memory #3896 is about, and All or a bulk tick would start every distro. The Instructions page lists them too (`asleepInstructions`, #4182), at the instructions file the shape keeps, switched on as library.json has them, with what each gets besides (magpie's own folder) and nothing read from the file: its own lines and edits aren't counted then, and its path is plain text, not a reveal, which would open the distro. One switched on whose file magpie never saw is listed as `unseen`, its switch greyed out and kept by every other switch; before, a switch on the page sent the agents without the stopped distro's and took them off. A switch on one is written by `Woken`, which watches a distro named in `Instructions.Agents`, or whose agent still has magpie's part (`Applied.Instructions`), so one switched off has it taken out. The Hooks page lists the stopped agents with a shape as it does while the distro runs (`hooksView`, #4237): greyed, since magpie gives no agent in WSL hooks yet (`wslNoHooks`), and a hook given one says so; there is nothing for `Woken` to write. So does the Subagents page for the kinds it lists (`subagentsView`, `wslNoSubagents`, #4238). | [`wsl_asleep.go`](../../internal/library/wsl_asleep.go), [`targets.go`](../../internal/library/targets.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) | | Sync | `sync` writes each target's instructions and MCP servers. It then takes edits made in agents' skill copies into the library (`takeEdits`) and links or copies the skills. `~/.agents/skills` goes first (`sweepShared`, then `syncShared` for the Put skills in setting), so an agent that reads it gets no second link. Then it syncs projects' skills. | [`sync.go`](../../internal/library/sync.go) | -| Projects | A project (`Project`) is a folder given some of the library's skills and MCP servers, each for some agents. A skill is linked (or copied) into the folder the agent reads a project's skills from (`projectSkillsDirs`): `.claude/skills` for Claude Code, `.qoder/skills` for Qoder and Qoder CN, `.codebuddy/skills` for CodeBuddy Code, `.commandcode/skills` for Command Code, and `.agents/skills` for Codex, Gemini CLI, OpenCode, Pi, Cursor, Copilot CLI, Antigravity, Kimi, Goose, Grok, Droid, Cline and DeepSeek Harness (which reads it, and `.dsh/skills`, at the nearest folder up with a `.git`, else where it runs: a project folder inside a repository but not at its root doesn't reach it, #5172). A server is written into the file the agent reads a project's servers from (`projectMCPFiles`), in the shape its user-wide file has: `.mcp.json` for Claude Code and CodeBuddy Code (CodeBuddy's `mcp.json` when the project has that and no `.mcp.json`, since it reads only the first of the two), `.codex/config.toml`, `.gemini/settings.json`, `.cursor/mcp.json`, `opencode.json`, `.zcode/config.json`, `.pi/mcp.json`, `.qoder/settings.json`'s `mcpServers` for Qoder and Qoder CN, and `.factory/mcp.json` for Droid. Claude Code, Qoder and CodeBuddy ask the user to approve a project's server before using it. Only targets whose vendor source or docs name them are listed (each map's comment cites them); an agent with none (Copilot CLI's MCP, Zed, WorkBuddy, Command Code's MCP, whose `.mcp.json` has its own `transport` shape, DeepSeek Harness's MCP, whose servers are rows in its profiles' patch layers with no project layer) can't be picked for a project (eirc on Discord). `Placed`, `Wrote`, `Made` and `MadeFiles` record what magpie put there, the only things it takes away. Nothing of magpie's goes into the project's git: what it placed is listed in the repository's own `info/exclude` (`writeExclude`, one block per project between `excludeBegin(dir)` and `ignoreEnd`, read by every worktree, never committed), and the project's `.gitignore` is left as it is (a block an older magpie wrote there is taken out, `TestProjectKeptOutOfGitByExclude`). A folder outside git gets no ignore file; once it is `git init`ed, `treesChanged` sees no block and the next `KeepLinked` writes it (`TestProjectOutsideGit`). A project is the global set ± its own (WhyULose0 on X): `ServersOff` and `SkillsOff` turn a global server or skill off in the project for some agents (`ProjectServerOff`, `ProjectSkillsOff`; `POST /api/library/projects/server-off` and `skill-off` with `dir`, `name`/`names`, `agents`; none gives it back). Each is done the way the agent reads it for a folder (`project_scope.go`): Claude Code's record of the project in `~/.claude.json` (`projects[
]`, `claudeRoot`) gets the name in `disabledMcpServers`, where magpie takes out only names it added (`Claude.Off`); Codex gets `[mcp_servers.] enabled = false` in the project's `.codex/config.toml`, only for a server in its own config (`CodexOff`); a skill is `skillOverrides. = "off"` in the project's `.claude/settings.local.json` (`Overrides`), a value the user set there is theirs (`TestProjectServerOff`, `TestProjectSkillOff`). Only those (`ProjectOffAgents`, `ProjectSkillOffAgents`) can take an off, and a skill an agent reaches through the [skill router](skill-router.md) can't; the card shows a global agent that can't as always on, with why. With the [MCP router](mcp-router.md) on, a project that adds or turns off a server the router serves gives Claude Code and Codex their own hub entry, `~` (`projectHubs`): Claude Code's in its record's `mcpServers` (local scope), Codex's in the project's `.codex/config.toml`; the server added isn't written into `.mcp.json` then (`TestProjectSetThroughRouter`). Claude Code keys its record by the repository's main top folder, so a project in a subfolder turns its offs on for the whole repository. A git worktree of the project's repository follows the project (`treeDirs`, `Trees`): the project's folder in each worktree gets the same skills, servers and offs, and is let go when the worktree is removed; `KeepLinked` checks for new ones (`keepProjectTrees`, `TestProjectWorktreeFollows`). `magpie library project …` (#5193, [`library_project_cli.go`](../../internal/cli/library_project_cli.go)) adds and removes a project and its skills through the same calls as the page (`AddProject`, `RemoveProject`, `ProjectSkills`, `ProjectSkill`, `ProjectCopy`); a skill added with no `agents=` goes to the agents the page's Skills menu picks (those the project's skills are for already, else every agent here with a project skills folder), and one not placed exits 1 with why (`TestLibraryProjectCmd`). A project card's Skills menu lists the skills by source as the Library does (`skillGroups(true)`, whatever sort the list has; one group is the flat list), a heading over each that ticks or unticks the whole group (`group` in `openProtoMenu`, half-ticked while some are in; Elorynth on X, `project-skills-groups.test.cjs`). | [`projects.go`](../../internal/library/projects.go), [`project_mcp.go`](../../internal/library/project_mcp.go), [`project_scope.go`](../../internal/library/project_scope.go), [`project_git.go`](../../internal/library/project_git.go) | +| Projects | A project (`Project`) is a folder given some of the library's skills and MCP servers, each for some agents. A skill is linked (or copied) into the folder the agent reads a project's skills from (`projectSkillsDirs`): `.claude/skills` for Claude Code, `.qoder/skills` for Qoder and Qoder CN, `.codebuddy/skills` for CodeBuddy Code, `.commandcode/skills` for Command Code, and `.agents/skills` for Codex, Gemini CLI, OpenCode, Pi, Cursor, Copilot CLI, Antigravity, Kimi, Goose, Grok, Droid, Cline and DeepSeek Harness (which reads it, and `.dsh/skills`, at the nearest folder up with a `.git`, else where it runs: a project folder inside a repository but not at its root doesn't reach it, #5172). A server is written into the file the agent reads a project's servers from (`projectMCPFiles`), in the shape its user-wide file has: `.mcp.json` for Claude Code and CodeBuddy Code (CodeBuddy's `mcp.json` when the project has that and no `.mcp.json`, since it reads only the first of the two), `.codex/config.toml`, `.gemini/settings.json`, `.cursor/mcp.json`, `opencode.json`, `.zcode/config.json`, `.pi/mcp.json`, `.qoder/settings.json`'s `mcpServers` for Qoder and Qoder CN, and `.factory/mcp.json` for Droid. Claude Code, Qoder and CodeBuddy ask the user to approve a project's server before using it. Only targets whose vendor source or docs name them are listed (each map's comment cites them); an agent with none (Copilot CLI's MCP, Zed, WorkBuddy, Command Code's MCP, whose `.mcp.json` has its own `transport` shape, DeepSeek Harness's MCP, whose servers are rows in its profiles' patch layers with no project layer) can't be picked for a project (eirc on Discord). `Placed`, `Wrote`, `Made` and `MadeFiles` record what magpie put there, the only things it takes away. Nothing of magpie's goes into the project's git: what it placed is listed in the repository's own `info/exclude` (`writeExclude`, one block per project between `excludeBegin(dir)` and `ignoreEnd`, read by every worktree, never committed), and the project's `.gitignore` is left as it is (a block an older magpie wrote there is taken out, `TestProjectKeptOutOfGitByExclude`). A folder outside git gets no ignore file; once it is `git init`ed, `treesChanged` sees no block and the next `KeepLinked` writes it (`TestProjectOutsideGit`). A project is the global set ± its own (WhyULose0 on X): `ServersOff` and `SkillsOff` turn a global server or skill off in the project for some agents (`ProjectServerOff`, `ProjectSkillsOff`; `POST /api/library/projects/server-off` and `skill-off` with `dir`, `name`/`names`, `agents`; none gives it back). Each is done the way the agent reads it for a folder (`project_scope.go`): Claude Code's record of the project in `~/.claude.json` (`projects[
]`, `claudeRoot`) gets the name in `disabledMcpServers`, where magpie takes out only names it added (`Claude.Off`); Codex gets `[mcp_servers.] enabled = false` in the project's `.codex/config.toml`, only for a server in its own config (`CodexOff`); a skill is `skillOverrides. = "off"` in the project's `.claude/settings.local.json` (`Overrides`), a value the user set there is theirs (`TestProjectServerOff`, `TestProjectSkillOff`). Only those (`ProjectOffAgents`, `ProjectSkillOffAgents`) can take an off, and a skill an agent reaches through the [skill router](skill-router.md) can't; the card shows a global agent that can't as always on, with why. With the [MCP router](mcp-router.md) on, a project that adds or turns off a server the router serves gives Claude Code and Codex their own hub entry, `~` (`projectHubs`): Claude Code's in its record's `mcpServers` (local scope), Codex's in the project's `.codex/config.toml`; the server added isn't written into `.mcp.json` then (`TestProjectSetThroughRouter`). Claude Code keys its record by the repository's main top folder, so a project in a subfolder turns its offs on for the whole repository. A git worktree of the project's repository follows the project (`treeDirs`, `Trees`): the project's folder in each worktree gets the same skills, servers and offs, and is let go when the worktree is removed; `KeepLinked` checks for new ones (`keepProjectTrees`, `TestProjectWorktreeFollows`). A project also takes the library's subagents (jinpwng on X; `Subagents`, `AgentFiles`, [`project_subagents.go`](../../internal/library/project_subagents.go)): one file per subagent in the folder the agent reads a project's subagents from (`projectSubagentDirs`, cited per agent in its comment): `.claude/agents` for Claude Code, `.codex/agents`, `.opencode/agents`, `.gemini/agents`, `.qwen/agents`, `.factory/droids` for Droid, `.cursor/agents` and `.github/agents` for Copilot, in that agent's own format. A file is recorded with its hash (`SubagentFile`) and rewritten or removed only while it is exactly as magpie wrote it, so a same-name file of the user's is never touched (`TestProjectSubagentsLeaveTheUsersFiles`); a subagent renamed in the library is renamed in each project (`TestProjectSubagentsFollowTheLibrary`); the files are kept out of git by the same `info/exclude` block and follow the project's worktrees. `POST /api/library/projects/subagents` with `dir`, `name`/`names`, `agents`; the Subagents tab lists the projects as Skills and MCP do (`project-subagents.test.cjs`). It has no CLI yet, like project servers. Hooks, instructions and Claude plugins have no project scope yet. `magpie library project …` (#5193, [`library_project_cli.go`](../../internal/cli/library_project_cli.go)) adds and removes a project and its skills through the same calls as the page (`AddProject`, `RemoveProject`, `ProjectSkills`, `ProjectSkill`, `ProjectCopy`); a skill added with no `agents=` goes to the agents the page's Skills menu picks (those the project's skills are for already, else every agent here with a project skills folder), and one not placed exits 1 with why (`TestLibraryProjectCmd`). A project card's Skills menu lists the skills by source as the Library does (`skillGroups(true)`, whatever sort the list has; one group is the flat list), a heading over each that ticks or unticks the whole group (`group` in `openProtoMenu`, half-ticked while some are in; Elorynth on X, `project-skills-groups.test.cjs`). | [`projects.go`](../../internal/library/projects.go), [`project_mcp.go`](../../internal/library/project_mcp.go), [`project_scope.go`](../../internal/library/project_scope.go), [`project_git.go`](../../internal/library/project_git.go) | | Instructions | magpie's part of an agent's instructions file sits between two marker lines. The rest of the file is the user's. Several named sets can be switched between (#106). A set can be kept in a file of the user's own instead of `instruction-sets/` (`InstrSet.File`, 新v学员 on Discord): `~/.agents/AGENTS.md`, which Droid and omp read too. `textPath` reads it, `putText` keeps it aside and writes it but never removes it, removing the set lets go of it, and `linkable` refuses a file magpie writes into (an agent's own instructions, a file with the marker line), the library's own and another set's. The app's `KeepLinked` looks at the file every 30 s and writes a change into the agents (`SyncLinked`). A set's text is read without magpie's part (`setText`), and an agent whose instructions file is, links followed, the file the set on is kept in (`isSetFile`: `instructions.md` linked to `~/.claude/CLAUDE.md`, or both linked to one dotfile) gets no part written into it, and one written before is taken out with every part nested in it: read with its part, each sync wrote the whole file into that part again and it doubled, to gigabytes (#2349, `TestInstructionsSetLinkedToAgentsFile`). `Collect` carries the set's text, not where its file is; `Put` keeps this computer's file for the set and never empties it for a text not carried. Alma's file is `~/.config/alma/USER.md`, which its main chat reads into its system prompt as its owner's profile (0.4.164's `out/main/index.js`; a workspace's `USER.md` is read instead), and whose leading front matter (`name`, `telegram_id`, `discord_id`) is who its bots answer to (#2315, Jie211). The target is a `Profile`: magpie's part goes after the user's, so the front matter stays first, and `ImportInstructions` refuses it, as moving it out would take that front matter out of the file and into every agent's (`TestAlmaInstructionsKeepTheProfile`, `TestAlmaProfileIsNotImported`, `library-alma-profile.test.cjs`). MiniMax Code reads `AGENTS.md` in its data folder (`$MINIMAX_DATA_DIR`, else `~/.minimax`) before every conversation, so its target is that file (`TestMiniMaxCodeInstructions`). WorkBuddy and WorkBuddy AI keep theirs as a string in a JSON file: `personalization.customPrompt` in `app/app-config.json` of their folder, the Custom Instructions of the app's Personalization settings (`Target.Field`, `instr_field.go`). magpie's part goes into that string between the same marker lines, after the user's own prompt, and a `Field` write goes through `edit.SetJSON`, so every other key, its order and its indentation stay as the app wrote them; taking the part back leaves the file as it was, the field (and a `personalization` object nothing else is in) going out when it holds nothing. A file that is not JSON, or a field that holds something other than text, is unknown: it is reported and written over by nothing (`TestWorkBuddyInstructionsAreAJSONField`, `TestWorkBuddyInstructionsFromNothing`, `TestWorkBuddyInstructionsUnreadFileIsLeftAlone`, `TestWorkBuddyInstructionsImport`). The app's config service loads the file as it starts and writes it whole on a save (`AppConfigService`, 5.5.6's app.asar), so a change made while it runs may need a restart of the app, and may be lost to its next save of any setting; this has not been tried against a running app. | [`instructions.go`](../../internal/library/instructions.go) | | MCP servers | A `Server` is a command or a URL (`http`, `sse`). `mcpFile` encodes it in each agent's own format (one `mcpFormat` per agent family) and merges it with the user's own fields for that entry. A server's `StartupTimeout` (#3168) goes to Codex alone, as `startup_timeout_sec` in seconds (`RawMcpServerConfig` in codex-rs/config's mcp_types.rs; 0 leaves Codex's own 30s), in the user-wide config.toml and a project's alike. magpie keeps the value it wrote (`Applied.Startup`, `Project.Startup`): one in the entry other than that, or a `startup_timeout_ms`, is the user's and stays as it is (`startupTheirs`), and once it is taken out magpie's goes in again. The editor shows the field only when an agent that takes it is here (`AgentView.Startup`, `mcp_startup_test.go`, `mcp-startup-timeout.test.cjs`). `Also` files get the same servers; `Extra` files are only read when importing. `CheckServers` connects as an agent would and keeps the result in memory only: with each tool's name and the first paragraph of its description (`ToolList`, at most `maxToolList`, a description cut at `maxToolDesc` runes), which the page lists when the server's "N tools" is clicked, following tools/list's `nextCursor` up to `maxToolPages` pages (`listTools`). Each step (initialize, notifications/initialized, tools/list; connect for SSE) has its own budget, 60s for a URL and 30s for a command (`remoteStep`, `stdioStep`), and a timeout names its `Step` and how long it `Waited`; a timeout isn't kept, so the next look asks again (#1467). A command named bare that magpie's PATH lacks is started from where `proc.FindTool` finds it (fnm's Nodes on Windows among the folders), with that folder on the check's PATH, since npx's package runs the node beside it by name (`stdioProgram`, #2685, `TestStdioProgramFindsWhatPathLacks`). The page asks once a session for the servers some agent or project has (`inUse` in plugins/library/client.js); one no agent has shows "not checked" and is checked only when its status is clicked (#1597, `library-mcp-health.test.cjs`). A server checked once is checked again when it changes, its sign-in included, so a server signed in to after a click's "needs sign-in" isn't left showing both (新v学员 on Discord, `mcp-signin-health.test.cjs`). The check sends magpie's sign-in as the gateway does: on a 401 it renews the token once and asks again, and a server that refuses even the renewed token has the sign-in marked run out (`mcpauth.Rejected`, also from the gateway's `/mcp/`), which `ServerHealth.SignIn` carries back so the row's tag says "Sign-in ran out" rather than "Signed in" beside "needs sign-in". A server that refuses the check (401 or 403) but that an agent signed in to on its own is named so (`ServerHealth.AgentSignIn`, `readOwnSignIns` in `mcp_agent_signin.go`): each Claude Code target's `.credentials.json` beside its settings.json, a WSL distro's under the distro's home, is read for a `mcpOAuth` entry of the server's name and URL with a token, and each Codex target's `.credentials.json` beside its config.toml for a flattened entry of them, the file codex-rs falls back to when its config's `mcp_oauth_credentials_store` is `file` or the keyring is missing, whose executor's own entries are no `codex mcp login` (#3508); and the row says "signed in in Claude Code (Ubuntu)" — or Codex — instead of "needs sign-in" (CyberCaius on Discord: signed in to with Claude Code's /mcp in WSL). The tokens are never sent or kept; a file that can't be read or parsed names nobody, a stopped distro isn't started for it, and on a Mac only the file is read, never the Keychain Claude Code keeps them in nor Codex's keyring store. They are part of the check's key, so a sign-in in the agent since is checked anew (`TestCheckNamesAgentsSignedInThemselves`, `library-mcp-health-wsl.test.cjs`). A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/` (#615). The editor's Sign in saves the form first only when the sign-in is to another server than the saved one (a new server, a name or URL changed), and its button then reads "Save and sign in"; anything else edited (headers, env, arguments) stays unsaved until Save, so Cancel leaves the server as it was (新v学员 on Discord, `mcp-editor-cancel.test.cjs`). A server whose authorization server refuses magpie's dynamic client registration with 401 or 403 admits only the clients it lists (Figma's, #1619): the sign-in fails with `mcpauth.ErrClientRefused`, which says so and that each agent signs in itself, and the agents keep the server's own address. A server whose authorization server has no registration endpoint at all (GitHub's remote server, 新v学员 on Discord) fails with `mcpauth.ErrNoRegistration`, which says to make an OAuth app with the vendor and give it in the editor; the editor then opens its "OAuth app" fields. The app is the server's `oauth` (`OAuthApp`: `clientId`, `clientSecret`, `callbackPort`, Claude Code's names for `--client-id`, `--client-secret` and `--callback-port`), checked on save (HTTP only, a client ID, a port from 1 to 65535), and `SignInServer` signs in as it through `mcpauth.StartWith` without registering. The callback is Claude Code's, `http://localhost:/callback` (its docs' "Use pre-configured OAuth credentials"; 2.1.296 builds it so), listened for on 127.0.0.1 alone as Claude Code does, so an app made for Claude Code signs magpie in as it is; a server that matches the registered URL exactly refuses another host, which is why Claude Code's 2.1.231 went back to `localhost` from 2.1.229's `127.0.0.1` (`TestAppMadeForClaudeCode`). Without a `callbackPort` the port is any free one, which a loopback callback registered without a port takes (GitHub's, RFC 8252); a fixed `callbackPort` is for a vendor that matches the port too. magpie's own registration, when a server has one, still names `127.0.0.1`. The client secret is kept in library.json, as a header's or env's value is: a backup without keys leaves it out, and `WithSecrets` puts back this computer's secret only for the same client ID; no agent is given the app, and the TUI's editor, which doesn't show it, keeps it. GitHub answers a token request's error with a 200 and `error` in the body (`bad_refresh_token`, `incorrect_client_credentials`), which `tokenRequest` reads as the error it is, and a dead refresh token marks the sign-in run out (`github_app_test.go`, `mcp-oauth-app.test.cjs`). magpie never registers under another client's name; one that reaches the gateway from another machine (a WSL distro under NAT) is given it with the LAN sharing key as its `Authorization` (`agent.KeyAt`), as its models are, which the gateway takes in place of a sign-in and never passes on; turning sharing on or off, or a new key (`access.LANChanged`), writes such entries again. `ConfigOfServers` is the servers picked as an agent's project file (`projectMCPFiles`) would hold them, written by the same code into a folder of its own and read back, with those the agent can't take there named; the page's Copy config… puts it on the clipboard for a project magpie doesn't keep (#1478). The editor's command is a box that wraps, so a long line is read whole, and Enter still saves it (hema_17384 on Discord). Its Form | JSON switch shows the server as JSON in Claude Code's `.mcp.json` shape, the one Copy config… gives for it (`jsonOf` in plugins/library/client.js), with `${NAME}` references as written. An edit there is read as a paste is (`serversIn`) and becomes the form's at once. JSON that isn't one server's keeps the dialog from saving or going back to the form, and counts as unsaved. The note, the agents and sync stay in the form (`library-mcp-json.test.cjs`). A server's and a skill's `Note` (youyo.p_10001 on Discord) is the user's own word on what it is for: one line of at most `maxNote` (200) characters, whitespace run together (`checkNote`), as a hook's description is. The row shows it in place of the command or description, and its tooltip still gives that line. The skills' filter reads it too. A sync carries it (a server whole, a skill as `CarriedSkill.Note`), and no agent is given it, through the MCP router or not (`TestNoteNeverGiven`, `TestNoteCarried`). A skill's is set by itself (`SkillNote`, `skills/note`) from the skill's reader. Each listed tool has a switch: the tools turned off are the server's `DisabledTools`, set by `ServerTools`, and written into each agent given the server that can leave out a single tool (see the constraint below). A server run as `npx -y args` (a registry package, no other npx flag) is given to an agent on this machine as `node args` (`npxDirect`): magpie installs the package with npm into a folder of its own under `mcp-npm` in the background, the next sync writes the node form, and until then, or when npm fails (tried again after an hour), the agent keeps npx. npx otherwise stays as the server's parent for its whole life, a node and two cmd.exe beside each instance on Windows (#3885). An unpinned spec is installed again after a day, as npx would fetch the newer one; an install no library server runs goes a day after its last. The library, a server's check, Copy config… and agents in WSL keep npx (`TestNpxServerRunsByNode`, `TestReadNpx`). A remote server holds several accounts (Elorynth on X), one in use that every agent is given: sets of headers are `Server.Accounts` with `Server.Account` the one in use ("" is the server's own `Headers`), laid over `Headers` by `live` in `through`, `remoteHeaders` and `hubKey`, so a switch rewrites each agent's file (`TestServerAccountsSwitchEveryAgent`); a save from the editor, which doesn't send them, keeps them, and a backup carries no account's key (`TestServerAccountKeysAreSecrets`). magpie's OAuth sign-ins are `mcpauth` records, the one in use at `m[name]` and the others in `Spare` (`Use`, `RemoveAccount`, `StartAccount`), which the gateway's `/mcp/` sends from its next request on; an agent's existing upstream `Mcp-Session-Id` isn't reset by a switch. API `/api/library/mcp-account`; GUI `headerAccounts` and `acctList` (`mcp-accounts.test.cjs`). | [`mcp.go`](../../internal/library/mcp.go), [`mcp_npx.go`](../../internal/library/mcp_npx.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go), [`mcp_agent_signin.go`](../../internal/library/mcp_agent_signin.go), [`mcp_copy.go`](../../internal/library/mcp_copy.go), [`mcp_tools_off.go`](../../internal/library/mcp_tools_off.go) | | MCP server on/off | `ServerOn` (`POST /api/library/servers/on` with `name` and `on`, `magpie library mcp off|on `) turns a server off for everyone without removing it (swang20201 on X, Docker gateway mode, where a server ticked for no agent is still given to every app at the MCP router's address). Off, it is `Hidden` with its agents kept in `Paused` and `Agents` empty, as a plugin's server hidden from agents is (`PluginServerOn`, [Plugin tools](plugin-tools.md)): no agent's file has it, no project's (`syncProjectMCP` skips it, keeping the project's own agents for it), no subagent names it (`renderSubagent`), the router lists and calls it for nobody, and a process the router held for it ends, since `Hidden` and `Paused` are part of its `hubKey`. Its command, URL, env, headers, sign-in, `DisabledTools` and note stay in library.json. On, the agents in `Paused` get it back (none when it had none, so the router gives it to other apps again), as before it was turned off; giving it agents (`ServerAgents`, the CLI's `mcp agents`) turns it on with those (`save`), while Turn all on (`EveryServerAgents` with every agent) leaves it off. The row's switch sits after its agent chips (`serverSwitch` in plugins/library/client.js); off, the row is dimmed, its chips take no click, and it is health-checked only on a click (`TestServerOnKeepsAndRestores`, `TestLibraryMCPOffOn`, `library-mcp-on.test.cjs`). | [`mcp_on.go`](../../internal/library/mcp_on.go), [`project_mcp.go`](../../internal/library/project_mcp.go), [`subagents.go`](../../internal/library/subagents.go) | diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index bbc7e7d94..fa3ec7b09 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -420,7 +420,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`. - A usage cap is kept per account (`AccountCaps`, 1–99) and, beside it, per window (`AccountWindowCaps`, by the account and the window's `capId`, its name in lower case: `WindowCapID`). A window's own share wins over the account's; 100 is no cap on that window. `CapsOf` gives both (`WindowCaps`), `CapHeld` and `capReached` judge each window by its own, and `SetWindowCap` (GUI `provider/windowcap`, `magpie provider account-cap --window `) sets one; `SetWindowCaps` sets several at once, as the GUI's meter for a family of models (Antigravity's Gemini 3.1 Pro, High and Low) posts its models' windows in `windows`. An Antigravity pool's own windows ("Gemini · 7 days") are set aside for routing but capped (`WithCapped`, `capId` the pool's name and its own, as `LineName`): `allowanceOf` hangs each on its members' windows (`Limit.pool`), and `CapHeld` and `NearCap` count them through `capLimits`, so a cap on one holds that pool's models only (pluviophile714 on Discord, `TestPoolWindowCapHeld`). A window counted in a unit with its total (`QuotaWindow.Amount`, `Limit`, `Unit`: WorkBuddy's credits, a plan's requests) can instead be capped at a fixed amount of that unit (`AccountWindowAmounts`, by account and `capId`; 9won_25273 on Discord). `SetWindowAmount` (GUI `provider/windowcap` with `amount` in place of `cap`, the meter's menu's Amount…, typed in place) sets it, 0 lifts it; a window has a share of its own or an amount, never both, and setting one clears the other. `limitShare` makes the amount a share of the window's total for marks and `NearCap`, while `CapHeld` and `capReached` hold the account once the count reaches the amount (`past`); `CapHold` and the trace carry `Amount`, `Count` and `Unit`, and `cappedError` says "has used 300 credits … past its cap of 300". A reading with no total leaves the amount aside and the account's share applies. Every cap reads the vendor's own count of the window, so what the account spent outside magpie (the vendor's app, another machine) counts toward it as the vendor reports it, from the next reading on; magpie can only hold back its own requests (`TestWindowAmountCapHeld`, `TestSetWindowAmount`, `window-cap.test.cjs`). A config without window caps reads as before. A key of a provider whose windows magpie reads (`TakesUsageCap`) has the same caps, by its key id (GUI `provider/accountcap` and `windowcap` with the key's id, `magpie provider account-cap`), kept when `ReplaceKey` changes the key's value; `KeyInfo.UsageCap` and `CapHeld` give its row's pill and held note (`TestKeyTakesUsageCap`, `key-usage-cap.test.cjs`). How a pool ends at its caps is kept with the provider (plugins#349): `CapStop` answers 429 rather than going on to the fallbacks once every account in use is at its cap, and `CapCareful` reads usage again near a cap and holds an account whose usage can't be told (both off by default; within 5 points of its cap an account takes one turn at a time whatever they say, [gateway routing](gateway-routing.md); `SetCapStop`, `SetCapCareful`, GUI `provider/capstop` and `provider/capcareful`, ticks under the account list once an account has a cap). `UsageRead` says when an account's usage was last read well and whether the last try failed (a failed try keeps the good reading's time), and `ReadUsageNow` reads it again. `magpie provider pool [--accounts a,b,…] [--cap percent|off] [--stop on|off] [--careful on|off]` shows and sets the whole pool in one command: which accounts are on and in what order, each one's cap, and both settings, and names the accounts in use with no cap. - A wallet's window, one that tells only what is left (`QuotaWindow.Balance`, no share and no total: AStudio's 通用积分 and 星火积分, SuperMagic's points), has its spend counted by magpie ([`wallet_spend.go`](../../internal/provider/wallet_spend.go), #5770, 9won on Discord: an account capped at 4 spent over 1,000 credits past it, since the wallet read 0% used until it was empty). Each reading a plugin's usage gives (`pluginLoginQuota` → `withWalletSpend`) is set against the one before: a fall is spent, a rise (a top-up, a daily grant) is not. The count runs over the window's own period when it tells a reset, else the local day, and starts at 0 at the period's first reading; what was spent before it, or between one period's last reading and the next's first, isn't known and isn't counted. Each window carries it as `spent` and `spentSince`. On an account with a usage cap (`WindowCaps.Holds`) the window reads as `amount` spent of `limit`, what the period had (spent plus what is left), and `used` that share, so a cap by share holds it in routing and on the GUI's row as it holds any window; without a cap the window is its balance alone, and routing goes by that (`Allowance.Left`). A cap set is judged from the next reading on. The counts are kept in `wallet-spend.json` beside providers.json, by provider, account and window, a period over for a week dropped; one that can't be read starts each count again. `holdsBounds` leaves a wallet out of a window's holds (no whole). `TestWalletSpendCounted`, `TestWalletCapHolds`, `TestPluginWalletCapHolds`. - A key's spend cap (`KeySpendCaps`, by the key's fingerprint, [`key_spend.go`](../../internal/provider/key_spend.go); sparkling_lemur_62868 on Discord: a team's OpenAI key whose granted credits other services spend from too) is how much magpie may spend on an API key, in USD, per calendar day or month in local time, or in all since it was set (`Since`, kept while the cap stays one in all, its amount changed or not). What counts is what the Usage page prices magpie's own calls on the key at (`usage.KeySpent`: records whose `ProviderKeyID` is the key, not turned away, not reported by an app; the log is read once and each new call added by `Append`, read again after 5 minutes), not the vendor's bill: a model with no known price counts nothing, and requests under way when it is reached still finish, so the key can go a little past it. At or past the cap the gateway passes the key over ([gateway routing](gateway-routing.md)). Only a key has one: `SetKeySpendCap` refuses a subscription, an amount not above 0 or over `MaxSpendCap` (1,000,000) and a period it doesn't know. `ReplaceKey` carries it to the new value. Set from the key's row in the editor (a pill: "$7.50 of $20.00 today", the app's menu, then the amount typed in place, drawn by `keyspend.js`, which app.js imports when it draws a key's row; GUI `provider/keyspendcap`, `key-spend-cap.test.cjs`) or `magpie provider spend-cap [key [usd [day|month|total]|off]]`, which also lists each key's spend. `TestKeySpendCapSet`, `TestSpendCapWindow`, `TestParseSpendCap`, `TestKeySpentCountsTheKeysCalls`, `TestSpendCapCmd`. -- A key's balance typed by hand (`KeyOwnBalances`, by the key's fingerprint: `{usd | cny, at, refill, expirings}`, [`key_balance_own.go`](../../internal/provider/key_balance_own.go); tenacious_eagle on Discord) is for a key whose vendor tells no balance magpie can read (`TakesOwnBalance`: an API key with no balance source, not Cline's or OpenCode Zen's, not on a plan's windows). The user types what the vendor's page says is left; the key's card on the Usage page and the tray then shows it less what the Usage page prices magpie's own calls on the key at since then (`usage.KeySpent` from `at`, through the `provider.KeySpent` hook usage sets), as `≈$12.50` with `Estimate` (`set`, `at`, `spent`) and below nothing as `≈$-2.00`. Typing it again counts from then. It is an estimate, not a reading: it is kept out of the balance history (no trend or runs-out), is never shared, and routing reads nothing from it; a low-balance alert reads its number. A balance the vendor tells always wins: with a Balance URL or a source magpie knows the card is the vendor's, and a relay whose query is looked for shows the typed one only when none is found (`errNoBalance`); the typed value stays saved as the user left it. `SetKeyOwnBalance` (GUI `provider/keyownbalance`, a pill in the key's row, "≈$12.50 left" or "Set balance", drawn by `keybalance.js` while `takesOwnBalance` and no balance was found; `magpie provider key-balance [key [usd|¥cny|off] [--refill …]]`) refuses a subscription, an amount outside ±`MaxOwnBalance` (1,000,000) in either currency (below 0 is a key the vendor let run past its balance, so typed as it reads: -1.84, -$1.84; AlanWang1027713 on X), and any currency but USD and CNY; nil takes it off, `ReplaceKey` carries it to the new value, and saving the editor keeps it. It may be typed in yuan (`cny`, "¥100", or a bare number with ¥ CNY picked in the currency button beside the field, which starts at the balance's own currency, else Settings' one; picking keeps the number typed and posts nothing until the field is left or Enter is pressed, so a balance's currency changes without clearing it or going to Settings, tenacious_eagle on Discord): what is spent is counted in USD and turned into yuan at `fx.Known()`, the rate `internal/fx` last fetched (cached 12h in `fxrate.json`, fetched again in the background, never on the request path); `fx.Known` never hands out `fx.Fallback`, so with no rate fetched yet and something spent the left is unknown (`left` null, the card's `Error` says why) rather than a guess. It may refill (`refill`: `{every: month, day: 1–31}`, a day past the month's end meaning its last, or `{every: week, day: 1 Monday–7 Sunday}`), at midnight in the user's local time: nothing is stored on a refill; the spend is counted from the last refill boundary after `at` (`From`), and `Next` is the next one. Typing the amount again keeps the refill. `SetKeyBalanceRefill` (GUI `provider/keybalancerefill`, the pill's menu: Refills each month…, Refills each week…, Never refills; CLI `--refill monthly[:day]|weekly[:mon…sun]|off`) refuses a key with no balance. Part of it may expire, in grants (`expirings`: a list of `{amount, until, at}`, up to `MaxExpiring` (20), each amount in the balance's currency, `until` the last day it counts as 2006-01-02, `at` when it was typed; tenacious_eagle_96548 on Discord: money that stays and promotional credit twice, one good until tomorrow and one the day after). Grants are spent first, as DeepSeek spends its granted balance before the money topped up, and of them the one that ends soonest first (`spendGrants`): the spend is taken piece by piece over the times between `From`, now, and each grant's `at` and end (midnight after `until`, local time), each piece going to the live grant that ends first, and only what grants took after `From` is off the rest, so a refill or typing the balance again doesn't count it twice. `left` is the whole balance, the grants' remainders included; from a grant's end its remainder counts no more (`expired`, the latest such end), and unspent credit is simply gone. A grant whose end is at or before `From` is dropped on the next write (`liveGrants`). `AddKeyExpiring` (GUI `provider/keyexpiring` `{expiring: {amount, until}}`), `RemoveKeyExpiring` (`{expiring: {at, until}, remove: true}`, matched by `at`, else by `until` and the amount when given; nothing matched is an error) and `ClearKeyExpiring` (`{expiring: null}`) edit them. The pill's menu has Add credit that expires…, which opens one small form (`.abal-form`, the app's popover, no native control but the date field) with the amount, in the balance's currency, and the last day, a month ahead to begin with: Add or Enter saves, Escape or a click outside leaves it, an amount in the other currency or a day gone by is refused with the form kept; then a Remove {amount} for each grant with when it goes beside it, and No credit that expires with two or more, or one that expired. The CLI takes `--expiring amount@yyyy-mm-dd` and `--expiring-remove [amount@]yyyy-mm-dd`, each as often as wanted and applied in order after the balance, every value read before anything is written; `--expiring off` takes every grant off. Each refuses a key with no balance typed (type the rest first, 0 when all of it expires), an amount not above 0 or past `MaxOwnBalance`, and a date that isn't one. A v0.1.3305 balance's one `expiring` object is read as the first grant (`UnmarshalJSON`) and saved as `expirings` on the next write; a magpie before this reads `expirings` as no grant, so going back loses them from the estimate, not from the file until it writes. Typing the balance again keeps the grants in the same currency and drops them in the other, where its amount would mean another sum. A balance saved before has none and is counted as it was. The estimate's `expiring`, one per grant soonest first (`set`, `at`, `until`, `left`, `ends`), is the pill's "≈$60.00 left · $5.00 expires tomorrow · $20.00 expires in 30 days" (wrapping at a grant on a narrow row), and the card's `BalanceSplit` a line each with `expires`, which the Usage page and the panel label "Expires in 30 days" (`expiresIn` in app.js), amber from a week; the TUI and CLI quota say "$20.00 until Dec 31" (`SplitWords`). Each key with one gets `balance` in `/api/providers`' `keyList` (`set`, `at`, `spent`, `currency`, `rate`, `left`, `from`, `refill`, `next`, `expiring`, `expired`). `TestTypedBalanceExpires`, `TestTypedBalanceSavedBeforeExpiring`, `TestTypedBalanceGrantsSoonestFirst`, `TestTypedBalanceGrantsEdited`, `TestTypedBalanceOneGrantMigrated`, `TestExpiringParsed`, `TestExpiringDayParsed`, `TestKeyBalanceCmd`, `key-balance-expiring.test.cjs`, `TestKnownIsNeverAGuess`, `TestTypedBalanceInYuan`, `TestTypedBalanceRefills`, `TestRefillDays`, `TestTypedBalanceCountsDown`, `TestToldBalanceWinsOverTyped`, `TestOwnBalanceParsed`, `TestKeyOwnBalanceRoutes`, `key-own-balance.test.cjs`. +- A key's balance typed by hand (`KeyOwnBalances`, by the key's fingerprint: `{usd | cny, at, refill, expirings}`, [`key_balance_own.go`](../../internal/provider/key_balance_own.go); tenacious_eagle on Discord) is for a key whose vendor tells no balance magpie can read (`TakesOwnBalance`: an API key with no balance source, not Cline's or OpenCode Zen's, not on a plan's windows). The user types what the vendor's page says is left; the key's card on the Usage page and the tray then shows it less what the Usage page prices magpie's own calls on the key at since then (`usage.KeySpent` from `at`, through the `provider.KeySpent` hook usage sets), as `≈$12.50` with `Estimate` (`set`, `at`, `spent`) and below nothing as `≈$-2.00`. Typing it again counts from then. It is an estimate, not a reading: it is kept out of the balance history (no trend or runs-out), is never shared, and routing reads nothing from it; a low-balance alert reads its number. A balance the vendor tells always wins: with a Balance URL or a source magpie knows the card is the vendor's, and a relay whose query is looked for shows the typed one only when none is found (`errNoBalance`); the typed value stays saved as the user left it. `SetKeyOwnBalance` (GUI `provider/keyownbalance`, a pill in the key's row, "≈$12.50 left" or "Set balance", drawn by `keybalance.js` while `takesOwnBalance` and no balance was found; `magpie provider key-balance [key [usd|¥cny|off] [--refill …]]`) refuses a subscription, an amount outside ±`MaxOwnBalance` (1,000,000) in either currency (below 0 is a key the vendor let run past its balance, so typed as it reads: -1.84, -$1.84; AlanWang1027713 on X), and any currency but USD and CNY; nil takes it off, `ReplaceKey` carries it to the new value, and saving the editor keeps it. It may be typed in yuan (`cny`, "¥100", or a bare number with ¥ CNY picked in the currency button beside the field, which starts at the balance's own currency, else Settings' one; picking keeps the number typed and posts nothing until the field is left or Enter is pressed, so a balance's currency changes without clearing it or going to Settings, tenacious_eagle on Discord): what is spent is counted in USD and turned into yuan at `fx.Known()`, the rate `internal/fx` last fetched (cached 12h in `fxrate.json`, fetched again in the background, never on the request path); `fx.Known` never hands out `fx.Fallback`, so with no rate fetched yet and something spent the left is unknown (`left` null, the card's `Error` says why) rather than a guess. It may refill (`refill`: `{every: month, day: 1–31}`, a day past the month's end meaning its last, or `{every: week, day: 1 Monday–7 Sunday}`, or `{every: day, day: 0}`, every midnight, Kelen_Yc on X), at midnight in the user's local time: nothing is stored on a refill; the spend is counted from the last refill boundary after `at` (`From`), and `Next` is the next one. Typing the amount again keeps the refill. `SetKeyBalanceRefill` (GUI `provider/keybalancerefill`, the pill's menu: Refills each month…, Refills each week…, Refills each day, Never refills; CLI `--refill monthly[:day]|weekly[:mon…sun]|daily|off`); a magpie before daily refills drops a `day` refill as one written by hand that isn't one refuses a key with no balance. Part of it may expire, in grants (`expirings`: a list of `{amount, until, at}`, up to `MaxExpiring` (20), each amount in the balance's currency, `until` the last day it counts as 2006-01-02, `at` when it was typed; tenacious_eagle_96548 on Discord: money that stays and promotional credit twice, one good until tomorrow and one the day after). Grants are spent first, as DeepSeek spends its granted balance before the money topped up, and of them the one that ends soonest first (`spendGrants`): the spend is taken piece by piece over the times between `From`, now, and each grant's `at` and end (midnight after `until`, local time), each piece going to the live grant that ends first, and only what grants took after `From` is off the rest, so a refill or typing the balance again doesn't count it twice. `left` is the whole balance, the grants' remainders included; from a grant's end its remainder counts no more (`expired`, the latest such end), and unspent credit is simply gone. A grant whose end is at or before `From` is dropped on the next write (`liveGrants`). `AddKeyExpiring` (GUI `provider/keyexpiring` `{expiring: {amount, until}}`), `RemoveKeyExpiring` (`{expiring: {at, until}, remove: true}`, matched by `at`, else by `until` and the amount when given; nothing matched is an error) and `ClearKeyExpiring` (`{expiring: null}`) edit them. The pill's menu has Add credit that expires…, which opens one small form (`.abal-form`, the app's popover, no native control but the date field) with the amount, in the balance's currency, and the last day, a month ahead to begin with: Add or Enter saves, Escape or a click outside leaves it, an amount in the other currency or a day gone by is refused with the form kept; then a Remove {amount} for each grant with when it goes beside it, and No credit that expires with two or more, or one that expired. The CLI takes `--expiring amount@yyyy-mm-dd` and `--expiring-remove [amount@]yyyy-mm-dd`, each as often as wanted and applied in order after the balance, every value read before anything is written; `--expiring off` takes every grant off. Each refuses a key with no balance typed (type the rest first, 0 when all of it expires), an amount not above 0 or past `MaxOwnBalance`, and a date that isn't one. A v0.1.3305 balance's one `expiring` object is read as the first grant (`UnmarshalJSON`) and saved as `expirings` on the next write; a magpie before this reads `expirings` as no grant, so going back loses them from the estimate, not from the file until it writes. Typing the balance again keeps the grants in the same currency and drops them in the other, where its amount would mean another sum. A balance saved before has none and is counted as it was. The estimate's `expiring`, one per grant soonest first (`set`, `at`, `until`, `left`, `ends`), is the pill's "≈$60.00 left · $5.00 expires tomorrow · $20.00 expires in 30 days" (wrapping at a grant on a narrow row), and the card's `BalanceSplit` a line each with `expires`, which the Usage page and the panel label "Expires in 30 days" (`expiresIn` in app.js), amber from a week; the TUI and CLI quota say "$20.00 until Dec 31" (`SplitWords`). Each key with one gets `balance` in `/api/providers`' `keyList` (`set`, `at`, `spent`, `currency`, `rate`, `left`, `from`, `refill`, `next`, `expiring`, `expired`). `TestTypedBalanceExpires`, `TestTypedBalanceSavedBeforeExpiring`, `TestTypedBalanceGrantsSoonestFirst`, `TestTypedBalanceGrantsEdited`, `TestTypedBalanceOneGrantMigrated`, `TestExpiringParsed`, `TestExpiringDayParsed`, `TestKeyBalanceCmd`, `key-balance-expiring.test.cjs`, `TestKnownIsNeverAGuess`, `TestTypedBalanceInYuan`, `TestTypedBalanceRefills`, `TestRefillDays`, `TestTypedBalanceCountsDown`, `TestToldBalanceWinsOverTyped`, `TestOwnBalanceParsed`, `TestKeyOwnBalanceRoutes`, `key-own-balance.test.cjs`. - A window whose reset time has passed has started again, whatever share it was read at (`resetPassed`). That holds for a reading kept from before (`AsOf`) and for a fresh one: Claude Code's `/usage` gives a reset to the minute and can lag it, so a run just after a reset can still say 100% with that reset. `claudeWindows` hands such a window back empty on every path, and `usedPast`, `usedUp`, `BackAt` and `capReached` leave it out when they judge an account spent, for Codex, Claude Code and `magpie quota wait` alike. A card can still show a kept reading as it was read (`reported`, for a Claude card while `/usage` is unavailable); that changes what it shows, never which account is used. A reset `/usage` gives as a time alone ("resets 3pm") can be read as its next one, a day on (`claudeResetTime`), and is then not seen as passed here. - A restart to update can run two magpies for up to the old one's drain ([GUI shell](gui-shell.md#a-restart-to-update-hands-the-gateway-over)), each diff --git a/internal/agent/pimagpie.go b/internal/agent/pimagpie.go index aa01b9735..60faaea05 100644 --- a/internal/agent/pimagpie.go +++ b/internal/agent/pimagpie.go @@ -3,14 +3,14 @@ package agent import ( "encoding/json" "os" - "regexp" "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/lazyre" ) // piMagpieExt matches a Pi package source for the pi-magpie extension: // npm:pi-magpie, npm:pi-magpie@0.1.6, or a path or git source ending in it. -var piMagpieExt = regexp.MustCompile(`(^|[:/\\])pi-magpie(@[^/\\]*)?(#.*)?$`) +var piMagpieExt = lazyre.New(`(^|[:/\\])pi-magpie(@[^/\\]*)?(#.*)?$`) // piMagpieInstalled says Pi's settings.json lists the pi-magpie extension // in "packages". It serves provider "magpie" from magpie's live catalog, diff --git a/internal/cli/key_balance_cli.go b/internal/cli/key_balance_cli.go index 7121cba38..c5edbb44e 100644 --- a/internal/cli/key_balance_cli.go +++ b/internal/cli/key_balance_cli.go @@ -8,7 +8,7 @@ import ( "github.com/yetone/magpie/internal/provider" ) -const keyBalanceUsage = "magpie provider key-balance [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|off] [--expiring amount@yyyy-mm-dd|off]… [--expiring-remove [amount@]yyyy-mm-dd]…]" +const keyBalanceUsage = "magpie provider key-balance [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|daily|off] [--expiring amount@yyyy-mm-dd|off]… [--expiring-remove [amount@]yyyy-mm-dd]…]" // keyBalanceCmd shows, or sets, the balance typed by hand on a provider's // API keys whose vendor tells none (tenacious_eagle on Discord): what is diff --git a/internal/cli/key_balance_cli_test.go b/internal/cli/key_balance_cli_test.go index 2dfb7ea9f..991c0191d 100644 --- a/internal/cli/key_balance_cli_test.go +++ b/internal/cli/key_balance_cli_test.go @@ -60,6 +60,15 @@ func TestKeyBalanceCmd(t *testing.T) { if b, _ := typed(); b.CNY == nil || *b.CNY != 700 || b.Refill == nil || *b.Refill != (provider.Refill{Every: provider.RefillWeek, Day: 5}) { t.Fatalf("weekly:fri: %+v", b) } + if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "--refill", "daily"}); err != nil { + t.Fatal(err) + } + if b, _ := typed(); b.CNY == nil || *b.CNY != 700 || b.Refill == nil || *b.Refill != (provider.Refill{Every: provider.RefillDay}) { + t.Fatalf("daily: %+v", b) + } + if err := providerCmd([]string{"provider", "key-balance", "relay", "Team", "--refill=weekly:fri"}); err != nil { + t.Fatal(err) + } for _, bad := range [][]string{{"relay", "Team", "--refill", "yearly"}, {"relay", "--refill", "monthly"}, {"relay", "Team", "off", "--refill", "monthly"}, {"relay", "Team", "--refill"}} { if err := providerCmd(append([]string{"provider", "key-balance"}, bad...)); err == nil { t.Fatalf("%v taken", bad) diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index d3fd439d9..279de231e 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -108,7 +108,7 @@ const providerUsage = `usage: how much an API key may spend, in USD as the Usage page prices its calls, a day (the default), a month or in all from now: at it, routing takes the key for used up and goes on to the other keys and the fallbacks - magpie provider key-balance [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|off] [--expiring amount@yyyy-mm-dd|off]… [--expiring-remove [amount@]yyyy-mm-dd]…] + magpie provider key-balance [key [usd|¥cny|off] [--refill monthly[:day]|weekly[:mon…sun]|daily|off] [--expiring amount@yyyy-mm-dd|off]… [--expiring-remove [amount@]yyyy-mm-dd]…] the balance on an API key whose vendor tells none, typed from its own page in USD or in yuan (¥100): the Usage page shows it less what magpie prices the key's calls at since; with --refill it is whole again each month or week; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index af14055ef..bec6b7eda 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -147,12 +147,14 @@ const I18N = { "No credit that expires": "去掉限期额度", "Refills each month…": "每月恢复…", "Refills each week…": "每周恢复…", + "Refills each day": "每日恢复", "Never refills": "不恢复", "Refills on": "恢复于", "Refill day of the month": "每月恢复的日期", "A day of the month is a whole number from 1 to 31": "每月的日期是 1 到 31 之间的整数", "{who} no longer refills": "{who} 不再恢复余额", "{who} refills each {weekday}": "{who} 每{weekday}恢复余额", + "{who} refills each day": "{who} 每日恢复余额", "{who} refills on day {day} of each month": "{who} 每月 {day} 日恢复余额", "A spend cap is an amount in USD above 0, up to 1,000,000": "消费上限是大于 0、不超过 1,000,000 的美元金额", "Spend cap": "消费上限", @@ -5300,12 +5302,14 @@ const I18N = { "No credit that expires": "去掉限期額度", "Refills each month…": "每月恢復…", "Refills each week…": "每週恢復…", + "Refills each day": "每日恢復", "Never refills": "不恢復", "Refills on": "恢復於", "Refill day of the month": "每月恢復的日期", "A day of the month is a whole number from 1 to 31": "每月的日期是 1 到 31 之間的整數", "{who} no longer refills": "{who} 不再恢復餘額", "{who} refills each {weekday}": "{who} 每{weekday}恢復餘額", + "{who} refills each day": "{who} 每日恢復餘額", "{who} refills on day {day} of each month": "{who} 每月 {day} 日恢復餘額", "A spend cap is an amount in USD above 0, up to 1,000,000": "消費上限是大於 0、不超過 1,000,000 的美元金額", "Spend cap": "消費上限", @@ -10438,12 +10442,14 @@ const I18N = { "No credit that expires": "期限付きクレジットなし", "Refills each month…": "毎月戻す…", "Refills each week…": "毎週戻す…", + "Refills each day": "毎日戻す", "Never refills": "戻さない", "Refills on": "戻す曜日", "Refill day of the month": "毎月戻す日", "A day of the month is a whole number from 1 to 31": "日付は 1 から 31 までの整数です", "{who} no longer refills": "{who} の残高はもう戻りません", "{who} refills each {weekday}": "{who} の残高は毎週{weekday}に戻ります", + "{who} refills each day": "{who} の残高は毎日戻ります", "{who} refills on day {day} of each month": "{who} の残高は毎月 {day} 日に戻ります", "A spend cap is an amount in USD above 0, up to 1,000,000": "支出上限は 0 より大きく 1,000,000 以下の USD 金額です", "Spend cap": "支出上限", @@ -15578,12 +15584,14 @@ const I18N = { "No credit that expires": "Kein ablaufendes Guthaben", "Refills each month…": "Monatlich auffüllen…", "Refills each week…": "Wöchentlich auffüllen…", + "Refills each day": "Täglich auffüllen", "Never refills": "Nie auffüllen", "Refills on": "Auffüllen am", "Refill day of the month": "Tag des Monats zum Auffüllen", "A day of the month is a whole number from 1 to 31": "Ein Tag des Monats ist eine ganze Zahl von 1 bis 31", "{who} no longer refills": "{who} wird nicht mehr aufgefüllt", "{who} refills each {weekday}": "{who} wird jeden {weekday} aufgefüllt", + "{who} refills each day": "{who} wird jeden Tag aufgefüllt", "{who} refills on day {day} of each month": "{who} wird am {day}. jedes Monats aufgefüllt", "A spend cap is an amount in USD above 0, up to 1,000,000": "Ein Ausgabenlimit ist ein Betrag in USD über 0, bis 1.000.000", "Spend cap": "Ausgabenlimit", diff --git a/internal/gui/assets/keybalance.js b/internal/gui/assets/keybalance.js index ed8d74cc9..931ff4a72 100644 --- a/internal/gui/assets/keybalance.js +++ b/internal/gui/assets/keybalance.js @@ -4,7 +4,8 @@ // own usage prices the calls it sends on the key (provider/ // key_balance_own.go). Typing it again sets it anew. It may be typed in // yuan ("¥100", or picked beside the field, which starts at the balance's -// own currency, else Settings' one), and may refill each month or week. +// own currency, else Settings' one), and may refill each month, week or +// day (Kelen_Yc on X). // Credit may come on top that expires on a day, in grants (promotional // credit twice, gone on two days: tenacious_eagle_96548), the one that // goes soonest spent first: the pill says how much of each is left and in @@ -71,6 +72,7 @@ function keyBalancePill(p, k) { const refill = (r) => accountAction("provider/keybalancerefill", { id: p.id, account: k.id, refill: r }, !r ? t("{who} no longer refills", { who: name }) : r.every === "week" ? t("{who} refills each {weekday}", { who: name, weekday: weekdayName(r.day) }) + : r.every === "day" ? t("{who} refills each day", { who: name }) : t("{who} refills on day {day} of each month", { who: name, day: r.day })); const expiring = (v) => accountAction("provider/keyexpiring", { id: p.id, account: k.id, expiring: v }, !v ? t("{who} has no credit that expires", { who: name }) : t("{who} has {amount} that counts through {last}", { who: name, amount: moneyText(v.amount, cny), last: dateText(v.until) })); @@ -187,9 +189,11 @@ function keyBalancePill(p, k) { ...xs.length > 1 || b.expired ? [{ v: "noexp", name: "No credit that expires", note: "" }] : [], { v: "month", name: "Refills each month…", note: "" }, { v: "week", name: "Refills each week…", note: "" }, + { v: "day", name: "Refills each day", note: "" }, { v: "never", name: "Never refills", note: "" }, { v: "off", name: "No balance", note: "" }, ], b.refill?.every || "never", (v) => v === "off" ? set(null) : v === "exp" ? credit() : v === "noexp" ? expiring(null) : v === "month" ? monthly() : v === "week" ? weekly() + : v === "day" ? refill({ every: "day", day: 0 }) : v === "never" ? b.refill && refill(null) : v[0] === "x" ? unexpiring(xs[+v.slice(1)]) : type(), "Balance", "sess-menu"); // a grant that goes within a week says so in amber, as on the pill const items = protoMenu?.box.querySelectorAll(".pm-item"); diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index 5c49d106f..1e75a6c04 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -4659,6 +4659,7 @@ magpie.plugin("library", (ctx) => { if (subs.some((s) => s.agents?.includes("cursor"))) body.append(el("p", "lib-aside lib-subagents-cursor", t("The Cursor app has these subagents; its cursor-agent command reads only a project's own .cursor/agents."))); const skip = all.filter((a) => subagentAgentOf(a.id).no); if (skip.length) body.append(el("p", "lib-aside lib-subagents-no", t("magpie can't give subagents to {agents} yet: their chips are greyed, and say why.", { agents: skip.map((a) => a.name).join(", ") }))); + if (!agentless() && (subs.length || lib.projects.length)) renderProjects(body, "subagents"); } function subagentRow(s, all) { @@ -4914,7 +4915,10 @@ magpie.plugin("library", (ctx) => { const who = el("div", "who"); who.append(el("div", "name mono", p.name + (p.version ? " " + p.version : ""))); if (p.description) who.append(el("div", "lib-subagentdesc", p.description)); - const line = pluginParts(p); + // counts, not every name: PStack has a hundred (jinpwng on X); the + // names are in the dialog, folded + const line = [[t("Skills"), p.skills], [t("MCP servers"), p.mcp], [t("Hooks"), p.hooks], [t("Subagents"), p.subagents]] + .filter(([, v]) => v?.length).map(([k, v]) => k + " " + v.length).join(" · "); if (line) who.append(el("div", "sub lib-plparts", line)); row.append(glyph(GLYPH.folder), who, agentChips(all, p.agents, chipsChange("plugins/agents", p.name, "plugins", (x) => pluginRow(x, all)), { all: true }), @@ -4932,7 +4936,11 @@ magpie.plugin("library", (ctx) => { ed.append(head); if (p.description) ed.append(el("p", "lib-subagentdesc", p.description)); const rows = [[t("Skills"), p.skills], [t("MCP servers"), p.mcp], [t("Hooks"), p.hooks], [t("Subagents"), p.subagents]].filter(([, v]) => v?.length); - for (const [label, names] of rows) ed.append(...field(label, el("div", "mono lib-plnames", names.join(", ")))); + for (const [label, names] of rows) { + const d = el("details", "lib-plgroup"); + d.append(el("summary", "", label + " " + names.length), el("div", "mono lib-plnames", names.join(", "))); + ed.append(d); + } if (p.missing?.length) ed.append(el("div", "hint lib-plmissing", t("Taken out by hand: {names}", { names: p.missing.join(", ") }))); if (p.left?.length) { const left = el("div", "lib-plleft"); @@ -6145,12 +6153,14 @@ magpie.plugin("library", (ctx) => { function renderProjects(body, kind) { const rh = el("div", "row-head"); - rh.append(el("span", "label", kind === "skills" ? t("Project skills") : t("Project servers")), el("span", "grow")); + rh.append(el("span", "label", kind === "skills" ? t("Project skills") : kind === "subagents" ? t("Project subagents") : t("Project servers")), el("span", "grow")); if (!addingProject) rh.append(button(t("Add a project"), "action lib-updall", () => { addingProject = { dir: "" }; render(); })); body.append(rh); if (addingProject) body.append(addProjectCard(kind)); if (!lib.projects.length && !addingProject) { - body.append(el("p", "lib-aside", kind === "mcp" + body.append(el("p", "lib-aside", kind === "subagents" + ? t("Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.") + : kind === "mcp" ? t("Give a project's agents some of these servers as the project's own: magpie writes them into its {files}, leaving the rest of each file as it is.", { files: projectFiles() }) : t("Give a project's agents some of these skills as the project's own: magpie links them into its .claude/skills and .agents/skills and keeps them out of git."))); return; @@ -6197,7 +6207,7 @@ magpie.plugin("library", (ctx) => { addingProject = null; const p = lib.projects.find((x) => !was.has(x.dir)); if (p) openProjects.add(p.dir); - status(kind === "mcp" ? t("{name} added — pick the servers it gets", { name: p?.name || dir }) : t("{name} added — pick the skills it gets", { name: p?.name || dir }), "ok"); + status(kind === "subagents" ? t("{name} added — pick the subagents it gets", { name: p?.name || dir }) : kind === "mcp" ? t("{name} added — pick the servers it gets", { name: p?.name || dir }) : t("{name} added — pick the skills it gets", { name: p?.name || dir }), "ok"); } catch (e) { a.busy = false; a.error = e.message; @@ -6208,24 +6218,24 @@ magpie.plugin("library", (ctx) => { } function projectCard(p, kind) { - const mcp = kind === "mcp"; + const mcp = kind === "mcp", sub = kind === "subagents"; const card = el("div", "list lib-card lib-project" + (p.missing ? " missing" : "")); const isOpen = openProjects.has(p.dir); const head = el("div", "row lib-row click lib-projhead" + (isOpen ? " open" : "")); const who = el("div", "who"); const nm = el("div", "name", p.name); if (p.missing) nm.append(tag(t("Folder is gone"), "warn")); - else if (p.copy && !mcp) nm.append(tag(t("Copies"), "")); + else if (p.copy && !mcp && !sub) nm.append(tag(t("Copies"), "")); who.append(nm); const src = el("div", "lib-src"); src.append(pathLink(p.dir)); who.append(src); - const names = Object.keys((mcp ? p.servers : p.skills) || {}).sort(); + const names = Object.keys((sub ? p.subagents : mcp ? p.servers : p.skills) || {}).sort(); const pills = el("div", "lib-tags"); if (!isOpen) { for (const n of names.slice(0, 4)) pills.append(tag(n, "lib-dot")); if (names.length > 4) pills.append(tag("+" + (names.length - 4), "")); - if (!names.length) pills.append(tag(mcp ? t("No servers yet") : t("No skills yet"), "lib-unchecked")); + if (!names.length) pills.append(tag(sub ? t("No subagents yet") : mcp ? t("No servers yet") : t("No skills yet"), "lib-unchecked")); } const acts = el("div", "lib-rowacts"); const rm = button("", "lib-icon danger", () => confirmRemoveProject(p)); @@ -6236,11 +6246,12 @@ magpie.plugin("library", (ctx) => { chev.append(svg(CHEV_R, 11, 1.7)); head.append(glyph(GLYPH.folder), who, pills, acts, chev); head.onclick = () => { isOpen ? openProjects.delete(p.dir) : openProjects.add(p.dir); projectShown.delete(p.dir); render(); }; - head.title = mcp ? (isOpen ? t("Hide its servers") : t("Pick the servers it gets")) : isOpen ? t("Hide its skills") : t("Pick the skills it gets"); + head.title = sub ? (isOpen ? t("Hide its subagents") : t("Pick the subagents it gets")) : mcp ? (isOpen ? t("Hide its servers") : t("Pick the servers it gets")) : isOpen ? t("Hide its skills") : t("Pick the skills it gets"); card.append(head); if (p.problems?.[""]) card.append(el("div", "lib-err", p.problems[""])); if (!isOpen) return card; if (mcp) return projectServers(p, card); + if (sub) return projectSubagents(p, card); const opts = el("div", "lib-projopts"); const copy = toggle(p.copy, t("Copy files instead of linking"), (on) => @@ -6440,6 +6451,32 @@ magpie.plugin("library", (ctx) => { return card; } + // The project's card, open on the Subagents tab: each library subagent + // with the chips of the agents that read a project's own subagent folder. + function projectSubagents(p, card) { + const all = shownAgents().filter((a) => a.projectSubagents); + for (const s of lib.subagents || []) { + const row = el("div", "row lib-row lib-projskill lib-projsubagent"); + const w = el("div", "who"); + const n = el("div", "name mono", s.name); + const problem = p.problems?.["subagent:" + s.name]; + if (problem) n.append(tag(t("Not written"), "warn", problem)); + w.append(n); + const sub = el("div", "sub", problem || s.description || ""); + sub.title = problem || s.description || ""; + w.append(sub); + const on = (p.subagents?.[s.name] || []).filter((id) => all.some((a) => a.id === id)); + const say = (next) => next.length + ? t("{item} is in {name} for {agents}", { item: s.name, name: p.name, agents: next.map(nameOf).join(", ") }) + : t("{item} is out of {name}", { item: s.name, name: p.name }); + row.append(glyph(GLYPH.subagent), w, agentChips(all, on, projectChange("projects/subagents", p.dir, s.name, say))); + card.append(row); + } + if (!(lib.subagents || []).length) card.append(el("p", "lib-aside lib-projfoot", t("No subagents in the library yet"))); + card.append(el("p", "lib-aside lib-projfoot", t("Written into the project's own agents folder, one file per subagent; a file magpie makes is kept out of git, its .gitignore untouched. A file there by the same name that isn't magpie's is left as it is."))); + return card; + } + function confirmRemoveProject(p) { const ed = el("div", "editor lib-editor"); const head = el("div", "ehead"); diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index 346edceb1..d3f413bdf 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -717,6 +717,15 @@ magpie.strings({ "{agents} has no skills folder.": "{agents} 没有技能文件夹。", "Claude Desktop shows skill changes once its window is reloaded ({keys}). It gets a copy of each skill, and one you change in Desktop is left as it is.": "Claude Desktop 刷新窗口({keys})后才显示技能变化。它使用技能的副本,在 Desktop 中改过的副本不会被覆盖。", "Project servers": "项目服务器", + "Project subagents": "项目子代理", + "Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.": "把这些子代理作为项目自己的给项目里的 Agent:magpie 写进它的 .claude/agents 等文件夹,并让它们不进 git。", + "{name} added — pick the subagents it gets": "已添加 {name},选择它要用的子代理", + "No subagents yet": "还没有子代理", + "Hide its subagents": "收起子代理", + "Pick the subagents it gets": "选择它要用的子代理", + "Written into the project's own agents folder, one file per subagent; a file magpie makes is kept out of git, its .gitignore untouched. A file there by the same name that isn't magpie's is left as it is.": "每个子代理一个文件,写进项目自己的 agents 文件夹;magpie 创建的文件不进 git,.gitignore 不动。里面同名但不是 magpie 写的文件保持原样。", + "{item} is in {name} for {agents}": "{item} 已在 {name} 中对 {agents} 开启", + "{item} is out of {name}": "{item} 已从 {name} 中移除", "Project skills": "项目技能", "Add a project": "添加项目", "Give a project's agents some of these skills as the project's own: magpie links them into its .claude/skills and .agents/skills and keeps them out of git.": "将部分技能作为项目技能提供给项目中的 Agent:链接到项目的 .claude/skills 和 .agents/skills,并让 git 忽略。", @@ -1718,6 +1727,15 @@ magpie.strings({ "{agents} has no skills folder.": "{agents} 沒有技能資料夾。", "Claude Desktop shows skill changes once its window is reloaded ({keys}). It gets a copy of each skill, and one you change in Desktop is left as it is.": "Claude Desktop 重新整理視窗({keys})後才顯示技能變化。它使用技能的副本,在 Desktop 中改過的副本不會被覆蓋。", "Project servers": "專案伺服器", + "Project subagents": "專案子代理", + "Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.": "把這些子代理作為專案自己的給專案裡的 Agent:magpie 寫進它的 .claude/agents 等資料夾,並讓它們不進 git。", + "{name} added — pick the subagents it gets": "已新增 {name},選擇它要用的子代理", + "No subagents yet": "還沒有子代理", + "Hide its subagents": "收起子代理", + "Pick the subagents it gets": "選擇它要用的子代理", + "Written into the project's own agents folder, one file per subagent; a file magpie makes is kept out of git, its .gitignore untouched. A file there by the same name that isn't magpie's is left as it is.": "每個子代理一個檔案,寫進專案自己的 agents 資料夾;magpie 建立的檔案不進 git,.gitignore 不動。裡面同名但不是 magpie 寫的檔案保持原樣。", + "{item} is in {name} for {agents}": "{item} 已在 {name} 中對 {agents} 開啟", + "{item} is out of {name}": "{item} 已從 {name} 中移除", "Project skills": "專案技能", "Add a project": "新增專案", "Give a project's agents some of these skills as the project's own: magpie links them into its .claude/skills and .agents/skills and keeps them out of git.": "將部分技能作為專案技能提供給專案中的 Agent:連結到專案的 .claude/skills 和 .agents/skills,並讓 git 忽略。", @@ -2710,6 +2728,15 @@ magpie.strings({ "{agents} has no skills folder.": "{agents} にはスキルフォルダがありません。", "Claude Desktop shows skill changes once its window is reloaded ({keys}). It gets a copy of each skill, and one you change in Desktop is left as it is.": "Claude Desktop はウィンドウを再読み込み({keys})するとスキルの変更を表示します。各スキルのコピーを受け取り、Desktop で変更したものはそのまま残ります。", "Project servers": "プロジェクトのサーバー", + "Project subagents": "プロジェクトのサブエージェント", + "Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.": "これらのサブエージェントをプロジェクト専用として渡します。magpie が .claude/agents などに書き込み、git には入れません。", + "{name} added — pick the subagents it gets": "{name} を追加しました。渡すサブエージェントを選んでください", + "No subagents yet": "サブエージェントはまだありません", + "Hide its subagents": "サブエージェントを隠す", + "Pick the subagents it gets": "渡すサブエージェントを選ぶ", + "Written into the project's own agents folder, one file per subagent; a file magpie makes is kept out of git, its .gitignore untouched. A file there by the same name that isn't magpie's is left as it is.": "サブエージェントごとに1ファイルをプロジェクトの agents フォルダに書きます。magpie が作ったファイルは git に入れず、.gitignore は触りません。同名で magpie のものではないファイルはそのままです。", + "{item} is in {name} for {agents}": "{item} は {name} で {agents} に対してオンです", + "{item} is out of {name}": "{item} は {name} から外れました", "Project skills": "プロジェクトのスキル", "Add a project": "プロジェクトを追加", "Give a project's agents some of these skills as the project's own: magpie links them into its .claude/skills and .agents/skills and keeps them out of git.": "プロジェクトのエージェントに、これらのスキルの一部をプロジェクト固有のものとして渡します:magpie はそれらを .claude/skills と .agents/skills にリンクし、git の対象外にします。", @@ -3707,6 +3734,15 @@ magpie.strings({ "{agents} has no skills folder.": "{agents} hat keinen Skills-Ordner.", "Claude Desktop shows skill changes once its window is reloaded ({keys}). It gets a copy of each skill, and one you change in Desktop is left as it is.": "Claude Desktop zeigt Skill-Änderungen erst nach dem Neuladen des Fensters ({keys}). Es erhält von jedem Skill eine Kopie, und eine in Desktop geänderte bleibt unverändert.", "Project servers": "Projektserver", + "Project subagents": "Projekt-Subagenten", + "Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.": "Gib den Agenten eines Projekts einige dieser Subagenten als eigene: magpie schreibt sie in dessen .claude/agents und Ähnliches und hält sie aus git heraus.", + "{name} added — pick the subagents it gets": "{name} hinzugefügt – wähle die Subagenten dafür", + "No subagents yet": "Noch keine Subagenten", + "Hide its subagents": "Subagenten ausblenden", + "Pick the subagents it gets": "Subagenten wählen", + "Written into the project's own agents folder, one file per subagent; a file magpie makes is kept out of git, its .gitignore untouched. A file there by the same name that isn't magpie's is left as it is.": "Eine Datei pro Subagent im agents-Ordner des Projekts; was magpie anlegt, bleibt aus git heraus, die .gitignore bleibt unberührt. Eine gleichnamige Datei, die nicht von magpie stammt, bleibt wie sie ist.", + "{item} is in {name} for {agents}": "{item} ist in {name} für {agents} an", + "{item} is out of {name}": "{item} ist aus {name} entfernt", "Project skills": "Projekt-Skills", "Add a project": "Projekt hinzufügen", "Give a project's agents some of these skills as the project's own: magpie links them into its .claude/skills and .agents/skills and keeps them out of git.": "Geben Sie den Agenten eines Projekts einige dieser Skills als projekteigene: magpie verlinkt sie in dessen .claude/skills und .agents/skills und hält sie aus git heraus.", diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.css index 634ae8182..4d013d5c0 100644 --- a/internal/gui/assets/plugins/library/library.css +++ b/internal/gui/assets/plugins/library/library.css @@ -798,6 +798,10 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col .lib-plugin > .who { flex-basis: 240px; } .lib-plugin.off .name, .lib-plugin.off .lib-subagentdesc { opacity: .55; } .lib-plugin .lib-plparts, .lib-plpick .lib-plparts { white-space: normal; overflow-wrap: anywhere; } +.lib-pldetail > :is(p, details, .hint), .lib-pldetail .ebody > :is(p, details, .hint) { grid-column: 1 / -1; margin: 0; } +.lib-pldetail p { font-size: 12.5px; line-height: 1.5; } +.lib-pldetail .lib-plgroup > summary { cursor: pointer; font-size: 12.5px; color: var(--fg-2); } +.lib-pldetail .lib-plgroup .lib-plnames { margin-top: 4px; font-size: 12px; } .lib-pldetail .lib-plnames, .lib-pldetail .lib-plsource { white-space: normal; overflow-wrap: anywhere; } .lib-subagentedit .lib-menu { max-width: 100%; height: 28px; color: var(--fg); } .lib-subagentedit .lib-menu > span:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } diff --git a/internal/gui/importlink.go b/internal/gui/importlink.go index ee1bbb303..c571dce6c 100644 --- a/internal/gui/importlink.go +++ b/internal/gui/importlink.go @@ -11,7 +11,8 @@ import ( "github.com/yetone/magpie/internal/provider" ) -// An import link (magpie://import?…, see provider.ParseImport) is parsed +// An import link (magpie://import?… or ccswitch://v1/import?…, see +// provider.ParseImport) is parsed // here, parked under a random id, and the window opens on the Providers tab // with that id; the page fetches it once and asks the user before saving // anything. @@ -44,10 +45,11 @@ func stashImport(link string) string { return id } -// ImportLink is the link among a launch's arguments, if any. +// ImportLink is the link among a launch's arguments, if any: a magpie:// one, +// or a ccswitch:// one, which relays put on their pages for CC Switch. func ImportLink(args []string) string { for _, a := range args { - if strings.HasPrefix(strings.ToLower(a), provider.Scheme+":") { + if l := strings.ToLower(a); strings.HasPrefix(l, provider.Scheme+":") || strings.HasPrefix(l, provider.CCSwitchScheme+":") { return a } } diff --git a/internal/gui/importlink_test.go b/internal/gui/importlink_test.go index 3236ce024..55fb4fb6e 100644 --- a/internal/gui/importlink_test.go +++ b/internal/gui/importlink_test.go @@ -31,6 +31,11 @@ func TestImportIsReadOnce(t *testing.T) { if rec, _ := get(id); rec.Code != 404 { t.Fatalf("second read: %d", rec.Code) } + // a relay's CC Switch link opens the same confirmation + id = stashImport("ccswitch://v1/import?resource=provider&app=claude&name=My%20Relay&endpoint=https%3A%2F%2Frelay.example&apiKey=sk-r") + if rec, in := get(id); rec.Code != 200 || in.Error != "" || in.Provider.ID != "my-relay" || in.Provider.Anthropic != "https://relay.example" || in.Provider.Key != "sk-r" { + t.Fatalf("%d %+v", rec.Code, in) + } if _, in := get(stashImport("magpie://import?name=x")); in.Error == "" { t.Fatal("a bad link reported no error") } @@ -68,4 +73,7 @@ func TestImportLink(t *testing.T) { if ImportLink([]string{"MAGPIE://import?preset=x"}) == "" { t.Fatal("missed an upper-case link") } + if ImportLink([]string{"ccswitch://v1/import?resource=provider&app=claude&name=x"}) == "" { + t.Fatal("missed a CC Switch link") + } } diff --git a/internal/gui/library.go b/internal/gui/library.go index e0834f739..5ff6ab312 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -852,6 +852,8 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { res, err = library.ProjectSkill(in.Dir, in.Name, in.Agents) case "projects/skills": res, err = library.ProjectSkills(in.Dir, in.Names, in.Agents) + case "projects/subagents": + res, err = library.ProjectSubagents(in.Dir, oneOrMore(in.Name, in.Names), in.Agents) case "projects/server": res, err = library.ProjectServer(in.Dir, in.Name, in.Agents) case "projects/server-off": diff --git a/internal/gui/scheme_linux.go b/internal/gui/scheme_linux.go index 301b0933c..747cc5775 100644 --- a/internal/gui/scheme_linux.go +++ b/internal/gui/scheme_linux.go @@ -61,7 +61,7 @@ Terminal=false ` if old, err := os.ReadFile(path); err == nil && strings.Contains(string(old), "Exec="+exe+" %u") && strings.Contains(string(old), "x-scheme-handler/magpie") && strings.Contains(string(old), "\nStartupWMClass="+programName+"\n") { - return iconErr + return errors.Join(iconErr, registerCCSwitch(dir, exe)) } if err := os.MkdirAll(dir, 0o755); err != nil { return err @@ -70,7 +70,44 @@ Terminal=false return err } _ = proc.Command("update-desktop-database", dir).Run() - return errors.Join(iconErr, proc.Command("xdg-mime", "default", "magpie.desktop", "x-scheme-handler/magpie").Run()) + return errors.Join(iconErr, proc.Command("xdg-mime", "default", "magpie.desktop", "x-scheme-handler/magpie").Run(), registerCCSwitch(dir, exe)) +} + +// ccSwitchEntry is the desktop entry that claims ccswitch:// links, apart +// from magpie's own so that it can be left out. +const ccSwitchEntry = "magpie-ccswitch.desktop" + +// registerCCSwitch lets magpie open ccswitch:// links, the one-click import +// links relays make for CC Switch, but only when no other app has them: CC +// Switch installed here keeps its links. The desktop's default for the +// scheme is asked first; it is set to this entry only when empty or already +// this entry. No icon or window class of its own: it is never shown. +func registerCCSwitch(dir, exe string) error { + const mime = "x-scheme-handler/ccswitch" + out, _ := proc.Command("xdg-mime", "query", "default", mime).Output() + if def := strings.TrimSpace(string(out)); def != "" && def != ccSwitchEntry { + return nil + } + path := filepath.Join(dir, ccSwitchEntry) + entry := `[Desktop Entry] +Type=Application +Name=magpie (ccswitch:// links) +Exec=` + exe + ` %u +NoDisplay=true +MimeType=` + mime + `; +Terminal=false +` + if old, err := os.ReadFile(path); err == nil && string(old) == entry && strings.TrimSpace(string(out)) == ccSwitchEntry { + return nil + } + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + if err := os.WriteFile(path, []byte(entry), 0o644); err != nil { + return err + } + _ = proc.Command("update-desktop-database", dir).Run() + return proc.Command("xdg-mime", "default", ccSwitchEntry, mime).Run() } // installIcon puts magpie's icon where the entry's Icon=magpie is looked diff --git a/internal/gui/scheme_linux_test.go b/internal/gui/scheme_linux_test.go index c0194562d..733625dd2 100644 --- a/internal/gui/scheme_linux_test.go +++ b/internal/gui/scheme_linux_test.go @@ -11,6 +11,28 @@ import ( "github.com/yetone/magpie/internal/testenv" ) +// fakeDesktopTools puts update-desktop-database and an xdg-mime that +// remembers the defaults it is given and answers `query default` with them, +// each call logged to calls (names only, or with arguments). +func fakeDesktopTools(t *testing.T, bin, calls string, args bool) { + t.Helper() + t.Setenv("MAGPIE_SCHEME_TEST_CALLS", calls) + t.Setenv("PATH", bin) + for _, name := range []string{"update-desktop-database", "xdg-mime"} { + log := `printf '%s\n' '` + name + `'` + if args { + log = `printf '%s\n' '` + name + `' "$@"` + } + script := "#!/bin/sh\n" + log + ` >> "$MAGPIE_SCHEME_TEST_CALLS"` + "\n" + if name == "xdg-mime" { + script += `f="$MAGPIE_SCHEME_TEST_CALLS.${3##*/}"` + "\n" + // PATH holds only these two, so shell builtins + `[ "$1" = query ] && { [ -f "$f" ] && read -r v < "$f" && echo "$v"; exit 0; }` + "\n" + + `[ "$1" = default ] && echo "$2" > "$f"` + "\n" + } + testenv.Program(t, filepath.Join(bin, name), script) + } +} + func TestRegisterScheme(t *testing.T) { for _, tc := range []struct { name string @@ -35,12 +57,7 @@ func TestRegisterScheme(t *testing.T) { t.Fatal(err) } calls := filepath.Join(root, "calls") - t.Setenv("MAGPIE_SCHEME_TEST_CALLS", calls) - t.Setenv("PATH", bin) - for _, name := range []string{"update-desktop-database", "xdg-mime"} { - script := "#!/bin/sh\nprintf '%s\\n' '" + name + "' \"$@\" >> \"$MAGPIE_SCHEME_TEST_CALLS\"\n" - testenv.Program(t, filepath.Join(bin, name), script) - } + fakeDesktopTools(t, bin, calls, true) dir := filepath.Join(data, "applications") path := filepath.Join(dir, "magpie.desktop") const old = "[Desktop Entry]\nExec=/usr/bin/magpie %u\nMimeType=x-scheme-handler/magpie;\n" @@ -84,7 +101,13 @@ func TestRegisterScheme(t *testing.T) { if err := registerScheme(); err != nil { t.Fatal(err) } - want := "update-desktop-database\n" + dir + "\nxdg-mime\ndefault\nmagpie.desktop\nx-scheme-handler/magpie\n" + // ccswitch:// links are claimed too, asked first, and on the second + // run only asked + udd := "update-desktop-database\n" + dir + "\n" + want := udd + "xdg-mime\ndefault\nmagpie.desktop\nx-scheme-handler/magpie\n" + + "xdg-mime\nquery\ndefault\nx-scheme-handler/ccswitch\n" + + udd + "xdg-mime\ndefault\nmagpie-ccswitch.desktop\nx-scheme-handler/ccswitch\n" + + "xdg-mime\nquery\ndefault\nx-scheme-handler/ccswitch\n" if got, err := os.ReadFile(calls); err != nil || string(got) != want { t.Fatalf("registration calls: %q, want %q (%v)", got, want, err) } @@ -120,11 +143,7 @@ func TestRegisterSchemeBindsAnOlderEntry(t *testing.T) { t.Fatal(err) } calls := filepath.Join(root, "calls") - t.Setenv("MAGPIE_SCHEME_TEST_CALLS", calls) - t.Setenv("PATH", bin) - for _, name := range []string{"update-desktop-database", "xdg-mime"} { - testenv.Program(t, filepath.Join(bin, name), "#!/bin/sh\nprintf '%s\\n' '"+name+"' >> \"$MAGPIE_SCHEME_TEST_CALLS\"\n") - } + fakeDesktopTools(t, bin, calls, false) exe, err := os.Executable() if err != nil { t.Fatal(err) @@ -149,7 +168,7 @@ func TestRegisterSchemeBindsAnOlderEntry(t *testing.T) { t.Fatal(err) } checkDesktopBinding(t, data, string(got)) - if c, err := os.ReadFile(calls); err != nil || string(c) != "update-desktop-database\nxdg-mime\n" { + if c, err := os.ReadFile(calls); err != nil || string(c) != "update-desktop-database\nxdg-mime\nxdg-mime\nupdate-desktop-database\nxdg-mime\nxdg-mime\n" { t.Fatalf("registered %q, want once (%v)", c, err) } } @@ -202,3 +221,34 @@ func TestKeepWebData(t *testing.T) { }) } } + +// CC Switch installed here keeps ccswitch:// links: magpie leaves the +// desktop's default for the scheme alone, and writes no entry for it. +func TestRegisterSchemeLeavesCCSwitchItsLinks(t *testing.T) { + t.Setenv("FLATPAK_ID", "") + root := t.TempDir() + data := filepath.Join(root, "data") + t.Setenv("XDG_DATA_HOME", data) + bin := filepath.Join(root, "bin") + if err := os.Mkdir(bin, 0o755); err != nil { + t.Fatal(err) + } + calls := filepath.Join(root, "calls") + fakeDesktopTools(t, bin, calls, true) + if err := os.WriteFile(calls+".ccswitch", []byte("cc-switch.desktop\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := registerScheme(); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(data, "applications", ccSwitchEntry)); !os.IsNotExist(err) { + t.Fatalf("an entry for ccswitch:// was written: %v", err) + } + if c, _ := os.ReadFile(calls); strings.Contains(string(c), "default\nmagpie-ccswitch.desktop") { + t.Fatalf("took the default from CC Switch: %q", c) + } + // magpie's own scheme is still registered + if _, err := os.Stat(filepath.Join(data, "applications", "magpie.desktop")); err != nil { + t.Fatal(err) + } +} diff --git a/internal/gui/scheme_other.go b/internal/gui/scheme_other.go index 0478ea06b..4ecd2f08c 100644 --- a/internal/gui/scheme_other.go +++ b/internal/gui/scheme_other.go @@ -2,7 +2,7 @@ package gui -// registerScheme: the Mac reads the scheme from the bundle's Info.plist. +// registerScheme: the Mac reads the schemes (magpie, ccswitch) from the bundle's Info.plist. func registerScheme() error { return nil } // keepWebData: the Mac's webview keeps its data by the bundle id. diff --git a/internal/gui/scheme_windows.go b/internal/gui/scheme_windows.go index 032ee8a26..711b1041d 100644 --- a/internal/gui/scheme_windows.go +++ b/internal/gui/scheme_windows.go @@ -1,7 +1,10 @@ package gui import ( + "errors" "os" + "path/filepath" + "strings" "golang.org/x/sys/windows/registry" ) @@ -13,12 +16,43 @@ func registerScheme() error { if err != nil { return err } - k, _, err := registry.CreateKey(registry.CURRENT_USER, `Software\Classes\magpie`, registry.SET_VALUE) + return errors.Join(setScheme("magpie", exe), registerCCSwitch(exe)) +} + +// registerCCSwitch lets magpie open ccswitch:// links, the one-click import +// links relays make for CC Switch, but only while no other program has +// them: CC Switch installed here, per user or for the machine, keeps its +// links. The merged view (HKEY_CLASSES_ROOT) is asked, so both count; a +// handler whose program is gone is replaced. +func registerCCSwitch(exe string) error { + if run := schemeCommand(registry.CLASSES_ROOT, "ccswitch"); run != "" && !strings.EqualFold(filepath.Clean(run), filepath.Clean(exe)) { + if _, err := os.Stat(run); err == nil { + return nil + } + } + return setScheme("ccswitch", exe) +} + +// schemeCommand is the program a scheme's open command runs, "" when none. +func schemeCommand(root registry.Key, scheme string) string { + k, err := registry.OpenKey(root, scheme+`\shell\open\command`, registry.QUERY_VALUE) + if err != nil { + return "" + } + defer k.Close() + v, _, _ := k.GetStringValue("") + run, _, _ := strings.Cut(strings.TrimPrefix(v, `"`), `"`) + return run +} + +// setScheme points the per-user handler of scheme at exe. +func setScheme(scheme, exe string) error { + k, _, err := registry.CreateKey(registry.CURRENT_USER, `Software\Classes\`+scheme, registry.SET_VALUE) if err != nil { return err } defer k.Close() - _ = k.SetStringValue("", "URL:magpie") + _ = k.SetStringValue("", "URL:"+scheme) _ = k.SetStringValue("URL Protocol", "") icon, _, err := registry.CreateKey(k, `DefaultIcon`, registry.SET_VALUE) if err == nil { diff --git a/internal/gui/tests/key-own-balance.test.cjs b/internal/gui/tests/key-own-balance.test.cjs index 3b414ee78..c00849971 100644 --- a/internal/gui/tests/key-own-balance.test.cjs +++ b/internal/gui/tests/key-own-balance.test.cjs @@ -67,11 +67,11 @@ function serve(lang, posts) { } const words = { - en: { currency: "Currency", yuan40: "≈¥40.00 left", usd100: "≈$100.00 left", k1: "≈$12.50 left", none: "Set balance", menu: "Balance", enter: "Enter balance…", off: "No balance", k2: "≈$5.00 left", k1again: "≈$40.00 left", yuan: "≈¥100.00 left", bad: "A balance is an amount from -1,000,000 to 1,000,000, in USD or in yuan (¥)", month: "Refills each month…", week: "Refills each week…", never: "Never refills", on: "Refills on", refills: "Refills to $40.00 on" }, - zh: { currency: "货币", yuan40: "≈¥40.00 剩余", usd100: "≈$100.00 剩余", k1: "≈$12.50 剩余", none: "设置余额", menu: "余额", enter: "填写余额…", off: "无余额", k2: "≈$5.00 剩余", k1again: "≈$40.00 剩余", yuan: "≈¥100.00 剩余", bad: "余额是 -1,000,000 到 1,000,000 之间的金额,美元或人民币(¥)", month: "每月恢复…", week: "每周恢复…", never: "不恢复", on: "恢复于", refills: "恢复为 $40.00" }, - "zh-TW": { currency: "貨幣", yuan40: "≈¥40.00 剩餘", usd100: "≈$100.00 剩餘", k1: "≈$12.50 剩餘", none: "設定餘額", menu: "餘額", enter: "填寫餘額…", off: "無餘額", k2: "≈$5.00 剩餘", k1again: "≈$40.00 剩餘", yuan: "≈¥100.00 剩餘", bad: "餘額是 -1,000,000 到 1,000,000 之間的金額,美元或人民幣(¥)", month: "每月恢復…", week: "每週恢復…", never: "不恢復", on: "恢復於", refills: "恢復為 $40.00" }, - ja: { currency: "通貨", yuan40: "残り ≈¥40.00", usd100: "残り ≈$100.00", k1: "残り ≈$12.50", none: "残高を設定", menu: "残高", enter: "残高を入力…", off: "残高なし", k2: "残り ≈$5.00", k1again: "残り ≈$40.00", yuan: "残り ≈¥100.00", bad: "残高は -1,000,000 から 1,000,000 までの金額です(USD または人民元 ¥)", month: "毎月戻す…", week: "毎週戻す…", never: "戻さない", on: "戻す曜日", refills: "$40.00 へ戻る" }, - de: { currency: "Währung", yuan40: "≈¥40.00 übrig", usd100: "≈$100.00 übrig", k1: "≈$12.50 übrig", none: "Guthaben festlegen", menu: "Guthaben", enter: "Guthaben eingeben…", off: "Kein Guthaben", k2: "≈$5.00 übrig", k1again: "≈$40.00 übrig", yuan: "≈¥100.00 übrig", bad: "Ein Guthaben ist ein Betrag von -1.000.000 bis 1.000.000, in USD oder in Yuan (¥)", month: "Monatlich auffüllen…", week: "Wöchentlich auffüllen…", never: "Nie auffüllen", on: "Auffüllen am", refills: "wieder auf $40.00 aufgefüllt" }, + en: { currency: "Currency", yuan40: "≈¥40.00 left", usd100: "≈$100.00 left", k1: "≈$12.50 left", none: "Set balance", menu: "Balance", enter: "Enter balance…", off: "No balance", k2: "≈$5.00 left", k1again: "≈$40.00 left", yuan: "≈¥100.00 left", bad: "A balance is an amount from -1,000,000 to 1,000,000, in USD or in yuan (¥)", month: "Refills each month…", week: "Refills each week…", day: "Refills each day", never: "Never refills", on: "Refills on", refills: "Refills to $40.00 on" }, + zh: { currency: "货币", yuan40: "≈¥40.00 剩余", usd100: "≈$100.00 剩余", k1: "≈$12.50 剩余", none: "设置余额", menu: "余额", enter: "填写余额…", off: "无余额", k2: "≈$5.00 剩余", k1again: "≈$40.00 剩余", yuan: "≈¥100.00 剩余", bad: "余额是 -1,000,000 到 1,000,000 之间的金额,美元或人民币(¥)", month: "每月恢复…", week: "每周恢复…", day: "每日恢复", never: "不恢复", on: "恢复于", refills: "恢复为 $40.00" }, + "zh-TW": { currency: "貨幣", yuan40: "≈¥40.00 剩餘", usd100: "≈$100.00 剩餘", k1: "≈$12.50 剩餘", none: "設定餘額", menu: "餘額", enter: "填寫餘額…", off: "無餘額", k2: "≈$5.00 剩餘", k1again: "≈$40.00 剩餘", yuan: "≈¥100.00 剩餘", bad: "餘額是 -1,000,000 到 1,000,000 之間的金額,美元或人民幣(¥)", month: "每月恢復…", week: "每週恢復…", day: "每日恢復", never: "不恢復", on: "恢復於", refills: "恢復為 $40.00" }, + ja: { currency: "通貨", yuan40: "残り ≈¥40.00", usd100: "残り ≈$100.00", k1: "残り ≈$12.50", none: "残高を設定", menu: "残高", enter: "残高を入力…", off: "残高なし", k2: "残り ≈$5.00", k1again: "残り ≈$40.00", yuan: "残り ≈¥100.00", bad: "残高は -1,000,000 から 1,000,000 までの金額です(USD または人民元 ¥)", month: "毎月戻す…", week: "毎週戻す…", day: "毎日戻す", never: "戻さない", on: "戻す曜日", refills: "$40.00 へ戻る" }, + de: { currency: "Währung", yuan40: "≈¥40.00 übrig", usd100: "≈$100.00 übrig", k1: "≈$12.50 übrig", none: "Guthaben festlegen", menu: "Guthaben", enter: "Guthaben eingeben…", off: "Kein Guthaben", k2: "≈$5.00 übrig", k1again: "≈$40.00 übrig", yuan: "≈¥100.00 übrig", bad: "Ein Guthaben ist ein Betrag von -1.000.000 bis 1.000.000, in USD oder in Yuan (¥)", month: "Monatlich auffüllen…", week: "Wöchentlich auffüllen…", day: "Täglich auffüllen", never: "Nie auffüllen", on: "Auffüllen am", refills: "wieder auf $40.00 aufgefüllt" }, }; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { @@ -196,7 +196,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual(p.body, { id: "relay", account: "k1", balance: 40 }); await page.waitForTimeout(250); - // k1 refills on a day of each month, then each Friday, then never + // k1 refills on a day of each month, then each Friday, then each day, then never await still("k1"); await menu.waitFor(); await item(w.month).click(); @@ -233,6 +233,21 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", p = await posted(n); assert.deepEqual(p.body, { id: "relay", account: "k1", refill: { every: "week", day: 5 } }); await page.waitForTimeout(250); + // each day (Kelen_Yc on X): picked at once, no day to choose, and + // the menu shows it picked + await still("k1"); + await menu.waitFor(); + n = posts.length; + await item(w.day).click(); + p = await posted(n); + assert.deepEqual(p.body, { id: "relay", account: "k1", refill: { every: "day", day: 0 } }); + await page.waitForTimeout(250); + assert.equal(await page.locator(".proto-menu").count(), 0, "a daily refill asked for more"); + await still("k1"); + await menu.waitFor(); + assert.equal(await item(w.day).getAttribute("aria-checked"), "true"); + await page.keyboard.press("Escape"); + await page.waitForTimeout(200); await still("k1"); await menu.waitFor(); n = posts.length; diff --git a/internal/gui/tests/library-plugins.test.cjs b/internal/gui/tests/library-plugins.test.cjs index 0d6e067da..e0ac6c274 100644 --- a/internal/gui/tests/library-plugins.test.cjs +++ b/internal/gui/tests/library-plugins.test.cjs @@ -139,6 +139,19 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.locator("#modal .lib-pldetail").waitFor(); await settled(page); assert.deepEqual(await sideways(page), [], "sideways scroll in the dialog at 1100"); + // the description keeps the dialog's width, and the parts are folded (jinpwng on X) + const m = await page.evaluate(() => { + const d = document.querySelector("#modal .lib-pldetail"); + const p = d.querySelector("p").getBoundingClientRect(); + const w = (x) => x.getBoundingClientRect().width; + return { p: p.width, d: d.getBoundingClientRect().width, open: [...d.querySelectorAll("details")].filter((x) => x.open).length, n: d.querySelectorAll("details").length, + parts: [...d.querySelectorAll("details")].map(w), src: w(d.querySelector(".lib-plsource")) }; + }); + assert(m.p > m.d * 0.8, "the description is squeezed: " + JSON.stringify(m)); + // #6309: Plannotator's Hooks heading sat far right and the GitHub line in the middle + for (const x of [...m.parts, m.src]) assert(x > m.d * 0.8, "a part or the source is squeezed: " + JSON.stringify(m)); + assert.equal(m.open, 0, "parts open by default"); + assert.equal(m.n, 4); await ctx.close(); } @@ -149,7 +162,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const tabs = (await v.locator(".lib-tabs button").allTextContents()).map((x) => x.trim()); assert(tabs.includes(w("Claude plugins") + " · 1"), tabs.join("|")); assert.equal((await row("code-kit").locator(".lib-plparts").textContent()).trim(), - [w("Skills: {names}", { names: "code-kit-tdd" }), w("MCP servers: {names}", { names: "code-kit-docs" }), w("Hooks: {names}", { names: "code-kit-lint" }), w("Subagents: {names}", { names: "code-kit-reviewer" })].join(" · ")); + [w("Skills") + " 1", w("MCP servers") + " 1", w("Hooks") + " 1", w("Subagents") + " 1"].join(" · ")); assert.deepEqual(await sideways(page), [], "sideways scroll at 420"); assert.equal(await page.locator("select").count(), 0, "a native