From c326853929fafdad84750585cb74d33f2f7ec2bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Salavisa?= Date: Mon, 10 Aug 2026 21:57:48 +0200 Subject: [PATCH] test(backend): cover the agentctl runtime client HTTP/WS surface (#2497) Co-authored-by: Kandev Agent --- .../runtime/agentctl/agent_session_test.go | 432 ++++++++++ .../agentctl/client_attachments_test.go | 289 +++++++ .../runtime/agentctl/client_core_test.go | 797 +++++++++++++++++ .../runtime/agentctl/client_files_test.go | 647 ++++++++++++++ .../runtime/agentctl/client_misc_test.go | 396 +++++++++ .../runtime/agentctl/client_process_test.go | 389 +++++++++ .../agentctl/client_shell_terminal_test.go | 405 +++++++++ .../runtime/agentctl/client_shell_test.go | 151 ++++ .../agent/runtime/agentctl/control_test.go | 607 +++++++++++++ .../agent/runtime/agentctl/git_test.go | 815 ++++++++++++++++++ .../runtime/agentctl/testhelpers_test.go | 55 ++ .../agentctl/workspace_dispatch_test.go | 237 +++++ 12 files changed, 5220 insertions(+) create mode 100644 apps/backend/internal/agent/runtime/agentctl/agent_session_test.go create mode 100644 apps/backend/internal/agent/runtime/agentctl/client_attachments_test.go create mode 100644 apps/backend/internal/agent/runtime/agentctl/client_core_test.go create mode 100644 apps/backend/internal/agent/runtime/agentctl/client_files_test.go create mode 100644 apps/backend/internal/agent/runtime/agentctl/client_misc_test.go create mode 100644 apps/backend/internal/agent/runtime/agentctl/client_process_test.go create mode 100644 apps/backend/internal/agent/runtime/agentctl/client_shell_terminal_test.go create mode 100644 apps/backend/internal/agent/runtime/agentctl/client_shell_test.go create mode 100644 apps/backend/internal/agent/runtime/agentctl/control_test.go create mode 100644 apps/backend/internal/agent/runtime/agentctl/git_test.go create mode 100644 apps/backend/internal/agent/runtime/agentctl/testhelpers_test.go create mode 100644 apps/backend/internal/agent/runtime/agentctl/workspace_dispatch_test.go diff --git a/apps/backend/internal/agent/runtime/agentctl/agent_session_test.go b/apps/backend/internal/agent/runtime/agentctl/agent_session_test.go new file mode 100644 index 0000000000..11cce5b0aa --- /dev/null +++ b/apps/backend/internal/agent/runtime/agentctl/agent_session_test.go @@ -0,0 +1,432 @@ +package client + +import ( + "context" + "encoding/json" + "strings" + "sync" + "testing" + "time" + + "github.com/kandev/kandev/internal/agentctl/types" + ws "github.com/kandev/kandev/pkg/websocket" +) + +// captureStreamRequest wires a stream client that records the first request the +// client sends, answers it with `response`, and returns both the client and a +// getter for the captured frame. +func captureStreamRequest( + t *testing.T, + response func(msg ws.Message) *ws.Message, +) (*Client, func() ws.Message) { + t.Helper() + + var mu sync.Mutex + var seen ws.Message + + c, ts := newTestClientWithStream(t, func(msg ws.Message) *ws.Message { + mu.Lock() + seen = msg + mu.Unlock() + return response(msg) + }) + // Close the client before the server so the read loop unwinds against a + // live connection rather than a torn-down listener. + t.Cleanup(func() { + c.Close() + ts.Close() + }) + + return c, func() ws.Message { + mu.Lock() + defer mu.Unlock() + return seen + } +} + +func okResponse(payload map[string]any) func(ws.Message) *ws.Message { + return func(msg ws.Message) *ws.Message { + resp, _ := ws.NewResponse(msg.ID, msg.Action, payload) + return resp + } +} + +func TestResetSession_UsesResetActionAndReturnsNewSessionID(t *testing.T) { + c, captured := captureStreamRequest(t, okResponse(map[string]any{ + "success": true, "session_id": "sess-reset-1", + })) + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + mcpServers := []types.McpServer{{Name: "kandev", Command: "kandev-mcp"}} + sessionID, err := c.ResetSession(ctx, "/workspace/task-1", mcpServers) + if err != nil { + t.Fatalf("ResetSession: %v", err) + } + if sessionID != "sess-reset-1" { + t.Errorf("session ID = %q, want sess-reset-1", sessionID) + } + + sent := captured() + // Reset must NOT reuse agent.session.new — that restarts the subprocess + // instead of resetting context on the live connection. + if sent.Action != "agent.session.reset" { + t.Errorf("action = %q, want agent.session.reset", sent.Action) + } + + var payload struct { + Cwd string `json:"cwd"` + McpServers []types.McpServer `json:"mcp_servers"` + } + if err := json.Unmarshal(sent.Payload, &payload); err != nil { + t.Fatalf("decode sent payload: %v", err) + } + if payload.Cwd != "/workspace/task-1" { + t.Errorf("cwd = %q, want /workspace/task-1", payload.Cwd) + } + if len(payload.McpServers) != 1 || payload.McpServers[0].Name != "kandev" { + t.Errorf("mcp_servers = %+v, want the kandev server forwarded", payload.McpServers) + } +} + +func TestResetSession_FailureModes(t *testing.T) { + t.Run("stream error frame", func(t *testing.T) { + c, _ := captureStreamRequest(t, func(msg ws.Message) *ws.Message { + resp, _ := ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "reset unsupported", nil) + return resp + }) + _, err := c.ResetSession(context.Background(), "/w", nil) + if err == nil || !strings.Contains(err.Error(), "agent.session.reset failed: reset unsupported") { + t.Fatalf("error = %v, want the labelled reset failure", err) + } + }) + + t.Run("unsuccessful payload", func(t *testing.T) { + c, _ := captureStreamRequest(t, okResponse(map[string]any{ + "success": false, "error": "no active session", + })) + _, err := c.ResetSession(context.Background(), "/w", nil) + if err == nil || !strings.Contains(err.Error(), "agent.session.reset failed: no active session") { + t.Fatalf("error = %v, want the labelled reset failure", err) + } + }) +} + +// SetMode / SetModel / SetConfigOption / Authenticate share one shape: send a +// typed payload, treat an error frame as a failure, ignore the response body. +func TestAgentSessionSetters_SendExpectedActionAndPayload(t *testing.T) { + tests := []struct { + name string + call func(c *Client) error + wantAction string + wantPayload map[string]any + }{ + { + name: "set mode", + call: func(c *Client) error { return c.SetMode(context.Background(), "sess-1", "plan") }, + wantAction: "agent.session.set_mode", + wantPayload: map[string]any{"session_id": "sess-1", "mode_id": "plan"}, + }, + { + name: "set model", + call: func(c *Client) error { return c.SetModel(context.Background(), "claude-opus-5") }, + wantAction: "agent.session.set_model", + wantPayload: map[string]any{"model_id": "claude-opus-5"}, + }, + { + name: "set config option", + call: func(c *Client) error { return c.SetConfigOption(context.Background(), "thinking", "high") }, + wantAction: "agent.session.set_config_option", + wantPayload: map[string]any{"config_id": "thinking", "value": "high"}, + }, + { + name: "authenticate", + call: func(c *Client) error { return c.Authenticate(context.Background(), "oauth") }, + wantAction: "agent.session.authenticate", + wantPayload: map[string]any{"method_id": "oauth"}, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + c, captured := captureStreamRequest(t, okResponse(map[string]any{"success": true})) + + if err := tc.call(c); err != nil { + t.Fatalf("call: %v", err) + } + + sent := captured() + if sent.Action != tc.wantAction { + t.Errorf("action = %q, want %q", sent.Action, tc.wantAction) + } + if sent.Type != ws.MessageTypeRequest { + t.Errorf("type = %q, want request", sent.Type) + } + + var payload map[string]any + if err := json.Unmarshal(sent.Payload, &payload); err != nil { + t.Fatalf("decode sent payload: %v", err) + } + if len(payload) != len(tc.wantPayload) { + t.Errorf("payload = %v, want exactly %v", payload, tc.wantPayload) + } + for key, want := range tc.wantPayload { + if payload[key] != want { + t.Errorf("payload[%q] = %v, want %v", key, payload[key], want) + } + } + }) + } +} + +func TestAgentSessionSetters_SurfaceStreamErrorFrames(t *testing.T) { + tests := []struct { + name string + call func(c *Client) error + wantErr string + }{ + { + name: "set mode", + call: func(c *Client) error { return c.SetMode(context.Background(), "sess-1", "plan") }, + wantErr: "set mode failed: mode not supported", + }, + { + name: "set model", + call: func(c *Client) error { return c.SetModel(context.Background(), "m") }, + wantErr: "set model failed: mode not supported", + }, + { + name: "set config option", + call: func(c *Client) error { return c.SetConfigOption(context.Background(), "c", "v") }, + wantErr: "set config option failed: mode not supported", + }, + { + name: "authenticate", + call: func(c *Client) error { return c.Authenticate(context.Background(), "oauth") }, + wantErr: "authenticate failed: mode not supported", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + c, _ := captureStreamRequest(t, func(msg ws.Message) *ws.Message { + resp, _ := ws.NewError(msg.ID, msg.Action, + ws.ErrorCodeBadRequest, "mode not supported", nil) + return resp + }) + + err := tc.call(c) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + }) + } +} + +// The setters deliberately ignore the response payload — only an error frame +// is a failure. An unsuccessful-looking body must not be turned into an error. +func TestAgentSessionSetters_IgnoreResponsePayload(t *testing.T) { + c, _ := captureStreamRequest(t, okResponse(map[string]any{ + "success": false, "error": "ignored", + })) + + if err := c.SetMode(context.Background(), "sess-1", "plan"); err != nil { + t.Errorf("SetMode = %v, want nil — only error frames are failures here", err) + } +} + +func TestAgentSessionSetters_FailWhenStreamIsNotConnected(t *testing.T) { + c := &Client{ + baseURL: "http://localhost:0", + logger: newTestLogger(), + pendingRequests: make(map[string]chan *ws.Message), + } + + calls := map[string]func() error{ + "SetMode": func() error { return c.SetMode(context.Background(), "s", "m") }, + "SetModel": func() error { return c.SetModel(context.Background(), "m") }, + "SetConfigOption": func() error { return c.SetConfigOption(context.Background(), "c", "v") }, + "Authenticate": func() error { return c.Authenticate(context.Background(), "oauth") }, + "ResetSession": func() error { + _, err := c.ResetSession(context.Background(), "/w", nil) + return err + }, + } + for name, call := range calls { + t.Run(name, func(t *testing.T) { + err := call() + if err == nil || !strings.Contains(err.Error(), "agent stream not connected") { + t.Fatalf("error = %v, want the not-connected sentinel", err) + } + }) + } +} + +func TestExtractMCPRequestCorrelation(t *testing.T) { + tests := []struct { + name string + payload string + wantSession string + wantPendingID string + }{ + { + name: "both fields", + payload: `{"session_id":"sess-1","pending_id":"pend-1"}`, + wantSession: "sess-1", + wantPendingID: "pend-1", + }, + {"session only", `{"session_id":"sess-1"}`, "sess-1", ""}, + {"pending only", `{"pending_id":"pend-1"}`, "", "pend-1"}, + {"empty payload", ``, "", ""}, + {"empty object", `{}`, "", ""}, + {"malformed JSON", `{"session_id":`, "", ""}, + {"non-object JSON", `["a"]`, "", ""}, + // Wrong types must not panic on the type assertion. + {"wrong field types", `{"session_id":42,"pending_id":true}`, "", ""}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + session, pending := extractMCPRequestCorrelation(json.RawMessage(tc.payload)) + if session != tc.wantSession { + t.Errorf("sessionID = %q, want %q", session, tc.wantSession) + } + if pending != tc.wantPendingID { + t.Errorf("pendingID = %q, want %q", pending, tc.wantPendingID) + } + }) + } +} + +// stubMCPHandler returns a fixed response/error pair for every dispatch. +type stubMCPHandler struct { + resp *ws.Message + err error + + mu sync.Mutex + sawe []string +} + +func (h *stubMCPHandler) Dispatch(_ context.Context, msg *ws.Message) (*ws.Message, error) { + h.mu.Lock() + h.sawe = append(h.sawe, msg.Action) + h.mu.Unlock() + return h.resp, h.err +} + +func (h *stubMCPHandler) actions() []string { + h.mu.Lock() + defer h.mu.Unlock() + return append([]string(nil), h.sawe...) +} + +func TestDispatchMCPRequest_WritesTheHandlerResponseBack(t *testing.T) { + resp, err := ws.NewResponse("req-1", "mcp.tools.call", map[string]any{"ok": true}) + if err != nil { + t.Fatalf("build response: %v", err) + } + handler := &stubMCPHandler{resp: resp} + + var written [][]byte + writeMessage := func(data []byte) error { + written = append(written, data) + return nil + } + + c := &Client{logger: newTestLogger()} + msg := ws.Message{ + ID: "req-1", + Type: ws.MessageTypeRequest, + Action: "mcp.tools.call", + Payload: json.RawMessage(`{"session_id":"sess-1","pending_id":"pend-1"}`), + } + c.dispatchMCPRequest(context.Background(), msg, handler, writeMessage) + + if actions := handler.actions(); len(actions) != 1 || actions[0] != "mcp.tools.call" { + t.Errorf("handler saw %v, want one mcp.tools.call dispatch", actions) + } + if len(written) != 1 { + t.Fatalf("wrote %d frames, want 1", len(written)) + } + + var sent ws.Message + if err := json.Unmarshal(written[0], &sent); err != nil { + t.Fatalf("decode written frame: %v", err) + } + if sent.ID != "req-1" || sent.Action != "mcp.tools.call" { + t.Errorf("written frame = %+v, want the request's id and action echoed", sent) + } + if sent.Type != ws.MessageTypeResponse { + t.Errorf("written type = %q, want response", sent.Type) + } +} + +// A handler error must still produce a frame — agentctl's MCP caller is blocked +// waiting on a correlated reply, so swallowing the error would hang the agent. +func TestDispatchMCPRequest_WritesAnErrorFrameOnHandlerFailure(t *testing.T) { + handler := &stubMCPHandler{err: errUnauthorizedStub{}} + + var written [][]byte + c := &Client{logger: newTestLogger()} + c.dispatchMCPRequest(context.Background(), + ws.Message{ID: "req-2", Type: ws.MessageTypeRequest, Action: "mcp.tools.call"}, + handler, + func(data []byte) error { written = append(written, data); return nil }) + + if len(written) != 1 { + t.Fatalf("wrote %d frames, want 1 error frame", len(written)) + } + var sent ws.Message + if err := json.Unmarshal(written[0], &sent); err != nil { + t.Fatalf("decode written frame: %v", err) + } + if sent.Type != ws.MessageTypeError { + t.Errorf("type = %q, want error", sent.Type) + } + if sent.ID != "req-2" { + t.Errorf("id = %q, want req-2 so the agent can correlate the failure", sent.ID) + } + var payload ws.ErrorPayload + if err := json.Unmarshal(sent.Payload, &payload); err != nil { + t.Fatalf("decode error payload: %v", err) + } + if payload.Code != ws.ErrorCodeInternalError { + t.Errorf("code = %q, want %q", payload.Code, ws.ErrorCodeInternalError) + } + if payload.Message != "not authorized" { + t.Errorf("message = %q, want the handler error text", payload.Message) + } +} + +type errUnauthorizedStub struct{} + +func (errUnauthorizedStub) Error() string { return "not authorized" } + +// A nil response with no error means the handler intentionally answered +// nothing (e.g. a notification); nothing should go on the wire. +func TestDispatchMCPRequest_WritesNothingForANilResponse(t *testing.T) { + handler := &stubMCPHandler{} + + var written [][]byte + c := &Client{logger: newTestLogger()} + c.dispatchMCPRequest(context.Background(), + ws.Message{ID: "req-3", Type: ws.MessageTypeRequest, Action: "mcp.notify"}, + handler, + func(data []byte) error { written = append(written, data); return nil }) + + if len(written) != 0 { + t.Errorf("wrote %d frames, want none for a nil handler response", len(written)) + } +} + +// A write failure is logged and swallowed — the read loop must keep running. +func TestDispatchMCPRequest_SurvivesAWriteFailure(t *testing.T) { + resp, _ := ws.NewResponse("req-4", "mcp.tools.call", map[string]any{"ok": true}) + handler := &stubMCPHandler{resp: resp} + + c := &Client{logger: newTestLogger()} + c.dispatchMCPRequest(context.Background(), + ws.Message{ID: "req-4", Type: ws.MessageTypeRequest, Action: "mcp.tools.call"}, + handler, + func([]byte) error { return errUnauthorizedStub{} }) +} diff --git a/apps/backend/internal/agent/runtime/agentctl/client_attachments_test.go b/apps/backend/internal/agent/runtime/agentctl/client_attachments_test.go new file mode 100644 index 0000000000..ac6107ae00 --- /dev/null +++ b/apps/backend/internal/agent/runtime/agentctl/client_attachments_test.go @@ -0,0 +1,289 @@ +package client + +import ( + "context" + "io" + "mime" + "mime/multipart" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + + "github.com/kandev/kandev/internal/task/models" +) + +// parseMaterializeUpload re-reads the multipart body the client streamed so +// tests can assert the exact fields and file bytes agentctl will see. +func parseMaterializeUpload(t *testing.T, got *capturedRequest) (map[string]string, string, []byte) { + t.Helper() + mediaType, params, err := mime.ParseMediaType(got.ContentType) + if err != nil { + t.Fatalf("parse content-type %q: %v", got.ContentType, err) + } + if mediaType != "multipart/form-data" { + t.Fatalf("media type = %q, want multipart/form-data", mediaType) + } + reader := multipart.NewReader(strings.NewReader(string(got.Body)), params["boundary"]) + + fields := map[string]string{} + var fileName string + var fileBytes []byte + for { + part, err := reader.NextPart() + if err == io.EOF { + break + } + if err != nil { + t.Fatalf("read multipart part: %v", err) + } + body, err := io.ReadAll(part) + if err != nil { + t.Fatalf("read part %q: %v", part.FormName(), err) + } + if part.FormName() == "file" { + fileName, fileBytes = part.FileName(), body + continue + } + fields[part.FormName()] = string(body) + } + return fields, fileName, fileBytes +} + +func TestMaterializeAttachment_StreamsMultipartWithEveryDescriptorField(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, + `{"name":"screenshot-1.png","size_bytes":11}`)) + + content := "PNGCONTENT" + result, err := newHTTPOnlyClient(srv.URL).MaterializeAttachment( + context.Background(), + "sess-1", "att-1", "screenshot.png", "image/png", + int64(len(content)+1), strings.NewReader(content+"!"), + ) + if err != nil { + t.Fatalf("MaterializeAttachment: %v", err) + } + + if got.Method != http.MethodPost || got.Path != "/api/v1/attachments/materialize" { + t.Errorf("request = %s %s, want POST /api/v1/attachments/materialize", got.Method, got.Path) + } + + fields, fileName, fileBytes := parseMaterializeUpload(t, got) + if fields["session_id"] != "sess-1" || fields["attachment_id"] != "att-1" { + t.Errorf("session/attachment = %q / %q", fields["session_id"], fields["attachment_id"]) + } + if fields["name"] != "screenshot.png" || fields["mime_type"] != "image/png" { + t.Errorf("name/mime = %q / %q", fields["name"], fields["mime_type"]) + } + if fields["size_bytes"] != "11" { + t.Errorf("size_bytes = %q, want 11", fields["size_bytes"]) + } + if fileName != "screenshot.png" { + t.Errorf("file part filename = %q, want screenshot.png", fileName) + } + if string(fileBytes) != content+"!" { + t.Errorf("file bytes = %q, want the raw content streamed verbatim", fileBytes) + } + + // The client renames server-side; the returned name is authoritative. + if result.Name != "screenshot-1.png" { + t.Errorf("Name = %q, want the server-chosen screenshot-1.png", result.Name) + } + if result.SizeBytes != 11 { + t.Errorf("SizeBytes = %d, want 11", result.SizeBytes) + } +} + +func TestMaterializeAttachment_RejectsInvalidArgumentsBeforeAnyRequest(t *testing.T) { + tests := []struct { + name string + sessionID string + attachmentID string + sizeBytes int64 + content io.Reader + wantErr string + }{ + { + name: "blank session", + sessionID: " ", + attachmentID: "att-1", + content: strings.NewReader("x"), + wantErr: "attachment session, id, and content are required", + }, + { + name: "blank attachment id", + sessionID: "sess-1", + attachmentID: "", + content: strings.NewReader("x"), + wantErr: "attachment session, id, and content are required", + }, + { + name: "nil content", + sessionID: "sess-1", + attachmentID: "att-1", + content: nil, + wantErr: "attachment session, id, and content are required", + }, + { + name: "negative size", + sessionID: "sess-1", + attachmentID: "att-1", + sizeBytes: -1, + content: strings.NewReader("x"), + wantErr: "attachment size exceeds maximum", + }, + { + name: "over the descriptor limit", + sessionID: "sess-1", + attachmentID: "att-1", + sizeBytes: models.MaxMessageAttachmentBytes + 1, + content: strings.NewReader("x"), + wantErr: "attachment size exceeds maximum", + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + var requests int + srv, _ := captureServer(t, func(w http.ResponseWriter, _ *http.Request) { + requests++ + w.WriteHeader(http.StatusOK) + }) + + result, err := newHTTPOnlyClient(srv.URL).MaterializeAttachment( + context.Background(), tc.sessionID, tc.attachmentID, "n", "text/plain", + tc.sizeBytes, tc.content) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + if result != nil { + t.Errorf("result = %+v, want nil", result) + } + if requests != 0 { + t.Errorf("sent %d requests, want the validation to short-circuit", requests) + } + }) + } +} + +// The exact limit must be accepted — an off-by-one here silently rejects the +// largest legal attachment. +func TestMaterializeAttachment_AcceptsExactlyTheDescriptorLimit(t *testing.T) { + srv, _ := captureServer(t, func(w http.ResponseWriter, r *http.Request) { + // Drain without buffering the whole (large) declared size. + _, _ = io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, + `{"name":"big.bin","size_bytes":`+ + strconv.FormatInt(models.MaxMessageAttachmentBytes, 10)+`}`) + }) + + result, err := newHTTPOnlyClient(srv.URL).MaterializeAttachment( + context.Background(), "sess-1", "att-1", "big.bin", "application/octet-stream", + models.MaxMessageAttachmentBytes, strings.NewReader("stub")) + if err != nil { + t.Fatalf("MaterializeAttachment at the limit: %v", err) + } + if result.SizeBytes != models.MaxMessageAttachmentBytes { + t.Errorf("SizeBytes = %d, want %d", result.SizeBytes, models.MaxMessageAttachmentBytes) + } +} + +func TestMaterializeAttachment_FailsOnNonSuccessStatusAndEchoesBody(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusRequestEntityTooLarge, + " attachment exceeds session quota ")) + + _, err := newHTTPOnlyClient(srv.URL).MaterializeAttachment( + context.Background(), "sess-1", "att-1", "n", "text/plain", 1, strings.NewReader("x")) + if err == nil { + t.Fatal("MaterializeAttachment returned nil error for 413") + } + if !strings.Contains(err.Error(), "materialize attachment failed with status 413") { + t.Errorf("error = %v, want status 413 named", err) + } + if !strings.Contains(err.Error(), "attachment exceeds session quota") { + t.Errorf("error = %v, want the server body echoed", err) + } + if strings.Contains(err.Error(), " attachment") { + t.Errorf("error = %v, want the echoed body trimmed", err) + } +} + +func TestMaterializeAttachment_RejectsMalformedResponseBody(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `{"name":`)) + + _, err := newHTTPOnlyClient(srv.URL).MaterializeAttachment( + context.Background(), "sess-1", "att-1", "n", "text/plain", 1, strings.NewReader("x")) + if err == nil || !strings.Contains(err.Error(), "decode materialized attachment") { + t.Fatalf("error = %v, want decode failure", err) + } +} + +// A response that disagrees with the descriptor means the file on the agentctl +// side is not the one the backend claimed — the caller must not treat it as +// materialized. +func TestMaterializeAttachment_RejectsInconsistentResponseMetadata(t *testing.T) { + tests := []struct { + name string + body string + }{ + {"blank name", `{"name":" ","size_bytes":5}`}, + {"missing name", `{"size_bytes":5}`}, + {"size mismatch", `{"name":"a.txt","size_bytes":4}`}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, tc.body)) + + result, err := newHTTPOnlyClient(srv.URL).MaterializeAttachment( + context.Background(), "sess-1", "att-1", "a.txt", "text/plain", + 5, strings.NewReader("12345")) + if err == nil || !strings.Contains(err.Error(), "materialize attachment returned invalid metadata") { + t.Fatalf("error = %v, want invalid metadata", err) + } + if result != nil { + t.Errorf("result = %+v, want nil", result) + } + }) + } +} + +func TestMaterializeAttachment_HonoursContextCancellation(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `{"name":"a","size_bytes":1}`)) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + _, err := newHTTPOnlyClient(srv.URL).MaterializeAttachment( + ctx, "sess-1", "att-1", "a.txt", "text/plain", 1, strings.NewReader("x")) + if err == nil || !strings.Contains(err.Error(), "context canceled") { + t.Fatalf("error = %v, want context canceled", err) + } +} + +// A reader that fails mid-copy must propagate through the pipe rather than +// hanging the request or silently truncating the upload. +type failingReader struct{ err error } + +func (r failingReader) Read([]byte) (int, error) { return 0, r.err } + +func TestMaterializeAttachment_PropagatesContentReadFailure(t *testing.T) { + // The pipe writer is closed with the reader's error, so the request body + // aborts mid-stream. Use a bare handler: the capture helper would report + // the (expected) truncated read as a test failure of its own. + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(srv.Close) + + _, err := newHTTPOnlyClient(srv.URL).MaterializeAttachment( + context.Background(), "sess-1", "att-1", "a.txt", "text/plain", + 1, failingReader{err: io.ErrUnexpectedEOF}) + if err == nil { + t.Fatal("MaterializeAttachment returned nil error for a failing content reader") + } + if !strings.Contains(err.Error(), "materialize attachment") { + t.Errorf("error = %v, want the upload failure wrapped", err) + } +} diff --git a/apps/backend/internal/agent/runtime/agentctl/client_core_test.go b/apps/backend/internal/agent/runtime/agentctl/client_core_test.go new file mode 100644 index 0000000000..5a6a385a4c --- /dev/null +++ b/apps/backend/internal/agent/runtime/agentctl/client_core_test.go @@ -0,0 +1,797 @@ +package client + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "testing/synctest" + "time" + + "github.com/kandev/kandev/internal/agentctl/types" +) + +func TestNewClient_BuildsBaseURLAndTimeouts(t *testing.T) { + c := NewClient("agentctl.internal", 40123, newTestLogger()) + + if c.BaseURL() != "http://agentctl.internal:40123" { + t.Errorf("BaseURL = %q, want http://agentctl.internal:40123", c.BaseURL()) + } + if c.Host() != "agentctl.internal" { + t.Errorf("Host = %q, want agentctl.internal", c.Host()) + } + if c.httpClient.Timeout != 60*time.Second { + t.Errorf("httpClient timeout = %v, want 60s", c.httpClient.Timeout) + } + // Inference prompts routinely outlast the 60s default, so the long-running + // client must keep its own 5m budget. + if c.longRunningHTTPClient.Timeout != 5*time.Minute { + t.Errorf("longRunningHTTPClient timeout = %v, want 5m", c.longRunningHTTPClient.Timeout) + } + if c.AuthToken() != "" { + t.Errorf("AuthToken = %q, want empty", c.AuthToken()) + } + if c.httpClient.Transport != nil { + t.Error("transport installed without auth token or execution ID") + } +} + +func TestNewClient_OptionsInstallAuthAndInstanceHeaders(t *testing.T) { + var gotAuth, gotInstance string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotAuth = r.Header.Get("Authorization") + gotInstance = r.Header.Get("X-Instance-ID") + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(srv.Close) + + host, port := splitTestServerHostPort(t, srv) + c := NewClient(host, port, newTestLogger(), + WithAuthToken("secret-token"), + WithExecutionID("exec-1"), + WithSessionID("sess-1"), + ) + + if c.AuthToken() != "secret-token" { + t.Errorf("AuthToken = %q, want secret-token", c.AuthToken()) + } + if c.executionID != "exec-1" || c.sessionID != "sess-1" { + t.Errorf("execution/session = %q / %q, want exec-1 / sess-1", c.executionID, c.sessionID) + } + + if err := c.Health(context.Background()); err != nil { + t.Fatalf("Health: %v", err) + } + if gotAuth != "Bearer secret-token" { + t.Errorf("Authorization = %q, want Bearer secret-token", gotAuth) + } + // Both transports are chained; a lost X-Instance-ID lets a recycled port + // serve a stale client. + if gotInstance != "exec-1" { + t.Errorf("X-Instance-ID = %q, want exec-1", gotInstance) + } +} + +func TestNewClient_LongRunningClientCarriesTheSameHeaders(t *testing.T) { + var gotAuth, gotInstance string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotAuth = r.Header.Get("Authorization") + gotInstance = r.Header.Get("X-Instance-ID") + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"name":"a.txt","size_bytes":1}`)) + })) + t.Cleanup(srv.Close) + + host, port := splitTestServerHostPort(t, srv) + c := NewClient(host, port, newTestLogger(), + WithAuthToken("secret-token"), WithExecutionID("exec-1")) + + // MaterializeAttachment is the one call that uses longRunningHTTPClient. + if _, err := c.MaterializeAttachment(context.Background(), + "sess-1", "att-1", "a.txt", "text/plain", 1, strings.NewReader("x")); err != nil { + t.Fatalf("MaterializeAttachment: %v", err) + } + if gotAuth != "Bearer secret-token" { + t.Errorf("Authorization on long-running client = %q, want Bearer secret-token", gotAuth) + } + if gotInstance != "exec-1" { + t.Errorf("X-Instance-ID on long-running client = %q, want exec-1", gotInstance) + } +} + +func TestWsAuthHeaders(t *testing.T) { + tests := []struct { + name string + token string + executionID string + wantNil bool + wantAuth string + wantID string + }{ + {name: "neither set", wantNil: true}, + {name: "token only", token: "t", wantAuth: "Bearer t"}, + {name: "execution only", executionID: "e", wantID: "e"}, + {name: "both", token: "t", executionID: "e", wantAuth: "Bearer t", wantID: "e"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + c := &Client{authToken: tc.token, executionID: tc.executionID} + headers := c.wsAuthHeaders() + if tc.wantNil { + if headers != nil { + t.Fatalf("headers = %v, want nil when unauthenticated", headers) + } + return + } + if headers == nil { + t.Fatal("headers = nil, want a populated header set") + } + if got := headers.Get("Authorization"); got != tc.wantAuth { + t.Errorf("Authorization = %q, want %q", got, tc.wantAuth) + } + if got := headers.Get("X-Instance-ID"); got != tc.wantID { + t.Errorf("X-Instance-ID = %q, want %q", got, tc.wantID) + } + }) + } +} + +func TestHost_FallsBackToBaseURLWhenUnparseable(t *testing.T) { + c := &Client{baseURL: "http://host with spaces:1/\x7f"} + if got := c.Host(); got != c.baseURL { + t.Errorf("Host = %q, want the raw baseURL as fallback", got) + } +} + +func TestSetTraceContext_ReplacesTheBackgroundParent(t *testing.T) { + c := &Client{} + if got := c.getTraceCtx(); got != context.Background() { + t.Errorf("getTraceCtx = %v, want context.Background before any set", got) + } + + type key struct{} + ctx := context.WithValue(context.Background(), key{}, "v") + c.SetTraceContext(ctx) + if got := c.getTraceCtx().Value(key{}); got != "v" { + t.Errorf("trace ctx value = %v, want the context set", got) + } +} + +func TestStatusResponse_IsAgentRunning(t *testing.T) { + tests := []struct { + status string + want bool + }{ + {"running", true}, + {"starting", true}, + {"stopped", false}, + {"error", false}, + {"", false}, + } + for _, tc := range tests { + t.Run(tc.status, func(t *testing.T) { + s := &StatusResponse{AgentStatus: tc.status} + if got := s.IsAgentRunning(); got != tc.want { + t.Errorf("IsAgentRunning(%q) = %v, want %v", tc.status, got, tc.want) + } + }) + } +} + +func TestHealth_HitsHealthEndpoint(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `ok`)) + + if err := newHTTPOnlyClient(srv.URL).Health(context.Background()); err != nil { + t.Fatalf("Health: %v", err) + } + if got.Method != http.MethodGet || got.Path != "/health" { + t.Errorf("request = %s %s, want GET /health", got.Method, got.Path) + } +} + +func TestHealth_FailsOnNonOKStatus(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusServiceUnavailable, ``)) + + err := newHTTPOnlyClient(srv.URL).Health(context.Background()) + if err == nil || !strings.Contains(err.Error(), "health check failed: 503") { + t.Fatalf("error = %v, want status 503 named", err) + } +} + +func TestGetStatus_DecodesAgentStatusAndProcessInfo(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, + `{"agent_status":"running","process_info":{"pid":4242,"command":"claude-code acp"}}`)) + + status, err := newHTTPOnlyClient(srv.URL).GetStatus(context.Background()) + if err != nil { + t.Fatalf("GetStatus: %v", err) + } + + if got.Method != http.MethodGet || got.Path != "/api/v1/status" { + t.Errorf("request = %s %s, want GET /api/v1/status", got.Method, got.Path) + } + if status.AgentStatus != "running" { + t.Errorf("AgentStatus = %q, want running", status.AgentStatus) + } + if !status.IsAgentRunning() { + t.Error("IsAgentRunning = false for a running agent") + } + if pid, ok := status.ProcessInfo["pid"].(float64); !ok || pid != 4242 { + t.Errorf("ProcessInfo[pid] = %v, want 4242", status.ProcessInfo["pid"]) + } + if status.ProcessInfo["command"] != "claude-code acp" { + t.Errorf("ProcessInfo[command] = %v", status.ProcessInfo["command"]) + } +} + +func TestGetStatus_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-2xx status", http.StatusInternalServerError, `boom`, "status request failed with status 500"}, + {"malformed body", http.StatusOK, `{"agent_status":`, "failed to parse status response"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(tc.status, tc.body)) + + status, err := newHTTPOnlyClient(srv.URL).GetStatus(context.Background()) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + if status != nil { + t.Errorf("status = %+v, want nil on failure", status) + } + }) + } +} + +func TestConfigureAgent_SendsCommandEnvAndApprovalPolicy(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{"success":true}`)) + + err := newHTTPOnlyClient(srv.URL).ConfigureAgent( + context.Background(), "claude-code acp", nil, + map[string]string{"ANTHROPIC_API_KEY": "k"}, "never", "", nil) + if err != nil { + t.Fatalf("ConfigureAgent: %v", err) + } + + if got.Method != http.MethodPost || got.Path != "/api/v1/agent/configure" { + t.Errorf("request = %s %s, want POST /api/v1/agent/configure", got.Method, got.Path) + } + if got.ContentType != "application/json" { + t.Errorf("content-type = %q, want application/json", got.ContentType) + } + + var sent struct { + Command string `json:"command"` + Env map[string]string `json:"env"` + ApprovalPolicy string `json:"approval_policy"` + } + if err := json.Unmarshal(got.Body, &sent); err != nil { + t.Fatalf("decode sent body: %v", err) + } + if sent.Command != "claude-code acp" { + t.Errorf("sent command = %q", sent.Command) + } + if sent.Env["ANTHROPIC_API_KEY"] != "k" { + t.Errorf("sent env = %v", sent.Env) + } + if sent.ApprovalPolicy != "never" { + t.Errorf("sent approval_policy = %q, want never", sent.ApprovalPolicy) + } +} + +func TestConfigureAgent_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-2xx status", http.StatusBadRequest, `bad`, "configure request failed with status 400"}, + {"malformed body", http.StatusOK, `{"success":`, "failed to parse configure response"}, + {"unsuccessful", http.StatusOK, `{"success":false,"error":"unknown protocol"}`, "configure failed: unknown protocol"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(tc.status, tc.body)) + + err := newHTTPOnlyClient(srv.URL).ConfigureAgent( + context.Background(), "cmd", nil, nil, "", "", nil) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + }) + } +} + +func TestSetMcpMode_PutsModePayload(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{}`)) + + if err := newHTTPOnlyClient(srv.URL).SetMcpMode(context.Background(), "office"); err != nil { + t.Fatalf("SetMcpMode: %v", err) + } + + if got.Method != http.MethodPut || got.Path != "/api/v1/mcp/mode" { + t.Errorf("request = %s %s, want PUT /api/v1/mcp/mode", got.Method, got.Path) + } + if got.ContentType != "application/json" { + t.Errorf("content-type = %q, want application/json", got.ContentType) + } + + var sent struct { + Mode string `json:"mode"` + } + if err := json.Unmarshal(got.Body, &sent); err != nil { + t.Fatalf("decode sent body: %v", err) + } + if sent.Mode != "office" { + t.Errorf("sent mode = %q, want office", sent.Mode) + } +} + +func TestSetMcpMode_FailsOnNonOKStatusAndEchoesBody(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusBadRequest, `unknown mode "turbo"`)) + + err := newHTTPOnlyClient(srv.URL).SetMcpMode(context.Background(), "turbo") + if err == nil || !strings.Contains(err.Error(), "set MCP mode failed with status 400") { + t.Fatalf("error = %v, want status 400 named", err) + } + if !strings.Contains(err.Error(), `unknown mode "turbo"`) { + t.Errorf("error = %v, want the server body echoed", err) + } +} + +func TestSetMcpProviders_PutsProviderListUnderMcpProvidersKey(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{}`)) + + err := newHTTPOnlyClient(srv.URL).SetMcpProviders( + context.Background(), []string{"github", "gitlab"}) + if err != nil { + t.Fatalf("SetMcpProviders: %v", err) + } + + if got.Method != http.MethodPut || got.Path != "/api/v1/mcp/providers" { + t.Errorf("request = %s %s, want PUT /api/v1/mcp/providers", got.Method, got.Path) + } + + var sent struct { + Providers []string `json:"mcp_providers"` + } + if err := json.Unmarshal(got.Body, &sent); err != nil { + t.Fatalf("decode sent body: %v", err) + } + if len(sent.Providers) != 2 || sent.Providers[0] != "github" || sent.Providers[1] != "gitlab" { + t.Errorf("sent mcp_providers = %v, want [github gitlab]", sent.Providers) + } +} + +func TestSetMcpProviders_FailsOnNonOKStatus(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusInternalServerError, `boom`)) + + err := newHTTPOnlyClient(srv.URL).SetMcpProviders(context.Background(), nil) + if err == nil || !strings.Contains(err.Error(), "set MCP providers failed with status 500") { + t.Fatalf("error = %v, want status 500 named", err) + } +} + +func TestStart_ReturnsTheExecutedCommand(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, + `{"success":true,"command":"claude-code acp --workspace-root /w"}`)) + + command, err := newHTTPOnlyClient(srv.URL).Start(context.Background()) + if err != nil { + t.Fatalf("Start: %v", err) + } + + if got.Method != http.MethodPost || got.Path != "/api/v1/start" { + t.Errorf("request = %s %s, want POST /api/v1/start", got.Method, got.Path) + } + if len(got.Body) != 0 { + t.Errorf("body = %q, want an empty POST", got.Body) + } + if command != "claude-code acp --workspace-root /w" { + t.Errorf("command = %q, want the full executed command", command) + } +} + +func TestStart_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-2xx status", http.StatusConflict, `already running`, "start request failed with status 409"}, + {"malformed body", http.StatusOK, `{"success":`, "failed to parse start response"}, + {"unsuccessful", http.StatusOK, `{"success":false,"error":"binary not found"}`, "start failed: binary not found"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(tc.status, tc.body)) + + command, err := newHTTPOnlyClient(srv.URL).Start(context.Background()) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + if command != "" { + t.Errorf("command = %q, want empty on failure", command) + } + }) + } +} + +func TestStop_PostsToStopEndpoint(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{"success":true}`)) + + if err := newHTTPOnlyClient(srv.URL).Stop(context.Background()); err != nil { + t.Fatalf("Stop: %v", err) + } + if got.Method != http.MethodPost || got.Path != "/api/v1/stop" { + t.Errorf("request = %s %s, want POST /api/v1/stop", got.Method, got.Path) + } +} + +func TestStop_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-2xx status", http.StatusInternalServerError, `boom`, "stop request failed with status 500"}, + {"malformed body", http.StatusOK, `{"success":`, "failed to parse stop response"}, + {"unsuccessful", http.StatusOK, `{"success":false,"error":"no agent running"}`, "stop failed: no agent running"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(tc.status, tc.body)) + + err := newHTTPOnlyClient(srv.URL).Stop(context.Background()) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + }) + } +} + +func TestWaitForReady_ReturnsOnceHealthSucceeds(t *testing.T) { + // The handler runs on the server's goroutine while the test goroutine reads + // the counter, so the count is atomic rather than a plain int. + var probes atomic.Int64 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if probes.Add(1) < 2 { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(srv.Close) + + if err := newHTTPOnlyClient(srv.URL).WaitForReady(context.Background(), 5*time.Second); err != nil { + t.Fatalf("WaitForReady: %v", err) + } + if n := probes.Load(); n < 2 { + t.Errorf("probes = %d, want the poll loop to retry past the first failure", n) + } +} + +func TestWaitForReady_ReturnsContextErrorWhenCancelled(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusServiceUnavailable) + })) + t.Cleanup(srv.Close) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + err := newHTTPOnlyClient(srv.URL).WaitForReady(ctx, 5*time.Second) + if err == nil || !strings.Contains(err.Error(), "context canceled") { + t.Fatalf("error = %v, want context canceled", err) + } +} + +func TestWaitForReady_TimesOutWhenNeverHealthy(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusServiceUnavailable) + })) + t.Cleanup(srv.Close) + client := newHTTPOnlyClient(srv.URL) + + // The deadline is only checked on a 500ms tick, so a zero timeout still + // waits one full tick before expiring. synctest advances that fake tick + // instantly once the poll loop is durably blocked — with a zero timeout the + // loop never reaches Health, so nothing inside the bubble does real I/O. + synctest.Test(t, func(t *testing.T) { + err := client.WaitForReady(context.Background(), 0) + if err == nil || !strings.Contains(err.Error(), "timeout waiting for agentctl to be ready") { + t.Fatalf("error = %v, want the ready timeout", err) + } + }) +} + +func TestStartVscode_PostsThemeAndDecodesResponse(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, + `{"success":true,"status":"running","port":8443}`)) + + resp, err := newHTTPOnlyClient(srv.URL).StartVscode(context.Background(), "dark") + if err != nil { + t.Fatalf("StartVscode: %v", err) + } + + if got.Method != http.MethodPost || got.Path != "/api/v1/vscode/start" { + t.Errorf("request = %s %s, want POST /api/v1/vscode/start", got.Method, got.Path) + } + if got.ContentType != "application/json" { + t.Errorf("content-type = %q, want application/json", got.ContentType) + } + + var sent struct { + Theme string `json:"theme"` + } + if err := json.Unmarshal(got.Body, &sent); err != nil { + t.Fatalf("decode sent body: %v", err) + } + if sent.Theme != "dark" { + t.Errorf("sent theme = %q, want dark", sent.Theme) + } + if !resp.Success || resp.Port != 8443 || resp.Status != "running" { + t.Errorf("response = %+v, want success running on port 8443", resp) + } +} + +func TestStartVscode_OmitsEmptyTheme(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{"success":true}`)) + + if _, err := newHTTPOnlyClient(srv.URL).StartVscode(context.Background(), ""); err != nil { + t.Fatalf("StartVscode: %v", err) + } + var raw map[string]json.RawMessage + if err := json.Unmarshal(got.Body, &raw); err != nil { + t.Fatalf("decode sent body: %v", err) + } + if _, present := raw["theme"]; present { + t.Errorf("theme sent despite being empty: %s", got.Body) + } +} + +func TestStartVscode_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-2xx status", http.StatusInternalServerError, `boom`, "vscode start failed with status 500"}, + {"malformed body", http.StatusOK, `{"success":`, "failed to parse vscode start response"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(tc.status, tc.body)) + + resp, err := newHTTPOnlyClient(srv.URL).StartVscode(context.Background(), "dark") + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + if resp != nil { + t.Errorf("response = %+v, want nil on failure", resp) + } + }) + } +} + +func TestStopVscode_PostsAndFailsOnNonOKStatus(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{"success":true}`)) + if err := newHTTPOnlyClient(srv.URL).StopVscode(context.Background()); err != nil { + t.Fatalf("StopVscode: %v", err) + } + if got.Method != http.MethodPost || got.Path != "/api/v1/vscode/stop" { + t.Errorf("request = %s %s, want POST /api/v1/vscode/stop", got.Method, got.Path) + } + + failing, _ := captureServer(t, jsonResponder(http.StatusInternalServerError, `not running`)) + err := newHTTPOnlyClient(failing.URL).StopVscode(context.Background()) + if err == nil || !strings.Contains(err.Error(), "vscode stop failed with status 500") { + t.Fatalf("error = %v, want status 500 named", err) + } + if !strings.Contains(err.Error(), "not running") { + t.Errorf("error = %v, want the server body echoed", err) + } +} + +func TestVscodeOpenFile_PostsPathLineAndColumn(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{"success":true}`)) + + err := newHTTPOnlyClient(srv.URL).VscodeOpenFile(context.Background(), "src/main.go", 42, 7) + if err != nil { + t.Fatalf("VscodeOpenFile: %v", err) + } + + if got.Method != http.MethodPost || got.Path != "/api/v1/vscode/open-file" { + t.Errorf("request = %s %s, want POST /api/v1/vscode/open-file", got.Method, got.Path) + } + + var sent types.VscodeOpenFileRequest + if err := json.Unmarshal(got.Body, &sent); err != nil { + t.Fatalf("decode sent body: %v", err) + } + if sent.Path != "src/main.go" { + t.Errorf("sent path = %q, want src/main.go", sent.Path) + } + if sent.Line != 42 || sent.Col != 7 { + t.Errorf("sent line/col = %d / %d, want 42 / 7", sent.Line, sent.Col) + } +} + +func TestVscodeOpenFile_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-2xx status", http.StatusBadGateway, `down`, "vscode open-file failed with status 502"}, + {"malformed body", http.StatusOK, `{"success":`, "failed to parse vscode open-file response"}, + {"unsuccessful", http.StatusOK, `{"success":false,"error":"no code-server"}`, "vscode open-file failed: no code-server"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(tc.status, tc.body)) + + err := newHTTPOnlyClient(srv.URL).VscodeOpenFile(context.Background(), "a.go", 1, 1) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + }) + } +} + +func TestVscodeStatus_DecodesRunningState(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, + `{"status":"running","port":8443,"url":"http://127.0.0.1:8443/","message":"ready"}`)) + + resp, err := newHTTPOnlyClient(srv.URL).VscodeStatus(context.Background()) + if err != nil { + t.Fatalf("VscodeStatus: %v", err) + } + + if got.Method != http.MethodGet || got.Path != "/api/v1/vscode/status" { + t.Errorf("request = %s %s, want GET /api/v1/vscode/status", got.Method, got.Path) + } + if resp.Status != "running" || resp.Port != 8443 { + t.Errorf("status/port = %q / %d, want running / 8443", resp.Status, resp.Port) + } + if resp.URL != "http://127.0.0.1:8443/" { + t.Errorf("URL = %q", resp.URL) + } + if resp.Message != "ready" { + t.Errorf("Message = %q, want ready", resp.Message) + } +} + +func TestVscodeStatus_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-2xx status", http.StatusInternalServerError, `boom`, "vscode status failed with status 500"}, + {"malformed body", http.StatusOK, `{"status":`, "failed to parse vscode status response"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(tc.status, tc.body)) + + resp, err := newHTTPOnlyClient(srv.URL).VscodeStatus(context.Background()) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + if resp != nil { + t.Errorf("response = %+v, want nil on failure", resp) + } + }) + } +} + +func TestClientHTTPMethods_HonourContextCancellation(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `{"success":true}`)) + c := newHTTPOnlyClient(srv.URL) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + calls := map[string]func() error{ + "Health": func() error { return c.Health(ctx) }, + "GetStatus": func() error { + _, err := c.GetStatus(ctx) + return err + }, + "ConfigureAgent": func() error { return c.ConfigureAgent(ctx, "cmd", nil, nil, "", "", nil) }, + "SetMcpMode": func() error { return c.SetMcpMode(ctx, "task") }, + "SetMcpProviders": func() error { return c.SetMcpProviders(ctx, nil) }, + "Start": func() error { + _, err := c.Start(ctx) + return err + }, + "Stop": func() error { return c.Stop(ctx) }, + "StartVscode": func() error { + _, err := c.StartVscode(ctx, "dark") + return err + }, + "StopVscode": func() error { return c.StopVscode(ctx) }, + "VscodeOpenFile": func() error { return c.VscodeOpenFile(ctx, "a.go", 1, 1) }, + "VscodeStatus": func() error { + _, err := c.VscodeStatus(ctx) + return err + }, + } + for name, call := range calls { + t.Run(name, func(t *testing.T) { + if err := call(); err == nil || !strings.Contains(err.Error(), "context canceled") { + t.Fatalf("error = %v, want context canceled", err) + } + }) + } +} + +func TestTruncateBody(t *testing.T) { + tests := []struct { + name string + body string + want string + }{ + {"short body is unchanged", "hello", "hello"}, + {"empty body", "", ""}, + {"exactly at the cap", strings.Repeat("x", 200), strings.Repeat("x", 200)}, + {"over the cap is elided", strings.Repeat("x", 201), strings.Repeat("x", 200) + "..."}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := truncateBody([]byte(tc.body)); got != tc.want { + t.Errorf("truncateBody(%d bytes) length = %d, want %d", + len(tc.body), len(got), len(tc.want)) + } + }) + } +} + +// A truncated error body must still name the status, so an HTML error page from +// a misrouted proxy is diagnosable from the log line alone. +func TestGetStatus_TruncatesOversizedMalformedBodyInError(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, strings.Repeat("z", 5000))) + + _, err := newHTTPOnlyClient(srv.URL).GetStatus(context.Background()) + if err == nil { + t.Fatal("GetStatus returned nil error for a 5000-byte non-JSON body") + } + if !strings.Contains(err.Error(), "...") { + t.Errorf("error = %v, want the body elided", err) + } + if len(err.Error()) > 500 { + t.Errorf("error message is %d bytes, want the body truncated to ~200", len(err.Error())) + } +} + +// Close is safe on a client that never opened a stream, and is idempotent. +func TestClose_IsSafeAndIdempotentWithoutStreams(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `{}`)) + c := newHTTPOnlyClient(srv.URL) + + c.Close() + c.Close() + + if !c.closed { + t.Error("closed = false after Close") + } + if c.HasAgentStream() { + t.Error("HasAgentStream = true on a client that never streamed") + } +} diff --git a/apps/backend/internal/agent/runtime/agentctl/client_files_test.go b/apps/backend/internal/agent/runtime/agentctl/client_files_test.go new file mode 100644 index 0000000000..abddfe7743 --- /dev/null +++ b/apps/backend/internal/agent/runtime/agentctl/client_files_test.go @@ -0,0 +1,647 @@ +package client + +import ( + "context" + "encoding/json" + "mime" + "net/http" + "strings" + "testing" + + "github.com/kandev/kandev/internal/agentctl/types/streams" + "github.com/kandev/kandev/internal/worktree/copyfiles" +) + +func TestRequestFileTree_BuildsQueryAndDecodesNestedTree(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{ + "request_id":"req-1", + "root":{ + "name":"src","path":"src","is_dir":true, + "children":[ + {"name":"main.go","path":"src/main.go","is_dir":false,"size":42}, + {"name":"link","path":"src/link","is_dir":false,"is_symlink":true} + ] + } + }`)) + + resp, err := newHTTPOnlyClient(srv.URL).RequestFileTree(context.Background(), "src/deep dir", 3) + if err != nil { + t.Fatalf("RequestFileTree: %v", err) + } + + if got.Method != http.MethodGet { + t.Errorf("method = %q, want GET", got.Method) + } + if got.Path != "/api/v1/workspace/tree" { + t.Errorf("path = %q, want /api/v1/workspace/tree", got.Path) + } + if p := got.Query.Get("path"); p != "src/deep dir" { + t.Errorf("path query = %q, want %q", p, "src/deep dir") + } + if d := got.Query.Get("depth"); d != "3" { + t.Errorf("depth query = %q, want 3", d) + } + // QueryEscape encodes the space as '+', which is what the server must see. + if !strings.Contains(got.RawQuery, "path=src%2Fdeep+dir") { + t.Errorf("raw query = %q, want percent-escaped path", got.RawQuery) + } + + if resp.RequestID != "req-1" { + t.Errorf("RequestID = %q, want req-1", resp.RequestID) + } + if resp.Root == nil { + t.Fatal("Root = nil, want decoded tree") + } + if resp.Root.Name != "src" || resp.Root.Path != "src" || !resp.Root.IsDir { + t.Errorf("Root = %+v, want src dir node", resp.Root) + } + if len(resp.Root.Children) != 2 { + t.Fatalf("Root.Children = %d, want 2", len(resp.Root.Children)) + } + child := resp.Root.Children[0] + if child.Name != "main.go" || child.Path != "src/main.go" || child.IsDir || child.Size != 42 { + t.Errorf("Children[0] = %+v, want main.go file of 42 bytes", child) + } + if link := resp.Root.Children[1]; !link.IsSymlink || link.Name != "link" { + t.Errorf("Children[1] = %+v, want symlink node", link) + } +} + +func TestRequestFileTree_SurfacesResponseErrorField(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `{"error":"path escapes workspace"}`)) + + _, err := newHTTPOnlyClient(srv.URL).RequestFileTree(context.Background(), "../etc", 1) + if err == nil { + t.Fatal("RequestFileTree returned nil error for error-bearing body") + } + if !strings.Contains(err.Error(), "file tree error: path escapes workspace") { + t.Errorf("error = %v, want wrapped file tree error", err) + } +} + +func TestRequestFileTree_RejectsMalformedBody(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `{"root":`)) + + _, err := newHTTPOnlyClient(srv.URL).RequestFileTree(context.Background(), "src", 1) + if err == nil { + t.Fatal("RequestFileTree returned nil error for truncated JSON") + } + if !strings.Contains(err.Error(), "failed to parse response") { + t.Errorf("error = %v, want parse failure", err) + } +} + +func TestRequestFileTree_HonoursContextCancellation(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `{}`)) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + _, err := newHTTPOnlyClient(srv.URL).RequestFileTree(ctx, "src", 1) + if err == nil { + t.Fatal("RequestFileTree returned nil error for cancelled context") + } + if !strings.Contains(err.Error(), "context canceled") { + t.Errorf("error = %v, want context canceled", err) + } +} + +func TestSearchFiles_BuildsQueryAndDecodesBothResultShapes(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{ + "files":["a/b.go","c/d.go"], + "results":[ + {"repository_name":"backend","path":"a/b.go"}, + {"path":"c/d.go"} + ] + }`)) + + resp, err := newHTTPOnlyClient(srv.URL).SearchFiles(context.Background(), "b.go&x", 25) + if err != nil { + t.Fatalf("SearchFiles: %v", err) + } + + if got.Method != http.MethodGet || got.Path != "/api/v1/workspace/search" { + t.Errorf("request = %s %s, want GET /api/v1/workspace/search", got.Method, got.Path) + } + if q := got.Query.Get("q"); q != "b.go&x" { + t.Errorf("q = %q, want %q — ampersand must be escaped, not split into a new param", q, "b.go&x") + } + if l := got.Query.Get("limit"); l != "25" { + t.Errorf("limit = %q, want 25", l) + } + + if len(resp.Files) != 2 || resp.Files[0] != "a/b.go" || resp.Files[1] != "c/d.go" { + t.Errorf("Files = %v, want both legacy paths", resp.Files) + } + if len(resp.Results) != 2 { + t.Fatalf("Results = %d, want 2", len(resp.Results)) + } + if resp.Results[0].RepositoryName != "backend" || resp.Results[0].Path != "a/b.go" { + t.Errorf("Results[0] = %+v, want backend/a/b.go", resp.Results[0]) + } + if resp.Results[1].RepositoryName != "" || resp.Results[1].Path != "c/d.go" { + t.Errorf("Results[1] = %+v, want untagged c/d.go", resp.Results[1]) + } +} + +func TestSearchFiles_RejectsNonOKStatus(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusServiceUnavailable, `{"files":[]}`)) + + _, err := newHTTPOnlyClient(srv.URL).SearchFiles(context.Background(), "q", 5) + if err == nil { + t.Fatal("SearchFiles returned nil error for 503") + } + if !strings.Contains(err.Error(), "503") { + t.Errorf("error = %v, want status 503 named", err) + } +} + +func TestRequestFileContent_OmitsRepoWhenEmptyAndDecodesEveryField(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{ + "request_id":"rc-1","path":"docs/readme.md","content":"aGk=", + "size":128,"is_binary":true,"resolved_path":"docs/real.md" + }`)) + + resp, err := newHTTPOnlyClient(srv.URL).RequestFileContent(context.Background(), "docs/readme.md", "") + if err != nil { + t.Fatalf("RequestFileContent: %v", err) + } + + if got.Path != "/api/v1/workspace/file/content" { + t.Errorf("path = %q, want /api/v1/workspace/file/content", got.Path) + } + if _, present := got.Query["repo"]; present { + t.Errorf("repo query present for single-repo call: %q", got.RawQuery) + } + if p := got.Query.Get("path"); p != "docs/readme.md" { + t.Errorf("path query = %q", p) + } + + if resp.RequestID != "rc-1" { + t.Errorf("RequestID = %q, want rc-1", resp.RequestID) + } + if resp.Path != "docs/readme.md" { + t.Errorf("Path = %q", resp.Path) + } + if resp.Content != "aGk=" { + t.Errorf("Content = %q, want aGk=", resp.Content) + } + if resp.Size != 128 { + t.Errorf("Size = %d, want 128", resp.Size) + } + if !resp.IsBinary { + t.Error("IsBinary = false, want true") + } + if resp.ResolvedPath != "docs/real.md" { + t.Errorf("ResolvedPath = %q, want docs/real.md", resp.ResolvedPath) + } +} + +func TestRequestFileContent_AppendsEscapedRepoSubpath(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{"path":"a.go","content":"x"}`)) + + if _, err := newHTTPOnlyClient(srv.URL).RequestFileContent(context.Background(), "a.go", "my repo/sub"); err != nil { + t.Fatalf("RequestFileContent: %v", err) + } + if repo := got.Query.Get("repo"); repo != "my repo/sub" { + t.Errorf("repo = %q, want %q", repo, "my repo/sub") + } +} + +func TestRequestFileContent_SurfacesResponseErrorField(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `{"error":"file not found"}`)) + + _, err := newHTTPOnlyClient(srv.URL).RequestFileContent(context.Background(), "gone.go", "") + if err == nil || !strings.Contains(err.Error(), "file content error: file not found") { + t.Fatalf("error = %v, want wrapped file content error", err) + } +} + +func TestRequestFileContentAtRef_SendsPathRefAndRepo(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{ + "request_id":"ref-1","path":"a.go","content":"old","size":3 + }`)) + + resp, err := newHTTPOnlyClient(srv.URL).RequestFileContentAtRef( + context.Background(), "a.go", "origin/main~2", "svc") + if err != nil { + t.Fatalf("RequestFileContentAtRef: %v", err) + } + + if got.Path != "/api/v1/workspace/file/content-at-ref" { + t.Errorf("path = %q, want /api/v1/workspace/file/content-at-ref", got.Path) + } + if ref := got.Query.Get("ref"); ref != "origin/main~2" { + t.Errorf("ref = %q, want origin/main~2", ref) + } + if p := got.Query.Get("path"); p != "a.go" { + t.Errorf("path = %q, want a.go", p) + } + if repo := got.Query.Get("repo"); repo != "svc" { + t.Errorf("repo = %q, want svc", repo) + } + if resp.RequestID != "ref-1" || resp.Content != "old" || resp.Size != 3 { + t.Errorf("response = %+v, want fully decoded", resp) + } +} + +func TestRequestFileContentAtRef_OmitsRepoWhenEmpty(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{"path":"a.go","content":"x"}`)) + + if _, err := newHTTPOnlyClient(srv.URL).RequestFileContentAtRef( + context.Background(), "a.go", "HEAD", ""); err != nil { + t.Fatalf("RequestFileContentAtRef: %v", err) + } + if _, present := got.Query["repo"]; present { + t.Errorf("repo query present for single-repo call: %q", got.RawQuery) + } +} + +func TestRequestFileContentAtRef_SurfacesResponseErrorField(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `{"error":"bad revision"}`)) + + _, err := newHTTPOnlyClient(srv.URL).RequestFileContentAtRef(context.Background(), "a.go", "nope", "") + if err == nil || !strings.Contains(err.Error(), "file content at ref error: bad revision") { + t.Fatalf("error = %v, want wrapped content-at-ref error", err) + } +} + +func TestApplyFileDiff_MarshalsFullRequestAndDecodesResolution(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{ + "request_id":"u-1","path":"a.go","success":true, + "new_hash":"deadbeef","resolution":"overwritten" + }`)) + + desired := "package main\n" + resp, err := newHTTPOnlyClient(srv.URL).ApplyFileDiff( + context.Background(), "a.go", "@@ -1 +1 @@\n-a\n+b\n", "cafe", "svc", &desired) + if err != nil { + t.Fatalf("ApplyFileDiff: %v", err) + } + + if got.Method != http.MethodPost || got.Path != "/api/v1/workspace/file/content" { + t.Errorf("request = %s %s, want POST /api/v1/workspace/file/content", got.Method, got.Path) + } + if got.ContentType != "application/json" { + t.Errorf("content-type = %q, want application/json", got.ContentType) + } + + var sent streams.FileUpdateRequest + if err := json.Unmarshal(got.Body, &sent); err != nil { + t.Fatalf("decode sent body: %v", err) + } + if sent.Path != "a.go" || sent.Repo != "svc" || sent.OriginalHash != "cafe" { + t.Errorf("sent = %+v, want path/repo/hash preserved", sent) + } + if sent.Diff != "@@ -1 +1 @@\n-a\n+b\n" { + t.Errorf("sent.Diff = %q", sent.Diff) + } + if sent.DesiredContent == nil || *sent.DesiredContent != desired { + t.Errorf("sent.DesiredContent = %v, want %q", sent.DesiredContent, desired) + } + + if resp.RequestID != "u-1" || resp.Path != "a.go" || !resp.Success { + t.Errorf("response = %+v, want successful update", resp) + } + if resp.NewHash != "deadbeef" { + t.Errorf("NewHash = %q, want deadbeef", resp.NewHash) + } + if resp.Resolution != "overwritten" { + t.Errorf("Resolution = %q, want overwritten", resp.Resolution) + } +} + +func TestApplyFileDiff_OmitsNilDesiredContent(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{"success":true}`)) + + if _, err := newHTTPOnlyClient(srv.URL).ApplyFileDiff( + context.Background(), "a.go", "d", "h", "", nil); err != nil { + t.Fatalf("ApplyFileDiff: %v", err) + } + + var raw map[string]json.RawMessage + if err := json.Unmarshal(got.Body, &raw); err != nil { + t.Fatalf("decode sent body: %v", err) + } + if _, present := raw["desired_content"]; present { + t.Errorf("desired_content sent despite nil pointer: %s", got.Body) + } + if _, present := raw["repo"]; present { + t.Errorf("repo sent despite empty value: %s", got.Body) + } +} + +func TestApplyFileDiff_SurfacesErrorFieldBeforeSuccessCheck(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `{"success":false,"error":"hash conflict"}`)) + + _, err := newHTTPOnlyClient(srv.URL).ApplyFileDiff(context.Background(), "a.go", "d", "h", "", nil) + if err == nil || !strings.Contains(err.Error(), "file update error: hash conflict") { + t.Fatalf("error = %v, want wrapped file update error", err) + } +} + +func TestApplyFileDiff_FailsOnUnsuccessfulResponseWithoutError(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `{"success":false}`)) + + _, err := newHTTPOnlyClient(srv.URL).ApplyFileDiff(context.Background(), "a.go", "d", "h", "", nil) + if err == nil || !strings.Contains(err.Error(), "file update failed") { + t.Fatalf("error = %v, want file update failed", err) + } +} + +func TestCreateFile_PostsPathAndRepoAndDecodesResponse(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{"path":"new.go","success":true}`)) + + resp, err := newHTTPOnlyClient(srv.URL).CreateFile(context.Background(), "new.go", "svc") + if err != nil { + t.Fatalf("CreateFile: %v", err) + } + + if got.Method != http.MethodPost || got.Path != "/api/v1/workspace/file/create" { + t.Errorf("request = %s %s, want POST /api/v1/workspace/file/create", got.Method, got.Path) + } + if got.ContentType != "application/json" { + t.Errorf("content-type = %q, want application/json", got.ContentType) + } + + var sent streams.FileCreateRequest + if err := json.Unmarshal(got.Body, &sent); err != nil { + t.Fatalf("decode sent body: %v", err) + } + if sent.Path != "new.go" || sent.Repo != "svc" { + t.Errorf("sent = %+v, want new.go in svc", sent) + } + + if resp.Path != "new.go" || !resp.Success { + t.Errorf("response = %+v, want created new.go", resp) + } +} + +func TestCreateFile_SurfacesErrorAndUnsuccessfulResponses(t *testing.T) { + tests := []struct { + name string + body string + want string + }{ + {"error field", `{"success":false,"error":"already exists"}`, "file create error: already exists"}, + {"unsuccessful", `{"success":false}`, "file create failed"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, tc.body)) + _, err := newHTTPOnlyClient(srv.URL).CreateFile(context.Background(), "new.go", "") + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("error = %v, want %q", err, tc.want) + } + }) + } +} + +func TestDeleteFile_UsesDeleteVerbWithEscapedQuery(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, + `{"request_id":"d-1","path":"old file.go","success":true}`)) + + resp, err := newHTTPOnlyClient(srv.URL).DeleteFile(context.Background(), "old file.go", "svc") + if err != nil { + t.Fatalf("DeleteFile: %v", err) + } + + if got.Method != http.MethodDelete { + t.Errorf("method = %q, want DELETE", got.Method) + } + if got.Path != "/api/v1/workspace/file" { + t.Errorf("path = %q, want /api/v1/workspace/file", got.Path) + } + if p := got.Query.Get("path"); p != "old file.go" { + t.Errorf("path query = %q, want %q", p, "old file.go") + } + if repo := got.Query.Get("repo"); repo != "svc" { + t.Errorf("repo = %q, want svc", repo) + } + if len(got.Body) != 0 { + t.Errorf("DELETE sent a body: %q", got.Body) + } + + if resp.RequestID != "d-1" || resp.Path != "old file.go" || !resp.Success { + t.Errorf("response = %+v, want deleted old file.go", resp) + } +} + +func TestDeleteFile_OmitsRepoWhenEmpty(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{"success":true}`)) + + if _, err := newHTTPOnlyClient(srv.URL).DeleteFile(context.Background(), "a.go", ""); err != nil { + t.Fatalf("DeleteFile: %v", err) + } + if _, present := got.Query["repo"]; present { + t.Errorf("repo query present for single-repo call: %q", got.RawQuery) + } +} + +func TestDeleteFile_SurfacesErrorAndUnsuccessfulResponses(t *testing.T) { + tests := []struct { + name string + body string + want string + }{ + {"error field", `{"success":false,"error":"permission denied"}`, "file delete error: permission denied"}, + {"unsuccessful", `{"success":false}`, "file delete failed"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, tc.body)) + _, err := newHTTPOnlyClient(srv.URL).DeleteFile(context.Background(), "a.go", "") + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("error = %v, want %q", err, tc.want) + } + }) + } +} + +func TestRenameFile_PostsBothPathsAndDecodesResponse(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, + `{"old_path":"a.go","new_path":"b.go","success":true}`)) + + resp, err := newHTTPOnlyClient(srv.URL).RenameFile(context.Background(), "a.go", "b.go", "svc") + if err != nil { + t.Fatalf("RenameFile: %v", err) + } + + if got.Method != http.MethodPost || got.Path != "/api/v1/workspace/file/rename" { + t.Errorf("request = %s %s, want POST /api/v1/workspace/file/rename", got.Method, got.Path) + } + + var sent streams.FileRenameRequest + if err := json.Unmarshal(got.Body, &sent); err != nil { + t.Fatalf("decode sent body: %v", err) + } + if sent.OldPath != "a.go" || sent.NewPath != "b.go" || sent.Repo != "svc" { + t.Errorf("sent = %+v, want a.go -> b.go in svc", sent) + } + + if resp.OldPath != "a.go" || resp.NewPath != "b.go" || !resp.Success { + t.Errorf("response = %+v, want renamed a.go -> b.go", resp) + } +} + +func TestRenameFile_SurfacesErrorAndUnsuccessfulResponses(t *testing.T) { + tests := []struct { + name string + body string + want string + }{ + {"error field", `{"success":false,"error":"target exists"}`, "file rename error: target exists"}, + {"unsuccessful", `{"success":false}`, "file rename failed"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, tc.body)) + _, err := newHTTPOnlyClient(srv.URL).RenameFile(context.Background(), "a.go", "b.go", "") + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("error = %v, want %q", err, tc.want) + } + }) + } +} + +func TestMaterializeDiagnosticBundle_StreamsZipToEscapedPath(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{"path":"/diag/b.zip","bytes":9}`)) + + resp, err := newHTTPOnlyClient(srv.URL).MaterializeDiagnosticBundle( + context.Background(), "bundle/id 1", strings.NewReader("ZIPBYTES!")) + if err != nil { + t.Fatalf("MaterializeDiagnosticBundle: %v", err) + } + + if got.Method != http.MethodPost { + t.Errorf("method = %q, want POST", got.Method) + } + // PathEscape (not QueryEscape) — the ID is a path segment, so '/' must be + // encoded and a space becomes %20 rather than '+'. + if got.Path != "/api/v1/workspace/diagnostics/bundle/id 1" { + t.Errorf("decoded path = %q, want the escaped id as one segment", got.Path) + } + if got.ContentType != "application/zip" { + t.Errorf("content-type = %q, want application/zip", got.ContentType) + } + if string(got.Body) != "ZIPBYTES!" { + t.Errorf("body = %q, want the raw source bytes", got.Body) + } + + if resp.Path != "/diag/b.zip" || resp.Bytes != 9 { + t.Errorf("response = %+v, want /diag/b.zip of 9 bytes", resp) + } +} + +func TestMaterializeDiagnosticBundle_FailsOnNonOKStatusAndErrorField(t *testing.T) { + tests := []struct { + name string + status int + body string + }{ + {"non-OK status", http.StatusInsufficientStorage, `{"path":"","bytes":0}`}, + {"error field on 200", http.StatusOK, `{"error":"bundle too large"}`}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(tc.status, tc.body)) + _, err := newHTTPOnlyClient(srv.URL).MaterializeDiagnosticBundle( + context.Background(), "b", strings.NewReader("x")) + if err == nil || !strings.Contains(err.Error(), "diagnostic materialization failed") { + t.Fatalf("error = %v, want materialization failure", err) + } + }) + } +} + +func TestCopyFiles_MarshalsEntriesAndDecodesCopiedAndWarnings(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, + `{"copied":[".env",".env.local"],"warnings":["skipped secrets/"]}`)) + + entries := []copyfiles.Entry{ + {RelPath: ".env", Mode: 0o600, Content: []byte("A=1")}, + {RelPath: ".env.local", Mode: 0o644, Content: []byte("B=2")}, + } + resp, err := newHTTPOnlyClient(srv.URL).CopyFiles(context.Background(), "svc", entries) + if err != nil { + t.Fatalf("CopyFiles: %v", err) + } + + if got.Method != http.MethodPost || got.Path != "/api/v1/workspace/copy-files" { + t.Errorf("request = %s %s, want POST /api/v1/workspace/copy-files", got.Method, got.Path) + } + if got.ContentType != "application/json" { + t.Errorf("content-type = %q, want application/json", got.ContentType) + } + + var sent CopyFilesRequest + if err := json.Unmarshal(got.Body, &sent); err != nil { + t.Fatalf("decode sent body: %v", err) + } + if sent.Repo != "svc" { + t.Errorf("sent.Repo = %q, want svc", sent.Repo) + } + if len(sent.Entries) != 2 { + t.Fatalf("sent.Entries = %d, want 2", len(sent.Entries)) + } + if sent.Entries[0].RelPath != ".env" || sent.Entries[0].Mode != 0o600 || + string(sent.Entries[0].Content) != "A=1" { + t.Errorf("sent.Entries[0] = %+v, want .env 0600 A=1", sent.Entries[0]) + } + if sent.Entries[1].RelPath != ".env.local" || string(sent.Entries[1].Content) != "B=2" { + t.Errorf("sent.Entries[1] = %+v, want .env.local B=2", sent.Entries[1]) + } + + if len(resp.Copied) != 2 || resp.Copied[0] != ".env" || resp.Copied[1] != ".env.local" { + t.Errorf("Copied = %v, want both entries", resp.Copied) + } + if len(resp.Warnings) != 1 || resp.Warnings[0] != "skipped secrets/" { + t.Errorf("Warnings = %v, want the skip warning", resp.Warnings) + } +} + +// CopyFiles is the one file helper that returns a non-nil response alongside +// its error, so callers can read partial progress out of a failed batch. +func TestCopyFiles_ReturnsPartialResponseWithError(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, + `{"copied":[".env"],"error":"disk full"}`)) + + resp, err := newHTTPOnlyClient(srv.URL).CopyFiles(context.Background(), "", nil) + if err == nil || !strings.Contains(err.Error(), "copy-files error: disk full") { + t.Fatalf("error = %v, want wrapped copy-files error", err) + } + if resp == nil { + t.Fatal("response = nil, want the partial result alongside the error") + } + if len(resp.Copied) != 1 || resp.Copied[0] != ".env" { + t.Errorf("Copied = %v, want the one file that made it", resp.Copied) + } +} + +func TestCopyFiles_RejectsMalformedBody(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `not json`)) + + _, err := newHTTPOnlyClient(srv.URL).CopyFiles(context.Background(), "", nil) + if err == nil || !strings.Contains(err.Error(), "failed to parse response") { + t.Fatalf("error = %v, want parse failure", err) + } +} + +// Guard the content-type the diagnostics endpoint depends on: agentctl routes +// the raw body straight to disk, so a JSON content-type would be a silent +// protocol break. +func TestMaterializeDiagnosticBundle_ContentTypeIsExactlyZip(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{"path":"p","bytes":1}`)) + + if _, err := newHTTPOnlyClient(srv.URL).MaterializeDiagnosticBundle( + context.Background(), "b", strings.NewReader("x")); err != nil { + t.Fatalf("MaterializeDiagnosticBundle: %v", err) + } + mediaType, _, err := mime.ParseMediaType(got.ContentType) + if err != nil { + t.Fatalf("parse content-type %q: %v", got.ContentType, err) + } + if mediaType != "application/zip" { + t.Errorf("media type = %q, want application/zip", mediaType) + } +} diff --git a/apps/backend/internal/agent/runtime/agentctl/client_misc_test.go b/apps/backend/internal/agent/runtime/agentctl/client_misc_test.go new file mode 100644 index 0000000000..47a0548748 --- /dev/null +++ b/apps/backend/internal/agent/runtime/agentctl/client_misc_test.go @@ -0,0 +1,396 @@ +package client + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "testing" + + "github.com/kandev/kandev/internal/agentctl/server/utility" +) + +func TestListPorts_UnwrapsPortsEnvelopeAndDecodesEveryField(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{ + "ports":[ + {"port":3000,"address":"0.0.0.0","process":"node"}, + {"port":5432,"address":"127.0.0.1"} + ] + }`)) + + ports, err := newHTTPOnlyClient(srv.URL).ListPorts(context.Background()) + if err != nil { + t.Fatalf("ListPorts: %v", err) + } + + if got.Method != http.MethodGet || got.Path != "/api/v1/ports" { + t.Errorf("request = %s %s, want GET /api/v1/ports", got.Method, got.Path) + } + if len(ports) != 2 { + t.Fatalf("ports = %d, want 2", len(ports)) + } + if ports[0].Port != 3000 || ports[0].Address != "0.0.0.0" || ports[0].Process != "node" { + t.Errorf("ports[0] = %+v, want 3000 on 0.0.0.0 owned by node", ports[0]) + } + if ports[1].Port != 5432 || ports[1].Address != "127.0.0.1" || ports[1].Process != "" { + t.Errorf("ports[1] = %+v, want 5432 on loopback with no owner", ports[1]) + } +} + +func TestListPorts_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-2xx status", http.StatusInternalServerError, `ss unavailable`, "list ports failed with status 500"}, + {"malformed body", http.StatusOK, `{"ports":`, "failed to parse list ports response"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(tc.status, tc.body)) + + ports, err := newHTTPOnlyClient(srv.URL).ListPorts(context.Background()) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + if ports != nil { + t.Errorf("ports = %+v, want nil on failure", ports) + } + }) + } +} + +func TestListPorts_EchoesServerBodyInStatusError(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusInternalServerError, `ss unavailable`)) + + _, err := newHTTPOnlyClient(srv.URL).ListPorts(context.Background()) + if err == nil || !strings.Contains(err.Error(), "ss unavailable") { + t.Fatalf("error = %v, want the server body echoed", err) + } +} + +func TestSystemMetrics_EncodesMetricIDsAsCommaSeparatedQuery(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{ + "id":"agentctl","label":"Container","kind":"container", + "executor_type":"local_docker","session_id":"sess-1","task_id":"task-1", + "metrics":[ + {"id":"cpu","label":"CPU","unit":"percent","value":42.5,"available":true}, + {"id":"disk","label":"Disk","available":false,"error":"statfs failed"} + ] + }`)) + + snapshot, err := newHTTPOnlyClient(srv.URL).SystemMetrics( + context.Background(), []string{"cpu", "memory", "disk"}, "/workspace") + if err != nil { + t.Fatalf("SystemMetrics: %v", err) + } + + if got.Method != http.MethodGet || got.Path != "/api/v1/system/metrics" { + t.Errorf("request = %s %s, want GET /api/v1/system/metrics", got.Method, got.Path) + } + if m := got.Query.Get("metrics"); m != "cpu,memory,disk" { + t.Errorf("metrics = %q, want one comma-joined param, not repeated keys", m) + } + if len(got.Query["metrics"]) != 1 { + t.Errorf("metrics appears %d times, want 1", len(got.Query["metrics"])) + } + if d := got.Query.Get("disk_path"); d != "/workspace" { + t.Errorf("disk_path = %q, want /workspace", d) + } + + if snapshot.ID != "agentctl" || snapshot.Label != "Container" || snapshot.Kind != "container" { + t.Errorf("id/label/kind = %q / %q / %q", snapshot.ID, snapshot.Label, snapshot.Kind) + } + if snapshot.ExecutorType != "local_docker" || snapshot.SessionID != "sess-1" || + snapshot.TaskID != "task-1" { + t.Errorf("executor/session/task = %q / %q / %q", + snapshot.ExecutorType, snapshot.SessionID, snapshot.TaskID) + } + if len(snapshot.Metrics) != 2 { + t.Fatalf("Metrics = %d, want 2", len(snapshot.Metrics)) + } + cpu := snapshot.Metrics[0] + if cpu.ID != "cpu" || cpu.Label != "CPU" || cpu.Unit != "percent" || !cpu.Available { + t.Errorf("Metrics[0] = %+v, want an available cpu percent sample", cpu) + } + if cpu.Value == nil || *cpu.Value != 42.5 { + t.Errorf("Metrics[0].Value = %v, want pointer to 42.5", cpu.Value) + } + disk := snapshot.Metrics[1] + if disk.Available || disk.Error != "statfs failed" { + t.Errorf("Metrics[1] = %+v, want an unavailable sample carrying its error", disk) + } + if disk.Value != nil { + t.Errorf("Metrics[1].Value = %v, want nil for an unavailable sample", disk.Value) + } +} + +func TestSystemMetrics_OmitsEmptyQueryParams(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{"id":"a","metrics":[]}`)) + + if _, err := newHTTPOnlyClient(srv.URL).SystemMetrics(context.Background(), nil, ""); err != nil { + t.Fatalf("SystemMetrics: %v", err) + } + if got.RawQuery != "" { + t.Errorf("raw query = %q, want no '?' appended when nothing is selected", got.RawQuery) + } +} + +func TestSystemMetrics_ReturnsSnapshotAndErrorOnHTTPError(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusServiceUnavailable, + `{"id":"agentctl","metrics":[]}`)) + + snapshot, err := newHTTPOnlyClient(srv.URL).SystemMetrics(context.Background(), nil, "") + if err == nil || !strings.Contains(err.Error(), "system metrics failed with status 503") { + t.Fatalf("error = %v, want status 503 named", err) + } + if snapshot == nil || snapshot.ID != "agentctl" { + t.Errorf("snapshot = %+v, want the decoded body alongside the error", snapshot) + } +} + +func TestSystemMetrics_ReturnsNilSnapshotOnMalformedBody(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `{"id":`)) + + snapshot, err := newHTTPOnlyClient(srv.URL).SystemMetrics(context.Background(), nil, "") + if err == nil || !strings.Contains(err.Error(), "failed to parse response") { + t.Fatalf("error = %v, want parse failure", err) + } + if snapshot != nil { + t.Errorf("snapshot = %+v, want nil on decode failure", snapshot) + } +} + +func TestSetBaseBranches_PostsPerRepoMapIncludingTheRootKey(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{}`)) + + branches := map[string]string{"": "origin/main", "web": "origin/develop"} + if err := newHTTPOnlyClient(srv.URL).SetBaseBranches(context.Background(), branches); err != nil { + t.Fatalf("SetBaseBranches: %v", err) + } + + if got.Method != http.MethodPost || got.Path != "/api/v1/workspace/base-branches" { + t.Errorf("request = %s %s, want POST /api/v1/workspace/base-branches", got.Method, got.Path) + } + if got.ContentType != "application/json" { + t.Errorf("content-type = %q, want application/json", got.ContentType) + } + + var sent struct { + BaseBranches map[string]string `json:"base_branches"` + } + if err := json.Unmarshal(got.Body, &sent); err != nil { + t.Fatalf("decode sent body: %v", err) + } + // The empty key addresses the workspace root tracker — dropping it silently + // reverts single-repo tasks to the hardcoded origin/main fallback. + if sent.BaseBranches[""] != "origin/main" { + t.Errorf("base_branches[\"\"] = %q, want origin/main", sent.BaseBranches[""]) + } + if sent.BaseBranches["web"] != "origin/develop" { + t.Errorf("base_branches[web] = %q, want origin/develop", sent.BaseBranches["web"]) + } +} + +func TestSetBaseBranches_SendsNilMapToClearTheOverride(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{}`)) + + if err := newHTTPOnlyClient(srv.URL).SetBaseBranches(context.Background(), nil); err != nil { + t.Fatalf("SetBaseBranches: %v", err) + } + var raw map[string]json.RawMessage + if err := json.Unmarshal(got.Body, &raw); err != nil { + t.Fatalf("decode sent body: %v", err) + } + // The key must still be present: an absent field would leave the server's + // existing override in place rather than clearing it. + body, present := raw["base_branches"] + if !present { + t.Fatalf("base_branches absent from clear request: %s", got.Body) + } + if string(body) != "null" { + t.Errorf("base_branches = %s, want null", body) + } +} + +func TestSetBaseBranches_FailsOnNonOKStatusAndEchoesBody(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusBadRequest, `unknown repo "web"`)) + + err := newHTTPOnlyClient(srv.URL).SetBaseBranches( + context.Background(), map[string]string{"web": "x"}) + if err == nil || !strings.Contains(err.Error(), "set base branches failed with status 400") { + t.Fatalf("error = %v, want status 400 named", err) + } + if !strings.Contains(err.Error(), `unknown repo "web"`) { + t.Errorf("error = %v, want the server body echoed", err) + } +} + +func TestInferencePrompt_PostsRequestAndDecodesUsage(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{ + "success":true,"response":"a summary","model":"claude-haiku-4-5", + "prompt_tokens":120,"response_tokens":48,"duration_ms":1500 + }`)) + + resp, err := newHTTPOnlyClient(srv.URL).InferencePrompt(context.Background(), + &utility.PromptRequest{ + Prompt: "summarize this", + AgentID: "claude-code", + Model: "claude-haiku-4-5", + Mode: "default", + }) + if err != nil { + t.Fatalf("InferencePrompt: %v", err) + } + + if got.Method != http.MethodPost || got.Path != "/api/v1/inference/prompt" { + t.Errorf("request = %s %s, want POST /api/v1/inference/prompt", got.Method, got.Path) + } + if got.ContentType != "application/json" { + t.Errorf("content-type = %q, want application/json", got.ContentType) + } + + var sent utility.PromptRequest + if err := json.Unmarshal(got.Body, &sent); err != nil { + t.Fatalf("decode sent body: %v", err) + } + if sent.Prompt != "summarize this" || sent.AgentID != "claude-code" { + t.Errorf("sent prompt/agent = %q / %q", sent.Prompt, sent.AgentID) + } + if sent.Model != "claude-haiku-4-5" || sent.Mode != "default" { + t.Errorf("sent model/mode = %q / %q", sent.Model, sent.Mode) + } + + if !resp.Success || resp.Response != "a summary" { + t.Errorf("success/response = %v / %q", resp.Success, resp.Response) + } + if resp.Model != "claude-haiku-4-5" { + t.Errorf("Model = %q", resp.Model) + } + if resp.PromptTokens != 120 || resp.ResponseTokens != 48 { + t.Errorf("tokens = %d / %d, want 120 / 48", resp.PromptTokens, resp.ResponseTokens) + } + if resp.DurationMs != 1500 { + t.Errorf("DurationMs = %d, want 1500", resp.DurationMs) + } +} + +func TestProbe_PostsRequestAndDecodesAgentIdentity(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{ + "success":true,"duration_ms":900, + "agent_name":"claude-code","agent_version":"1.2.3","protocol_version":1 + }`)) + + resp, err := newHTTPOnlyClient(srv.URL).Probe(context.Background(), + &utility.ProbeRequest{ + AgentID: "claude-acp", + Model: "claude-opus-5", + Mode: "plan", + ConfigOptions: map[string]string{"thinking": "high"}, + Refresh: true, + }) + if err != nil { + t.Fatalf("Probe: %v", err) + } + + if got.Method != http.MethodPost || got.Path != "/api/v1/inference/probe" { + t.Errorf("request = %s %s, want POST /api/v1/inference/probe", got.Method, got.Path) + } + + var sent utility.ProbeRequest + if err := json.Unmarshal(got.Body, &sent); err != nil { + t.Fatalf("decode sent body: %v", err) + } + if sent.AgentID != "claude-acp" || sent.Model != "claude-opus-5" || sent.Mode != "plan" { + t.Errorf("sent agent/model/mode = %q / %q / %q", sent.AgentID, sent.Model, sent.Mode) + } + if sent.ConfigOptions["thinking"] != "high" || !sent.Refresh { + t.Errorf("sent config/refresh = %v / %v", sent.ConfigOptions, sent.Refresh) + } + + if !resp.Success || resp.DurationMs != 900 { + t.Errorf("success/duration = %v / %d", resp.Success, resp.DurationMs) + } + if resp.AgentName != "claude-code" || resp.AgentVersion != "1.2.3" { + t.Errorf("agent name/version = %q / %q", resp.AgentName, resp.AgentVersion) + } + if resp.ProtocolVersion != 1 { + t.Errorf("ProtocolVersion = %d, want 1", resp.ProtocolVersion) + } +} + +// Both utility endpoints share doLongRunningJSON, so the failure modes are +// asserted once through each entry point's label. +func TestLongRunningJSONEndpoints_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + call func(c *Client) error + wantErr string + }{ + { + name: "prompt non-2xx status", + status: http.StatusBadGateway, + body: `agent unreachable`, + call: func(c *Client) error { + _, err := c.InferencePrompt(context.Background(), &utility.PromptRequest{}) + return err + }, + wantErr: "utility prompt failed with status 502: agent unreachable", + }, + { + name: "prompt malformed body", + status: http.StatusOK, + body: `{"success":`, + call: func(c *Client) error { + _, err := c.InferencePrompt(context.Background(), &utility.PromptRequest{}) + return err + }, + wantErr: "failed to parse utility prompt response", + }, + { + name: "probe non-2xx status", + status: http.StatusInternalServerError, + body: `handshake timed out`, + call: func(c *Client) error { _, err := c.Probe(context.Background(), &utility.ProbeRequest{}); return err }, + wantErr: "probe failed with status 500: handshake timed out", + }, + { + name: "probe malformed body", + status: http.StatusOK, + body: `{"success":`, + call: func(c *Client) error { _, err := c.Probe(context.Background(), &utility.ProbeRequest{}); return err }, + wantErr: "failed to parse probe response", + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(tc.status, tc.body)) + + err := tc.call(newHTTPOnlyClient(srv.URL)) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + }) + } +} + +func TestLongRunningJSONEndpoints_HonourContextCancellation(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `{"success":true}`)) + c := newHTTPOnlyClient(srv.URL) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + if _, err := c.InferencePrompt(ctx, &utility.PromptRequest{}); err == nil || + !strings.Contains(err.Error(), "context canceled") { + t.Fatalf("InferencePrompt error = %v, want context canceled", err) + } + if _, err := c.Probe(ctx, &utility.ProbeRequest{}); err == nil || + !strings.Contains(err.Error(), "context canceled") { + t.Fatalf("Probe error = %v, want context canceled", err) + } +} diff --git a/apps/backend/internal/agent/runtime/agentctl/client_process_test.go b/apps/backend/internal/agent/runtime/agentctl/client_process_test.go new file mode 100644 index 0000000000..3b1cbfe2c7 --- /dev/null +++ b/apps/backend/internal/agent/runtime/agentctl/client_process_test.go @@ -0,0 +1,389 @@ +package client + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "testing" + "time" +) + +func TestStartProcess_MarshalsRequestAndDecodesProcessInfo(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{ + "process":{ + "id":"proc-1","session_id":"sess-1","kind":"script","script_name":"dev", + "command":"pnpm dev","working_dir":"/workspace/task-1","status":"running", + "exit_code":null, + "started_at":"2026-08-10T10:00:00Z","updated_at":"2026-08-10T10:00:05Z", + "output":[ + {"stream":"stdout","data":"listening\n","timestamp":"2026-08-10T10:00:01Z"}, + {"stream":"stderr","data":"warn\n","timestamp":"2026-08-10T10:00:02Z"} + ] + } + }`)) + + req := StartProcessRequest{ + SessionID: "sess-1", + Kind: "script", + ScriptName: "dev", + Command: "pnpm dev", + WorkingDir: "/workspace/task-1", + Env: map[string]string{"PORT": "3000"}, + BufferMaxBytes: 65536, + } + info, err := newHTTPOnlyClient(srv.URL).StartProcess(context.Background(), req) + if err != nil { + t.Fatalf("StartProcess: %v", err) + } + + if got.Method != http.MethodPost || got.Path != "/api/v1/processes/start" { + t.Errorf("request = %s %s, want POST /api/v1/processes/start", got.Method, got.Path) + } + if got.ContentType != "application/json" { + t.Errorf("content-type = %q, want application/json", got.ContentType) + } + + var sent StartProcessRequest + if err := json.Unmarshal(got.Body, &sent); err != nil { + t.Fatalf("decode sent body: %v", err) + } + if sent.SessionID != "sess-1" || sent.Kind != "script" || sent.ScriptName != "dev" { + t.Errorf("sent session/kind/script = %q / %q / %q", sent.SessionID, sent.Kind, sent.ScriptName) + } + if sent.Command != "pnpm dev" || sent.WorkingDir != "/workspace/task-1" { + t.Errorf("sent command/dir = %q / %q", sent.Command, sent.WorkingDir) + } + if sent.Env["PORT"] != "3000" || sent.BufferMaxBytes != 65536 { + t.Errorf("sent env/buffer = %v / %d", sent.Env, sent.BufferMaxBytes) + } + + if info.ID != "proc-1" || info.SessionID != "sess-1" { + t.Errorf("id/session = %q / %q", info.ID, info.SessionID) + } + if info.Kind != "script" || info.ScriptName != "dev" { + t.Errorf("kind/script = %q / %q", info.Kind, info.ScriptName) + } + if info.Command != "pnpm dev" || info.WorkingDir != "/workspace/task-1" { + t.Errorf("command/dir = %q / %q", info.Command, info.WorkingDir) + } + if info.Status != "running" { + t.Errorf("Status = %q, want running", info.Status) + } + if info.ExitCode != nil { + t.Errorf("ExitCode = %v, want nil while running", info.ExitCode) + } + if want := time.Date(2026, 8, 10, 10, 0, 0, 0, time.UTC); !info.StartedAt.Equal(want) { + t.Errorf("StartedAt = %v, want %v", info.StartedAt, want) + } + if want := time.Date(2026, 8, 10, 10, 0, 5, 0, time.UTC); !info.UpdatedAt.Equal(want) { + t.Errorf("UpdatedAt = %v, want %v", info.UpdatedAt, want) + } + if len(info.Output) != 2 { + t.Fatalf("Output = %d chunks, want 2", len(info.Output)) + } + if info.Output[0].Stream != "stdout" || info.Output[0].Data != "listening\n" { + t.Errorf("Output[0] = %+v, want the stdout chunk", info.Output[0]) + } + if want := time.Date(2026, 8, 10, 10, 0, 1, 0, time.UTC); !info.Output[0].Timestamp.Equal(want) { + t.Errorf("Output[0].Timestamp = %v, want %v", info.Output[0].Timestamp, want) + } + if info.Output[1].Stream != "stderr" || info.Output[1].Data != "warn\n" { + t.Errorf("Output[1] = %+v, want the stderr chunk", info.Output[1]) + } +} + +func TestStartProcess_DecodesExitCodeOnFinishedProcess(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, + `{"process":{"id":"p","status":"exited","exit_code":137}}`)) + + info, err := newHTTPOnlyClient(srv.URL).StartProcess( + context.Background(), StartProcessRequest{SessionID: "s"}) + if err != nil { + t.Fatalf("StartProcess: %v", err) + } + if info.ExitCode == nil { + t.Fatal("ExitCode = nil, want a decoded 137") + } + if *info.ExitCode != 137 { + t.Errorf("ExitCode = %d, want 137", *info.ExitCode) + } +} + +func TestStartProcess_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + { + name: "non-2xx status echoes body", + status: http.StatusBadRequest, + body: `{"error":"working_dir is required"}`, + wantErr: "start process failed with status 400", + }, + { + name: "malformed body", + status: http.StatusOK, + body: `{"process":`, + wantErr: "failed to parse start process response", + }, + { + name: "nil process with error field", + status: http.StatusOK, + body: `{"error":"spawn failed"}`, + wantErr: "start process failed: spawn failed", + }, + { + name: "nil process without error field", + status: http.StatusOK, + body: `{}`, + wantErr: "start process failed: no process returned", + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(tc.status, tc.body)) + + info, err := newHTTPOnlyClient(srv.URL).StartProcess( + context.Background(), StartProcessRequest{SessionID: "s"}) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + if info != nil { + t.Errorf("info = %+v, want nil on failure", info) + } + }) + } +} + +func TestStartProcess_EchoesServerBodyInStatusError(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusBadRequest, `{"error":"working_dir is required"}`)) + + _, err := newHTTPOnlyClient(srv.URL).StartProcess( + context.Background(), StartProcessRequest{SessionID: "s"}) + if err == nil || !strings.Contains(err.Error(), "working_dir is required") { + t.Fatalf("error = %v, want the server body included for diagnosis", err) + } +} + +func TestStopProcess_PostsProcessIDInBody(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{"success":true}`)) + + if err := newHTTPOnlyClient(srv.URL).StopProcess(context.Background(), "proc-7"); err != nil { + t.Fatalf("StopProcess: %v", err) + } + + if got.Method != http.MethodPost || got.Path != "/api/v1/processes/stop" { + t.Errorf("request = %s %s, want POST /api/v1/processes/stop", got.Method, got.Path) + } + if got.ContentType != "application/json" { + t.Errorf("content-type = %q, want application/json", got.ContentType) + } + + var sent map[string]string + if err := json.Unmarshal(got.Body, &sent); err != nil { + t.Fatalf("decode sent body: %v", err) + } + if sent["process_id"] != "proc-7" { + t.Errorf("sent process_id = %q, want proc-7", sent["process_id"]) + } +} + +func TestStopProcess_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-2xx status", http.StatusNotFound, `no such process`, "stop process failed with status 404"}, + {"malformed body", http.StatusOK, `{"success":`, "failed to parse stop process response"}, + {"unsuccessful", http.StatusOK, `{"success":false,"error":"already exited"}`, "stop process failed: already exited"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(tc.status, tc.body)) + + err := newHTTPOnlyClient(srv.URL).StopProcess(context.Background(), "proc-7") + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + }) + } +} + +func TestListProcesses_FiltersBySessionIDAndDecodesList(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `[ + {"id":"p1","session_id":"sess-1","kind":"script","command":"a","status":"running"}, + {"id":"p2","session_id":"sess-1","kind":"user_shell","command":"b","status":"exited","exit_code":0} + ]`)) + + processes, err := newHTTPOnlyClient(srv.URL).ListProcesses(context.Background(), "sess-1") + if err != nil { + t.Fatalf("ListProcesses: %v", err) + } + + if got.Method != http.MethodGet || got.Path != "/api/v1/processes" { + t.Errorf("request = %s %s, want GET /api/v1/processes", got.Method, got.Path) + } + if sid := got.Query.Get("session_id"); sid != "sess-1" { + t.Errorf("session_id = %q, want sess-1", sid) + } + + if len(processes) != 2 { + t.Fatalf("processes = %d, want 2", len(processes)) + } + if processes[0].ID != "p1" || processes[0].Kind != "script" || processes[0].Status != "running" { + t.Errorf("processes[0] = %+v", processes[0]) + } + if processes[1].ID != "p2" || processes[1].Kind != "user_shell" || processes[1].Status != "exited" { + t.Errorf("processes[1] = %+v", processes[1]) + } + if processes[1].ExitCode == nil || *processes[1].ExitCode != 0 { + t.Errorf("processes[1].ExitCode = %v, want pointer to 0", processes[1].ExitCode) + } +} + +func TestListProcesses_OmitsQueryWhenSessionIDIsEmpty(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `[]`)) + + processes, err := newHTTPOnlyClient(srv.URL).ListProcesses(context.Background(), "") + if err != nil { + t.Fatalf("ListProcesses: %v", err) + } + if got.RawQuery != "" { + t.Errorf("raw query = %q, want empty when unfiltered", got.RawQuery) + } + if len(processes) != 0 { + t.Errorf("processes = %+v, want empty", processes) + } +} + +func TestListProcesses_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-2xx status", http.StatusInternalServerError, `[]`, "list processes failed with status 500"}, + {"malformed body", http.StatusOK, `[{"id":`, "unexpected EOF"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(tc.status, tc.body)) + + processes, err := newHTTPOnlyClient(srv.URL).ListProcesses(context.Background(), "") + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + if processes != nil { + t.Errorf("processes = %+v, want nil on failure", processes) + } + }) + } +} + +func TestGetProcess_PutsIDInPathAndRequestsOutputOnDemand(t *testing.T) { + tests := []struct { + name string + includeOutput bool + wantQuery string + }{ + {"without output", false, ""}, + {"with output", true, "include_output=true"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{ + "id":"proc-4","session_id":"sess-2","kind":"script","command":"go test", + "working_dir":"/w","status":"running", + "output":[{"stream":"stdout","data":"ok\n","timestamp":"2026-08-10T10:00:00Z"}] + }`)) + + info, err := newHTTPOnlyClient(srv.URL).GetProcess( + context.Background(), "proc-4", tc.includeOutput) + if err != nil { + t.Fatalf("GetProcess: %v", err) + } + + if got.Method != http.MethodGet { + t.Errorf("method = %q, want GET", got.Method) + } + if got.Path != "/api/v1/processes/proc-4" { + t.Errorf("path = %q, want the ID as the last segment", got.Path) + } + if got.RawQuery != tc.wantQuery { + t.Errorf("raw query = %q, want %q", got.RawQuery, tc.wantQuery) + } + + if info.ID != "proc-4" || info.SessionID != "sess-2" { + t.Errorf("id/session = %q / %q", info.ID, info.SessionID) + } + if info.Command != "go test" || info.WorkingDir != "/w" || info.Status != "running" { + t.Errorf("command/dir/status = %q / %q / %q", info.Command, info.WorkingDir, info.Status) + } + if len(info.Output) != 1 || info.Output[0].Data != "ok\n" { + t.Errorf("Output = %+v, want one stdout chunk", info.Output) + } + }) + } +} + +func TestGetProcess_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-2xx status", http.StatusNotFound, `{}`, "get process failed with status 404"}, + {"malformed body", http.StatusOK, `{"id":`, "unexpected EOF"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(tc.status, tc.body)) + + info, err := newHTTPOnlyClient(srv.URL).GetProcess(context.Background(), "p", false) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + if info != nil { + t.Errorf("info = %+v, want nil on failure", info) + } + }) + } +} + +func TestProcessEndpoints_HonourContextCancellation(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `{"success":true}`)) + c := newHTTPOnlyClient(srv.URL) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + calls := map[string]func() error{ + "StartProcess": func() error { + _, err := c.StartProcess(ctx, StartProcessRequest{SessionID: "s"}) + return err + }, + "StopProcess": func() error { return c.StopProcess(ctx, "p") }, + "ListProcesses": func() error { + _, err := c.ListProcesses(ctx, "") + return err + }, + "GetProcess": func() error { + _, err := c.GetProcess(ctx, "p", false) + return err + }, + } + for name, call := range calls { + t.Run(name, func(t *testing.T) { + if err := call(); err == nil || !strings.Contains(err.Error(), "context canceled") { + t.Fatalf("error = %v, want context canceled", err) + } + }) + } +} diff --git a/apps/backend/internal/agent/runtime/agentctl/client_shell_terminal_test.go b/apps/backend/internal/agent/runtime/agentctl/client_shell_terminal_test.go new file mode 100644 index 0000000000..90f2cf9efe --- /dev/null +++ b/apps/backend/internal/agent/runtime/agentctl/client_shell_terminal_test.go @@ -0,0 +1,405 @@ +package client + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/gorilla/websocket" +) + +func TestStartShellTerminal_PostsTerminalGeometry(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{}`)) + + if err := newHTTPOnlyClient(srv.URL).StartShellTerminal( + context.Background(), "term-1", 120, 40); err != nil { + t.Fatalf("StartShellTerminal: %v", err) + } + + if got.Method != http.MethodPost || got.Path != "/api/v1/shell/terminal/start" { + t.Errorf("request = %s %s, want POST /api/v1/shell/terminal/start", got.Method, got.Path) + } + if got.ContentType != "application/json" { + t.Errorf("content-type = %q, want application/json", got.ContentType) + } + + var sent struct { + TerminalID string `json:"terminal_id"` + Cols int `json:"cols"` + Rows int `json:"rows"` + } + if err := json.Unmarshal(got.Body, &sent); err != nil { + t.Fatalf("decode sent body: %v", err) + } + if sent.TerminalID != "term-1" { + t.Errorf("terminal_id = %q, want term-1", sent.TerminalID) + } + if sent.Cols != 120 || sent.Rows != 40 { + t.Errorf("cols/rows = %d / %d, want 120 / 40", sent.Cols, sent.Rows) + } +} + +func TestStartShellTerminal_FailsOnNonOKStatusWithoutRetrying(t *testing.T) { + // The handler runs on the server's goroutine while the test goroutine reads + // the counter, so the count is atomic rather than a plain int. + var attempts atomic.Int64 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + attempts.Add(1) + w.WriteHeader(http.StatusInternalServerError) + })) + t.Cleanup(srv.Close) + + err := newHTTPOnlyClient(srv.URL).StartShellTerminal(context.Background(), "term-1", 80, 24) + if err == nil || !strings.Contains(err.Error(), "start shell terminal failed: 500") { + t.Fatalf("error = %v, want status 500 named", err) + } + // A status error means agentctl answered — retrying would just repeat a + // deterministic rejection, so the client must give up immediately. + if n := attempts.Load(); n != 1 { + t.Errorf("attempts = %d, want 1 — status errors must not be retried", n) + } +} + +// flakyTransport fails the first `failures` round trips with `err`, then +// delegates to base. It stands in for the Sprites proxy tunnel dropping the +// first connection attempt. +// +// Note: the retry tests install this as the client's whole Transport, which +// replaces anything WithAuthToken/WithExecutionID would have chained on. +// newHTTPOnlyClient sets no auth options, so these tests are correctly +// isolated — but if a future test builds its client through NewClient with auth +// options, it must wrap the existing c.httpClient.Transport as `base` instead +// of overwriting it, or the retried request will silently lose its headers. +type flakyTransport struct { + mu sync.Mutex + failures int + attempts int + err error + base http.RoundTripper +} + +func (t *flakyTransport) RoundTrip(req *http.Request) (*http.Response, error) { + t.mu.Lock() + t.attempts++ + shouldFail := t.attempts <= t.failures + t.mu.Unlock() + if shouldFail { + return nil, t.err + } + return t.base.RoundTrip(req) +} + +func (t *flakyTransport) attemptCount() int { + t.mu.Lock() + defer t.mu.Unlock() + return t.attempts +} + +func TestStartShellTerminal_RetriesTransientConnectionErrors(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{}`)) + + c := newHTTPOnlyClient(srv.URL) + transport := &flakyTransport{ + failures: 1, + err: errors.New("dial tcp 127.0.0.1:1: connect: connection refused"), + base: http.DefaultTransport, + } + c.httpClient.Transport = transport + + if err := c.StartShellTerminal(context.Background(), "term-1", 80, 24); err != nil { + t.Fatalf("StartShellTerminal should have recovered on retry: %v", err) + } + if transport.attemptCount() != 2 { + t.Errorf("attempts = %d, want 2 (one transient failure then success)", transport.attemptCount()) + } + // The retry must rebuild the body — a consumed reader would post an empty + // payload on the second attempt. + var sent struct { + TerminalID string `json:"terminal_id"` + } + if err := json.Unmarshal(got.Body, &sent); err != nil { + t.Fatalf("decode retried body: %v", err) + } + if sent.TerminalID != "term-1" { + t.Errorf("retried terminal_id = %q, want term-1 — the retry lost the body", sent.TerminalID) + } +} + +func TestStartShellTerminal_DoesNotRetryNonTransientErrors(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `{}`)) + + c := newHTTPOnlyClient(srv.URL) + transport := &flakyTransport{ + failures: 1, + err: errors.New("x509: certificate signed by unknown authority"), + base: http.DefaultTransport, + } + c.httpClient.Transport = transport + + err := c.StartShellTerminal(context.Background(), "term-1", 80, 24) + if err == nil || !strings.Contains(err.Error(), "certificate signed by unknown authority") { + t.Fatalf("error = %v, want the transport error surfaced", err) + } + if transport.attemptCount() != 1 { + t.Errorf("attempts = %d, want 1 — a TLS failure is not transient", transport.attemptCount()) + } +} + +// signallingTransport fails its first round trip with a transient error and +// announces it on `first`, then delegates every later attempt to base so the +// real transport can observe the request context. +type signallingTransport struct { + mu sync.Mutex + attempts int + first chan struct{} + once sync.Once + base http.RoundTripper +} + +func (t *signallingTransport) RoundTrip(req *http.Request) (*http.Response, error) { + t.mu.Lock() + t.attempts++ + isFirst := t.attempts == 1 + t.mu.Unlock() + if isFirst { + t.once.Do(func() { close(t.first) }) + return nil, errors.New("read tcp 127.0.0.1:1: connection reset by peer") + } + return t.base.RoundTrip(req) +} + +// StartShellTerminal's retry loop sleeps with time.Sleep rather than a +// context-aware timer, so cancelling mid-backoff does not shorten the wait — +// the call still burns the full 200ms before the next attempt notices. This +// pins that observable behaviour; if the production loop is changed to +// `time.NewTimer` + `select` on ctx.Done() (the convention in +// apps/backend/CLAUDE.md), this test should be inverted to assert a prompt +// return instead. +func TestStartShellTerminal_RetryBackoffIsNotInterruptedByCancellation(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `{}`)) + + c := newHTTPOnlyClient(srv.URL) + transport := &signallingTransport{first: make(chan struct{}), base: http.DefaultTransport} + c.httpClient.Transport = transport + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + // Cancel as soon as the first attempt has failed, i.e. while the client is + // inside its 200ms backoff sleep. + go func() { + <-transport.first + cancel() + }() + + start := time.Now() + err := c.StartShellTerminal(ctx, "term-1", 80, 24) + elapsed := time.Since(start) + + // The second attempt reaches the real transport with a cancelled context. + if !errors.Is(err, context.Canceled) { + t.Fatalf("error = %v, want context.Canceled once the retry re-dials", err) + } + // A context-aware backoff would return in ~0ms; the fixed sleep means the + // caller waits the whole 200ms after cancellation. + if elapsed < 150*time.Millisecond { + t.Errorf("elapsed = %v, want >=150ms — the backoff is a plain time.Sleep, "+ + "so cancellation cannot cut it short", elapsed) + } + transport.mu.Lock() + attempts := transport.attempts + transport.mu.Unlock() + if attempts != 2 { + t.Errorf("attempts = %d, want 2 — one transient failure then a cancelled re-dial", attempts) + } +} + +func TestIsTransientConnError(t *testing.T) { + tests := []struct { + name string + err error + want bool + }{ + {"nil", nil, false}, + {"connection reset", errors.New("read tcp: connection reset by peer"), true}, + {"connection refused", errors.New("dial tcp: connect: connection refused"), true}, + {"io.EOF sentinel", io.EOF, true}, + {"unexpected EOF text", fmt.Errorf("proxy: %w", io.ErrUnexpectedEOF), true}, + {"wrapped connection reset", fmt.Errorf("post: %w", errors.New("connection reset")), true}, + {"plain EOF text is not matched", errors.New("EOF"), false}, + {"unrelated", errors.New("permission denied"), false}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := isTransientConnError(tc.err); got != tc.want { + t.Errorf("isTransientConnError(%v) = %v, want %v", tc.err, got, tc.want) + } + }) + } +} + +func TestShellTerminalBuffer_ReturnsDecodedData(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, + `{"terminal_id":"term-1","data":"$ echo hi\r\nhi\r\n"}`)) + + data, err := newHTTPOnlyClient(srv.URL).ShellTerminalBuffer(context.Background(), "term-1") + if err != nil { + t.Fatalf("ShellTerminalBuffer: %v", err) + } + + if got.Method != http.MethodGet { + t.Errorf("method = %q, want GET", got.Method) + } + if got.Path != "/api/v1/shell/terminal/term-1/buffer" { + t.Errorf("path = %q, want the terminal ID between /terminal/ and /buffer", got.Path) + } + if data != "$ echo hi\r\nhi\r\n" { + t.Errorf("data = %q, want the buffered terminal output", data) + } +} + +func TestShellTerminalBuffer_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-OK status", http.StatusNotFound, `{}`, "shell terminal buffer failed"}, + {"malformed body", http.StatusOK, `{"data":`, "unexpected EOF"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(tc.status, tc.body)) + + data, err := newHTTPOnlyClient(srv.URL).ShellTerminalBuffer(context.Background(), "term-1") + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + if data != "" { + t.Errorf("data = %q, want empty on failure", data) + } + }) + } +} + +func TestStopShellTerminal_UsesDeleteVerbOnTerminalPath(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{}`)) + + if err := newHTTPOnlyClient(srv.URL).StopShellTerminal(context.Background(), "term-1"); err != nil { + t.Fatalf("StopShellTerminal: %v", err) + } + + if got.Method != http.MethodDelete { + t.Errorf("method = %q, want DELETE", got.Method) + } + if got.Path != "/api/v1/shell/terminal/term-1" { + t.Errorf("path = %q, want /api/v1/shell/terminal/term-1", got.Path) + } +} + +func TestStopShellTerminal_FailsOnNonOKStatus(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusConflict, `{}`)) + + err := newHTTPOnlyClient(srv.URL).StopShellTerminal(context.Background(), "term-1") + if err == nil || !strings.Contains(err.Error(), "stop shell terminal failed") { + t.Fatalf("error = %v, want the stop failure named", err) + } + if !strings.Contains(err.Error(), "409") { + t.Errorf("error = %v, want the HTTP status carried through", err) + } +} + +func TestStreamShellTerminal_DialsBinaryWebSocketWithAuthHeaders(t *testing.T) { + upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }} + var gotPath, gotAuth, gotInstance string + serverDone := make(chan struct{}) + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotPath = r.URL.Path + gotAuth = r.Header.Get("Authorization") + gotInstance = r.Header.Get("X-Instance-ID") + conn, err := upgrader.Upgrade(w, r, nil) + if err != nil { + close(serverDone) + return + } + defer func() { + _ = conn.Close() + close(serverDone) + }() + _ = conn.WriteMessage(websocket.BinaryMessage, []byte("hello from pty")) + // Block until the client hangs up so the handler owns its own teardown. + for { + if _, _, err := conn.ReadMessage(); err != nil { + return + } + } + })) + t.Cleanup(srv.Close) + + c := newHTTPOnlyClient(srv.URL) + c.authToken = "term-token" + c.executionID = "exec-9" + + conn, err := c.StreamShellTerminal(context.Background(), "term-1") + if err != nil { + t.Fatalf("StreamShellTerminal: %v", err) + } + + msgType, payload, err := conn.ReadMessage() + if err != nil { + _ = conn.Close() + t.Fatalf("read from terminal stream: %v", err) + } + if msgType != websocket.BinaryMessage { + t.Errorf("message type = %d, want BinaryMessage", msgType) + } + if string(payload) != "hello from pty" { + t.Errorf("payload = %q, want the pty bytes", payload) + } + + // The caller owns the connection; closing it drains the server handler. + if err := conn.Close(); err != nil { + t.Errorf("close terminal stream: %v", err) + } + <-serverDone + + if gotPath != "/api/v1/shell/terminal/term-1/stream" { + t.Errorf("path = %q, want /api/v1/shell/terminal/term-1/stream", gotPath) + } + if gotAuth != "Bearer term-token" { + t.Errorf("Authorization = %q, want Bearer term-token", gotAuth) + } + if gotInstance != "exec-9" { + t.Errorf("X-Instance-ID = %q, want exec-9 — a recycled port would go undetected", gotInstance) + } +} + +func TestStreamShellTerminal_ReturnsErrorWhenUpgradeIsRefused(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, "no such terminal", http.StatusNotFound) + })) + t.Cleanup(srv.Close) + + conn, err := newHTTPOnlyClient(srv.URL).StreamShellTerminal(context.Background(), "gone") + if err == nil { + _ = conn.Close() + t.Fatal("StreamShellTerminal returned nil error for a refused upgrade") + } + if !strings.Contains(err.Error(), "failed to connect to shell terminal stream") { + t.Errorf("error = %v, want the dial failure wrapped", err) + } + if conn != nil { + t.Error("conn non-nil alongside an error") + } +} diff --git a/apps/backend/internal/agent/runtime/agentctl/client_shell_test.go b/apps/backend/internal/agent/runtime/agentctl/client_shell_test.go new file mode 100644 index 0000000000..07fe2941b0 --- /dev/null +++ b/apps/backend/internal/agent/runtime/agentctl/client_shell_test.go @@ -0,0 +1,151 @@ +package client + +import ( + "context" + "net/http" + "strings" + "testing" +) + +func TestShellStatus_DecodesSessionState(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, + `{"running":true,"pid":8123,"shell":"/bin/bash","cwd":"/workspace/task-1"}`)) + + status, err := newHTTPOnlyClient(srv.URL).ShellStatus(context.Background()) + if err != nil { + t.Fatalf("ShellStatus: %v", err) + } + + if got.Method != http.MethodGet || got.Path != "/api/v1/shell/status" { + t.Errorf("request = %s %s, want GET /api/v1/shell/status", got.Method, got.Path) + } + if !status.Running { + t.Error("Running = false, want true") + } + if status.Pid != 8123 { + t.Errorf("Pid = %d, want 8123", status.Pid) + } + if status.Shell != "/bin/bash" { + t.Errorf("Shell = %q, want /bin/bash", status.Shell) + } + if status.Cwd != "/workspace/task-1" { + t.Errorf("Cwd = %q, want /workspace/task-1", status.Cwd) + } +} + +func TestShellStatus_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-OK status", http.StatusNotFound, `{}`, "shell status failed"}, + {"malformed body", http.StatusOK, `{"running":`, "unexpected EOF"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(tc.status, tc.body)) + + status, err := newHTTPOnlyClient(srv.URL).ShellStatus(context.Background()) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + if status != nil { + t.Errorf("status = %+v, want nil on failure", status) + } + }) + } +} + +func TestShellBuffer_ReturnsDataField(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, + `{"data":"$ ls\r\nREADME.md\r\n"}`)) + + data, err := newHTTPOnlyClient(srv.URL).ShellBuffer(context.Background()) + if err != nil { + t.Fatalf("ShellBuffer: %v", err) + } + + if got.Method != http.MethodGet || got.Path != "/api/v1/shell/buffer" { + t.Errorf("request = %s %s, want GET /api/v1/shell/buffer", got.Method, got.Path) + } + if data != "$ ls\r\nREADME.md\r\n" { + t.Errorf("data = %q, want the buffered shell output", data) + } +} + +func TestShellBuffer_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-OK status", http.StatusInternalServerError, `{}`, "shell buffer failed"}, + {"malformed body", http.StatusOK, `{"data":`, "unexpected EOF"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(tc.status, tc.body)) + + data, err := newHTTPOnlyClient(srv.URL).ShellBuffer(context.Background()) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + if data != "" { + t.Errorf("data = %q, want empty on failure", data) + } + }) + } +} + +func TestStartShell_PostsToShellStart(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{}`)) + + if err := newHTTPOnlyClient(srv.URL).StartShell(context.Background()); err != nil { + t.Fatalf("StartShell: %v", err) + } + if got.Method != http.MethodPost || got.Path != "/api/v1/shell/start" { + t.Errorf("request = %s %s, want POST /api/v1/shell/start", got.Method, got.Path) + } +} + +func TestStartShell_FailsOnNonOKStatus(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusConflict, `{}`)) + + err := newHTTPOnlyClient(srv.URL).StartShell(context.Background()) + if err == nil || !strings.Contains(err.Error(), "start shell failed") { + t.Fatalf("error = %v, want the start failure named", err) + } + if !strings.Contains(err.Error(), "409") { + t.Errorf("error = %v, want the HTTP status carried through", err) + } +} + +func TestShellEndpoints_HonourContextCancellation(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `{}`)) + c := newHTTPOnlyClient(srv.URL) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + calls := map[string]func() error{ + "ShellStatus": func() error { + _, err := c.ShellStatus(ctx) + return err + }, + "ShellBuffer": func() error { + _, err := c.ShellBuffer(ctx) + return err + }, + "StartShell": func() error { return c.StartShell(ctx) }, + } + for name, call := range calls { + t.Run(name, func(t *testing.T) { + if err := call(); err == nil || !strings.Contains(err.Error(), "context canceled") { + t.Fatalf("error = %v, want context canceled", err) + } + }) + } +} diff --git a/apps/backend/internal/agent/runtime/agentctl/control_test.go b/apps/backend/internal/agent/runtime/agentctl/control_test.go new file mode 100644 index 0000000000..3c4ba785ef --- /dev/null +++ b/apps/backend/internal/agent/runtime/agentctl/control_test.go @@ -0,0 +1,607 @@ +package client + +import ( + "context" + "encoding/json" + "fmt" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + mcpprofile "github.com/kandev/kandev/internal/mcp/profile" + "github.com/kandev/kandev/internal/task/models" +) + +// splitTestServerHostPort turns an httptest listener address into the +// (host, port) pair the New*Client constructors take. +func splitTestServerHostPort(t *testing.T, srv *httptest.Server) (string, int) { + t.Helper() + host, port, err := net.SplitHostPort(srv.Listener.Addr().String()) + if err != nil { + t.Fatalf("split server address: %v", err) + } + var portNumber int + if _, err := fmt.Sscanf(port, "%d", &portNumber); err != nil { + t.Fatalf("parse server port: %v", err) + } + return host, portNumber +} + +// newTestControlClient builds a ControlClient pointed at srv, going through the +// real constructor so base-URL assembly and the auth transport are exercised. +func newTestControlClient(t *testing.T, srv *httptest.Server, opts ...ControlClientOption) *ControlClient { + t.Helper() + host, port := splitTestServerHostPort(t, srv) + return NewControlClient(host, port, newTestLogger(), opts...) +} + +func TestNewControlClient_BuildsBaseURLFromHostAndPort(t *testing.T) { + c := NewControlClient("agentctl.internal", 7777, newTestLogger()) + if c.baseURL != "http://agentctl.internal:7777" { + t.Errorf("baseURL = %q, want http://agentctl.internal:7777", c.baseURL) + } + if c.httpClient.Timeout != 30*time.Second { + t.Errorf("timeout = %v, want 30s", c.httpClient.Timeout) + } + if c.httpClient.Transport != nil { + t.Error("transport installed without an auth token") + } + if c.AuthToken() != "" { + t.Errorf("AuthToken = %q, want empty", c.AuthToken()) + } +} + +func TestControlClient_SetAuthTokenIsSentOnSubsequentRequests(t *testing.T) { + var seen []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + seen = append(seen, r.Header.Get("Authorization")) + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(srv.Close) + + c := newTestControlClient(t, srv) + if err := c.Health(context.Background()); err != nil { + t.Fatalf("Health before token: %v", err) + } + + c.SetAuthToken("rotated-token") + if c.AuthToken() != "rotated-token" { + t.Errorf("AuthToken = %q, want rotated-token", c.AuthToken()) + } + if err := c.Health(context.Background()); err != nil { + t.Fatalf("Health after token: %v", err) + } + + if len(seen) != 2 { + t.Fatalf("saw %d requests, want 2", len(seen)) + } + if seen[0] != "" { + t.Errorf("first Authorization = %q, want empty before SetAuthToken", seen[0]) + } + if seen[1] != "Bearer rotated-token" { + t.Errorf("second Authorization = %q, want Bearer rotated-token", seen[1]) + } +} + +func TestControlClient_Health(t *testing.T) { + tests := []struct { + name string + status int + wantErr string + }{ + {"healthy", http.StatusOK, ""}, + {"unavailable", http.StatusServiceUnavailable, "health check failed: 503"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + var gotPath, gotMethod string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotPath, gotMethod = r.URL.Path, r.Method + w.WriteHeader(tc.status) + })) + t.Cleanup(srv.Close) + + err := newTestControlClient(t, srv).Health(context.Background()) + if gotMethod != http.MethodGet || gotPath != "/health" { + t.Errorf("request = %s %s, want GET /health", gotMethod, gotPath) + } + if tc.wantErr == "" { + if err != nil { + t.Fatalf("Health: %v", err) + } + return + } + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + }) + } +} + +func TestControlClient_HealthHonoursContextCancellation(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(srv.Close) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + err := newTestControlClient(t, srv).Health(ctx) + if err == nil || !strings.Contains(err.Error(), "context canceled") { + t.Fatalf("error = %v, want context canceled", err) + } +} + +func TestHandshake_PostsNonceAndAdoptsReturnedToken(t *testing.T) { + var gotPath, gotMethod, gotContentType string + var gotBody map[string]string + var secondAuth string + requests := 0 + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests++ + if requests == 1 { + gotPath, gotMethod = r.URL.Path, r.Method + gotContentType = r.Header.Get("Content-Type") + _ = json.NewDecoder(r.Body).Decode(&gotBody) + _, _ = w.Write([]byte(`{"token":"issued-token"}`)) + return + } + secondAuth = r.Header.Get("Authorization") + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(srv.Close) + + c := newTestControlClient(t, srv) + token, err := c.Handshake(context.Background(), "one-time-nonce") + if err != nil { + t.Fatalf("Handshake: %v", err) + } + + if gotMethod != http.MethodPost || gotPath != "/auth/handshake" { + t.Errorf("request = %s %s, want POST /auth/handshake", gotMethod, gotPath) + } + if gotContentType != "application/json" { + t.Errorf("content-type = %q, want application/json", gotContentType) + } + if gotBody["nonce"] != "one-time-nonce" { + t.Errorf("nonce = %q, want one-time-nonce", gotBody["nonce"]) + } + if token != "issued-token" { + t.Errorf("token = %q, want issued-token", token) + } + if c.AuthToken() != "issued-token" { + t.Errorf("AuthToken = %q, want the handshake to adopt the token", c.AuthToken()) + } + + // The adopted token must actually reach the wire, not just the field. + if err := c.Health(context.Background()); err != nil { + t.Fatalf("Health after handshake: %v", err) + } + if secondAuth != "Bearer issued-token" { + t.Errorf("post-handshake Authorization = %q, want Bearer issued-token", secondAuth) + } +} + +func TestHandshake_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + { + name: "rejected with structured error", + status: http.StatusUnauthorized, + body: `{"error":"nonce already consumed"}`, + wantErr: "handshake rejected: nonce already consumed (status 401)", + }, + { + name: "rejected without structured error", + status: http.StatusForbidden, + body: `not json`, + wantErr: "handshake failed: status 403", + }, + { + name: "empty token", + status: http.StatusOK, + body: `{"token":""}`, + wantErr: "handshake returned empty token", + }, + { + name: "malformed success body", + status: http.StatusOK, + body: `{"token":`, + wantErr: "failed to decode handshake response", + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv := httptest.NewServer(jsonResponder(tc.status, tc.body)) + t.Cleanup(srv.Close) + + c := newTestControlClient(t, srv) + token, err := c.Handshake(context.Background(), "n") + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + if token != "" { + t.Errorf("token = %q, want empty on failure", token) + } + if c.AuthToken() != "" { + t.Errorf("AuthToken = %q, want no token adopted on failure", c.AuthToken()) + } + }) + } +} + +func TestSubprocessAdmission_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-OK status", http.StatusInternalServerError, `{}`, "failed to get subprocess admission: status 500"}, + {"malformed body", http.StatusOK, `{"pool":`, "failed to decode subprocess admission"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv := httptest.NewServer(jsonResponder(tc.status, tc.body)) + t.Cleanup(srv.Close) + + snapshot, err := newTestControlClient(t, srv).SubprocessAdmission(context.Background()) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + if snapshot.Pool != "" || snapshot.Capacity != 0 { + t.Errorf("snapshot = %+v, want the zero value on failure", snapshot) + } + }) + } +} + +func TestCreateInstance_MarshalsFullRequestAndDecodesIDAndPort(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusCreated, `{"id":"inst-1","port":41234}`)) + + autoApprove := true + req := &CreateInstanceRequest{ + ID: "inst-1", + WorkspacePath: "/workspace/task-1", + AgentCommand: "claude-code acp", + Protocol: "acp", + AgentType: "codex", + WorkspaceFlag: "--workspace-root", + Env: map[string]string{"FOO": "bar"}, + AutoStart: true, + AutoApprovePermissions: &autoApprove, + McpServers: []McpServerConfig{{ + Name: "kandev", + URL: "http://127.0.0.1:9/mcp", + Type: "http", + Command: "kandev-mcp", + Args: []string{"--stdio"}, + Env: map[string]string{"TOKEN": "t"}, + Headers: map[string]string{"X-Trace": "1"}, + }}, + SessionID: "sess-1", + TaskID: "task-1", + DisableAskQuestion: true, + AssumeMcpSse: true, + AssumeMcpHttp: true, + McpMode: "task", + McpProviders: []string{"github"}, + McpProfile: &mcpprofile.Context{}, + RequiresProcessKill: true, + StripEnv: []string{"ANTHROPIC_API_KEY"}, + BaseBranches: map[string]string{"": "origin/main", "web": "origin/develop"}, + RemoteContributions: map[string]models.RemoteContribution{"": {}}, + WorkspaceSourceRoots: []string{"/sources/a"}, + } + + resp, err := newTestControlClient(t, srv).CreateInstance(context.Background(), req) + if err != nil { + t.Fatalf("CreateInstance: %v", err) + } + + if got.Method != http.MethodPost || got.Path != "/api/v1/instances" { + t.Errorf("request = %s %s, want POST /api/v1/instances", got.Method, got.Path) + } + if got.ContentType != "application/json" { + t.Errorf("content-type = %q, want application/json", got.ContentType) + } + + var sent CreateInstanceRequest + if err := json.Unmarshal(got.Body, &sent); err != nil { + t.Fatalf("decode sent body: %v", err) + } + if sent.ID != "inst-1" || sent.WorkspacePath != "/workspace/task-1" { + t.Errorf("sent id/workspace = %q / %q", sent.ID, sent.WorkspacePath) + } + if sent.AgentCommand != "claude-code acp" || sent.Protocol != "acp" || sent.AgentType != "codex" { + t.Errorf("sent command/protocol/type = %q / %q / %q", sent.AgentCommand, sent.Protocol, sent.AgentType) + } + if sent.WorkspaceFlag != "--workspace-root" || sent.Env["FOO"] != "bar" || !sent.AutoStart { + t.Errorf("sent flag/env/autostart = %q / %v / %v", sent.WorkspaceFlag, sent.Env, sent.AutoStart) + } + if sent.AutoApprovePermissions == nil || !*sent.AutoApprovePermissions { + t.Errorf("sent AutoApprovePermissions = %v, want pointer to true", sent.AutoApprovePermissions) + } + if len(sent.McpServers) != 1 { + t.Fatalf("sent McpServers = %d, want 1", len(sent.McpServers)) + } + mcp := sent.McpServers[0] + if mcp.Name != "kandev" || mcp.URL != "http://127.0.0.1:9/mcp" || mcp.Type != "http" { + t.Errorf("sent mcp identity = %+v", mcp) + } + if mcp.Command != "kandev-mcp" || len(mcp.Args) != 1 || mcp.Args[0] != "--stdio" { + t.Errorf("sent mcp command/args = %q / %v", mcp.Command, mcp.Args) + } + if mcp.Env["TOKEN"] != "t" || mcp.Headers["X-Trace"] != "1" { + t.Errorf("sent mcp env/headers = %v / %v", mcp.Env, mcp.Headers) + } + if sent.SessionID != "sess-1" || sent.TaskID != "task-1" { + t.Errorf("sent session/task = %q / %q", sent.SessionID, sent.TaskID) + } + if !sent.DisableAskQuestion || !sent.AssumeMcpSse || !sent.AssumeMcpHttp { + t.Errorf("sent mcp capability flags = %v / %v / %v", + sent.DisableAskQuestion, sent.AssumeMcpSse, sent.AssumeMcpHttp) + } + if sent.McpMode != "task" || len(sent.McpProviders) != 1 || sent.McpProviders[0] != "github" { + t.Errorf("sent mcp mode/providers = %q / %v", sent.McpMode, sent.McpProviders) + } + if sent.McpProfile == nil { + t.Error("sent McpProfile = nil, want the backend-owned profile forwarded") + } + if !sent.RequiresProcessKill { + t.Error("sent RequiresProcessKill = false, want true") + } + if len(sent.StripEnv) != 1 || sent.StripEnv[0] != "ANTHROPIC_API_KEY" { + t.Errorf("sent StripEnv = %v", sent.StripEnv) + } + if sent.BaseBranches[""] != "origin/main" || sent.BaseBranches["web"] != "origin/develop" { + t.Errorf("sent BaseBranches = %v", sent.BaseBranches) + } + if _, ok := sent.RemoteContributions[""]; !ok { + t.Errorf("sent RemoteContributions = %v, want the root binding", sent.RemoteContributions) + } + if len(sent.WorkspaceSourceRoots) != 1 || sent.WorkspaceSourceRoots[0] != "/sources/a" { + t.Errorf("sent WorkspaceSourceRoots = %v", sent.WorkspaceSourceRoots) + } + + if resp.ID != "inst-1" || resp.Port != 41234 { + t.Errorf("response = %+v, want inst-1 on port 41234", resp) + } +} + +// 200 is accepted alongside 201 — agentctl returns 200 when it reuses an +// existing instance for the same ID. +func TestCreateInstance_AcceptsBoth200And201(t *testing.T) { + for _, status := range []int{http.StatusOK, http.StatusCreated} { + t.Run(http.StatusText(status), func(t *testing.T) { + srv := httptest.NewServer(jsonResponder(status, `{"id":"i","port":1}`)) + t.Cleanup(srv.Close) + + resp, err := newTestControlClient(t, srv).CreateInstance( + context.Background(), &CreateInstanceRequest{WorkspacePath: "/w"}) + if err != nil { + t.Fatalf("CreateInstance on %d: %v", status, err) + } + if resp.ID != "i" || resp.Port != 1 { + t.Errorf("response = %+v", resp) + } + }) + } +} + +func TestCreateInstance_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + { + name: "structured error", + status: http.StatusConflict, + body: `{"error":"port range exhausted"}`, + wantErr: "failed to create instance: port range exhausted (status 409)", + }, + { + name: "unparseable error body", + status: http.StatusBadGateway, + body: `502`, + wantErr: "failed to decode error response", + }, + { + name: "malformed success body", + status: http.StatusCreated, + body: `{"id":`, + wantErr: "failed to decode response", + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv := httptest.NewServer(jsonResponder(tc.status, tc.body)) + t.Cleanup(srv.Close) + + resp, err := newTestControlClient(t, srv).CreateInstance( + context.Background(), &CreateInstanceRequest{WorkspacePath: "/w"}) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + if resp != nil { + t.Errorf("response = %+v, want nil on failure", resp) + } + }) + } +} + +func TestDeleteInstance_UsesDeleteVerbWithIDInPath(t *testing.T) { + for _, status := range []int{http.StatusOK, http.StatusNoContent} { + t.Run(http.StatusText(status), func(t *testing.T) { + srv, got := captureServer(t, jsonResponder(status, ``)) + + if err := newTestControlClient(t, srv).DeleteInstance( + context.Background(), "inst-9"); err != nil { + t.Fatalf("DeleteInstance: %v", err) + } + if got.Method != http.MethodDelete { + t.Errorf("method = %q, want DELETE", got.Method) + } + if got.Path != "/api/v1/instances/inst-9" { + t.Errorf("path = %q, want the ID as the last segment", got.Path) + } + }) + } +} + +func TestDeleteInstance_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + { + name: "structured error", + status: http.StatusNotFound, + body: `{"error":"no such instance"}`, + wantErr: "failed to delete instance: no such instance (status 404)", + }, + { + name: "unparseable error body", + status: http.StatusInternalServerError, + body: `boom`, + wantErr: "failed to decode error response", + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv := httptest.NewServer(jsonResponder(tc.status, tc.body)) + t.Cleanup(srv.Close) + + err := newTestControlClient(t, srv).DeleteInstance(context.Background(), "inst-9") + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + }) + } +} + +func TestGetInstance_DecodesEveryField(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{ + "id":"inst-3","port":40001,"status":"running", + "workspace_path":"/workspace/task-3","agent_command":"claude-code acp", + "env":{"FOO":"bar"},"created_at":"2026-08-10T12:34:56Z" + }`)) + + info, err := newTestControlClient(t, srv).GetInstance(context.Background(), "inst-3") + if err != nil { + t.Fatalf("GetInstance: %v", err) + } + + if got.Method != http.MethodGet || got.Path != "/api/v1/instances/inst-3" { + t.Errorf("request = %s %s, want GET /api/v1/instances/inst-3", got.Method, got.Path) + } + + if info.ID != "inst-3" || info.Port != 40001 || info.Status != "running" { + t.Errorf("id/port/status = %q / %d / %q", info.ID, info.Port, info.Status) + } + if info.WorkspacePath != "/workspace/task-3" || info.AgentCommand != "claude-code acp" { + t.Errorf("workspace/command = %q / %q", info.WorkspacePath, info.AgentCommand) + } + if info.Env["FOO"] != "bar" { + t.Errorf("Env = %v, want FOO=bar", info.Env) + } + wantCreated := time.Date(2026, 8, 10, 12, 34, 56, 0, time.UTC) + if !info.CreatedAt.Equal(wantCreated) { + t.Errorf("CreatedAt = %v, want %v", info.CreatedAt, wantCreated) + } +} + +func TestGetInstance_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"not found", http.StatusNotFound, `{}`, `instance "inst-3" not found`}, + {"other status", http.StatusInternalServerError, `{}`, "failed to get instance: status 500"}, + {"malformed body", http.StatusOK, `{"id":`, "failed to decode response"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv := httptest.NewServer(jsonResponder(tc.status, tc.body)) + t.Cleanup(srv.Close) + + info, err := newTestControlClient(t, srv).GetInstance(context.Background(), "inst-3") + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + if info != nil { + t.Errorf("info = %+v, want nil on failure", info) + } + }) + } +} + +func TestListInstances_UnwrapsInstancesEnvelope(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{ + "instances":[ + {"id":"a","port":1,"status":"running","workspace_path":"/w/a","agent_command":"cmd-a"}, + {"id":"b","port":2,"status":"stopped","workspace_path":"/w/b","agent_command":"cmd-b"} + ] + }`)) + + instances, err := newTestControlClient(t, srv).ListInstances(context.Background()) + if err != nil { + t.Fatalf("ListInstances: %v", err) + } + + if got.Method != http.MethodGet || got.Path != "/api/v1/instances" { + t.Errorf("request = %s %s, want GET /api/v1/instances", got.Method, got.Path) + } + if len(instances) != 2 { + t.Fatalf("instances = %d, want 2", len(instances)) + } + if instances[0].ID != "a" || instances[0].Port != 1 || + instances[0].Status != "running" || instances[0].WorkspacePath != "/w/a" || + instances[0].AgentCommand != "cmd-a" { + t.Errorf("instances[0] = %+v", instances[0]) + } + if instances[1].ID != "b" || instances[1].Port != 2 || instances[1].Status != "stopped" { + t.Errorf("instances[1] = %+v", instances[1]) + } +} + +func TestListInstances_FailureModes(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-OK status", http.StatusBadGateway, `{}`, "failed to list instances: status 502"}, + {"malformed body", http.StatusOK, `{"instances":`, "failed to decode response"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv := httptest.NewServer(jsonResponder(tc.status, tc.body)) + t.Cleanup(srv.Close) + + instances, err := newTestControlClient(t, srv).ListInstances(context.Background()) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + if instances != nil { + t.Errorf("instances = %+v, want nil on failure", instances) + } + }) + } +} diff --git a/apps/backend/internal/agent/runtime/agentctl/git_test.go b/apps/backend/internal/agent/runtime/agentctl/git_test.go new file mode 100644 index 0000000000..55c543358e --- /dev/null +++ b/apps/backend/internal/agent/runtime/agentctl/git_test.go @@ -0,0 +1,815 @@ +package client + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "testing" +) + +// gitOperationOK is the canonical success body every /api/v1/git/* POST returns. +const gitOperationOK = `{"success":true,"operation":"pull","output":"Already up to date."}` + +// TestGitOperations_PostExpectedPathAndPayload pins the endpoint and JSON body +// of every thin wrapper over gitOperation. A wrapper that posts to the wrong +// path or drops a field is the whole failure mode for this layer. +func TestGitOperations_PostExpectedPathAndPayload(t *testing.T) { + tests := []struct { + name string + call func(c *Client) (*GitOperationResult, error) + wantPath string + wantBody map[string]any + }{ + { + name: "pull with rebase", + call: func(c *Client) (*GitOperationResult, error) { return c.GitPull(context.Background(), true, "svc") }, + wantPath: "/api/v1/git/pull", + wantBody: map[string]any{"rebase": true, "repo": "svc"}, + }, + { + name: "pull without rebase omits empty repo", + call: func(c *Client) (*GitOperationResult, error) { return c.GitPull(context.Background(), false, "") }, + wantPath: "/api/v1/git/pull", + wantBody: map[string]any{"rebase": false}, + }, + { + name: "push force with upstream", + call: func(c *Client) (*GitOperationResult, error) { + return c.GitPush(context.Background(), true, true, "svc") + }, + wantPath: "/api/v1/git/push", + wantBody: map[string]any{"force": true, "set_upstream": true, "repo": "svc"}, + }, + { + name: "push plain", + call: func(c *Client) (*GitOperationResult, error) { + return c.GitPush(context.Background(), false, false, "") + }, + wantPath: "/api/v1/git/push", + wantBody: map[string]any{"force": false, "set_upstream": false}, + }, + { + name: "push preflight", + call: func(c *Client) (*GitOperationResult, error) { return c.GitPushPreflight(context.Background(), "svc") }, + wantPath: "/api/v1/git/push-preflight", + wantBody: map[string]any{"repo": "svc"}, + }, + { + name: "rebase onto base branch", + call: func(c *Client) (*GitOperationResult, error) { + return c.GitRebase(context.Background(), "main", "svc") + }, + wantPath: "/api/v1/git/rebase", + wantBody: map[string]any{"base_branch": "main", "repo": "svc"}, + }, + { + name: "merge base branch", + call: func(c *Client) (*GitOperationResult, error) { + return c.GitMerge(context.Background(), "develop", "") + }, + wantPath: "/api/v1/git/merge", + wantBody: map[string]any{"base_branch": "develop"}, + }, + { + name: "abort rebase", + call: func(c *Client) (*GitOperationResult, error) { + return c.GitAbort(context.Background(), "rebase", "svc") + }, + wantPath: "/api/v1/git/abort", + wantBody: map[string]any{"operation": "rebase", "repo": "svc"}, + }, + { + name: "commit with stage-all and amend", + call: func(c *Client) (*GitOperationResult, error) { + return c.GitCommit(context.Background(), "fix: thing", true, true, "svc") + }, + wantPath: "/api/v1/git/commit", + wantBody: map[string]any{"message": "fix: thing", "stage_all": true, "amend": true, "repo": "svc"}, + }, + { + name: "commit plain", + call: func(c *Client) (*GitOperationResult, error) { + return c.GitCommit(context.Background(), "msg", false, false, "") + }, + wantPath: "/api/v1/git/commit", + wantBody: map[string]any{"message": "msg", "stage_all": false, "amend": false}, + }, + { + name: "rename branch", + call: func(c *Client) (*GitOperationResult, error) { + return c.GitRenameBranch(context.Background(), "feature/new", "svc") + }, + wantPath: "/api/v1/git/rename-branch", + wantBody: map[string]any{"new_name": "feature/new", "repo": "svc"}, + }, + { + name: "stage explicit paths", + call: func(c *Client) (*GitOperationResult, error) { + return c.GitStage(context.Background(), []string{"a.go", "b.go"}, "svc") + }, + wantPath: "/api/v1/git/stage", + wantBody: map[string]any{"paths": []any{"a.go", "b.go"}, "repo": "svc"}, + }, + { + name: "stage all sends null paths", + call: func(c *Client) (*GitOperationResult, error) { + return c.GitStage(context.Background(), nil, "") + }, + wantPath: "/api/v1/git/stage", + wantBody: map[string]any{"paths": nil}, + }, + { + name: "unstage explicit paths", + call: func(c *Client) (*GitOperationResult, error) { + return c.GitUnstage(context.Background(), []string{"a.go"}, "") + }, + wantPath: "/api/v1/git/unstage", + wantBody: map[string]any{"paths": []any{"a.go"}}, + }, + { + name: "discard paths", + call: func(c *Client) (*GitOperationResult, error) { + return c.GitDiscard(context.Background(), []string{"a.go"}, "svc") + }, + wantPath: "/api/v1/git/discard", + wantBody: map[string]any{"paths": []any{"a.go"}, "repo": "svc"}, + }, + { + name: "revert commit", + call: func(c *Client) (*GitOperationResult, error) { + return c.GitRevertCommit(context.Background(), "abc123", "svc") + }, + wantPath: "/api/v1/git/revert-commit", + wantBody: map[string]any{"commit_sha": "abc123", "repo": "svc"}, + }, + { + name: "reset hard", + call: func(c *Client) (*GitOperationResult, error) { + return c.GitReset(context.Background(), "abc123", "hard", "svc") + }, + wantPath: "/api/v1/git/reset", + wantBody: map[string]any{"commit_sha": "abc123", "mode": "hard", "repo": "svc"}, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, gitOperationOK)) + + result, err := tc.call(newHTTPOnlyClient(srv.URL)) + if err != nil { + t.Fatalf("call: %v", err) + } + + if got.Method != http.MethodPost { + t.Errorf("method = %q, want POST", got.Method) + } + if got.Path != tc.wantPath { + t.Errorf("path = %q, want %q", got.Path, tc.wantPath) + } + if got.ContentType != "application/json" { + t.Errorf("content-type = %q, want application/json", got.ContentType) + } + + var sent map[string]any + if err := json.Unmarshal(got.Body, &sent); err != nil { + t.Fatalf("decode sent body %q: %v", got.Body, err) + } + if len(sent) != len(tc.wantBody) { + t.Errorf("sent body has %d fields (%s), want %d (%v)", + len(sent), got.Body, len(tc.wantBody), tc.wantBody) + } + for key, want := range tc.wantBody { + gotVal, present := sent[key] + if !present { + t.Errorf("sent body missing %q: %s", key, got.Body) + continue + } + if !jsonEqual(gotVal, want) { + t.Errorf("sent %q = %#v, want %#v", key, gotVal, want) + } + } + + if !result.Success || result.Operation != "pull" || result.Output != "Already up to date." { + t.Errorf("result = %+v, want the decoded success body", result) + } + }) + } +} + +// jsonEqual compares two values decoded from (or destined for) JSON. +func jsonEqual(a, b any) bool { + ab, err := json.Marshal(a) + if err != nil { + return false + } + bb, err := json.Marshal(b) + if err != nil { + return false + } + return string(ab) == string(bb) +} + +func TestGitOperation_DecodesConflictFilesOnHTTP409(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusConflict, `{ + "success":false,"operation":"merge","output":"CONFLICT", + "error":"merge conflict","conflict_files":["a.go","dir/b.go"] + }`)) + + // 409 is the documented "operation in progress / conflicted" case: the + // client must return the decoded result WITHOUT an error so callers can + // read conflict_files. + result, err := newHTTPOnlyClient(srv.URL).GitMerge(context.Background(), "main", "") + if err != nil { + t.Fatalf("GitMerge on 409 returned error %v, want the result with no error", err) + } + if result.Success { + t.Error("Success = true, want false") + } + if result.Operation != "merge" { + t.Errorf("Operation = %q, want merge", result.Operation) + } + if result.Error != "merge conflict" { + t.Errorf("Error = %q, want merge conflict", result.Error) + } + if len(result.ConflictFiles) != 2 || + result.ConflictFiles[0] != "a.go" || result.ConflictFiles[1] != "dir/b.go" { + t.Errorf("ConflictFiles = %v, want both conflicted paths", result.ConflictFiles) + } +} + +func TestGitOperation_ReturnsResultAndErrorOnOtherHTTPErrors(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusInternalServerError, + `{"success":false,"operation":"pull","error":"remote unreachable"}`)) + + result, err := newHTTPOnlyClient(srv.URL).GitPull(context.Background(), false, "") + if err == nil { + t.Fatal("GitPull returned nil error for 500") + } + if !strings.Contains(err.Error(), "git operation failed with status 500") { + t.Errorf("error = %v, want status 500 named", err) + } + if !strings.Contains(err.Error(), "remote unreachable") { + t.Errorf("error = %v, want the server error message included", err) + } + if result == nil || result.Error != "remote unreachable" { + t.Errorf("result = %+v, want the decoded body alongside the error", result) + } +} + +func TestGitOperation_RejectsMalformedBody(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `{"success":`)) + + _, err := newHTTPOnlyClient(srv.URL).GitPull(context.Background(), false, "") + if err == nil || !strings.Contains(err.Error(), "failed to parse response") { + t.Fatalf("error = %v, want parse failure", err) + } +} + +func TestGitOperation_HonoursContextCancellation(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, gitOperationOK)) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + _, err := newHTTPOnlyClient(srv.URL).GitPush(ctx, false, false, "") + if err == nil || !strings.Contains(err.Error(), "context canceled") { + t.Fatalf("error = %v, want context canceled", err) + } +} + +func TestGitCreatePR_PostsFullPayloadAndDecodesResult(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{ + "success":true,"branch_pushed":true, + "pr_url":"https://github.com/kdlbs/kandev/pull/1", + "provider":"github","output":"created" + }`)) + + result, err := newHTTPOnlyClient(srv.URL).GitCreatePR( + context.Background(), "feat: thing", "body text", "main", true, "svc") + if err != nil { + t.Fatalf("GitCreatePR: %v", err) + } + + if got.Method != http.MethodPost || got.Path != "/api/v1/git/create-pr" { + t.Errorf("request = %s %s, want POST /api/v1/git/create-pr", got.Method, got.Path) + } + if got.ContentType != "application/json" { + t.Errorf("content-type = %q, want application/json", got.ContentType) + } + + var sent struct { + Title string `json:"title"` + Body string `json:"body"` + BaseBranch string `json:"base_branch"` + Draft bool `json:"draft"` + Repo string `json:"repo"` + } + if err := json.Unmarshal(got.Body, &sent); err != nil { + t.Fatalf("decode sent body: %v", err) + } + if sent.Title != "feat: thing" || sent.Body != "body text" { + t.Errorf("sent title/body = %q / %q", sent.Title, sent.Body) + } + if sent.BaseBranch != "main" || !sent.Draft || sent.Repo != "svc" { + t.Errorf("sent = %+v, want main/draft/svc", sent) + } + + if !result.Success || !result.BranchPushed { + t.Errorf("result = %+v, want success with branch pushed", result) + } + if result.PRURL != "https://github.com/kdlbs/kandev/pull/1" { + t.Errorf("PRURL = %q", result.PRURL) + } + if result.Provider != "github" || result.Output != "created" { + t.Errorf("provider/output = %q / %q, want github / created", result.Provider, result.Output) + } +} + +func TestGitCreatePR_TreatsConflictAsNonError(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusConflict, + `{"success":false,"error":"a PR operation is already running"}`)) + + result, err := newHTTPOnlyClient(srv.URL).GitCreatePR( + context.Background(), "t", "b", "main", false, "") + if err != nil { + t.Fatalf("GitCreatePR on 409 returned error %v, want the result with no error", err) + } + if result.Success || result.Error != "a PR operation is already running" { + t.Errorf("result = %+v, want the decoded in-progress body", result) + } +} + +func TestGitCreatePR_ReturnsErrorOnOtherHTTPErrors(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusForbidden, + `{"success":false,"error":"gh not authenticated"}`)) + + result, err := newHTTPOnlyClient(srv.URL).GitCreatePR( + context.Background(), "t", "b", "main", false, "") + if err == nil || !strings.Contains(err.Error(), "create PR failed with status 403") { + t.Fatalf("error = %v, want status 403 named", err) + } + if result == nil || result.Error != "gh not authenticated" { + t.Errorf("result = %+v, want the decoded body alongside the error", result) + } +} + +func TestGitShowCommit_PutsSHAInPathAndDecodesStats(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{ + "success":true,"commit_sha":"abc123","message":"fix: thing", + "author":"Dev ","date":"2026-08-10T10:00:00Z", + "files":{"a.go":{"additions":3}}, + "files_changed":1,"insertions":3,"deletions":1 + }`)) + + result, err := newHTTPOnlyClient(srv.URL).GitShowCommit(context.Background(), "abc123", "my svc") + if err != nil { + t.Fatalf("GitShowCommit: %v", err) + } + + if got.Method != http.MethodGet { + t.Errorf("method = %q, want GET", got.Method) + } + if got.Path != "/api/v1/git/commit/abc123" { + t.Errorf("path = %q, want the SHA as the last path segment", got.Path) + } + if repo := got.Query.Get("repo"); repo != "my svc" { + t.Errorf("repo = %q, want %q", repo, "my svc") + } + + if !result.Success || result.CommitSHA != "abc123" { + t.Errorf("result = %+v, want abc123", result) + } + if result.Message != "fix: thing" || result.Author != "Dev " { + t.Errorf("message/author = %q / %q", result.Message, result.Author) + } + if result.Date != "2026-08-10T10:00:00Z" { + t.Errorf("Date = %q", result.Date) + } + if result.FilesChanged != 1 || result.Insertions != 3 || result.Deletions != 1 { + t.Errorf("stats = %d/%d/%d, want 1/3/1", + result.FilesChanged, result.Insertions, result.Deletions) + } + if _, ok := result.Files["a.go"]; !ok { + t.Errorf("Files = %v, want an a.go entry", result.Files) + } +} + +func TestGitShowCommit_OmitsRepoQueryWhenEmpty(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{"success":true,"commit_sha":"a"}`)) + + if _, err := newHTTPOnlyClient(srv.URL).GitShowCommit(context.Background(), "a", ""); err != nil { + t.Fatalf("GitShowCommit: %v", err) + } + if got.RawQuery != "" { + t.Errorf("raw query = %q, want empty for single-repo call", got.RawQuery) + } +} + +func TestGitShowCommit_ReturnsErrorOnHTTPError(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusNotFound, + `{"success":false,"error":"unknown revision"}`)) + + result, err := newHTTPOnlyClient(srv.URL).GitShowCommit(context.Background(), "nope", "") + if err == nil || !strings.Contains(err.Error(), "git show commit failed with status 404") { + t.Fatalf("error = %v, want status 404 named", err) + } + if result == nil || result.Error != "unknown revision" { + t.Errorf("result = %+v, want the decoded body alongside the error", result) + } +} + +func TestGitLog_BuildsFullQueryAndDecodesCommits(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{ + "success":true, + "commits":[{ + "commit_sha":"aaa","parent_sha":"bbb","commit_message":"feat: x", + "author_name":"Dev","author_email":"dev@example.com", + "committed_at":"2026-08-10T09:00:00Z", + "files_changed":2,"insertions":10,"deletions":4, + "pushed":true,"repository_name":"backend" + }] + }`)) + + result, err := newHTTPOnlyClient(srv.URL).GitLog( + context.Background(), "base sha", 50, "feature/x", "my svc") + if err != nil { + t.Fatalf("GitLog: %v", err) + } + + if got.Method != http.MethodGet || got.Path != "/api/v1/git/log" { + t.Errorf("request = %s %s, want GET /api/v1/git/log", got.Method, got.Path) + } + if since := got.Query.Get("since"); since != "base sha" { + t.Errorf("since = %q, want %q", since, "base sha") + } + if limit := got.Query.Get("limit"); limit != "50" { + t.Errorf("limit = %q, want 50", limit) + } + if tb := got.Query.Get("target_branch"); tb != "feature/x" { + t.Errorf("target_branch = %q, want feature/x", tb) + } + if repo := got.Query.Get("repo"); repo != "my svc" { + t.Errorf("repo = %q, want %q", repo, "my svc") + } + + if !result.Success { + t.Error("Success = false, want true") + } + if len(result.Commits) != 1 { + t.Fatalf("Commits = %d, want 1", len(result.Commits)) + } + commit := result.Commits[0] + if commit.CommitSHA != "aaa" || commit.ParentSHA != "bbb" { + t.Errorf("sha/parent = %q / %q, want aaa / bbb", commit.CommitSHA, commit.ParentSHA) + } + if commit.CommitMessage != "feat: x" { + t.Errorf("CommitMessage = %q", commit.CommitMessage) + } + if commit.AuthorName != "Dev" || commit.AuthorEmail != "dev@example.com" { + t.Errorf("author = %q <%q>", commit.AuthorName, commit.AuthorEmail) + } + if commit.CommittedAt != "2026-08-10T09:00:00Z" { + t.Errorf("CommittedAt = %q", commit.CommittedAt) + } + if commit.FilesChanged != 2 || commit.Insertions != 10 || commit.Deletions != 4 { + t.Errorf("stats = %d/%d/%d, want 2/10/4", + commit.FilesChanged, commit.Insertions, commit.Deletions) + } + if !commit.Pushed { + t.Error("Pushed = false, want true") + } + if commit.RepositoryName != "backend" { + t.Errorf("RepositoryName = %q, want backend", commit.RepositoryName) + } +} + +func TestGitLog_OmitsOptionalQueryParams(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{"success":true,"commits":[]}`)) + + if _, err := newHTTPOnlyClient(srv.URL).GitLog(context.Background(), "", 10, "", ""); err != nil { + t.Fatalf("GitLog: %v", err) + } + for _, key := range []string{"target_branch", "repo"} { + if _, present := got.Query[key]; present { + t.Errorf("%s query present when empty: %q", key, got.RawQuery) + } + } + // since is always sent, even empty — the server distinguishes "" from absent. + if _, present := got.Query["since"]; !present { + t.Errorf("since query absent: %q", got.RawQuery) + } +} + +func TestGitLog_DecodesPerRepoErrorsFromPartialFanOut(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `{ + "success":true,"commits":[], + "per_repo_errors":[ + {"repository_name":"docs","error":"not a git repository"}, + {"repository_name":"web","error":"detached HEAD"} + ] + }`)) + + result, err := newHTTPOnlyClient(srv.URL).GitLog(context.Background(), "", 10, "", "") + if err != nil { + t.Fatalf("GitLog: %v", err) + } + if len(result.PerRepoErrors) != 2 { + t.Fatalf("PerRepoErrors = %d, want 2", len(result.PerRepoErrors)) + } + if result.PerRepoErrors[0].RepositoryName != "docs" || + result.PerRepoErrors[0].Error != "not a git repository" { + t.Errorf("PerRepoErrors[0] = %+v", result.PerRepoErrors[0]) + } + if result.PerRepoErrors[1].RepositoryName != "web" || + result.PerRepoErrors[1].Error != "detached HEAD" { + t.Errorf("PerRepoErrors[1] = %+v", result.PerRepoErrors[1]) + } +} + +func TestGitLog_ReturnsErrorOnHTTPError(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusBadRequest, + `{"success":false,"error":"invalid limit"}`)) + + result, err := newHTTPOnlyClient(srv.URL).GitLog(context.Background(), "", -1, "", "") + if err == nil || !strings.Contains(err.Error(), "git log failed with status 400") { + t.Fatalf("error = %v, want status 400 named", err) + } + if result == nil || result.Error != "invalid limit" { + t.Errorf("result = %+v, want the decoded body alongside the error", result) + } +} + +func TestGetCumulativeDiff_BuildsQueryAndDecodesTruncation(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{ + "success":true,"base_commit":"base1","head_commit":"head1", + "total_commits":7,"files":{"a.go":{"additions":1}}, + "truncated_files_count":12 + }`)) + + result, err := newHTTPOnlyClient(srv.URL).GetCumulativeDiff( + context.Background(), "base sha", "feature/x") + if err != nil { + t.Fatalf("GetCumulativeDiff: %v", err) + } + + if got.Method != http.MethodGet || got.Path != "/api/v1/git/cumulative-diff" { + t.Errorf("request = %s %s, want GET /api/v1/git/cumulative-diff", got.Method, got.Path) + } + if base := got.Query.Get("base"); base != "base sha" { + t.Errorf("base = %q, want %q", base, "base sha") + } + if tb := got.Query.Get("target_branch"); tb != "feature/x" { + t.Errorf("target_branch = %q, want feature/x", tb) + } + + if !result.Success { + t.Error("Success = false, want true") + } + if result.BaseCommit != "base1" || result.HeadCommit != "head1" { + t.Errorf("base/head = %q / %q, want base1 / head1", result.BaseCommit, result.HeadCommit) + } + if result.TotalCommits != 7 { + t.Errorf("TotalCommits = %d, want 7", result.TotalCommits) + } + if result.TruncatedFilesCount != 12 { + t.Errorf("TruncatedFilesCount = %d, want 12 — the UI's hidden-files banner reads this", + result.TruncatedFilesCount) + } + if _, ok := result.Files["a.go"]; !ok { + t.Errorf("Files = %v, want an a.go entry", result.Files) + } +} + +func TestGetCumulativeDiff_OmitsTargetBranchWhenEmpty(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{"success":true}`)) + + if _, err := newHTTPOnlyClient(srv.URL).GetCumulativeDiff(context.Background(), "b", ""); err != nil { + t.Fatalf("GetCumulativeDiff: %v", err) + } + if _, present := got.Query["target_branch"]; present { + t.Errorf("target_branch present when empty: %q", got.RawQuery) + } +} + +func TestGetCumulativeDiff_ReturnsErrorOnHTTPError(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusInternalServerError, + `{"success":false,"error":"diff too large"}`)) + + result, err := newHTTPOnlyClient(srv.URL).GetCumulativeDiff(context.Background(), "b", "") + if err == nil || !strings.Contains(err.Error(), "cumulative diff failed with status 500") { + t.Fatalf("error = %v, want status 500 named", err) + } + if result == nil || result.Error != "diff too large" { + t.Errorf("result = %+v, want the decoded body alongside the error", result) + } +} + +// gitStatusBody exercises every field of GitStatusResult. +const gitStatusBody = `{ + "success":true,"is_submodule":true, + "branch":"feature/x","remote_branch":"origin/feature/x", + "head_commit":"head1","base_commit":"base1", + "ahead":3,"behind":1, + "modified":["m.go"],"added":["a.go"],"deleted":["d.go"], + "untracked":["u.go"],"renamed":["r.go"], + "files":{"m.go":{"status":"M"}}, + "timestamp":"2026-08-10T11:00:00Z", + "branch_additions":25,"branch_deletions":7 +}` + +func assertFullGitStatus(t *testing.T, result *GitStatusResult) { + t.Helper() + if !result.Success || !result.IsSubmodule { + t.Errorf("success/is_submodule = %v / %v, want true / true", result.Success, result.IsSubmodule) + } + if result.Branch != "feature/x" || result.RemoteBranch != "origin/feature/x" { + t.Errorf("branch/remote = %q / %q", result.Branch, result.RemoteBranch) + } + if result.HeadCommit != "head1" || result.BaseCommit != "base1" { + t.Errorf("head/base = %q / %q", result.HeadCommit, result.BaseCommit) + } + if result.Ahead != 3 || result.Behind != 1 { + t.Errorf("ahead/behind = %d / %d, want 3 / 1", result.Ahead, result.Behind) + } + for name, got := range map[string][]string{ + "modified": result.Modified, + "added": result.Added, + "deleted": result.Deleted, + "untracked": result.Untracked, + "renamed": result.Renamed, + } { + if len(got) != 1 { + t.Errorf("%s = %v, want exactly one path", name, got) + } + } + if result.Modified[0] != "m.go" || result.Untracked[0] != "u.go" { + t.Errorf("modified/untracked = %v / %v", result.Modified, result.Untracked) + } + if _, ok := result.Files["m.go"]; !ok { + t.Errorf("Files = %v, want an m.go entry", result.Files) + } + if result.Timestamp != "2026-08-10T11:00:00Z" { + t.Errorf("Timestamp = %q", result.Timestamp) + } + if result.BranchAdditions != 25 || result.BranchDeletions != 7 { + t.Errorf("branch additions/deletions = %d / %d, want 25 / 7", + result.BranchAdditions, result.BranchDeletions) + } +} + +func TestGetGitStatus_UsesCachedEndpointAndDecodesEveryField(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, gitStatusBody)) + + result, err := newHTTPOnlyClient(srv.URL).GetGitStatus(context.Background()) + if err != nil { + t.Fatalf("GetGitStatus: %v", err) + } + + if got.Method != http.MethodGet || got.Path != "/api/v1/git/status" { + t.Errorf("request = %s %s, want GET /api/v1/git/status", got.Method, got.Path) + } + if got.RawQuery != "" { + t.Errorf("raw query = %q, want empty — the cached path must not send fresh=true", got.RawQuery) + } + assertFullGitStatus(t, result) +} + +func TestGetGitStatusFresh_SendsFreshQueryParam(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, gitStatusBody)) + + result, err := newHTTPOnlyClient(srv.URL).GetGitStatusFresh(context.Background()) + if err != nil { + t.Fatalf("GetGitStatusFresh: %v", err) + } + + if got.Path != "/api/v1/git/status" { + t.Errorf("path = %q, want /api/v1/git/status", got.Path) + } + if fresh := got.Query.Get("fresh"); fresh != "true" { + t.Errorf("fresh = %q, want true — without it the server serves the poll-loop cache", fresh) + } + assertFullGitStatus(t, result) +} + +func TestGetGitStatusMultiFresh_UsesMultiEndpointAndDecodesPerRepoEntries(t *testing.T) { + srv, got := captureServer(t, jsonResponder(http.StatusOK, `{ + "success":true, + "repos":[ + {"repository_name":"backend","status":{"success":true,"branch":"main","ahead":2}}, + {"repository_name":"web","status":{"success":true,"branch":"feature/y","behind":5}} + ] + }`)) + + result, err := newHTTPOnlyClient(srv.URL).GetGitStatusMultiFresh(context.Background()) + if err != nil { + t.Fatalf("GetGitStatusMultiFresh: %v", err) + } + + if got.Path != "/api/v1/git/status/multi" { + t.Errorf("path = %q, want /api/v1/git/status/multi", got.Path) + } + if fresh := got.Query.Get("fresh"); fresh != "true" { + t.Errorf("fresh = %q, want true", fresh) + } + + if !result.Success { + t.Error("Success = false, want true") + } + if len(result.Repos) != 2 { + t.Fatalf("Repos = %d, want 2", len(result.Repos)) + } + if result.Repos[0].RepositoryName != "backend" || + result.Repos[0].Status.Branch != "main" || result.Repos[0].Status.Ahead != 2 { + t.Errorf("Repos[0] = %+v, want backend on main ahead 2", result.Repos[0]) + } + if result.Repos[1].RepositoryName != "web" || + result.Repos[1].Status.Branch != "feature/y" || result.Repos[1].Status.Behind != 5 { + t.Errorf("Repos[1] = %+v, want web on feature/y behind 5", result.Repos[1]) + } +} + +func TestGitStatusEndpoints_ReturnResultAndErrorOnHTTPError(t *testing.T) { + tests := []struct { + name string + call func(c *Client) (string, error) + wantMsg string + }{ + { + name: "cached status", + call: func(c *Client) (string, error) { + r, err := c.GetGitStatus(context.Background()) + if r == nil { + return "", err + } + return r.Error, err + }, + wantMsg: "git status failed with status 500", + }, + { + name: "fresh status", + call: func(c *Client) (string, error) { + r, err := c.GetGitStatusFresh(context.Background()) + if r == nil { + return "", err + } + return r.Error, err + }, + wantMsg: "git status fresh failed with status 500", + }, + { + name: "multi status", + call: func(c *Client) (string, error) { + r, err := c.GetGitStatusMultiFresh(context.Background()) + if r == nil { + return "", err + } + return r.Error, err + }, + wantMsg: "git status multi failed with status 500", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusInternalServerError, + `{"success":false,"error":"worktree gone"}`)) + + bodyErr, err := tc.call(newHTTPOnlyClient(srv.URL)) + if err == nil || !strings.Contains(err.Error(), tc.wantMsg) { + t.Fatalf("error = %v, want %q", err, tc.wantMsg) + } + if bodyErr != "worktree gone" { + t.Errorf("result.Error = %q, want the decoded body alongside the error", bodyErr) + } + }) + } +} + +// fetchJSONResult is shared by all three status endpoints; a decode failure +// must return nil (not a partially-filled result) so callers can't mistake +// garbage for a real status. +func TestGitStatusEndpoints_ReturnNilResultOnMalformedBody(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, `{"branch":`)) + + result, err := newHTTPOnlyClient(srv.URL).GetGitStatus(context.Background()) + if err == nil || !strings.Contains(err.Error(), "failed to parse response") { + t.Fatalf("error = %v, want parse failure", err) + } + if result != nil { + t.Errorf("result = %+v, want nil on decode failure", result) + } +} + +func TestGitStatus_HonoursContextCancellation(t *testing.T) { + srv, _ := captureServer(t, jsonResponder(http.StatusOK, gitStatusBody)) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + if _, err := newHTTPOnlyClient(srv.URL).GetGitStatus(ctx); err == nil || + !strings.Contains(err.Error(), "context canceled") { + t.Fatalf("error = %v, want context canceled", err) + } +} diff --git a/apps/backend/internal/agent/runtime/agentctl/testhelpers_test.go b/apps/backend/internal/agent/runtime/agentctl/testhelpers_test.go new file mode 100644 index 0000000000..083ddbae62 --- /dev/null +++ b/apps/backend/internal/agent/runtime/agentctl/testhelpers_test.go @@ -0,0 +1,55 @@ +package client + +import ( + "io" + "net/http" + "net/http/httptest" + "net/url" + "testing" +) + +// Shared HTTP test scaffolding for the whole package. Every endpoint in this +// client is request-construction plus response-decoding, so the tests need to +// assert what actually went on the wire — not merely that no error came back. + +// capturedRequest records everything the client put on the wire so each test +// can assert the request rather than just the decoded response. +type capturedRequest struct { + Method string + Path string + RawQuery string + Query url.Values + ContentType string + Body []byte +} + +// captureServer serves `respond` and records the single request it receives. +func captureServer(t *testing.T, respond http.HandlerFunc) (*httptest.Server, *capturedRequest) { + t.Helper() + got := &capturedRequest{} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + if err != nil { + t.Errorf("read request body: %v", err) + return + } + got.Method = r.Method + got.Path = r.URL.Path + got.RawQuery = r.URL.RawQuery + got.Query = r.URL.Query() + got.ContentType = r.Header.Get("Content-Type") + got.Body = body + respond(w, r) + })) + t.Cleanup(srv.Close) + return srv, got +} + +// jsonResponder writes a fixed status and raw JSON body. +func jsonResponder(status int, body string) http.HandlerFunc { + return func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = io.WriteString(w, body) + } +} diff --git a/apps/backend/internal/agent/runtime/agentctl/workspace_dispatch_test.go b/apps/backend/internal/agent/runtime/agentctl/workspace_dispatch_test.go new file mode 100644 index 0000000000..b55954f961 --- /dev/null +++ b/apps/backend/internal/agent/runtime/agentctl/workspace_dispatch_test.go @@ -0,0 +1,237 @@ +package client + +import ( + "strconv" + "testing" + + "github.com/kandev/kandev/internal/agentctl/types" +) + +// recordingCallbacks builds a WorkspaceStreamCallbacks whose every hook appends +// its name (and the payload identity it received) to `calls`. +func recordingCallbacks(calls *[]string) WorkspaceStreamCallbacks { + return WorkspaceStreamCallbacks{ + OnShellOutput: func(data string) { *calls = append(*calls, "shell_output:"+data) }, + OnShellExit: func(code int) { *calls = append(*calls, "shell_exit:"+strconv.Itoa(code)) }, + OnGitStatus: func(*GitStatusUpdate) { *calls = append(*calls, "git_status") }, + OnGitCommit: func(*GitCommitNotification) { *calls = append(*calls, "git_commit") }, + OnGitReset: func(*GitResetNotification) { *calls = append(*calls, "git_reset") }, + OnBranchSwitch: func(*GitBranchSwitchNotification) { *calls = append(*calls, "branch_switch") }, + OnFileChange: func(*FileChangeNotification) { *calls = append(*calls, "file_change") }, + OnProcessOutput: func(*types.ProcessOutput) { *calls = append(*calls, "process_output") }, + OnProcessStatus: func(*types.ProcessStatusUpdate) { *calls = append(*calls, "process_status") }, + OnConnected: func() { *calls = append(*calls, "connected") }, + OnError: func(err string) { *calls = append(*calls, "error:"+err) }, + } +} + +// Every message type must reach exactly its own callback. A misrouted case in +// the dispatch switch silently drops UI updates rather than erroring. +func TestDispatchWorkspaceMessage_RoutesEachTypeToItsOwnCallback(t *testing.T) { + tests := []struct { + name string + msg types.WorkspaceStreamMessage + want string + }{ + { + name: "shell output", + msg: types.WorkspaceStreamMessage{Type: types.WorkspaceMessageTypeShellOutput, Data: "hi"}, + want: "shell_output:hi", + }, + { + name: "shell exit", + msg: types.WorkspaceStreamMessage{Type: types.WorkspaceMessageTypeShellExit, Code: 137}, + want: "shell_exit:137", + }, + { + name: "connected", + msg: types.WorkspaceStreamMessage{Type: types.WorkspaceMessageTypeConnected}, + want: "connected", + }, + { + name: "error", + msg: types.WorkspaceStreamMessage{Type: types.WorkspaceMessageTypeError, Error: "boom"}, + want: "error:boom", + }, + { + name: "git status", + msg: types.WorkspaceStreamMessage{ + Type: types.WorkspaceMessageTypeGitStatus, GitStatus: &GitStatusUpdate{}, + }, + want: "git_status", + }, + { + name: "git commit", + msg: types.WorkspaceStreamMessage{ + Type: types.WorkspaceMessageTypeGitCommit, GitCommit: &GitCommitNotification{}, + }, + want: "git_commit", + }, + { + name: "git reset", + msg: types.WorkspaceStreamMessage{ + Type: types.WorkspaceMessageTypeGitReset, GitReset: &GitResetNotification{}, + }, + want: "git_reset", + }, + { + name: "branch switch", + msg: types.WorkspaceStreamMessage{ + Type: types.WorkspaceMessageTypeBranchSwitch, BranchSwitch: &GitBranchSwitchNotification{}, + }, + want: "branch_switch", + }, + { + name: "file change", + msg: types.WorkspaceStreamMessage{ + Type: types.WorkspaceMessageTypeFileChange, FileChange: &FileChangeNotification{}, + }, + want: "file_change", + }, + { + name: "process output", + msg: types.WorkspaceStreamMessage{ + Type: types.WorkspaceMessageTypeProcessOutput, ProcessOutput: &types.ProcessOutput{}, + }, + want: "process_output", + }, + { + name: "process status", + msg: types.WorkspaceStreamMessage{ + Type: types.WorkspaceMessageTypeProcessStatus, ProcessStatus: &types.ProcessStatusUpdate{}, + }, + want: "process_status", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + var calls []string + dispatchWorkspaceMessage(tc.msg, recordingCallbacks(&calls)) + + if len(calls) != 1 { + t.Fatalf("callbacks fired = %v, want exactly [%s]", calls, tc.want) + } + if calls[0] != tc.want { + t.Errorf("callback fired = %q, want %q", calls[0], tc.want) + } + }) + } +} + +// Typed messages carry a nillable payload; dispatching one with a nil body must +// not invoke the callback (which would panic on the nil deref downstream). +func TestDispatchWorkspaceMessage_SkipsCallbacksWithNilPayloads(t *testing.T) { + nilPayloadTypes := []types.WorkspaceMessageType{ + types.WorkspaceMessageTypeGitStatus, + types.WorkspaceMessageTypeGitCommit, + types.WorkspaceMessageTypeGitReset, + types.WorkspaceMessageTypeBranchSwitch, + types.WorkspaceMessageTypeFileChange, + types.WorkspaceMessageTypeProcessOutput, + types.WorkspaceMessageTypeProcessStatus, + } + for _, msgType := range nilPayloadTypes { + t.Run(string(msgType), func(t *testing.T) { + var calls []string + dispatchWorkspaceMessage( + types.WorkspaceStreamMessage{Type: msgType}, recordingCallbacks(&calls)) + if len(calls) != 0 { + t.Errorf("callbacks fired = %v, want none for a nil payload", calls) + } + }) + } +} + +// A message whose callback is unset (the common case — most callers wire only a +// few hooks) must be a no-op rather than a nil-func panic. +func TestDispatchWorkspaceMessage_ToleratesUnsetCallbacks(t *testing.T) { + allTypes := []types.WorkspaceMessageType{ + types.WorkspaceMessageTypeShellOutput, + types.WorkspaceMessageTypeShellExit, + types.WorkspaceMessageTypeConnected, + types.WorkspaceMessageTypeError, + types.WorkspaceMessageTypeGitStatus, + types.WorkspaceMessageTypeGitCommit, + types.WorkspaceMessageTypeGitReset, + types.WorkspaceMessageTypeBranchSwitch, + types.WorkspaceMessageTypeFileChange, + types.WorkspaceMessageTypeProcessOutput, + types.WorkspaceMessageTypeProcessStatus, + } + for _, msgType := range allTypes { + t.Run(string(msgType), func(t *testing.T) { + // Payloads are populated so the nil-payload guard doesn't mask a + // nil-callback panic. + msg := types.WorkspaceStreamMessage{ + Type: msgType, + GitStatus: &GitStatusUpdate{}, + GitCommit: &GitCommitNotification{}, + GitReset: &GitResetNotification{}, + BranchSwitch: &GitBranchSwitchNotification{}, + FileChange: &FileChangeNotification{}, + ProcessOutput: &types.ProcessOutput{}, + ProcessStatus: &types.ProcessStatusUpdate{}, + } + dispatchWorkspaceMessage(msg, WorkspaceStreamCallbacks{}) + }) + } +} + +// Ping/pong and shell_input are handled elsewhere in the stream loop; the +// dispatcher must fall through them without firing an unrelated callback. +func TestDispatchWorkspaceMessage_IgnoresUnroutedTypes(t *testing.T) { + for _, msgType := range []types.WorkspaceMessageType{ + types.WorkspaceMessageTypePing, + types.WorkspaceMessageTypePong, + types.WorkspaceMessageTypeShellInput, + types.WorkspaceMessageTypeShellResize, + "totally_unknown", + } { + t.Run(string(msgType), func(t *testing.T) { + var calls []string + dispatchWorkspaceMessage( + types.WorkspaceStreamMessage{Type: msgType, Data: "x", Error: "y"}, + recordingCallbacks(&calls)) + if len(calls) != 0 { + t.Errorf("callbacks fired = %v, want none for an unrouted type", calls) + } + }) + } +} + +// The dispatcher is layered shell → git → process, with the first two +// short-circuiting on a match. These assertions pin the handled/unhandled +// contract each layer reports. +func TestDispatchWorkspaceLayers_ReportWhetherTheyHandledTheMessage(t *testing.T) { + var calls []string + callbacks := recordingCallbacks(&calls) + + shellMsg := types.WorkspaceStreamMessage{Type: types.WorkspaceMessageTypeShellOutput, Data: "x"} + if !dispatchWorkspaceShellMessages(shellMsg, callbacks) { + t.Error("shell layer reported unhandled for a shell_output message") + } + if dispatchWorkspaceGitMessages(shellMsg, callbacks) { + t.Error("git layer claimed a shell_output message") + } + + gitMsg := types.WorkspaceStreamMessage{ + Type: types.WorkspaceMessageTypeGitStatus, GitStatus: &GitStatusUpdate{}, + } + if dispatchWorkspaceShellMessages(gitMsg, callbacks) { + t.Error("shell layer claimed a git_status message") + } + if !dispatchWorkspaceGitMessages(gitMsg, callbacks) { + t.Error("git layer reported unhandled for a git_status message") + } + + processMsg := types.WorkspaceStreamMessage{ + Type: types.WorkspaceMessageTypeProcessOutput, ProcessOutput: &types.ProcessOutput{}, + } + if dispatchWorkspaceShellMessages(processMsg, callbacks) { + t.Error("shell layer claimed a process_output message") + } + if dispatchWorkspaceGitMessages(processMsg, callbacks) { + t.Error("git layer claimed a process_output message") + } +}