diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index e1fd5f48e..ce7f4e420 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -58,6 +58,7 @@ something else shows up as drift. - The YAML ones go through `yamlKept` and `mergeKept` in [`sync.go`](../../internal/agent/sync.go). Each is tested by a `TestKeepsTheUsersSettings`. - Copilot in JetBrains IDEs keeps its Bring Your Own Key providers in the Copilot language server's `byok.json`, shared with Xcode's and Eclipse's Copilot (`copilotJetBrains` in [`copilotjetbrains.go`](../../internal/agent/copilotjetbrains.go)). magpie writes its own three keys there, `magpie-provider-config`, `magpie-api-key` and `magpie-models-config`, in the bytes the server itself writes, and only when they differ; the user's providers and keys stay. A magpie model the user hid in Manage Models (`isRegistered: false`) stays hidden through a sync. A new file is made 0600 in a 0700 folder, as the server makes it. - dsh (DeepSeek Harness) sets one API per llm-pi-ai route, so magpie writes a route per protocol (`dshKinds` in [`dsh.go`](../../internal/agent/dsh.go); 01huadalang on Discord): `magpie` (Chat Completions) for most models, `magpie-responses` (`openai-responses`) for a model served on Responses, `magpie-anthropic` (`anthropic-messages`, the gateway root, `forceAdaptiveThinking` where `AdaptiveThinking`) for one served on Messages, by the model's `APIs` (`dshRouteOf`). A model's `APIs` is the one its provider serves it on best (`Provider.Native`, in `magpieModels`, [`route.go`](../../internal/agent/route.go)), and Pi, omp and droid read it the same way. A routing group has `responses` when every member is best on Responses (`allResponses`, #1594), so its tool-call arguments are relayed as they stream; any other group has none and stays on Chat, a Messages-only group too, as a Claude member's thinking is known by its own model. A route with no models is taken out. An api the user picked for a route in dsh's Models page is kept, and so are keys they added there. The start (`agent-default-model`) names its model's route, and Sync moves a start on one of magpie's routes to the route its model is now on (`dshStartOnItsRoute`), its effort and marks kept. Check asks the route the start names to list its model. A dsh session resumed on a model that has since moved routes asks for the model to be picked again, since dsh finds a model by route and id. +- dsh takes a model's listed `maxTokens` as every request's output and reserves it, with 65536 of headroom, out of `contextWindow` before deciding when to compact (compaction-basic's `resolveCompactSpec`: the smaller of 80% of the window and window − maxTokens − 65536). A vendor's reply limit near its window had dsh compact at 41248 of a 500000 group (#2823) or fail with no budget (524288/524288, LoKi on Discord; 131072/65536), so magpie lists it held to a quarter of the window on every route and in the older `llm-deepseek` entry (`dshMaxTokens`), as VS Code and Copilot in JetBrains do. A Max output the user set stays as they set it (`outputOr`), even one that leaves dsh no budget. `TestDshOutputLeavesCompactionRoom`. - DeepSeek Harness Desktop (macOS arm64 and Windows x64; no Linux build) reads the same `$DSH_HOME` or `~/.dsh` as the CLI, as its own profile `profiles/desktop` (`resolveDshHome` and `resolveDesktopPaths` in the app's `lib/main.js`), so it takes magpie's routes with no wiring of its own (#2279, liangjinyuan-sihan). It is found by `/Applications/DeepSeek Harness.app`, by `%LOCALAPPDATA%\Programs\DeepSeek Harness`, or by the folder its current-user installer records under `HKCU\Software\1bf39983-50d0-5fe0-9ef4-cece76f67c5e` (`InstallLocation`), whose Uninstall key gives the version (`registered` in [`desktopapp.go`](../../internal/agent/desktopapp.go)), so a user who picked another folder is found. With the app installed but never opened there is no `~/.dsh`: the row is still listed, and connecting writes `profiles/desktop/cordis.patch.yml` from dsh's own template (`dshProfileTemplate`) with magpie's routes, which the app keeps on its first start, since it writes only the files that are missing. The notice says the app starts on it the first time it opens (`noticeDsh5`). Disconnect before that first start removes the profile magpie made when nothing else is in it (`dshTidyUnopened`); once the app has opened it, the profile stays and only magpie's entries go (`TestDshDesktopNeverOpened`, `TestDshDesktopRegisteredFolder`). - Ante's `catalog.json` keeps user-added fields in `providers.magpie` the same way (`ante` in [`ante.go`](../../internal/agent/ante.go)); its `auth`, `http_headers`, `extra_body` and `stream_idle_timeout_secs` are what a gateway shared on the local network or reached from WSL needs to send a key. Ante starts a session on the `provider` and `model` of `settings.json`, not on what its catalog holds (#1210), so magpie sets that pair and puts back what it found there; a pick the user makes in Ante while magpie is wired is theirs and stands. - AstrBot keeps its providers in `data/cmd_config.json` under its root (`$ASTRBOT_ROOT`, else `~/.astrbot`, the desktop app's, else `~/astrbot`), written with a UTF-8 BOM, which magpie keeps (`astrbot` in [`astrbot.go`](../../internal/agent/astrbot.go)). magpie adds a `magpie` entry to `provider_sources` and one `magpie/` entry per model to `provider`, keeps the user's own entries byte for byte and keeps what the user changes in magpie's (timeout, proxy, enable), and sets the default chat model (`agent_runner.config.model.provider_id`, or `provider_settings.default_provider_id` before the agent runner), putting back what it found there. A pick the user makes while magpie is wired is theirs and stands. The first connect copies the file to `cmd_config.json.before-magpie`. AstrBot reads the file only at start-up and its WebUI writes it back whole on save, so the agent's notice says to restart AstrBot before saving in the WebUI. A Docker install's root is inside its container, which magpie doesn't reach. diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 7b069dbb6..6f0e54bf1 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -126,6 +126,7 @@ recorded as a prediction failure (`noPrediction`). - In turn (`rotate`), a conversation nobody has answered yet goes to the key, account or model the fewest other conversations of the provider's model or the group answered in the last `heldFor` (30 minutes) are on (`leastHeld`, #946). Ties, resting ones and a group with a group in it keep routing's order. With session affinity, two sessions of one group so stay on different models. - A ChatGPT account that holds credits answers past its windows on them; the vendor spends them. That is the default. Set not to spend them (Usage card's *Use credits*, `magpie quota credits off`), the account is held at 100% of a window till it renews, by magpie's latest reading of its windows (`provider.Allowances`, refreshed about every minute), so the other accounts, groups and fallbacks take the request. A cap set on the account (1–99%) takes precedence. Unlike a cap, the hold is at the vendor's own 100%, so an account allowed to spend its resets spends one there, both when every candidate is held and after the last one is refused. A reset made forgets the account's cached allowance (`renewedNow`), so neither hold outlives the windows it started again. - Different failures are classified separately: out of credit, out of quota, rate limit and other errors rest for different lengths. A fix must not merge them into one bucket (see #873). +- One of Codex's own models on the backend path with no routing to do (`codexAccounts` false: one ChatGPT account, no usage cap, no key holds, nothing pinned) is relayed as Codex sent it, on Codex's own sign-in, its bytes and headers unchanged and its reply streamed as it comes (`codexUpstreamOn` with no account): routing was built for more than one account, and that path also keeps the turn's native compaction with the backend. Before, nothing was asked again on it, so an overload went straight to Codex, which doesn't retry the backend's `server_is_overloaded` itself (夜松云 on Discord). Now a transient overload (`codexBusy`: what `busy` calls busy, a 529, a 503 saying overloaded, the backend's in-stream `response.failed` with `server_is_overloaded` (#1418); never a 429, a usage limit, an edge's drop of the connection (`edgeSaidDrop`) or a reset (`codexReset`)) is asked again of the same account, the same body and headers, up to `lastRetries` times after `retryPause<` with the account left out of the candidates, `fallbacksOnly`, and the same keepalive carried in `handedOnKey`); without fallbacks Codex gets the last try's failure as the backend said it. Each try is a `HandedOn` usage record and a try in the trace. A success is relayed as before, with nothing held when no retry or fallback is left (`TestCodexOneAccountOverloadAskedAgain`, `…StreamOverloadAskedAgain`, `…OverloadBounded`, `…OverloadFallsBack`, `…OverloadKeptAlive`, `…RefusalNotAskedAgain` in [`codex_one_account_overload_test.go`](../../internal/gateway/codex_one_account_overload_test.go)). - A subscription account whose sign-in its vendor revoked (`provider.SignInRevoked`: 401 `token_revoked` and the like, #1793) fails as `failAuth`: the next member is asked at once, nothing rests, and the account is marked (`noteSignIn` in [`signin_revoked.go`](../../internal/gateway/signin_revoked.go)). Its later requests aren't sent while it has that credential: `forwardOnce` answers them with a 401 of magpie's own (`revokedReply`), so they too pass on. Compaction on an account of magpie's (`compactOn`) picks a marked one last. A key's provider answering the same words rests as before. - A sub2api key out of its own limit answers 429 `api key 7天限额已用完` (or `日限额`, `5小时限额`) as `rate_limit_exceeded`. It is out of quota (`plannedWords`), not rate limited: it rests till the window it filled renews when its windows as last read say so, else `quotaRest`, and its windows are read again (`staleKeyAllowance`). A reading that finds that window full no more (the limit raised in the relay's panel, or the key's usage reset) lifts the rest (`renewed`, told through `provider.OnRenewed`), as a Codex reset spent does an account's; the key's other rests stay. While it rests out of its windows, they are read again each time it is planned (`restingOf`, once a minute at most), so this holds where nothing weighs it by them: an ordered group. The relay out of accounts for everyone (503 `No available accounts`, or a later version's 429 `All available accounts are currently rate-limited`) says nothing of the key's windows: it backs off as any failure or rate limit does, never to the window. A key's windows count only its own spend, so other users draining the relay's accounts show up as those errors, not in the windows. - A 5xx is a server error, not quota, unless the vendor's own quota code says so (`quotaCodes`: `usage_limit_reached`, `RESOURCE_EXHAUSTED`, Claude Code's `usage limit reached|`). A relay's 500 "当前模型 gpt-5.5 负载已经达到上限,请稍后重试" names its load, not the key's allowance: it was read as out of quota by `usedUpWords` (上限), which rested the key till a reset and kept a group's Patience from waiting it out (#1418). The quota words (`usedUpWords`) still apply to a 4xx. diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 563b7412e..4c71707ec 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -349,7 +349,7 @@ covers it in both engines, every language and a narrow window. ### Shared UI rules -- Settings → General is laid out as macOS System Settings is (1ooogle on X): a row says its name alone when that says enough (Appearance, Colorblind mode, Language, Text size, the fonts, the tray click, the Codex model rows, Open at login, Show in Dock), and keeps one short line where the setting isn't clear from its name or has a consequence (Long conversations, Lightweight mode, Prevent sleep, Session terminal, Codex subagents). A font row's line shows only while its fonts load or fail; the text size keys are the choices' tooltip, and Colorblind mode's note is its Off/On control's (`#colorblindSegs`). Colorblind mode (`settings.Colorblind`, `data-colorblind="1"` on `:root`, #2073) switches the chart series (`--c1`…`--c7`) in both light and dark themes to an Okabe–Ito palette where adjacent series differ in hue and lightness. On a quota curve each window (`data-series`, its index mod 7, set by `drawQuotaPlot` and `quotaCurve`'s legend only) gets a dash of its own on `path.qc-line`, its legend key shows a sample of that line (`.qc-sample`) for the dot, and the even paces (`line.qc-even`) are dotted; the curve's tooltip says so. The balance curve sets no `data-series` and keeps its solid line, dashed fit and dot. The Context tab's "good" grade, which takes `--c2` as a colour rather than a series, keeps a blue (`--c1`). Language is one menu button showing the language picked, opened in the app's menu (`renderLangPick`). See `settings-general.test.cjs` and `quota-curve.test.cjs`. +- Settings → General is laid out as macOS System Settings is (1ooogle on X): a row says its name alone when that says enough (Appearance, Colorblind mode, Language, Text size, the fonts, the tray click, the Codex model rows, Open at login, Show in Dock), and keeps one short line where the setting isn't clear from its name or has a consequence (Long conversations, Lightweight mode, Prevent sleep, Session terminal, Codex subagents). A font row's line shows only while its fonts load or fail; the text size keys are the choices' tooltip, and Colorblind mode's note is its Off/On control's (`#colorblindSegs`). Colorblind mode (`settings.Colorblind`, `data-colorblind="1"` on `:root`, #2073) switches the chart series (`--c1`…`--c7`) in both light and dark themes to an Okabe–Ito palette where adjacent series differ in hue and lightness. On a quota curve each window (`data-series`, its index mod 7, set by `drawQuotaPlot` and `quotaCurve`'s legend only) gets a dash of its own on `path.qc-line`, its legend key shows a sample of that line (`.qc-sample`) for the dot, and the even paces (`line.qc-even`) are dotted; the curve's tooltip says so. The balance curve sets no `data-series` and keeps its solid line, dashed fit and dot. The Context tab's "good" grade, which takes `--c2` as a colour rather than a series, keeps a blue (`--c1`). Language is one menu button showing the language picked, opened in the app's menu (`renderLangPick`). See `settings-general.test.cjs` and `quota-curve.test.cjs`. Open at login reads `autostart.Enabled`, which on macOS 13 and later also asks Background Task Management about magpie's launch agent (`SMAppService.statusForLegacyURL:`, matched by the plist's Label, not its path); a record the user switched off in System Settings › General › Login Items reads as needing allowing, and the row keeps On with one line saying so and a button that opens Login Items (`/api/open` allows that one `x-apple.systempreferences` URL). The status read again when the window comes back to the front clears the line. On macOS 12, in a build without cgo, or when the system can't be asked, the plist alone decides, as before (#2120, `login-allow.test.cjs`, `login_allow_test.go`). - Settings' search-provider picker offers **Off**, saved as `searcher: "off"`. Its help explains API-only search and suppresses provider fallback/own-search hints while off; the search priority row is hidden because no provider competes with the APIs. See [gateway search behavior](gateway-routing.md#turning-provider-search-off), [`renderSearcher`](../../internal/gui/assets/app.js), `TestSettingsSearchProviderOff` and `searcher-pick.test.cjs`. - Settings' search APIs are asked in their listed order: each API's row (with its keys' row) is dragged as one, or moved with Alt+↑/↓, and has a switch that turns it off without removing its key (#2286). See [the search APIs' order](gateway-routing.md#the-search-apis-order-and-one-switched-off), `searchArrange` in [`app.js`](../../internal/gui/assets/app.js) and `search-order.test.cjs`. - Settings' Search APIs add row has a base URL field under the key for every API (#1580): the vendor's own address is its placeholder, picking an API already added fills in its saved URL so a new key alone keeps it, and Add with no key changes only the URL. See [a search API's base URL](gateway-routing.md#a-search-apis-base-url), [`renderSearch`](../../internal/gui/assets/app.js) and `search-api.test.cjs`. diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index ce474ca27..07fda2c11 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -28,7 +28,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it. | Hooks | A `Hook` (#1790) is a command, an event, an optional matcher, a timeout and the agents ticked for it. Its optional `Description` (#2011) says what it is for in any language, since its name is letters, digits, - and _: one line of at most `maxHookDescription` (200) characters, shown under the name; only library.json keeps it, and no agent is given it. Its event is portable (`HookEvents`: turn-end, after-tool, before-tool, prompt, session-start, each under the agent's own name) or an agent's own (`"codex:PermissionRequest"`), which only that agent is given. A portable tool event can be narrowed to shell or edit tools, each agent's own tool names for them. `syncHooks` writes each into the agent's own file and shape (`hookSpecOf`): Claude Code `/settings.json`, Codex `hooks.json` beside its config.toml, Gemini CLI `~/.gemini/settings.json` (timeout in ms), Cursor `~/.cursor/hooks.json` (flat entries, `version: 1`), and Grok Build `~/.grok/config.toml` and Grok App `agent-home/config.toml` as `[[hooks.]]` array tables with a `[[hooks..hooks]]` child. Grok Build and Grok App run the one CLI, so a `grok:` own event goes to both (`sameHookFamily`). Every other agent, and an agent in WSL, is refused with why, and the page greys its chip with that reason. The page also says when an agent has every hook turned off (`hooksOff`: Claude Code's `disableAllHooks`, Gemini's `hooksConfig.enabled`, Codex's `[features] hooks`). | [`hooks.go`](../../internal/library/hooks.go) | | Subagents | A `Subagent` (#2283) is a name (lowercase letters, digits and -), a one-line description, a prompt, and the library's skills and MCP servers it uses, given to the agents ticked for it. `syncSubagents` writes it as a file of its own in each agent's user-level folder, in that agent's format (`subagentSpecOf`): Markdown with YAML front matter in `~/.claude/agents` (with `skills` and `mcpServers`), `~/.factory/droids` (with `mcpServers`), `~/.config/opencode/agents` (`mode: subagent`), `~/.gemini/agents`, `~/.qwen/agents`, `~/.grok/agents`, `~/.cursor/agents` and `~/.copilot/agents` (`.agent.md`); a TOML role (`name`, `description`, `developer_instructions`) in `$CODEX_HOME/agents`. Skills and servers are named only where the agent's file can name them, and only those the library has. The page lists, per agent, whether it binds skills and servers (`SubagentAgentView`) and greys out an agent that takes none. | [`subagents.go`](../../internal/library/subagents.go) | | Backups | Before a change first writes an agent file, `backups` copies it to `BackupDir`, one folder per change. The last `keepBackups` (30) changes are kept. The Backups button at the top of every tab, beside Library folder, opens that folder (`libHead`; Dade on Discord found it at the foot of a long page). | [`backup.go`](../../internal/library/backup.go) | -| RTK | `SetRTK` runs rtk's own installer (`rtk init -g …`) for an agent being switched on. For one being switched off, it removes exactly what the installer wrote, using magpie's own code, which works even with rtk gone. `ReadRTK` reads each agent's files to say which have the hook. An agent gone for its CLI (`CLIMissing`, #2254) isn't offered rtk, but one that still has the hook is listed so it can be taken out. `rtkSpec.blocked` stops the installer where it would break an agent. `rtkSpec.env` tells the installer the agent's folder where rtk would pick another: Hermes Agent's is `appdir.HermesHome` (`%LOCALAPPDATA%\hermes` on Windows), which rtk is given as `HERMES_HOME`, since rtk 0.51 knows only `$HERMES_HOME` and `~/.hermes`. Antigravity CLI (`agy`, #2202) gets rtk 0.51's own plugin for Antigravity, `plugins/rtk` in its global customization folder `~/.gemini/config` (`plugin.json`, `hooks.json` with `PreToolUse` → `rtk hook antigravity`, `rules/AGENTS.md`), which `agy plugin list` lists; switching it off takes that one folder out. rtk 0.50 knows Antigravity only per project and fails `rtk init -g --agent antigravity`, so an older rtk is `blocked` (`agyBlocked`) and the row says to update RTK. OpenCode 2 loads only the plugin rtk 0.52 on writes (one default object with `id` and `setup()`, rtk-ai/rtk#4187); an older rtk's plugin is for OpenCode 1 and OpenCode 2 refuses it, so with an OpenCode 2 here an older rtk is `blocked` (`openCodeBlocked`) and the row says to update RTK (#2295). Under OpenCode 2, an old plugin left from before an rtk update counts as off once the rtk here can write the new one (`openCodeHas`), so switching it on writes the new one over it; with an older rtk it counts as on, so it can be switched off. A detected agent RTK has no hook for at all is still listed, from `rtkNoHook`, with the reason and a switch that can't be turned on (dsh: its hooks can allow or deny a command but not rewrite it, and `rtk init` has no `--agent dsh`; Grok Build and Grok App: `rtk init` has no Grok or Grok App agent, so both are listed with the switch off). | [`rtk.go`](../../internal/library/rtk.go) | +| RTK | `SetRTK` runs rtk's own installer (`rtk init -g …`) for an agent being switched on. For one being switched off, it removes exactly what the installer wrote, using magpie's own code, which works even with rtk gone. `ReadRTK` reads each agent's files to say which have the hook. An agent gone for its CLI (`CLIMissing`, #2254) isn't offered rtk, but one that still has the hook is listed so it can be taken out. `rtkSpec.blocked` stops the installer where it would break an agent. `rtkSpec.env` tells the installer the agent's folder where rtk would pick another: Hermes Agent's is `appdir.HermesHome` (`%LOCALAPPDATA%\hermes` on Windows), which rtk is given as `HERMES_HOME`, since rtk 0.51 knows only `$HERMES_HOME` and `~/.hermes`. Antigravity CLI (`agy`, #2202) gets rtk 0.51's own plugin for Antigravity, `plugins/rtk` in its global customization folder `~/.gemini/config` (`plugin.json`, `hooks.json` with `PreToolUse` → `rtk hook antigravity`, `rules/AGENTS.md`), which `agy plugin list` lists; switching it off takes that one folder out. rtk 0.50 knows Antigravity only per project and fails `rtk init -g --agent antigravity`, so an older rtk is `blocked` (`agyBlocked`) and the row says to update RTK. OpenCode 2 loads only the plugin rtk 0.52 on writes (one default object with `id` and `setup()`, rtk-ai/rtk#4187); an older rtk's plugin is for OpenCode 1 and OpenCode 2 refuses it, so with an OpenCode 2 here an older rtk is `blocked` (`openCodeBlocked`) and the row says to update RTK (#2295). Under OpenCode 2, an old plugin left from before an rtk update counts as off once the rtk here can write the new one (`openCodeHas`), so switching it on writes the new one over it; with an older rtk it counts as on, so it can be switched off. A detected agent RTK has no hook for at all is still listed, from `rtkNoHook`, with the reason and a switch that can't be turned on (dsh: its hooks can allow or deny a command but not rewrite it, and `rtk init` has no `--agent dsh`; Grok Build and Grok App: `rtk init` has no Grok or Grok App agent, so both are listed with the switch off). The page's No RTK hook tag gives each agent's own reason and rtk-ai/rtk issue (`rtkNoHookWhy` in plugins/library/client.js: dsh #3847, Grok Build and Grok App #2136), and an agent with no entry gets no link; `TestRTKNoHookIssuesAreEachAgents` fails when the page and `rtkNoHook` cite different issues, or two agents cite the same ones without a reason in `sharedRTKIssues`. | [`rtk.go`](../../internal/library/rtk.go) | ## Runtime path diff --git a/internal/agent/dsh.go b/internal/agent/dsh.go index be8b7223b..3a6bce4f3 100644 --- a/internal/agent/dsh.go +++ b/internal/agent/dsh.go @@ -1500,6 +1500,23 @@ func dshLevels(ref string) []string { return nil } +// dshMaxTokens is the maxTokens magpie lists m with. dsh takes a listed +// maxTokens as every request's output and reserves it, with 65536 of +// headroom, out of contextWindow before it decides when to compact +// (compaction-basic's resolveCompactSpec: the threshold is the smaller of +// 80% of the window and window - maxTokens - 65536). A vendor's reply limit +// near its window leaves dsh compacting at a sliver of it, or failing to +// (#2823): 500000 with 393216 compacted at 41248; 524288 with 524288, and +// 131072 with 65536, left it no budget at all. So the vendor's figure is +// held to a quarter of the window, as VS Code's and Copilot's are, while a +// Max output the user set stays as they set it (outputOr). +func dshMaxTokens(m catalog.Model) int { + if m.Context <= 0 { + return maxTokens(m) + } + return outputOr(m, min(maxTokens(m), max(1, m.Context/4))) +} + // dshRouteConfig is magpie's first route with every one of models on it. func dshRouteConfig(models []catalog.Model, api, gw string) dshPiRoute { return dshKindConfig(dshKinds[0], models, api, gw) @@ -1518,7 +1535,7 @@ func dshKindConfig(k dshKind, models []catalog.Model, api, gw string) dshPiRoute for _, m := range models { e := dshPiModel{ID: m.ID, Name: m.Name, ContextWindow: m.Context} if m.Output > 0 { - e.MaxTokens = maxTokens(m) + e.MaxTokens = dshMaxTokens(m) } switch { case m.Images: @@ -1604,7 +1621,7 @@ func dshProviderLines(effort string, models []catalog.Model, gw string) []string lines = append(lines, fmt.Sprintf(" contextWindow: %d", m.Context)) } if m.Output > 0 { - lines = append(lines, fmt.Sprintf(" maxTokens: %d", maxTokens(m))) + lines = append(lines, fmt.Sprintf(" maxTokens: %d", dshMaxTokens(m))) } if m.Images { lines = append(lines, " inputModalities: [text, image]") diff --git a/internal/agent/dsh_compaction_budget_test.go b/internal/agent/dsh_compaction_budget_test.go new file mode 100644 index 000000000..0531722bc --- /dev/null +++ b/internal/agent/dsh_compaction_budget_test.go @@ -0,0 +1,66 @@ +package agent + +import ( + "fmt" + "strings" + "testing" + + "github.com/yetone/magpie/internal/catalog" +) + +// dshCompactsAt is where dsh's compaction-basic starts compacting a model +// listed with window and maxTokens out, as its resolveCompactSpec works it +// out with the default policy (thresholdRatio 0.8, headroomTokens 65536): +// 0 when it has no budget and fails instead (#2823). +func dshCompactsAt(window, out int) int { + pressure := window - out - 65536 + if window-out <= 0 || pressure <= 0 { + return 0 + } + return min(window*8/10, pressure) +} + +// TestDshOutputLeavesCompactionRoom: dsh reserves the maxTokens magpie lists +// a model with, and 65536 more, out of its window before it compacts. A +// vendor's reply limit near the window had dsh compact at 41248 of a 500000 +// group (#2823) or fail outright on 524288/524288 (LoKi on Discord) and +// 131072/65536; it is held to a quarter of the window on every route and in +// the older llm-deepseek entry, while a Max output the user set stays. +func TestDshOutputLeavesCompactionRoom(t *testing.T) { + for _, tc := range []struct { + name string + model catalog.Model + want int + }{ + {"full window", catalog.Model{ID: "space-bunny-free", Context: 524288, Output: 524288}, 131072}, + {"above the window", catalog.Model{ID: "above", Context: 524288, Output: 1048576}, 131072}, + {"group window under its members' output", catalog.Model{ID: "group/smart-split", Context: 500000, Output: 393216}, 125000}, + {"half the window", catalog.Model{ID: "k131", Context: 131072, Output: 65536}, 32768}, + {"within a quarter", catalog.Model{ID: "flash", Context: 1000000, Output: 128000}, 128000}, + {"user output", catalog.Model{ID: "user", Context: 524288, Output: 393216, OutputSet: true}, 393216}, + {"user full window", catalog.Model{ID: "user-full", Context: 524288, Output: 524288, OutputSet: true}, 524288}, + {"unknown window", catalog.Model{ID: "unknown", Output: 128000}, 128000}, + {"unknown output", catalog.Model{ID: "no-output", Context: 524288}, 0}, + } { + t.Run(tc.name, func(t *testing.T) { + for _, k := range dshKinds { + got := dshKindConfig(k, []catalog.Model{tc.model}, "", "http://127.0.0.1:3425").Models[0] + if got.MaxTokens != tc.want || got.ContextWindow != tc.model.Context { + t.Fatalf("%s: contextWindow %d, maxTokens %d; want %d, %d", k.key, got.ContextWindow, got.MaxTokens, tc.model.Context, tc.want) + } + } + lines := strings.Join(dshProviderLines("high", []catalog.Model{tc.model}, "http://127.0.0.1:3425"), "\n") + if tc.want > 0 && !strings.Contains(lines+"\n", fmt.Sprintf("maxTokens: %d\n", tc.want)) { + t.Fatalf("llm-deepseek entry, want maxTokens: %d:\n%s", tc.want, lines) + } + if tc.want == 0 && strings.Contains(lines, "maxTokens") { + t.Fatalf("llm-deepseek entry lists a maxTokens for a model of no known output:\n%s", lines) + } + if tc.model.Context > 0 && !tc.model.OutputSet { + if at := dshCompactsAt(tc.model.Context, tc.want); at < tc.model.Context/4 { + t.Fatalf("dsh compacts %d/%d at %d tokens", tc.model.Context, tc.want, at) + } + } + }) + } +} diff --git a/internal/agent/dsh_test.go b/internal/agent/dsh_test.go index ee63e397b..1e309f473 100644 --- a/internal/agent/dsh_test.go +++ b/internal/agent/dsh_test.go @@ -197,7 +197,7 @@ func TestDshModelLimits(t *testing.T) { want := ` - id: v/see name: see · V contextWindow: 400000 - maxTokens: 128000 + maxTokens: 100000 input: [text, image] - id: v/plain name: plain · V diff --git a/internal/agent/sync_test.go b/internal/agent/sync_test.go index 5cbfe8d24..435eebcce 100644 --- a/internal/agent/sync_test.go +++ b/internal/agent/sync_test.go @@ -139,10 +139,11 @@ func TestCrushModelsCarryMaxTokens(t *testing.T) { // output. ZCode and WorkBuddy cap it at zcodeMaxOutput besides, Crush falls // back to 16384 without a known output, OpenCode is handed no limit without // a window, and AtomCode and Snow CLI, each told a window of its own when -// the model's isn't known, are cut to that. +// the model's isn't known, are cut to that. dsh is held to a quarter of +// a known window (dshMaxTokens, #2823). func TestMaxTokensWithinContextWindow(t *testing.T) { home := syncHome(t) - check := func(limit string, want int) { + check := func(limit string, want, window int) { t.Helper() os.WriteFile(catalog.CachePath(), []byte(`{"zai":{"models":{"glm-4.6":{"id":"glm-4.6","name":"GLM-4.6","limit":{`+limit+`}}}}}`), 0o644) catalog.Reset() @@ -179,6 +180,12 @@ func TestMaxTokensWithinContextWindow(t *testing.T) { if !strings.Contains(limit, "context") { told = strconv.Itoa(min(want, atomcodeContext)) } + // dsh reserves maxTokens out of its window before compacting, so a + // known window holds it to a quarter (dshMaxTokens, #2823). + dshTold := n + if strings.Contains(limit, "context") { + dshTold = strconv.Itoa(min(want, window/4)) + } snowTold := n if !strings.Contains(limit, "context") { snowTold = strconv.Itoa(min(want, snowContext)) @@ -187,7 +194,7 @@ func TestMaxTokensWithinContextWindow(t *testing.T) { "pi": {string(pi), `"maxTokens":` + n}, "cline": {string(cline), `"maxTokens":` + n}, "omp": {string(omp), "maxTokens: " + n}, - "dsh": {string(dshRoute), "maxTokens: " + n}, + "dsh": {string(dshRoute), "maxTokens: " + dshTold}, "droid": {string(droid), `"maxOutputTokens":` + n}, "qoder": {string(qoder), `"maxOutputTokens":` + n}, "hanako": {string(hanako), `"maxOutput":` + n}, @@ -207,10 +214,10 @@ func TestMaxTokensWithinContextWindow(t *testing.T) { } } } - check(`"context":128000,"output":384000`, 128000) - check(`"output":384000`, 384000) - check(`"context":204800,"output":131072`, 131072) - check(`"context":64000,"output":384000`, 64000) + check(`"context":128000,"output":384000`, 128000, 128000) + check(`"output":384000`, 384000, 0) + check(`"context":204800,"output":131072`, 131072, 204800) + check(`"context":64000,"output":384000`, 64000, 64000) } // A provider added after a magpie model was picked reaches the lists agents diff --git a/internal/autostart/autostart.go b/internal/autostart/autostart.go index 5cbb147ab..2ca573d95 100644 --- a/internal/autostart/autostart.go +++ b/internal/autostart/autostart.go @@ -16,8 +16,37 @@ import ( // Arg is what magpie is started with at login: the tray, no window. const Arg = "tray" -// Enabled reports whether magpie opens at login. -func Enabled() bool { return enabled() } +// State is whether magpie opens at login, as the system will act on it. +type State string + +const ( + // Off: no record, so nothing opens magpie at login. + Off State = "off" + // On: the record is there, and nothing the system says holds it back. + On State = "on" + // NeedsAllowing: the record is there, but the user switched it off in + // the system's own settings (on the Mac, System Settings › General › + // Login Items › Allow in the Background), so it opens nothing until + // it is allowed there again; writing the record anew doesn't do that. + NeedsAllowing State = "allow" +) + +// LoginItemsURL opens System Settings' Login Items pane, where a record +// that NeedsAllowing is allowed again. +const LoginItemsURL = "x-apple.systempreferences:com.apple.LoginItems-Settings.extension" + +// Enabled reports whether magpie opens at login. A system that can't be +// asked, or that answers something else, is not taken for a no: the +// record's own word stands (On). +func Enabled() State { + if !enabled() { + return Off + } + if heldBack() { + return NeedsAllowing + } + return On +} // Set has magpie open at login, or not, as this copy of it. func Set(on bool) error { diff --git a/internal/autostart/autostart_android.go b/internal/autostart/autostart_android.go index 1ea69cfe0..a1aea3c79 100644 --- a/internal/autostart/autostart_android.go +++ b/internal/autostart/autostart_android.go @@ -41,3 +41,6 @@ func disable() error { } func refresh() error { return nil } + +// heldBack: nothing here is switched off apart from the record itself +func heldBack() bool { return false } diff --git a/internal/autostart/autostart_android_test.go b/internal/autostart/autostart_android_test.go index 6c10de4e3..c27110694 100644 --- a/internal/autostart/autostart_android_test.go +++ b/internal/autostart/autostart_android_test.go @@ -25,13 +25,13 @@ func TestBootScript(t *testing.T) { if err := os.Chmod(record(), 0o600); err != nil { t.Fatal(err) } - if Enabled() { + if Enabled() != Off { t.Fatal("non-executable script reported as enabled") } if err := enable(exe); err != nil { t.Fatal(err) } - if !Enabled() { + if Enabled() == Off { t.Fatal("enable did not restore executable permission") } if err := exec.Command("/system/bin/sh", record()).Run(); err != nil { diff --git a/internal/autostart/autostart_darwin.go b/internal/autostart/autostart_darwin.go index 422b0d774..1671afec1 100644 --- a/internal/autostart/autostart_darwin.go +++ b/internal/autostart/autostart_darwin.go @@ -28,6 +28,31 @@ func enabled() bool { return err == nil && ourLabel.Match(b) && program.Match(b) } +// What ServiceManagement's statusForLegacyURL: says of a launch agent +// (SMAppServiceStatus). Background Task Management keeps it, by the +// plist's Label, wherever the file is: switched off under Login Items › +// Allow in the Background, it is requiresApproval, and stays so when the +// plist is written anew, or removed and written again. launchctl +// print-disabled doesn't follow that switch (it went on saying enabled, +// macOS 26.2), so it isn't asked. +const ( + smNotRegistered = 0 + smEnabled = 1 + smRequiresApproval = 2 + smNotFound = 3 + // the system couldn't be asked: before macOS 13, or a build without cgo + smUnknown = -1 +) + +// legacyStatus asks the system about the launch agent at path. A var for +// the tests; a build without cgo can't ask. +var legacyStatus = func(path string) int { return smUnknown } + +// heldBack: the system says the user switched the launch agent off. Only +// requiresApproval says so; not registered yet, not found, or no answer +// leave the record's own word. +func heldBack() bool { return legacyStatus(record()) == smRequiresApproval } + // a launch agent the system loads at the next login: the app itself, run // once, not kept alive — quitting magpie quits it until then func enable(exe string) error { diff --git a/internal/autostart/autostart_darwin_test.go b/internal/autostart/autostart_darwin_test.go index c1d9c4eda..495cba573 100644 --- a/internal/autostart/autostart_darwin_test.go +++ b/internal/autostart/autostart_darwin_test.go @@ -51,7 +51,7 @@ func TestRefreshOlderLaunchAgent(t *testing.T) { home := t.TempDir() t.Setenv("HOME", home) t.Setenv("USERPROFILE", home) - if err := Refresh(); err != nil || Enabled() { + if err := Refresh(); err != nil || Enabled() != Off { t.Fatalf("Refresh turned Open at login on: %v", err) } if _, err := os.Stat(filepath.Join(home, "Library")); !os.IsNotExist(err) { @@ -176,7 +176,7 @@ func TestSetThenTruncatedRecordReadsAsOff(t *testing.T) { if err := Set(true); err != nil { t.Fatal(err) } - if !Enabled() { + if Enabled() == Off { t.Fatal("not on after Set(true)") } p := record() @@ -190,13 +190,13 @@ func TestSetThenTruncatedRecordReadsAsOff(t *testing.T) { if err := os.WriteFile(p, head, 0o644); err != nil { t.Fatal(err) } - if Enabled() { + if Enabled() != Off { t.Errorf("a launch agent with no ProgramArguments reads as on:\n%s", head) } if err := os.WriteFile(p, nil, 0o644); err != nil { t.Fatal(err) } - if Enabled() { + if Enabled() != Off { t.Error("an empty launch agent reads as on") } // a program named as nothing is no program to run either, and launchd @@ -205,7 +205,93 @@ func TestSetThenTruncatedRecordReadsAsOff(t *testing.T) { if err := os.WriteFile(p, []byte(empty), 0o644); err != nil { t.Fatal(err) } - if Enabled() { + if Enabled() != Off { t.Errorf("a launch agent with no program reads as on:\n%s", empty) } } + +// Switched off under System Settings › Login Items › Allow in the +// Background, the launch agent stays where it was and opens nothing, so +// Open at login says it needs allowing, not on (#2120). Only the system's +// requiresApproval says that: no answer, or any other, leaves the record's +// word, and no record is off whatever the system says. +func TestEnabledFollowsTheSystemsSwitch(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + prev := legacyStatus + t.Cleanup(func() { legacyStatus = prev }) + var asked string + status := smRequiresApproval + legacyStatus = func(p string) int { asked = p; return status } + + if got := Enabled(); got != Off { + t.Fatalf("no launch agent reads %q, want off", got) + } + if err := Set(true); err != nil { + t.Fatal(err) + } + if got := Enabled(); got != NeedsAllowing { + t.Fatalf("switched off in System Settings reads %q, want %q", got, NeedsAllowing) + } + if asked != record() { + t.Fatalf("asked the system about %q, not the launch agent %q", asked, record()) + } + for _, s := range []int{smEnabled, smNotRegistered, smNotFound, smUnknown, 7} { + status = s + if got := Enabled(); got != On { + t.Errorf("the system answering %d reads %q, want on", s, got) + } + } + status = smRequiresApproval + if err := Set(false); err != nil { + t.Fatal(err) + } + if got := Enabled(); got != Off { + t.Fatalf("turned off reads %q", got) + } +} + +// The system's switch is kept by the launch agent's label, wherever its +// plist is: a test's record under a sandbox home is com.yetone.magpie +// too, and the system would answer for the user's own. The tests ask a +// stand-in that knows nothing; askSystem is the real question. +var askSystem func(string) int + +func keepToTheSandbox() { + askSystem = legacyStatus + legacyStatus = func(string) int { return smUnknown } +} + +// The real question reaches ServiceManagement: a launch agent under a +// label Background Task Management has never seen is notFound, and a path +// with no file at all is notRegistered. The user's own label is never +// asked about. +func TestLegacyStatusAsksTheSystem(t *testing.T) { + out, err := exec.Command("sw_vers", "-productVersion").Output() + if err != nil { + t.Skip("no sw_vers") + } + dir := t.TempDir() + p := filepath.Join(dir, "com.yetone.magpie-test.plist") + b := strings.Replace(string(plist("/usr/bin/true")), ""+label+"", "com.yetone.magpie-test-"+filepath.Base(dir)+"", 1) + if err := os.WriteFile(p, []byte(b), 0o644); err != nil { + t.Fatal(err) + } + got := askSystem(p) + if major := strings.SplitN(strings.TrimSpace(string(out)), ".", 2)[0]; major == "11" || major == "12" { + if got != smUnknown { + t.Fatalf("macOS %s answered %d, want unknown", out, got) + } + return + } + if !cgoBuilt { + t.Skip("built without cgo: the system can't be asked") + } + if got != smNotFound { + t.Errorf("a label BTM never saw answered %d, want notFound (%d)", got, smNotFound) + } + if got := askSystem(filepath.Join(dir, "none.plist")); got != smNotRegistered { + t.Errorf("no file answered %d, want notRegistered (%d)", got, smNotRegistered) + } +} diff --git a/internal/autostart/autostart_other.go b/internal/autostart/autostart_other.go index e05d6d5b9..3bf1c5924 100644 --- a/internal/autostart/autostart_other.go +++ b/internal/autostart/autostart_other.go @@ -58,3 +58,6 @@ func disable() error { // refresh: nothing an older magpie wrote here needs writing again func refresh() error { return nil } + +// heldBack: nothing here is switched off apart from the record itself +func heldBack() bool { return false } diff --git a/internal/autostart/autostart_other_test.go b/internal/autostart/autostart_other_test.go index ca6daa6b0..6f48abe6a 100644 --- a/internal/autostart/autostart_other_test.go +++ b/internal/autostart/autostart_other_test.go @@ -21,7 +21,7 @@ func TestSetThenTruncatedRecordReadsAsOff(t *testing.T) { if err := Set(true); err != nil { t.Fatal(err) } - if !Enabled() { + if Enabled() == Off { t.Fatal("not on after Set(true)") } p := record() @@ -35,13 +35,13 @@ func TestSetThenTruncatedRecordReadsAsOff(t *testing.T) { if err := os.WriteFile(p, head, 0o644); err != nil { t.Fatal(err) } - if Enabled() { + if Enabled() != Off { t.Errorf("a desktop entry with no Exec reads as on:\n%s", head) } if err := os.WriteFile(p, nil, 0o644); err != nil { t.Fatal(err) } - if Enabled() { + if Enabled() != Off { t.Error("an empty desktop entry reads as on") } // an Exec key with nothing after it names nothing to run either, and the @@ -49,7 +49,7 @@ func TestSetThenTruncatedRecordReadsAsOff(t *testing.T) { if err := os.WriteFile(p, []byte("[Desktop Entry]\nType=Application\nName=magpie\nExec=\n"), 0o644); err != nil { t.Fatal(err) } - if Enabled() { + if Enabled() != Off { t.Error("a desktop entry with an empty Exec reads as on") } } diff --git a/internal/autostart/autostart_sm_darwin.go b/internal/autostart/autostart_sm_darwin.go new file mode 100644 index 000000000..848503ae3 --- /dev/null +++ b/internal/autostart/autostart_sm_darwin.go @@ -0,0 +1,33 @@ +//go:build darwin && cgo + +package autostart + +/* +#cgo CFLAGS: -x objective-c -fobjc-arc +#cgo LDFLAGS: -framework Foundation -framework ServiceManagement +#include +#import +#import + +// SMAppService is macOS 13's; before it there is nothing to ask (-1) +static long magpieLegacyStatus(const char *path) { + if (@available(macOS 13.0, *)) { + @autoreleasepool { + NSURL *u = [NSURL fileURLWithPath:[NSString stringWithUTF8String:path]]; + return (long)[SMAppService statusForLegacyURL:u]; + } + } + return -1; +} +*/ +import "C" + +import "unsafe" + +func init() { + legacyStatus = func(path string) int { + p := C.CString(path) + defer C.free(unsafe.Pointer(p)) + return int(C.magpieLegacyStatus(p)) + } +} diff --git a/internal/autostart/autostart_test.go b/internal/autostart/autostart_test.go index 260815687..890602749 100644 --- a/internal/autostart/autostart_test.go +++ b/internal/autostart/autostart_test.go @@ -18,13 +18,13 @@ func TestSet(t *testing.T) { t.Setenv("USERPROFILE", home) t.Setenv("XDG_CONFIG_HOME", home+"/.config") t.Setenv("APPIMAGE", "/opt/my apps/magpie.AppImage") - if Enabled() { + if Enabled() != Off { t.Fatal("on before it was turned on") } if err := Set(true); err != nil { t.Fatal(err) } - if !Enabled() { + if Enabled() == Off { t.Fatal("not on after Set(true)") } path := record() @@ -41,7 +41,7 @@ func TestSet(t *testing.T) { t.Errorf("%s lacks %q:\n%s", path, want, b) } } - if err := Set(false); err != nil || Enabled() { + if err := Set(false); err != nil || Enabled() != Off { t.Fatalf("still on after Set(false): %v", err) } if err := Set(false); err != nil { diff --git a/internal/autostart/autostart_windows.go b/internal/autostart/autostart_windows.go index a9ae231ff..8b111bdd9 100644 --- a/internal/autostart/autostart_windows.go +++ b/internal/autostart/autostart_windows.go @@ -117,3 +117,6 @@ func disable() error { // refresh: nothing an older magpie wrote here needs writing again func refresh() error { return nil } + +// heldBack: nothing here is switched off apart from the record itself +func heldBack() bool { return false } diff --git a/internal/autostart/autostart_windows_test.go b/internal/autostart/autostart_windows_test.go index a5b6d09dd..d76126369 100644 --- a/internal/autostart/autostart_windows_test.go +++ b/internal/autostart/autostart_windows_test.go @@ -44,13 +44,13 @@ func TestEnabledUnreadableKeyIsNotOff(t *testing.T) { openRunKey = func(registry.Key, string, uint32) (registry.Key, error) { return 0, windows.ERROR_ACCESS_DENIED } - if !Enabled() { + if Enabled() == Off { t.Fatal("a Run key that cannot be read reads as off") } openRunKey = func(registry.Key, string, uint32) (registry.Key, error) { return 0, registry.ErrNotExist } - if Enabled() { + if Enabled() != Off { t.Fatal("no Run key reads as on") } } @@ -121,7 +121,7 @@ func TestEnabledWithNoMarkerIsOn(t *testing.T) { openApprovedKey = func(registry.Key, string, uint32) (registry.Key, error) { return 0, registry.ErrNotExist } - if !Enabled() { + if Enabled() == Off { t.Fatal("a Run value with no Startup apps marker reads as off") } } diff --git a/internal/autostart/cgo_darwin_test.go b/internal/autostart/cgo_darwin_test.go new file mode 100644 index 000000000..73af65cb3 --- /dev/null +++ b/internal/autostart/cgo_darwin_test.go @@ -0,0 +1,6 @@ +//go:build darwin && cgo + +package autostart + +// cgoBuilt: this build asks ServiceManagement (autostart_sm_darwin.go) +const cgoBuilt = true diff --git a/internal/autostart/isolate_other_test.go b/internal/autostart/isolate_other_test.go new file mode 100644 index 000000000..3a7ea2536 --- /dev/null +++ b/internal/autostart/isolate_other_test.go @@ -0,0 +1,6 @@ +//go:build !darwin + +package autostart + +// keepToTheSandbox: only the Mac's switch is asked of the system +func keepToTheSandbox() {} diff --git a/internal/autostart/main_test.go b/internal/autostart/main_test.go index f3937e852..4f2b3d87d 100644 --- a/internal/autostart/main_test.go +++ b/internal/autostart/main_test.go @@ -6,5 +6,9 @@ import ( "github.com/yetone/magpie/internal/testenv" ) -// The tests run in a home of their own, never the user's real files. -func TestMain(m *testing.M) { testenv.Main(m) } +// The tests run in a home of their own, never the user's real files, and +// never ask the system about the user's own login item. +func TestMain(m *testing.M) { + keepToTheSandbox() + testenv.Main(m) +} diff --git a/internal/autostart/nocgo_darwin_test.go b/internal/autostart/nocgo_darwin_test.go new file mode 100644 index 000000000..58d8d331d --- /dev/null +++ b/internal/autostart/nocgo_darwin_test.go @@ -0,0 +1,6 @@ +//go:build darwin && !cgo + +package autostart + +// cgoBuilt: this build has no way to ask ServiceManagement +const cgoBuilt = false diff --git a/internal/cli/autostart_cli.go b/internal/cli/autostart_cli.go index 1a28dc8ff..e6ee8659c 100644 --- a/internal/cli/autostart_cli.go +++ b/internal/cli/autostart_cli.go @@ -22,13 +22,17 @@ func autostartCmd(args []string) error { return fmt.Errorf("usage: magpie autostart [on|off]") } } - if autostart.Enabled() { + switch autostart.Enabled() { + case autostart.NeedsAllowing: + // the record is there, and Set(true) can't undo the user's switch + fmt.Println("magpie is set to open at login, but it is switched off in System Settings › General › Login Items › Allow in the Background: switch it on there") + case autostart.On: if runtime.GOOS == "android" { fmt.Println(green.Render("✓"), "magpie starts the gateway at boot (requires Termux:Boot)") } else { fmt.Println(green.Render("✓"), "magpie opens at login, in the tray") } - } else { + default: fmt.Println("magpie doesn't open at login") } return nil diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 42eafeb85..fd1613e00 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -278,8 +278,11 @@ func installed(f func(manager) error) error { }) } -// autostartEnabled is a var for the tests. -var autostartEnabled = autostart.Enabled +// autostartEnabled: magpie's own record is there, whether or not the +// user has it switched off in System Settings for now, since switching +// it back on there opens the app with the service still installed. A +// var for the tests. +var autostartEnabled = func() bool { return autostart.Enabled() != autostart.Off } // self is the program the service runs: this one, by the name on PATH // when that is this same file, so a package manager's link (Homebrew's diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index b783f9be7..07e4e654e 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -829,6 +829,7 @@ func (s *Server) codexUpstream(w http.ResponseWriter, r *http.Request, rest stri func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest string, body []byte, on *provider.Provider) { start := time.Now() usage.Saw(agentOf(r)) + w0, body0 := w, body // as they came, for the fallbacks (codexFallBack) if r.Method == http.MethodPost { var unmask func() var err error @@ -852,6 +853,18 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st if r.URL.RawQuery != "" { u += "?" + r.URL.RawQuery } + // Codex's turn on its own sign-in, the one account it has, with + // nobody else to ask (codexAccounts): an overload of the backend's — + // a busy status, or server_is_overloaded on a stream that has said + // nothing yet (#1418), which Codex doesn't ask again for — is asked + // again of it, as the accounts loop asks its last account, the same + // bytes with the same sign-in, and then of the subscription's + // fallbacks; nobody rests for it (夜松云 on Discord) + overload := r.Method == http.MethodPost && rest == "/responses" && base == provider.CodexBase && on == nil + streams := streamOf(body) + kept := &keptAlive{proto: provider.Responses, told: start, streams: streams} + busyAgain := 0 // times the turn was asked again for an overload + var tried []string // what each of those said, for the request log // a turn goes in the Routing view's live trace as the others do, to // the one it can go to: Codex's own sign-in, or its key var tr *Route @@ -904,10 +917,12 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st window = cmp.Or(provider.CodexWindow(user, model), catalog.ContextOf(model)) } s.trace.update(tr, func(t *Route) { - t.Tries[0].Done, t.Tries[0].Status, t.Tries[0].Millis, t.Tries[0].Error = true, status, ms, msg - t.Tries[0].TTFT, t.Tries[0].FirstText = ttft, text + // the last try: the turn asked again for an overload has one each + try := &t.Tries[len(t.Tries)-1] + try.Done, try.Status, try.Millis, try.Error = true, status, time.Since(try.Start).Milliseconds(), msg + try.TTFT, try.FirstText = ttft, text t.ReasoningHidden = first.hidesReasoning(provider.Responses) - t.Tries[0].ReasoningHidden = t.ReasoningHidden + try.ReasoningHidden = t.ReasoningHidden t.Done, t.Status, t.Error, t.Millis, t.Tokens = true, status, msg, ms, tokens if t.TitleLink != nil && isTitleKind(kind) && status < 400 && msg == "" && !titleReply.truncated { link := *t.TitleLink @@ -916,13 +931,13 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st } t.Output, t.Reasoning, t.TTFT, t.FirstText = out, uu.Reasoning, ttft, text flow := first.flowFor(uu.Reasoning) - t.Flow, t.Tries[0].Flow = flow, flow + t.Flow, try.Flow = flow, flow t.Usage = routeUsage("openai", model, uu) if prompt != nil { t.Prompt = prompt.calibrated(promptCounted(t.Usage), window) } - t.Tries[0].Served, t.Tries[0].Swapped = served, swapped(model, served) - t.Served, t.Swapped = t.Tries[0].Served, t.Tries[0].Swapped + try.Served, try.Swapped = served, swapped(model, served) + t.Served, t.Swapped = try.Served, try.Swapped }) } } @@ -931,188 +946,311 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st resetNote := "" // what spending it did, for the request log resets := 0 // times a large request ChatGPT closed on was asked again (#1628) sent := len(body) // the bytes that went, compressed (provider.CodexCompressed) - for tries := 0; ; tries++ { - ctx := provider.ViaSignedIn(r.Context(), "codex") - if on != nil { - ctx = on.Via(r.Context()) - } - req, err := http.NewRequestWithContext(ctx, r.Method, u, bytes.NewReader(body)) - if err != nil { - writeError(w, provider.Responses, 502, err.Error()) - end(502, err.Error(), 0, 0) + began := start // when the try now going began + // failWith tells Codex of a failure before any reply: as the stream's + // error once it was sent the stream's headers while it waited + failWith := func(status int, msg string) { + if kept.sent { + streamError(w, provider.Responses, status, msg) return } - copyHeaders(req.Header, r.Header) - if on != nil { - // the account's own token and id in place of the sign-in's; - // what Codex said it takes back stays as it said it - accept := req.Header.Values("Accept") - if err := on.Sign(ctx, req, provider.Responses, body); err != nil { - msg := "OpenAI (" + on.Account.User + "): " + err.Error() - writeError(w, provider.Responses, 502, msg) + writeError(w, provider.Responses, status, msg) + } + // handOn notes a try that failed for an overload, which the turn goes + // on from, after wait: in the trace, and as a row handed on, as the + // accounts loop notes one + handOn := func(status int, msg string, wait time.Duration) { + s.trace.update(tr, func(t *Route) { + try := &t.Tries[len(t.Tries)-1] + try.Done, try.Status, try.Error, try.Fail = true, status, msg, failOther + try.Millis, try.Again = time.Since(try.Start).Milliseconds(), wait.Milliseconds() + }) + servedProvider, servedAccount := codexServed(base, r.Header, on) + rec := usage.Record{RouteID: tr.ID, Time: began, Agent: agentOf(r), Provider: servedProvider, Host: provider.HostOf(base), + ProviderAccount: servedAccount, Model: modelOf(body), Requested: modelOf(body), Effort: effort, + Millis: time.Since(began).Milliseconds(), Status: status, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), + Kind: kind, Endpoint: r.URL.Path, HandedOn: true} + failedWith(&rec, status, msg, "") + appendUsage(r, rec) + tried = append(tried, fmt.Sprintf("openai: %d %s", status, msg)) + } + // askAgain pauses wait, Codex kept alive meanwhile, for the turn to be + // asked again; false when Codex went away in it + askAgain := func(status int, msg string, wait time.Duration) bool { + handOn(status, msg, wait) + busyAgain++ + if !pauseAlive(r.Context(), w, kept, streams, start, wait) { + s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1].Gone = true }) + end(status, msg, 0, 0) + return false + } + began = time.Now() + s.trace.update(tr, func(t *Route) { + again := t.Tries[0] + t.Tries = append(t.Tries, Try{ID: again.ID, Model: again.Model, Effort: again.Effort, Start: began}) + }) + first, titleReply = firstToken{start: start}, capturedBody{} + return true + } + var sniff *usageSniffer + var refusal []byte // what OpenAI said, of a request it turned away + for { + // the try's own, which a stream that failed before its reply ends + // (holdWriter.stop) + attempt, cancel := context.WithCancel(r.Context()) + defer cancel() + for tries := 0; ; tries++ { + ctx := provider.ViaSignedIn(attempt, "codex") + if on != nil { + ctx = on.Via(attempt) + } + req, err := http.NewRequestWithContext(ctx, r.Method, u, bytes.NewReader(body)) + if err != nil { + failWith(502, err.Error()) + end(502, err.Error(), 0, 0) + return + } + copyHeaders(req.Header, r.Header) + if on != nil { + // the account's own token and id in place of the sign-in's; + // what Codex said it takes back stays as it said it + accept := req.Header.Values("Accept") + if err := on.Sign(ctx, req, provider.Responses, body); err != nil { + msg := "OpenAI (" + on.Account.User + "): " + err.Error() + writeError(w, provider.Responses, 502, msg) + end(502, msg, 0, 0) + return + } + // a sign-in its vendor revoked isn't sent again (#1793) + if why, ok := provider.RevokedSignIn(on.Account, req); ok { + writeError(w, provider.Responses, 401, why) + end(401, why, 0, 0) + return + } + req.Header.Del("Accept") + for _, v := range accept { + req.Header.Add("Accept", v) + } + } + // left to the transport, the reply comes back plain for the usage in it + req.Header.Del("Accept-Encoding") + // a turn to ChatGPT goes zstd-compressed again, as Codex sent it + // before magpie read it (ylorn on X); an API key's goes plain + sent = provider.CodexCompressed(req, body) + if res, err = s.client.Do(req); err != nil { + msg := "OpenAI: " + err.Error() + if rest == "/responses" { + msg = codexUnreached(modelOf(body), err) + } + failWith(502, msg) end(502, msg, 0, 0) return } - // a sign-in its vendor revoked isn't sent again (#1793) - if why, ok := provider.RevokedSignIn(on.Account, req); ok { - writeError(w, provider.Responses, 401, why) - end(401, why, 0, 0) - return + if on != nil { + // one of magpie's accounts: a revoked sign-in shows on its + // row, to sign in again (#1793) + noteSignIn(ctx, on.Account, req, res) } - req.Header.Del("Accept") - for _, v := range accept { - req.Header.Add("Accept", v) + if !autoReset && rest == "/responses" && base != codexAPIBase && res.StatusCode == http.StatusTooManyRequests { + // the account is out of its allowance: one it lets spend its + // resets by itself, its week used up, spends one and is asked + // again — nobody else is there to ask + autoReset = true + msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + res.Body.Close() + res.Body = io.NopCloser(bytes.NewReader(msg)) + if failure(res.StatusCode, msg) == failQuota { + if who, out, ok := s.autoResetSignedIn(r.Context()); ok { + s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1].Reset = &AutoReset{Who: who, Text: out.Text()} }) + resetNote = "openai (" + who + "): used one of its resets by itself (" + out.Text() + ")" + continue + } + } } - } - // left to the transport, the reply comes back plain for the usage in it - req.Header.Del("Accept-Encoding") - // a turn to ChatGPT goes zstd-compressed again, as Codex sent it - // before magpie read it (ylorn on X); an API key's goes plain - sent = provider.CodexCompressed(req, body) - if res, err = s.client.Do(req); err != nil { - msg := "OpenAI: " + err.Error() - if rest == "/responses" { - msg = codexUnreached(modelOf(body), err) + if rest == "/responses" && base != codexAPIBase && edgeMayDrop(res.StatusCode, sent) && resets < lastRetries { + // ChatGPT closed the connection before answering a large + // request, which often passes (#1628), or its front couldn't + // retry one that large (#2034): asked again after a moment, + // as the accounts loop asks its last one again + head, _ := io.ReadAll(io.LimitReader(res.Body, 4<<10)) + res.Body.Close() + res.Body = io.NopCloser(bytes.NewReader(head)) + if edgeSaidDrop(res.StatusCode, head) { + wait := retryPause << resets + resets++ + select { + case <-time.After(wait): + continue + case <-r.Context().Done(): + } + } } - writeError(w, provider.Responses, 502, msg) - end(502, msg, 0, 0) - return - } - if on != nil { - // one of magpie's accounts: a revoked sign-in shows on its - // row, to sign in again (#1793) - noteSignIn(ctx, on.Account, req, res) - } - if !autoReset && rest == "/responses" && base != codexAPIBase && res.StatusCode == http.StatusTooManyRequests { - // the account is out of its allowance: one it lets spend its - // resets by itself, its week used up, spends one and is asked - // again — nobody else is there to ask - autoReset = true + if overload && busyAgain < lastRetries && res.StatusCode >= 400 { + // the backend too busy for the turn, said as its status + msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + res.Body.Close() + res.Body = io.NopCloser(bytes.NewReader(msg)) + if codexBusy(res.StatusCode, msg) { + if wait, ok := passing(res.StatusCode, res.Header, msg, busyAgain); ok { + if !askAgain(res.StatusCode, provider.APIError(msg, res.Status), wait) { + return + } + continue + } + } + } + if rest != "/responses" || tries >= 3 || (res.StatusCode != 400 && res.StatusCode != 404) { + break + } + // an item OpenAI can't take — sealed by another account, or + // another vendor's that it looks up and doesn't have — is taken + // out and the rest asked again, rather than the conversation + // stuck on it for good msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) res.Body.Close() res.Body = io.NopCloser(bytes.NewReader(msg)) - if failure(res.StatusCode, msg) == failQuota { - if who, out, ok := s.autoResetSignedIn(r.Context()); ok { - s.trace.update(tr, func(t *Route) { t.Tries[0].Reset = &AutoReset{Who: who, Text: out.Text()} }) - resetNote = "openai (" + who + "): used one of its resets by itself (" + out.Text() + ")" - continue - } - } - } - if rest == "/responses" && base != codexAPIBase && edgeMayDrop(res.StatusCode, sent) && resets < lastRetries { - // ChatGPT closed the connection before answering a large - // request, which often passes (#1628), or its front couldn't - // retry one that large (#2034): asked again after a moment, - // as the accounts loop asks its last one again - head, _ := io.ReadAll(io.LimitReader(res.Body, 4<<10)) - res.Body.Close() - res.Body = io.NopCloser(bytes.NewReader(head)) - if edgeSaidDrop(res.StatusCode, head) { - wait := retryPause << resets - resets++ - select { - case <-time.After(wait): - continue - case <-r.Context().Done(): - } - } - } - if rest != "/responses" || tries >= 3 || (res.StatusCode != 400 && res.StatusCode != 404) { - break - } - // an item OpenAI can't take — sealed by another account, or - // another vendor's that it looks up and doesn't have — is taken - // out and the rest asked again, rather than the conversation - // stuck on it for good - msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) - res.Body.Close() - res.Body = io.NopCloser(bytes.NewReader(msg)) - b, ok := withoutUnreadable(body, msg) - if !ok { - break - } - body = b - } - if rest == "/responses" { - // a web page or nothing at all, served 200, is the 502 it stands - // for (#1012) - res = notAnAPIReply(res, "OpenAI: ") - if base != codexAPIBase { - // still closed on after that: Codex is told what may help, - // at the 503 it asks again for (#1628) - res = codexDropped(res, sent) - } - } - defer res.Body.Close() - if base == codexAPIBase && res.StatusCode == http.StatusUnauthorized { - // Codex signed in with an API key OpenAI refuses — often one a - // relay issued, left in ~/.codex/auth.json — and one of Codex's own - // models was picked, which goes out with Codex's own sign-in - msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) - writeError(w, provider.Responses, res.StatusCode, codexKeyRefused(msg)) - s.record(Call{Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body), - Provider: "openai", Agent: agentOf(r), Status: res.StatusCode, - Millis: time.Since(start).Milliseconds(), Error: res.Status}) - end(res.StatusCode, res.Status, 0, 0) - return - } - if rest == "/responses" && res.StatusCode >= 400 { - msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) - res.Body = io.NopCloser(bytes.NewReader(msg)) - if len(bytes.TrimSpace(msg)) == 0 { - // a failure with nothing said of it, which Codex shows as - // "Unknown error" alone (#409): said where the turn went - said := codexFailedEmpty(modelOf(body), res.Status) - writeError(w, provider.Responses, res.StatusCode, said) - s.record(Call{Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body), - Provider: "openai", Agent: agentOf(r), Kind: callKind(r.Header), Status: res.StatusCode, - Millis: time.Since(start).Milliseconds(), Error: said}) - end(res.StatusCode, said, 0, 0) - return - } - } - for k, vs := range res.Header { - if !hopHeader(k) { - w.Header()[k] = vs - } - } - modelsEtag(w.Header()) - w.WriteHeader(res.StatusCode) - var sniff *usageSniffer - if rest == "/responses" { - ct := res.Header.Get("Content-Type") - if ct == "" && streamOf(body) { // the ChatGPT backend streams without saying so - ct = "text/event-stream" - } - sniff = newSniffer(provider.Responses, ct) - } - f, _ := w.(http.Flusher) - buf := make([]byte, 32<<10) - var refusal []byte // what OpenAI said, of a request it turned away - for { - n, err := res.Body.Read(buf) - if n > 0 { - if captureTitle { - titleReply.add(buf[:n]) - } - if sniff != nil { - sniff.write(buf[:n]) - first.see(buf[:n]) - tools.add(buf[:n]) - } - if res.StatusCode >= 400 && len(refusal) < 8<<10 { - refusal = append(refusal, buf[:n]...) - } - if _, werr := w.Write(buf[:n]); werr != nil { + b, ok := withoutUnreadable(body, msg) + if !ok { break } - if f != nil { - f.Flush() + body = b + } + if rest == "/responses" { + // a web page or nothing at all, served 200, is the 502 it stands + // for (#1012) + res = notAnAPIReply(res, "OpenAI: ") + if base != codexAPIBase { + // still closed on after that: Codex is told what may help, + // at the 503 it asks again for (#1628) + res = codexDropped(res, sent) } } - if err != nil { + defer res.Body.Close() + if base == codexAPIBase && res.StatusCode == http.StatusUnauthorized { + // Codex signed in with an API key OpenAI refuses — often one a + // relay issued, left in ~/.codex/auth.json — and one of Codex's own + // models was picked, which goes out with Codex's own sign-in + msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + writeError(w, provider.Responses, res.StatusCode, codexKeyRefused(msg)) + s.record(Call{Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body), + Provider: "openai", Agent: agentOf(r), Status: res.StatusCode, + Millis: time.Since(start).Milliseconds(), Error: res.Status}) + end(res.StatusCode, res.Status, 0, 0) + return + } + if rest == "/responses" && res.StatusCode >= 400 { + msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + res.Body = io.NopCloser(bytes.NewReader(msg)) + if overload && codexBusy(res.StatusCode, msg) && s.codexFallsBack(modelOf(body), body) { + // still too busy once asked again: the fallbacks answer + said := provider.APIError(msg, res.Status) + handOn(res.StatusCode, said, 0) + end(res.StatusCode, said, 0, 0) + s.codexFallBack(w0, r, body0, kept) + return + } + if len(bytes.TrimSpace(msg)) == 0 { + // a failure with nothing said of it, which Codex shows as + // "Unknown error" alone (#409): said where the turn went + said := codexFailedEmpty(modelOf(body), res.Status) + failWith(res.StatusCode, said) + s.record(Call{Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body), + Provider: "openai", Agent: agentOf(r), Kind: callKind(r.Header), Status: res.StatusCode, + Millis: time.Since(start).Milliseconds(), Error: said}) + end(res.StatusCode, said, 0, 0) + return + } + } + // a stream that may still be asked again, or whose Codex has the + // stream's headers already, goes through a holdWriter: the frames + // before a reply held, its reasoning and text let through as they + // come, an error before them held for the turn to be asked again + out := w + var hw *holdWriter + if overload && streams && (busyAgain < lastRetries || kept.sent || s.codexFallsBack(modelOf(body), body)) { + hw = newHoldWriter(w, true) + hw.alive, hw.streams, hw.ctx, hw.stop = kept, true, r.Context(), cancel + // reasoning goes to Codex at once, as it always went + hw.thinkingShown = true + out = hw + } + for k, vs := range res.Header { + if !hopHeader(k) { + out.Header()[k] = vs + } + } + if hw != nil && res.StatusCode < 400 && res.Header.Get("Content-Type") == "" { + // the ChatGPT backend streams without saying so: held as the + // stream it is + out.Header().Set("Content-Type", "text/event-stream") + } + modelsEtag(out.Header()) + out.WriteHeader(res.StatusCode) + stopWatch := func() {} + if hw != nil { + stopWatch = hw.watch() + } + if rest == "/responses" { + ct := res.Header.Get("Content-Type") + if ct == "" && streams { // the ChatGPT backend streams without saying so + ct = "text/event-stream" + } + sniff = newSniffer(provider.Responses, ct) + } + f, _ := out.(http.Flusher) + buf := make([]byte, 32<<10) + refusal = nil + for { + n, err := res.Body.Read(buf) + if n > 0 { + if captureTitle { + titleReply.add(buf[:n]) + } + if sniff != nil { + sniff.write(buf[:n]) + first.see(buf[:n]) + tools.add(buf[:n]) + } + if res.StatusCode >= 400 && len(refusal) < 8<<10 { + refusal = append(refusal, buf[:n]...) + } + if _, werr := out.Write(buf[:n]); werr != nil { + break + } + if f != nil { + f.Flush() + } + } + if err != nil { + break + } + } + stopWatch() + if hw == nil { break } + hw.settle() + if hw.mayAskAgain() && hw.failure != 0 && !hw.refused && codexBusy(hw.failure, hw.errBody()) && r.Context().Err() == nil { + // the backend too busy for the turn, said on its stream before + // any of the reply (#1418) + said := "OpenAI: " + string(hw.errBody()) + if wait, ok := passing(hw.failure, res.Header, hw.errBody(), busyAgain); ok { + res.Body.Close() + if !askAgain(hw.failure, said, wait) { + return + } + continue + } + if s.codexFallsBack(modelOf(body), body) { + res.Body.Close() + handOn(hw.failure, said, 0) + end(hw.failure, said, 0, 0) + s.codexFallBack(w0, r, body0, kept) + return + } + } + hw.release() + break } if sniff == nil { return @@ -1120,6 +1258,11 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st call := Call{Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body), Provider: "openai", Agent: agentOf(r), Kind: kind, Status: res.StatusCode, Millis: time.Since(start).Milliseconds(), Fallback: resetNote} + if len(tried) > 0 { + // the overloads it was asked again for, before the one that answered + call.Fallback = strings.Join(append(tried, call.Fallback), "; ") + call.Fallback = strings.TrimSuffix(call.Fallback, "; ") + } call.TTFT, call.FirstText = first.ms() call.ReasoningHidden = first.hidesReasoning(provider.Responses) uu.add(sniff.usage()) @@ -1148,6 +1291,91 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st appendUsage(r, rec) } +// codexBusy says a failure of the ChatGPT backend's, said as a status or +// on a stream before any reply, is it too busy for the turn (busy): no +// fault of the account's, nor of the request's. Its front closing on the +// request is no overload: a large request's has its own retries +// (edgeSaidDrop, codexDropped), and a small one's goes to Codex as the +// 503 it asks again for (TestCodexResetJudgedByTheBytesSent). A 429 is +// the account's allowance or rate, which isn't outwaited in seconds. +func codexBusy(status int, msg []byte) bool { + if status == http.StatusTooManyRequests || edgeSaidDrop(status, msg) || codexReset(status, msg) { + return false + } + return busy(status, msg) +} + +// codexFallsBack says Codex's turn on one of its own models has fallbacks +// to go on to (codexFallBack): the Codex subscription's, set in magpie, at +// least one of them found. A turn compacting natively is the backend's to +// answer, and goes nowhere else. +func (s *Server) codexFallsBack(model string, body []byte) bool { + if model == "" || strings.Contains(model, "/") || compactionTriggerIn(body) { + return false + } + p, _, ok := provider.Resolve("codex/" + model) + if !ok || p.Account == nil || p.Account.Agent != "codex" { + return false + } + for _, id := range p.Fallback { + if _, _, ok := provider.Resolve(id); ok { + return true + } + } + return false +} + +// codexFallBack serves Codex's turn on its own sign-in, which the backend +// was too busy for however often it was asked again, from the Codex +// subscription's fallbacks, as serve goes on to them for a turn through +// magpie's accounts; the account itself is not asked again (handedOnOf). +// kept is what Codex was sent while it waited: the stream's headers, once +// it had them, which the fallback's reply follows. +func (s *Server) codexFallBack(w http.ResponseWriter, r *http.Request, body []byte, kept *keptAlive) { + id := "codex/" + modelOf(body) + body, _ = codexInputAs(withModel(body, id), true, s.nativeCompactionFor(id)) + s.serve(w, r.WithContext(context.WithValue(r.Context(), handedOnKey{}, kept)), provider.Responses, body) +} + +// handedOnKey carries, in a request codexFallBack hands on, what its +// agent was sent while it waited. +type handedOnKey struct{} + +// handedOnOf is what the agent of a request codexFallBack handed on was +// sent while it waited, nil for any other request. +func handedOnOf(r *http.Request) *keptAlive { + k, _ := r.Context().Value(handedOnKey{}).(*keptAlive) + return k +} + +// fallbacksOnly is cands without model's own on provider id, pl with +// them: a request handed on to the fallbacks (codexFallBack) after the +// account was asked as often as it is asked. +func fallbacksOnly(cands []candidate, pl planned, id, model string) ([]candidate, planned) { + own := func(c candidate) bool { return c.p.ID == id && c.model == model } + var kept []candidate + var order []Weighed + for i, c := range cands { + if !own(c) { + kept = append(kept, c) + order = append(order, pl.order[i]) + } + } + cands, pl.order = kept, order + pl.held = slices.DeleteFunc(slices.Clone(pl.held), own) + pl.capped = slices.DeleteFunc(slices.Clone(pl.capped), own) + var unlisted []candidate + var unlistedW []Weighed + for i, c := range pl.unlisted { + if !own(c) { + unlisted = append(unlisted, c) + unlistedW = append(unlistedW, pl.unlistedW[i]) + } + } + pl.unlisted, pl.unlistedW = unlisted, unlistedW + return cands, pl +} + // codexServed is who a relay through codexUpstreamOn is recorded as. // Codex's own ChatGPT sign-in is the codex account, and a compaction // signed by another of its accounts (compactOn) is that account, so the diff --git a/internal/gateway/codex_one_account_overload_test.go b/internal/gateway/codex_one_account_overload_test.go new file mode 100644 index 000000000..8fd149771 --- /dev/null +++ b/internal/gateway/codex_one_account_overload_test.go @@ -0,0 +1,244 @@ +package gateway + +import ( + "bytes" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// overloadedStatus is the ChatGPT backend's overload said as a status. +const overloadedStatus = `{"error":{"type":"server_error","code":"server_is_overloaded","message":"Our servers are currently overloaded. Please try again later."}}` + +// codexAnswer is a turn the ChatGPT backend answers, its frames first. +var codexAnswer = sse(append(slices.Clone(overloadedLead), + `event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"hello"}`, + `event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[],"usage":{"input_tokens":9,"output_tokens":2}}}`)...) + +// overloadedBackend stands in for the ChatGPT backend, answering the n-th +// request (from 0) with replies[n], the last one after that; it keeps +// every request's body and headers. A 200 goes with no Content-Type, as +// the backend sends it. +type overloadedBackend struct { + replies []reply + mu sync.Mutex + bodies [][]byte + heads []http.Header +} + +func (o *overloadedBackend) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + o.mu.Lock() + i := min(len(o.bodies), len(o.replies)-1) + o.bodies = append(o.bodies, b) + o.heads = append(o.heads, r.Header.Clone()) + o.mu.Unlock() + x := o.replies[i] + if x.ctype != "" { + w.Header().Set("Content-Type", x.ctype) + } else { + w.Header()["Content-Type"] = nil + } + w.WriteHeader(x.code) + io.WriteString(w, x.body) +} + +func (o *overloadedBackend) asked() int { + o.mu.Lock() + defer o.mu.Unlock() + return len(o.bodies) +} + +// oneCodexAccount is Codex signed in to ChatGPT with its one account and +// nothing else on in magpie, the ChatGPT backend o: a turn on one of +// Codex's own models is relayed as it came (codexAccounts), nobody else +// to ask. +func oneCodexAccount(t *testing.T, o *overloadedBackend) { + t.Helper() + codexSignedIn(t) + up := httptest.NewServer(o) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + pause := retryPause + retryPause = time.Millisecond + t.Cleanup(func() { retryPause = pause }) + if id, routed := codexAccounts(httptest.NewRequest("POST", CodexPath+"/responses", nil), "gpt-5.5"); routed { + t.Fatalf("one account goes through routing as %s", id) + } +} + +const oneAccountTurn = `{"model":"gpt-5.5","stream":true,"input":"ping"}` + +// noneResting says nothing rests after an overload: no account is at +// fault for it. +func noneResting(t *testing.T) { + t.Helper() + restingUntil.Lock() + defer restingUntil.Unlock() + if len(restingUntil.m) > 0 { + t.Fatalf("rested for an overload: %v", restingUntil.m) + } +} + +// With one ChatGPT account, Codex's own turn the backend says it is too +// busy for (529) is asked again of the same account, after the pause the +// accounts loop takes, as Codex sent it (夜松云 on Discord): the answer +// reaches Codex, nothing of the failure. +func TestCodexOneAccountOverloadAskedAgain(t *testing.T) { + o := &overloadedBackend{replies: []reply{{529, "application/json", overloadedStatus}, {200, "", codexAnswer}}} + oneCodexAccount(t, o) + code, body := codexPost(t, oneAccountTurn) + if code != 200 || !strings.Contains(body, "hello") || strings.Contains(body, "overloaded") || o.asked() != 2 { + t.Fatalf("%d %q, asked %d times", code, body, o.asked()) + } + // the turn goes again as it went: the same bytes, the same sign-in + if !bytes.Equal(o.bodies[0], o.bodies[1]) { + t.Fatalf("asked again with another body:\n%s\n%s", o.bodies[0], o.bodies[1]) + } + for _, k := range []string{"Authorization", "Chatgpt-Account-Id"} { + if o.heads[0].Get(k) == "" || o.heads[0].Get(k) != o.heads[1].Get(k) { + t.Fatalf("%s: %q then %q", k, o.heads[0].Get(k), o.heads[1].Get(k)) + } + } + noneResting(t) +} + +// The ChatGPT backend's overload as it says it on a turn (#1418): a 200, +// the frames before a reply, then server_is_overloaded. Codex doesn't ask +// again for it; held while it has only those frames, the turn is asked +// again, and Codex has the answer and nothing of the failure. +func TestCodexOneAccountStreamOverloadAskedAgain(t *testing.T) { + failed := reply{200, "", sse(append(slices.Clone(overloadedLead), overloadedFailed)...)} + o := &overloadedBackend{replies: []reply{failed, {200, "", codexAnswer}}} + oneCodexAccount(t, o) + code, body := codexPost(t, oneAccountTurn) + if code != 200 || !strings.Contains(body, "hello") || strings.Contains(body, "server_is_overloaded") || o.asked() != 2 { + t.Fatalf("%d %q, asked %d times", code, body, o.asked()) + } + // the answer's frames go with it, once + if strings.Count(body, "event: response.created") != 1 { + t.Fatalf("frames: %q", body) + } + noneResting(t) +} + +// An overload that lasts is asked again as often as the accounts loop +// asks its last account (lastRetries), and then Codex has the backend's +// own failure, as it had before. +func TestCodexOneAccountOverloadBounded(t *testing.T) { + for name, failed := range map[string]reply{ + "status": {529, "application/json", overloadedStatus}, + "stream": {200, "", sse(append(slices.Clone(overloadedLead), overloadedFailed)...)}, + } { + t.Run(name, func(t *testing.T) { + o := &overloadedBackend{replies: []reply{failed}} + oneCodexAccount(t, o) + code, body := codexPost(t, oneAccountTurn) + if o.asked() != 1+lastRetries || !strings.Contains(body, "server_is_overloaded") { + t.Fatalf("%d %q, asked %d times", code, body, o.asked()) + } + if code != failed.code { + t.Fatalf("status %d, the backend's %d", code, failed.code) + } + noneResting(t) + }) + } +} + +// With fallbacks set on the Codex subscription, an overload that lasts +// goes on to them once the account was asked again, as a turn through +// magpie's accounts does; without the account asked any more. +func TestCodexOneAccountOverloadFallsBack(t *testing.T) { + for name, failed := range map[string]reply{ + "status": {529, "application/json", overloadedStatus}, + "stream": {200, "", sse(append(slices.Clone(overloadedLead), overloadedFailed)...)}, + } { + t.Run(name, func(t *testing.T) { + o := &overloadedBackend{replies: []reply{failed}} + oneCodexAccount(t, o) + fb := &scripted{replies: []reply{{200, "text/event-stream", sse( + `event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"from the fallback"}`, + `event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"f1","status":"completed","output":[]}}`)}}} + responsesOn(t, "fb", fb) + if err := provider.Save(provider.Provider{ID: "codex", Fallback: []string{"fb/m"}}); err != nil { + t.Fatal(err) + } + code, body := codexPost(t, oneAccountTurn) + if code != 200 || !strings.Contains(body, "from the fallback") || strings.Contains(body, "server_is_overloaded") { + t.Fatalf("%d %q", code, body) + } + if o.asked() != 1+lastRetries || fb.n != 1 { + t.Fatalf("ChatGPT asked %d times, the fallback %d", o.asked(), fb.n) + } + noneResting(t) + }) + } +} + +// A usage limit isn't an overload: with one account it still goes to +// Codex as the backend said it, asked once (TestCodexOwnModelOneAccountRelayed), +// and so does a refusal of the request. +func TestCodexOneAccountRefusalNotAskedAgain(t *testing.T) { + o := &overloadedBackend{replies: []reply{{400, "application/json", `{"error":{"type":"invalid_request_error","message":"Unsupported parameter: foo"}}`}}} + oneCodexAccount(t, o) + code, body := codexPost(t, oneAccountTurn) + if code != 400 || !strings.Contains(body, "Unsupported parameter") || o.asked() != 1 { + t.Fatalf("%d %q, asked %d times", code, body, o.asked()) + } +} + +// A backend that is slow to say it is overloaded (#1418: 36s after its +// frames) has Codex kept alive meanwhile with the stream's headers and +// comments, none of the failed tries; what follows goes on in that +// stream: the last try's failure as it was said, or the fallback's reply. +func TestCodexOneAccountOverloadKeptAlive(t *testing.T) { + k, w := keepHeldAfter, watchEvery + keepHeldAfter, watchEvery = 20*time.Millisecond, 5*time.Millisecond + t.Cleanup(func() { keepHeldAfter, watchEvery = k, w }) + for _, withFallback := range []bool{false, true} { + codexSignedIn(t) + slow := &slowFrames{wait: 150 * time.Millisecond, then: func(int) string { return sse(overloadedFailed) }} + up := httptest.NewServer(slow) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + pause := retryPause + retryPause = time.Millisecond + t.Cleanup(func() { retryPause = pause }) + fb := &scripted{replies: []reply{{200, "text/event-stream", sse( + `event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"from the fallback"}`, + `event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"f1","status":"completed","output":[]}}`)}}} + if withFallback { + responsesOn(t, "fb", fb) + if err := provider.Save(provider.Provider{ID: "codex", Fallback: []string{"fb/m"}}); err != nil { + t.Fatal(err) + } + } + code, body := codexPost(t, oneAccountTurn) + slow.mu.Lock() + asked := slow.n + slow.mu.Unlock() + if code != 200 || !strings.Contains(body, ": keepalive") || asked != 1+lastRetries { + t.Fatalf("fallback %v: %d %q, asked %d times", withFallback, code, body, asked) + } + if withFallback { + if !strings.Contains(body, "from the fallback") || strings.Contains(body, "server_is_overloaded") || fb.n != 1 { + t.Fatalf("fallback: %q, asked %d times", body, fb.n) + } + } else if strings.Count(body, "server_is_overloaded") != 1 || strings.Count(body, "event: response.created") != 1 { + // the last try's own failure, once, and none of the others' + t.Fatalf("no fallback: %q", body) + } + noneResting(t) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index b42a67796..dcd6568df 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1977,6 +1977,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } } else { cands, pl = s.plan(p, model, from) + if handedOnOf(r) != nil { + // Codex's own sign-in, asked as often as it is asked: only + // the fallbacks are left (codexFallBack) + cands, pl = fallbacksOnly(cands, pl, p.ID, model) + } if provider.IsFastPick(agent, p.ID+"/"+model) { // the agent's pick of it is sent in its vendor's fast mode // (#954), as a group's member may be; its fallbacks, other @@ -2278,6 +2283,10 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro autoReset := resetFirst != nil // a Codex or Claude reset looked at, once a request // what the tries' held streams sent the agent ahead of a reply (#751) kept := &keptAlive{proto: from, told: start} + if k := handedOnOf(r); k != nil { + // Codex's own sign-in waited for first, with Codex kept alive + kept = k + } var sentMs int64 // ms from the request to its answering try going to the vendor // of it, magpie's own, the tries that failed first and the wait for a // slot (usage.Record.Own, Retried, Queued: #1532) diff --git a/internal/gui/api.go b/internal/gui/api.go index f9edf4612..9e563e478 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -395,8 +395,11 @@ type settingsJSON struct { // settings, environment, system, off or none ProxyNow string `json:"proxyNow"` ProxySource string `json:"proxySource"` - // whether magpie opens at login: the system's record, not a setting - Login bool `json:"login"` + // whether magpie opens at login: the system's record, not a setting; + // LoginAllow, the record is there but the user switched it off in + // System Settings › Login Items, which is where it's allowed again + Login bool `json:"login"` + LoginAllow bool `json:"loginAllow,omitempty"` // the model that describes images when Vision names none, and those // that can be named VisionAuto string `json:"visionAuto,omitempty"` @@ -583,6 +586,10 @@ type searchFailedJSON struct { At time.Time `json:"at"` } +// loginState is whether magpie opens at login, as the system will act on +// it. A var for the tests: the real one asks the user's own system. +var loginState = autostart.Enabled + func settingsState() settingsJSON { s := settingsJSON{Settings: settings.Load(), Version: Version, Dir: tilde(settings.Dir()), Portable: settings.Portable() != "", Gateway: gateway.URL()} s.AddrEnv = os.Getenv("MAGPIE_ADDR") @@ -622,7 +629,8 @@ func settingsState() settingsJSON { s.OTelEnv = true } } - s.Login = autostart.Enabled() + login := loginState() + s.Login, s.LoginAllow = login != autostart.Off, login == autostart.NeedsAllowing if s.LAN { s.LANURLs, s.LANContainer = gateway.LANURLs(), gateway.ContainerAddrs() } diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index eaec35c30..d854cee9b 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -3343,6 +3343,8 @@ input.words.search-key, input.words.search-url { flex: 1 1 120px; width: auto; m .warm-at .warm-rm, .warm-at .warm-add { min-width: 24px; height: 27px; padding: 0 6px; font-size: 14px; line-height: 1; } .row.pref .sub .warn { color: var(--amber); } .row.pref .sub.wraps { white-space: normal; } +.row.pref .login-allow-open { font: inherit; color: var(--accent); padding: 0; background: none; border: 0; cursor: pointer; } +.row.pref .login-allow-open:hover { text-decoration: underline; } /* the field's clock and picker in the page's own palette */ :root[data-theme="dark"] .warm-at input.at { color-scheme: dark; } @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .warm-at input.at { color-scheme: dark; } } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 484b2bdfa..a016366e0 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -18794,6 +18794,32 @@ function renderBarIcon() { .catch((e) => { status(t(e.message), "err"); renderBarIcon(); }))); } +// renderLoginAllow: Open at login switched off in System Settings, its +// launch agent still there (#2120, Anoninz). On stays picked, as the record +// is, and writing it again doesn't undo the user's switch, so the row says +// it won't open and opens Login Items, where it is allowed again. Coming +// back to the window reads the settings again (load), so the line goes once +// it is allowed there. +const loginItemsURL = "x-apple.systempreferences:com.apple.LoginItems-Settings.extension"; +function renderLoginAllow(s) { + const who = $("#loginRow .who"); + let sub = who.querySelector(".login-allow"); + if (!s.loginAllow) { sub?.remove(); return; } + if (!sub) { + sub = document.createElement("div"); + sub.className = "sub wraps login-allow"; + who.append(sub); + } + // the row is hidden on a page served to another computer (web), which + // has no System Settings to open + const open = document.createElement("button"); + open.type = "button"; + open.className = "login-allow-open"; + open.textContent = t("Open Login Items"); + open.onclick = () => api("open", { url: loginItemsURL }).catch((e) => status(t(e.message), "err")); + sub.replaceChildren(t("Switched off in System Settings’ Login Items, so magpie won’t open at login"), " ", open); +} + async function loadSettings() { const since = prefsWrites; if (!web && fontList === null && !fontListError) loadFonts(); @@ -19205,6 +19231,7 @@ function renderSettings() { // the system's record, set on its own, not with the other choices $("#loginSegs").replaceChildren(segs([["off", t("Off")], ["on", t("On")]], s.login ? "on" : "off", (v) => writingPrefs(api("settings/login", { on: v === "on" })).then((ns) => { prefs = ns; renderSettings(); }).catch((e) => { status(t(e.message), "err"); renderSettings(); }))); + renderLoginAllow(s); // Codex's and Claude Code's warm-ups and WorkBuddy's check-in, one tab // each over one card, the rows' names not saying the service again. // A ChatGPT account's next window started as soon as the last resets diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 7475dc6ea..91e56fbad 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -858,6 +858,8 @@ const I18N = { "Guesses your next message for the composer, reading the whole conversation again each time; at Codex’s own, it goes on the thread’s model through its ChatGPT sign-in": "为输入框猜测你的下一条消息,每次都把整段对话重读一遍;选 Codex 自带时用该会话的模型,经它的 ChatGPT 登录", "Decides an approval in your place when Codex’s approvals are on auto-review; Codex’s own pick is codex-auto-review, else the conversation’s model at low effort": "Codex 的审批设为自动审批时,代你决定是否批准;由 Codex 决定时用 codex-auto-review,没有则用当前对话的模型(低推理)", "Writes Codex’s memories of past threads, in the background; Codex’s own: gpt-5.6-terra, with gpt-5.6-luna summing up each thread": "在后台把过去的会话整理成 Codex 的记忆;Codex 自带的:整理用 gpt-5.6-terra,总结对话用 gpt-5.6-luna", + "Switched off in System Settings’ Login Items, so magpie won’t open at login": "已在系统设置的登录项里关闭,登录时不会打开 magpie", + "Open Login Items": "打开登录项", "Opens in the menu bar with no window. System Settings › General › Login Items lists it under App Background Activity, not Open at Login": "登录后在菜单栏打开,不弹出窗口。系统设置 › 通用 › 登录项 里,它列在「App后台活动」下,而不是「登录时打开」", "Opens in the tray with no window": "登录后在托盘打开,不弹出窗口", "With window": "跟随窗口", @@ -3510,6 +3512,9 @@ const I18N = { "Unofficial, on GitHub": "非官方插件 · GitHub", "Looking on GitHub": "正在 GitHub 上查找", "Couldn't ask GitHub: {error}": "无法连接 GitHub:{error}", + "{n} more on GitHub couldn't be read: {error}": "GitHub 上还有 {n} 个插件没能读取:{error}", + "GitHub found {n} repositories, but none of them could be read: {error}": "GitHub 找到了 {n} 个仓库,但一个都没能读取:{error}", + "Couldn't ask GitHub, so these are from before: {error}": "无法连接 GitHub,下面是之前获取的列表:{error}", "Kind of plugin": "插件类型", "Installed or not": "是否已安装", "Not installed": "未安装", @@ -4603,6 +4608,8 @@ const I18N = { "Guesses your next message for the composer, reading the whole conversation again each time; at Codex’s own, it goes on the thread’s model through its ChatGPT sign-in": "為輸入框猜測你的下一則訊息,每次都把整段對話重讀一遍;選 Codex 自帶時用該會話的模型,經它的 ChatGPT 登入", "Decides an approval in your place when Codex’s approvals are on auto-review; Codex’s own pick is codex-auto-review, else the conversation’s model at low effort": "Codex 的審批設為自動審批時,代你決定是否批准;由 Codex 決定時用 codex-auto-review,沒有則用目前對話的模型(低推理)", "Writes Codex’s memories of past threads, in the background; Codex’s own: gpt-5.6-terra, with gpt-5.6-luna summing up each thread": "在背景把過去的會話整理成 Codex 的記憶;Codex 自帶的:整理用 gpt-5.6-terra,總結對話用 gpt-5.6-luna", + "Switched off in System Settings’ Login Items, so magpie won’t open at login": "已在系統設定的登入項目裡關閉,登入時不會開啟 magpie", + "Open Login Items": "打開登入項目", "Opens in the menu bar with no window. System Settings › General › Login Items lists it under App Background Activity, not Open at Login": "登入後在選單列開啟,不彈出視窗。系統設定 › 一般 › 登入項目 裡,它列在「App背景活動」下,而不是「在登入時打開」", "Opens in the tray with no window": "登入後在系統匣開啟,不彈出視窗", "With window": "跟隨視窗", @@ -7219,6 +7226,9 @@ const I18N = { "Unofficial, on GitHub": "非官方外掛 · GitHub", "Looking on GitHub": "正在 GitHub 上尋找", "Couldn't ask GitHub: {error}": "無法連線 GitHub:{error}", + "{n} more on GitHub couldn't be read: {error}": "GitHub 上還有 {n} 個外掛未能讀取:{error}", + "GitHub found {n} repositories, but none of them could be read: {error}": "GitHub 找到了 {n} 個儲存庫,但一個都未能讀取:{error}", + "Couldn't ask GitHub, so these are from before: {error}": "無法連線 GitHub,以下是先前取得的列表:{error}", "Kind of plugin": "外掛類型", "Installed or not": "是否已安裝", "Not installed": "未安裝", @@ -8320,6 +8330,8 @@ const I18N = { "Guesses your next message for the composer, reading the whole conversation again each time; at Codex’s own, it goes on the thread’s model through its ChatGPT sign-in": "入力欄に次のメッセージを予測し、そのたびに会話全体を読み直します。Codex 自身ならスレッドのモデルで、その ChatGPT サインインで送られます", "Decides an approval in your place when Codex’s approvals are on auto-review; Codex’s own pick is codex-auto-review, else the conversation’s model at low effort": "Codex の承認が自動レビューのとき、あなたの代わりに承認を判断します。Codex に任せると codex-auto-review、なければ会話のモデル(低い推論)", "Writes Codex’s memories of past threads, in the background; Codex’s own: gpt-5.6-terra, with gpt-5.6-luna summing up each thread": "過去のスレッドを Codex のメモリにバックグラウンドでまとめます。Codex の初期設定:整理は gpt-5.6-terra、スレッドの要約は gpt-5.6-luna", + "Switched off in System Settings’ Login Items, so magpie won’t open at login": "システム設定のログイン項目でオフになっているため、ログイン時に magpie は開きません", + "Open Login Items": "ログイン項目を開く", "Opens in the menu bar with no window. System Settings › General › Login Items lists it under App Background Activity, not Open at Login": "ログイン後、ウィンドウなしでメニューバーに開きます。システム設定 › 一般 › ログイン項目では「ログイン時に開く」ではなく「アプリのバックグラウンドでのアクティビティ」に表示されます", "Opens in the tray with no window": "ログイン後、ウィンドウなしでトレイに開きます", "With window": "ウィンドウと連動", @@ -10950,6 +10962,9 @@ const I18N = { "Unofficial, on GitHub": "非公式 · GitHub", "Looking on GitHub": "GitHub を検索中", "Couldn't ask GitHub: {error}": "GitHub に接続できませんでした:{error}", + "{n} more on GitHub couldn't be read: {error}": "GitHub 上のほか {n} 件を読み込めませんでした:{error}", + "GitHub found {n} repositories, but none of them could be read: {error}": "GitHub で {n} 件のリポジトリが見つかりましたが、どれも読み込めませんでした:{error}", + "Couldn't ask GitHub, so these are from before: {error}": "GitHub に接続できないため、以前の一覧を表示しています:{error}", "Kind of plugin": "プラグインの種類", "Installed or not": "インストール済みかどうか", "Not installed": "未インストール", @@ -12051,6 +12066,8 @@ const I18N = { "Guesses your next message for the composer, reading the whole conversation again each time; at Codex’s own, it goes on the thread’s model through its ChatGPT sign-in": "Errät Ihre nächste Nachricht fürs Eingabefeld und liest dafür jedes Mal das ganze Gespräch neu; bei „Eigene von Codex“ mit dem Modell des Threads über seine ChatGPT-Anmeldung", "Decides an approval in your place when Codex’s approvals are on auto-review; Codex’s own pick is codex-auto-review, else the conversation’s model at low effort": "Entscheidet eine Freigabe an Ihrer Stelle, wenn Codex’ Freigaben auf Auto-Review stehen; „Wie Codex es wählt“ ist codex-auto-review, sonst das Modell des Gesprächs mit wenig Reasoning", "Writes Codex’s memories of past threads, in the background; Codex’s own: gpt-5.6-terra, with gpt-5.6-luna summing up each thread": "Schreibt im Hintergrund Codex’ Erinnerungen an frühere Threads; Codex’ eigenes: gpt-5.6-terra, Threads zusammengefasst mit gpt-5.6-luna", + "Switched off in System Settings’ Login Items, so magpie won’t open at login": "In den Systemeinstellungen unter „Anmeldeobjekte“ ausgeschaltet, daher öffnet sich magpie bei der Anmeldung nicht", + "Open Login Items": "Anmeldeobjekte öffnen", "Opens in the menu bar with no window. System Settings › General › Login Items lists it under App Background Activity, not Open at Login": "Öffnet sich in der Menüleiste, ohne Fenster. Systemeinstellungen › Allgemein › Anmeldeobjekte führt es unter „App-Hintergrundaktivitäten“, nicht unter „Bei der Anmeldung öffnen“", "Opens in the tray with no window": "Öffnet sich im Infobereich, ohne Fenster", "With window": "Mit Fenster", @@ -14694,6 +14711,9 @@ const I18N = { "Unofficial, on GitHub": "Inoffiziell, auf GitHub", "Looking on GitHub": "Suche auf GitHub", "Couldn't ask GitHub: {error}": "GitHub nicht erreichbar: {error}", + "{n} more on GitHub couldn't be read: {error}": "{n} weitere auf GitHub konnten nicht gelesen werden: {error}", + "GitHub found {n} repositories, but none of them could be read: {error}": "GitHub hat {n} Repositories gefunden, aber keines konnte gelesen werden: {error}", + "Couldn't ask GitHub, so these are from before: {error}": "GitHub nicht erreichbar, dies ist die Liste von zuvor: {error}", "Kind of plugin": "Art des Plugins", "Installed or not": "Installiert oder nicht", "Not installed": "Nicht installiert", diff --git a/internal/gui/assets/plugins.css b/internal/gui/assets/plugins.css index 389afc265..4b5c6cd93 100644 --- a/internal/gui/assets/plugins.css +++ b/internal/gui/assets/plugins.css @@ -50,6 +50,10 @@ .pm-ghbar .segs { flex: none; max-width: 100%; } .pm-ghfind { width: min(240px, 100%); } .pm-ghnone { display: flex; flex-direction: column; align-items: center; gap: 6px; padding: 22px 12px; border-radius: 12px; border: 1px dashed var(--line); font-size: 12px; color: var(--muted); text-align: center; } +/* what GitHub couldn't give, over the cards it could: a quiet line, its + reason wrapping anywhere (a URL in it is one long word) */ +.pm-ghwarn { display: flex; align-items: baseline; flex-wrap: wrap; gap: 2px 10px; font-size: 12px; color: var(--muted); } +.pm-ghwarn > span, .pm-ghnone > span { overflow-wrap: anywhere; } .pm-logo { flex: none; width: 36px; height: 36px; border-radius: 10px; display: grid; place-items: center; background: var(--pill); color: var(--fg-2); } .pm-logo .ic { width: 20px; height: 20px; } diff --git a/internal/gui/assets/plugins.js b/internal/gui/assets/plugins.js index 36f627569..0abb82bdb 100644 --- a/internal/gui/assets/plugins.js +++ b/internal/gui/assets/plugins.js @@ -14,7 +14,8 @@ let mine = null; // /api/plugins: what's installed let listings = null; // /api/plugins/listings: the plugins suggested let tagged = null; // /api/plugins/github: repositories their authors tagged magpie-plugin, as listings - let taggedErr = ""; // why they couldn't be asked for, while none were had + let taggedErr = ""; // why the list isn't GitHub's whole answer: it couldn't be asked, or... + let taggedMissing = 0; // ...this many repositories it named couldn't be read let topic = "magpie-plugin"; const npm = {}; // /api/plugins/npm: package → what npm says of it const heads = {}; // /api/plugins/git: a git plugin's spec → the commit its repository is at @@ -170,14 +171,22 @@ summary: r.description ? { en: r.description } : undefined, npm: { version: r.version || "", publisher: r.owner, repository: r.url, license: r.license, weekly: 0 }, }); - async function loadTagged() { + // A failed ask is said, with why, whether or not a list was had before: + // an empty list was read as there being no unofficial plugins (till on + // Discord: GitHub unreachable from their desktop, the section gone). + // A list had before stands through a failed ask that brings none. + // again: Try again, which has magpie ask GitHub at once. + async function loadTagged(again) { try { - const r = await api("plugins/github"); - tagged = (r.repos || []).map(ghListing); - taggedErr = ""; + const r = await api("plugins/github" + (again ? "?again=1" : "")); + const got = (r.repos || []).map(ghListing); + if (!(r.error && !got.length && tagged?.length)) tagged = got; + taggedErr = r.error || ""; + taggedMissing = r.missing || 0; if (r.topic) topic = r.topic; } catch (e) { - if (!tagged) taggedErr = e.message || String(e); + taggedErr = e.message || String(e); + taggedMissing = 0; tagged = tagged || []; } } @@ -644,6 +653,10 @@ replaceKeeping(ghSec, [ghHead, skeleton(3)]); return ghSec; } + // why the list isn't GitHub's whole answer; kept: cards are shown + const ghWhy = (kept) => taggedMissing + ? t(kept ? "{n} more on GitHub couldn't be read: {error}" : "GitHub found {n} repositories, but none of them could be read: {error}", { n: taggedMissing, error: taggedErr }) + : t(kept ? "Couldn't ask GitHub, so these are from before: {error}" : "Couldn't ask GitHub: {error}", { error: taggedErr }); // and one GitHub couldn't be asked of says so, with another go function ghFailed() { ghHead.replaceChildren(...ghTitle()); @@ -654,13 +667,28 @@ again.onclick = () => { tagged = null; taggedErr = ""; + taggedMissing = 0; drawBody(); - loadTagged().then(drawBody); + loadTagged(true).then(drawBody); }; - box.append(el("span", "", t("Couldn't ask GitHub: {error}", { error: taggedErr })), again); + box.append(el("span", "", ghWhy(false)), again); replaceKeeping(ghSec, [ghHead, box]); return ghSec; } + // the cards GitHub could give, and a line saying what it couldn't, with + // another go that keeps them until it answers + function ghNote() { + const note = el("div", "pm-ghwarn"); + note.setAttribute("role", "status"); + const again = el("button", "text", t("Try again")); + again.type = "button"; + again.onclick = () => { + again.disabled = true; + loadTagged(true).then(drawBody); + }; + note.append(el("span", "", ghWhy(true)), again); + return note; + } function ghSection(list) { ghList = list; ghHead.replaceChildren(...ghTitle()); @@ -677,9 +705,10 @@ return ghSec; } function drawGh() { + const head = taggedErr ? [ghHead, ghNote()] : [ghHead]; if ((tagged || []).length <= 6) { ghGrid.replaceChildren(...ghList.map(card)); - replaceKeeping(ghSec, [ghHead, ghGrid]); + replaceKeeping(ghSec, [...head, ghGrid]); return; } // the kinds there are, in the market's order, each with how many the @@ -724,7 +753,7 @@ const shown = found.filter((l) => (!ghKind || kindOf(l) === ghKind) && (!ghHave || have(l) === (ghHave === "have"))); if (shown.length) { ghGrid.replaceChildren(...shown.map(card)); - replaceKeeping(ghSec, [ghHead, ghBar, ghGrid]); + replaceKeeping(ghSec, [...head, ghBar, ghGrid]); return; } const none = el("div", "pm-ghnone"); @@ -732,7 +761,7 @@ all.type = "button"; all.onclick = () => { ghKind = ""; ghHave = ""; ghQuery = ""; drawGh(); ghQ.focus(); }; none.append(el("span", "", t("No plugin on GitHub matches")), all); - replaceKeeping(ghSec, [ghHead, ghBar, none]); + replaceKeeping(ghSec, [...head, ghBar, none]); } // the head and its search field are made once and drawn again in @@ -886,7 +915,7 @@ if (pgs.length) out.push(section(t("Pages"), t("pages of their own in magpie's window, each shut off from the rest and reading only what it lists"), pgs)); if (gh.length) out.push(ghSection(gh)); else if (!tagged) out.push(ghWaiting()); - else if (taggedErr) out.push(ghFailed()); + else if (taggedErr && !tagged.length) out.push(ghFailed()); out.push(manual()); replaceKeeping(body, out); return; @@ -894,6 +923,7 @@ if (ls.length) out.push(section(t("Suggested"), "", ls)); if (gh.length) out.push(ghSection(gh)); else if (!tagged) out.push(ghWaiting()); + else if (taggedErr && !tagged.length) out.push(ghFailed()); const known = new Set([...listings.map((l) => l.package), ...(tagged || []).map((l) => l.github.package).filter(Boolean)]); const box = el("section", "pm-sec"); const h = el("div", "pm-sechead"); diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index 12524fc19..fa3ad6ac5 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -947,8 +947,8 @@ magpie.plugin("library", (ctx) => { if (a.on && !rtk.path) row.append(tag(t("RTK missing"), "warn", t("{agent}'s hook calls rtk, which isn't installed, so its shell commands fail. Install RTK, or switch this off.", { agent: a.name }))); // …or one that is, off the PATH the agent gets else if (a.on && rtk.offPath) row.append(tag(t("Not on PATH"), "warn", t("{agent}'s hook runs rtk by name and can't find it, so RTK does nothing for it. Put RTK on PATH above.", { agent: a.name }))); - // an agent RTK has no hook for (DeepSeek Harness): listed, with why - if (a.noHook) row.append(tag(t("No RTK hook"), "warn", t("RTK can't be given to {agent} yet: RTK works by rewriting the shell command an agent is about to run, and {agent}'s hooks can only allow or deny a command, not change it. RTK's installer has no option for it either (github.com/rtk-ai/rtk/issues/3847).", { agent: a.name }))); + // an agent RTK has no hook for (rtkNoHook in rtk.go): listed, with its own why + if (a.noHook) row.append(tag(t("No RTK hook"), "warn", rtkNoHookWhy(a))); // RTK before 0.51 installs Antigravity's hook only per project else if (a.blocked && a.id === "agy") row.append(tag(t("Update RTK"), "warn", t("{agent}'s hook needs RTK 0.51 or newer: older ones install it only per project. Update RTK (brew upgrade rtk, or its installer again), then switch it on.", { agent: a.name }))); else if (a.blocked && a.id !== "opencode") row.append(tag(t("Update RTK"), "warn", t("{agent}'s hook needs RTK 0.50 or newer: older ones only add @RTK.md to AGENTS.md, which rewrites no command. Update RTK (brew upgrade rtk, or its installer again), then switch it on.", { agent: a.name }))); @@ -965,6 +965,20 @@ magpie.plugin("library", (ctx) => { if (!rows.length) list.append(el("div", "lib-none", t("None of your agents is one RTK has a hook for."))); body.append(list); } + // Why RTK has no hook for an agent: each agent's own reason and its own + // rtk-ai/rtk issue, never another agent's (新v学员 on Discord: Grok Build's + // said DeepSeek Harness's hooks can't rewrite and linked dsh's issue). + // Keyed as rtkNoHook in rtk.go; TestRTKNoHookIssuesAreEachAgents holds the + // two together. An agent with no entry gets no reason and no link. + function rtkNoHookWhy(a) { + const agent = a.name; + switch (a.id) { + case "dsh": return t("RTK can't be given to {agent} yet: RTK works by rewriting the shell command an agent is about to run, and {agent}'s hooks can only allow or deny a command, not change it. RTK's installer has no option for it either (github.com/rtk-ai/rtk/issues/3847).", { agent }); + case "grok": return t("RTK can't be given to {agent} yet: RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).", { agent }); + case "grok-app": return t("RTK can't be given to {agent} yet: {agent} runs Grok Build, and RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).", { agent }); + default: return t("RTK can't be given to {agent} yet: RTK has no hook for it.", { agent }); + } + } async function setRTK(a, on) { rtkBusy.add(a.id); render(); diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index 20b75f605..2e6c018d0 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -170,6 +170,9 @@ magpie.strings({ "OpenCode 2 needs RTK 0.52 or newer: older ones write a plugin for OpenCode 1, which OpenCode 2 refuses to load. Update RTK (brew upgrade rtk, or its installer again), then switch it on.": "OpenCode 2 需要 RTK 0.52 或更高版本:旧版写的是 OpenCode 1 的插件,OpenCode 2 拒绝加载。请先更新 RTK(brew upgrade rtk,或重新运行其安装脚本)再打开。", "No RTK hook": "RTK 暂不支持", "RTK can't be given to {agent} yet: RTK works by rewriting the shell command an agent is about to run, and {agent}'s hooks can only allow or deny a command, not change it. RTK's installer has no option for it either (github.com/rtk-ai/rtk/issues/3847).": "暂时无法给 {agent} 接入 RTK:RTK 的做法是在 agent 执行 shell 命令前把命令改写掉,而 {agent} 的 hook 只能放行或拦截命令,不能改写;RTK 的安装程序也还没有它的选项(github.com/rtk-ai/rtk/issues/3847)。", + "RTK can't be given to {agent} yet: RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).": "暂时无法给 {agent} 接入 RTK:RTK 的安装程序还没有 Grok Build 的选项(github.com/rtk-ai/rtk/issues/2136)。", + "RTK can't be given to {agent} yet: {agent} runs Grok Build, and RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).": "暂时无法给 {agent} 接入 RTK:{agent} 运行的是 Grok Build,而 RTK 的安装程序还没有 Grok Build 的选项(github.com/rtk-ai/rtk/issues/2136)。", + "RTK can't be given to {agent} yet: RTK has no hook for it.": "暂时无法给 {agent} 接入 RTK:RTK 还没有它的 hook。", "Get RTK": "获取 RTK", "restart an agent after switching it": "切换后需重启对应 Agent", "{agent} runs its commands through RTK": "{agent} 的命令经过 RTK", @@ -777,6 +780,9 @@ magpie.strings({ "OpenCode 2 needs RTK 0.52 or newer: older ones write a plugin for OpenCode 1, which OpenCode 2 refuses to load. Update RTK (brew upgrade rtk, or its installer again), then switch it on.": "OpenCode 2 需要 RTK 0.52 或更高版本:舊版寫的是 OpenCode 1 的外掛,OpenCode 2 拒絕載入。請先更新 RTK(brew upgrade rtk,或重新執行其安裝指令碼)再開啟。", "No RTK hook": "RTK 暫不支援", "RTK can't be given to {agent} yet: RTK works by rewriting the shell command an agent is about to run, and {agent}'s hooks can only allow or deny a command, not change it. RTK's installer has no option for it either (github.com/rtk-ai/rtk/issues/3847).": "暫時無法給 {agent} 接入 RTK:RTK 的做法是在 agent 執行 shell 命令前把命令改寫掉,而 {agent} 的 hook 只能放行或攔截命令,不能改寫;RTK 的安裝程式也還沒有它的選項(github.com/rtk-ai/rtk/issues/3847)。", + "RTK can't be given to {agent} yet: RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).": "暫時無法給 {agent} 接入 RTK:RTK 的安裝程式還沒有 Grok Build 的選項(github.com/rtk-ai/rtk/issues/2136)。", + "RTK can't be given to {agent} yet: {agent} runs Grok Build, and RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).": "暫時無法給 {agent} 接入 RTK:{agent} 執行的是 Grok Build,而 RTK 的安裝程式還沒有 Grok Build 的選項(github.com/rtk-ai/rtk/issues/2136)。", + "RTK can't be given to {agent} yet: RTK has no hook for it.": "暫時無法給 {agent} 接入 RTK:RTK 還沒有它的 hook。", "Get RTK": "取得 RTK", "restart an agent after switching it": "切換後需重啟對應 Agent", "{agent} runs its commands through RTK": "{agent} 的命令經過 RTK", @@ -1379,6 +1385,9 @@ magpie.strings({ "OpenCode 2 needs RTK 0.52 or newer: older ones write a plugin for OpenCode 1, which OpenCode 2 refuses to load. Update RTK (brew upgrade rtk, or its installer again), then switch it on.": "OpenCode 2 には RTK 0.52 以降が必要です。古いバージョンは OpenCode 1 向けのプラグインを書き込み、OpenCode 2 はその読み込みを拒否します。RTK を更新(brew upgrade rtk、またはインストーラを再実行)してからオンにしてください。", "No RTK hook": "RTK 未対応", "RTK can't be given to {agent} yet: RTK works by rewriting the shell command an agent is about to run, and {agent}'s hooks can only allow or deny a command, not change it. RTK's installer has no option for it either (github.com/rtk-ai/rtk/issues/3847).": "{agent} にはまだ RTK を使えません。RTK はエージェントが実行しようとするシェルコマンドを書き換えて動きますが、{agent} のフックはコマンドを許可・拒否できるだけで書き換えられません。RTK のインストーラーにもそのためのオプションはありません(github.com/rtk-ai/rtk/issues/3847)。", + "RTK can't be given to {agent} yet: RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).": "{agent} にはまだ RTK を使えません。RTK のインストーラーに Grok Build のオプションがありません(github.com/rtk-ai/rtk/issues/2136)。", + "RTK can't be given to {agent} yet: {agent} runs Grok Build, and RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).": "{agent} にはまだ RTK を使えません。{agent} は Grok Build を実行しますが、RTK のインストーラーに Grok Build のオプションがありません(github.com/rtk-ai/rtk/issues/2136)。", + "RTK can't be given to {agent} yet: RTK has no hook for it.": "{agent} にはまだ RTK を使えません。RTK にはそのフックがありません。", "Get RTK": "RTK を入手", "restart an agent after switching it": "切り替え後はエージェントを再起動してください", "{agent} runs its commands through RTK": "{agent} のコマンドは RTK を通ります", @@ -1984,6 +1993,9 @@ magpie.strings({ "OpenCode 2 needs RTK 0.52 or newer: older ones write a plugin for OpenCode 1, which OpenCode 2 refuses to load. Update RTK (brew upgrade rtk, or its installer again), then switch it on.": "OpenCode 2 benötigt RTK 0.52 oder neuer: Ältere Versionen schreiben eine Erweiterung für OpenCode 1, die OpenCode 2 nicht lädt. Aktualisieren Sie RTK (brew upgrade rtk oder erneut über den Installer) und schalten Sie es dann ein.", "No RTK hook": "Kein RTK-Hook", "RTK can't be given to {agent} yet: RTK works by rewriting the shell command an agent is about to run, and {agent}'s hooks can only allow or deny a command, not change it. RTK's installer has no option for it either (github.com/rtk-ai/rtk/issues/3847).": "RTK lässt sich {agent} noch nicht geben: RTK schreibt den Shell-Befehl um, den ein Agent gleich ausführt, und die Hooks von {agent} können einen Befehl nur erlauben oder ablehnen, nicht ändern. Auch der Installer von RTK hat keine Option dafür (github.com/rtk-ai/rtk/issues/3847).", + "RTK can't be given to {agent} yet: RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).": "RTK lässt sich {agent} noch nicht geben: Der Installer von RTK hat keine Option für Grok Build (github.com/rtk-ai/rtk/issues/2136).", + "RTK can't be given to {agent} yet: {agent} runs Grok Build, and RTK's installer has no option for Grok Build (github.com/rtk-ai/rtk/issues/2136).": "RTK lässt sich {agent} noch nicht geben: {agent} führt Grok Build aus, und der Installer von RTK hat keine Option für Grok Build (github.com/rtk-ai/rtk/issues/2136).", + "RTK can't be given to {agent} yet: RTK has no hook for it.": "RTK lässt sich {agent} noch nicht geben: RTK hat keinen Hook dafür.", "Get RTK": "RTK holen", "restart an agent after switching it": "Agenten nach dem Umschalten neu starten", "{agent} runs its commands through RTK": "{agent} führt seine Befehle über RTK aus", diff --git a/internal/gui/login_allow_test.go b/internal/gui/login_allow_test.go new file mode 100644 index 000000000..51570f7ea --- /dev/null +++ b/internal/gui/login_allow_test.go @@ -0,0 +1,47 @@ +package gui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/autostart" +) + +// Open at login switched off in System Settings, its launch agent still +// there, reads as needing to be allowed, not as on (#2120, Anoninz): the +// row says so and opens Login Items, the one System Settings pane the page +// may open. +func TestLoginNeedsAllowing(t *testing.T) { + sandboxHome(t) + prev := loginState + t.Cleanup(func() { loginState = prev }) + for _, c := range []struct { + st autostart.State + login, allow bool + }{{autostart.Off, false, false}, {autostart.On, true, false}, {autostart.NeedsAllowing, true, true}} { + loginState = func() autostart.State { return c.st } + s := settingsState() + if s.Login != c.login || s.LoginAllow != c.allow { + t.Errorf("%s: login %v, loginAllow %v; want %v, %v", c.st, s.Login, s.LoginAllow, c.login, c.allow) + } + b, _ := json.Marshal(s) + if got := strings.Contains(string(b), `"loginAllow":true`); got != c.allow { + t.Errorf("%s: loginAllow in the JSON is %v: %s", c.st, got, b) + } + } + + w := &importWindows{} + mux := http.NewServeMux() + providerRoutes(mux, w) + for _, link := range []string{autostart.LoginItemsURL, "x-apple.systempreferences:com.apple.preference.security?Privacy_FilesAndFolders", "x-apple.systempreferences:"} { + w.opened = "" + body, _ := json.Marshal(map[string]string{"url": link}) + mux.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("POST", "/api/open", strings.NewReader(string(body)))) + if want := link == autostart.LoginItemsURL; (w.opened == link) != want { + t.Errorf("%s: opened %q", link, w.opened) + } + } +} diff --git a/internal/gui/plugins.go b/internal/gui/plugins.go index e10c18db6..d36829d47 100644 --- a/internal/gui/plugins.go +++ b/internal/gui/plugins.go @@ -3,6 +3,7 @@ package gui import ( "context" "encoding/json" + "errors" "io" "net/http" "regexp" @@ -495,9 +496,15 @@ func pluginRoutes(mux *http.ServeMux, w Windows) { // repositories on GitHub tagged magpie-plugin: nobody's list, shown // apart as not reviewed, installed from the repository mux.HandleFunc("GET /api/plugins/github", func(rw http.ResponseWriter, r *http.Request) { + // Try again asks GitHub at once when the list standing isn't its + // whole answer + if r.URL.Query().Get("again") != "" { + plugin.TaggedAskAgain() + } + got, err := plugin.TaggedRepos(r.Context()) // each one's own picture as the page can show it, kept here as an // installed plugin's is (a data URI isn't sent on to the page) - repos := append([]plugin.Tagged(nil), plugin.TaggedRepos(r.Context())...) + repos := append([]plugin.Tagged(nil), got...) said := make([]string, len(repos)) for i := range repos { said[i] = repos[i].Icon @@ -505,7 +512,17 @@ func pluginRoutes(mux *http.ServeMux, w Windows) { for i, ic := range provider.RepoIcons(said, 3*time.Second) { repos[i].Icon = ic } - writeJSON(rw, map[string]any{"repos": repos, "topic": plugin.Topic}) + out := map[string]any{"repos": repos, "topic": plugin.Topic} + // why the list isn't GitHub's whole answer: the page says so with + // Try again, rather than the section reading as there being none + if err != nil { + out["error"] = err.Error() + var m *plugin.TaggedMissing + if errors.As(err, &m) { + out["error"], out["missing"] = m.Why.Error(), m.Missing + } + } + writeJSON(rw, out) }) // the commit each installed git plugin's repository is at now (asked // at most every ten minutes), by spec; one that didn't answer is left diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 2c771e35f..263abc938 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -15,6 +15,7 @@ import ( "time" "github.com/yetone/magpie/internal/agent" + "github.com/yetone/magpie/internal/autostart" "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/provider" @@ -2276,7 +2277,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) { mux.HandleFunc("POST /api/open", func(rw http.ResponseWriter, r *http.Request) { var in struct{ URL string } _ = json.NewDecoder(r.Body).Decode(&in) - if strings.HasPrefix(in.URL, "https://") || strings.HasPrefix(in.URL, "http://") || strings.HasPrefix(in.URL, agent.CindyScheme) || strings.HasPrefix(in.URL, agent.LodyScheme) { + // and System Settings' Login Items, where Open at login is allowed + // again: that one pane, not System Settings' scheme at large + if strings.HasPrefix(in.URL, "https://") || strings.HasPrefix(in.URL, "http://") || strings.HasPrefix(in.URL, agent.CindyScheme) || strings.HasPrefix(in.URL, agent.LodyScheme) || in.URL == autostart.LoginItemsURL { // Open again on a sign-in says why it didn't open (#2043) if err := w.OpenURL(in.URL); err != nil { fail(rw, err) diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index c115d5b28..5418bbc09 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -2348,8 +2348,9 @@ node --test internal/gui/tests/ledger-protocol.test.cjs `library-rtk-nohook.test.cjs` checks that an agent RTK has no hook for (DeepSeek Harness) is listed in Library › RTK with a No RTK hook tag saying -why, and that its switch can't be turned on, while Pi's can. English and -Chinese, Chromium and WebKit. +why, and that its switch can't be turned on, while Pi's can. Grok Build's +tag gives its own reason and rtk-ai/rtk#2136, never dsh's #3847. English +and Chinese, Chromium and WebKit. ```sh node --test internal/gui/tests/library-rtk-nohook.test.cjs diff --git a/internal/gui/tests/library-rtk-nohook.test.cjs b/internal/gui/tests/library-rtk-nohook.test.cjs index aa7158b95..41bbdd77f 100644 --- a/internal/gui/tests/library-rtk-nohook.test.cjs +++ b/internal/gui/tests/library-rtk-nohook.test.cjs @@ -4,6 +4,10 @@ // --agent dsh), and the RTK tab left it out, as if magpie hadn't seen it. // It is listed now, tagged No RTK hook with why, and its switch can't be // turned on; in English and Chinese. No backend: the API is faked here. +// Discord (新v学员): Grok Build's tag said DeepSeek Harness's reason and +// linked dsh's rtk-ai/rtk#3847. Each agent's tag says its own reason now: +// Grok Build's cites rtk-ai/rtk#2136, the request for Grok Build, and says +// nothing about its hooks. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); const path = require("node:path"); @@ -15,7 +19,7 @@ const HOME = "/Users/aimer"; const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json` }); const lib = () => ({ dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, - agents: [agent("pi", "Pi"), agent("dsh", "DeepSeek Harness")], + agents: [agent("pi", "Pi"), agent("dsh", "DeepSeek Harness"), agent("grok", "Grok Build")], instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [], servers: [], }); const rtkView = () => ({ @@ -23,6 +27,7 @@ const rtkView = () => ({ agents: [ { id: "pi", name: "Pi", icon: "", on: false }, { id: "dsh", name: "DeepSeek Harness", icon: "", on: false, noHook: true, blocked: "RTK has no hook for DeepSeek Harness yet" }, + { id: "grok", name: "Grok Build", icon: "", on: false, noHook: true, blocked: "RTK has no hook for Grok Build yet" }, ], }); @@ -49,8 +54,8 @@ function server(lang, calls) { } const words = { - en: { tag: "No RTK hook", why: "DeepSeek Harness's hooks can only allow or deny a command, not change it" }, - zh: { tag: "RTK 暂不支持", why: "DeepSeek Harness 的 hook 只能放行或拦截命令,不能改写" }, + en: { tag: "No RTK hook", why: "DeepSeek Harness's hooks can only allow or deny a command, not change it", grok: "RTK's installer has no option for Grok Build" }, + zh: { tag: "RTK 暂不支持", why: "DeepSeek Harness 的 hook 只能放行或拦截命令,不能改写", grok: "RTK 的安装程序还没有 Grok Build 的选项" }, }; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { @@ -79,6 +84,15 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const tag = row("DeepSeek Harness").locator(".lib-tag"); assert.deepEqual(await tag.allTextContents(), [w.tag]); assert((await tag.getAttribute("title")).includes(w.why), await tag.getAttribute("title")); + assert((await tag.getAttribute("title")).includes("rtk-ai/rtk/issues/3847")); + // Grok Build's tag is its own: its issue, not dsh's, and nothing + // said about its hooks + const gtag = row("Grok Build").locator(".lib-tag"); + assert.deepEqual(await gtag.allTextContents(), [w.tag]); + const gwhy = await gtag.getAttribute("title"); + assert(gwhy.includes(w.grok) && gwhy.includes("rtk-ai/rtk/issues/2136"), gwhy); + assert(!gwhy.includes("3847") && !gwhy.includes("DeepSeek") && !gwhy.includes("hook"), gwhy); + assert.equal(await row("Grok Build").locator(".lib-switch").isDisabled(), true); const sw = row("DeepSeek Harness").locator(".lib-switch"); assert.equal(await sw.isDisabled(), true); // Pi has a hook: nothing to say, and it can be switched on diff --git a/internal/gui/tests/login-allow.test.cjs b/internal/gui/tests/login-allow.test.cjs new file mode 100644 index 000000000..ee45e5b74 --- /dev/null +++ b/internal/gui/tests/login-allow.test.cjs @@ -0,0 +1,122 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Anoninz on #2120: magpie's Open at login said On while the Mac's own +// switch for it, in System Settings › General › Login Items, was off, so +// magpie never opened at login. Settings now says whether the system will +// open it: in every language, at 1000px and 440px, in both engines, on a Mac, +// with the API faked: +// - a record the system holds switched off shows On with one line under it +// saying so, and a button that asks magpie to open Login Items (the exact +// x-apple.systempreferences URL, through /api/open); +// - the window coming back to the front reads the state again: switched +// back on there, the line goes; +// - a page served to another computer (web) has no System Settings to +// open, and no Open at login row at all. +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 { watchSettingsReads, settingsDrawn } = require("./reader.cjs"); + +const assets = path.resolve(__dirname, "../assets"); +const loginItems = "x-apple.systempreferences:com.apple.LoginItems-Settings.extension"; +const line = { + en: "Switched off in System Settings’ Login Items, so magpie won’t open at login", + zh: "已在系统设置的登录项里关闭,登录时不会打开 magpie", + "zh-TW": "已在系統設定的登入項目裡關閉,登入時不會開啟 magpie", + ja: "システム設定のログイン項目でオフになっているため、ログイン時に magpie は開きません", + de: "In den Systemeinstellungen unter „Anmeldeobjekte“ ausgeschaltet, daher öffnet sich magpie bei der Anmeldung nicht", +}; +const button = { en: "Open Login Items", zh: "打开登录项", "zh-TW": "打開登入項目", ja: "ログイン項目を開く", de: "Anmeldeobjekte öffnen" }; + +function serve(lang, web, st, opened) { + const settings = () => ({ lang, theme: "light", searchVendors: [], searchAPIs: [], ...st }); + return async (r) => { + const url = new URL(r.request().url()); + const json = (data, status = 200) => r.fulfill({ status, json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${web}};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: settings() }); + if (url.pathname === "/api/settings") return json(settings()); + if (url.pathname === "/api/open") { + opened.push(JSON.parse(r.request().postData()).url); + return json({}); + } + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname.startsWith("/api/")) return json({}); + 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)]; + await r.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) for (const width of [1000, 440]) for (const web of [false, true]) { + test(`${engine} ${lang} ${width}px${web ? " web" : ""}: Open at login says when the Mac's own switch for it is off`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 760 } })).newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.addInitScript(() => Object.defineProperty(navigator, "platform", { get: () => "MacIntel" })); + const st = { login: true, loginAllow: true }, opened = []; + await page.route("**/*", serve(lang, web, st, opened)); + await watchSettingsReads(page); + await page.goto("http://magpie.test/?view=settings&tab=general"); + await settingsDrawn(page); + const sub = page.locator("#loginRow .login-allow"); + if (web) { + await page.locator("#loginRow").waitFor({ state: "hidden" }); + await page.locator("#langPick span").waitFor(); + assert.equal(await page.locator("#loginRow").isHidden(), true, "a page served to another computer offers Open at login"); + assert.deepEqual(errors, []); + return; + } + await sub.waitFor(); + + const seen = await page.evaluate(() => { + const row = document.querySelector("#loginRow"), s = row.querySelector(".login-allow"), r = row.getBoundingClientRect(); + return { + text: s.firstChild.textContent, + inside: [...s.getClientRects()].every((x) => x.left >= r.left - 0.5 && x.right <= r.right + 0.5), + stripe: parseFloat(getComputedStyle(row).borderLeftWidth) > 1, + sideways: document.documentElement.scrollWidth > innerWidth, + selects: document.querySelectorAll("#setPage-general select").length, + }; + }); + assert.equal(seen.text, line[lang]); + assert.ok(seen.inside, "the line runs out of its row"); + assert.equal(seen.stripe, false, "the row has a stripe down its left"); + assert.equal(seen.sideways, false, "the page scrolls sideways"); + assert.equal(seen.selects, 0, "no native