From aaf313e7544e1e46b272dcf66d362b3e27be9404 Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Thu, 1 Oct 2026 21:22:59 -0400 Subject: [PATCH] fix(client): validate mutation results before updating state Keep confirmed changes and require complete mutation responses. Drop legacy extension fallbacks. --- cli/internal/app/model_select.go | 5 +- cli/internal/app/prompt.go | 3 +- cli/internal/app/service.go | 31 +- cli/internal/daemon/auth.go | 38 +- cli/internal/daemon/client.go | 33 +- cli/internal/daemon/credentials.go | 20 +- cli/internal/daemon/folders.go | 2 +- cli/internal/daemon/http.go | 28 +- cli/internal/daemon/lifecycle.go | 2 +- cli/internal/daemon/mutation_commands.go | 419 +++++++++++++ cli/internal/daemon/mutation_commands_test.go | 86 +++ cli/internal/daemon/mutations.go | 571 ++++++++++++++++++ cli/internal/daemon/mutations_test.go | 353 +++++++++++ cli/internal/daemon/pages.go | 45 ++ cli/internal/daemon/settings.go | 20 +- cli/internal/tui/agents_view.go | 11 +- cli/internal/tui/app.go | 175 ++---- cli/internal/tui/app_commands_test.go | 22 +- cli/internal/tui/capability_pages.go | 21 +- cli/internal/tui/extension_picker.go | 54 +- cli/internal/tui/model_change_test.go | 121 ++++ cli/internal/tui/page_secret_test.go | 11 +- cli/internal/tui/page_view.go | 181 +----- cli/internal/tui/tree_picker.go | 4 +- cli/internal/tui/uncertain_outcome_test.go | 45 ++ cli/internal/tui/webhooks_page.go | 60 +- 26 files changed, 1887 insertions(+), 474 deletions(-) create mode 100644 cli/internal/daemon/mutation_commands.go create mode 100644 cli/internal/daemon/mutation_commands_test.go create mode 100644 cli/internal/daemon/mutations.go create mode 100644 cli/internal/daemon/mutations_test.go create mode 100644 cli/internal/daemon/pages.go create mode 100644 cli/internal/tui/model_change_test.go diff --git a/cli/internal/app/model_select.go b/cli/internal/app/model_select.go index 0f2501313..d22d18136 100644 --- a/cli/internal/app/model_select.go +++ b/cli/internal/app/model_select.go @@ -4,8 +4,6 @@ import ( "context" "fmt" "maps" - "net/http" - "net/url" "slices" "strings" @@ -83,8 +81,7 @@ func switchModel(ctx context.Context, conn *daemon.Connection, sessionID string, if err := daemon.CheckCapability(ctx, conn, "session_model", "to choose a model for an existing session"); err != nil { return err } - path := "/sessions/" + url.PathEscape(sessionID) + "/model" - _, err := daemon.RequestOperation[map[string]any](ctx, conn, daemon.Operation{Name: "switch model", Method: http.MethodPost, Path: path, Body: map[string]string{"model": choice.model, "provider": choice.provider}, Policy: daemon.AuthRecovery}) + _, err := daemon.SelectModel(ctx, conn, sessionID, map[string]string{"model": choice.model, "provider": choice.provider}) return err } diff --git a/cli/internal/app/prompt.go b/cli/internal/app/prompt.go index f67c554f7..e7e5df85a 100644 --- a/cli/internal/app/prompt.go +++ b/cli/internal/app/prompt.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "net/http" "sync" "time" @@ -49,7 +48,7 @@ func (s *Service) RunPrompt(ctx context.Context, options PromptOptions) (PromptR if model != "" { create["provider"], create["model"] = choice.provider, choice.model } - session, createErr := daemon.RequestOperation[daemon.Session](ctx, conn, daemon.Operation{Name: "create session", Method: http.MethodPost, Path: "/sessions", Body: create, Policy: daemon.AuthRecovery}) + session, createErr := daemon.CreateSession(ctx, conn, create) if createErr != nil { return PromptResult{}, createErr } diff --git a/cli/internal/app/service.go b/cli/internal/app/service.go index 1f3f6dc10..57a65aba9 100644 --- a/cli/internal/app/service.go +++ b/cli/internal/app/service.go @@ -3,11 +3,9 @@ package app import ( "context" - "encoding/json" "errors" "fmt" "net/http" - "net/url" "path/filepath" "slices" "strings" @@ -74,7 +72,7 @@ func (s *Service) PrepareOpen(ctx context.Context, options OpenOptions) (Prepare if selected != nil { initial = selected } else if configured && (fresh || len(sessions) == 0) { - created, createErr := daemon.RequestOperation[daemon.Session](ctx, conn, daemon.Operation{Name: "create session", Method: http.MethodPost, Path: "/sessions", Body: map[string]string{"workspace": absWorkspace}, Policy: daemon.AuthRecovery}) + created, createErr := daemon.CreateSession(ctx, conn, map[string]string{"workspace": absWorkspace}) if createErr != nil { return PreparedOpen{}, createErr } @@ -138,27 +136,33 @@ func resolveSession(ctx context.Context, conn *daemon.Connection, id string) (st return session.ID, err } -func (s *Service) Send(ctx context.Context, id, prompt string) (json.RawMessage, error) { +func (s *Service) Send(ctx context.Context, id, prompt string) (daemon.SendResult, error) { conn, err := s.Connect(ctx) if err != nil { - return nil, err + return daemon.SendResult{}, err } id, err = resolveSession(ctx, conn, id) if err != nil { - return nil, err + return daemon.SendResult{}, err } - return daemon.RequestOperation[json.RawMessage](ctx, conn, daemon.Operation{Name: "send message", Method: http.MethodPost, Path: "/sessions/" + url.PathEscape(id) + "/events", Body: map[string]string{"content": prompt}, Policy: daemon.AuthRecovery}) + return daemon.Submit(ctx, conn, id, map[string]any{"content": prompt}) } -func (s *Service) Stop(ctx context.Context, id string) (json.RawMessage, error) { + +type InterruptionResult struct { + Interrupted bool `json:"interrupted"` +} + +func (s *Service) Stop(ctx context.Context, id string) (InterruptionResult, error) { conn, err := s.Connect(ctx) if err != nil { - return nil, err + return InterruptionResult{}, err } id, err = resolveSession(ctx, conn, id) if err != nil { - return nil, err + return InterruptionResult{}, err } - return daemon.RequestOperation[json.RawMessage](ctx, conn, daemon.Operation{Name: "interrupt session", Method: http.MethodPost, Path: "/sessions/" + url.PathEscape(id) + "/interrupt", Body: map[string]any{}, Policy: daemon.AuthRecovery}) + interrupted, err := daemon.InterruptSession(ctx, conn, id) + return InterruptionResult{Interrupted: interrupted}, err } func (s *Service) DeleteSessions(ctx context.Context, ids []string) error { conn, err := s.Connect(ctx) @@ -166,7 +170,7 @@ func (s *Service) DeleteSessions(ctx context.Context, ids []string) error { return err } for _, id := range ids { - if _, err := daemon.RequestOperation[json.RawMessage](ctx, conn, daemon.Operation{Name: "delete session", Method: http.MethodDelete, Path: "/sessions/" + url.PathEscape(id), Policy: daemon.AuthRecovery}); err != nil { + if _, err := daemon.DeleteSession(ctx, conn, id, false); err != nil { return err } } @@ -177,8 +181,7 @@ func (s *Service) StopDaemon(ctx context.Context) error { if err != nil || conn == nil { return err } - _, err = daemon.RequestOperation[json.RawMessage](ctx, conn, daemon.Operation{Name: "stop daemon", Method: http.MethodPost, Path: "/shutdown", Body: map[string]any{}, Policy: daemon.NoRecovery}) - return err + return daemon.StopDaemon(ctx, conn) } func (s *Service) PrepareLogin(ctx context.Context) (PreparedOpen, error) { conn, err := s.Connect(ctx) diff --git a/cli/internal/daemon/auth.go b/cli/internal/daemon/auth.go index 8ed0776c5..35fe1c584 100644 --- a/cli/internal/daemon/auth.go +++ b/cli/internal/daemon/auth.go @@ -2,8 +2,10 @@ package daemon import ( "context" + "encoding/json" "net/http" "net/url" + "strings" ) // Browser sign-ins run in the daemon so every client shares one OAuth @@ -42,10 +44,6 @@ type SignInStatus struct { Message string `json:"message"` } -type acknowledged struct { - OK bool `json:"ok"` -} - func accountPath(provider, id string) string { return "/auth/" + url.PathEscape(provider) + "/accounts/" + url.PathEscape(id) } @@ -56,7 +54,29 @@ func SignInList(ctx context.Context, conn *Connection) (SignIns, error) { // StartSignIn begins a sign-in and returns the url the browser should open. func StartSignIn(ctx context.Context, conn *Connection, provider string) (StartedSignIn, error) { - return RequestOperation[StartedSignIn](ctx, conn, Operation{Name: "start sign in", Method: http.MethodPost, Path: "/auth/" + url.PathEscape(provider), Body: nil, Policy: AuthRecovery}) + var result StartedSignIn + err := executeMutation(ctx, conn, Operation{Name: "start sign in", Method: http.MethodPost, Path: "/auth/" + url.PathEscape(provider), Policy: AuthRecovery}, []int{http.StatusCreated}, func(data []byte, _ int) error { + var wire struct { + ID *string `json:"id"` + URL *string `json:"url"` + } + if err := json.Unmarshal(data, &wire); err != nil { + return err + } + if wire.ID == nil || strings.TrimSpace(*wire.ID) == "" { + return fieldError("id") + } + if wire.URL == nil { + return fieldError("url") + } + parsed, err := url.Parse(*wire.URL) + if err != nil || !parsed.IsAbs() || parsed.Host == "" || (parsed.Scheme != "http" && parsed.Scheme != "https") { + return fieldError("url") + } + result = StartedSignIn{ID: *wire.ID, URL: *wire.URL} + return nil + }) + return result, err } func PollSignIn(ctx context.Context, conn *Connection, id string) (SignInStatus, error) { @@ -66,21 +86,21 @@ func PollSignIn(ctx context.Context, conn *Connection, id string) (SignInStatus, // SignInInput delivers a pasted callback url, code#state, query string, or // bare code; the daemon parses and races it against the browser callback. func SignInInput(ctx context.Context, conn *Connection, id, input string) error { - _, err := RequestOperation[acknowledged](ctx, conn, Operation{Name: "sign in input", Method: http.MethodPost, Path: "/auth/logins/" + url.PathEscape(id), Body: map[string]string{"input": input}, Policy: AuthRecovery}) + err := acknowledge(ctx, conn, Operation{Name: "sign in input", Method: http.MethodPost, Path: "/auth/logins/" + url.PathEscape(id), Body: map[string]string{"input": input}, Policy: AuthRecovery}) return err } func CancelSignIn(ctx context.Context, conn *Connection, id string) error { - _, err := RequestOperation[acknowledged](ctx, conn, Operation{Name: "cancel sign in", Method: http.MethodDelete, Path: "/auth/logins/" + url.PathEscape(id), Body: nil, Policy: AuthRecovery}) + err := acknowledge(ctx, conn, Operation{Name: "cancel sign in", Method: http.MethodDelete, Path: "/auth/logins/" + url.PathEscape(id), Body: nil, Policy: AuthRecovery}) return err } func SelectAccount(ctx context.Context, conn *Connection, provider, id string) error { - _, err := RequestOperation[acknowledged](ctx, conn, Operation{Name: "select account", Method: http.MethodPost, Path: accountPath(provider, id), Body: nil, Policy: AuthRecovery}) + err := acknowledge(ctx, conn, Operation{Name: "select account", Method: http.MethodPost, Path: accountPath(provider, id), Body: nil, Policy: AuthRecovery}) return err } func RemoveAccount(ctx context.Context, conn *Connection, provider, id string) error { - _, err := RequestOperation[acknowledged](ctx, conn, Operation{Name: "remove account", Method: http.MethodDelete, Path: accountPath(provider, id), Body: nil, Policy: AuthRecovery}) + err := acknowledge(ctx, conn, Operation{Name: "remove account", Method: http.MethodDelete, Path: accountPath(provider, id), Body: nil, Policy: AuthRecovery}) return err } diff --git a/cli/internal/daemon/client.go b/cli/internal/daemon/client.go index 4a96a06d5..8fd4dff9e 100644 --- a/cli/internal/daemon/client.go +++ b/cli/internal/daemon/client.go @@ -51,7 +51,7 @@ func (e *WorkspaceMissingError) Error() string { type SendResult struct { OK bool `json:"ok"` - Queued bool `json:"queued,omitempty"` + Queued bool `json:"queued"` } type ChatClient struct { @@ -95,24 +95,11 @@ func (c *ChatClient) submitPayload(ctx context.Context, payload map[string]any) payload["clientId"] = c.clientID } - operation := Operation{Name: "submit message", Method: http.MethodPost, Path: c.agentPath("/events"), Body: payload, Policy: AuthRecovery} - body, err := requestBytes(reqCtx, c.conn, operation, responseLimits{bodyBytes: 64 * 1024, errorBytes: 64 * 1024}) + result, err := Submit(reqCtx, c.conn, c.agentID, payload) if err != nil { return nil, err } - - var data struct { - OK bool `json:"ok"` - Queued bool `json:"queued"` - } - if err := json.Unmarshal(body, &data); err != nil { - return nil, uncertainOperation(operation, err) - } - - return &SendResult{ - OK: true, - Queued: data.Queued, - }, nil + return &result, nil } func (c *ChatClient) Send(ctx context.Context, content string, image *ImageAttachment) (*SendResult, error) { @@ -135,19 +122,7 @@ func (c *ChatClient) Interrupt(ctx context.Context) (bool, error) { reqCtx, cancel := context.WithTimeout(ctx, 15*time.Second) defer cancel() - operation := Operation{Name: "interrupt session", Method: http.MethodPost, Path: c.agentPath("/interrupt"), Body: map[string]any{}, Policy: AuthRecovery} - body, err := requestBytes(reqCtx, c.conn, operation, responseLimits{successStatus: http.StatusOK, bodyBytes: 64 * 1024, errorBytes: 64 * 1024}) - if err != nil { - return false, err - } - - var data struct { - Interrupted bool `json:"interrupted"` - } - if err := json.Unmarshal(body, &data); err != nil { - return false, uncertainOperation(operation, err) - } - return data.Interrupted, nil + return InterruptSession(reqCtx, c.conn, c.agentID) } // HistoryPage is older transcript, rendered as the stream renders a reset. diff --git a/cli/internal/daemon/credentials.go b/cli/internal/daemon/credentials.go index 03e50ab10..f40885716 100644 --- a/cli/internal/daemon/credentials.go +++ b/cli/internal/daemon/credentials.go @@ -2,6 +2,7 @@ package daemon import ( "context" + "encoding/json" "net/http" ) @@ -36,8 +37,19 @@ type MCPSecretsPatch map[string]any // TakeMigration names the files the daemon's start moved secrets out of, only // to the first client that asks, so the user hears about it once. func TakeMigration(ctx context.Context, conn *Connection) ([]string, error) { - taken, err := RequestOperation[struct { - Moved []string `json:"moved"` - }](ctx, conn, Operation{Name: "take migration", Method: http.MethodPost, Path: "/auth/credentials/migration", Body: map[string]string{}, Policy: AuthRecovery}) - return taken.Moved, err + var moved []string + err := executeMutation(ctx, conn, Operation{Name: "take migration", Method: http.MethodPost, Path: "/auth/credentials/migration", Body: map[string]string{}, Policy: AuthRecovery}, []int{200}, func(data []byte, _ int) error { + var wire struct { + Moved *stringCollection `json:"moved"` + } + if err := json.Unmarshal(data, &wire); err != nil { + return err + } + if wire.Moved == nil { + return fieldError("moved") + } + moved = []string(*wire.Moved) + return nil + }) + return moved, err } diff --git a/cli/internal/daemon/folders.go b/cli/internal/daemon/folders.go index d770e82f6..e3b97cbe2 100644 --- a/cli/internal/daemon/folders.go +++ b/cli/internal/daemon/folders.go @@ -81,5 +81,5 @@ func PreviewFolder(ctx context.Context, conn *Connection, path string) (FolderPr // MoveSession moves an idle session to another folder. func MoveSession(ctx context.Context, conn *Connection, id, workspace string) (Session, error) { - return RequestOperation[Session](ctx, conn, Operation{Name: "move session", Method: http.MethodPost, Path: "/sessions/" + url.PathEscape(id) + "/workspace", Body: map[string]string{"workspace": workspace}, Policy: AuthRecovery}) + return mutateSession(ctx, conn, Operation{Name: "move session", Method: http.MethodPost, Path: sessionPath(id, "/workspace"), Body: map[string]string{"workspace": workspace}, Policy: AuthRecovery}, http.StatusOK) } diff --git a/cli/internal/daemon/http.go b/cli/internal/daemon/http.go index 1321c860b..44c9e1426 100644 --- a/cli/internal/daemon/http.go +++ b/cli/internal/daemon/http.go @@ -67,9 +67,11 @@ func isConnectionError(err error) bool { // responseLimits preserves each endpoint's accepted status and bounded reads. // A zero successStatus accepts any 2xx response. type responseLimits struct { - successStatus int - bodyBytes int64 - errorBytes int64 + status *int + successStatuses []int + successStatus int + bodyBytes int64 + errorBytes int64 } // operationRequest binds the address and credentials to one immutable snapshot. @@ -153,11 +155,29 @@ func requestBytes(ctx context.Context, conn *Connection, operation Operation, li return nil, uncertainOperation(operation, err) } success := (limits.successStatus == 0 && res.StatusCode >= 200 && res.StatusCode < 300) || res.StatusCode == limits.successStatus + if limits.status != nil { + *limits.status = res.StatusCode + } + if len(limits.successStatuses) > 0 { + success = false + for _, expected := range limits.successStatuses { + if res.StatusCode == expected { + success = true + } + } + } var body []byte if success { body, err = readBounded(res.Body, limits.bodyBytes) + if err != nil && operation.Policy != ReadRecovery { + err = &ProtocolError{Code: "invalid_response", Operation: operation.Name, Cause: err} + } } else { - err = readHTTPError(res, limits.errorBytes) + if res.StatusCode >= 200 && res.StatusCode < 300 && operation.Policy != ReadRecovery { + err = invalidResponse(operation, "status", fmt.Errorf("unexpected HTTP status %d", res.StatusCode)) + } else { + err = readHTTPError(res, limits.errorBytes) + } } _ = res.Body.Close() if err == nil { diff --git a/cli/internal/daemon/lifecycle.go b/cli/internal/daemon/lifecycle.go index b39919a90..a27a1e139 100644 --- a/cli/internal/daemon/lifecycle.go +++ b/cli/internal/daemon/lifecycle.go @@ -435,7 +435,7 @@ func daemonCommand(daemonExe, projectRoot string, env []string) (*exec.Cmd, erro // stop shuts a daemon down and waits until its process has exited, so the // next daemon can take the home. func stop(homeDir string, conn *Connection) error { - _, _ = RequestOperation[any](context.Background(), conn, Operation{Name: "stop daemon", Method: http.MethodPost, Path: "/shutdown", Body: map[string]any{}, Policy: NoRecovery}) + _ = StopDaemon(context.Background(), conn) for range pollAttempts { running, err := Existing(homeDir) if err != nil { diff --git a/cli/internal/daemon/mutation_commands.go b/cli/internal/daemon/mutation_commands.go new file mode 100644 index 000000000..58bf24e9a --- /dev/null +++ b/cli/internal/daemon/mutation_commands.go @@ -0,0 +1,419 @@ +package daemon + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "strings" +) + +type CommandResult struct { + Model *ModelSelection + Effort *EffortResult + Page *PageDocument + Webhooks *WebhookResult + Message string + Result json.RawMessage + Submitted bool +} +type EffortResult struct { + Effort string `json:"-"` + Message string `json:"message"` + Available []string `json:"available"` +} +type Webhook struct { + ID string `json:"id"` + Session string `json:"session"` + Name string `json:"name"` + URL string `json:"url"` + Header string `json:"signatureHeader"` + Prefix string `json:"signaturePrefix"` + Revision int `json:"revision"` + Enabled bool `json:"enabled"` +} +type WebhookEntry struct { + Deferred *string `json:"deferred"` + Hook Webhook `json:"hook"` + Queued int `json:"queued"` +} +type WebhookResult struct { + Hook *Webhook `json:"hook"` + Session string `json:"session"` + Secret string `json:"secret"` + Message string `json:"message"` + Hooks []WebhookEntry `json:"hooks"` + AgentManagement bool `json:"agentManagement"` +} + +func decodeCommand(data []byte, status int) (CommandResult, error) { + var wire struct { + Result json.RawMessage `json:"result"` + Submitted json.RawMessage `json:"submitted"` + } + if err := json.Unmarshal(data, &wire); err != nil { + return CommandResult{}, err + } + if status == 200 { + if wire.Result == nil { + return CommandResult{}, fieldError("result") + } + if wire.Submitted != nil { + return CommandResult{}, fieldError("submitted") + } + return CommandResult{Result: wire.Result}, nil + } + if wire.Result != nil { + return CommandResult{}, fieldError("result") + } + var submitted bool + if wire.Submitted == nil || json.Unmarshal(wire.Submitted, &submitted) != nil || !submitted { + return CommandResult{}, fieldError("submitted") + } + return CommandResult{Submitted: true}, nil +} + +func ExecuteCommand(ctx context.Context, conn *Connection, id string, body map[string]any) (CommandResult, error) { + return executeCommand(ctx, conn, id, body, false) +} +func ExecutePageCommand(ctx context.Context, conn *Connection, id string, body map[string]any) (CommandResult, error) { + return executeCommand(ctx, conn, id, body, true) +} +func executeCommand(ctx context.Context, conn *Connection, id string, body map[string]any, page bool) (CommandResult, error) { + var result CommandResult + name, _ := body["name"].(string) + err := executeMutation(ctx, conn, Operation{Name: "execute command " + name, Method: http.MethodPost, Path: sessionPath(id, "/commands"), Body: body, Policy: AuthRecovery}, []int{200, 202}, func(data []byte, status int) error { + var err error + result, err = decodeCommand(data, status) + if err != nil { + return err + } + if page || name == "/model" || name == "/effort" || name == "/webhooks" { + if result.Submitted { + return fieldError("result") + } + payload := result.Result + switch { + case page: + if err := validatePage(payload); err != nil { + return err + } + var envelope struct { + Page PageDocument `json:"page"` + } + if err := json.Unmarshal(payload, &envelope); err != nil { + return err + } + result.Page = &envelope.Page + return nil + case name == "/model": + model, err := decodeModelSelection(payload) + if err != nil { + return err + } + result.Model = &model + return nil + case name == "/effort": + if err := validateEffort(payload, body); err != nil { + return err + } + var wire struct { + Effort *string `json:"effort"` + Message string `json:"message"` + Available []string `json:"available"` + } + if err := json.Unmarshal(payload, &wire); err != nil { + return err + } + effort := EffortResult{Available: wire.Available, Message: wire.Message} + if wire.Effort != nil { + effort.Effort = *wire.Effort + } + result.Effort = &effort + return nil + case name == "/webhooks": + if err := validateWebhooks(payload, body); err != nil { + return err + } + var webhook WebhookResult + if err := json.Unmarshal(payload, &webhook); err != nil { + return err + } + result.Webhooks = &webhook + result.Message = webhook.Message + return nil + } + } + if len(result.Result) > 0 && result.Result[0] == '{' { + if fields, err := object(result.Result); err == nil { + var message string + if raw := fields["message"]; raw != nil && json.Unmarshal(raw, &message) == nil { + result.Message = message + } + } + } + return nil + }) + return result, err +} +func validateEffort(data []byte, body map[string]any) error { + fields, err := object(data) + if err != nil { + return err + } + var effort *string + if err := nullable(fields, "effort", &effort); err != nil { + return err + } + var message string + if err := required(fields, "message", &message); err != nil { + return err + } + arguments, _ := body["arguments"].(string) + args, _ := body["args"].(map[string]string) + if arguments == "" && args["level"] == "" { + var available stringCollection + return required(fields, "available", &available) + } + return nil +} + +func validatePage(data []byte) error { + envelope, err := object(data) + if err != nil { + return err + } + page, err := object(envelope["page"]) + if err != nil { + return fieldError("page") + } + for _, key := range []string{"title", "summary", "empty"} { + var value string + if err := required(page, key, &value); err != nil { + return err + } + } + if err := validateRows(page["rows"]); err != nil { + return err + } + var actions []json.RawMessage + if err := required(page, "actions", &actions); err != nil { + return err + } + for _, raw := range actions { + action, err := object(raw) + if err != nil { + return err + } + var key, input string + if err := required(action, "key", &key); err != nil { + return err + } + if len([]rune(key)) != 1 { + return fieldError("key") + } + for _, key := range []string{"label", "run"} { + var value string + if err := required(action, key, &value); err != nil { + return err + } + } + for _, key := range []string{"row", "confirm"} { + var value bool + if err := required(action, key, &value); err != nil { + return err + } + } + if err := required(action, "input", &input); err != nil { + return err + } + switch input { + case "none": + case "text", "secret": + var prompt string + if err := required(action, "prompt", &prompt); err != nil { + return err + } + if input == "text" { + var prefill bool + if err := required(action, "prefill", &prefill); err != nil { + return err + } + } + case "value": + var value string + if err := required(action, "value", &value); err != nil { + return err + } + case "choice": + var options stringCollection + if err := required(action, "options", &options); err != nil { + return err + } + if len(options) == 0 { + return fieldError("options") + } + default: + return fieldError("input") + } + } + raw, ok := page["glance"] + if !ok { + return fieldError("glance") + } + if string(raw) != "null" { + glance, err := object(raw) + if err != nil { + return err + } + var title string + if err := required(glance, "title", &title); err != nil { + return err + } + return validateRows(glance["rows"]) + } + return nil +} +func validateRows(data []byte) error { + var rows []json.RawMessage + if err := json.Unmarshal(data, &rows); err != nil { + return err + } + if rows == nil { + return fieldError("rows") + } + for _, raw := range rows { + row, err := object(raw) + if err != nil { + return err + } + for _, key := range []string{"id", "text", "badge", "detail"} { + var value string + if err := required(row, key, &value); err != nil { + return err + } + } + var tone string + if err := required(row, "tone", &tone); err != nil { + return err + } + switch tone { + case "plain", "active", "warning", "muted": + default: + return fieldError("tone") + } + } + return nil +} +func validateHook(data []byte) error { + hook, err := object(data) + if err != nil { + return err + } + for _, key := range []string{"id", "session", "name", "url", "signatureHeader", "signaturePrefix"} { + var value string + if err := required(hook, key, &value); err != nil { + return err + } + if key == "id" && value == "" { + return fieldError("id") + } + } + var enabled bool + if err := required(hook, "enabled", &enabled); err != nil { + return err + } + var revision int + return required(hook, "revision", &revision) +} +func webhookArguments(body map[string]any) (action, details string) { + args, _ := body["args"].(map[string]string) + if len(args) > 0 { + return args["action"], strings.TrimSpace(args["details"]) + } + arguments, _ := body["arguments"].(string) + action, details, _ = strings.Cut(strings.TrimSpace(arguments), " ") + return strings.TrimSpace(action), strings.TrimSpace(details) +} + +func webhookGeneratesSecret(action, details string) bool { + switch action { + case "create", "rotate": + return true + case "create_in": + _, rest, _ := strings.Cut(details, " ") + _, supplied, _ := strings.Cut(rest, " ") + return supplied == "" + default: + return false + } +} + +func validateWebhooks(data []byte, body map[string]any) error { + fields, err := object(data) + if err != nil { + return err + } + action, details := webhookArguments(body) + switch action { + case "", "list": + var session string + if err := required(fields, "session", &session); err != nil { + return err + } + var management bool + if err := required(fields, "agentManagement", &management); err != nil { + return err + } + var hooks []json.RawMessage + if err := required(fields, "hooks", &hooks); err != nil { + return err + } + for _, raw := range hooks { + entry, err := object(raw) + if err != nil { + return err + } + if err := validateHook(entry["hook"]); err != nil { + return err + } + var queued int + if err := required(entry, "queued", &queued); err != nil { + return err + } + if queued < 0 { + return fieldError("queued") + } + var deferred *string + if err := nullable(entry, "deferred", &deferred); err != nil { + return err + } + } + case "agent_on", "agent_off": + var message string + return required(fields, "message", &message) + case "create", "create_with_secret", "create_in", "rotate", "rotate_with_secret": + if err := validateHook(fields["hook"]); err != nil { + return err + } + var message string + if err := required(fields, "message", &message); err != nil { + return err + } + _, hasSecret := fields["secret"] + if hasSecret || webhookGeneratesSecret(action, details) { + var secret string + if err := required(fields, "secret", &secret); err != nil { + return err + } + if secret == "" { + return fieldError("secret") + } + } + case "signature", "enable", "disable", "delete": + return validateHook(data) + default: + return errors.New("unsupported webhook action") + } + return nil +} diff --git a/cli/internal/daemon/mutation_commands_test.go b/cli/internal/daemon/mutation_commands_test.go new file mode 100644 index 000000000..53473ce3a --- /dev/null +++ b/cli/internal/daemon/mutation_commands_test.go @@ -0,0 +1,86 @@ +// These wire-parser tests catch numeric rounding and missing generated secrets +// that a healthy daemon cannot emit. Workflow fault tests cover durable effects. +package daemon + +import ( + "context" + "errors" + "fmt" + "testing" +) + +func webhookReceipt(revision, secretField string) string { + return fmt.Sprintf(`{"result":{"hook":{"id":"h","session":"s","name":"notes","url":"/webhooks/h","signatureHeader":"x-albedo-signature","signaturePrefix":"sha256=","revision":%s,"enabled":true},"message":"created"%s}}`, revision, secretField) +} + +func TestWebhookRevisionRejectsFractionalWireValue(t *testing.T) { + for _, revision := range []string{"1.0000000000000001", "1.5"} { + t.Run(revision, func(t *testing.T) { + conn, transport := mutationConnection(webhookReceipt(revision, `,"secret":"generated"`), 200) + result, err := ExecuteCommand(context.Background(), conn, "s", map[string]any{ + "name": "/webhooks", "args": map[string]string{"action": "create", "details": "notes"}, + }) + uncertainty, ok := errors.AsType[*UncertainOutcomeError](err) + if !ok { + t.Fatalf("missing uncertainty: %v", err) + } + protocol, ok := errors.AsType[*ProtocolError](uncertainty) + if !ok || protocol.Field != "revision" { + t.Fatalf("missing revision protocol error: %v", err) + } + if result.Webhooks != nil || transport.calls != 1 { + t.Fatalf("unconfirmed webhook or replay: %+v, calls=%d", result.Webhooks, transport.calls) + } + }) + } +} + +func TestCreateInGeneratedSecretRequired(t *testing.T) { + requests := map[string]map[string]any{ + "declared": {"name": "/webhooks", "args": map[string]string{"action": "create_in", "details": " s notes "}}, + "raw": {"name": "/webhooks", "arguments": " create_in s notes "}, + "empty_args": {"name": "/webhooks", "args": map[string]string{}, "arguments": "create_in s notes"}, + } + for name, body := range requests { + t.Run(name, func(t *testing.T) { + for _, secretField := range []string{"", `,"secret":null`, `,"secret":""`, `,"secret":false`} { + conn, transport := mutationConnection(webhookReceipt("1", secretField), 200) + result, err := ExecuteCommand(context.Background(), conn, "s", body) + uncertainty, ok := errors.AsType[*UncertainOutcomeError](err) + if !ok { + t.Fatalf("accepted generated receipt %s: %v", secretField, err) + } + protocol, ok := errors.AsType[*ProtocolError](uncertainty) + if !ok || protocol.Code != "invalid_response" || protocol.Field != "secret" { + t.Fatalf("missing protocol error: %v", err) + } + if result.Webhooks != nil || transport.calls != 1 { + t.Fatalf("unconfirmed webhook or replay: %+v, calls=%d", result.Webhooks, transport.calls) + } + } + conn, _ := mutationConnection(webhookReceipt("1", `,"secret":"generated"`), 200) + result, err := ExecuteCommand(context.Background(), conn, "s", body) + if err != nil || result.Webhooks == nil || result.Webhooks.Secret != "generated" { + t.Fatalf("valid generated receipt rejected: %+v, %v", result.Webhooks, err) + } + }) + } +} + +func TestCreateInSuppliedSecretReceipt(t *testing.T) { + for name, body := range map[string]map[string]any{ + "declared": {"name": "/webhooks", "args": map[string]string{"action": "create_in", "details": "s notes supplied-secret"}}, + "raw": {"name": "/webhooks", "arguments": "create_in s notes supplied-secret"}, + } { + t.Run(name, func(t *testing.T) { + conn, transport := mutationConnection(webhookReceipt("1", ""), 200) + result, err := ExecuteCommand(context.Background(), conn, "s", body) + if err != nil || result.Webhooks == nil || result.Webhooks.Hook == nil || result.Webhooks.Secret != "" { + t.Fatalf("supplied-secret receipt rejected: %+v, %v", result.Webhooks, err) + } + if result.Webhooks.Hook.Revision != 1 || transport.calls != 1 { + t.Fatalf("receipt changed or replayed: %+v, calls=%d", result.Webhooks, transport.calls) + } + }) + } +} diff --git a/cli/internal/daemon/mutations.go b/cli/internal/daemon/mutations.go new file mode 100644 index 000000000..e8be1711d --- /dev/null +++ b/cli/internal/daemon/mutations.go @@ -0,0 +1,571 @@ +package daemon + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "time" +) + +// ProtocolError identifies an invalid successful mutation response. +type ProtocolError struct { + Cause error + Code string + Operation string + Field string +} + +func (e *ProtocolError) Error() string { + return fmt.Sprintf("invalid response for %s (%s): %v", e.Operation, e.Field, e.Cause) +} +func (e *ProtocolError) Unwrap() error { return e.Cause } + +func invalidResponse(operation Operation, field string, cause error) error { + return uncertainOperation(operation, &ProtocolError{Code: "invalid_response", Operation: operation.Name, Field: field, Cause: cause}) +} + +type responseFieldError struct { + cause error + field string +} + +func (e *responseFieldError) Error() string { return e.field + ": " + e.cause.Error() } +func fieldError(field string) error { + return &responseFieldError{field: field, cause: errors.New("required field is missing or invalid")} +} + +// executeMutation validates only after requestBytes has finished authentication +// recovery. A malformed success can never enter the retry path. +func executeMutation(ctx context.Context, conn *Connection, operation Operation, statuses []int, decode func([]byte, int) error) error { + if conn == nil { + return errors.New("not connected to Albedo") + } + if ctx == nil { + ctx = context.Background() + } + reqCtx := ctx + if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > 20*time.Second { + var cancel context.CancelFunc + reqCtx, cancel = context.WithTimeout(ctx, 20*time.Second) + defer cancel() + } + status := 0 + body, err := requestBytes(reqCtx, conn, operation, responseLimits{successStatuses: statuses, status: &status, bodyBytes: 50 * 1024 * 1024, errorBytes: 64 * 1024}) + if err != nil { + return err + } + if err = decode(body, status); err != nil { + field := "" + if detail, ok := errors.AsType[*responseFieldError](err); ok { + field = detail.field + } else if detail, ok := errors.AsType[*json.UnmarshalTypeError](err); ok { + field = detail.Field + } + return invalidResponse(operation, field, err) + } + return nil +} + +func object(data []byte) (map[string]json.RawMessage, error) { + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil { + return nil, err + } + if fields == nil { + return nil, errors.New("expected an object") + } + return fields, nil +} +func required(fields map[string]json.RawMessage, key string, target any) error { + raw, ok := fields[key] + if !ok || string(raw) == "null" { + return fieldError(key) + } + if err := json.Unmarshal(raw, target); err != nil { + return &responseFieldError{field: key, cause: err} + } + return nil +} +func nullable(fields map[string]json.RawMessage, key string, target any) error { + raw, ok := fields[key] + if !ok { + return fieldError(key) + } + if err := json.Unmarshal(raw, target); err != nil { + return &responseFieldError{field: key, cause: err} + } + return nil +} +func decodeAck(data []byte, _ int) error { + var wire struct { + OK *bool `json:"ok"` + } + if err := json.Unmarshal(data, &wire); err != nil { + return err + } + if wire.OK == nil || !*wire.OK { + return fieldError("ok") + } + return nil +} +func acknowledge(ctx context.Context, conn *Connection, operation Operation) error { + return executeMutation(ctx, conn, operation, []int{http.StatusOK}, decodeAck) +} +func sessionPath(id, tail string) string { return "/sessions/" + url.PathEscape(id) + tail } + +func decodeSubmission(data []byte, _ int) (SendResult, error) { + var wire struct { + OK *bool `json:"ok"` + Queued *bool `json:"queued"` + } + if err := json.Unmarshal(data, &wire); err != nil { + return SendResult{}, err + } + if wire.OK == nil || !*wire.OK { + return SendResult{}, fieldError("ok") + } + if wire.Queued == nil { + return SendResult{}, fieldError("queued") + } + return SendResult{OK: *wire.OK, Queued: *wire.Queued}, nil +} +func Submit(ctx context.Context, conn *Connection, id string, payload map[string]any) (SendResult, error) { + var result SendResult + err := executeMutation(ctx, conn, Operation{Name: "submit message", Method: http.MethodPost, Path: sessionPath(id, "/events"), Body: payload, Policy: AuthRecovery}, []int{http.StatusAccepted}, func(body []byte, status int) error { + var err error + result, err = decodeSubmission(body, status) + return err + }) + return result, err +} +func decodeInterruption(data []byte, _ int) (bool, error) { + var wire struct { + Interrupted *bool `json:"interrupted"` + } + if err := json.Unmarshal(data, &wire); err != nil { + return false, err + } + if wire.Interrupted == nil { + return false, fieldError("interrupted") + } + return *wire.Interrupted, nil +} +func InterruptSession(ctx context.Context, conn *Connection, id string) (bool, error) { + var interrupted bool + err := executeMutation(ctx, conn, Operation{Name: "interrupt session", Method: http.MethodPost, Path: sessionPath(id, "/interrupt"), Body: map[string]any{}, Policy: AuthRecovery}, []int{http.StatusOK}, func(body []byte, status int) error { + var err error + interrupted, err = decodeInterruption(body, status) + return err + }) + return interrupted, err +} +func decodeSession(data []byte) (Session, error) { + var wire struct { + ID *string `json:"id"` + Title *string `json:"title"` + Workspace *string `json:"workspace"` + Model *string `json:"model"` + Protocol *string `json:"protocol"` + Provider *string `json:"provider"` + Effort json.RawMessage `json:"effort"` + LastAssistantAt json.RawMessage `json:"last_assistant_at"` + } + if err := json.Unmarshal(data, &wire); err != nil { + return Session{}, err + } + for _, field := range []struct { + value *string + name string + }{{wire.ID, "id"}, {wire.Title, "title"}, {wire.Workspace, "workspace"}, {wire.Model, "model"}, {wire.Protocol, "protocol"}, {wire.Provider, "provider"}} { + if field.value == nil { + return Session{}, fieldError(field.name) + } + } + if wire.Effort == nil { + return Session{}, fieldError("effort") + } + if wire.LastAssistantAt == nil { + return Session{}, fieldError("last_assistant_at") + } + var effort *string + if !bytes.Equal(bytes.TrimSpace(wire.Effort), []byte("null")) { + if err := json.Unmarshal(wire.Effort, &effort); err != nil { + return Session{}, &responseFieldError{field: "effort", cause: err} + } + } + session := Session{ID: *wire.ID, Title: *wire.Title, Workspace: *wire.Workspace, Model: *wire.Model, Protocol: *wire.Protocol, Provider: *wire.Provider} + if effort != nil { + session.Effort = *effort + } + if !bytes.Equal(bytes.TrimSpace(wire.LastAssistantAt), []byte("null")) { + if err := json.Unmarshal(wire.LastAssistantAt, &session.LastAssistantAt); err != nil { + return Session{}, &responseFieldError{field: "last_assistant_at", cause: err} + } + } + return session, nil +} +func mutateSession(ctx context.Context, conn *Connection, operation Operation, status int) (Session, error) { + var session Session + err := executeMutation(ctx, conn, operation, []int{status}, func(body []byte, _ int) error { + var err error + session, err = decodeSession(body) + return err + }) + return session, err +} +func CreateSession(ctx context.Context, conn *Connection, body map[string]string) (Session, error) { + return mutateSession(ctx, conn, Operation{Name: "create session", Method: http.MethodPost, Path: "/sessions", Body: body, Policy: AuthRecovery}, http.StatusCreated) +} +func RenameSession(ctx context.Context, conn *Connection, id, name string) (Session, error) { + return mutateSession(ctx, conn, Operation{Name: "rename session", Method: http.MethodPatch, Path: sessionPath(id, ""), Body: map[string]string{"name": name}, Policy: AuthRecovery}, http.StatusOK) +} +func ForkSession(ctx context.Context, conn *Connection, id string, body map[string]any) (Session, error) { + return mutateSession(ctx, conn, Operation{Name: "fork session", Method: http.MethodPost, Path: sessionPath(id, "/fork"), Body: body, Policy: AuthRecovery}, http.StatusCreated) +} + +type DeletionResult struct { + OK bool `json:"ok"` + Deleted int `json:"deleted"` +} + +func decodeDeletion(data []byte) (DeletionResult, error) { + var wire struct { + OK *bool `json:"ok"` + Deleted *int `json:"deleted"` + } + if err := json.Unmarshal(data, &wire); err != nil { + return DeletionResult{}, err + } + if wire.OK == nil || !*wire.OK { + return DeletionResult{}, fieldError("ok") + } + if wire.Deleted == nil || *wire.Deleted < 1 { + return DeletionResult{}, fieldError("deleted") + } + return DeletionResult{OK: *wire.OK, Deleted: *wire.Deleted}, nil +} +func DeleteSession(ctx context.Context, conn *Connection, id string, tree bool) (DeletionResult, error) { + path := sessionPath(id, "") + if tree { + path += "?tree=1" + } + var result DeletionResult + err := executeMutation(ctx, conn, Operation{Name: "delete session", Method: http.MethodDelete, Path: path, Policy: AuthRecovery}, []int{200}, func(body []byte, _ int) error { + var err error + result, err = decodeDeletion(body) + return err + }) + return result, err +} +func StopDaemon(ctx context.Context, conn *Connection) error { + return acknowledge(ctx, conn, Operation{Name: "stop daemon", Method: http.MethodPost, Path: "/shutdown", Body: map[string]any{}, Policy: NoRecovery}) +} + +type ModelSelection struct { + Provider string `json:"provider"` + Model string `json:"model"` + Protocol string `json:"protocol"` + Effort string `json:"effort"` +} + +func decodeModelSelection(data []byte) (ModelSelection, error) { + var wire struct { + Provider *string `json:"provider"` + Model *string `json:"model"` + Protocol *string `json:"protocol"` + Effort json.RawMessage `json:"effort"` + } + if err := json.Unmarshal(data, &wire); err != nil { + return ModelSelection{}, err + } + if wire.Provider == nil { + return ModelSelection{}, fieldError("provider") + } + if wire.Model == nil { + return ModelSelection{}, fieldError("model") + } + if wire.Protocol == nil { + return ModelSelection{}, fieldError("protocol") + } + if wire.Effort == nil { + return ModelSelection{}, fieldError("effort") + } + var effort *string + if !bytes.Equal(bytes.TrimSpace(wire.Effort), []byte("null")) { + if err := json.Unmarshal(wire.Effort, &effort); err != nil { + return ModelSelection{}, &responseFieldError{field: "effort", cause: err} + } + } + result := ModelSelection{Provider: *wire.Provider, Model: *wire.Model, Protocol: *wire.Protocol} + if effort != nil { + result.Effort = *effort + } + return result, nil +} +func SelectModel(ctx context.Context, conn *Connection, id string, body map[string]string) (ModelSelection, error) { + var result ModelSelection + err := executeMutation(ctx, conn, Operation{Name: "select model", Method: http.MethodPost, Path: sessionPath(id, "/model"), Body: body, Policy: AuthRecovery}, []int{200}, func(body []byte, _ int) error { + var err error + result, err = decodeModelSelection(body) + return err + }) + return result, err +} + +type ExtensionSummary struct { + Name string `json:"name"` + Description string `json:"description"` + Quarantined string `json:"quarantined"` + Tools []string `json:"tools"` + PythonModules []string `json:"python_modules"` + Requires []string `json:"requires"` + Plugins []string `json:"plugins"` + Enabled bool `json:"enabled"` + Context bool `json:"context"` + Overridden bool `json:"overridden"` + GlobalEnabled bool `json:"global_enabled"` +} + +func decodeExtensions(data []byte) ([]ExtensionSummary, error) { + type extensionWire struct { + Name *string `json:"name"` + Description *string `json:"description"` + Enabled *bool `json:"enabled"` + Context *bool `json:"context"` + Overridden *bool `json:"overridden"` + GlobalEnabled *bool `json:"global_enabled"` + Tools stringCollection `json:"tools"` + PythonModules stringCollection `json:"python_modules"` + Requires stringCollection `json:"requires"` + Plugins stringCollection `json:"plugins"` + Quarantined json.RawMessage `json:"quarantined"` + } + var wire []extensionWire + if err := json.Unmarshal(data, &wire); err != nil { + return nil, err + } + if wire == nil { + return nil, errors.New("expected an array") + } + summaries := make([]ExtensionSummary, 0, len(wire)) + for i, item := range wire { + missing := "" + switch { + case item.Name == nil: + missing = "name" + case item.Description == nil: + missing = "description" + case item.Tools == nil: + missing = "tools" + case item.PythonModules == nil: + missing = "python_modules" + case item.Requires == nil: + missing = "requires" + case item.Plugins == nil: + missing = "plugins" + case item.Enabled == nil: + missing = "enabled" + case item.Context == nil: + missing = "context" + case item.Overridden == nil: + missing = "overridden" + case item.GlobalEnabled == nil: + missing = "global_enabled" + case item.Quarantined == nil: + missing = "quarantined" + } + if missing != "" { + return nil, fieldError(fmt.Sprintf("extensions[%d].%s", i, missing)) + } + var quarantine *string + if !bytes.Equal(bytes.TrimSpace(item.Quarantined), []byte("null")) { + if err := json.Unmarshal(item.Quarantined, &quarantine); err != nil { + return nil, &responseFieldError{field: fmt.Sprintf("extensions[%d].quarantined", i), cause: err} + } + } + summary := ExtensionSummary{Name: *item.Name, Description: *item.Description, Tools: []string(item.Tools), PythonModules: []string(item.PythonModules), Requires: []string(item.Requires), Plugins: []string(item.Plugins), Enabled: *item.Enabled, Context: *item.Context, Overridden: *item.Overridden, GlobalEnabled: *item.GlobalEnabled} + if quarantine != nil { + summary.Quarantined = *quarantine + } + summaries = append(summaries, summary) + } + return summaries, nil +} +func SelectExtension(ctx context.Context, conn *Connection, id string, body map[string]any) ([]ExtensionSummary, error) { + var result []ExtensionSummary + err := executeMutation(ctx, conn, Operation{Name: "select extension", Method: http.MethodPost, Path: sessionPath(id, "/extensions"), Body: body, Policy: AuthRecovery}, []int{200}, func(body []byte, _ int) error { + var err error + result, err = decodeExtensions(body) + return err + }) + return result, err +} + +type Member struct { + Session string `json:"session"` + Parent string `json:"parent"` + Name string `json:"name"` + Depth int `json:"depth"` + Closed bool `json:"closed"` +} +type ChildResult struct { + Session Session `json:"session"` + Member Member `json:"member"` +} + +func decodeChild(data []byte) (ChildResult, error) { + fields, err := object(data) + if err != nil { + return ChildResult{}, err + } + var result ChildResult + raw, ok := fields["session"] + if !ok { + return result, fieldError("session") + } + result.Session, err = decodeSession(raw) + if err != nil { + return ChildResult{}, err + } + member, err := object(fields["member"]) + if err != nil { + return ChildResult{}, err + } + for _, field := range []struct { + target any + name string + }{{&result.Member.Session, "session"}, {&result.Member.Parent, "parent"}, {&result.Member.Name, "name"}, {&result.Member.Depth, "depth"}, {&result.Member.Closed, "closed"}} { + if err := required(member, field.name, field.target); err != nil { + return ChildResult{}, err + } + } + return result, nil +} +func CreateChild(ctx context.Context, conn *Connection, id string, body map[string]any) (ChildResult, error) { + var result ChildResult + err := executeMutation(ctx, conn, Operation{Name: "create child", Method: http.MethodPost, Path: sessionPath(id, "/children"), Body: body, Policy: AuthRecovery}, []int{201}, func(body []byte, _ int) error { + var err error + result, err = decodeChild(body) + return err + }) + return result, err +} + +type ReloadResult struct { + Reloaded string `json:"reloaded"` + Message string `json:"message"` + Warning string `json:"warning"` +} + +func decodeReload(data []byte, _ int) (ReloadResult, error) { + var wire struct { + Reloaded *string `json:"reloaded"` + Message json.RawMessage `json:"message"` + Warning json.RawMessage `json:"warning"` + } + if err := json.Unmarshal(data, &wire); err != nil { + return ReloadResult{}, err + } + if wire.Reloaded == nil || *wire.Reloaded != "session" { + return ReloadResult{}, fieldError("reloaded") + } + result := ReloadResult{Reloaded: *wire.Reloaded} + if (wire.Message == nil) == (wire.Warning == nil) { + return ReloadResult{}, fieldError("message") + } + raw, target := wire.Message, &result.Message + field := "message" + if raw == nil { + raw, target, field = wire.Warning, &result.Warning, "warning" + } + if string(raw) == "null" { + return ReloadResult{}, fieldError(field) + } + if err := json.Unmarshal(raw, target); err != nil { + return ReloadResult{}, &responseFieldError{field: field, cause: err} + } + return result, nil +} +func reloadSettings(ctx context.Context, conn *Connection, operation Operation) (ReloadResult, error) { + var result ReloadResult + err := executeMutation(ctx, conn, operation, []int{200}, func(data []byte, status int) error { + var err error + result, err = decodeReload(data, status) + return err + }) + return result, err +} +func decodeUI(data []byte, _ int) (UIPreferences, error) { + var wire struct { + Opens *map[string]*int `json:"opens"` + Pinned *stringCollection `json:"pinned"` + Archived *stringCollection `json:"archived"` + Thinking *bool `json:"thinking"` + Tools *bool `json:"tools"` + } + if err := json.Unmarshal(data, &wire); err != nil { + return UIPreferences{}, err + } + if wire.Opens == nil { + return UIPreferences{}, fieldError("opens") + } + if wire.Pinned == nil { + return UIPreferences{}, fieldError("pinned") + } + if wire.Archived == nil { + return UIPreferences{}, fieldError("archived") + } + if wire.Thinking == nil { + return UIPreferences{}, fieldError("thinking") + } + if wire.Tools == nil { + return UIPreferences{}, fieldError("tools") + } + opens := make(map[string]int, len(*wire.Opens)) + for id, count := range *wire.Opens { + if count == nil { + return UIPreferences{}, fieldError("opens." + id) + } + opens[id] = *count + } + return UIPreferences{Opens: opens, Pinned: []string(*wire.Pinned), Archived: []string(*wire.Archived), Thinking: *wire.Thinking, Tools: *wire.Tools}, nil +} +func mutateUI(ctx context.Context, conn *Connection, operation Operation) (UIPreferences, error) { + var result UIPreferences + err := executeMutation(ctx, conn, operation, []int{200}, func(data []byte, status int) error { + var err error + result, err = decodeUI(data, status) + return err + }) + return result, err +} + +// stringCollection rejects null entries rather than decoding them as empty strings. +type stringCollection []string + +func (values *stringCollection) UnmarshalJSON(data []byte) error { + if bytes.Equal(bytes.TrimSpace(data), []byte("[]")) { + *values = stringCollection{} + return nil + } + var wire []*string + if err := json.Unmarshal(data, &wire); err != nil { + return err + } + if wire == nil { + return errors.New("expected a string array") + } + result := make(stringCollection, len(wire)) + for i, value := range wire { + if value == nil { + return errors.New("string array contains null") + } + result[i] = *value + } + *values = result + return nil +} diff --git a/cli/internal/daemon/mutations_test.go b/cli/internal/daemon/mutations_test.go new file mode 100644 index 000000000..7ed493be6 --- /dev/null +++ b/cli/internal/daemon/mutations_test.go @@ -0,0 +1,353 @@ +// Malformed mutation response combinations are client wire-parser invariants. +// A live daemon only emits valid shapes, so focused fixtures cover absent, +// nullable and conflicting fields that workflow scenarios cannot enumerate. +package daemon + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "os" + "slices" + "strings" + "testing" +) + +type mutationFixture struct { + Body json.RawMessage `json:"body"` + Status int `json:"status"` +} + +func mutationFixtures(t *testing.T) map[string]mutationFixture { + t.Helper() + data, err := os.ReadFile("../../../test/fixtures/mutation_responses.json") + if err != nil { + t.Fatal(err) + } + var fixtures map[string]mutationFixture + if err := json.Unmarshal(data, &fixtures); err != nil { + t.Fatal(err) + } + return fixtures +} + +type mutationTransport struct { + body string + calls int + status int +} + +func (transport *mutationTransport) RoundTrip(*http.Request) (*http.Response, error) { + transport.calls++ + return &http.Response{StatusCode: transport.status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(transport.body))}, nil +} +func mutationConnection(body string, status int) (*Connection, *mutationTransport) { + conn := NewConnection(ConnectionSnapshot{Port: 12345}, "") + transport := &mutationTransport{body: body, status: status} + conn.HTTPClient().Transport = transport + return conn, transport +} + +func TestMutationContracts(t *testing.T) { + fixtures := mutationFixtures(t) + decoders := map[string]func([]byte, int) error{ + "acknowledgement": decodeAck, + "submission": func(data []byte, status int) error { _, err := decodeSubmission(data, status); return err }, + "interruption": func(data []byte, status int) error { _, err := decodeInterruption(data, status); return err }, + "session": func(data []byte, _ int) error { _, err := decodeSession(data); return err }, + "child": func(data []byte, _ int) error { _, err := decodeChild(data); return err }, + "deletion": func(data []byte, _ int) error { _, err := decodeDeletion(data); return err }, + "model": func(data []byte, _ int) error { _, err := decodeModelSelection(data); return err }, + "extensions": func(data []byte, _ int) error { _, err := decodeExtensions(data); return err }, + "reload_message": func(data []byte, status int) error { _, err := decodeReload(data, status); return err }, + "reload_warning": func(data []byte, status int) error { _, err := decodeReload(data, status); return err }, + "ui": func(data []byte, status int) error { _, err := decodeUI(data, status); return err }, + "command_result": func(data []byte, status int) error { _, err := decodeCommand(data, status); return err }, + "command_submitted": func(data []byte, status int) error { _, err := decodeCommand(data, status); return err }, + } + contracts := []struct { + name string + required []string + nullable []string + numeric []string + }{ + {"acknowledgement", []string{"ok"}, nil, nil}, + {"submission", []string{"ok", "queued"}, nil, nil}, + {"interruption", []string{"interrupted"}, nil, nil}, + {"session", []string{"id", "title", "workspace", "provider", "model", "effort", "protocol", "last_assistant_at"}, []string{"effort", "last_assistant_at"}, []string{"last_assistant_at"}}, + {"child", []string{"session", "member"}, nil, nil}, + {"deletion", []string{"ok", "deleted"}, nil, []string{"deleted"}}, + {"model", []string{"provider", "model", "protocol", "effort"}, []string{"effort"}, nil}, + {"extensions", []string{"name", "description", "quarantined", "tools", "python_modules", "requires", "plugins", "enabled", "context", "overridden", "global_enabled"}, []string{"quarantined"}, nil}, + {"reload_message", []string{"reloaded", "message"}, nil, nil}, + {"reload_warning", []string{"reloaded", "warning"}, nil, nil}, + {"ui", []string{"thinking", "tools", "pinned", "archived", "opens"}, nil, nil}, + {"command_result", []string{"result"}, []string{"result"}, []string{"result"}}, + {"command_submitted", []string{"submitted"}, nil, nil}, + } + for _, contract := range contracts { + t.Run(contract.name, func(t *testing.T) { + fixture := fixtures[contract.name] + decode := decoders[contract.name] + if err := decode(fixture.Body, fixture.Status); err != nil { + t.Fatalf("valid fixture: %v", err) + } + for _, body := range []string{"", "{", "null", "[]", "42", "{}"} { + if contract.name == "extensions" && body == "[]" { + continue + } + if err := decode([]byte(body), fixture.Status); err == nil { + t.Errorf("accepted %s", body) + } + } + var fields map[string]json.RawMessage + raw := fixture.Body + if contract.name == "extensions" { + var entries []json.RawMessage + if err := json.Unmarshal(raw, &entries); err != nil { + t.Fatal(err) + } + raw = entries[0] + } + if err := json.Unmarshal(raw, &fields); err != nil { + t.Fatal(err) + } + encode := func() []byte { + body, err := json.Marshal(fields) + if err != nil { + t.Fatal(err) + } + if contract.name == "extensions" { + body = append(append([]byte{'['}, body...), ']') + } + return body + } + for _, key := range contract.required { + t.Run(key, func(t *testing.T) { + original := fields[key] + delete(fields, key) + if err := decode(encode(), fixture.Status); err == nil { + t.Error("accepted missing field") + } + fields[key] = json.RawMessage("null") + if err := decode(encode(), fixture.Status); (err == nil) != slices.Contains(contract.nullable, key) { + t.Errorf("nullable contract: %v", err) + } + fields[key] = json.RawMessage("42") + if err := decode(encode(), fixture.Status); (err == nil) != slices.Contains(contract.numeric, key) { + t.Errorf("numeric contract: %v", err) + } + fields[key] = original + }) + } + }) + } +} + +func TestInvalidMutationIsUncertainWithoutReplay(t *testing.T) { + for _, test := range []struct { + body string + status int + }{{"{}", 202}, {`{"ok":false,"queued":false}`, 202}, {`{"ok":true}`, 202}, {`{"ok":true,"queued":null}`, 202}, {`{"ok":true,"queued":false}`, 200}, {"", 204}, {"{", 202}, {`{"ok":true,"queued":"false"}`, 202}} { + conn, transport := mutationConnection(test.body, test.status) + _, err := Submit(context.Background(), conn, "s", map[string]any{"content": "hello"}) + uncertainty, ok := errors.AsType[*UncertainOutcomeError](err) + if !ok { + t.Fatalf("missing uncertainty for %s/%d: %v", test.body, test.status, err) + } + protocol, ok := errors.AsType[*ProtocolError](uncertainty) + if !ok || protocol.Code != "invalid_response" || protocol.Operation != "submit message" || protocol.Cause == nil { + t.Fatalf("missing protocol details: %v", err) + } + if strings.Contains(test.body, `"queued":"false"`) && protocol.Field != "queued" { + t.Fatalf("missing known field: %+v", protocol) + } + if transport.calls != 1 { + t.Fatalf("mutation executed %d times", transport.calls) + } + } + conn, transport := mutationConnection(`{"code":"invalid_submission","error":"bad"}`, 400) + _, err := Submit(context.Background(), conn, "s", map[string]any{}) + if api, ok := errors.AsType[*APIError](err); !ok || api.Code != "invalid_submission" { + t.Fatalf("non-2xx error changed: %v", err) + } + if _, ok := errors.AsType[*UncertainOutcomeError](err); ok { + t.Fatal("400 wrapped as uncertain") + } + if transport.calls != 1 { + t.Fatal("400 retried") + } +} + +func TestCommandAlternativesAndOpaqueResults(t *testing.T) { + for _, result := range []string{"null", "false", "42", `"text"`, "[]", `{"message":42}`, "{}", "9007199254740993", "1.0000000000000001", "1e400", `{"nested":[9007199254740993,1.0000000000000001]}`} { + conn, transport := mutationConnection(`{"result":`+result+`}`, 200) + got, err := ExecuteCommand(context.Background(), conn, "s", map[string]any{"name": "/extension"}) + if err != nil || got.Submitted || string(got.Result) != result { + t.Fatalf("opaque %s: %+v %v", result, got, err) + } + if transport.calls != 1 { + t.Fatal("replayed") + } + } + for _, test := range []struct { + body string + status int + }{{`{"result":null,"submitted":null}`, 200}, {`{"result":null,"submitted":false}`, 200}, {`{"submitted":false}`, 202}, {`{"submitted":null}`, 202}, {`{"submitted":true,"result":null}`, 202}} { + if _, err := decodeCommand([]byte(test.body), test.status); err == nil { + t.Errorf("accepted conflicting command %s", test.body) + } + } +} + +func TestMutationCollectionsRejectNullEntries(t *testing.T) { + fixture := mutationFixtures(t)["extensions"] + var entries []map[string]any + if err := json.Unmarshal(fixture.Body, &entries); err != nil { + t.Fatal(err) + } + for _, key := range []string{"tools", "python_modules", "requires", "plugins"} { + entries[0][key] = []any{nil} + data, _ := json.Marshal(entries) + if _, err := decodeExtensions(data); err == nil { + t.Errorf("accepted null in %s", key) + } + entries[0][key] = []any{} + } + if _, err := decodeUI([]byte(`{"thinking":false,"tools":false,"pinned":[],"archived":[],"opens":{"s":null}}`), 200); err == nil { + t.Fatal("accepted null open count") + } +} + +func TestAuthMutationContracts(t *testing.T) { + fixtures := mutationFixtures(t) + for _, family := range []string{"sign_in", "migration"} { + t.Run(family, func(t *testing.T) { + fixture := fixtures[family] + call := func(body string) error { + conn, transport := mutationConnection(body, fixture.Status) + var err error + if family == "sign_in" { + _, err = StartSignIn(context.Background(), conn, "offline") + } else { + _, err = TakeMigration(context.Background(), conn) + } + if transport.calls != 1 { + t.Fatal("mutation replayed") + } + return err + } + if err := call(string(fixture.Body)); err != nil { + t.Fatal(err) + } + malformed := []string{"", "{", "null", "[]", "{}"} + if family == "sign_in" { + malformed = append(malformed, `{"id":null,"url":"https://example.com"}`, `{"id":"","url":"https://example.com"}`, `{"id":42,"url":"https://example.com"}`, `{"id":"login","url":null}`, `{"id":"login","url":"/relative"}`, `{"id":"login","url":"https:"}`, `{"id":"login","url":"javascript:alert(1)"}`) + } else { + malformed = append(malformed, `{"moved":null}`, `{"moved":"file"}`, `{"moved":[null]}`, `{"moved":[42]}`) + } + for _, body := range malformed { + err := call(body) + if _, ok := errors.AsType[*ProtocolError](err); !ok { + t.Errorf("expected invalid_response for %s: %v", body, err) + } + if _, ok := errors.AsType[*UncertainOutcomeError](err); !ok { + t.Errorf("missing uncertainty for %s", body) + } + } + }) + } +} + +func TestSessionNullableFields(t *testing.T) { + sessionFixture := mutationFixtures(t)["session"] + var sessionFields map[string]json.RawMessage + if err := json.Unmarshal(sessionFixture.Body, &sessionFields); err != nil { + t.Fatal(err) + } + sessionFields["effort"] = json.RawMessage(`"high"`) + sessionFields["last_assistant_at"] = json.RawMessage(`42`) + sessionData, _ := json.Marshal(sessionFields) + session, err := decodeSession(sessionData) + if err != nil || session.Effort != "high" || session.LastAssistantAt == nil || *session.LastAssistantAt != 42 { + t.Fatalf("present nullable session values rejected: %+v %v", session, err) + } +} + +func TestChildMemberCompleteness(t *testing.T) { + fixture := mutationFixtures(t)["child"] + var fields map[string]json.RawMessage + if err := json.Unmarshal(fixture.Body, &fields); err != nil { + t.Fatal(err) + } + var member map[string]json.RawMessage + if err := json.Unmarshal(fields["member"], &member); err != nil { + t.Fatal(err) + } + for _, key := range []string{"session", "parent", "name", "depth", "closed"} { + value := member[key] + delete(member, key) + fields["member"], _ = json.Marshal(member) + body, _ := json.Marshal(fields) + if _, err := decodeChild(body); err == nil { + t.Errorf("accepted child member without %s", key) + } + member[key] = value + } +} + +func TestDeletionRequiresPositiveIntegerCount(t *testing.T) { + for _, body := range []string{`{"ok":true,"deleted":0}`, `{"ok":true,"deleted":-1}`, `{"ok":true,"deleted":1.5}`, `{"ok":false,"deleted":1}`} { + if _, err := decodeDeletion([]byte(body)); err == nil { + t.Errorf("accepted deletion %s", body) + } + } +} + +func TestReloadRequiresOneOutcome(t *testing.T) { + for _, body := range []string{`{"reloaded":"session","message":"done","warning":"partial"}`, `{"reloaded":"other","message":"done"}`, `{"reloaded":"session","warning":null}`} { + if _, err := decodeReload([]byte(body), 200); err == nil { + t.Errorf("accepted reload %s", body) + } + } +} + +func TestInterpretedCommandContracts(t *testing.T) { + for _, test := range []struct { + name string + result string + }{ + {"/model", `{"model":"selected"}`}, + {"/effort", `{"effort":null,"available":[null],"message":"levels"}`}, + {"/webhooks", `{"session":"s","agentManagement":false,"hooks":[{}]}`}, + {"/page", `{"page":{"title":"title","summary":"","empty":"","rows":[{"id":"i","text":"t","badge":"","tone":"plain"}],"actions":[],"glance":null}}`}, + } { + conn, transport := mutationConnection(`{"result":`+test.result+`}`, 200) + var err error + if test.name == "/page" { + _, err = ExecutePageCommand(context.Background(), conn, "s", map[string]any{"name": test.name}) + } else { + _, err = ExecuteCommand(context.Background(), conn, "s", map[string]any{"name": test.name}) + } + if _, ok := errors.AsType[*ProtocolError](err); !ok { + t.Errorf("accepted interpreted %s result: %v", test.name, err) + } + if transport.calls != 1 { + t.Fatal("replayed interpreted command") + } + } + for _, body := range []map[string]any{{"name": "/effort", "args": map[string]string{"level": "high"}}, {"name": "/effort", "arguments": "high"}} { + conn, _ := mutationConnection(`{"result":{"effort":"high","message":"set"}}`, 200) + result, err := ExecuteCommand(context.Background(), conn, "s", body) + if err != nil || result.Effort == nil || result.Effort.Effort != "high" { + t.Fatalf("effort selection rejected: %+v %v", result, err) + } + } + conn, _ := mutationConnection(`{"result":{"message":"enabled"}}`, 200) + result, err := ExecuteCommand(context.Background(), conn, "s", map[string]any{"name": "/webhooks", "arguments": "agent_on"}) + if err != nil || result.Webhooks == nil || result.Webhooks.Message != "enabled" || result.Message != "enabled" { + t.Fatalf("webhook raw arguments rejected: %+v %v", result, err) + } +} diff --git a/cli/internal/daemon/pages.go b/cli/internal/daemon/pages.go new file mode 100644 index 000000000..eee7cd54e --- /dev/null +++ b/cli/internal/daemon/pages.go @@ -0,0 +1,45 @@ +package daemon + +type PageTone string + +const ( + TonePlain PageTone = "plain" + ToneActive PageTone = "active" + ToneWarning PageTone = "warning" + ToneMuted PageTone = "muted" +) + +type PageRow struct { + ID string `json:"id"` + Text string `json:"text"` + Badge string `json:"badge"` + Tone PageTone `json:"tone"` + Detail string `json:"detail,omitempty"` +} + +type PageAction struct { + Key string `json:"key"` + Label string `json:"label"` + Run string `json:"run"` + Input string `json:"input"` // "none" | "text" | "secret" | "choice" | "value" + Prompt string `json:"prompt,omitempty"` + Value string `json:"value,omitempty"` + Options []string `json:"options,omitempty"` + Row bool `json:"row"` + Confirm bool `json:"confirm"` + Prefill bool `json:"prefill,omitempty"` +} + +type PageGlance struct { + Title string `json:"title"` + Rows []PageRow `json:"rows"` +} + +type PageDocument struct { + Glance *PageGlance `json:"glance,omitempty"` + Title string `json:"title"` + Summary string `json:"summary"` + Empty string `json:"empty"` + Rows []PageRow `json:"rows"` + Actions []PageAction `json:"actions"` +} diff --git a/cli/internal/daemon/settings.go b/cli/internal/daemon/settings.go index a386e4cc4..a67a0bce5 100644 --- a/cli/internal/daemon/settings.go +++ b/cli/internal/daemon/settings.go @@ -37,26 +37,25 @@ func ProviderProfiles(ctx context.Context, conn *Connection) (config.Profiles, e } func SaveProvider(ctx context.Context, conn *Connection, name string, profile config.Settings) error { - _, err := RequestOperation[acknowledged](ctx, conn, Operation{Name: "save provider", Method: http.MethodPut, Path: "/settings/providers/" + url.PathEscape(name), Body: profile, Policy: AuthRecovery}) + err := acknowledge(ctx, conn, Operation{Name: "save provider", Method: http.MethodPut, Path: "/settings/providers/" + url.PathEscape(name), Body: profile, Policy: AuthRecovery}) return err } func DeleteProvider(ctx context.Context, conn *Connection, name string) error { - _, err := RequestOperation[acknowledged](ctx, conn, Operation{Name: "delete provider", Method: http.MethodDelete, Path: "/settings/providers/" + url.PathEscape(name), Body: nil, Policy: AuthRecovery}) + err := acknowledge(ctx, conn, Operation{Name: "delete provider", Method: http.MethodDelete, Path: "/settings/providers/" + url.PathEscape(name), Body: nil, Policy: AuthRecovery}) return err } -func SetCapability(ctx context.Context, conn *Connection, session, kind, name, scope string, enabled *bool) error { - _, err := RequestOperation[acknowledged](ctx, conn, Operation{Name: "set capability", Method: http.MethodPost, Path: "/sessions/" + url.PathEscape(session) + "/settings/capabilities", Body: struct { +func SetCapability(ctx context.Context, conn *Connection, session, kind, name, scope string, enabled *bool) (ReloadResult, error) { + return reloadSettings(ctx, conn, Operation{Name: "set capability", Method: http.MethodPost, Path: "/sessions/" + url.PathEscape(session) + "/settings/capabilities", Body: struct { Enabled *bool `json:"enabled"` Kind string `json:"kind"` Name string `json:"name"` Scope string `json:"scope"` }{Kind: kind, Name: name, Scope: scope, Enabled: enabled}, Policy: AuthRecovery}) - return err } -func SaveMCP(ctx context.Context, conn *Connection, session, name string, server *config.MCPServer, secrets MCPSecretsPatch) error { +func SaveMCP(ctx context.Context, conn *Connection, session, name string, server *config.MCPServer, secrets MCPSecretsPatch) (ReloadResult, error) { path := "/sessions/" + url.PathEscape(session) + "/settings/mcp/" + url.PathEscape(name) method := http.MethodPut var body any = struct { @@ -66,20 +65,19 @@ func SaveMCP(ctx context.Context, conn *Connection, session, name string, server if server == nil { method, body = http.MethodDelete, nil } - _, err := RequestOperation[acknowledged](ctx, conn, Operation{Name: "save MCP", Method: method, Path: path, Body: body, Policy: AuthRecovery}) - return err + return reloadSettings(ctx, conn, Operation{Name: "save MCP", Method: method, Path: path, Body: body, Policy: AuthRecovery}) } func PatchUI(ctx context.Context, conn *Connection, patch map[string]bool) (UIPreferences, error) { - return RequestOperation[UIPreferences](ctx, conn, Operation{Name: "patch u i", Method: http.MethodPatch, Path: "/settings/ui", Body: patch, Policy: AuthRecovery}) + return mutateUI(ctx, conn, Operation{Name: "patch u i", Method: http.MethodPatch, Path: "/settings/ui", Body: patch, Policy: AuthRecovery}) } func PatchSessionUI(ctx context.Context, conn *Connection, session string, patch map[string]bool) (UIPreferences, error) { - return RequestOperation[UIPreferences](ctx, conn, Operation{Name: "patch session u i", Method: http.MethodPatch, Path: "/settings/ui/sessions/" + url.PathEscape(session), Body: patch, Policy: AuthRecovery}) + return mutateUI(ctx, conn, Operation{Name: "patch session u i", Method: http.MethodPatch, Path: "/settings/ui/sessions/" + url.PathEscape(session), Body: patch, Policy: AuthRecovery}) } // RecordOpen is never replayed after transport loss. The server may have already // incremented the count even when its response did not reach us. func RecordOpen(ctx context.Context, conn *Connection, session string) (UIPreferences, error) { - return RequestOperation[UIPreferences](ctx, conn, Operation{Name: "record open", Method: http.MethodPost, Path: "/settings/ui/sessions/" + url.PathEscape(session) + "/open", Body: nil, Policy: NoRecovery}) + return mutateUI(ctx, conn, Operation{Name: "record open", Method: http.MethodPost, Path: "/settings/ui/sessions/" + url.PathEscape(session) + "/open", Body: nil, Policy: NoRecovery}) } diff --git a/cli/internal/tui/agents_view.go b/cli/internal/tui/agents_view.go index 8be912a7e..8cae9b06b 100644 --- a/cli/internal/tui/agents_view.go +++ b/cli/internal/tui/agents_view.go @@ -523,10 +523,7 @@ func (m AgentsViewModel) below(id string) int { func (m AgentsViewModel) deleteCmd(id string) tea.Cmd { conn, gen, name := m.Conn, m.Gen, m.label(id, "") return func() tea.Msg { - path := fmt.Sprintf("/sessions/%s?tree=1", url.PathEscape(id)) - res, err := daemon.RequestOperation[struct { - Deleted int `json:"deleted"` - }](context.Background(), conn, daemon.Operation{Name: "delete", Method: http.MethodDelete, Path: path, Body: nil, Policy: daemon.AuthRecovery}) + res, err := daemon.DeleteSession(context.Background(), conn, id, true) if err != nil { return agentsSentMsg{Gen: gen, Action: "delete " + name, Err: err} } @@ -537,8 +534,7 @@ func (m AgentsViewModel) deleteCmd(id string) tea.Cmd { func (m AgentsViewModel) sendCmd(id, text string) tea.Cmd { conn, gen, target := m.Conn, m.Gen, m.label(id, "agent") return func() tea.Msg { - path := fmt.Sprintf("/sessions/%s/events", url.PathEscape(id)) - _, err := daemon.RequestOperation[map[string]any](context.Background(), conn, daemon.Operation{Name: "send", Method: http.MethodPost, Path: path, Body: map[string]any{"content": text}, Policy: daemon.AuthRecovery}) + _, err := daemon.Submit(context.Background(), conn, id, map[string]any{"content": text}) return agentsSentMsg{Gen: gen, Action: "send a message to " + target, Err: err} } } @@ -549,8 +545,7 @@ func (m AgentsViewModel) spawnCmd(parent, name, task string) tea.Cmd { if name == "" || task == "" { return agentsSentMsg{Gen: gen, Action: "start an agent", Err: errors.New("use /spawn ")} } - path := fmt.Sprintf("/sessions/%s/children", url.PathEscape(parent)) - _, err := daemon.RequestOperation[map[string]any](context.Background(), conn, daemon.Operation{Name: "spawn", Method: http.MethodPost, Path: path, Body: map[string]any{"name": name, "task": task}, Policy: daemon.AuthRecovery}) + _, err := daemon.CreateChild(context.Background(), conn, parent, map[string]any{"name": name, "task": task}) if err != nil { return agentsSentMsg{Gen: gen, Action: "start " + name, Err: err} } diff --git a/cli/internal/tui/app.go b/cli/internal/tui/app.go index dca81225e..11a09c765 100644 --- a/cli/internal/tui/app.go +++ b/cli/internal/tui/app.go @@ -60,24 +60,23 @@ type commandCatalogLoadedMsg struct { } type modelChangedMsg struct { - Err error - Model string - Provider string - Protocol string - Effort string - Gen int -} - -type commandExecutedMsg struct { + Selection *daemon.ModelSelection Err error - Name string - Message string - Effort string SessionID string - Available []string Gen int } +type commandExecutedMsg struct { + Err error + Name string + Message string + Effort string + SessionID string + Available []string + Gen int + EffortChanged bool +} + type glancesPolledMsg struct { Err error Glances []PageGlance @@ -235,8 +234,7 @@ func (m *AppModel) renameSessionCmd(rename SessionRenameMsg) tea.Cmd { if conn == nil { return sessionRenamedMsg{SessionRenameMsg: rename, Err: errors.New("daemon connection unavailable")} } - path := "/sessions/" + url.PathEscape(rename.ID) - s, err := daemon.RequestOperation[daemon.Session](context.Background(), conn, daemon.Operation{Name: "rename session", Method: http.MethodPatch, Path: path, Body: map[string]string{"name": rename.Name}, Policy: daemon.AuthRecovery}) + s, err := daemon.RenameSession(context.Background(), conn, rename.ID, rename.Name) return sessionRenamedMsg{SessionRenameMsg: rename, Session: s, Err: err} } } @@ -247,7 +245,7 @@ func (m *AppModel) deleteSessionCmd(id string) tea.Cmd { if conn == nil { return sessionDeletedMsg{ID: id, Err: errors.New("daemon connection unavailable")} } - _, err := daemon.RequestOperation[struct{}](context.Background(), conn, daemon.Operation{Name: "delete session", Method: http.MethodDelete, Path: "/sessions/" + url.PathEscape(id) + "?tree=1", Body: nil, Policy: daemon.AuthRecovery}) + _, err := daemon.DeleteSession(context.Background(), conn, id, true) return sessionDeletedMsg{ID: id, Err: err} } } @@ -265,7 +263,7 @@ func (m *AppModel) createSessionCmd(gen int, workspace string) tea.Cmd { if conn == nil { return sessionCreatedMsg{Err: errors.New("daemon connection unavailable"), Gen: gen} } - s, err := daemon.RequestOperation[daemon.Session](context.Background(), conn, daemon.Operation{Name: "create session", Method: http.MethodPost, Path: "/sessions", Body: map[string]string{"workspace": workspace}, Policy: daemon.AuthRecovery}) + s, err := daemon.CreateSession(context.Background(), conn, map[string]string{"workspace": workspace}) return sessionCreatedMsg{Session: s, Err: err, Gen: gen} } } @@ -317,16 +315,15 @@ func (m *AppModel) changeModelCmd(model, provider, effort string, raiseCap *bool } return func() tea.Msg { if conn == nil || !hasSession { - return modelChangedMsg{Err: errors.New("no active session or connection"), Gen: gen} + return modelChangedMsg{Err: errors.New("no active session or connection"), SessionID: sessionID, Gen: gen} } if provider != "" && provider != currentProvider { if err := daemon.CheckCapability(context.Background(), conn, "session_provider", "to switch providers"); err != nil { - return modelChangedMsg{Err: err, Gen: gen} + return modelChangedMsg{Err: err, SessionID: sessionID, Gen: gen} } } - path := fmt.Sprintf("/sessions/%s/commands", url.PathEscape(sessionID)) args := map[string]string{"model": model} if provider != "" { args["provider"] = provider @@ -339,47 +336,25 @@ func (m *AppModel) changeModelCmd(model, provider, effort string, raiseCap *bool "args": args, } - res, err := daemon.RequestOperation[map[string]any](context.Background(), conn, daemon.Operation{Name: "change model", Method: http.MethodPost, Path: path, Body: body, Policy: daemon.AuthRecovery}) + res, err := daemon.ExecuteCommand(context.Background(), conn, sessionID, body) if err != nil { - return modelChangedMsg{Err: err, Gen: gen} + return modelChangedMsg{Err: err, SessionID: sessionID, Gen: gen} } - // The cap follows the switch, so a failed switch changes nothing. + changed := modelChangedMsg{Selection: res.Model, SessionID: sessionID, Gen: gen} + // Keep the confirmed switch if the following cap update fails. if saveCap { state := "off" if capEnabled { state = "on" } - capBody := map[string]any{"name": "/raise-cap", "args": map[string]string{"state": state, "model": model}} - if _, err := daemon.RequestOperation[map[string]any](context.Background(), conn, daemon.Operation{Name: "save context cap", Method: http.MethodPost, Path: path, Body: capBody, Policy: daemon.AuthRecovery}); err != nil { - return modelChangedMsg{Err: fmt.Errorf("switched model; context cap update: %w", err), Gen: gen} + capBody := map[string]any{"name": "/raise-cap", "args": map[string]string{"state": state, "model": res.Model.Model}} + if _, err := daemon.ExecuteCommand(context.Background(), conn, sessionID, capBody); err != nil { + changed.Err = fmt.Errorf("switched model; context cap update: %w", err) + return changed } } - newModel, newProvider := model, provider - var newProtocol, newEffort string - - if r, ok := res["result"].(map[string]any); ok { - if s, _ := r["model"].(string); s != "" { - newModel = s - } - if s, _ := r["provider"].(string); s != "" { - newProvider = s - } - if s, _ := r["protocol"].(string); s != "" { - newProtocol = s - } - if s, ok := r["effort"].(string); ok { - newEffort = s - } - } - - return modelChangedMsg{ - Model: newModel, - Provider: newProvider, - Protocol: newProtocol, - Effort: newEffort, - Gen: gen, - } + return changed } } @@ -394,46 +369,31 @@ func (m *AppModel) executeCommandCmd(name, args string, gen int) tea.Cmd { return commandExecutedMsg{Name: name, Err: errors.New("no active session or connection"), Gen: gen} } - path := fmt.Sprintf("/sessions/%s/commands", url.PathEscape(sessionID)) body := map[string]any{"name": name} if args != "" { body["arguments"] = args } - res, err := daemon.RequestOperation[map[string]any](context.Background(), conn, daemon.Operation{Name: "execute command", Method: http.MethodPost, Path: path, Body: body, Policy: daemon.AuthRecovery}) + res, err := daemon.ExecuteCommand(context.Background(), conn, sessionID, body) if err != nil { return commandExecutedMsg{Name: name, Err: err, Gen: gen} } msg := fmt.Sprintf("%s done", name) var newEffort string - if res != nil { - if r, ok := res["result"].(map[string]any); ok { - var available []string - if name == "/effort" && args == "" { - if levels, ok := r["available"].([]any); ok { - for _, level := range levels { - if text, ok := level.(string); ok { - available = append(available, text) - } - } - } - } - if len(available) > 0 { - return commandExecutedMsg{Name: name, Available: available, SessionID: sessionID, Gen: gen} - } - if s, _ := r["effort"].(string); s != "" { - newEffort = s - } - if s, _ := r["message"].(string); s != "" { - msg = s - } - } else if s, _ := res["message"].(string); s != "" { - msg = s + if res.Effort != nil { + if args == "" { + return commandExecutedMsg{Name: name, Available: res.Effort.Available, SessionID: sessionID, Gen: gen} } + newEffort = res.Effort.Effort + if res.Effort.Message != "" { + msg = res.Effort.Message + } + } else if res.Message != "" { + msg = res.Message } - return commandExecutedMsg{Name: name, Message: msg, Effort: newEffort, Gen: gen} + return commandExecutedMsg{Name: name, Message: msg, Effort: newEffort, EffortChanged: res.Effort != nil, SessionID: sessionID, Gen: gen} } } @@ -466,20 +426,15 @@ func (m *AppModel) pollGlancesCmd(gen int) tea.Cmd { return glancesPolledMsg{Gen: gen} } - path := fmt.Sprintf("/sessions/%s/commands", url.PathEscape(sessionID)) var glances []PageGlance for _, name := range pageNames { body := map[string]any{"name": name, "args": map[string]string{}} - res, err := daemon.RequestOperation[map[string]any](context.Background(), conn, daemon.Operation{Name: "poll glances", Method: http.MethodPost, Path: path, Body: body, Policy: daemon.AuthRecovery}) + res, err := daemon.ExecutePageCommand(context.Background(), conn, sessionID, body) if err != nil { - continue - } - target := res - if res["result"] != nil { - target, _ = res["result"].(map[string]any) + return glancesPolledMsg{Gen: gen, Err: err} } - if doc, err := parsePageDocument(target); err == nil && doc != nil && doc.Glance != nil { - glances = append(glances, *doc.Glance) + if res.Page.Glance != nil { + glances = append(glances, *res.Page.Glance) } } @@ -717,6 +672,9 @@ func (m AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if msg.Open { if msg.Err != nil { m.Chat.AddError(msg.Err.Error()) + if _, uncertain := errors.AsType[*daemon.UncertainOutcomeError](msg.Err); uncertain { + return m, nil + } } return m, m.loadSettingsCmd(m.SettingsGen) } @@ -864,36 +822,30 @@ func (m AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { ) case modelChangedMsg: - if msg.Gen != m.ModelGen { + if msg.Gen != m.ModelGen || m.ActiveSession == nil || msg.SessionID != m.ActiveSession.ID { return m, nil } + if msg.Selection != nil { + selected := msg.Selection + m.ActiveSession.Model, m.Chat.Model = selected.Model, selected.Model + m.ActiveSession.Effort, m.Chat.Effort = selected.Effort, selected.Effort + m.ActiveSession.Provider, m.Chat.Provider = selected.Provider, selected.Provider + m.ActiveSession.Protocol = selected.Protocol + m.ModelPicker.Saving = false + if m.State == AppStateModelPicker { + m.State = AppStateChat + } + m.ClearNotices() + } if msg.Err != nil { + message := operationError(msg.Err, "Model settings error: ", "Model settings may have changed; check them before trying again.") if m.State == AppStateModelPicker { m.ModelPicker.Saving = false - m.ModelPicker.Error = msg.Err.Error() + m.ModelPicker.Error = message } else { - m.AddError("Model settings error: " + msg.Err.Error()) - } - return m, nil - } - if m.ActiveSession != nil { - if msg.Model != "" { - m.ActiveSession.Model = msg.Model - m.Chat.Model = msg.Model - } - m.ActiveSession.Effort = msg.Effort - m.Chat.Effort = msg.Effort - if msg.Provider != "" { - m.ActiveSession.Provider = msg.Provider - m.Chat.Provider = msg.Provider - } - if msg.Protocol != "" { - m.ActiveSession.Protocol = msg.Protocol + m.AddError(message) } } - m.ModelPicker.Saving = false - m.State = AppStateChat - m.ClearNotices() return m, nil case commandExecutedMsg: @@ -910,14 +862,17 @@ func (m AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil } m.AddNotice(msg.Message) - if msg.Effort != "" && m.ActiveSession != nil { + if msg.EffortChanged && m.ActiveSession != nil { m.ActiveSession.Effort = msg.Effort m.Chat.Effort = msg.Effort } return m, nil case glancesPolledMsg: - if msg.Gen == m.GlanceGen && msg.Err == nil { + if msg.Err != nil { + return m, nil + } + if msg.Gen == m.GlanceGen { m.Glances = msg.Glances m.Chat.Glances = msg.Glances m.Chat.SetSize(m.Width, m.Height) diff --git a/cli/internal/tui/app_commands_test.go b/cli/internal/tui/app_commands_test.go index 258f567d4..31c639ada 100644 --- a/cli/internal/tui/app_commands_test.go +++ b/cli/internal/tui/app_commands_test.go @@ -47,7 +47,7 @@ func TestModelChangeCapturesProviderAndCapBeforeExecution(t *testing.T) { {name: "cap fails", failCap: true}, } { t.Run(scenario.name, func(t *testing.T) { - var paths, names, capStates []string + var paths, names, capStates, capModels []string healthCalls := 0 conn := commandTestConnection(t, func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/health" { @@ -66,12 +66,13 @@ func TestModelChangeCapturesProviderAndCapBeforeExecution(t *testing.T) { names = append(names, body.Name) if body.Name == "/raise-cap" { capStates = append(capStates, body.Args["state"]) + capModels = append(capModels, body.Args["model"]) } if body.Name == "/model" && scenario.failSwitch || body.Name == "/raise-cap" && scenario.failCap { http.Error(w, `{"error":"refused"}`, http.StatusBadRequest) return } - _, _ = w.Write([]byte(`{"result":{"model":"chosen","provider":"new","effort":"high"}}`)) + _, _ = w.Write([]byte(`{"result":{"model":"resolved","provider":"new","protocol":"openai","effort":"high"}}`)) }) session := &daemon.Session{ID: "original", Provider: "old"} app := AppModel{Conn: conn, ActiveSession: session} @@ -81,7 +82,7 @@ func TestModelChangeCapturesProviderAndCapBeforeExecution(t *testing.T) { raiseCap = false app.Conn, app.ActiveSession, app.ModelGen = nil, nil, 8 msg := cmd().(modelChangedMsg) - if msg.Gen != 7 || (msg.Err != nil) != (scenario.failSwitch || scenario.failCap) { + if msg.Gen != 7 || msg.SessionID != "original" || (msg.Err != nil) != (scenario.failSwitch || scenario.failCap) { t.Fatalf("unexpected model result: %+v", msg) } if healthCalls != 1 { @@ -91,8 +92,8 @@ func TestModelChangeCapturesProviderAndCapBeforeExecution(t *testing.T) { wantPaths := []string{"/sessions/original/commands", "/sessions/original/commands"} if scenario.failSwitch { wantNames, wantPaths = wantNames[:1], wantPaths[:1] - } else if !reflect.DeepEqual(capStates, []string{"on"}) { - t.Fatalf("cap used changed input: %v", capStates) + } else if !reflect.DeepEqual(capStates, []string{"on"}) || !reflect.DeepEqual(capModels, []string{"resolved"}) { + t.Fatalf("cap used changed input or unconfirmed model: state=%v model=%v", capStates, capModels) } if !reflect.DeepEqual(names, wantNames) || !reflect.DeepEqual(paths, wantPaths) { t.Fatalf("requests changed target or order: paths=%v commands=%v", paths, names) @@ -111,7 +112,7 @@ func TestSessionCommandKeepsSessionWhileRequestIsRunning(t *testing.T) { } close(started) <-release - _, _ = w.Write([]byte(`{"result":{"available":["low","high"]}}`)) + _, _ = w.Write([]byte(`{"result":{"effort":null,"message":"","available":["low","high"]}}`)) }) // Release the handler before the server cleanup, including on test failure. t.Cleanup(releaseRequest) @@ -138,9 +139,10 @@ func TestGlancePollingCapturesPageNames(t *testing.T) { t.Error(err) } paths, names = append(paths, r.URL.Path), append(names, body.Name) - _ = json.NewEncoder(w).Encode(map[string]any{"page": map[string]any{ - "title": body.Name, "glance": map[string]any{"title": body.Name}, - }}) + _ = json.NewEncoder(w).Encode(map[string]any{"result": map[string]any{"page": map[string]any{ + "title": body.Name, "summary": "", "empty": "", "rows": []any{}, "actions": []any{}, + "glance": map[string]any{"title": body.Name, "rows": []any{}}, + }}}) }) pageFlag := true session := &daemon.Session{ID: "original"} @@ -178,7 +180,7 @@ func TestUIPatchCapturesValues(t *testing.T) { if err := json.NewDecoder(r.Body).Decode(&got); err != nil { t.Error(err) } - _, _ = w.Write([]byte(`{"thinking":true,"tools":false}`)) + _, _ = w.Write([]byte(`{"thinking":true,"tools":false,"pinned":[],"archived":[],"opens":{}}`)) }) app := AppModel{Conn: conn} patch := map[string]bool{"thinking": true, "tools": false} diff --git a/cli/internal/tui/capability_pages.go b/cli/internal/tui/capability_pages.go index 158a96749..b6fe313af 100644 --- a/cli/internal/tui/capability_pages.go +++ b/cli/internal/tui/capability_pages.go @@ -45,8 +45,9 @@ type capabilityLoadedMsg struct { ExtensionEnabled bool } type capabilitySavedMsg struct { - Err error - Gen int + Err error + Warning string + Gen int } type CapabilityPageDoneMsg struct{} type CapabilityPageChangedMsg struct{} @@ -170,8 +171,7 @@ func discoverInstructions(workspace string) []capabilityItem { func (m CapabilityPageModel) enableExtensionCmd(gen int) tea.Cmd { return func() tea.Msg { - path := fmt.Sprintf("/sessions/%s/extensions", url.PathEscape(m.SessionID)) - _, err := daemon.RequestOperation[[]ExtensionItem](context.Background(), m.Conn, daemon.Operation{Name: "enable extension", Method: http.MethodPost, Path: path, Body: map[string]any{"name": m.Kind, "enabled": true}, Policy: daemon.AuthRecovery}) + _, err := daemon.SelectExtension(context.Background(), m.Conn, m.SessionID, map[string]any{"name": m.Kind, "enabled": true}) return capabilitySavedMsg{Gen: gen, Err: err} } } @@ -183,8 +183,8 @@ func (m CapabilityPageModel) toggleCmd(item capabilityItem, gen int) tea.Cmd { scope = "global" } return func() tea.Msg { - err := daemon.SetCapability(context.Background(), m.Conn, m.SessionID, m.Kind, item.ID, scope, &next) - return capabilitySavedMsg{Gen: gen, Err: err} + result, err := daemon.SetCapability(context.Background(), m.Conn, m.SessionID, m.Kind, item.ID, scope, &next) + return capabilitySavedMsg{Gen: gen, Err: err, Warning: result.Warning} } } @@ -196,13 +196,15 @@ var mcpEnvName = regexp.MustCompile(`^[A-Za-z_][A-Za-z_0-9]*$`) // restored, so a half-configured server is never left behind. func (m CapabilityPageModel) saveMCPCmd(sub mcpSubmission, gen int) tea.Cmd { return func() tea.Msg { - return capabilitySavedMsg{Gen: gen, Err: daemon.SaveMCP(context.Background(), m.Conn, m.SessionID, sub.Name, &sub.Server, sub.Secrets)} + result, err := daemon.SaveMCP(context.Background(), m.Conn, m.SessionID, sub.Name, &sub.Server, sub.Secrets) + return capabilitySavedMsg{Gen: gen, Err: err, Warning: result.Warning} } } func (m CapabilityPageModel) deleteMCPCmd(name string, gen int) tea.Cmd { return func() tea.Msg { - return capabilitySavedMsg{Gen: gen, Err: daemon.SaveMCP(context.Background(), m.Conn, m.SessionID, name, nil, nil)} + result, err := daemon.SaveMCP(context.Background(), m.Conn, m.SessionID, name, nil, nil) + return capabilitySavedMsg{Gen: gen, Err: err, Warning: result.Warning} } } @@ -242,6 +244,9 @@ func (m CapabilityPageModel) Update(msg tea.Msg) (CapabilityPageModel, tea.Cmd) m.Form = nil m.ConfirmDelete = false m.Notice = "Saved. Session reloaded." + if msg.Warning != "" { + m.Notice = msg.Warning + } m.Loading, m.Generation = true, nextCapabilityGen() return m, tea.Batch(m.loadCmd(m.Generation), func() tea.Msg { return CapabilityPageChangedMsg{} }) case tea.PasteMsg: diff --git a/cli/internal/tui/extension_picker.go b/cli/internal/tui/extension_picker.go index 973d274b3..c92933e9f 100644 --- a/cli/internal/tui/extension_picker.go +++ b/cli/internal/tui/extension_picker.go @@ -13,23 +13,7 @@ import ( "github.com/charmbracelet/x/ansi" ) -type ExtensionItem struct { - Name string `json:"name"` - Description string `json:"description"` - // Quarantined is why the daemon will not run this extension; empty when - // it is usable. A quarantined extension cannot be toggled. - Quarantined string `json:"quarantined"` - Tools []string `json:"tools"` - PythonModules []string `json:"python_modules"` - Requires []string `json:"requires"` - Plugins []string `json:"plugins"` - Enabled bool `json:"enabled"` - Context bool `json:"context"` - // Overridden means this session has its own choice; otherwise it follows - // GlobalEnabled, the default for sessions without one. - Overridden bool `json:"overridden"` - GlobalEnabled bool `json:"global_enabled"` -} +type ExtensionItem = daemon.ExtensionSummary type ExtensionPickerDoneMsg struct{} type ExtensionPickerChangedMsg struct{} @@ -38,8 +22,6 @@ type extensionsLoadedMsg struct { Err error Extensions []ExtensionItem Gen int - // NoGlobal reports a daemon that predates global extension defaults. - NoGlobal bool } type extensionToggledMsg struct { @@ -57,7 +39,6 @@ type ExtensionPickerModel struct { // Session scopes changes to this session; the page opens on the global // defaults, so a session only diverges once a change is made here. Session bool - NoGlobal bool Confirming bool // Inheriting confirms dropping this session's choice instead of a toggle. Inheriting bool @@ -82,18 +63,9 @@ func (m ExtensionPickerModel) loadExtensionsCmd(gen int) tea.Cmd { return extensionsLoadedMsg{Err: errors.New("daemon connection unavailable"), Gen: gen} } - caps, err := daemon.Capabilities(context.Background(), m.Conn) - if err != nil { - return extensionsLoadedMsg{Err: err, Gen: gen} - } - if !slices.Contains(caps, "session_extensions") { - return extensionsLoadedMsg{Err: daemon.UpgradeNeeded("for /extensions"), Gen: gen} - } - noGlobal := !slices.Contains(caps, "global_extensions") - path := fmt.Sprintf("/sessions/%s/extensions", m.SessionID) items, err := daemon.RequestOperation[[]ExtensionItem](context.Background(), m.Conn, daemon.Operation{Name: "load extensions", Method: http.MethodGet, Path: path, Body: nil, Policy: daemon.ReadRecovery}) - return extensionsLoadedMsg{Extensions: items, Err: err, Gen: gen, NoGlobal: noGlobal} + return extensionsLoadedMsg{Extensions: items, Err: err, Gen: gen} } } @@ -104,16 +76,11 @@ func (m ExtensionPickerModel) changeExtensionCmd(name, scope string, enabled boo if m.Conn == nil { return extensionToggledMsg{Err: errors.New("daemon connection unavailable"), Gen: gen} } - path := fmt.Sprintf("/sessions/%s/extensions", m.SessionID) body := map[string]any{"name": name, "scope": scope} if scope != "inherit" { body["enabled"] = enabled } - if m.NoGlobal { - // Older daemons only know session choices. - body = map[string]any{"name": name, "enabled": enabled} - } - updated, err := daemon.RequestOperation[[]ExtensionItem](context.Background(), m.Conn, daemon.Operation{Name: "change extension", Method: http.MethodPost, Path: path, Body: body, Policy: daemon.AuthRecovery}) + updated, err := daemon.SelectExtension(context.Background(), m.Conn, m.SessionID, body) return extensionToggledMsg{Extensions: updated, Err: err, Gen: gen} } } @@ -140,10 +107,6 @@ func (m ExtensionPickerModel) Update(msg tea.Msg) (ExtensionPickerModel, tea.Cmd } m.Extensions = msg.Extensions m.Error = "" - m.NoGlobal = msg.NoGlobal - if m.NoGlobal { - m.Session = true - } if m.Cursor >= len(m.Extensions) { m.Cursor = max(0, len(m.Extensions)-1) } @@ -217,9 +180,7 @@ func (m ExtensionPickerModel) Update(msg tea.Msg) (ExtensionPickerModel, tea.Cmd m.Confirming = true } case "g": - if !m.NoGlobal { - m.Session = false - } + m.Session = false case "s": m.Session = true case "o": @@ -227,7 +188,7 @@ func (m ExtensionPickerModel) Update(msg tea.Msg) (ExtensionPickerModel, tea.Cmd return m, func() tea.Msg { return ChatOpenWebhooksPageMsg{} } } case "x": - if m.Session && !m.NoGlobal && m.Cursor < len(m.Extensions) && m.Extensions[m.Cursor].Overridden { + if m.Session && m.Cursor < len(m.Extensions) && m.Extensions[m.Cursor].Overridden { m.Error = "" m.Confirming, m.Inheriting = true, true } @@ -242,9 +203,6 @@ func (m ExtensionPickerModel) View() string { scope, note := "global defaults", "Sessions without their own choice use these defaults · s to change this session only" if m.Session { scope, note = "this session", "Changes here affect only this session · g to edit global defaults" - if m.NoGlobal { - note = "This version only supports choices for this session. Restart Albedo to use global defaults." - } } b.WriteString(titleRule(m.Width, brand("albedo")+" "+m.Styles.Muted.Render("/extensions"), m.Styles.Faint.Render(scope))) b.WriteByte('\n') @@ -380,7 +338,7 @@ func (m ExtensionPickerModel) View() string { keys := []hint{{"↑↓", "select"}, {"enter/space", "toggle"}} if !m.Session { keys = append(keys, hint{"s", "this session"}) - } else if !m.NoGlobal { + } else { keys = append(keys, hint{"x", "follow global"}, hint{"g", "global defaults"}) } keys = append(keys, hint{"esc", "return to chat"}) diff --git a/cli/internal/tui/model_change_test.go b/cli/internal/tui/model_change_test.go new file mode 100644 index 000000000..4221c0903 --- /dev/null +++ b/cli/internal/tui/model_change_test.go @@ -0,0 +1,121 @@ +// A confirmed model switch must survive its following cap failure. Controlled +// partial responses and stale deliveries cannot be produced deterministically +// by the healthy daemon, so these tests isolate the UI state transition. +package tui + +import ( + "errors" + "net/http" + "testing" + + "albedo/cli/internal/config" + "albedo/cli/internal/daemon" +) + +func TestModelChangeRetainsConfirmedSelectionWhenCapFails(t *testing.T) { + for _, status := range []int{http.StatusBadRequest, http.StatusOK} { + t.Run(http.StatusText(status), func(t *testing.T) { + requests := 0 + conn := commandTestConnection(t, func(w http.ResponseWriter, _ *http.Request) { + requests++ + if requests == 1 { + _, _ = w.Write([]byte(`{"result":{"model":"confirmed","provider":"provider","protocol":"openai","effort":null}}`)) + return + } + w.WriteHeader(status) + _, _ = w.Write([]byte(`{}`)) + }) + session := &daemon.Session{ID: "session", Model: "old", Provider: "old-provider", Effort: "high"} + app := NewAppModel(conn, config.Profiles{}, session, "", false, nil) + t.Cleanup(app.Chat.Close) + app.State, app.ModelPicker.Saving, app.ModelGen = AppStateModelPicker, true, 1 + raise := true + msg := app.changeModelCmd("requested", "", "", &raise, app.ModelGen)().(modelChangedMsg) + if msg.Err == nil || msg.Selection == nil { + t.Fatalf("lost confirmed switch or following failure: %+v", msg) + } + if status == http.StatusOK { + var uncertain *daemon.UncertainOutcomeError + var protocol *daemon.ProtocolError + if !errors.As(msg.Err, &uncertain) || !errors.As(msg.Err, &protocol) { + t.Fatalf("invalid cap response lost typed uncertainty: %v", msg.Err) + } + } + updated, cmd := app.Update(msg) + app = updated.(AppModel) + if cmd != nil || requests != 2 { + t.Fatalf("cap failure caused another operation: requests=%d command=%v", requests, cmd != nil) + } + if app.ActiveSession.Model != "confirmed" || app.Chat.Model != "confirmed" || app.ActiveSession.Provider != "provider" || app.Chat.Provider != "provider" || app.ActiveSession.Protocol != "openai" || app.ActiveSession.Effort != "" || app.Chat.Effort != "" { + t.Fatalf("did not apply confirmed switch: %+v", app.ActiveSession) + } + if app.State != AppStateChat || app.ModelPicker.Saving || len(app.Chat.Notices) != 1 { + t.Fatal("confirmed switch did not settle picker and surface the cap failure") + } + }) + } +} + +func TestModelChangeFailureDoesNotApplySelectionOrRaiseCap(t *testing.T) { + for _, status := range []int{http.StatusBadRequest, http.StatusOK} { + t.Run(http.StatusText(status), func(t *testing.T) { + requests := 0 + conn := commandTestConnection(t, func(w http.ResponseWriter, _ *http.Request) { + requests++ + w.WriteHeader(status) + _, _ = w.Write([]byte(`{}`)) + }) + session := &daemon.Session{ID: "session", Model: "old", Provider: "provider", Effort: "low"} + app := NewAppModel(conn, config.Profiles{}, session, "", false, nil) + t.Cleanup(app.Chat.Close) + app.State, app.ModelPicker.Saving, app.ModelGen = AppStateModelPicker, true, 1 + raise := true + msg := app.changeModelCmd("requested", "", "", &raise, app.ModelGen)().(modelChangedMsg) + updated, cmd := app.Update(msg) + app = updated.(AppModel) + if msg.Err == nil || msg.Selection != nil || requests != 1 || cmd != nil { + t.Fatalf("failed switch proceeded to cap or invented confirmation: %+v requests=%d", msg, requests) + } + if app.ActiveSession.Model != "old" || app.Chat.Model != "old" || app.ActiveSession.Effort != "low" || app.Chat.Effort != "low" || app.State != AppStateModelPicker || app.ModelPicker.Saving || app.ModelPicker.Error == "" { + t.Fatal("failed switch changed confirmed state or failed to settle picker") + } + }) + } +} + +func TestModelChangeIgnoresStaleSessionOrGeneration(t *testing.T) { + for _, scenario := range []struct { + name, sessionID string + generation int + }{ + {"session", "other", 1}, + {"generation", "session", 0}, + } { + t.Run(scenario.name, func(t *testing.T) { + app := NewAppModel(daemon.NewConnection(daemon.ConnectionSnapshot{Port: 1}, ""), config.Profiles{}, &daemon.Session{ID: "session", Model: "old"}, "", false, nil) + t.Cleanup(app.Chat.Close) + app.State, app.ModelPicker.Saving, app.ModelGen = AppStateModelPicker, true, 1 + updated, cmd := app.Update(modelChangedMsg{ + Selection: &daemon.ModelSelection{Model: "stale"}, + Err: errors.New("stale failure"), SessionID: scenario.sessionID, Gen: scenario.generation, + }) + app = updated.(AppModel) + if cmd != nil || app.ActiveSession.Model != "old" || app.Chat.Model != "old" || app.State != AppStateModelPicker || !app.ModelPicker.Saving || app.ModelPicker.Error != "" || len(app.Chat.Notices) != 0 { + t.Fatal("stale result changed current session, picker, or notices") + } + }) + } +} + +func TestModelChangePreservesScreenAfterLeavingPicker(t *testing.T) { + app := NewAppModel(daemon.NewConnection(daemon.ConnectionSnapshot{Port: 1}, ""), config.Profiles{}, &daemon.Session{ID: "session", Model: "old"}, "", false, nil) + t.Cleanup(app.Chat.Close) + app.State, app.ModelGen = AppStateSessionPicker, 1 + updated, cmd := app.Update(modelChangedMsg{ + Selection: &daemon.ModelSelection{Model: "confirmed"}, SessionID: "session", Gen: 1, + }) + app = updated.(AppModel) + if cmd != nil || app.ActiveSession.Model != "confirmed" || app.Chat.Model != "confirmed" || app.State != AppStateSessionPicker { + t.Fatal("confirmed switch failed to update its session or changed an unrelated screen") + } +} diff --git a/cli/internal/tui/page_secret_test.go b/cli/internal/tui/page_secret_test.go index 0313f2bee..a12fcc3ac 100644 --- a/cli/internal/tui/page_secret_test.go +++ b/cli/internal/tui/page_secret_test.go @@ -12,14 +12,9 @@ import ( ) func TestPageSecretInputIsMasked(t *testing.T) { - doc, err := parsePageDocument(map[string]any{"page": map[string]any{ - "title": "webhooks", "actions": []any{map[string]any{ - "key": "k", "label": "rotate", "run": "rotate_with_secret", "input": "secret", "prompt": "replacement", - }}, - }}) - if err != nil { - t.Fatal(err) - } + doc := &PageDocument{Title: "webhooks", Actions: []PageAction{ + {Key: "k", Label: "rotate", Run: "rotate_with_secret", Input: "secret", Prompt: "replacement"}, + }} m := NewPageViewModel(nil, "session", "/webhooks") m.Doc = doc m.Busy = false diff --git a/cli/internal/tui/page_view.go b/cli/internal/tui/page_view.go index 5db1a7e8a..05c1b858b 100644 --- a/cli/internal/tui/page_view.go +++ b/cli/internal/tui/page_view.go @@ -6,7 +6,6 @@ import ( "context" "errors" "fmt" - "net/http" "slices" "strings" @@ -16,49 +15,19 @@ import ( "github.com/charmbracelet/x/ansi" ) -type PageTone string +type PageTone = daemon.PageTone const ( - TonePlain PageTone = "plain" - ToneActive PageTone = "active" - ToneWarning PageTone = "warning" - ToneMuted PageTone = "muted" + TonePlain = daemon.TonePlain + ToneActive = daemon.ToneActive + ToneWarning = daemon.ToneWarning + ToneMuted = daemon.ToneMuted ) -type PageRow struct { - ID string `json:"id"` - Text string `json:"text"` - Badge string `json:"badge"` - Tone PageTone `json:"tone"` - Detail string `json:"detail,omitempty"` -} - -type PageAction struct { - Key string `json:"key"` - Label string `json:"label"` - Run string `json:"run"` - Input string `json:"input"` // "none" | "text" | "secret" | "choice" | "value" - Prompt string `json:"prompt,omitempty"` - Value string `json:"value,omitempty"` - Options []string `json:"options,omitempty"` - Row bool `json:"row"` - Confirm bool `json:"confirm"` - Prefill bool `json:"prefill,omitempty"` -} - -type PageGlance struct { - Title string `json:"title"` - Rows []PageRow `json:"rows"` -} - -type PageDocument struct { - Glance *PageGlance `json:"glance,omitempty"` - Title string `json:"title"` - Summary string `json:"summary"` - Empty string `json:"empty"` - Rows []PageRow `json:"rows"` - Actions []PageAction `json:"actions"` -} +type PageRow = daemon.PageRow +type PageAction = daemon.PageAction +type PageGlance = daemon.PageGlance +type PageDocument = daemon.PageDocument type PageCancelMsg struct{} type PageViewChangedMsg struct{} @@ -70,10 +39,10 @@ type pageLoadedMsg struct { } type pageActionExecutedMsg struct { - Err error - Result map[string]any - Action PageAction - Gen int + Err error + Message string + Action PageAction + Gen int } type pageModeKind int @@ -121,122 +90,18 @@ func (m PageViewModel) Init() tea.Cmd { return m.loadPageCmd(m.Generation) } -func parsePageDocument(result map[string]any) (*PageDocument, error) { - page, _ := result["page"].(map[string]any) - title, ok := page["title"].(string) - if !ok { - return nil, errors.New("command did not answer a page") - } - doc := &PageDocument{Title: title, Empty: "Nothing here yet."} - if summary, ok := page["summary"].(string); ok { - doc.Summary = summary - } - if empty, ok := page["empty"].(string); ok { - doc.Empty = empty - } - parseRows := func(raw any) []PageRow { - result := []PageRow{} - entries, _ := raw.([]any) - for _, entry := range entries { - obj, ok := entry.(map[string]any) - if !ok { - continue - } - id, idOK := obj["id"].(string) - text, textOK := obj["text"].(string) - badge, badgeOK := obj["badge"].(string) - if !idOK || !textOK || !badgeOK { - continue - } - tone, _ := obj["tone"].(string) - switch tone { - case "active", "warning", "muted": - default: - tone = "plain" - } - detail, _ := obj["detail"].(string) - result = append(result, PageRow{ID: id, Text: text, Badge: badge, Tone: PageTone(tone), Detail: detail}) - } - return result - } - doc.Rows = parseRows(page["rows"]) - if raw, ok := page["actions"].([]any); ok { - for _, entry := range raw { - obj, ok := entry.(map[string]any) - if !ok { - continue - } - key, keyOK := obj["key"].(string) - label, labelOK := obj["label"].(string) - run, runOK := obj["run"].(string) - if !keyOK || len([]rune(key)) != 1 || !labelOK || !runOK { - continue - } - action := PageAction{Key: key, Label: label, Run: run, Row: obj["row"] == true, Confirm: obj["confirm"] == true, Input: "none"} - kind, _ := obj["input"].(string) - switch kind { - case "text", "secret": - action.Input, action.Prompt = kind, label - if prompt, ok := obj["prompt"].(string); ok { - action.Prompt = prompt - } - action.Prefill = obj["prefill"] == true - case "choice": - choices, _ := obj["options"].([]any) - if len(choices) == 0 { - continue - } - var opts []string - for _, raw := range choices { - value, ok := raw.(string) - if !ok { - break - } - opts = append(opts, value) - } - if len(opts) != len(choices) { - continue - } - action.Input, action.Options = "choice", opts - case "value": - value, ok := obj["value"].(string) - if !ok { - continue - } - action.Input, action.Value = "value", value - } - doc.Actions = append(doc.Actions, action) - } - } - if glance, ok := page["glance"].(map[string]any); ok { - if title, ok := glance["title"].(string); ok { - doc.Glance = &PageGlance{Title: title, Rows: parseRows(glance["rows"])} - } - } - return doc, nil -} - func (m PageViewModel) loadPageCmd(gen int) tea.Cmd { return func() tea.Msg { if m.Conn == nil { return pageLoadedMsg{Err: errors.New("daemon connection unavailable"), Gen: gen} } - path := fmt.Sprintf("/sessions/%s/commands", m.SessionID) body := map[string]any{"name": m.Command, "args": map[string]string{}} - res, err := daemon.RequestOperation[map[string]any](context.Background(), m.Conn, daemon.Operation{Name: "load page", Method: http.MethodPost, Path: path, Body: body, Policy: daemon.AuthRecovery}) + res, err := daemon.ExecutePageCommand(context.Background(), m.Conn, m.SessionID, body) if err != nil { return pageLoadedMsg{Err: err, Gen: gen} } - target := res - if res["result"] != nil { - target, _ = res["result"].(map[string]any) - } - doc, err := parsePageDocument(target) - if err != nil { - err = fmt.Errorf("%s did not return a page", m.Command) - } - return pageLoadedMsg{Doc: doc, Err: err, Gen: gen} + return pageLoadedMsg{Doc: res.Page, Gen: gen} } } @@ -258,7 +123,6 @@ func (m PageViewModel) executeActionCmd(act PageAction, row *PageRow, entered st details = append(details, val) } - path := fmt.Sprintf("/sessions/%s/commands", m.SessionID) body := map[string]any{ "name": m.Command, "args": map[string]string{ @@ -267,8 +131,8 @@ func (m PageViewModel) executeActionCmd(act PageAction, row *PageRow, entered st }, } - res, err := daemon.RequestOperation[map[string]any](context.Background(), m.Conn, daemon.Operation{Name: "execute action", Method: http.MethodPost, Path: path, Body: body, Policy: daemon.AuthRecovery}) - return pageActionExecutedMsg{Result: res, Action: act, Err: err, Gen: gen} + res, err := daemon.ExecuteCommand(context.Background(), m.Conn, m.SessionID, body) + return pageActionExecutedMsg{Message: res.Message, Action: act, Err: err, Gen: gen} } } @@ -613,15 +477,8 @@ func toneStyle(tone PageTone, styles Styles) lipgloss.Style { // when it sent one, else the action's label. func pageNotice(msg pageActionExecutedMsg) string { notice := fmt.Sprintf("%s completed", msg.Action.Label) - if msg.Result == nil { - return notice - } - r, _ := msg.Result["result"].(map[string]any) - if r == nil { - r = msg.Result - } - if s, ok := r["message"].(string); ok && s != "" { - return s + if msg.Message != "" { + return msg.Message } return notice } diff --git a/cli/internal/tui/tree_picker.go b/cli/internal/tui/tree_picker.go index 541b06337..7d99b0128 100644 --- a/cli/internal/tui/tree_picker.go +++ b/cli/internal/tui/tree_picker.go @@ -128,9 +128,7 @@ func (m TreePickerModel) forkCmd(checkpointID int, gen int) tea.Cmd { if m.Conn == nil { return treeForkedMsg{Err: errors.New("daemon connection unavailable"), Gen: gen} } - path := fmt.Sprintf("/sessions/%s/fork", m.SessionID) - body := map[string]int{"checkpoint": checkpointID} - branch, err := daemon.RequestOperation[daemon.Session](context.Background(), m.Conn, daemon.Operation{Name: "fork", Method: http.MethodPost, Path: path, Body: body, Policy: daemon.AuthRecovery}) + branch, err := daemon.ForkSession(context.Background(), m.Conn, m.SessionID, map[string]any{"checkpoint": checkpointID}) return treeForkedMsg{Session: branch, Err: err, Gen: gen} } } diff --git a/cli/internal/tui/uncertain_outcome_test.go b/cli/internal/tui/uncertain_outcome_test.go index 760bd02bc..c2fcfe2c0 100644 --- a/cli/internal/tui/uncertain_outcome_test.go +++ b/cli/internal/tui/uncertain_outcome_test.go @@ -171,3 +171,48 @@ func TestUncertainSignInDoesNotRestartOrOpenBrowser(t *testing.T) { t.Fatal("Enter automatically restarted an uncertain sign-in") } } + +func TestInvalidGlanceResponseKeepsConfirmedGlances(t *testing.T) { + conn := daemon.NewConnection(daemon.ConnectionSnapshot{Port: 1}, "") + m := NewAppModel(conn, config.Profiles{}, &daemon.Session{ID: "current"}, "", false, nil) + t.Cleanup(m.Chat.Close) + m.Glances = []PageGlance{{Title: "confirmed"}} + m.Chat.Glances = m.Glances + updated, cmd := m.Update(glancesPolledMsg{ + Gen: m.GlanceGen, + Err: invalidResponseOutcome("/work", "page", errors.New("missing page")), + }) + m = updated.(AppModel) + if cmd != nil || len(m.Glances) != 1 || m.Glances[0].Title != "confirmed" || len(m.Chat.Glances) != 1 { + t.Fatal("invalid glance response replaced confirmed state or retried") + } +} + +func TestInvalidOpenResponseDoesNotRefreshSettings(t *testing.T) { + conn := daemon.NewConnection(daemon.ConnectionSnapshot{Port: 1}, "") + m := NewAppModel(conn, config.Profiles{}, &daemon.Session{ID: "current"}, "", false, nil) + t.Cleanup(m.Chat.Close) + _, cmd := m.Update(uiSavedMsg{Open: true, Err: invalidResponseOutcome("record open", "thinking", errors.New("missing preference"))}) + if cmd != nil { + t.Fatal("invalid open response scheduled a settings refresh") + } +} + +func TestUncertainWebhookStepRetainsConfirmedSecretWithoutRefresh(t *testing.T) { + m := loadedWebhooksPage(t) + m.Saving = true + secret := &webhookSecret{Hook: "ci", Session: "s", Secret: "confirmed-secret"} + m, cmd := m.Update(webhooksSavedMsg{ + Gen: m.Generation, Reveal: secret, + Err: invalidResponseOutcome("/webhooks", "hook", errors.New("missing hook")), + }) + if cmd != nil || m.Reveal != secret || m.Saving || m.Loading { + t.Fatal("uncertain later step lost the confirmed secret or scheduled a refresh") + } +} + +func invalidResponseOutcome(operation, field string, cause error) error { + return &daemon.UncertainOutcomeError{Operation: operation, Cause: &daemon.ProtocolError{ + Code: "invalid_response", Operation: operation, Field: field, Cause: cause, + }} +} diff --git a/cli/internal/tui/webhooks_page.go b/cli/internal/tui/webhooks_page.go index 410510de0..4982d1d1a 100644 --- a/cli/internal/tui/webhooks_page.go +++ b/cli/internal/tui/webhooks_page.go @@ -84,20 +84,16 @@ func NewWebhooksPageModel(conn *daemon.Connection, sessionID string) WebhooksPag func (m WebhooksPageModel) Init() tea.Cmd { return m.loadCmd(m.Generation) } // run calls /webhooks with an action and answers its result object. -func (m WebhooksPageModel) run(action, details string) (map[string]any, error) { +func (m WebhooksPageModel) run(action, details string) (*daemon.WebhookResult, error) { if m.Conn == nil { return nil, errors.New("daemon connection unavailable") } - path := fmt.Sprintf("/sessions/%s/commands", url.PathEscape(m.SessionID)) body := map[string]any{"name": "/webhooks", "args": map[string]string{"action": action, "details": details}} - res, err := daemon.RequestOperation[map[string]any](context.Background(), m.Conn, daemon.Operation{Name: "run", Method: http.MethodPost, Path: path, Body: body, Policy: daemon.AuthRecovery}) + res, err := daemon.ExecuteCommand(context.Background(), m.Conn, m.SessionID, body) if err != nil { return nil, err } - if r, ok := res["result"].(map[string]any); ok { - return r, nil - } - return res, nil + return res.Webhooks, nil } func (m WebhooksPageModel) loadCmd(gen int) tea.Cmd { @@ -131,30 +127,18 @@ func (m WebhooksPageModel) loadCmd(gen int) tea.Cmd { if err != nil { return webhooksLoadedMsg{Gen: gen, Err: err} } - agent, _ := res["agentManagement"].(bool) - var hooks []webhookEntry - entries, _ := res["hooks"].([]any) - for _, raw := range entries { - entry, _ := raw.(map[string]any) - hook, _ := entry["hook"].(map[string]any) - if hook == nil { - continue - } - queued, _ := entry["queued"].(float64) - enabled, _ := hook["enabled"].(bool) - w := webhookEntry{ - ID: str(hook, "id"), - Session: str(hook, "session"), - Name: str(hook, "name"), - URL: str(hook, "url"), - Header: str(hook, "signatureHeader"), - Prefix: str(hook, "signaturePrefix"), - Enabled: enabled, - Queued: int(queued), - Deferred: str(entry, "deferred"), + agent := res.AgentManagement + hooks := make([]webhookEntry, len(res.Hooks)) + for i, entry := range res.Hooks { + hook := entry.Hook + deferred := "" + if entry.Deferred != nil { + deferred = *entry.Deferred } - if w.ID != "" { - hooks = append(hooks, w) + hooks[i] = webhookEntry{ + ID: hook.ID, Session: hook.Session, Name: hook.Name, URL: hook.URL, + Header: hook.Header, Prefix: hook.Prefix, Enabled: hook.Enabled, + Queued: entry.Queued, Deferred: deferred, } } // Group by session in the order they are offered, current first. @@ -185,14 +169,11 @@ func (m WebhooksPageModel) save(gen int, notice string, steps ...[2]string) tea. // failed, so it still has to be shown. return webhooksSavedMsg{Reveal: reveal, Gen: gen, Err: err} } - hook, _ := res["hook"].(map[string]any) - if id, ok := hook["id"].(string); ok { - created = id - } - if secret, _ := res["secret"].(string); secret != "" { - name, _ := hook["name"].(string) - session, _ := hook["session"].(string) - reveal = &webhookSecret{Hook: name, Session: session, Secret: secret} + if res.Hook != nil { + created = res.Hook.ID + if res.Secret != "" { + reveal = &webhookSecret{Hook: res.Hook.Name, Session: res.Hook.Session, Secret: res.Secret} + } } } return webhooksSavedMsg{Notice: notice, Reveal: reveal, Gen: gen} @@ -257,6 +238,9 @@ func (m WebhooksPageModel) Update(msg tea.Msg) (WebhooksPageModel, tea.Cmd) { m.Saving, m.Reveal = false, msg.Reveal if msg.Err != nil { m.Error = msg.Err.Error() + if _, uncertain := errors.AsType[*daemon.UncertainOutcomeError](msg.Err); uncertain { + return m, nil + } if msg.Reveal == nil { return m, nil } -- knotmirror 0.0.1