From a654af3d66ce674aa146bf912652ffb7fc2c9bbc Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Wed, 30 Sep 2026 06:32:03 -0400 Subject: [PATCH] fix(cli): preserve error identities and causes --- cli/internal/config/capabilities.go | 8 ++-- cli/internal/config/config.go | 37 +++++++++-------- cli/internal/config/errors_test.go | 43 +++++++++++++++++++ cli/internal/config/mcp.go | 34 +++++++++------ cli/internal/daemon/client.go | 22 +--------- cli/internal/daemon/commands.go | 4 +- cli/internal/daemon/errors.go | 57 ++++++++++++++++++++++++++ cli/internal/daemon/errors_test.go | 54 ++++++++++++++++++++++++ cli/internal/daemon/lifecycle.go | 31 +++++++------- cli/internal/tui/app.go | 5 ++- cli/internal/tui/error_routing_test.go | 26 ++++++++++++ cli/internal/tui/mcp_form.go | 17 ++++---- robot-docs/commands.md | 2 + 13 files changed, 257 insertions(+), 83 deletions(-) create mode 100644 cli/internal/config/errors_test.go create mode 100644 cli/internal/daemon/errors.go create mode 100644 cli/internal/daemon/errors_test.go create mode 100644 cli/internal/tui/error_routing_test.go diff --git a/cli/internal/config/capabilities.go b/cli/internal/config/capabilities.go index 5d32bee39..1f481588a 100644 --- a/cli/internal/config/capabilities.go +++ b/cli/internal/config/capabilities.go @@ -25,10 +25,10 @@ func ReadCapabilityPrefs(home string) (CapabilityPrefs, error) { return prefs, err } if len(data) > 1<<20 { - return prefs, errors.New("capabilities.json exceeds 1 MiB") + return prefs, errors.New("capabilities.json is larger than 1 MiB. Reduce its size and try again.") } if err = json.Unmarshal(data, &prefs); err != nil { - return CapabilityPrefs{}, errors.New("invalid capabilities.json") + return CapabilityPrefs{}, fmt.Errorf("invalid capabilities.json: %w", err) } return prefs, nil } @@ -49,7 +49,7 @@ func (p CapabilityPrefs) Enabled(session, kind, name string) bool { // Session changes affect only one session; global changes become the default. func SetCapability(home, session, kind, name string, global, enabled bool) error { if session == "" || name == "" || (kind != "skills" && kind != "instructions" && kind != "mcp") { - return errors.New("invalid capability selection") + return errors.New("Choose a session, capability type, and name.") } return lockedUpdate(home, "capabilities.lock", 50, func() error { p, err := ReadCapabilityPrefs(home) @@ -77,7 +77,7 @@ func SetCapability(home, session, kind, name string, global, enabled bool) error p.Sessions[session][kind][name] = enabled } if err = writeJSONAtomic(home, "capabilities.json", p); err != nil { - return fmt.Errorf("save capability: %w", err) + return fmt.Errorf("Could not save the capability setting: %w", err) } return nil }) diff --git a/cli/internal/config/config.go b/cli/internal/config/config.go index b60a14385..45f94642c 100644 --- a/cli/internal/config/config.go +++ b/cli/internal/config/config.go @@ -3,6 +3,7 @@ package config import ( "encoding/json" "errors" + "fmt" "net/url" "os" "path/filepath" @@ -46,11 +47,11 @@ type Settings struct { func validateModel(value string) (string, error) { trimmed := strings.TrimSpace(value) if trimmed == "" || len(trimmed) > 512 { - return "", errors.New("provider needs a model id of 1–512 characters") + return "", errors.New("Model ID must be 1–512 characters and contain no control characters.") } for _, r := range trimmed { if r < 0x20 || r == 0x7f { - return "", errors.New("provider needs a model id of 1–512 characters") + return "", errors.New("Model ID must be 1–512 characters and contain no control characters.") } } return trimmed, nil @@ -59,7 +60,7 @@ func validateModel(value string) (string, error) { // Validate checks whether the Settings instance is valid. func (s Settings) Validate() (Settings, error) { if s.Protocol != "responses" && s.Protocol != "chat_completions" { - return s, errors.New("provider protocol must be responses or chat_completions") + return s, errors.New("Protocol must be responses or chat_completions.") } model, err := validateModel(s.Model) @@ -81,11 +82,11 @@ func (s Settings) Validate() (Settings, error) { } if ext == "openai" && endpoint == "" { - return s, errors.New("openai provider needs an endpoint, model and valid protocol") + return s, errors.New("OpenAI provider needs an API base URL.") } if strings.ContainsFunc(s.APIKey, func(r rune) bool { return unicode.IsSpace(r) || r < 0x20 || r == 0x7f }) { - return s, errors.New("api key must not contain spaces or control characters") + return s, errors.New("API key must not contain spaces or control characters.") } return Settings{ @@ -102,7 +103,7 @@ func (s Settings) Validate() (Settings, error) { func ValidateProviderName(value string) (string, error) { name := strings.TrimSpace(value) if !providerNameRegex.MatchString(name) { - return "", errors.New("name must be 1–64 letters, numbers, dots, underscores or hyphens") + return "", errors.New("Provider name must start with a letter or number and use only letters, numbers, dots, underscores, or hyphens (1–64 characters).") } return name, nil } @@ -111,13 +112,13 @@ func ValidateProviderName(value string) (string, error) { func ValidateEndpoint(value string) (string, error) { u, err := url.Parse(strings.TrimSpace(value)) if err != nil || u.Scheme == "" || u.Host == "" { - return "", errors.New("enter an http or https api base url") + return "", errors.New("Enter an HTTP or HTTPS API base URL.") } if u.Scheme != "http" && u.Scheme != "https" { - return "", errors.New("enter an http or https api base url") + return "", errors.New("Enter an HTTP or HTTPS API base URL.") } if u.User != nil || u.RawQuery != "" || u.Fragment != "" { - return "", errors.New("use an http or https base url without credentials, query or fragment") + return "", errors.New("Use an HTTP or HTTPS API base URL without credentials, a query, or a fragment.") } res := u.String() for strings.HasSuffix(res, "/") { @@ -153,7 +154,7 @@ func LoadProfiles(directory string) (Profiles, error) { return Profiles{}, err } if fi.Size() > 2*1024*1024 { - return Profiles{}, errors.New("invalid provider configuration in config.json; repair it before logging in") + return Profiles{}, fmt.Errorf("provider configuration in %s exceeds 2 MiB", configPath) } data, err := os.ReadFile(configPath) if err != nil { @@ -165,17 +166,17 @@ func LoadProfiles(directory string) (Profiles, error) { var rawMap map[string]json.RawMessage if err := json.Unmarshal(data, &rawMap); err != nil { - return Profiles{}, errors.New("invalid provider configuration in config.json; repair it before logging in") + return Profiles{}, fmt.Errorf("invalid provider configuration in %s: %w", configPath, err) } if _, hasProviders := rawMap["providers"]; !hasProviders { var single Settings if err := json.Unmarshal(data, &single); err != nil { - return Profiles{}, errors.New("invalid provider configuration in config.json; repair it before logging in") + return Profiles{}, fmt.Errorf("invalid provider configuration in %s: %w", configPath, err) } validated, err := single.Validate() if err != nil { - return Profiles{}, errors.New("invalid provider configuration in config.json; repair it before logging in") + return Profiles{}, fmt.Errorf("invalid provider configuration in %s: %w", configPath, err) } return Profiles{ Active: "default", @@ -185,18 +186,18 @@ func LoadProfiles(directory string) (Profiles, error) { var cfg rawConfigFile if err := json.Unmarshal(data, &cfg); err != nil { - return Profiles{}, errors.New("invalid provider configuration in config.json; repair it before logging in") + return Profiles{}, fmt.Errorf("invalid provider configuration in %s: %w", configPath, err) } providers := make(map[string]Settings) for k, v := range cfg.Providers { name, err := ValidateProviderName(k) if err != nil { - return Profiles{}, errors.New("invalid provider configuration in config.json; repair it before logging in") + return Profiles{}, fmt.Errorf("invalid provider name %q in %s: %w", k, configPath, err) } validated, err := v.Validate() if err != nil { - return Profiles{}, errors.New("invalid provider configuration in config.json; repair it before logging in") + return Profiles{}, fmt.Errorf("invalid provider %q in %s: %w", name, configPath, err) } providers[name] = validated } @@ -205,7 +206,7 @@ func LoadProfiles(directory string) (Profiles, error) { if cfg.Active != nil { active = *cfg.Active if _, ok := providers[active]; !ok { - return Profiles{}, errors.New("invalid provider configuration in config.json; repair it before logging in") + return Profiles{}, fmt.Errorf("active provider %q is not defined in %s", active, configPath) } } @@ -265,7 +266,7 @@ func updateProfiles(directory string, update func(*Profiles)) error { return writeJSONAtomic(directory, "config.json", saved) }) if errors.Is(err, os.ErrExist) { - return errors.New("another login is saving; retry, or remove config.lock if that process has stopped") + return fmt.Errorf("another login is saving configuration; retry or remove config.lock if that process has stopped: %w", err) } return err } diff --git a/cli/internal/config/errors_test.go b/cli/internal/config/errors_test.go new file mode 100644 index 000000000..8cd17a697 --- /dev/null +++ b/cli/internal/config/errors_test.go @@ -0,0 +1,43 @@ +// Malformed local configuration must keep actionable causes without exposing +// credentials. Daemon E2E tests do not exercise the CLI's local file decoder. +package config + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestLoadProfilesPreservesSafeDiagnostics(t *testing.T) { + for _, tc := range []struct { + name, data, detail string + typeError bool + }{ + {"decode", `{"providers":{"work":{"apiKey":"private-credential","model":[]}}}`, "model", true}, + {"validate", `{"providers":{"work":{"apiKey":"private-credential","model":"test","protocol":"invalid"}}}`, "work", false}, + } { + t.Run(tc.name, func(t *testing.T) { + home := t.TempDir() + path := filepath.Join(home, "config.json") + if err := os.WriteFile(path, []byte(tc.data), 0600); err != nil { + t.Fatal(err) + } + _, err := LoadProfiles(home) + if err == nil || !strings.Contains(err.Error(), path) || !strings.Contains(err.Error(), tc.detail) { + t.Fatalf("missing configuration context: %v", err) + } + if strings.Contains(err.Error(), "private-credential") { + t.Fatalf("exposed credential: %v", err) + } + if tc.typeError { + var cause *json.UnmarshalTypeError + if !errors.As(err, &cause) { + t.Fatalf("lost JSON decoding cause: %v", err) + } + } + }) + } +} diff --git a/cli/internal/config/mcp.go b/cli/internal/config/mcp.go index 3e5100e7b..3ecbc5c2a 100644 --- a/cli/internal/config/mcp.go +++ b/cli/internal/config/mcp.go @@ -3,6 +3,7 @@ package config import ( "encoding/json" "errors" + "fmt" "os" "path/filepath" ) @@ -32,15 +33,15 @@ func ReadMCPServers(home string) (map[string]MCPServer, error) { return nil, err } if len(data) > 1<<20 { - return nil, errors.New("extensions.json exceeds 1 MiB") + return nil, errors.New("extensions.json is larger than 1 MiB. Reduce its size and try again.") } var root struct { MCP struct { Servers map[string]MCPServer `json:"servers"` } `json:"mcp"` } - if json.Unmarshal(data, &root) != nil { - return nil, errors.New("invalid extensions.json") + if err := json.Unmarshal(data, &root); err != nil { + return nil, fmt.Errorf("invalid extensions.json: %w", err) } if root.MCP.Servers == nil { return map[string]MCPServer{}, nil @@ -52,7 +53,7 @@ func ReadMCPServers(home string) (map[string]MCPServer, error) { // configuration contains no plaintext secrets; the daemon keeps those in creds.json. func PutMCPServer(home, name string, server *MCPServer) error { if name == "" { - return errors.New("missing MCP server name") + return errors.New("Enter an MCP server name.") } return lockedUpdate(home, "extensions.lock", 50, func() error { path := filepath.Join(home, "extensions.json") @@ -61,16 +62,22 @@ func PutMCPServer(home, name string, server *MCPServer) error { return err } root := map[string]json.RawMessage{} - if len(data) > 0 && json.Unmarshal(data, &root) != nil { - return errors.New("invalid extensions.json") + if len(data) > 0 { + if err := json.Unmarshal(data, &root); err != nil { + return fmt.Errorf("invalid extensions.json: %w", err) + } } mcp := map[string]json.RawMessage{} - if len(root["mcp"]) > 0 && json.Unmarshal(root["mcp"], &mcp) != nil { - return errors.New("invalid MCP settings") + if len(root["mcp"]) > 0 { + if err := json.Unmarshal(root["mcp"], &mcp); err != nil { + return fmt.Errorf("invalid MCP settings in extensions.json: %w", err) + } } servers := map[string]json.RawMessage{} - if len(mcp["servers"]) > 0 && json.Unmarshal(mcp["servers"], &servers) != nil { - return errors.New("invalid MCP servers") + if len(mcp["servers"]) > 0 { + if err := json.Unmarshal(mcp["servers"], &servers); err != nil { + return fmt.Errorf("invalid MCP servers in extensions.json: %w", err) + } } if server == nil { delete(servers, name) @@ -81,8 +88,11 @@ func PutMCPServer(home, name string, server *MCPServer) error { } if len(servers[name]) > 0 { old, patch := map[string]json.RawMessage{}, map[string]json.RawMessage{} - if json.Unmarshal(servers[name], &old) != nil || json.Unmarshal(next, &patch) != nil { - return errors.New("invalid MCP server configuration") + if err := json.Unmarshal(servers[name], &old); err != nil { + return fmt.Errorf("invalid MCP server %q in extensions.json: %w", name, err) + } + if err := json.Unmarshal(next, &patch); err != nil { + return fmt.Errorf("decode MCP server update: %w", err) } for key, value := range patch { old[key] = value diff --git a/cli/internal/daemon/client.go b/cli/internal/daemon/client.go index e6dcd5e98..69ea15299 100644 --- a/cli/internal/daemon/client.go +++ b/cli/internal/daemon/client.go @@ -167,28 +167,10 @@ func (c *ChatClient) agentURL(path string) string { func (c *ChatClient) parseResponseError(res *http.Response) error { body, err := readBounded(res.Body, 64*1024) if err != nil { - return fmt.Errorf("%d %s: %w", res.StatusCode, res.Status, err) + return &APIError{StatusCode: res.StatusCode, Cause: err} } - var data struct { - Code string `json:"code"` - Error string `json:"error"` - Workspace string `json:"workspace"` - } - if err := json.Unmarshal(body, &data); err == nil { - if data.Code == "workspace_missing" && data.Workspace != "" { - return &WorkspaceMissingError{Workspace: data.Workspace} - } - if data.Error != "" { - return errors.New(data.Error) - } - } - - fallback := strings.TrimSpace(fmt.Sprintf("%d %s", res.StatusCode, res.Status)) - if fallback == "" { - fallback = "request failed" - } - return errors.New(fallback) + return decodeAPIError(res.StatusCode, body) } func (c *ChatClient) submitPayload(ctx context.Context, payload map[string]any) (*SendResult, error) { diff --git a/cli/internal/daemon/commands.go b/cli/internal/daemon/commands.go index 332f7d76e..20a1220f9 100644 --- a/cli/internal/daemon/commands.go +++ b/cli/internal/daemon/commands.go @@ -76,7 +76,7 @@ func isValidCommand(cmd SessionCommand) bool { func ParseCommandCatalog(data []byte) ([]SessionCommand, error) { var rawList []json.RawMessage if err := json.Unmarshal(data, &rawList); err != nil { - return nil, errors.New("daemon returned invalid command catalog") + return nil, fmt.Errorf("decode command catalog: %w", err) } commands := make([]SessionCommand, 0, len(rawList)) @@ -90,7 +90,7 @@ func ParseCommandCatalog(data []byte) ([]SessionCommand, error) { } if len(rawList) > 0 && len(commands) == 0 { - return nil, errors.New("daemon returned invalid command metadata") + return nil, errors.New("Albedo returned command details that this client could not read.") } return commands, nil diff --git a/cli/internal/daemon/errors.go b/cli/internal/daemon/errors.go new file mode 100644 index 000000000..0ed3c5e76 --- /dev/null +++ b/cli/internal/daemon/errors.go @@ -0,0 +1,57 @@ +package daemon + +import ( + "encoding/json" + "fmt" + "net/http" +) + +// UpgradeRequiredError identifies a feature missing from the running daemon. +type UpgradeRequiredError struct { + Feature string +} + +func (e *UpgradeRequiredError) Error() string { + return "The running copy of Albedo needs an update " + e.Feature + ". Restarting will interrupt work in all sessions and clear their Python variables. When you are ready, run albedo daemon --stop, then launch your updated copy of Albedo." +} + +// APIError retains the HTTP status and daemon error code independently of copy. +type APIError struct { + StatusCode int + Code string + Message string + Cause error +} + +func (e *APIError) Error() string { + if e.Message != "" { + return e.Message + } + if e.Cause != nil { + return fmt.Sprintf("HTTP %d: %v", e.StatusCode, e.Cause) + } + if status := http.StatusText(e.StatusCode); status != "" { + return fmt.Sprintf("HTTP %d: %s", e.StatusCode, status) + } + return fmt.Sprintf("HTTP %d", e.StatusCode) +} + +func (e *APIError) Unwrap() error { return e.Cause } + +func decodeAPIError(status int, body []byte) error { + var data struct { + Code string `json:"code"` + Error string `json:"error"` + Workspace string `json:"workspace"` + } + apiErr := &APIError{StatusCode: status} + if err := json.Unmarshal(body, &data); err != nil { + return apiErr + } + apiErr.Code, apiErr.Message = data.Code, data.Error + if data.Code == "workspace_missing" && data.Workspace != "" { + apiErr.Cause = &WorkspaceMissingError{Workspace: data.Workspace} + apiErr.Message = apiErr.Cause.Error() + } + return apiErr +} diff --git a/cli/internal/daemon/errors_test.go b/cli/internal/daemon/errors_test.go new file mode 100644 index 000000000..fac27b1f9 --- /dev/null +++ b/cli/internal/daemon/errors_test.go @@ -0,0 +1,54 @@ +// Error decoding must preserve status and structured causes even for malformed +// responses, which the real daemon E2E suite does not produce. +package daemon + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestHTTPFailuresRetainIdentity(t *testing.T) { + for _, tc := range []struct { + name, body, code, workspace string + status int + }{ + {"workspace", `{"code":"workspace_missing","workspace":"/missing","error":"wording can change"}`, "workspace_missing", "/missing", 409}, + {"forbidden", `{"code":"forbidden","error":"access denied"}`, "forbidden", "", 403}, + {"unauthorized", `{"code":"unauthorized","error":"sign in again"}`, "unauthorized", "", 401}, + {"code only", `{"code":"busy"}`, "busy", "", 503}, + {"malformed", `bad gateway`, "", "", 502}, + } { + t.Run(tc.name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(tc.status) + _, _ = io.WriteString(w, tc.body) + })) + defer server.Close() + conn := NewConnection(ConnectionSnapshot{Port: server.Listener.Addr().(*net.TCPAddr).Port}, t.TempDir()) + _, requestErr := RequestMethod[any](context.Background(), conn, http.MethodGet, "/failure", nil) + client := NewChatClient(ChatClientOptions{}) + chatErr := client.parseResponseError(&http.Response{StatusCode: tc.status, Body: io.NopCloser(strings.NewReader(tc.body))}) + for _, err := range []error{requestErr, chatErr} { + err = fmt.Errorf("request context: %w", err) + var apiErr *APIError + if !errors.As(err, &apiErr) || apiErr.StatusCode != tc.status || apiErr.Code != tc.code { + t.Fatalf("lost HTTP failure identity: %v", err) + } + var workspaceErr *WorkspaceMissingError + if tc.workspace != "" && (!errors.As(err, &workspaceErr) || workspaceErr.Workspace != tc.workspace) { + t.Fatalf("lost workspace recovery information: %v", err) + } + if strings.Contains(err.Error(), "") { + t.Fatalf("exposed unstructured response body: %v", err) + } + } + }) + } +} diff --git a/cli/internal/daemon/lifecycle.go b/cli/internal/daemon/lifecycle.go index 5d003f7c4..8ccac0158 100644 --- a/cli/internal/daemon/lifecycle.go +++ b/cli/internal/daemon/lifecycle.go @@ -226,10 +226,10 @@ func (t *ReconnectingTransport) RoundTrip(req *http.Request) (*http.Response, er } if t.Provider != nil && req.URL != nil && req.URL.Path != "/shutdown" && isStaleDaemon(err, status) { - if res != nil { - _ = res.Body.Close() - } if refreshErr := t.Provider.Refresh(req.Context()); refreshErr == nil { + if res != nil { + _ = res.Body.Close() + } newReq := req.Clone(req.Context()) newBase := t.Provider.BaseURL() if parsed, parseErr := url.Parse(newBase); parseErr == nil && newReq.URL != nil { @@ -687,10 +687,8 @@ func staleLock(lockPath string) bool { } func startupExitError(waitErr error, logPath string, logStart int64, projectRoot string) error { - msg := "daemon exited during startup" - if waitErr != nil { - msg = fmt.Sprintf("%s (%v)", msg, waitErr) - } + msg := "Albedo stopped before it finished starting" + if f, err := os.Open(logPath); err == nil { defer f.Close() if _, err := f.Seek(logStart, io.SeekStart); err == nil { @@ -701,7 +699,10 @@ func startupExitError(waitErr error, logPath string, logStart int64, projectRoot } } if projectRoot != "" { - msg += fmt.Sprintf("\n(project root: %s; set ALBEDO_ROOT or install with -ldflags \"-X main.buildRoot=...\")", projectRoot) + msg += fmt.Sprintf("\nSource checkout: %s. If this is not your Albedo checkout, set ALBEDO_ROOT to its full path.", projectRoot) + } + if waitErr != nil { + return fmt.Errorf("%s: %w", msg, waitErr) } return errors.New(msg) } @@ -734,7 +735,7 @@ func CheckCapability(ctx context.Context, conn *Connection, capability, feature // UpgradeNeeded is the error for a feature the running daemon predates; // feature finishes the sentence, as in "for /tree" or "to switch providers". func UpgradeNeeded(feature string) error { - return errors.New("daemon upgrade needed " + feature + "; when ready, run albedo daemon --stop, then albedo (this clears python variables)") + return &UpgradeRequiredError{Feature: feature} } func RequestMethod[T any](ctx context.Context, conn *Connection, method, path string, body any) (T, error) { @@ -788,18 +789,14 @@ func RequestMethod[T any](ctx context.Context, conn *Connection, method, path st respData, err := readBounded(res.Body, 50*1024*1024) if err != nil { + if res.StatusCode < 200 || res.StatusCode >= 300 { + return zero, &APIError{StatusCode: res.StatusCode, Cause: err} + } return zero, err } if res.StatusCode < 200 || res.StatusCode >= 300 { - var errResp struct { - Error string `json:"error"` - } - _ = json.Unmarshal(respData, &errResp) - if errResp.Error != "" { - return zero, errors.New(errResp.Error) - } - return zero, fmt.Errorf("HTTP %d", res.StatusCode) + return zero, decodeAPIError(res.StatusCode, respData) } var result T diff --git a/cli/internal/tui/app.go b/cli/internal/tui/app.go index 16f549ad9..3dbfa7af8 100644 --- a/cli/internal/tui/app.go +++ b/cli/internal/tui/app.go @@ -754,8 +754,9 @@ func (m AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil } if msg.Err != nil { - if strings.Contains(msg.Err.Error(), "daemon upgrade") { - m.AddError("Error: " + msg.Err.Error()) + var upgradeErr *daemon.UpgradeRequiredError + if errors.As(msg.Err, &upgradeErr) { + m.AddError("Could not load commands: " + msg.Err.Error()) } return m, nil } diff --git a/cli/internal/tui/error_routing_test.go b/cli/internal/tui/error_routing_test.go new file mode 100644 index 000000000..e3bf97e6f --- /dev/null +++ b/cli/internal/tui/error_routing_test.go @@ -0,0 +1,26 @@ +// TUI routing and in-flight save rendering cannot be exercised by daemon E2E +// tests. These checks keep display text from controlling either state machine. +package tui + +import ( + "albedo/cli/internal/daemon" + "errors" + "fmt" + "testing" +) + +func TestCatalogFailureUsesErrorIdentity(t *testing.T) { + for _, tc := range []struct { + err error + show bool + }{ + {fmt.Errorf("catalog: %w", daemon.UpgradeNeeded("for commands")), true}, + {errors.New("unrelated service needs an update"), false}, + } { + m := AppModel{} + next, _ := m.Update(commandCatalogLoadedMsg{Err: tc.err}) + if next.(AppModel).Notices.HasError() != tc.show { + t.Fatalf("catalog failure was routed using its wording: %v", tc.err) + } + } +} diff --git a/cli/internal/tui/mcp_form.go b/cli/internal/tui/mcp_form.go index 5f751cab2..174bed4b1 100644 --- a/cli/internal/tui/mcp_form.go +++ b/cli/internal/tui/mcp_form.go @@ -5,6 +5,7 @@ import ( "albedo/cli/internal/daemon" "cmp" "errors" + "fmt" "net/url" "path" "regexp" @@ -145,10 +146,10 @@ type mcpSubmission struct { func (f *mcpForm) submission(existing []capabilityItem) (mcpSubmission, error) { name := f.value(fieldName) if !mcpName.MatchString(name) { - return mcpSubmission{}, errors.New("name: use 1–64 letters, digits, _ or -") + return mcpSubmission{}, errors.New("Use 1–64 letters, digits, underscores, or hyphens for the server name.") } if f.Editing == "" && slices.ContainsFunc(existing, func(item capabilityItem) bool { return item.ID == name && !item.Draft }) { - return mcpSubmission{}, errors.New("name: a server called " + name + " already exists") + return mcpSubmission{}, fmt.Errorf("A server called %s already exists. Choose another name.", name) } server := f.Base server.Type = f.Transport @@ -157,7 +158,7 @@ func (f *mcpForm) submission(existing []capabilityItem) (mcpSubmission, error) { raw := f.value(fieldURL) parsed, err := url.Parse(raw) if raw == "" || err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" { - return mcpSubmission{}, errors.New("url: enter an http:// or https:// address") + return mcpSubmission{}, errors.New("Enter a server URL starting with http:// or https://.") } server.URL, server.Command, server.Args, server.CWD = raw, "", nil, "" if token := f.value(fieldToken); token == "-" { @@ -169,11 +170,11 @@ func (f *mcpForm) submission(existing []capabilityItem) (mcpSubmission, error) { switch { case header == "" && value == "": case !mcpHeaderName.MatchString(header): - return mcpSubmission{}, errors.New("header: enter a valid HTTP header name") + return mcpSubmission{}, errors.New("Enter a valid HTTP header name.") case value == "-": secrets["headers"] = map[string]any{header: nil} case value == "": - return mcpSubmission{}, errors.New("header value: enter a value, or - to remove " + header) + return mcpSubmission{}, fmt.Errorf("Enter a value for %s, or - to remove it.", header) default: secrets["headers"] = map[string]any{header: value} } @@ -181,18 +182,18 @@ func (f *mcpForm) submission(existing []capabilityItem) (mcpSubmission, error) { } else { argv, err := splitCommand(f.Inputs[fieldCommand].Value()) if err != nil || len(argv) == 0 { - return mcpSubmission{}, errors.New("command: enter the command that starts the server") + return mcpSubmission{}, errors.New("Enter the command that starts the server.") } server.Command, server.Args, server.URL = argv[0], argv[1:], "" entries, err := splitCommand(f.Inputs[fieldEnv].Value()) if err != nil { - return mcpSubmission{}, errors.New("env: " + err.Error()) + return mcpSubmission{}, fmt.Errorf("check environment variables: %w", err) } var env map[string]any for _, entry := range entries { key, value, ok := strings.Cut(entry, "=") if !ok || !mcpEnvName.MatchString(key) { - return mcpSubmission{}, errors.New("env: use KEY=value entries separated by spaces") + return mcpSubmission{}, errors.New("Enter environment variables as KEY=value pairs separated by spaces.") } if env == nil { env = map[string]any{} diff --git a/robot-docs/commands.md b/robot-docs/commands.md index f6924977b..f8f8c1bcc 100644 --- a/robot-docs/commands.md +++ b/robot-docs/commands.md @@ -8,6 +8,8 @@ every session command is one definition with three faces: the CLI menu, user inv `POST /sessions/:id/commands` runs one command. the body is `{name, arguments}` with raw invocation text (`{"name": "/model", "arguments": "gpt-5 anthropic"}`) or `{name, args}` with declared names (`{"name": "/model", "args": {"model": "gpt-5"}}`); `clientId` labels a submitted turn. the answer is `{"result": ...}` with the command's JSON value or `{"submitted": true}` when a user invocation submitted its turn. +The Go client returns `daemon.APIError` for HTTP failures, retaining the status, daemon error code, and message. Use `errors.As` to inspect it. Workspace failures also unwrap to `daemon.WorkspaceMissingError` so the chat can offer a replacement folder. Capability checks return `daemon.UpgradeRequiredError`; the TUI recognizes that type when displaying catalog upgrade failures. Error wording does not control this routing. + ## contributing commands `CommandPlugin` in an extension declares static commands; a `ManagedPlugin` contributes dynamic ones through `Managed.commands` (this is how skills registers its slash commands). the type lives in [`command.gleam`](../src/albedo/harness/command.gleam): -- knotmirror 0.0.1