From 34cc05286c0d3d0d8f0d0b444f54925a52cba1ac Mon Sep 17 00:00:00 2001 From: zhoushoujian Date: Thu, 26 Nov 2026 14:01:34 +0800 Subject: [PATCH] feat(macos): configure caller defaults in settings Co-authored-by: multica-agent --- README.md | 6 +- docs/guide.md | 5 +- internal/cli/caller_default_test.go | 73 +++++- internal/cli/cli.go | 20 +- internal/config/caller_defaults.go | 34 +++ internal/config/native_auth_test.go | 78 ++++++ .../Sources/OffloadMonitor/CLIServices.swift | 15 ++ .../OffloadMonitor/ControlModels.swift | 16 ++ .../OffloadMonitor/ProfileModels.swift | 69 +++++ .../Sources/OffloadMonitor/SettingsView.swift | 45 +++- .../CallerDefaultTests.swift | 247 ++++++++++++++++++ 11 files changed, 596 insertions(+), 12 deletions(-) create mode 100644 macos/Tests/OffloadMonitorTests/CallerDefaultTests.swift diff --git a/README.md b/README.md index 5d346d0..037b6f9 100644 --- a/README.md +++ b/README.md @@ -54,8 +54,10 @@ offload stats # usage and estimated costs `-p` selects a profile for one task; `offload default ` changes the saved default. `OFFLOAD_PROFILE` overrides that default. `offload default --caller -` sets a profile for runs that pass `--caller `, a routing convenience and -not access control. Resumes retain their recorded profile and account. Costs are estimates when available, not billing records. +` sets a profile for runs that pass `--caller `, and `offload default +--caller --clear` removes it. This is a routing convenience, not access control. +The macOS App sets the Codex and Claude callers in Settings > Profiles > Caller defaults. +Resumes retain their recorded profile and account. Costs are estimates when available, not billing records. **Execution scope:** default-policy Codex workers bypass approvals and sandboxing. `-w` communicates write intent; it does not enforce a filesystem boundary. Give diff --git a/docs/guide.md b/docs/guide.md index 2fc974e..d9e91e7 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -102,9 +102,12 @@ An external main agent can have its own default profile, so Claude Code and Code offload default --caller claude claude-sonnet # saved as caller_defaults.claude offload default --caller codex codex offload default --caller claude # print it (the global default if none is set) +offload default --caller claude --clear # remove the mapping; the caller follows the global default again ``` -The profile may be an alias; the canonical name is saved. The caller follows the `--caller` rules (lowercase `[a-z0-9][a-z0-9._-]{0,63}`; `unspecified` is refused). There is no clearing syntax yet; point the caller at another profile, or edit `caller_defaults` in `config.json`. +The profile may be an alias; the canonical name is saved. The caller follows the `--caller` rules (lowercase `[a-z0-9][a-z0-9._-]{0,63}`; `unspecified` is refused). `--clear` removes only that caller's entry, keeps every other config field, and succeeds without changing the file when the caller has no mapping. It also clears a mapping to a profile that was deleted by hand. Like showing, clearing prints the profile the caller now uses. + +In the macOS App, **Settings > Profiles** has a **Caller defaults** section with one picker for Codex (`--caller codex`) and one for Claude (`--caller claude`). Each lists **Follow global default** (with the configured default named) and every enabled profile. Choosing one runs the commands above at once and refreshes the list; the pickers are disabled while another profile action runs. A saved mapping to a disabled or missing profile stays selected and is labelled "(disabled)" or "(not found)" instead of being replaced. The App edits only the Codex and Claude callers; use the CLI for other caller IDs. The routing rules below apply unchanged: the run must pass the caller ID, and `-p` or `OFFLOAD_PROFILE` still override the mapping. New runs choose the profile in this order: `-p`; the profile a resumed session or named thread is bound to; `OFFLOAD_PROFILE`; the default mapped to an **explicitly supplied** `--caller`; the global default. A run without `--caller`, or with a caller that has no mapping, uses the global default; `unspecified` never matches. A mapped profile that is missing or disabled fails the run instead of falling back; one that is only marked unavailable is still selected, like `-p`. Resuming (`-r`, `-thread`, `offload resume`) keeps the session's original profile after any default changes. A profile that a caller default names cannot be disabled or deleted until that caller points elsewhere. diff --git a/internal/cli/caller_default_test.go b/internal/cli/caller_default_test.go index 39fd0ae..d513f43 100644 --- a/internal/cli/caller_default_test.go +++ b/internal/cli/caller_default_test.go @@ -230,6 +230,77 @@ func TestDefaultCallerCommand(t *testing.T) { } } +func TestDefaultCallerClearCommand(t *testing.T) { + setup(t, okReply) + writeCallerDefaultsCfg(t, func(s string) string { + return strings.Replace(s, `"default":"glob"`, `"default":"glob","future":{"keep":true}`, 1) + }) + for _, args := range [][]string{{"claude", "son"}, {"codex", "cx"}} { + if code, _, e := runCLI(append([]string{"default", "--caller"}, args...)...); code != 0 { + t.Fatal(e) + } + } + code, out, e := runCLI("default", "--caller", "Claude", "--clear") + if code != 0 || strings.TrimSpace(out) != "glob" { + t.Fatalf("clear prints the global default the caller now follows: %d %q %s", code, out, e) + } + if code, out, _ := runCLI("default", "--caller", "claude"); code != 0 || strings.TrimSpace(out) != "glob" { + t.Fatalf("show after clear: %d %q", code, out) + } + if code, out, _ := runCLI("default", "--caller", "codex"); code != 0 || strings.TrimSpace(out) != "cx" { + t.Fatalf("the other caller must keep its mapping: %d %q", code, out) + } + if code, out, _ := runCLI("default"); code != 0 || strings.TrimSpace(out) != "glob" { + t.Fatalf("the global default must not change: %q", out) + } + raw, _ := os.ReadFile(config.Path()) + var f struct { + CallerDefaults map[string]string `json:"caller_defaults"` + Future json.RawMessage `json:"future"` + } + if err := json.Unmarshal(raw, &f); err != nil || len(f.CallerDefaults) != 1 || f.CallerDefaults["codex"] != "cx" || !strings.Contains(string(f.Future), "keep") { + t.Fatalf("%v %s", err, raw) + } + // Clearing twice, or an unmapped caller, is a successful no-op that leaves the file alone. + before, _ := os.ReadFile(config.Path()) + for _, caller := range []string{"claude", "never-set"} { + if code, out, e := runCLI("default", "--caller", caller, "--clear"); code != 0 || strings.TrimSpace(out) != "glob" { + t.Fatalf("clear %s: %d %q %s", caller, code, out, e) + } + } + if after, _ := os.ReadFile(config.Path()); string(after) != string(before) { + t.Fatal("a no-op clear modified the config") + } + // Invalid callers and extra arguments are refused without changing the config. + for _, args := range [][]string{{"unspecified", "--clear"}, {"bad caller", "--clear"}, {"codex", "--clear", "extra"}, {"--clear"}} { + if code, _, _ := runCLI(append([]string{"default", "--caller"}, args...)...); code != 2 { + t.Errorf("%q: code %d", args, code) + } + } + if after, _ := os.ReadFile(config.Path()); string(after) != string(before) { + t.Fatal("a rejected clear modified the config") + } + // A cleared caller routes new runs to the global default again. + work, _ := setup(t, okReply) + writeCallerDefaultsCfg(t, nil) + if code, _, e := runCLI("default", "--caller", "claude", "claude-sonnet"); code != 0 { + t.Fatal(e) + } + if code, _, e := runCLI("default", "--caller", "claude", "--clear"); code != 0 { + t.Fatal(e) + } + if code, _, e := runCLI("-d", work, "--caller", "claude", "task"); code != 0 { + t.Fatal(e) + } + if got := ranProfile(t); got != "glob" { + t.Fatalf("a cleared caller ran on %q, want the global default", got) + } + // Clearing releases the profile for disable. + if code, _, e := runCLI("profile", "disable", "claude-sonnet"); code != 0 { + t.Fatalf("disable after clear: %s", e) + } +} + func TestProfileLifecycleRefusesCallerDefaultTargets(t *testing.T) { setup(t, okReply) writeCallerDefaultsCfg(t, nil) @@ -399,7 +470,7 @@ func TestProfilesJSONCallerDefaultsAreAdditiveAndGlobalFieldsStayGlobal(t *testi func TestHelpDocumentsCallerDefaultAndRoutingOnly(t *testing.T) { _, out, e := runCLI("-h") text := out + e - for _, want := range []string{"offload default --caller ID [profile]", "not authentication or access control", "--caller default"} { + for _, want := range []string{"offload default --caller ID [profile|--clear]", "not authentication or access control", "--caller default"} { if !strings.Contains(text, want) { t.Errorf("help missing %q", want) } diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 4ad2754..e46023e 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -63,8 +63,8 @@ usage: offload profiles [--json] list profiles (* = the one a run would use) offload profile save --json create or edit a profile from a JSON request on stdin offload default [profile] show or set the saved default profile - offload default --caller ID [profile] - show or set the profile new runs with --caller ID use + offload default --caller ID [profile|--clear] + show, set or clear (--clear) the profile new runs with --caller ID use (a routing convenience, not authentication or access control) offload disable / enable [--json] persistently block / allow every new worker and model call (running tasks are not stopped) @@ -831,7 +831,7 @@ func cmdProfiles(stdout, stderr io.Writer) int { return 0 } -const defaultUsage = "usage: offload default [profile] | offload default --caller [profile]" +const defaultUsage = "usage: offload default [profile] | offload default --caller [profile|--clear]" func cmdDefault(args []string, stdout, stderr io.Writer) int { if len(args) > 0 && (args[0] == "--caller" || args[0] == "-caller") { @@ -853,9 +853,10 @@ func cmdDefault(args []string, stdout, stderr io.Writer) int { return 0 } -// cmdCallerDefault shows or sets the default profile for one explicit --caller ID. Setting stores -// the canonical profile name, resolving an alias. Showing prints the mapped profile, or the global -// default when the caller has none. +// cmdCallerDefault shows, sets or clears the default profile for one explicit --caller ID. Setting +// stores the canonical profile name, resolving an alias. Clearing (--clear) removes the mapping so +// the caller follows the global default. Showing, and the output after setting or clearing, is the +// mapped profile, or the global default when the caller has none. func cmdCallerDefault(args []string, stdout, stderr io.Writer) int { if len(args) < 1 || len(args) > 2 { return fail(stderr, errors.New(defaultUsage)) @@ -865,7 +866,12 @@ func cmdCallerDefault(args []string, stdout, stderr io.Writer) int { return fail(stderr, err) } if len(args) == 2 { - if err := config.SetCallerDefault(config.Path(), caller, args[1]); err != nil { + if args[1] == "--clear" || args[1] == "-clear" { + err = config.ClearCallerDefault(config.Path(), caller) + } else { + err = config.SetCallerDefault(config.Path(), caller, args[1]) + } + if err != nil { return fail(stderr, err) } } diff --git a/internal/config/caller_defaults.go b/internal/config/caller_defaults.go index 7bb0a59..2a9a44e 100644 --- a/internal/config/caller_defaults.go +++ b/internal/config/caller_defaults.go @@ -111,6 +111,40 @@ func SetCallerDefault(path, caller, name string) error { return writeSettings(path, fields) } +// ClearCallerDefault removes the saved default profile for one caller, so its runs follow the +// global default again. Clearing a caller that has no mapping succeeds without touching the file. +// The mapped profile need not exist, so a mapping to a hand-deleted profile can be cleared. Other +// fields, including unknown JSON, are preserved; the caller_defaults key is dropped when it +// becomes empty. +func ClearCallerDefault(path, caller string) error { + key, err := NormalizeCallerDefaultKey(caller) + if err != nil { + return err + } + fields, err := modeSettings(path) + if err != nil { + return err + } + raw, ok := fields["caller_defaults"] + if !ok { + return nil + } + var defaults map[string]string + if err := json.Unmarshal(raw, &defaults); err != nil || defaults == nil { + return errors.New("caller_defaults must be a JSON object of profile names") + } + if _, mapped := defaults[key]; !mapped { + return nil + } + delete(defaults, key) + if len(defaults) == 0 { + delete(fields, "caller_defaults") + } else if fields["caller_defaults"], err = json.Marshal(defaults); err != nil { + return err + } + return writeSettings(path, fields) +} + // callerDefaultsUse reports whether any stored caller default names the profile, by canonical name // or alias. func callerDefaultsUse(fields map[string]json.RawMessage, profile string) (bool, error) { diff --git a/internal/config/native_auth_test.go b/internal/config/native_auth_test.go index 409d521..667e97f 100644 --- a/internal/config/native_auth_test.go +++ b/internal/config/native_auth_test.go @@ -199,6 +199,84 @@ func TestSetCallerDefaultRejectsBadInputAndLeavesConfigUntouched(t *testing.T) { } } +func TestClearCallerDefaultRemovesOneMappingAndPreservesFields(t *testing.T) { + path := writeCallerCfg(t, callerCfg) + for caller, profile := range map[string]string{"claude": "sonnet", "codex": "cx"} { + if err := SetCallerDefault(path, caller, profile); err != nil { + t.Fatal(err) + } + } + if err := ClearCallerDefault(path, "Claude"); err != nil { + t.Fatal(err) + } + c, err := Load(path) + if err != nil { + t.Fatal(err) + } + if _, ok := c.CallerDefaults["claude"]; ok || c.CallerDefaults["codex"] != "cx" || len(c.CallerDefaults) != 1 { + t.Fatalf("only the claude mapping may go: %v", c.CallerDefaults) + } + if name, mapped := c.DefaultFor("claude"); name != "gw" || mapped { + t.Fatalf("a cleared caller must follow the global default: %q %v", name, mapped) + } + if b, _ := os.ReadFile(path); !strings.Contains(string(b), `"keep": true`) || c.Default != "gw" { + t.Fatalf("unknown fields or the global default changed:\n%s", b) + } + // Clearing the last mapping drops the key; the profile is released for disable and delete. + if err := ClearCallerDefault(path, "codex"); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(path); strings.Contains(string(b), "caller_defaults") || !strings.Contains(string(b), `"keep": true`) { + t.Fatalf("an empty caller_defaults must be removed:\n%s", b) + } + if err := SetProfileDisabled(path, "cx", true); err != nil { + t.Fatalf("a cleared caller default must not block disable: %v", err) + } +} + +func TestClearCallerDefaultIsIdempotentAndValidatesInput(t *testing.T) { + path := writeCallerCfg(t, callerCfg) + before, _ := os.ReadFile(path) + if err := ClearCallerDefault(path, "claude"); err != nil { + t.Fatalf("clearing a caller with no caller_defaults key must succeed: %v", err) + } + if after, _ := os.ReadFile(path); string(after) != string(before) { + t.Fatal("a no-op clear rewrote the config") + } + if err := SetCallerDefault(path, "codex", "cx"); err != nil { + t.Fatal(err) + } + mapped, _ := os.ReadFile(path) + if err := ClearCallerDefault(path, "claude"); err != nil { + t.Fatal(err) + } + if after, _ := os.ReadFile(path); string(after) != string(mapped) { + t.Fatal("clearing an unmapped caller rewrote the config") + } + for _, caller := range []string{"", "has space", "unspecified"} { + if err := ClearCallerDefault(path, caller); err == nil { + t.Errorf("ClearCallerDefault(%q) succeeded", caller) + } + } + bad := strings.Replace(callerCfg, `"future"`, `"caller_defaults":["x"],"future"`, 1) + badPath := writeCallerCfg(t, bad) + if err := ClearCallerDefault(badPath, "claude"); err == nil || !strings.Contains(err.Error(), "JSON object") { + t.Fatalf("a malformed caller_defaults must be refused: %v", err) + } +} + +func TestClearCallerDefaultWorksForMissingOrDisabledTargets(t *testing.T) { + gone := strings.Replace(callerCfg, `"future"`, `"caller_defaults":{"claude":"gone","codex":"cx"},"future"`, 1) + path := writeCallerCfg(t, gone) + if err := ClearCallerDefault(path, "claude"); err != nil { + t.Fatalf("a mapping to a missing profile must be clearable: %v", err) + } + c, err := Load(path) + if err != nil || len(c.CallerDefaults) != 1 || c.CallerDefaults["codex"] != "cx" { + t.Fatalf("%v %v", err, c.CallerDefaults) + } +} + func TestDefaultForOnlyMapsAnExplicitCaller(t *testing.T) { path := writeCallerCfg(t, callerCfg) if err := SetCallerDefault(path, "claude", "sonnet"); err != nil { diff --git a/macos/Sources/OffloadMonitor/CLIServices.swift b/macos/Sources/OffloadMonitor/CLIServices.swift index 2b81126..667d2e1 100644 --- a/macos/Sources/OffloadMonitor/CLIServices.swift +++ b/macos/Sources/OffloadMonitor/CLIServices.swift @@ -91,6 +91,21 @@ struct OffloadCLI { _ = try await run(["default", name]) } + /// Arguments for `offload default --caller ` (set) or `... --clear` (follow the global default). + static func callerDefaultArguments(_ caller: CallerDefaultCaller, profile: String?) -> [String]? { + guard let profile else { return ["default", "--caller", caller.rawValue, "--clear"] } + guard validArgumentName(profile) else { return nil } + return ["default", "--caller", caller.rawValue, profile] + } + + /// Sets (or, with a nil profile, clears) the default profile of one caller. The global default is untouched. + func setCallerDefault(_ caller: CallerDefaultCaller, profile: String?) async throws { + guard let args = Self.callerDefaultArguments(caller, profile: profile) else { + throw CLIError.invalidArgument("That profile name cannot be selected from here.") + } + _ = try await run(args) + } + struct ProfileTestResult { var snapshot: ProfilesSnapshot var succeeded: Bool diff --git a/macos/Sources/OffloadMonitor/ControlModels.swift b/macos/Sources/OffloadMonitor/ControlModels.swift index 4c84e58..03f18dd 100644 --- a/macos/Sources/OffloadMonitor/ControlModels.swift +++ b/macos/Sources/OffloadMonitor/ControlModels.swift @@ -183,6 +183,22 @@ final class ProfilesModel: ObservableObject { return true } + /// Sets (nil profile: clears) the default profile of one caller, then re-reads. Serialized with every other + /// action through `busy`. A failed command changes nothing, shows its message and re-reads nothing. + @discardableResult + func setCallerDefault(_ caller: CallerDefaultCaller, profile: String?) async -> Bool { + guard let cli, !busy else { return false } + busy = true + defer { busy = false } + actionError = nil + do { try await cli.setCallerDefault(caller, profile: profile) } catch { + actionError = message(error) + return false + } + if !(await fetch(cli)) { actionError = "Saved, but the profile list could not be refreshed." } + return true + } + /// Creates or patches a profile. The reply is the refreshed redacted list. @discardableResult func save(_ request: ProfileSaveRequest) async -> Bool { diff --git a/macos/Sources/OffloadMonitor/ProfileModels.swift b/macos/Sources/OffloadMonitor/ProfileModels.swift index e6df4c8..455dec5 100644 --- a/macos/Sources/OffloadMonitor/ProfileModels.swift +++ b/macos/Sources/OffloadMonitor/ProfileModels.swift @@ -46,9 +46,30 @@ struct ProfilesSnapshot: Codable, Equatable { var active: String var activeSource: String var delegationMode: String + /// Saved default profile per `--caller` ID (`caller_defaults`). Empty when none, or when an older CLI omits it. + var callerDefaults: [String: String] = [:] var profiles: [ProfileEntry] var warnings: [String] + private enum CodingKeys: String, CodingKey { + case managedAccounts, schemaVersion, configExists, configuredDefault, active, activeSource, delegationMode + case callerDefaults, profiles, warnings + } + + init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + managedAccounts = try c.decodeIfPresent([String].self, forKey: .managedAccounts) + schemaVersion = try c.decode(Int.self, forKey: .schemaVersion) + configExists = try c.decode(Bool.self, forKey: .configExists) + configuredDefault = try c.decode(String.self, forKey: .configuredDefault) + active = try c.decode(String.self, forKey: .active) + activeSource = try c.decode(String.self, forKey: .activeSource) + delegationMode = try c.decode(String.self, forKey: .delegationMode) + callerDefaults = try c.decodeIfPresent([String: String].self, forKey: .callerDefaults) ?? [:] + profiles = try c.decode([ProfileEntry].self, forKey: .profiles) + warnings = try c.decode([String].self, forKey: .warnings) + } + static func decode(_ data: Data) throws -> ProfilesSnapshot { let d = JSONDecoder() d.keyDecodingStrategy = .convertFromSnakeCase @@ -75,6 +96,54 @@ struct ProfilesSnapshot: Codable, Equatable { var overriddenByEnvironment: Bool { activeSource == "environment" } } +// MARK: - Caller defaults + +/// The main agents whose default profile the App can set. The caller ID is the `--caller` value the agent +/// passes on every call. +enum CallerDefaultCaller: String, CaseIterable, Identifiable { + case codex, claude + var id: String { rawValue } + var label: String { self == .codex ? "Codex" : "Claude" } +} + +/// One row of a caller-default picker. An empty `value` means "follow the global default". +struct CallerDefaultOption: Equatable, Identifiable { + var value: String + var title: String + var id: String { value } +} + +extension ProfilesSnapshot { + /// The profile saved for the caller, or "" when it follows the global default. + func callerDefault(for caller: CallerDefaultCaller) -> String { callerDefaults[caller.rawValue] ?? "" } + + func followGlobalTitle() -> String { + configuredDefault.isEmpty ? "Follow global default (none set)" : "Follow global default (\(configuredDefault))" + } + + /// Follow-global first, then every enabled profile. A saved mapping to a disabled or missing profile stays + /// listed and labelled, so the picker never silently shows or saves something else. + func callerDefaultOptions(for caller: CallerDefaultCaller) -> [CallerDefaultOption] { + var options = [CallerDefaultOption(value: "", title: followGlobalTitle())] + options += profiles.filter { !$0.isDisabled }.map { CallerDefaultOption(value: $0.name, title: ProfilePresentation.pickerTitle($0)) } + let current = callerDefault(for: caller) + if !current.isEmpty, !options.contains(where: { $0.value == current }) { + let title = entry(current).map(ProfilePresentation.pickerTitle) ?? "\(current) (not found)" + options.append(CallerDefaultOption(value: current, title: title)) + } + return options + } +} + +enum CallerDefaultPresentation { + static let explanation = "Needs --caller codex or --caller claude on the run. -p and OFFLOAD_PROFILE still override it." + + static func notice(_ caller: CallerDefaultCaller, profile: String?) -> String { + guard let profile else { return "\(caller.label) callers now follow the global default." } + return "\(caller.label) callers now use \"\(profile)\"." + } +} + // MARK: - `offload profile save --json` request /// Pointer-style patch: nil fields are left out of the JSON so the backend keeps the stored value. diff --git a/macos/Sources/OffloadMonitor/SettingsView.swift b/macos/Sources/OffloadMonitor/SettingsView.swift index 531c376..ee2138f 100644 --- a/macos/Sources/OffloadMonitor/SettingsView.swift +++ b/macos/Sources/OffloadMonitor/SettingsView.swift @@ -13,7 +13,7 @@ final class SettingsNavigator: ObservableObject { enum SettingsLayout { static let width: CGFloat = 580 - static let height: CGFloat = 560 + static let height: CGFloat = 640 } /// The native Settings window. Fixed size; every tab is laid out to fit without scrolling. @@ -202,6 +202,7 @@ struct ProfilesSettingsView: View { .lineLimit(3).fixedSize(horizontal: false, vertical: true) Text("Choosing a profile affects new runs only. Workers that are already running keep the profile they started with.") .font(.system(size: 10)).foregroundStyle(.secondary).lineLimit(2).fixedSize(horizontal: false, vertical: true) + callerDefaults(s) } picker availability @@ -240,6 +241,48 @@ struct ProfilesSettingsView: View { // MARK: pieces + /// Per-caller default profiles (`offload default --caller `). Each pick runs the CLI at once; the list + /// is refreshed from the CLI afterwards, so a failed change leaves the previous choice on screen. + private func callerDefaults(_ s: ProfilesSnapshot) -> some View { + VStack(alignment: .leading, spacing: 3) { + Text("Caller defaults").font(.system(size: 11, weight: .semibold)) + HStack(spacing: 12) { + ForEach(CallerDefaultCaller.allCases) { caller in + HStack(spacing: 6) { + Text(caller.label).foregroundStyle(.secondary) + Picker("\(caller.label) default profile", selection: Binding( + get: { s.callerDefault(for: caller) }, + set: { setCallerDefault(caller, to: $0, current: s.callerDefault(for: caller)) })) { + ForEach(s.callerDefaultOptions(for: caller)) { option in + Text(option.title).lineLimit(1).truncationMode(.middle).tag(option.value) + } + } + .labelsHidden() + .frame(maxWidth: .infinity) + .disabled(profiles.busy) + .help("Profile for new runs that pass --caller \(caller.rawValue)") + .accessibilityLabel("\(caller.label) default profile") + } + .frame(maxWidth: .infinity) + } + } + Text(CallerDefaultPresentation.explanation) + .font(.system(size: 10)).foregroundStyle(.secondary).lineLimit(1).truncationMode(.tail) + } + } + + private func setCallerDefault(_ caller: CallerDefaultCaller, to value: String, current: String) { + guard value != current, !profiles.busy else { return } + formError = nil + notice = nil + let profile = value.isEmpty ? nil : value + Task { + if await profiles.setCallerDefault(caller, profile: profile) { + notice = CallerDefaultPresentation.notice(caller, profile: profile) + } + } + } + private var picker: some View { HStack(spacing: 8) { Picker("Profile", selection: Binding(get: { draft.isNew ? "" : selection }, set: { choose($0) })) { diff --git a/macos/Tests/OffloadMonitorTests/CallerDefaultTests.swift b/macos/Tests/OffloadMonitorTests/CallerDefaultTests.swift new file mode 100644 index 0000000..234e46d --- /dev/null +++ b/macos/Tests/OffloadMonitorTests/CallerDefaultTests.swift @@ -0,0 +1,247 @@ +import XCTest +import AppKit +import SwiftUI +@testable import OffloadMonitor + +private enum CallerFixtures { + static func disabled(_ profile: String) -> String { + profile.replacingOccurrences(of: #""auth_mode":"token"}"#, with: #""auth_mode":"token","disabled":true}"#) + } + + static func unavailable(_ profile: String) -> String { + profile.replacingOccurrences(of: #""auth_mode":"token"}"#, with: #""auth_mode":"token","available":false,"unavailable_reason":"quota"}"#) + } + + /// A snapshot with caller defaults. `callers` is inserted as the `caller_defaults` object. + static func json(_ entries: [String], callers: String?, configured: String = "work", active: String = "work", source: String = "config") -> String { + let base = Fixtures.profiles(entries, active: active, source: source, configured: configured) + guard let callers else { return base } + return base.replacingOccurrences(of: #""delegation_mode":"proactive","#, with: #""delegation_mode":"proactive","caller_defaults":\#(callers),"#) + } + + static func snapshot(_ entries: [String], callers: String?, configured: String = "work") throws -> ProfilesSnapshot { + try ProfilesSnapshot.decode(Data(json(entries, callers: callers, configured: configured).utf8)) + } +} + +final class CallerDefaultDecodeTests: XCTestCase { + func testMissingCallerDefaultsDecodesAsEmpty() throws { + let s = try CallerFixtures.snapshot([Fixtures.profile(name: "work")], callers: nil) + XCTAssertEqual(s.callerDefaults, [:]) + XCTAssertEqual(s.callerDefault(for: .codex), "") + XCTAssertEqual(s.callerDefault(for: .claude), "") + } + + func testEmptyAndPopulatedCallerDefaultsDecode() throws { + XCTAssertEqual(try CallerFixtures.snapshot([Fixtures.profile(name: "work")], callers: "{}").callerDefaults, [:]) + let s = try CallerFixtures.snapshot([Fixtures.profile(name: "work"), Fixtures.profile(name: "cx", backend: "codex", auth: "none")], + callers: #"{"codex":"cx","claude":"work","agh":"work"}"#) + XCTAssertEqual(s.callerDefault(for: .codex), "cx") + XCTAssertEqual(s.callerDefault(for: .claude), "work") + XCTAssertEqual(s.callerDefaults["agh"], "work", "callers the App has no control for are still decoded") + XCTAssertEqual(s.configuredDefault, "work", "caller defaults never change the global fields") + } + + func testSnapshotRoundTripKeepsCallerDefaults() throws { + let s = try CallerFixtures.snapshot([Fixtures.profile(name: "work")], callers: #"{"codex":"work"}"#) + let again = try JSONDecoder().decode(ProfilesSnapshot.self, from: JSONEncoder().encode(s)) + XCTAssertEqual(again, s) + } +} + +final class CallerDefaultOptionTests: XCTestCase { + func testFollowGlobalIsFirstAndNamesTheConfiguredDefault() throws { + let s = try CallerFixtures.snapshot([Fixtures.profile(name: "work"), Fixtures.profile(name: "alt")], callers: nil) + let options = s.callerDefaultOptions(for: .codex) + XCTAssertEqual(options.map(\.value), ["", "work", "alt"], "Follow global default first, then profiles in snapshot order") + XCTAssertEqual(options.first?.title, "Follow global default (work)") + XCTAssertEqual(try CallerFixtures.snapshot([Fixtures.profile(name: "work")], callers: nil, configured: "").followGlobalTitle(), + "Follow global default (none set)") + } + + func testOnlyEnabledProfilesAreOffered() throws { + let s = try CallerFixtures.snapshot([Fixtures.profile(name: "work"), CallerFixtures.disabled(Fixtures.profile(name: "off")), + CallerFixtures.unavailable(Fixtures.profile(name: "slow"))], callers: nil) + let values = s.callerDefaultOptions(for: .claude).map(\.value) + XCTAssertEqual(values, ["", "work", "slow"]) + XCTAssertEqual(s.callerDefaultOptions(for: .claude).last?.title, "slow — m1 (unavailable)") + } + + func testDisabledOrMissingCurrentMappingStaysVisibleAndLabelled() throws { + let entries = [Fixtures.profile(name: "work"), CallerFixtures.disabled(Fixtures.profile(name: "off"))] + let s = try CallerFixtures.snapshot(entries, callers: #"{"codex":"off","claude":"gone"}"#) + let codex = s.callerDefaultOptions(for: .codex) + XCTAssertEqual(codex.map(\.value), ["", "work", "off"]) + XCTAssertEqual(codex.last?.title, "off — m1 (disabled)") + XCTAssertEqual(s.callerDefault(for: .codex), "off", "the saved mapping is shown, not replaced by the global default") + let claude = s.callerDefaultOptions(for: .claude) + XCTAssertEqual(claude.map(\.value), ["", "work", "gone"]) + XCTAssertEqual(claude.last?.title, "gone (not found)") + XCTAssertTrue(claude.contains { $0.value == s.callerDefault(for: .claude) }, "the selection always has a matching row") + } + + func testPickersAreIndependentPerCaller() throws { + let s = try CallerFixtures.snapshot([Fixtures.profile(name: "work"), Fixtures.profile(name: "alt")], callers: #"{"codex":"alt"}"#) + XCTAssertEqual(s.callerDefault(for: .codex), "alt") + XCTAssertEqual(s.callerDefault(for: .claude), "") + } + + func testExplanationNamesTheRequirementAndOverrides() { + let t = CallerDefaultPresentation.explanation + XCTAssertTrue(t.contains("--caller")) + XCTAssertTrue(t.contains("-p")) + XCTAssertTrue(t.contains("OFFLOAD_PROFILE")) + XCTAssertEqual(CallerDefaultPresentation.notice(.codex, profile: nil), "Codex callers now follow the global default.") + XCTAssertEqual(CallerDefaultPresentation.notice(.claude, profile: "x"), "Claude callers now use \"x\".") + } +} + +final class CallerDefaultCommandTests: XCTestCase { + func testArgumentsSetAndClear() { + XCTAssertEqual(OffloadCLI.callerDefaultArguments(.codex, profile: "cx"), ["default", "--caller", "codex", "cx"]) + XCTAssertEqual(OffloadCLI.callerDefaultArguments(.claude, profile: "claude-sonnet"), ["default", "--caller", "claude", "claude-sonnet"]) + XCTAssertEqual(OffloadCLI.callerDefaultArguments(.claude, profile: nil), ["default", "--caller", "claude", "--clear"]) + } + + func testOptionLikeAndInvalidNamesNeverReachTheCommandLine() { + for bad in ["--clear", "-x", "", "a\nb"] { + XCTAssertNil(OffloadCLI.callerDefaultArguments(.codex, profile: bad), bad) + } + } + + func testCLISetAndClearRunTheDocumentedCommands() async throws { + let fake = try FakeCLI() + try await fake.cli.setCallerDefault(.codex, profile: "cx") + try await fake.cli.setCallerDefault(.claude, profile: nil) + XCTAssertEqual(fake.argv, ["default --caller codex cx", "default --caller claude --clear"]) + } + + func testCLIRejectsInvalidNameWithoutRunning() async throws { + let fake = try FakeCLI() + do { + try await fake.cli.setCallerDefault(.codex, profile: "--agent") + XCTFail("expected an invalid argument error") + } catch let e as CLIError { + guard case .invalidArgument = e else { return XCTFail("\(e)") } + } + XCTAssertTrue(fake.argv.isEmpty) + } +} + +@MainActor +final class CallerDefaultModelTests: XCTestCase { + private func fake(_ callers: String? = nil, failDefault: Bool = false) throws -> FakeCLI { + try FakeCLI(profilesJSON: CallerFixtures.json([Fixtures.profile(name: "work"), Fixtures.profile(name: "cx", backend: "codex", auth: "none")], callers: callers), + failDefault: failDefault) + } + + func testSetRefreshesSnapshotAfterTheCommand() async throws { + let f = try fake(#"{"codex":"cx"}"#) + let m = ProfilesModel(cli: f.cli, autoLoad: false) + let ok = await m.setCallerDefault(.codex, profile: "cx") + XCTAssertTrue(ok) + XCTAssertEqual(f.argv, ["default --caller codex cx", "profiles --json"]) + XCTAssertEqual(m.snapshot?.callerDefault(for: .codex), "cx") + XCTAssertNil(m.actionError) + XCTAssertFalse(m.busy) + } + + func testClearRunsClearThenRefreshes() async throws { + let f = try fake() + let m = ProfilesModel(cli: f.cli, autoLoad: false) + let ok = await m.setCallerDefault(.claude, profile: nil) + XCTAssertTrue(ok) + XCTAssertEqual(f.argv, ["default --caller claude --clear", "profiles --json"]) + XCTAssertEqual(m.snapshot?.callerDefault(for: .claude), "") + } + + func testFailureShowsErrorKeepsSnapshotAndDoesNotRefresh() async throws { + let f = try fake(#"{"claude":"work"}"#, failDefault: true) + let m = ProfilesModel(cli: f.cli, autoLoad: false) + let loaded = await m.reload() + XCTAssertTrue(loaded) + let before = m.snapshot + let ok = await m.setCallerDefault(.claude, profile: "cx") + XCTAssertFalse(ok) + XCTAssertEqual(m.actionError, "unknown profile") + XCTAssertEqual(m.snapshot, before, "a failed change leaves the previous choice on screen") + XCTAssertEqual(f.argv, ["profiles --json", "default --caller claude cx"], "no refetch after a failed command") + XCTAssertFalse(m.busy) + } + + func testOptionLikeNameIsRefusedWithAMessage() async throws { + let f = try fake() + let m = ProfilesModel(cli: f.cli, autoLoad: false) + let ok = await m.setCallerDefault(.codex, profile: "--clear") + XCTAssertFalse(ok) + XCTAssertTrue(f.argv.isEmpty) + XCTAssertNotNil(m.actionError) + } + + func testActionsAreSerialized() async throws { + let f = try fake(#"{"codex":"cx"}"#) + var script = try String(contentsOf: f.exe) + script = script.replacingOccurrences(of: "echo \"$*\" >> \"$D/argv.log\"", with: "echo \"$*\" >> \"$D/argv.log\"\ncase \"$1\" in default) sleep 0.4 ;; esac") + try script.write(to: f.exe, atomically: false, encoding: .utf8) + let m = ProfilesModel(cli: f.cli, autoLoad: false) + async let first = m.setCallerDefault(.codex, profile: "cx") + try await Task.sleep(nanoseconds: 150_000_000) + XCTAssertTrue(m.busy, "the model is busy while the command runs, which disables the pickers") + let second = await m.setCallerDefault(.claude, profile: "work") + XCTAssertFalse(second, "a second change is refused while one runs") + let firstOK = await first + XCTAssertTrue(firstOK) + XCTAssertEqual(f.argv, ["default --caller codex cx", "profiles --json"], "the refused change never ran") + } + + func testUnavailableCLIDoesNothing() async { + let m = ProfilesModel(testingSnapshot: nil) + let ok = await m.setCallerDefault(.codex, profile: "x") + XCTAssertFalse(ok) + } + + func testCallerDefaultChangeLeavesGlobalDefaultFieldsAlone() async throws { + let f = try fake() + let m = ProfilesModel(cli: f.cli, autoLoad: false) + _ = await m.setCallerDefault(.codex, profile: "cx") + XCTAssertFalse(f.argv.contains { $0 == "default cx" || $0.hasPrefix("default cx") }, "the global default command is never used") + XCTAssertEqual(m.snapshot?.configuredDefault, "work") + } +} + +@MainActor +final class CallerDefaultLayoutTests: XCTestCase { + func testSectionFitsSettingsWindowOffscreen() throws { + let long = String(repeating: "very-long-profile-name-", count: 5) + let entries = [Fixtures.profile(name: "work"), Fixtures.profile(name: "cx", backend: "codex", auth: "none"), + CallerFixtures.disabled(Fixtures.profile(name: "off")), Fixtures.profile(name: long, model: String(repeating: "model-", count: 12))] + let snapshot = try CallerFixtures.snapshot(entries, callers: #"{"codex":"off","claude":"\#(long)"}"#) + let model = ProfilesModel(testingSnapshot: snapshot) + // The tallest forms: a gateway Claude profile and a Codex profile (account and Fast rows). + let drafts = [("claude", ProfileDraft(editing: snapshot.profiles[0])), ("codex", ProfileDraft(editing: snapshot.profiles[1]))] + for (kind, draft) in drafts { + for scheme in [ColorScheme.light, .dark] { + let size = NSSize(width: SettingsLayout.width, height: SettingsLayout.height - 56) + let host = NSHostingView(rootView: ProfilesSettingsView(profiles: model, initialDraft: draft) + .font(.system(size: 12)).environment(\.colorScheme, scheme) + .background(Color(nsColor: .windowBackgroundColor)) + .frame(width: size.width, height: size.height)) + host.appearance = NSAppearance(named: scheme == .light ? .aqua : .darkAqua) + host.frame = NSRect(origin: .zero, size: size) + host.layoutSubtreeIfNeeded() + XCTAssertLessThanOrEqual(host.fittingSize.width, SettingsLayout.width + 1) + XCTAssertLessThanOrEqual(host.fittingSize.height, size.height + 1) + host.displayIfNeeded() + let bitmap = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds)) + host.cacheDisplay(in: host.bounds, to: bitmap) + let data = try XCTUnwrap(bitmap.representation(using: .png, properties: [:])) + XCTAssertGreaterThan(data.count, 1000) + if let directory = ProcessInfo.processInfo.environment["OFFLOAD_SETTINGS_RENDER_DIR"] { + let output = URL(fileURLWithPath: directory) + try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true) + try data.write(to: output.appendingPathComponent("caller-defaults-\(kind)-\(scheme == .light ? "light" : "dark").png")) + } + } + } + } +}