diff --git a/cli/internal/daemon/agents.go b/cli/internal/daemon/agents.go new file mode 100644 index 000000000..965996b3c --- /dev/null +++ b/cli/internal/daemon/agents.go @@ -0,0 +1,48 @@ +package daemon + +import ( + "bufio" + "context" + "encoding/json" + "net/http" + "strings" +) + +// StreamAgents delivers nonempty batches until the stream ends or onBatch fails. +// The caller controls cancellation, including any blocking work in onBatch. +func StreamAgents(ctx context.Context, conn *Connection, onBatch func([]map[string]any) error) error { + req, err := newJSONRequest(ctx, http.MethodGet, conn.BaseURL()+"/agents/stream", nil) + if err != nil { + return err + } + req.Header.Set("Accept", "text/event-stream") + req.Header.Set("Authorization", "Bearer "+conn.Token()) + res, err := doAuthenticatedRequest(conn.HTTPClient(), conn.Token(), req) + if err != nil { + return err + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + // Error responses may never finish; do not wait for their bodies. + return &APIError{StatusCode: res.StatusCode} + } + scanner := bufio.NewScanner(res.Body) + scanner.Buffer(make([]byte, 64*1024), 8*1024*1024) + // The daemon sends each JSON batch on one data: line; batches do not span lines. + for scanner.Scan() { + line := scanner.Text() + if !strings.HasPrefix(line, "data:") { + continue + } + var batch struct { + Events []map[string]any `json:"events"` + } + if json.Unmarshal([]byte(strings.TrimSpace(line[5:])), &batch) != nil || len(batch.Events) == 0 { + continue + } + if err := onBatch(batch.Events); err != nil { + return err + } + } + return scanner.Err() +} diff --git a/cli/internal/daemon/auth.go b/cli/internal/daemon/auth.go index ad5586fc7..1d94ad971 100644 --- a/cli/internal/daemon/auth.go +++ b/cli/internal/daemon/auth.go @@ -2,7 +2,6 @@ package daemon import ( "context" - "errors" "net/http" "net/url" ) @@ -52,44 +51,36 @@ func accountPath(provider, id string) string { } func SignInList(ctx context.Context, conn *Connection) (SignIns, error) { - return authRequest[SignIns](ctx, conn, http.MethodGet, "/auth", nil) + return RequestMethod[SignIns](ctx, conn, http.MethodGet, "/auth", nil) } // 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 authRequest[StartedSignIn](ctx, conn, http.MethodPost, "/auth/"+url.PathEscape(provider), nil) + return RequestMethod[StartedSignIn](ctx, conn, http.MethodPost, "/auth/"+url.PathEscape(provider), nil) } func PollSignIn(ctx context.Context, conn *Connection, id string) (SignInStatus, error) { - return authRequest[SignInStatus](ctx, conn, http.MethodGet, "/auth/logins/"+url.PathEscape(id), nil) + return RequestMethod[SignInStatus](ctx, conn, http.MethodGet, "/auth/logins/"+url.PathEscape(id), nil) } // 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 := authRequest[acknowledged](ctx, conn, http.MethodPost, "/auth/logins/"+url.PathEscape(id), map[string]string{"input": input}) + _, err := RequestMethod[acknowledged](ctx, conn, http.MethodPost, "/auth/logins/"+url.PathEscape(id), map[string]string{"input": input}) return err } func CancelSignIn(ctx context.Context, conn *Connection, id string) error { - _, err := authRequest[acknowledged](ctx, conn, http.MethodDelete, "/auth/logins/"+url.PathEscape(id), nil) + _, err := RequestMethod[acknowledged](ctx, conn, http.MethodDelete, "/auth/logins/"+url.PathEscape(id), nil) return err } func SelectAccount(ctx context.Context, conn *Connection, provider, id string) error { - _, err := authRequest[acknowledged](ctx, conn, http.MethodPost, accountPath(provider, id), nil) + _, err := RequestMethod[acknowledged](ctx, conn, http.MethodPost, accountPath(provider, id), nil) return err } func RemoveAccount(ctx context.Context, conn *Connection, provider, id string) error { - _, err := authRequest[acknowledged](ctx, conn, http.MethodDelete, accountPath(provider, id), nil) + _, err := RequestMethod[acknowledged](ctx, conn, http.MethodDelete, accountPath(provider, id), nil) return err } - -func authRequest[T any](ctx context.Context, conn *Connection, method, path string, body any) (T, error) { - var zero T - if conn == nil { - return zero, errors.New("Not connected to Albedo.") - } - return RequestMethod[T](ctx, conn, method, path, body) -} diff --git a/cli/internal/daemon/client.go b/cli/internal/daemon/client.go index 1d4b7f4ac..9f96fbf55 100644 --- a/cli/internal/daemon/client.go +++ b/cli/internal/daemon/client.go @@ -2,14 +2,12 @@ package daemon import ( "bufio" - "bytes" "context" "crypto/rand" "encoding/hex" "encoding/json" "errors" "fmt" - "io" "net/http" "net/url" "strings" @@ -79,17 +77,6 @@ type ChatClient struct { Tail int } -func readBounded(r io.Reader, limit int64) ([]byte, error) { - data, err := io.ReadAll(io.LimitReader(r, limit+1)) - if err != nil { - return nil, err - } - if int64(len(data)) > limit { - return nil, fmt.Errorf("Albedo returned more data than this client can read (limit: %d bytes).", limit) - } - return data, nil -} - func NewChatClient(opts ChatClientOptions) *ChatClient { var endpoint EndpointProvider if opts.Conn != nil { @@ -111,7 +98,11 @@ func NewChatClient(opts ChatClientOptions) *ChatClient { var httpClient *http.Client if opts.HTTPClient == nil { - httpClient = NewReconnectingClient(endpoint) + if opts.Conn != nil { + httpClient = opts.Conn.HTTPClient() + } else { + httpClient = NewReconnectingClient(endpoint) + } } else { base := opts.HTTPClient.Transport if base == nil { @@ -160,15 +151,6 @@ func (c *ChatClient) agentURL(path string) string { return fmt.Sprintf("%s/sessions/%s%s", base, url.PathEscape(c.agentID), path) } -func (c *ChatClient) parseResponseError(res *http.Response) error { - body, err := readBounded(res.Body, 64*1024) - if err != nil { - return &APIError{StatusCode: res.StatusCode, Cause: err} - } - - return decodeAPIError(res.StatusCode, body) -} - func (c *ChatClient) submitPayload(ctx context.Context, payload map[string]any) (*SendResult, error) { reqCtx, cancel := context.WithTimeout(ctx, 20*time.Second) defer cancel() @@ -177,28 +159,19 @@ func (c *ChatClient) submitPayload(ctx context.Context, payload map[string]any) payload["clientId"] = c.clientID } - bodyData, err := json.Marshal(payload) - if err != nil { - return nil, err - } - - req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, c.agentURL("/events"), bytes.NewReader(bodyData)) + req, err := newJSONRequest(reqCtx, http.MethodPost, c.agentURL("/events"), payload) if err != nil { return nil, err } - req.Header.Set("Content-Type", "application/json") - if token := c.Token(); token != "" { - req.Header.Set("Authorization", "Bearer "+token) - } - res, err := c.httpClient.Do(req) + res, err := doAuthenticatedRequest(c.httpClient, c.Token(), req) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode < 200 || res.StatusCode >= 300 { - return nil, c.parseResponseError(res) + return nil, readHTTPError(res, 64*1024) } body, err := readBounded(res.Body, 64*1024) @@ -238,23 +211,19 @@ func (c *ChatClient) Interrupt(ctx context.Context) (bool, error) { reqCtx, cancel := context.WithTimeout(ctx, 15*time.Second) defer cancel() - req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, c.agentURL("/interrupt"), bytes.NewReader([]byte("{}"))) + req, err := newJSONRequest(reqCtx, http.MethodPost, c.agentURL("/interrupt"), map[string]any{}) if err != nil { return false, err } - req.Header.Set("Content-Type", "application/json") - if token := c.Token(); token != "" { - req.Header.Set("Authorization", "Bearer "+token) - } - res, err := c.httpClient.Do(req) + res, err := doAuthenticatedRequest(c.httpClient, c.Token(), req) if err != nil { return false, err } defer res.Body.Close() if res.StatusCode != http.StatusOK { - return false, c.parseResponseError(res) + return false, readHTTPError(res, 64*1024) } body, err := readBounded(res.Body, 64*1024) @@ -288,20 +257,17 @@ func (c *ChatClient) History(ctx context.Context, before int64, rows int) (*Hist if before > 0 { route += fmt.Sprintf("&before=%d", before) } - req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, c.agentURL(route), nil) + req, err := newJSONRequest(reqCtx, http.MethodGet, c.agentURL(route), nil) if err != nil { return nil, err } - if token := c.Token(); token != "" { - req.Header.Set("Authorization", "Bearer "+token) - } - res, err := c.httpClient.Do(req) + res, err := doAuthenticatedRequest(c.httpClient, c.Token(), req) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode != http.StatusOK { - return nil, c.parseResponseError(res) + return nil, readHTTPError(res, 64*1024) } body, err := readBounded(res.Body, 32*1024*1024) if err != nil { @@ -328,20 +294,17 @@ func (c *ChatClient) History(ctx context.Context, before int64, rows int) (*Hist func (c *ChatClient) ContextWindow(ctx context.Context) (*int, error) { reqCtx, cancel := context.WithTimeout(ctx, 20*time.Second) defer cancel() - req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, c.agentURL("/context"), nil) + req, err := newJSONRequest(reqCtx, http.MethodGet, c.agentURL("/context"), nil) if err != nil { return nil, err } - if token := c.Token(); token != "" { - req.Header.Set("Authorization", "Bearer "+token) - } - res, err := c.httpClient.Do(req) + res, err := doAuthenticatedRequest(c.httpClient, c.Token(), req) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode != http.StatusOK { - return nil, c.parseResponseError(res) + return nil, readHTTPError(res, 64*1024) } body, err := readBounded(res.Body, 1024*1024) if err != nil { @@ -363,22 +326,19 @@ func (c *ChatClient) GetStatus(ctx context.Context) (*AgentStatus, error) { reqCtx, cancel := context.WithTimeout(ctx, 20*time.Second) defer cancel() - req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, c.agentURL("/status"), nil) + req, err := newJSONRequest(reqCtx, http.MethodGet, c.agentURL("/status"), nil) if err != nil { return nil, err } - if token := c.Token(); token != "" { - req.Header.Set("Authorization", "Bearer "+token) - } - res, err := c.httpClient.Do(req) + res, err := doAuthenticatedRequest(c.httpClient, c.Token(), req) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode != http.StatusOK { - return nil, c.parseResponseError(res) + return nil, readHTTPError(res, 64*1024) } body, err := readBounded(res.Body, 64*1024) @@ -627,6 +587,7 @@ func parseStreamEvent(raw map[string]any) *StreamEvent { } } +// Stream uses ctx for cancellation; onEvent must also honor ctx if it blocks. func (c *ChatClient) Stream(ctx context.Context, onOpen func(), onEvent func(StreamEvent) error) error { c.mu.Lock() afterSeq := c.afterSeq @@ -637,23 +598,20 @@ func (c *ChatClient) Stream(ctx context.Context, onOpen func(), onEvent func(Str route += fmt.Sprintf("&tail=%d", c.Tail) } - req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.agentURL(route), nil) + req, err := newJSONRequest(ctx, http.MethodGet, c.agentURL(route), nil) if err != nil { return err } req.Header.Set("Accept", "text/event-stream") - if token := c.Token(); token != "" { - req.Header.Set("Authorization", "Bearer "+token) - } - res, err := c.httpClient.Do(req) + res, err := doAuthenticatedRequest(c.httpClient, c.Token(), req) if err != nil { return err } defer res.Body.Close() if res.StatusCode != http.StatusOK { - return c.parseResponseError(res) + return readHTTPError(res, 64*1024) } if onOpen != nil { @@ -667,6 +625,8 @@ func (c *ChatClient) Stream(ctx context.Context, onOpen func(), onEvent func(Str defer func() { _ = reporter.Report(nil, "running") if ctx.Err() != nil { + // Cancellation starts the next subscription from a fresh snapshot. + // Transient stream failures retain the cursor and partial tool previews. c.mu.Lock() c.afterSeq = -1 c.argumentsByCall = make(map[string]string) diff --git a/cli/internal/daemon/credentials.go b/cli/internal/daemon/credentials.go index e9c9f8fbb..5e8492801 100644 --- a/cli/internal/daemon/credentials.go +++ b/cli/internal/daemon/credentials.go @@ -36,7 +36,7 @@ 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 := authRequest[struct { + taken, err := RequestMethod[struct { Moved []string `json:"moved"` }](ctx, conn, http.MethodPost, "/auth/credentials/migration", map[string]string{}) return taken.Moved, err diff --git a/cli/internal/daemon/errors_test.go b/cli/internal/daemon/errors_test.go index fac27b1f9..6550f5975 100644 --- a/cli/internal/daemon/errors_test.go +++ b/cli/internal/daemon/errors_test.go @@ -31,10 +31,11 @@ func TestHTTPFailuresRetainIdentity(t *testing.T) { _, _ = io.WriteString(w, tc.body) })) defer server.Close() - conn := NewConnection(ConnectionSnapshot{Port: server.Listener.Addr().(*net.TCPAddr).Port}, t.TempDir()) + // This fixed peer has no discovery directory; authentication errors stay local. + conn := NewConnection(ConnectionSnapshot{Port: server.Listener.Addr().(*net.TCPAddr).Port}, "") _, requestErr := RequestMethod[any](context.Background(), conn, http.MethodGet, "/failure", nil) - client := NewChatClient(ChatClientOptions{}) - chatErr := client.parseResponseError(&http.Response{StatusCode: tc.status, Body: io.NopCloser(strings.NewReader(tc.body))}) + client := NewChatClient(ChatClientOptions{Conn: conn, AgentID: "session"}) + _, chatErr := client.GetStatus(context.Background()) for _, err := range []error{requestErr, chatErr} { err = fmt.Errorf("request context: %w", err) var apiErr *APIError diff --git a/cli/internal/daemon/http.go b/cli/internal/daemon/http.go new file mode 100644 index 000000000..f127b4835 --- /dev/null +++ b/cli/internal/daemon/http.go @@ -0,0 +1,226 @@ +package daemon + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strings" + "syscall" + "time" +) + +type EndpointProvider interface { + BaseURL() string + AuthToken() string + Refresh(ctx context.Context) error +} + +type StaticEndpoint struct { + URL string + Token string +} + +func (s StaticEndpoint) BaseURL() string { + return strings.TrimRight(s.URL, "/") +} + +func (s StaticEndpoint) AuthToken() string { + return s.Token +} + +func (s StaticEndpoint) Refresh(ctx context.Context) error { + return errors.New("Cannot reconnect automatically to a fixed server address.") +} + +type ReconnectingTransport struct { + Provider EndpointProvider + Base http.RoundTripper +} + +func (t *ReconnectingTransport) RoundTrip(req *http.Request) (*http.Response, error) { + base := t.Base + if base == nil { + base = http.DefaultTransport + } + + res, err := base.RoundTrip(req) + status := 0 + if res != nil { + status = res.StatusCode + } + + if t.Provider != nil && req.URL != nil && req.URL.Path != "/shutdown" && !strings.HasSuffix(req.URL.Path, "/open") && isStaleDaemon(err, status) { + if refreshErr := t.Provider.Refresh(req.Context()); refreshErr == nil { + if res != nil { + _ = res.Body.Close() + } + newReq := req.Clone(req.Context()) + newBase := t.Provider.BaseURL() + if parsed, parseErr := url.Parse(newBase); parseErr == nil && newReq.URL != nil { + newReq.URL.Scheme = parsed.Scheme + newReq.URL.Host = parsed.Host + newReq.Host = parsed.Host + } + if token := t.Provider.AuthToken(); token != "" { + newReq.Header.Set("Authorization", "Bearer "+token) + } + if req.GetBody != nil { + body, bodyErr := req.GetBody() + if bodyErr != nil { + return nil, bodyErr + } + newReq.Body = body + } + return base.RoundTrip(newReq) + } + } + return res, err +} + +func NewReconnectingClient(provider EndpointProvider) *http.Client { + return &http.Client{ + Transport: &ReconnectingTransport{ + Provider: provider, + Base: &http.Transport{ + Proxy: http.ProxyFromEnvironment, + }, + }, + CheckRedirect: func(req *http.Request, via []*http.Request) error { + return http.ErrUseLastResponse + }, + } +} + +func isConnectionError(err error) bool { + if err == nil { + return false + } + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return false + } + if errors.Is(err, io.EOF) || + errors.Is(err, syscall.ECONNREFUSED) || + errors.Is(err, syscall.ECONNRESET) || + errors.Is(err, syscall.EPIPE) || + errors.Is(err, net.ErrClosed) { + return true + } + var opErr *net.OpError + if errors.As(err, &opErr) { + return true + } + msg := err.Error() + return strings.Contains(msg, "connection refused") || + strings.Contains(msg, "connection reset") || + strings.Contains(msg, "broken pipe") || + strings.Contains(msg, "EOF") +} + +func isStaleDaemon(err error, statusCode int) bool { + if statusCode == http.StatusUnauthorized || statusCode == http.StatusForbidden { + return true + } + return isConnectionError(err) +} + +func newJSONRequest(ctx context.Context, method, url string, body any) (*http.Request, error) { + var reader io.Reader + if body != nil { + encoded, err := json.Marshal(body) + if err != nil { + return nil, err + } + // A bytes.Reader lets net/http populate GetBody for a reconnect retry. + reader = bytes.NewReader(encoded) + } + req, err := http.NewRequestWithContext(ctx, method, url, reader) + if err != nil { + return nil, err + } + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + return req, nil +} + +func doAuthenticatedRequest(client *http.Client, token string, req *http.Request) (*http.Response, error) { + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + return client.Do(req) +} + +func readHTTPError(res *http.Response, limit int64) error { + body, err := readBounded(res.Body, limit) + if err != nil { + return &APIError{StatusCode: res.StatusCode, Cause: err} + } + return decodeAPIError(res.StatusCode, body) +} + +func readBounded(r io.Reader, limit int64) ([]byte, error) { + data, err := io.ReadAll(io.LimitReader(r, limit+1)) + if err != nil { + return nil, err + } + if int64(len(data)) > limit { + return nil, fmt.Errorf("Albedo returned more data than this client can read (limit: %d bytes).", limit) + } + return data, nil +} + +func Request[T any](ctx context.Context, conn *Connection, path string, body any) (T, error) { + method := http.MethodGet + if body != nil { + method = http.MethodPost + } + return RequestMethod[T](ctx, conn, method, path, body) +} + +func RequestMethod[T any](ctx context.Context, conn *Connection, method, path string, body any) (T, error) { + var zero T + if conn == nil { + return zero, errors.New("Not connected to Albedo.") + } + if ctx == nil { + ctx = context.Background() + } + + reqCtx, cancel := context.WithTimeout(ctx, 20*time.Second) + defer cancel() + + reqURL := conn.BaseURL() + path + req, err := newJSONRequest(reqCtx, method, reqURL, body) + if err != nil { + return zero, err + } + req.Header.Set("Content-Type", "application/json") + + res, err := doAuthenticatedRequest(conn.HTTPClient(), conn.Token(), req) + if err != nil { + return zero, err + } + defer res.Body.Close() + + if res.StatusCode < 200 || res.StatusCode >= 300 { + return zero, readHTTPError(res, 50*1024*1024) + } + respData, err := readBounded(res.Body, 50*1024*1024) + if err != nil { + return zero, err + } + + var result T + if len(respData) > 0 { + if err := json.Unmarshal(respData, &result); err != nil { + return zero, err + } + } + return result, nil +} diff --git a/cli/internal/daemon/lifecycle.go b/cli/internal/daemon/lifecycle.go index d5c84ce8f..6c4705c25 100644 --- a/cli/internal/daemon/lifecycle.go +++ b/cli/internal/daemon/lifecycle.go @@ -1,8 +1,6 @@ package daemon import ( - "albedo/cli/internal/config" - "bytes" "context" "crypto/rand" "encoding/hex" @@ -10,9 +8,7 @@ import ( "errors" "fmt" "io" - "net" "net/http" - "net/url" "os" "os/exec" "path/filepath" @@ -22,7 +18,6 @@ import ( "strings" "sync" "sync/atomic" - "syscall" "time" ) @@ -45,11 +40,15 @@ type ConnectionSnapshot struct { } type Connection struct { - snapshot atomic.Pointer[ConnectionSnapshot] - refreshMu sync.Mutex - homeDir string + snapshot atomic.Pointer[ConnectionSnapshot] + refreshMu sync.Mutex + homeDir string + httpOnce sync.Once + httpClient *http.Client } +// NewConnection binds a daemon snapshot to its discovery directory. An empty +// directory permits HTTP requests but disables automatic rediscovery. func NewConnection(snap ConnectionSnapshot, homeDir string) *Connection { c := &Connection{homeDir: homeDir} c.snapshot.Store(&snap) @@ -132,7 +131,7 @@ func (c *Connection) Refresh(ctx context.Context) error { homeDir := c.HomeDir() if homeDir == "" { - homeDir = config.HomeDir() + return errors.New("Cannot reconnect without a daemon home directory.") } const attempts = 20 @@ -167,8 +166,11 @@ func (c *Connection) Refresh(ctx context.Context) error { return fmt.Errorf("Could not reconnect to Albedo. Check whether it is running with ALBEDO_HOME=%s.", homeDir) } +// HTTPClient returns the reusable HTTP client owned by this Connection. +// Address and token updates retain the same client and pool. func (c *Connection) HTTPClient() *http.Client { - return NewReconnectingClient(c) + c.httpOnce.Do(func() { c.httpClient = NewReconnectingClient(c) }) + return c.httpClient } func (c *Connection) MarshalJSON() ([]byte, error) { @@ -185,88 +187,6 @@ func (c *Connection) UnmarshalJSON(data []byte) error { return nil } -type EndpointProvider interface { - BaseURL() string - AuthToken() string - Refresh(ctx context.Context) error -} - -type StaticEndpoint struct { - URL string - Token string -} - -func (s StaticEndpoint) BaseURL() string { - return strings.TrimRight(s.URL, "/") -} - -func (s StaticEndpoint) AuthToken() string { - return s.Token -} - -func (s StaticEndpoint) Refresh(ctx context.Context) error { - return errors.New("Cannot reconnect automatically to a fixed server address.") -} - -type ReconnectingTransport struct { - Provider EndpointProvider - Base http.RoundTripper -} - -func (t *ReconnectingTransport) RoundTrip(req *http.Request) (*http.Response, error) { - base := t.Base - if base == nil { - base = http.DefaultTransport - } - - res, err := base.RoundTrip(req) - status := 0 - if res != nil { - status = res.StatusCode - } - - if t.Provider != nil && req.URL != nil && req.URL.Path != "/shutdown" && !strings.HasSuffix(req.URL.Path, "/open") && isStaleDaemon(err, status) { - if refreshErr := t.Provider.Refresh(req.Context()); refreshErr == nil { - if res != nil { - _ = res.Body.Close() - } - newReq := req.Clone(req.Context()) - newBase := t.Provider.BaseURL() - if parsed, parseErr := url.Parse(newBase); parseErr == nil && newReq.URL != nil { - newReq.URL.Scheme = parsed.Scheme - newReq.URL.Host = parsed.Host - newReq.Host = parsed.Host - } - if token := t.Provider.AuthToken(); token != "" { - newReq.Header.Set("Authorization", "Bearer "+token) - } - if req.GetBody != nil { - body, bodyErr := req.GetBody() - if bodyErr != nil { - return nil, bodyErr - } - newReq.Body = body - } - return base.RoundTrip(newReq) - } - } - return res, err -} - -func NewReconnectingClient(provider EndpointProvider) *http.Client { - return &http.Client{ - Transport: &ReconnectingTransport{ - Provider: provider, - Base: &http.Transport{ - Proxy: http.ProxyFromEnvironment, - }, - }, - CheckRedirect: func(req *http.Request, via []*http.Request) error { - return http.ErrUseLastResponse - }, - } -} - func ctxDone(ctx context.Context) <-chan struct{} { if ctx == nil { return nil @@ -274,38 +194,6 @@ func ctxDone(ctx context.Context) <-chan struct{} { return ctx.Done() } -func isConnectionError(err error) bool { - if err == nil { - return false - } - if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { - return false - } - if errors.Is(err, io.EOF) || - errors.Is(err, syscall.ECONNREFUSED) || - errors.Is(err, syscall.ECONNRESET) || - errors.Is(err, syscall.EPIPE) || - errors.Is(err, net.ErrClosed) { - return true - } - var opErr *net.OpError - if errors.As(err, &opErr) { - return true - } - msg := err.Error() - return strings.Contains(msg, "connection refused") || - strings.Contains(msg, "connection reset") || - strings.Contains(msg, "broken pipe") || - strings.Contains(msg, "EOF") -} - -func isStaleDaemon(err error, statusCode int) bool { - if statusCode == http.StatusUnauthorized || statusCode == http.StatusForbidden { - return true - } - return isConnectionError(err) -} - // Stale is a live daemon from a build other than the one this client bundles. type Stale struct { Running *Connection @@ -397,6 +285,7 @@ func Existing(homeDir string) (*Connection, error) { } req.Header.Set("Authorization", "Bearer "+snap.Token) + // Refresh calls Existing; a reconnecting health probe would recurse into Refresh. client := &http.Client{ CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse @@ -707,14 +596,6 @@ func startupExitError(waitErr error, logPath string, logStart int64, projectRoot return errors.New(msg) } -func Request[T any](ctx context.Context, conn *Connection, path string, body any) (T, error) { - method := http.MethodGet - if body != nil { - method = http.MethodPost - } - return RequestMethod[T](ctx, conn, method, path, body) -} - // Capabilities lists what the daemon at conn says it supports. func Capabilities(ctx context.Context, conn *Connection) ([]string, error) { health, err := Request[struct { @@ -737,73 +618,3 @@ func CheckCapability(ctx context.Context, conn *Connection, capability, feature func UpgradeNeeded(feature string) error { return &UpgradeRequiredError{Feature: feature} } - -func RequestMethod[T any](ctx context.Context, conn *Connection, method, path string, body any) (T, error) { - var zero T - if ctx == nil { - ctx = context.Background() - } - - reqCtx, cancel := context.WithTimeout(ctx, 20*time.Second) - defer cancel() - - var bodyReader io.Reader - if body != nil { - encoded, err := json.Marshal(body) - if err != nil { - return zero, err - } - bodyReader = bytes.NewReader(encoded) - } - - var client *http.Client - var baseURL, token string - if conn != nil { - client = conn.HTTPClient() - baseURL = conn.BaseURL() - token = conn.AuthToken() - } else { - client = &http.Client{ - CheckRedirect: func(req *http.Request, via []*http.Request) error { - return http.ErrUseLastResponse - }, - } - baseURL = "http://127.0.0.1:0" - } - - reqURL := fmt.Sprintf("%s%s", baseURL, path) - req, err := http.NewRequestWithContext(reqCtx, method, reqURL, bodyReader) - if err != nil { - return zero, err - } - if token != "" { - req.Header.Set("Authorization", "Bearer "+token) - } - req.Header.Set("Content-Type", "application/json") - - res, err := client.Do(req) - if err != nil { - return zero, err - } - defer res.Body.Close() - - respData, err := readBounded(res.Body, 50*1024*1024) - if err != nil { - if res.StatusCode < 200 || res.StatusCode >= 300 { - return zero, &APIError{StatusCode: res.StatusCode, Cause: err} - } - return zero, err - } - - if res.StatusCode < 200 || res.StatusCode >= 300 { - return zero, decodeAPIError(res.StatusCode, respData) - } - - var result T - if len(respData) > 0 { - if err := json.Unmarshal(respData, &result); err != nil { - return zero, err - } - } - return result, nil -} diff --git a/cli/internal/daemon/settings.go b/cli/internal/daemon/settings.go index 36fd950e9..077534730 100644 --- a/cli/internal/daemon/settings.go +++ b/cli/internal/daemon/settings.go @@ -28,7 +28,7 @@ func GetSettings(ctx context.Context, conn *Connection) (Settings, error) { if err := CheckCapability(ctx, conn, "settings_api", "for persisted settings; upgrade the CLI and daemon together"); err != nil { return Settings{}, err } - return authRequest[Settings](ctx, conn, http.MethodGet, "/settings", nil) + return RequestMethod[Settings](ctx, conn, http.MethodGet, "/settings", nil) } func ProviderProfiles(ctx context.Context, conn *Connection) (config.Profiles, error) { @@ -37,17 +37,17 @@ func ProviderProfiles(ctx context.Context, conn *Connection) (config.Profiles, e } func SaveProvider(ctx context.Context, conn *Connection, name string, profile config.Settings) error { - _, err := authRequest[acknowledged](ctx, conn, http.MethodPut, "/settings/providers/"+url.PathEscape(name), profile) + _, err := RequestMethod[acknowledged](ctx, conn, http.MethodPut, "/settings/providers/"+url.PathEscape(name), profile) return err } func DeleteProvider(ctx context.Context, conn *Connection, name string) error { - _, err := authRequest[acknowledged](ctx, conn, http.MethodDelete, "/settings/providers/"+url.PathEscape(name), nil) + _, err := RequestMethod[acknowledged](ctx, conn, http.MethodDelete, "/settings/providers/"+url.PathEscape(name), nil) return err } func SetCapability(ctx context.Context, conn *Connection, session, kind, name, scope string, enabled *bool) error { - _, err := authRequest[acknowledged](ctx, conn, http.MethodPost, "/sessions/"+url.PathEscape(session)+"/settings/capabilities", struct { + _, err := RequestMethod[acknowledged](ctx, conn, http.MethodPost, "/sessions/"+url.PathEscape(session)+"/settings/capabilities", struct { Kind string `json:"kind"` Name string `json:"name"` Scope string `json:"scope"` @@ -66,20 +66,20 @@ func SaveMCP(ctx context.Context, conn *Connection, session, name string, server if server == nil { method, body = http.MethodDelete, nil } - _, err := authRequest[acknowledged](ctx, conn, method, path, body) + _, err := RequestMethod[acknowledged](ctx, conn, method, path, body) return err } func PatchUI(ctx context.Context, conn *Connection, patch map[string]bool) (UIPreferences, error) { - return authRequest[UIPreferences](ctx, conn, http.MethodPatch, "/settings/ui", patch) + return RequestMethod[UIPreferences](ctx, conn, http.MethodPatch, "/settings/ui", patch) } func PatchSessionUI(ctx context.Context, conn *Connection, session string, patch map[string]bool) (UIPreferences, error) { - return authRequest[UIPreferences](ctx, conn, http.MethodPatch, "/settings/ui/sessions/"+url.PathEscape(session), patch) + return RequestMethod[UIPreferences](ctx, conn, http.MethodPatch, "/settings/ui/sessions/"+url.PathEscape(session), patch) } // 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 authRequest[UIPreferences](ctx, conn, http.MethodPost, "/settings/ui/sessions/"+url.PathEscape(session)+"/open", nil) + return RequestMethod[UIPreferences](ctx, conn, http.MethodPost, "/settings/ui/sessions/"+url.PathEscape(session)+"/open", nil) } diff --git a/cli/internal/tui/agents_view.go b/cli/internal/tui/agents_view.go index 1e640b733..99939b952 100644 --- a/cli/internal/tui/agents_view.go +++ b/cli/internal/tui/agents_view.go @@ -1,10 +1,8 @@ package tui import ( - "bufio" "cmp" "context" - "encoding/json" "errors" "fmt" "hash/fnv" @@ -219,7 +217,8 @@ func (m *AgentsViewModel) Init() tea.Cmd { return tea.Batch(m.snapshotCmd(m.Gen), m.startStream(m.Gen), m.frameCmd(m.Gen), textinput.Blink) } -// Close stops the stream; the view is gone once the app leaves it. +// Close stops the stream and invalidates batches, completions, and timers +// already queued for this view. func (m *AgentsViewModel) Close() { if m.cancel != nil { m.cancel() @@ -242,8 +241,6 @@ func (m AgentsViewModel) snapshotCmd(gen int) tea.Cmd { } } -// startStream reads the daemon's agents stream into a channel the view drains -// one batch at a time. func (m *AgentsViewModel) startStream(gen int) tea.Cmd { if m.Conn == nil { return nil @@ -258,39 +255,18 @@ func (m *AgentsViewModel) startStream(gen int) tea.Cmd { conn := m.Conn go func() { defer close(events) - req, err := http.NewRequestWithContext(ctx, http.MethodGet, conn.BaseURL()+"/agents/stream", nil) - if err != nil { - return - } - req.Header.Set("Accept", "text/event-stream") - req.Header.Set("Authorization", "Bearer "+conn.AuthToken()) - res, err := conn.HTTPClient().Do(req) - if err != nil { - return - } - defer res.Body.Close() - if res.StatusCode != http.StatusOK { - return - } - scanner := bufio.NewScanner(res.Body) - scanner.Buffer(make([]byte, 64*1024), 8*1024*1024) - for scanner.Scan() { - line := scanner.Text() - if !strings.HasPrefix(line, "data:") { - continue - } - var batch struct { - Events []map[string]any `json:"events"` - } - if json.Unmarshal([]byte(strings.TrimSpace(line[5:])), &batch) != nil || len(batch.Events) == 0 { - continue - } + // EOF and failures both reconnect through queue closure, so the view + // deliberately discards the transport error here. + _ = daemon.StreamAgents(ctx, conn, func(batch []map[string]any) error { + // Leaving the view stops its consumer. Cancellation must release a + // producer blocked on a full queue so it can close the HTTP body. select { - case events <- batch.Events: + case events <- batch: + return nil case <-ctx.Done(): - return + return ctx.Err() } - } + }) }() return waitAgents(events, gen) }