agent: Claude Code's permission mode is set in magpie and kept (EricChenChannel on X)
The report: "every time I configure settings.json it is overwritten and
reset" for permissions.defaultMode = bypassPermissions.
Cause, reproduced in a sandbox HOME with Claude Code 2.1.316: magpie's
writes to ~/.claude/settings.json are key-level and kept the user's
permissions block. Claude Code itself drops the mode: it ignores
bypassPermissions at launch unless skipDangerousModePermissionPrompt is
true, and its auto-mode nudge and /config write defaultMode over it.
Change:
- agent.Field gets Own: the user's own setting of the agent. Apply does
not record it, Disconnect neither clears nor restores it, Pick never
connects the agent for it, magpieValueIn is false for it, and profiles
(Fields, ApplyFields, InUse) and the WSL copy leave it alone. So the
mode outlives disconnecting magpie and switching profiles.
- Claude Code's permission_mode field (default, acceptEdits, plan, auto,
dontAsk, bypassPermissions; "" removes the key) writes
permissions.defaultMode, and bypassPermissions also writes
skipDangerousModePermissionPrompt: true so Claude Code honours it.
- GUI: own fields go in agentJSON.own, apart from fields, and
agentcompact.js draws them in an Advanced fold (collapsed) under the
agent's settings, with the app menu (no <select>). app.js unchanged.
Labels in en, zh, zh-TW, ja, de (zh: 高级 › 权限模式 › 跳过权限确认).
- docs/subsystems/agent-wiring.md: Fields and options row.
Run at this tree (base aa358555f, origin/main at commit time), on mote/mica:
- go test ./internal/agent -run 'Permission|Profile' ; ./internal/profile ;
./internal/gui -run 'Budget|PermissionMode|AgentOwn|AgentModels': ok
- GUI claude-permission-mode.test.cjs in chromium and webkit, en and zh:
4/4; i18n-keys, i18n-en-no-cjk: ok
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./...: ok
Broken by hand:
- Own: false on the field: TestClaudePermissionModeOutlivesMagpie
("disconnecting took the mode to \"\"") and TestProfileLeavesPermissionMode
("a profile wrote the permission mode") went red.
- Without the GUI own/fields split, the "not a picker on the row" check in
claude-permission-mode.test.cjs went red.
Not run yet: the full go test ./... and the full GUI suite. Both machines
had another session's GUI suite running; they run next and their result
goes on the follow-up. Not tried: a real Claude Code session's /config
changing the mode back (Claude Code's own write; this change can't stop it).
This commit is contained in:
@@ -13,7 +13,7 @@ something else shows up as drift.
|
||||
| Part | Responsibility | Source |
|
||||
| --- | --- | --- |
|
||||
| Agent description | `Agent` has an id, name, icon, `Bin` and `Dir` for detection, `Path`, `Fields` and `Native`. It also has optional hooks: `Notice`, `UA`, `ListsModels`, `Sync`, `Unwire`, `Join`/`Joined`, `Routed`, `Follow`, `RenameRefs`, `Check`, `LastUsed`, `Reached`, `Import`/`Added`, `Launch`, `SplitSuffix`, `Spelled` and `ModelAliases`. Each hook's comment says which agents need it. A `Dir` holding only its `signIn` file (Codex's `auth.json`, Claude Code's `.credentials.json`), which a sign-in added in magpie writes for an agent signed in to nothing, is no sign the agent is installed (`TestSignInFileAloneIsNoAgent`; jiangshangmuyun on X). | [`agent.go`](../../internal/agent/agent.go) |
|
||||
| Fields and options | A `Field` has `Get`, `Set` and `Options`. `Set("")` returns the field to the agent's default and takes magpie's wiring out. `Quiet` fields follow another field until set (`Follows`, such as Claude Code's tiers). An `Option` carries the picker's facts: `Direct`, `Via`, `Same`, `Alias`, `Rate` and `Context`. The GUI's and TUI's pickers list `Agent.Picks`: with the agent in settings' `ownModelsHidden` (the switch at the top of its model list, #1642), a field that offers catalog models (`Ref`) leaves out the agent's own (no `Ref`), but for its default and the value it is set to. The CLI still takes an own model by name. | [`agent.go`](../../internal/agent/agent.go), [`route.go`](../../internal/agent/route.go) |
|
||||
| Fields and options | A `Field` has `Get`, `Set` and `Options`. `Set("")` returns the field to the agent's default and takes magpie's wiring out. `Quiet` fields follow another field until set (`Follows`, such as Claude Code's tiers). `Own` fields are the user's own settings of the agent's, never magpie's wiring: Claude Code's `permission_mode` (`claudePermissionField` in [`claude.go`](../../internal/agent/claude.go), EricChenChannel on X) writes `permissions.defaultMode` in the settings.json that row reads, with `skipDangerousModePermissionPrompt: true` beside `bypassPermissions`, since Claude Code ignores bypass at launch without it; `""` takes the mode out. Apply doesn't record an Own field, so Disconnect, Reapply and the stash put back at disconnect leave it as the user set it; it never counts as one of magpie's values (`magpieValueIn`) and a pick of it never connects the agent; profiles neither keep nor write it (`profile.Fields`, `ApplyFields`, `InUse`); a WSL copy keeps the flag. The GUI gets it as the agent's `own`, apart from `fields`, so no picker on the row draws it, and `agentcompact.js` folds it under Advanced in the agent's settings, written through `POST /api/set`. Claude Code itself still writes the key from its `/config` menu and its auto-mode suggestion. `TestClaudePermissionModeWritten`, `TestClaudePermissionModeOutlivesMagpie`, `TestProfileLeavesPermissionMode`, `TestClaudePermissionModeSentAsOwn`, claude-permission-mode.test.cjs. An `Option` carries the picker's facts: `Direct`, `Via`, `Same`, `Alias`, `Rate` and `Context`. The GUI's and TUI's pickers list `Agent.Picks`: with the agent in settings' `ownModelsHidden` (the switch at the top of its model list, #1642), a field that offers catalog models (`Ref`) leaves out the agent's own (no `Ref`), but for its default and the value it is set to. The CLI still takes an own model by name. | [`agent.go`](../../internal/agent/agent.go), [`route.go`](../../internal/agent/route.go) |
|
||||
| The agent's own telemetry | `Agent.Telemetry` (`Get`, `Set`) is the agent's documented switch for the usage data it sends its vendor: Codex's `[analytics] enabled = false`, Claude Code's env `DISABLE_TELEMETRY` and `DISABLE_ERROR_REPORTING`, Gemini CLI's and Qwen Code's `privacy.usageStatisticsEnabled = false` (OipsAnthony on X), Crush's `options.disable_metrics = true`, Kimi Code's top-level `telemetry = false` in config.toml, Goose's `GOOSE_TELEMETRY_ENABLED: false` in config.yaml, Pi's `enableInstallTelemetry = false` and Cline CLI's `telemetryOptOut = true` in global-settings.json (daoche_wuzui on X). Antigravity has none to write (agy's `EnableTelemetry` is `json:"-"`; it is the Google account's setting), nor do Droid (organisation-set), OpenCode and omp (OpenTelemetry is opt-in), Cursor CLI (account privacy mode) and Hermes (sends none). TOML and YAML files are read strictly (`topTelemetryFile`), so a file that doesn't parse is unknown. It is not a `Field`, so profiles never carry it and Unwire leaves it. Off writes only keys the file lacks and records them in the stash (`<id>.telemetry`); a key the user set on refuses Off, naming it, and one they set off stays. On takes out only what magpie wrote and still holds magpie's value. An unreadable file is unknown: the row says so and can't be pressed. Offered for an agent on this computer only, never a WSL distro's (#3896). The GUI row is `telemetryRow` in the agent's Settings; the route is `POST /api/agents/telemetry/{id}`. Settings › Privacy's "Turn off telemetry for all agents" (`settings.AgentTelemetryOff`, `POST /api/settings/agent-telemetry`, `SetTelemetryAll`) is above every row: on, each agent here is turned off by the same rules and marked in the stash (`<id>.telemetry.all`) unless it was off already; an agent found later is turned off as `state()` sees it and by the gateway's `KeepTelemetryAllOff` loop; each row then shows off, held (`ErrTelemetryAllOff`), or why it couldn't. Off again, only the marked agents are turned back on, so each is as its own row had it. The setting is this computer's (`KeepOwn`), and an unreadable settings.json writes nothing. | [`telemetry.go`](../../internal/agent/telemetry.go), [`telemetry_all.go`](../../internal/agent/telemetry_all.go), [`api.go`](../../internal/gui/api.go) |
|
||||
| The list of agents | `All` lists every agent magpie knows, then the WSL agents (`wslAgents`). `Clients` lists every agent whose requests the gateway knows by name, which `usage.Agents` reads. One file per agent: `claude.go`, `codex.go`, `opencode` in `agents.go`, and so on. | [`agents.go`](../../internal/agent/agents.go) |
|
||||
| Connect | `ConnectHow` picks the model an agent starts on and reports how. `How` is one of: `kept`, `again`, `joined`, `magpie`, `same`, `alike`, `default` or `first` (#726). With no models to give, it returns `NoModelsError` (code `no_models`). | [`applied.go`](../../internal/agent/applied.go) |
|
||||
|
||||
@@ -116,6 +116,12 @@ type Field struct {
|
||||
// ("model" for Claude Code's tiers and subagents): a profile's details
|
||||
// say so, and Drift reads the field as on that one's model (#1050).
|
||||
Follows string
|
||||
// Own fields are the user's own settings of the agent's, never
|
||||
// magpie's wiring (Claude Code's permission mode): magpie writes one
|
||||
// only when the user picks it, so Disconnect, Reapply and a restore
|
||||
// leave it as it is, and a profile neither keeps nor writes it. A
|
||||
// value the user then sets in the agent itself stays theirs.
|
||||
Own bool
|
||||
}
|
||||
|
||||
// Agent is one supported coding agent.
|
||||
|
||||
@@ -129,7 +129,10 @@ func (a *Agent) Apply(key, v string) error {
|
||||
record(a.ID, k, now[k])
|
||||
}
|
||||
}
|
||||
record(a.ID, f.Key, f.Get())
|
||||
// the user's own setting isn't magpie's to put back or take out
|
||||
if !f.Own {
|
||||
record(a.ID, f.Key, f.Get())
|
||||
}
|
||||
// magpie picked in by the user's own hand (magpie model, a pick in
|
||||
// the CLI) connects it again
|
||||
if a.Wired() {
|
||||
@@ -405,7 +408,8 @@ func (m *valueMemo) in(a *Agent, f Field, v string, vals map[string]string, opts
|
||||
// magpieValueIn is magpieValue reading a field's options from opts, made
|
||||
// for the same vals; nil reads them anew.
|
||||
func magpieValueIn(a *Agent, f Field, v string, vals map[string]string, opts fieldOptions) bool {
|
||||
if v == "" {
|
||||
// the user's own setting (a permission mode) is never one of magpie's
|
||||
if v == "" || f.Own {
|
||||
return false
|
||||
}
|
||||
v, _, one := a.split(v)
|
||||
@@ -618,7 +622,8 @@ func (a *Agent) Pick(key, v string) error {
|
||||
}
|
||||
return a.Apply(key, value)
|
||||
}
|
||||
if f := a.Field(key); f != nil && !a.Wired() {
|
||||
// the user's own setting never connects the agent to magpie
|
||||
if f := a.Field(key); f != nil && !f.Own && !a.Wired() {
|
||||
vals := a.Values()
|
||||
vals[key] = v
|
||||
if v == magpieID || magpieValue(a, *f, v, vals) {
|
||||
@@ -934,6 +939,9 @@ func (a *Agent) Disconnect() (err error) {
|
||||
}
|
||||
}
|
||||
for _, f := range a.Fields {
|
||||
if f.Own {
|
||||
continue
|
||||
}
|
||||
vals := a.Values()
|
||||
v := vals[f.Key]
|
||||
// set by magpie: as it set it, or its group by the model's name
|
||||
@@ -960,6 +968,10 @@ func (a *Agent) Disconnect() (err error) {
|
||||
}
|
||||
}
|
||||
for _, f := range a.Fields {
|
||||
// the user's own setting is as they left it, not as it was at connect
|
||||
if f.Own {
|
||||
continue
|
||||
}
|
||||
if w := was[f.Key]; w != "" && after[f.Key] == "" && w != magpieID && !magpieValue(a, f, w, was) {
|
||||
if err := f.Set(w); err != nil {
|
||||
return fmt.Errorf("%s: %w", f.Label, err)
|
||||
|
||||
@@ -2418,6 +2418,11 @@ func claudeIn(at place) *Agent {
|
||||
return claudeViaMagpie(false)
|
||||
},
|
||||
})
|
||||
// permission mode: the mode a new session starts in, Claude Code's own
|
||||
// permissions.defaultMode (EricChenChannel on X). The user's setting,
|
||||
// not magpie's wiring (Own): written only when picked here, and
|
||||
// nothing magpie does takes it out or puts it back.
|
||||
fields = append(fields, claudePermissionField(path))
|
||||
// its sign-in while it runs through magpie: magpie's key, or its own
|
||||
// claude.ai sign-in kept (loginKey), where the gateway takes any key
|
||||
fields = append(fields, Field{
|
||||
@@ -3336,3 +3341,41 @@ func inMagpieWork(m map[string]json.RawMessage) bool {
|
||||
base = base[strings.LastIndexAny(base, `/\`)+1:]
|
||||
return base == "magpie-claude-work" || strings.HasPrefix(base, "magpie-claude-work-")
|
||||
}
|
||||
|
||||
// claudePermissionModes are the modes Claude Code's permissions.defaultMode
|
||||
// takes (2.1.316), each with the name its own /permissions gives it.
|
||||
var claudePermissionModes = []Option{
|
||||
{Value: "default", Label: "Default", Note: "asks before each edit and command"},
|
||||
{Value: "acceptEdits", Label: "Accept edits", Note: "edits files without asking"},
|
||||
{Value: "plan", Label: "Plan mode", Note: "reads and plans, changes nothing"},
|
||||
{Value: "auto", Label: "Auto", Note: "a classifier lets safe actions through"},
|
||||
{Value: "dontAsk", Label: "Don't ask", Note: "refuses what isn't allowed, never asks"},
|
||||
{Value: "bypassPermissions", Label: "Bypass permissions", Note: "runs everything without asking"},
|
||||
}
|
||||
|
||||
// claudePermissionField is the permission mode Claude Code at path starts
|
||||
// a new session in. Bypass permissions also records the consent Claude
|
||||
// Code otherwise asks for (skipDangerousModePermissionPrompt), without
|
||||
// which it ignores the mode at launch; empty takes the mode out, back to
|
||||
// Claude Code's own default, and leaves a consent given before.
|
||||
func claudePermissionField(path string) Field {
|
||||
return Field{
|
||||
Key: "permission_mode", Label: "permission mode", Quiet: true, Own: true,
|
||||
Get: jsonGet(path, "permissions.defaultMode"),
|
||||
Set: func(v string) error {
|
||||
v = strings.TrimSpace(v)
|
||||
if v == "" {
|
||||
return edit.DelJSON(path, "permissions.defaultMode")
|
||||
}
|
||||
if !slices.ContainsFunc(claudePermissionModes, func(o Option) bool { return o.Value == v }) {
|
||||
return fmt.Errorf("permission mode: Claude Code has no mode %q", v)
|
||||
}
|
||||
kv := []edit.KV{{Path: "permissions.defaultMode", Value: v}}
|
||||
if v == "bypassPermissions" {
|
||||
kv = append(kv, edit.KV{Path: "skipDangerousModePermissionPrompt", Value: true})
|
||||
}
|
||||
return edit.SetJSON(path, kv...)
|
||||
},
|
||||
Options: func(map[string]string) []Option { return slices.Clone(claudePermissionModes) },
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// Claude Code's permission mode is the user's own (EricChenChannel on X:
|
||||
// bypassPermissions set by hand in settings.json kept coming back as
|
||||
// default). magpie writes it where Claude Code reads it, with the consent
|
||||
// key bypass needs at launch, and nothing magpie does to the agent puts it
|
||||
// back or takes it out.
|
||||
func permissionHome(t *testing.T) (string, string) {
|
||||
t.Helper()
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
|
||||
t.Setenv("CLAUDE_CONFIG_DIR", "")
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: "https://relay.example.com/v1", Key: "synthetic-key", Models: []string{"pro", "flash"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(home, ".claude", "settings.json")
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(`{"theme": "dark"}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return home, path
|
||||
}
|
||||
|
||||
func permAt(t *testing.T, path, key string) string {
|
||||
t.Helper()
|
||||
v, _ := edit.GetJSON(path, key)
|
||||
return v
|
||||
}
|
||||
|
||||
func TestClaudePermissionModeWritten(t *testing.T) {
|
||||
home, path := permissionHome(t)
|
||||
f := claude(home).Field("permission_mode")
|
||||
if f == nil {
|
||||
t.Fatal("Claude Code has no permission mode setting")
|
||||
}
|
||||
if !f.Own {
|
||||
t.Error("the permission mode is the user's own, not magpie's wiring")
|
||||
}
|
||||
if err := f.Set("bypassPermissions"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// bypass without its consent key is ignored at launch by Claude Code
|
||||
if m, ok := permAt(t, path, "permissions.defaultMode"), permAt(t, path, "skipDangerousModePermissionPrompt"); m != "bypassPermissions" || ok != "true" {
|
||||
b, _ := os.ReadFile(path)
|
||||
t.Errorf("bypass written as:\n%s", b)
|
||||
}
|
||||
if err := f.Set("plan"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := f.Get(); got != "plan" {
|
||||
t.Errorf("mode reads %q", got)
|
||||
}
|
||||
if err := f.Set("everything"); err == nil {
|
||||
t.Error("a mode Claude Code doesn't have was written")
|
||||
}
|
||||
if err := f.Set(""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if permAt(t, path, "permissions.defaultMode") != "" || permAt(t, path, "theme") != "dark" {
|
||||
b, _ := os.ReadFile(path)
|
||||
t.Errorf("not set should take out the mode alone:\n%s", b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaudePermissionModeOutlivesMagpie(t *testing.T) {
|
||||
home, path := permissionHome(t)
|
||||
if _, err := claude(home).ConnectHow(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// picked in magpie, so Apply has seen it
|
||||
if err := claude(home).Pick("permission_mode", "bypassPermissions"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := appliedOf(claude(home).ID).Fields["permission_mode"]; ok {
|
||||
t.Error("the user's permission mode was recorded as magpie's")
|
||||
}
|
||||
if err := claude(home).Pick("model", "relay/flash"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := claude(home).Disconnect(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m := permAt(t, path, "permissions.defaultMode"); m != "bypassPermissions" {
|
||||
b, _ := os.ReadFile(path)
|
||||
t.Errorf("disconnecting took the mode to %q:\n%s", m, b)
|
||||
}
|
||||
if _, err := claude(home).ConnectHow(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := claude(home).Field("permission_mode").Set("plan"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := claude(home).Disconnect(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m := permAt(t, path, "permissions.defaultMode"); m != "plan" {
|
||||
t.Errorf("the mode set while connected came back as %q", m)
|
||||
}
|
||||
}
|
||||
@@ -1124,7 +1124,7 @@ func asleep(live *Agent, k wslKind, d distro) *Agent {
|
||||
}}
|
||||
for _, lf := range live.Fields {
|
||||
key := lf.Key
|
||||
f := Field{Key: key, Label: lf.Label, Quiet: lf.Quiet, Live: lf.Live, Follows: lf.Follows, Options: lf.Options,
|
||||
f := Field{Key: key, Label: lf.Label, Quiet: lf.Quiet, Live: lf.Live, Follows: lf.Follows, Own: lf.Own, Options: lf.Options,
|
||||
Get: func() string { return wslLastSeen(d.Name, k.memo(key)) },
|
||||
Set: func(v string) error {
|
||||
// opening a stopped distro's files is aborted rather than
|
||||
|
||||
@@ -82,8 +82,21 @@ func takesCatalog(fields []fieldJSON) bool {
|
||||
|
||||
// agentFields are an agent's pickers as the Agents page draws them.
|
||||
func agentFields(a *agent.Agent, vals map[string]string) []fieldJSON {
|
||||
return fieldsOf(a, vals, false)
|
||||
}
|
||||
|
||||
// ownFields are its settings of the user's own (agent.Field.Own), which
|
||||
// its Settings fold under Advanced and no picker draws.
|
||||
func ownFields(a *agent.Agent, vals map[string]string) []fieldJSON {
|
||||
return fieldsOf(a, vals, true)
|
||||
}
|
||||
|
||||
func fieldsOf(a *agent.Agent, vals map[string]string, own bool) []fieldJSON {
|
||||
out := []fieldJSON{}
|
||||
for _, f := range a.Fields {
|
||||
if f.Own != own {
|
||||
continue
|
||||
}
|
||||
opts := a.Picks(f, vals)
|
||||
if opts == nil {
|
||||
opts = []agent.Option{}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/agent"
|
||||
)
|
||||
|
||||
// Claude Code's permission mode is the user's own setting (EricChenChannel
|
||||
// on X): the Agents page gets it apart from the row's pickers, as the
|
||||
// agent's own, with what settings.json holds and every mode to pick.
|
||||
func TestClaudePermissionModeSentAsOwn(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
|
||||
t.Setenv("CLAUDE_CONFIG_DIR", "")
|
||||
path := filepath.Join(home, ".claude", "settings.json")
|
||||
os.MkdirAll(filepath.Dir(path), 0o755)
|
||||
if err := os.WriteFile(path, []byte(`{"permissions": {"defaultMode": "bypassPermissions"}}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a, err := agent.Find("claude")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vals := a.Values()
|
||||
for _, f := range agentFields(a, vals) {
|
||||
if f.Key == "permission_mode" {
|
||||
t.Error("the permission mode is among the row's pickers")
|
||||
}
|
||||
}
|
||||
own := ownFields(a, vals)
|
||||
if len(own) != 1 || own[0].Key != "permission_mode" || own[0].Value != "bypassPermissions" || len(own[0].Options) != 6 {
|
||||
t.Fatalf("the agent's own settings: %+v", own)
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -199,6 +199,10 @@ type agentJSON struct {
|
||||
Icon string `json:"icon"`
|
||||
Path string `json:"path"`
|
||||
Fields []fieldJSON `json:"fields"`
|
||||
// Own: the user's own settings of the agent's (agent.Field.Own,
|
||||
// Claude Code's permission mode), apart from Fields so no picker on
|
||||
// its row draws them: agentcompact.js folds them under Advanced
|
||||
Own []fieldJSON `json:"own,omitempty"`
|
||||
// Drift: its config no longer does what magpie set, and how to set it again
|
||||
Drift *agent.Drift `json:"drift,omitempty"`
|
||||
// Wired: magpie is in its config, which its menu's Disconnect takes out
|
||||
@@ -3314,7 +3318,7 @@ func state() stateJSON {
|
||||
}
|
||||
vals := a.Values()
|
||||
now[a.ID] = vals
|
||||
aj := agentJSON{ID: a.ID, Name: a.Name, Icon: a.Icon, Path: tilde(a.Path), Fields: agentFields(a, vals)}
|
||||
aj := agentJSON{ID: a.ID, Name: a.Name, Icon: a.Icon, Path: tilde(a.Path), Fields: agentFields(a, vals), Own: ownFields(a, vals)}
|
||||
aj.Models = agentModelCount(a, aj.Fields)
|
||||
aj.Menu = a.ListsModels
|
||||
aj.NoNames = a.NoNames
|
||||
|
||||
@@ -150,8 +150,59 @@ function claudeAttributionRow(list) {
|
||||
return row;
|
||||
}
|
||||
|
||||
// The user's own settings of the agent's (agent.Field.Own: Claude Code's
|
||||
// permission mode, EricChenChannel on X), seldom changed, so folded under
|
||||
// Advanced after the sheet's list; written in the agent's own config, never
|
||||
// taken back when magpie lets go of the agent.
|
||||
function ownFieldsFold(list, a) {
|
||||
const own = a.own || [];
|
||||
if (!own.length) return;
|
||||
queueMicrotask(() => {
|
||||
if (!list.parentNode) return;
|
||||
list.parentNode.querySelector(":scope > .own-fields")?.remove();
|
||||
const fold = el("details", "prefs-more own-fields");
|
||||
const inner = el("div", "list prefs");
|
||||
fold.append(el("summary", "", t("Advanced")), inner);
|
||||
for (const f of own) {
|
||||
const label = f.label[0].toUpperCase() + f.label.slice(1);
|
||||
const row = el("div", "row pref own-field");
|
||||
row.dataset.key = f.key;
|
||||
const who = el("div", "who"), val = el("div", "val");
|
||||
who.append(el("div", "name", t(label)));
|
||||
row.append(who, val);
|
||||
const draw = (cur) => {
|
||||
const opts = [{ v: "", name: "Not set", note: "" }, ...f.options.map((o) => ({ v: o.value, name: o.label || o.value, note: o.note || "" }))];
|
||||
const known = opts.find((o) => o.v === cur);
|
||||
const b = el("button", "sess-pick");
|
||||
b.type = "button";
|
||||
b.setAttribute("aria-label", t(label));
|
||||
b.setAttribute("aria-haspopup", "menu");
|
||||
b.setAttribute("aria-expanded", "false");
|
||||
b.append(el("span", "", known ? t(known.name) : cur), svg(CHEV, 11, 1.6));
|
||||
b.onclick = (e) => {
|
||||
e.stopPropagation();
|
||||
if (b.classList.contains("open")) return closeProtoMenu();
|
||||
openProtoMenu(b, opts, cur, (v) => {
|
||||
if (v === cur) return;
|
||||
api("set", { agent: a.id, field: f.key, value: v }).then((ns) => {
|
||||
state = ns;
|
||||
if (row.isConnected) draw(v);
|
||||
status(t("Takes effect when {agent} next starts", { agent: a.name }), "ok");
|
||||
}, (err) => status(t(err.message), "err"));
|
||||
}, label, "sess-menu", "right");
|
||||
};
|
||||
val.replaceChildren(b);
|
||||
};
|
||||
draw(f.value || "");
|
||||
inner.append(row);
|
||||
}
|
||||
list.after(fold);
|
||||
});
|
||||
}
|
||||
|
||||
// Its own context windows come in the same sheet, last (agentwindow.js).
|
||||
window.agentCompactFill = function (list, a, ids) {
|
||||
if (ids.includes("fullContextRow")) compactFill(list, a);
|
||||
ownFieldsFold(list, a);
|
||||
if (a.fields.length) import("./agentwindow.js").then(() => agentWindowFill(list, a), () => {});
|
||||
};
|
||||
|
||||
@@ -5283,6 +5283,17 @@ const I18N = {
|
||||
"Where": "位置",
|
||||
"Copy Report": "复制报告",
|
||||
"This report is no longer kept: magpie keeps the last 5.": "这份报告已经不在了:magpie 只保留最近 5 份。",
|
||||
"Permission mode": "权限模式",
|
||||
"Accept edits": "自动接受编辑",
|
||||
"Plan mode": "计划模式",
|
||||
"Don't ask": "不询问",
|
||||
"Bypass permissions": "跳过权限确认",
|
||||
"asks before each edit and command": "每次编辑和运行命令前都询问",
|
||||
"edits files without asking": "直接编辑文件,不询问",
|
||||
"reads and plans, changes nothing": "只读取和规划,不做改动",
|
||||
"a classifier lets safe actions through": "由分类器放行安全的操作",
|
||||
"refuses what isn't allowed, never asks": "不在允许范围内的直接拒绝,从不询问",
|
||||
"runs everything without asking": "所有操作都直接运行,不询问",
|
||||
},
|
||||
"zh-TW": {
|
||||
"Calls": "呼叫次數",
|
||||
@@ -10548,6 +10559,17 @@ const I18N = {
|
||||
"Where": "位置",
|
||||
"Copy Report": "複製報告",
|
||||
"This report is no longer kept: magpie keeps the last 5.": "這份報告已經不在了:magpie 只保留最近 5 份。",
|
||||
"Permission mode": "權限模式",
|
||||
"Accept edits": "自動接受編輯",
|
||||
"Plan mode": "計畫模式",
|
||||
"Don't ask": "不詢問",
|
||||
"Bypass permissions": "略過權限確認",
|
||||
"asks before each edit and command": "每次編輯和執行命令前都詢問",
|
||||
"edits files without asking": "直接編輯檔案,不詢問",
|
||||
"reads and plans, changes nothing": "只讀取和規劃,不做變更",
|
||||
"a classifier lets safe actions through": "由分類器放行安全的操作",
|
||||
"refuses what isn't allowed, never asks": "不在允許範圍內的直接拒絕,從不詢問",
|
||||
"runs everything without asking": "所有操作都直接執行,不詢問",
|
||||
},
|
||||
ja: {
|
||||
"Calls": "呼び出し数",
|
||||
@@ -15815,6 +15837,17 @@ const I18N = {
|
||||
"Where": "場所",
|
||||
"Copy Report": "レポートをコピー",
|
||||
"This report is no longer kept: magpie keeps the last 5.": "このレポートはもう残っていません。magpie は最新の 5 件だけを保存します。",
|
||||
"Permission mode": "権限モード",
|
||||
"Accept edits": "編集を自動承認",
|
||||
"Plan mode": "プランモード",
|
||||
"Don't ask": "確認しない",
|
||||
"Bypass permissions": "権限確認をスキップ",
|
||||
"asks before each edit and command": "編集やコマンドのたびに確認する",
|
||||
"edits files without asking": "確認せずにファイルを編集する",
|
||||
"reads and plans, changes nothing": "読み取りと計画のみで、変更しない",
|
||||
"a classifier lets safe actions through": "分類器が安全な操作を通す",
|
||||
"refuses what isn't allowed, never asks": "許可外の操作は拒否し、確認しない",
|
||||
"runs everything without asking": "すべて確認せずに実行する",
|
||||
},
|
||||
de: {
|
||||
"Calls": "Aufrufe",
|
||||
@@ -21082,6 +21115,17 @@ const I18N = {
|
||||
"Where": "Wo",
|
||||
"Copy Report": "Bericht kopieren",
|
||||
"This report is no longer kept: magpie keeps the last 5.": "Dieser Bericht ist nicht mehr da: magpie behält nur die letzten 5.",
|
||||
"Permission mode": "Berechtigungsmodus",
|
||||
"Accept edits": "Änderungen annehmen",
|
||||
"Plan mode": "Planmodus",
|
||||
"Don't ask": "Nicht fragen",
|
||||
"Bypass permissions": "Berechtigungen umgehen",
|
||||
"asks before each edit and command": "fragt vor jeder Änderung und jedem Befehl",
|
||||
"edits files without asking": "ändert Dateien ohne Nachfrage",
|
||||
"reads and plans, changes nothing": "liest und plant, ändert nichts",
|
||||
"a classifier lets safe actions through": "ein Klassifikator lässt sichere Aktionen durch",
|
||||
"refuses what isn't allowed, never asks": "lehnt Nicht-Erlaubtes ab, fragt nie",
|
||||
"runs everything without asking": "führt alles ohne Nachfrage aus",
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Claude Code's permission mode (EricChenChannel on X: bypassPermissions set
|
||||
// by hand in settings.json kept coming back): the user's own setting
|
||||
// (agent.Field.Own), sent as the agent's own and not among its fields, so
|
||||
// not a picker on its row but folded under Advanced in its settings, picked
|
||||
// from the app's menu and posted to /api/set. Chromium and WebKit, English and Chinese; the API is faked.
|
||||
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, agentRow, openAgentSettings, pickItem } = require("./reader.cjs");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const MODES = [
|
||||
["default", "Default", "asks before each edit and command"],
|
||||
["acceptEdits", "Accept edits", "edits files without asking"],
|
||||
["plan", "Plan mode", "reads and plans, changes nothing"],
|
||||
["auto", "Auto", "a classifier lets safe actions through"],
|
||||
["dontAsk", "Don't ask", "refuses what isn't allowed, never asks"],
|
||||
["bypassPermissions", "Bypass permissions", "runs everything without asking"],
|
||||
];
|
||||
|
||||
function serve(lang, posts) {
|
||||
const settings = {
|
||||
theme: "light", lang, tray: "panel", currency: "usd", version: "0.1.900", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425", proxyNow: "none", proxySource: "none", visionModels: [], imageGenModels: [], titleModels: [], workbuddyCheckins: [], lanURLs: [], redactWords: [], trayUsageEvery: 3, compactAt: 400000,
|
||||
};
|
||||
let mode = "bypassPermissions";
|
||||
const claude = () => {
|
||||
const a = agentRow("claude", "Claude Code");
|
||||
a.own = [{ key: "permission_mode", label: "permission mode", value: mode, options: MODES.map(([value, label, note]) => ({ value, label, note })) }];
|
||||
return a;
|
||||
};
|
||||
const state = () => ({ agents: [claude(), agentRow("codex", "Codex")], profiles: [], settings: { lang, theme: "light" } });
|
||||
return async (route) => {
|
||||
const req = route.request(), url = new URL(req.url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json(state());
|
||||
if (url.pathname === "/api/set") {
|
||||
const body = req.postDataJSON();
|
||||
posts.push(body);
|
||||
mode = body.value;
|
||||
return json(state());
|
||||
}
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
if (url.pathname === "/api/settings") return json(settings);
|
||||
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);
|
||||
try {
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType: { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)] });
|
||||
} catch {
|
||||
await route.fulfill({ status: 404, body: "" });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const words = {
|
||||
en: { advanced: "Advanced", name: "Permission mode", bypass: "Bypass permissions", plan: "Plan mode", unset: "Not set", names: ["Not set", ...MODES.map((m) => m[1])] },
|
||||
zh: { advanced: "高级", name: "权限模式", bypass: "跳过权限确认", plan: "计划模式", unset: "未设置", names: ["未设置", "默认", "自动接受编辑", "计划模式", "自动", "不询问", "跳过权限确认"] },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh"]) {
|
||||
const w = words[lang];
|
||||
test(`${engine} ${lang}: Claude Code's permission mode is set under Advanced in its settings`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await (await browser.newContext({ viewport: { width: 900, height: 760 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [], posts = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, posts));
|
||||
await watchSettingsReads(page);
|
||||
await page.goto("http://magpie.test/?view=agents");
|
||||
const agent = page.locator('.row.agent[data-id="claude"]');
|
||||
await agent.waitFor();
|
||||
await openAgentSettings(page, "claude");
|
||||
assert.equal(await agent.locator('.field[data-key="permission_mode"]').count(), 0, "not a picker on the row");
|
||||
const fold = page.locator('.row.agent[data-id="claude"] details.own-fields');
|
||||
await fold.waitFor();
|
||||
assert.equal(await fold.evaluate((d) => d.open), false, "folded");
|
||||
assert.equal((await fold.locator("summary").textContent()).trim(), w.advanced);
|
||||
await fold.locator("summary").click();
|
||||
const row = fold.locator('.own-field[data-key="permission_mode"]');
|
||||
await row.waitFor();
|
||||
assert.equal(await row.locator(".name").textContent(), w.name);
|
||||
const btn = row.locator("button.sess-pick");
|
||||
assert.equal((await btn.textContent()).trim(), w.bypass);
|
||||
await btn.click();
|
||||
const menu = page.locator(".proto-menu");
|
||||
await menu.waitFor();
|
||||
assert.deepEqual(await menu.locator(".pm-name").allTextContents(), w.names);
|
||||
await pickItem(page, menu.locator(".pm-item", { hasText: w.plan }).first());
|
||||
await page.waitForFunction((v) => document.querySelector('.own-field[data-key="permission_mode"] button')?.textContent.trim() === v, w.plan);
|
||||
assert.deepEqual(posts, [{ agent: "claude", field: "permission_mode", value: "plan" }]);
|
||||
await btn.click();
|
||||
await menu.waitFor();
|
||||
await pickItem(page, menu.locator(".pm-item").first());
|
||||
await page.waitForFunction((v) => document.querySelector('.own-field[data-key="permission_mode"] button')?.textContent.trim() === v, w.unset);
|
||||
assert.deepEqual(posts.at(-1), { agent: "claude", field: "permission_mode", value: "" });
|
||||
await page.keyboard.press("Escape");
|
||||
await page.locator('.row.agent[data-id="codex"] .ag-link').click();
|
||||
await page.locator('.row.agent[data-id="codex"] .ag-prefs').waitFor();
|
||||
assert.equal(await page.locator('.row.agent[data-id="codex"] .own-fields').count(), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -152,6 +152,10 @@ func Fields() map[string]string {
|
||||
p := map[string]string{}
|
||||
for _, a := range agent.Detected() {
|
||||
for k, v := range a.Values() {
|
||||
// the user's own setting of the agent's isn't a profile's
|
||||
if f := a.Field(k); f != nil && f.Own {
|
||||
continue
|
||||
}
|
||||
p[a.ID+"."+k] = v
|
||||
}
|
||||
}
|
||||
@@ -315,7 +319,8 @@ func ApplyFields(p map[string]string) (int, error) {
|
||||
continue
|
||||
}
|
||||
f := a.Field(field)
|
||||
if f == nil {
|
||||
// one saved before a field was the user's own isn't written over it
|
||||
if f == nil || f.Own {
|
||||
continue
|
||||
}
|
||||
v := wanted(a, f.Key, p[k])
|
||||
@@ -366,7 +371,7 @@ func InUse(p Profile, agents []*agent.Agent, now map[string]map[string]string) b
|
||||
continue
|
||||
}
|
||||
f := a.Field(k[i+1:])
|
||||
if f == nil {
|
||||
if f == nil || f.Own {
|
||||
continue
|
||||
}
|
||||
cur, ok := now[a.ID][f.Key]
|
||||
|
||||
@@ -264,3 +264,21 @@ func TestRename(t *testing.T) {
|
||||
t.Errorf("an unreadable profiles.json was written over: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A profile is magpie's routing, not the user's own settings of an agent:
|
||||
// Claude Code's permission mode is neither saved in one nor written by one
|
||||
// (EricChenChannel on X: bypassPermissions kept coming back as it was).
|
||||
func TestProfileLeavesPermissionMode(t *testing.T) {
|
||||
h := sandbox(t)
|
||||
path := filepath.Join(h, ".claude/settings.json")
|
||||
write(t, path, `{"permissions": {"defaultMode": "bypassPermissions"}}`)
|
||||
if _, ok := Fields()["claude.permission_mode"]; ok {
|
||||
t.Error("a profile keeps the permission mode")
|
||||
}
|
||||
if _, err := ApplyFields(map[string]string{"claude.permission_mode": "default"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s := read(t, path); !strings.Contains(s, "bypassPermissions") {
|
||||
t.Errorf("a profile wrote the permission mode:\n%s", s)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user