From d7cda856ad681ccb0936906784716efcab279a14 Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 15 Nov 2026 16:54:13 +0800 Subject: [PATCH] library: MCP servers turned off fold away below the ones on (hzlxb on X) hzlxb on X asked for Library -> MCP servers to keep the servers turned off apart, folded, as Providers keeps the providers turned off. The list now holds the servers on. The ones off sit below it, above "+ Add server", under a "Servers turned off (N)" fold drawn with Providers' Turned off markup (row-head off-head, .fold with the chevron, the count in .note). It is folded at first and remembered in localStorage magpie.offServersOpen, as magpie.offProvidersOpen is. A server switched off moves under the fold, and one switched on comes back up. While picking (Select) the fold is held open and disabled, so every server picked is in sight, as Providers holds its fold open while searching. The MCP tab has no filter of its own, so there is nothing else for it to hide from. With every server off only the fold shows. With none off there is no fold. Strings are in en, zh, zh-TW, ja and de. Run: - library-mcp-off-fold.test.cjs (new): Chromium and WebKit, 1100 and 420 wide, en/zh/zh-TW/ja/de. It checks order, label, count, title, aria-expanded, that opening by a wheel-scrolled click leaves the head where it is and opens no editor, the reload memory, moving on a switch, picking, all off and none off. It is red on the old library files (no fold; checked on mica in chromium). - Library/MCP/i18n/click-scroll/providers-off-fold GUI files (102 files, both engines) on mote at the pre-rebase head 29a5f10f9: 2304 of 2310 pass. The 6 reds are library-open-again's 1100px cases, red the same alone on the old tree (filed as #6751). - go test -count=1 ./internal/gui/ on mica at this head: ok (143s). gofmt clean. - The whole GUI suite on mote at 29a5f10f9, in two parts (mote rebooted mid-run; the rest ran after it came back, under suite.lock). Part 1: 411 not ok in 75 files. Part 2 (640 files): 11355 tests, 10911 pass, 444 fail. No red is in the files this change touches except library-open-again (#6751). Every red file has an open issue saying it is red on main: skill-fold-all/skill-manual (#6667, #6668, the window's /api/update/using), skill-group-shared (#6687), view-open-wheel (#4723), view-trackpad-coast (#4724), view-wheel-unheard (#5158), usage-* (#6743, #4263), the rest in #6709 or by name; icon-tile was unfiled and is now #6759 (dim-color from 2649d5d72, not in app.css's tile rule). - After rebasing on origin/main 923cc8747 (1f04ed219 touched library.css): Library/i18n/click-scroll/providers-off/gui-* files on mote: 1837 of 1847 pass. Reds: library-open-again's 1100px cases (#6751), library-env de (#6675, NO_PROXYlocalhost) and library-chip-fan de no-preference (#3072), both chromium only; those two pass 3 of 3 alone at this head and at origin/main 923cc8747; go test -count=1 ./internal/gui/ on mica: ok (154s). Not tried: the real app, including WebKitGTK on Linux. The fold has no motion of its own (it uses Providers' chevron rotation). --- docs/subsystems/library.md | 2 +- internal/gui/assets/plugins/library/client.js | 41 +++- internal/gui/assets/plugins/library/i18n.js | 12 ++ .../gui/assets/plugins/library/library.css | 2 + .../gui/tests/library-mcp-off-fold.test.cjs | 185 ++++++++++++++++++ internal/gui/tests/library-mcp-on.test.cjs | 7 +- 6 files changed, 244 insertions(+), 5 deletions(-) create mode 100644 internal/gui/tests/library-mcp-off-fold.test.cjs diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index cad3942c8..9d9d62961 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -25,7 +25,7 @@ Pi's extensions and packages. | 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) | +| 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`). The servers off are listed apart, below the ones on, under a Servers turned off (N) fold drawn as Providers' Turned off one (`.fold` in an `.off-head`), folded at first and remembered in localStorage (`magpie.offServersOpen`); while picking (Select) it is held open, so every server picked is in sight (hzlxb on X, `library-mcp-off-fold.test.cjs`). | [`mcp_on.go`](../../internal/library/mcp_on.go), [`project_mcp.go`](../../internal/library/project_mcp.go), [`subagents.go`](../../internal/library/subagents.go) | | MCP router | With `MCPHub` on, `syncMCP` gives each agent that can take it one entry, `magpie`, at the gateway's `/mcp/magpie/hub/`, in place of the servers ticked for it; magpie runs those servers itself, once for every agent. | [MCP router](mcp-router.md), [`mcp_hub.go`](../../internal/library/mcp_hub.go) | | MCP market | `MarketServers` lists the featured servers that match a search, then the MCP Registry's; a search that is an address (a repository, a page, an endpoint, a package; `market_addr.go`) finds the ones at it, and `CustomAt` offers one to fill in by hand when none is. The registry lists no server by a repository's folder, so a GitHub address naming one (`#subdirectory=`, `/tree//…`, `parseRepoAt`) is read first: the folder's `pyproject.toml` names the program, and the README's `"env": {…}` examples the keys, offered as `uvx --from git+https://github.com/o/r#subdirectory=p ` (`fromRepo`, CyberCaius on Discord: volcengine/mcp-server's askecho search). A bare repository is read so only when the registry has nothing at it, and a PyPI page, or a one-word search naming mcp the registry lists nothing by, asks PyPI (`fromPyPI`, `uvx `). Of several README keys none is required, since a README often has the user pick one way to sign in (`envInputs`; `TestMarketServerInRepoFolder`). Only Python projects are read from a folder; a Node one there still gets the blank form. A registry package is started the way its entry says (`launchLine`): its `runtimeArguments` are the runner's options (`uvx -p 3.13`, `npx --package`, docker's mounts) and the program's own words (Serena's `start-mcp-server`), then its `packageArguments`; an executable not named after the package is reached with `uvx --from ` or `npx --package `. The shipped crawl keeps each package's executables (`bins`, from npm's `bin` and the wheel's console scripts); a package with none, several with none standing out (`pickBin`), or a required option magpie can't fill isn't offered. A server installed from the market before, still on the line magpie gave it then, is given the new one on load (`healMarketLines`; fwxkogaia on X, `TestRegistryLaunchLines`, `TestInstalledMarketLineHealed`). | [`market.go`](../../internal/library/market.go), [`market_launch.go`](../../internal/library/market_launch.go), [`market_repo.go`](../../internal/library/market_repo.go) | | Skills | A skill is a folder with a `SKILL.md`. It goes by the `name` its front matter gives, made fit for a file name (ASCII letters, digits, `_` and `-`); a name that would lose a letter or digit that way (one in another script, `CTF•密码学`) or none goes by its folder's name instead, and a skill at a repository's top by the repository's (`nameFor`, `srcFolder`). A front matter setting `disable-model-invocation: true` marks it "Manual only" in the page, in the library and in the agents' own (`meta.Manual`, `SkillView.Manual`, `FoundSkill.Manual`; sunset3279 on Discord): Claude Code runs such a skill only on the user's `/name`. A front matter that doesn't parse, or a value that isn't a bool, is not known to be, and gets no mark (`TestSkillManualFromFrontMatter`, `skill-manual.test.cjs`). Two skills a probe names alike are listed once (`unhiddenFirst`), so names that fell to `CTF`, `Strix` and nothing listed asdfgh1445/ctf-super-hub's 35 skills as 16 (tnt1223 on Discord, `TestSkillsNamedInAnotherScriptAllListed`). It comes from GitHub, from any other git repository, from a folder on this machine (linked, so editing the folder edits the skill) or from the market. A git repository (`kind: git`, sunset on Discord: GitLab, a company's own GitLab) is any https, http, ssh or `file://` address, `git@host:group/repo.git`, a bare `host.name/group/repo`, or a GitLab or Gitea page of a folder (`/-/tree//`, `/-/blob/…`, `/src/branch/…`; a branch with a `/` in its name is read as its first segment) (`gitSource`). It is fetched by the user's own `git` (`proc.FindTool`), so their credential helpers and SSH keys reach an intranet host: `git init`, then `fetch --depth 1 --no-tags -- ` and `checkout FETCH_HEAD` into a `magpie-skill-*` folder, then its `.git` is removed (`fetchGit`). What the user typed is data: an address starting with `-` and a `transport::` address (`ext::`, `fd::`, `file::`) are refused before git runs, the address follows `--`, git runs with `protocol.ext.allow=never` and `core.symlinks=false`, no shell, `GIT_TERMINAL_PROMPT=0` and (unless the user set an SSH command) `ssh -o BatchMode=yes`, so a sign-in it can't make fails instead of waiting. An address with a password or token in it is refused: library.json is shown and backed up. Git missing, a sign-in refused, a host key unknown, a branch missing and a host unreachable each say so (`gitError`; `TestGitSourceReads`, `TestInstallFromGitRepo`, `TestGitTreeURLInstallsFolder`, `TestGitMissingSaysSo`, `TestGitSignInRefusedSaysSo`, `TestGitRefusesOptionsAndTransports`, `TestGitErrorsSaid`). Each agent gets a link or a marked copy (#896, `SkillHow`). On Windows, Antigravity (the app and agy) and Crush get copies only (`junctionBlind`, `skipsJunctions`, `Target.Copy`; #5107, #6610): they are Go programs that keep a skills-folder entry only when it is a folder or a symlink, and Go lists a junction, magpie's link where the user may not make a symlink, as neither (`ModeIrregular`), so a junctioned skill never showed there; GetAllSkills of Antigravity 2.30's language server and Crush 0.101's prompt list a folder and a symlink and leave out a junction, and agy 1.5.8 on macOS takes a symlink leading out of its folder. A junction in `~/.agents/skills` is no skill to them either (`inShared`), and a project entry one of them reads is a copy too (`syncFolder`); an edit in a project's copy goes to the library as one in an agent's copy does (`takeEdits`). An agent in a WSL distro gets a link too, to the distro's one copy of the skill, magpie's, in `~/.local/share/magpie/skills` (`Target.Store`, `storeSkill`; cutemmuu on X): the distro can't follow a link to the library's folder on Windows, and a link Windows makes through `\\wsl.localhost` is an empty folder in the distro, which in turn shows Windows its own links as entries it can't read, follow or remove, so the link is made, read and taken away in the distro by wsl.exe (`agent.WSLSymlink`, `WSLReadlink`, `WSLRemoveLink`; `TestWSLLinksLive` and `TestWSLSkillsLinkedLive` on a real distro with `MAGPIE_WSL_TEST_DISTRO`). An edit made through the link is in the distro's copy, which `takeEdits` reads as any copy of magpie's (`TestWSLEditThroughLinkReachesTheLibrary`); a copy no agent there links to or is given any more goes, to the backups when edited (`sweepWSLStores`, `TestWSLStoreSweepKeepsEdits`); a folder there that isn't magpie's is never touched, and each agent it is in the way of says so. The copy isn't put in the distro's `~/.agents/skills`, since every agent there reading that folder would get each skill, ticked for it or not. An agent set to copies gets one of its own, as does one whose skills folder or the store is on a Windows drive (#4502), where the distro's link is one Windows can't read. A copy an agent there was given before is made a link on the next sync, its edit taken first and a losing edit set aside (`wslRelink`, `TestWSLOldCopiesBecomeLinks`). A copy's mark keeps the hash of what was copied, so a sync knows a copy unchanged since then is current without reading its files (`copyIsFresh`, #1031); other copies are hashed. A skill of the user's own is made with `CreateSkill` (`POST /api/library/skills/create`, Skills > New skill; josephBenchap on X): a name (`checkName`, and not one the library or an agent has, compared without case, nor a folder in the way) and a one-line description of at most 1024 characters make `skills//SKILL.md` with `name` and `description` front matter, listed with no source and given to the agents picked; the page then opens it in the reader (`TestCreateSkill`, `library-new-skill.test.cjs`). A skill an agent has of its own (`foundSkills`, the page's "In your agents") is brought in with `ImportSkill`, or taken out of every agent that has it with `RemoveFoundSkill` (#1303): its folders and copies of the very same files, its shared `~/.agents/skills` entry and a folder of it in the library's own folder go to the backups, its links are taken away, and a folder elsewhere it only links to, or another skill by that name, stays. Several go at once with `RemoveFoundSkills` (`POST /api/library/skills/remove-found-some`, wongxy on Discord): the "In your agents" heading's own Select picks them, and Remove… asks once, naming the count, before one change takes each out as `RemoveFoundSkill` would. A name that can't be taken out is left as it was, in `Result.Unremoved`, and stays picked with its error in its row's place (`foundErrs`); when none can go the change fails and nothing is touched. This Select and the library's are never on together: while one is on the other is dimmed, saying why, so neither click takes the other's bar away from above the pointer (`TestRemoveFoundSkills`, `found-skill-pick-remove.test.cjs`). A repository is fetched as one tarball of at most `maxFetch` (200 MB); a bigger one is fetched file by file from its tree (`fetchSkillFiles`), only as far as the caller reads: a link to a folder and an update ask GitHub for that folder's own list (`treeUnder`, git's `ref:path`; the whole list when that fails), the market fetches only the skills whose folder is the one it installs (#2794, sickn33/agentic-awesome-skills' 8,589 skills are 287 MB together), and a fetcher keeps such a part apart from another skill's of the same repository, which would otherwise read as removed (`fetcher.get`, `TestMarketSkillFromAHugeRepository`). GitHub's list is read up to `maxTree` (64 MB; that repository's is 11 MB) and an answer over the cap a caller gives `apiGet`, or one cut off, is an error saying so, never a body cut short for JSON to trip on (ye4241's `TestRepoTreeBigList`, `TestApiGetWholeAnswer`); a list GitHub truncated itself is too big (`TestTruncatedListIsTooBig`). And a skill over 200 MB on its own is left out rather than failing the rest: the probe lists the others and names it in `Probe.Left`, under the list in the page and in the TUI's flash. Only when every skill is too big does the fetch fail (#2062, mikubaka88/CCFA-Skills' 297 MB ccf-paper-writer; `TestOneSkillTooBigLeavesTheOthers`, `skill-too-big.test.cjs`). A probe keeps its download for the install from it for 15 minutes (`keepProbe`, `probeLife`), and removes it when it is probed again or that time is up, not at the next probe, which may never come. A download a magpie that quit left in the temp dir goes at the next probe once it is an hour old (`sweepStaleDownloads`). The package's TestMain gives the tests a temp dir of their own and fails a run that leaves a `magpie-skill-*` in it (#2321, `TestProbeDownloadEndsWithIt`, `TestStaleDownloadsSwept`). | [`skilltree.go`](../../internal/library/skilltree.go), [`skills.go`](../../internal/library/skills.go), [`skillgit.go`](../../internal/library/skillgit.go), [`skill_how.go`](../../internal/library/skill_how.go), [`skill_edits.go`](../../internal/library/skill_edits.go), [`skill_from.go`](../../internal/library/skill_from.go), [`skill_beside.go`](../../internal/library/skill_beside.go) | diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index 2e08be73c..7c4b5f76f 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -1055,7 +1055,7 @@ magpie.plugin("library", (ctx) => { else if (tab === "plugins") renderPlugins(body); else renderSkills(body); page.append(body); - for (const n of body.querySelectorAll(".row-head .note")) n.title = n.textContent; + for (const n of body.querySelectorAll(".row-head .note")) if (!n.closest(".fold")) n.title = n.textContent; for (const d of page.querySelectorAll(".lib-detail[data-detail]")) if (had.has(d.dataset.detail)) d.classList.add("kept"); for (const f of fits.splice(0)) f(); page.scrollTop = top; @@ -2780,6 +2780,8 @@ magpie.plugin("library", (ctx) => { const remote = (s) => s.transport === "http" || s.transport === "sse"; const reaches = (s) => (a) => !a || (!(remote(s) && a.noRemote) && !(s.transport === "sse" && a.noSSE) && !(envRefs(s) && a.noEnvRefs)); + let serversOffFolded = true; // the servers turned off, folded below the ones on + try { serversOffFolded = localStorage.getItem("magpie.offServersOpen") !== "1"; } catch {} function renderServers(body) { body.append(intro(agentless() ? t("Add the servers other apps should reach, and turn on the MCP router: they connect at its address, from another computer with a gateway key.") @@ -2794,8 +2796,41 @@ magpie.plugin("library", (ctx) => { if (agentless()) body.append(...hubPart()); } else { const list = el("div", "list lib-list"); + // turned off, they fold away below the ones on, as Providers' do + // (hzlxb on X), folded at first and remembered; while picking, the + // fold stays open, for every server picked to be in sight + const offList = el("div", "list lib-list lib-offlist"); + offList.id = "lib-offServers"; + const offHead = el("div", "row-head off-head lib-offhead"); + const fold = el("button", "fold"); + fold.type = "button"; + fold.setAttribute("aria-controls", offList.id); + const offCount = el("span", "note"); + fold.append(svg(CHEV_R, 11, 1.6), el("span", "label", t("Servers turned off")), offCount); + offHead.append(fold); + const syncFold = () => { + const offs = offList.childElementCount, open = !!picking || !serversOffFolded; + offHead.hidden = !offs; + list.hidden = offs > 0 && !list.childElementCount; + offList.hidden = !offs || !open; + offCount.textContent = offs || ""; + fold.disabled = !!picking; + fold.setAttribute("aria-expanded", String(open)); + fold.title = t(open ? "Fold the servers turned off away" : "Show the servers turned off"); + }; + fold.onclick = (e) => { + e.stopPropagation(); + serversOffFolded = !serversOffFolded; + try { localStorage.setItem("magpie.offServersOpen", serversOffFolded ? "0" : "1"); } catch {} + syncFold(); + }; // in the order the reader picked (#481), A→Z till then - const fill = () => list.replaceChildren(...[...lib.servers].sort(byName(sortOf("libServers"))).map((s) => serverRow(s, all))); + const fill = () => { + const sorted = [...lib.servers].sort(byName(sortOf("libServers"))); + list.replaceChildren(...sorted.filter((s) => !s.hidden).map((s) => serverRow(s, all))); + offList.replaceChildren(...sorted.filter((s) => s.hidden).map((s) => serverRow(s, all))); + syncFold(); + }; // one heading over the list, with what the skills' has (#1027): the // order, Select, every server on or off for every agent shown, one // agent's (#475, or out of a hidden one) and every server out @@ -2815,7 +2850,7 @@ magpie.plugin("library", (ctx) => { body.append(rh); } fill(); - body.append(list); + body.append(list, offHead, offList); if (picking) body.append(pickBar(all)); const after = el("div", "after-list"); after.append(button(t("+ Add server"), "", () => editServer(null))); diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index 4b98f48b9..acf211cee 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -737,6 +737,9 @@ magpie.strings({ "Added {n} servers": "已添加 {n} 个服务器", "A skill is a folder with a SKILL.md an agent loads when it's needed. The library keeps each one once and links it into the agents you pick.": "技能是一个带 SKILL.md 的文件夹,Agent 在需要时加载。资源库只保存一份,再链接到你选的 Agent 中。", "In the library": "资源库中", + "Servers turned off": "已关闭的服务器", + "Show the servers turned off": "展开已关闭的服务器", + "Fold the servers turned off away": "收起已关闭的服务器", "By source": "按来源", "not in the library — bring one in to give it to the others": "不在资源库中 — 导入后可以给其他 Agent", "{agents} has no skills folder.": "{agents} 没有技能文件夹。", @@ -1813,6 +1816,9 @@ magpie.strings({ "Added {n} servers": "已新增 {n} 個伺服器", "A skill is a folder with a SKILL.md an agent loads when it's needed. The library keeps each one once and links it into the agents you pick.": "技能是一個帶 SKILL.md 的資料夾,Agent 在需要時載入。資源庫只儲存一份,再連結到你選的 Agent 中。", "In the library": "資源庫中", + "Servers turned off": "已關閉的伺服器", + "Show the servers turned off": "展開已關閉的伺服器", + "Fold the servers turned off away": "收起已關閉的伺服器", "By source": "按來源", "not in the library — bring one in to give it to the others": "不在資源庫中 — 匯入後可以給其他 Agent", "{agents} has no skills folder.": "{agents} 沒有技能資料夾。", @@ -2880,6 +2886,9 @@ magpie.strings({ "Added {n} servers": "{n} 個のサーバーを追加しました", "A skill is a folder with a SKILL.md an agent loads when it's needed. The library keeps each one once and links it into the agents you pick.": "スキルとは、エージェントが必要なときに読み込む SKILL.md を含むフォルダです。ライブラリは各スキルを1つだけ保管し、選んだエージェントにリンクします。", "In the library": "ライブラリ内", + "Servers turned off": "オフのサーバー", + "Show the servers turned off": "オフのサーバーを表示", + "Fold the servers turned off away": "オフのサーバーを折りたたむ", "By source": "ソース別", "not in the library — bring one in to give it to the others": "ライブラリにありません — 取り込むと他のエージェントにも渡せます", "{agents} has no skills folder.": "{agents} にはスキルフォルダがありません。", @@ -3952,6 +3961,9 @@ magpie.strings({ "Added {n} servers": "{n} Server hinzugefügt", "A skill is a folder with a SKILL.md an agent loads when it's needed. The library keeps each one once and links it into the agents you pick.": "Ein Skill ist ein Ordner mit einer SKILL.md, die ein Agent bei Bedarf lädt. Die Bibliothek hält jeden nur einmal vor und verlinkt ihn in die Agenten, die Sie wählen.", "In the library": "In der Bibliothek", + "Servers turned off": "Ausgeschaltete Server", + "Show the servers turned off": "Ausgeschaltete Server anzeigen", + "Fold the servers turned off away": "Ausgeschaltete Server einklappen", "By source": "Nach Quelle", "not in the library — bring one in to give it to the others": "nicht in der Bibliothek – übernehmen Sie einen, um ihn den anderen zu geben", "{agents} has no skills folder.": "{agents} hat keinen Skills-Ordner.", diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.css index ead633b02..1565b579a 100644 --- a/internal/gui/assets/plugins/library/library.css +++ b/internal/gui/assets/plugins/library/library.css @@ -967,3 +967,5 @@ input.lib-memq:focus, input.lib-memtags:focus, input.lib-memwhy:focus { border-c .lib-bili-phil { display: grid; gap: 6px; padding: 8px 0 0 15px; } .lib-bili-phil > .name { font-size: 12.5px; color: var(--fg-2); } .lib-bili-phil .lib-acts { justify-content: flex-end; } +/* the servers turned off, folded below the ones on, as Providers' */ +#view-library .lib-offhead .fold:disabled { cursor: default; opacity: 1; } diff --git a/internal/gui/tests/library-mcp-off-fold.test.cjs b/internal/gui/tests/library-mcp-off-fold.test.cjs new file mode 100644 index 000000000..9c319b9e3 --- /dev/null +++ b/internal/gui/tests/library-mcp-off-fold.test.cjs @@ -0,0 +1,185 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// hzlxb on X: in Library → MCP servers the servers turned off sat among the +// ones on. They are kept apart now, as Providers' are: the list holds the +// ones on, and the ones off sit below it under a "Servers turned off (N)" +// fold, folded at first. The fold opens and closes on a click that leaves +// the page where it is and opens no editor, and is remembered across a +// reload; a server switched off moves under it, one switched on again comes +// back up. While picking (Select) the fold is open, for every server picked +// to be in sight. Every language, Chromium and WebKit, at 1100 and 420 wide +// with nothing running off to the side. No backend: the API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { strings } = require("./strings.cjs"); + +const assets = path.resolve(__dirname, "../assets"); +const HOME = "/Users/tester"; +const NAMES = ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel"]; +const fixture = (st) => ({ + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color", skills: `${HOME}/.claude/skills`, mcp: `${HOME}/.claude.json` }], + instructions: { agents: [], sets: [] }, foundSkills: [], skills: [], problems: [], foundServers: [], projects: [], + servers: NAMES.map((name) => st.off.has(name) + ? { name, transport: "stdio", command: "uvx", args: [name + "-mcp"], agents: [], hidden: true, paused: ["claude"] } + : { name, transport: "stdio", command: "uvx", args: [name + "-mcp"], agents: ["claude"] }), +}); + +let I18N; +const tr = (lang, key, vars = {}) => { + let s = key; + if (lang !== "en") { + assert.equal(typeof I18N[lang][key], "string", `${lang} has no ${JSON.stringify(key)}`); + s = I18N[lang][key]; + } + return s.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? String(vars[k]) : m)); +}; + +function server(lang, st) { + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light", gateway: "http://127.0.0.1:3425" } }); + if (url.pathname === "/api/library") return json(fixture(st)); + if (url.pathname === "/api/library/servers/on") { + const { name, on } = req.postDataJSON(); + if (on) st.off.delete(name); else st.off.add(name); + return json({ ...fixture(st), result: { changed: [] } }); + } + if (url.pathname === "/api/library/mcp/check") return json({ servers: Object.fromEntries(req.postDataJSON().names.map((n) => [n, { state: "ok", tools: 2 }])) }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true } }); + if (url.pathname.startsWith("/api/")) return json({}); + if (url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const sideways = (page) => page.evaluate(() => { + const over = []; + const w = document.documentElement.clientWidth; + if (document.documentElement.scrollWidth > w) over.push("page " + document.documentElement.scrollWidth); + for (const e of document.querySelectorAll("#view-library .lib-offhead, #view-library .lib-offhead .fold, #view-library .lib-server")) { + const r = e.getBoundingClientRect(); + if (r.width && (r.right > w + 0.5 || r.left < -0.5)) over.push((e.className || e.tagName) + " " + Math.round(r.left) + "–" + Math.round(r.right)); + } + return over; +}); +const names = (page, sel) => page.locator(`#view-library ${sel} > .lib-server`).evaluateAll((rs) => rs.map((r) => r.dataset.server)); +const top = (loc) => loc.evaluate((e) => e.getBoundingClientRect().top); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": MCP servers turned off fold away below the ones on", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + I18N = strings().I18N; + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" })); + t.after(() => browser.close()); + + for (const width of [1100, 420]) for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + await t.test(`${lang} ${width}px`, async () => { + const w = (key, vars) => tr(lang, key, vars); + const st = { off: new Set(["bravo", "echo", "golf"]) }; + const errors = []; + const ctx = await browser.newContext({ viewport: { width, height: 560 }, reducedMotion: "reduce" }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "mcp"); } catch {} }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, st)); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + const v = page.locator("#view-library"); + await v.locator('.lib-server[data-server="alpha"]').waitFor(); + + // the list holds the ones on; the ones off are under the fold, folded + assert.deepEqual(await names(page, ".lib-list:not(.lib-offlist)"), ["alpha", "charlie", "delta", "foxtrot", "hotel"]); + const fold = v.locator(".lib-offhead .fold"); + assert(await fold.isVisible(), "the fold shows"); + assert.equal((await fold.locator(".label").textContent()).trim(), w("Servers turned off")); + assert.equal((await fold.locator(".note").textContent()).trim(), "3"); + assert.equal(await fold.getAttribute("aria-expanded"), "false", "folded at first"); + assert.equal(await fold.getAttribute("title"), w("Show the servers turned off")); + const offList = v.locator(".lib-offlist"); + assert(await offList.evaluate((l) => l.hidden), "folded, the ones off are hidden"); + const listBottom = await v.locator(".lib-list:not(.lib-offlist)").first().evaluate((e) => e.getBoundingClientRect().bottom); + assert(await top(v.locator(".lib-offhead")) >= listBottom, "the fold is below the list"); + assert(await top(v.locator(".lib-offhead")) < await top(v.locator(".after-list").first()), "the fold is above Add server"); + assert.deepEqual(await sideways(page), [], "sideways scroll, folded"); + + // opened with the page scrolled to it by the wheel (a scroll by + // code is put back on the click, as not the reader's), the head + // stays where it is + await page.mouse.move(width / 2, 300); + for (let i = 0; i < 12 && await top(fold) > 420; i++) { + await page.mouse.wheel(0, 120); + await page.waitForTimeout(120); + } + await page.waitForTimeout(300); + const scrolled = await v.evaluate((x) => x.scrollTop); + const was = await top(fold); + await fold.click(); + await page.waitForFunction(() => document.querySelector("#view-library .lib-offhead .fold")?.getAttribute("aria-expanded") === "true"); + assert.deepEqual(await names(page, ".lib-offlist"), ["bravo", "echo", "golf"]); + assert(await offList.isVisible()); + assert.equal(await fold.getAttribute("title"), w("Fold the servers turned off away")); + { const now = await top(fold); assert(Math.abs(now - was) <= 1, `opening moved the head: ${was} → ${now}, scrollTop ${scrolled} → ${await v.evaluate((x) => x.scrollTop)}, window ${await page.evaluate(() => window.scrollY)}`); } + assert(Math.abs(await v.evaluate((x) => x.scrollTop) - scrolled) <= 1, "opening scrolled the page"); + assert.equal(await page.locator("#modal").evaluate((m) => !m.hidden && m.getBoundingClientRect().height > 0).catch(() => false), false, "the fold opened the editor"); + assert.deepEqual(await sideways(page), [], "sideways scroll, open"); + + // remembered across a reload + await page.reload(); + await page.locator('button[data-view="library"]').click(); + await v.locator('.lib-server[data-server="alpha"]').waitFor(); + assert.equal(await v.locator(".lib-offhead .fold").getAttribute("aria-expanded"), "true", "the fold is remembered"); + assert.deepEqual(await names(page, ".lib-offlist"), ["bravo", "echo", "golf"]); + + // a server switched off moves under it, one switched on comes back up + await v.locator('.lib-list:not(.lib-offlist) > .lib-server[data-server="delta"] > .lib-switch').click(); + await page.waitForFunction(() => document.querySelector('#view-library .lib-offlist > .lib-server[data-server="delta"]')); + assert.equal((await v.locator(".lib-offhead .note").textContent()).trim(), "4"); + await v.locator('.lib-offlist > .lib-server[data-server="echo"] > .lib-switch').click(); + await page.waitForFunction(() => document.querySelector('#view-library .lib-list:not(.lib-offlist) > .lib-server[data-server="echo"]')); + assert.deepEqual(await names(page, ".lib-offlist"), ["bravo", "delta", "golf"]); + + // folded, picking opens it, and it can't be folded while picking + await v.locator(".lib-offhead .fold").click(); + await page.waitForFunction(() => document.querySelector("#view-library .lib-offlist")?.hidden); + await v.locator(".lib-serverhead .lib-select").click(); + await v.locator(".lib-pickbar").waitFor(); + assert.equal(await v.locator(".lib-offhead .fold").getAttribute("aria-expanded"), "true"); + assert(await v.locator(".lib-offhead .fold").isDisabled(), "the fold folds while picking"); + assert(await v.locator(".lib-offlist").isVisible(), "a server off is out of sight while picking"); + assert.equal(await v.locator(".lib-offlist .lib-pickbox, .lib-offlist input[type=checkbox]").count() > 0, true, "a server off can't be picked"); + await v.locator(".lib-pickdone").click(); + await page.waitForFunction(() => document.querySelector("#view-library .lib-offlist")?.hidden); + + // every one off: the fold is all there is + for (const n of NAMES) st.off.add(n); + await page.reload(); + await page.locator('button[data-view="library"]').click(); + await v.locator(".lib-offhead .fold").waitFor(); + assert.equal((await v.locator(".lib-offhead .note").textContent()).trim(), String(NAMES.length)); + assert(await v.locator(".lib-list:not(.lib-offlist)").first().evaluate((l) => l.hidden), "an empty list shows"); + // and none off: no fold + st.off.clear(); + await page.reload(); + await page.locator('button[data-view="library"]').click(); + await v.locator('.lib-server[data-server="alpha"]').waitFor(); + assert(await v.locator(".lib-offhead").evaluate((h) => h.hidden), "a fold over nothing"); + + assert.deepEqual(errors, []); + await ctx.close(); + }); + } + }); +} diff --git a/internal/gui/tests/library-mcp-on.test.cjs b/internal/gui/tests/library-mcp-on.test.cjs index d17a730dd..b57f62f47 100644 --- a/internal/gui/tests/library-mcp-on.test.cjs +++ b/internal/gui/tests/library-mcp-on.test.cjs @@ -2,7 +2,8 @@ // swang20201 on X (v0.1.3375, Docker gateway mode): an installed MCP server // in Library could only be removed. Each server row has a switch: off // posts servers/on {on:false}, says the settings are kept, and the row -// shows dimmed with its agent chips out of reach; on posts {on:true} and +// shows dimmed with its agent chips out of reach, under the fold of the +// ones turned off; on posts {on:true} and // the row is as it was. The switch doesn't open the editor. In the app // with an agent at 1100px and a browser in gateway mode at 420px, every // language, both engines: no sideways scroll, no native select. @@ -121,6 +122,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.waitForFunction((x) => document.querySelector("#status")?.textContent === x, w("{name} is off; its settings are kept", { name: "notes" })); assert.deepEqual(st.sent, [{ name: "notes", on: false }]); await page.waitForFunction(() => document.querySelector('#view-library .lib-server[data-server="notes"]')?.classList.contains("off")); + // turned off, it is under the fold below the ones on, folded at first + // (library-mcp-off-fold): opened to see it + assert.equal(await v.locator(".lib-offhead .fold").getAttribute("aria-expanded"), "false"); + await v.locator(".lib-offhead .fold").click(); const offRow = v.locator('.lib-server[data-server="notes"]'); assert.equal(await offRow.locator(":scope > .lib-switch").getAttribute("aria-checked"), "false"); assert.equal(await page.locator("#modal").evaluate((m) => !m.hidden && m.getBoundingClientRect().height > 0).catch(() => false), false, `${where}: the switch opened the editor`);