From e9d3cb02cb1013a41e0ddec88940eb74a5960316 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Salavisa?= Date: Mon, 10 Aug 2026 20:44:44 +0200 Subject: [PATCH] test(agentctl): cover the agentctl HTTP API handlers (#2499) Co-authored-by: Kandev Agent Co-authored-by: Claude Opus 5 (1M context) --- .../server/api/agent_adapter_actions_test.go | 350 +++++++ .../agentctl/server/api/git_handlers_test.go | 973 ++++++++++++++++++ .../api/git_status_fresh_concurrency_test.go | 48 - .../server/api/git_status_helpers_test.go | 65 ++ .../server/api/metrics_handler_test.go | 93 ++ .../api/port_listener_shim_unix_test.go | 209 ++++ .../agentctl/server/api/port_listener_test.go | 96 ++ .../agentctl/server/api/processes_test.go | 391 +++++++ .../server/api/server_handlers_test.go | 308 ++++++ .../server/api/shell_terminal_test.go | 207 ++++ .../api/workspace_base_branches_test.go | 146 +++ .../server/api/workspace_handlers_test.go | 552 ++++++++++ .../server/api/workspace_stream_ws_test.go | 277 +++++ 13 files changed, 3667 insertions(+), 48 deletions(-) create mode 100644 apps/backend/internal/agentctl/server/api/agent_adapter_actions_test.go create mode 100644 apps/backend/internal/agentctl/server/api/git_handlers_test.go create mode 100644 apps/backend/internal/agentctl/server/api/git_status_helpers_test.go create mode 100644 apps/backend/internal/agentctl/server/api/metrics_handler_test.go create mode 100644 apps/backend/internal/agentctl/server/api/port_listener_shim_unix_test.go create mode 100644 apps/backend/internal/agentctl/server/api/port_listener_test.go create mode 100644 apps/backend/internal/agentctl/server/api/processes_test.go create mode 100644 apps/backend/internal/agentctl/server/api/server_handlers_test.go create mode 100644 apps/backend/internal/agentctl/server/api/shell_terminal_test.go create mode 100644 apps/backend/internal/agentctl/server/api/workspace_base_branches_test.go create mode 100644 apps/backend/internal/agentctl/server/api/workspace_handlers_test.go create mode 100644 apps/backend/internal/agentctl/server/api/workspace_stream_ws_test.go diff --git a/apps/backend/internal/agentctl/server/api/agent_adapter_actions_test.go b/apps/backend/internal/agentctl/server/api/agent_adapter_actions_test.go new file mode 100644 index 0000000000..5219c1df33 --- /dev/null +++ b/apps/backend/internal/agentctl/server/api/agent_adapter_actions_test.go @@ -0,0 +1,350 @@ +package api + +import ( + "context" + "errors" + "io" + "strings" + "testing" + + "github.com/kandev/kandev/internal/agentctl/server/adapter" + "github.com/kandev/kandev/internal/agentctl/types" + v1 "github.com/kandev/kandev/pkg/api/v1" + ws "github.com/kandev/kandev/pkg/websocket" +) + +// bareAgentAdapter satisfies adapter.AgentAdapter and nothing else, so it +// stands in for a transport that supports none of the optional session +// controls (set_mode, set_model, authenticate, reset). +type bareAgentAdapter struct { + sessionID string +} + +func (*bareAgentAdapter) PrepareEnvironment() (map[string]string, error) { return nil, nil } +func (*bareAgentAdapter) PrepareCommandArgs() []string { return nil } +func (*bareAgentAdapter) Connect(io.Writer, io.Reader) error { return nil } +func (*bareAgentAdapter) Initialize(context.Context) error { return nil } +func (*bareAgentAdapter) GetAgentInfo() *adapter.AgentInfo { return nil } +func (a *bareAgentAdapter) NewSession(context.Context, []types.McpServer) (string, error) { + return a.sessionID, nil +} + +func (a *bareAgentAdapter) LoadSession(_ context.Context, sessionID string, _ []types.McpServer) error { + a.sessionID = sessionID + return nil +} + +func (*bareAgentAdapter) Prompt(context.Context, string, []v1.MessageAttachment, uint64) error { + return nil +} +func (*bareAgentAdapter) Cancel(context.Context) error { return nil } +func (*bareAgentAdapter) Updates() <-chan adapter.AgentEvent { return nil } +func (a *bareAgentAdapter) GetSessionID() string { return a.sessionID } +func (*bareAgentAdapter) GetOperationID() string { return "" } +func (*bareAgentAdapter) SetPermissionHandler(adapter.PermissionHandler) {} +func (*bareAgentAdapter) Close() error { return nil } +func (*bareAgentAdapter) RequiresProcessKill() bool { return false } + +// capableAgentAdapter additionally implements every optional session-control +// interface and records exactly what it was handed, so the tests can prove the +// payload field reached the adapter rather than a zero value. +type capableAgentAdapter struct { + bareAgentAdapter + modeID string + modelID string + methodID string + resetServers []types.McpServer + resetErr error + failWith error +} + +func (a *capableAgentAdapter) SetMode(_ context.Context, modeID string) error { + a.modeID = modeID + return a.failWith +} + +func (a *capableAgentAdapter) SetModel(_ context.Context, modelID string) error { + a.modelID = modelID + return a.failWith +} + +func (a *capableAgentAdapter) Authenticate(_ context.Context, methodID string) error { + a.methodID = methodID + return a.failWith +} + +func (a *capableAgentAdapter) ResetSession(_ context.Context, servers []types.McpServer) (string, error) { + a.resetServers = servers + if a.resetErr != nil { + return "", a.resetErr + } + return "session-after-reset", nil +} + +func errorPayload(t *testing.T, msg *ws.Message) ws.ErrorPayload { + t.Helper() + if msg.Type != ws.MessageTypeError { + t.Fatalf("message type = %q, want %q (payload %s)", msg.Type, ws.MessageTypeError, string(msg.Payload)) + } + var payload ws.ErrorPayload + if err := msg.ParsePayload(&payload); err != nil { + t.Fatalf("parse error payload: %v", err) + } + return payload +} + +func assertAdapterActionSuccess(t *testing.T, msg *ws.Message) { + t.Helper() + if msg.Type == ws.MessageTypeError { + t.Fatalf("action failed: %s", string(msg.Payload)) + } + var payload map[string]any + if err := msg.ParsePayload(&payload); err != nil { + t.Fatalf("parse response payload: %v", err) + } + if payload["success"] != true { + t.Errorf("payload = %v, want success:true", payload) + } +} + +// adapterActionCase describes one optional session-control handler. Running +// them through a single table is what keeps the three failure shapes +// (no adapter / unsupported adapter / adapter error) identical across +// handlers — the frontend renders them with shared code. +type adapterActionCase struct { + name string + action string + payload any + invoke func(s *Server, msg *ws.Message) *ws.Message + // unsupported is the message a transport lacking the optional interface + // must produce. + unsupported string + // assertReceived checks the value the adapter was handed. + assertReceived func(t *testing.T, a *capableAgentAdapter) +} + +func adapterActionCases() []adapterActionCase { + return []adapterActionCase{ + { + name: "set_mode", + action: "agent.session.set_mode", + payload: map[string]string{"session_id": "s1", "mode_id": "plan"}, + invoke: func(s *Server, msg *ws.Message) *ws.Message { return s.handleWSSetMode(context.Background(), msg) }, + unsupported: "agent does not support mode switching", + assertReceived: func(t *testing.T, a *capableAgentAdapter) { + if a.modeID != "plan" { + t.Errorf("mode_id = %q, want %q", a.modeID, "plan") + } + }, + }, + { + name: "set_model", + action: "agent.session.set_model", + payload: map[string]string{"model_id": "claude-opus-5"}, + invoke: func(s *Server, msg *ws.Message) *ws.Message { return s.handleWSSetModel(context.Background(), msg) }, + unsupported: "agent does not support model switching", + assertReceived: func(t *testing.T, a *capableAgentAdapter) { + if a.modelID != "claude-opus-5" { + t.Errorf("model_id = %q, want %q", a.modelID, "claude-opus-5") + } + }, + }, + { + name: "authenticate", + action: "agent.authenticate", + payload: map[string]string{"method_id": "oauth"}, + invoke: func(s *Server, msg *ws.Message) *ws.Message { return s.handleWSAuthenticate(context.Background(), msg) }, + unsupported: "agent does not support authenticate", + assertReceived: func(t *testing.T, a *capableAgentAdapter) { + if a.methodID != "oauth" { + t.Errorf("method_id = %q, want %q", a.methodID, "oauth") + } + }, + }, + } +} + +// TestAdapterActions_ForwardPayloadToAdapter covers the success branch of +// adapterAction for every optional session control, and asserts the specific +// payload field reached the adapter. +func TestAdapterActions_ForwardPayloadToAdapter(t *testing.T) { + for _, tc := range adapterActionCases() { + t.Run(tc.name, func(t *testing.T) { + s := newTestServer(t) + agentAdapter := &capableAgentAdapter{} + s.procMgr.SetAdapterForTest(agentAdapter) + + msg, err := ws.NewRequest("req-1", tc.action, tc.payload) + if err != nil { + t.Fatalf("build request: %v", err) + } + assertAdapterActionSuccess(t, tc.invoke(s, msg)) + tc.assertReceived(t, agentAdapter) + }) + } +} + +// TestAdapterActions_RejectWhenAgentNotRunning covers the nil-adapter branch, +// which is what a click on a stale UI produces after the agent exits. +func TestAdapterActions_RejectWhenAgentNotRunning(t *testing.T) { + for _, tc := range adapterActionCases() { + t.Run(tc.name, func(t *testing.T) { + s := newTestServer(t) + + msg, err := ws.NewRequest("req-1", tc.action, tc.payload) + if err != nil { + t.Fatalf("build request: %v", err) + } + payload := errorPayload(t, tc.invoke(s, msg)) + if payload.Code != ws.ErrorCodeInternalError { + t.Errorf("code = %q, want %q", payload.Code, ws.ErrorCodeInternalError) + } + if payload.Message != "agent not running" { + t.Errorf("message = %q, want %q", payload.Message, "agent not running") + } + }) + } +} + +// TestAdapterActions_RejectUnsupportedTransport covers the interface assertion. +// A transport that never implemented the control must say so by name rather +// than reporting a generic failure. +func TestAdapterActions_RejectUnsupportedTransport(t *testing.T) { + for _, tc := range adapterActionCases() { + t.Run(tc.name, func(t *testing.T) { + s := newTestServer(t) + s.procMgr.SetAdapterForTest(&bareAgentAdapter{}) + + msg, err := ws.NewRequest("req-1", tc.action, tc.payload) + if err != nil { + t.Fatalf("build request: %v", err) + } + if got := errorPayload(t, tc.invoke(s, msg)).Message; got != tc.unsupported { + t.Errorf("message = %q, want %q", got, tc.unsupported) + } + }) + } +} + +// TestAdapterActions_SurfaceAdapterError covers the last branch: the adapter +// accepted the call and failed, and its reason has to reach the caller intact. +func TestAdapterActions_SurfaceAdapterError(t *testing.T) { + for _, tc := range adapterActionCases() { + t.Run(tc.name, func(t *testing.T) { + s := newTestServer(t) + s.procMgr.SetAdapterForTest(&capableAgentAdapter{failWith: errors.New("upstream refused")}) + + msg, err := ws.NewRequest("req-1", tc.action, tc.payload) + if err != nil { + t.Fatalf("build request: %v", err) + } + if got := errorPayload(t, tc.invoke(s, msg)).Message; got != "upstream refused" { + t.Errorf("message = %q, want %q", got, "upstream refused") + } + }) + } +} + +// TestAdapterActions_RejectMalformedPayload covers the parse guard, which runs +// before the adapter is even looked up. +func TestAdapterActions_RejectMalformedPayload(t *testing.T) { + for _, tc := range adapterActionCases() { + t.Run(tc.name, func(t *testing.T) { + s := newTestServer(t) + s.procMgr.SetAdapterForTest(&capableAgentAdapter{}) + + msg, err := ws.NewRequest("req-1", tc.action, "not-an-object") + if err != nil { + t.Fatalf("build request: %v", err) + } + payload := errorPayload(t, tc.invoke(s, msg)) + if payload.Code != ws.ErrorCodeBadRequest { + t.Errorf("code = %q, want %q", payload.Code, ws.ErrorCodeBadRequest) + } + if !strings.HasPrefix(payload.Message, "invalid request: ") { + t.Errorf("message = %q, want an %q prefix", payload.Message, "invalid request: ") + } + }) + } +} + +// TestHandleWSResetSession_ReturnsNewSessionID covers the happy path of the +// context-reset control. The new session ID is what the backend persists as +// ACPSessionID, so returning the old one would silently break resume. +func TestHandleWSResetSession_ReturnsNewSessionID(t *testing.T) { + s := newTestServer(t) + agentAdapter := &capableAgentAdapter{} + agentAdapter.sessionID = "session-before-reset" + s.procMgr.SetAdapterForTest(agentAdapter) + + msg, err := ws.NewRequest("req-1", "agent.session.reset", NewSessionRequest{ + McpServers: []types.McpServer{{Name: "external", URL: "https://example.invalid/mcp"}}, + }) + if err != nil { + t.Fatalf("build request: %v", err) + } + resp := s.handleWSResetSession(context.Background(), msg) + if resp.Type == ws.MessageTypeError { + t.Fatalf("reset failed: %s", string(resp.Payload)) + } + var payload NewSessionResponse + if err := resp.ParsePayload(&payload); err != nil { + t.Fatalf("parse reset payload: %v", err) + } + if !payload.Success || payload.SessionID != "session-after-reset" { + t.Errorf("payload = %+v, want the adapter's new session id", payload) + } + if len(agentAdapter.resetServers) != 1 || agentAdapter.resetServers[0].Name != "external" { + t.Errorf("adapter received %+v, want the caller's MCP servers", agentAdapter.resetServers) + } +} + +// TestHandleWSResetSession_Rejections covers all three refusal branches of the +// reset handler, which does not go through adapterAction and so needs its own +// coverage of each shape. +func TestHandleWSResetSession_Rejections(t *testing.T) { + cases := []struct { + name string + payload any + adapter adapter.AgentAdapter + wantCode string + wantMessage string + }{ + {"malformed payload", "not-an-object", &capableAgentAdapter{}, ws.ErrorCodeBadRequest, ""}, + {"agent not running", NewSessionRequest{}, nil, ws.ErrorCodeInternalError, "agent not running"}, + { + "unsupported transport", + NewSessionRequest{}, + &bareAgentAdapter{}, + ws.ErrorCodeInternalError, + "agent does not support session reset", + }, + { + "adapter failure", + NewSessionRequest{}, + &capableAgentAdapter{resetErr: errors.New("reset refused")}, + ws.ErrorCodeInternalError, + "reset refused", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + s := newTestServer(t) + if tc.adapter != nil { + s.procMgr.SetAdapterForTest(tc.adapter) + } + + msg, err := ws.NewRequest("req-1", "agent.session.reset", tc.payload) + if err != nil { + t.Fatalf("build request: %v", err) + } + payload := errorPayload(t, s.handleWSResetSession(context.Background(), msg)) + if payload.Code != tc.wantCode { + t.Errorf("code = %q, want %q", payload.Code, tc.wantCode) + } + if tc.wantMessage != "" && payload.Message != tc.wantMessage { + t.Errorf("message = %q, want %q", payload.Message, tc.wantMessage) + } + }) + } +} diff --git a/apps/backend/internal/agentctl/server/api/git_handlers_test.go b/apps/backend/internal/agentctl/server/api/git_handlers_test.go new file mode 100644 index 0000000000..91aa61e1c6 --- /dev/null +++ b/apps/backend/internal/agentctl/server/api/git_handlers_test.go @@ -0,0 +1,973 @@ +package api + +import ( + "bytes" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/kandev/kandev/internal/agentctl/server/config" + "github.com/kandev/kandev/internal/agentctl/server/process" + "github.com/kandev/kandev/internal/common/logger" +) + +// gitAPIFixture is a single-repo workspace wired to a bare `origin` remote. +// The remote matters: it gives `origin/main` a real ref so merge-base anchoring +// in handleGitLog / handleGitCumulativeDiff behaves the way it does in +// production rather than falling through the no-upstream recovery paths. +type gitAPIFixture struct { + server *Server + repo string + bare string +} + +// newGitAPIFixture seeds main (one commit, pushed to origin) plus a +// feature/work branch carrying two more commits, and returns a Server whose +// workspace root is that repository. +func newGitAPIFixture(t *testing.T) *gitAPIFixture { + t.Helper() + root := t.TempDir() + bare := filepath.Join(root, "origin.git") + runGitAPI(t, root, "init", "--bare", "--initial-branch=main", bare) + + repo := filepath.Join(root, "work") + if err := os.Mkdir(repo, 0o755); err != nil { + t.Fatalf("mkdir work: %v", err) + } + runGitAPI(t, repo, "init", "--initial-branch=main") + runGitAPI(t, repo, "config", "user.email", "test@test.com") + runGitAPI(t, repo, "config", "user.name", "Test User") + writeFileAPI(t, repo, "README.md", "base\n") + runGitAPI(t, repo, "add", ".") + runGitAPI(t, repo, "commit", "-m", "initial") + runGitAPI(t, repo, "remote", "add", "origin", bare) + runGitAPI(t, repo, "push", "-u", "origin", "main") + + runGitAPI(t, repo, "checkout", "-b", "feature/work") + writeFileAPI(t, repo, "one.txt", "one\n") + runGitAPI(t, repo, "add", ".") + runGitAPI(t, repo, "commit", "-m", "feature one") + writeFileAPI(t, repo, "two.txt", "two\n") + runGitAPI(t, repo, "add", ".") + runGitAPI(t, repo, "commit", "-m", "feature two") + + log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error"}) + cfg := &config.InstanceConfig{WorkDir: repo} + return &gitAPIFixture{ + server: NewServer(cfg, process.NewManager(cfg, log), nil, nil, log), + repo: repo, + bare: bare, + } +} + +func (f *gitAPIFixture) head(t *testing.T) string { + t.Helper() + return strings.TrimSpace(runGitAPI(t, f.repo, "rev-parse", "HEAD")) +} + +func (f *gitAPIFixture) branch(t *testing.T) string { + t.Helper() + return strings.TrimSpace(runGitAPI(t, f.repo, "rev-parse", "--abbrev-ref", "HEAD")) +} + +// postGitAPI issues a POST with a JSON body (or a raw string body verbatim, +// which is how the malformed-payload cases are expressed). +func postGitAPI(t *testing.T, srv *Server, path string, body any) *httptest.ResponseRecorder { + t.Helper() + var payload []byte + switch v := body.(type) { + case string: + payload = []byte(v) + default: + encoded, err := json.Marshal(v) + if err != nil { + t.Fatalf("marshal body: %v", err) + } + payload = encoded + } + req := httptest.NewRequest(http.MethodPost, path, bytes.NewReader(payload)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + srv.Router().ServeHTTP(rec, req) + return rec +} + +func getGitAPI(t *testing.T, srv *Server, path string) *httptest.ResponseRecorder { + t.Helper() + rec := httptest.NewRecorder() + srv.Router().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil)) + return rec +} + +func decodeGitOperationResult(t *testing.T, rec *httptest.ResponseRecorder) process.GitOperationResult { + t.Helper() + var result process.GitOperationResult + if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { + t.Fatalf("decode git operation result from %q: %v", rec.Body.String(), err) + } + return result +} + +// TestGitHandlers_RejectMalformedBody pins the shape of the 400 every git POST +// handler writes for an unparseable body: the operation label the caller sent +// the request for, and an "invalid request: " prefixed error. The operation +// label is what the frontend keys its error toast off, so a copy-paste slip +// between handlers is a user-visible bug that no status-code-only test catches. +func TestGitHandlers_RejectMalformedBody(t *testing.T) { + fixture := newGitAPIFixture(t) + + cases := []struct { + path string + operation string + }{ + {"/api/v1/git/pull", "pull"}, + {"/api/v1/git/push", "push"}, + {"/api/v1/git/push-preflight", "push_preflight"}, + {"/api/v1/git/rebase", "rebase"}, + {"/api/v1/git/merge", "merge"}, + {"/api/v1/git/abort", "abort"}, + {"/api/v1/git/commit", "commit"}, + {"/api/v1/git/rename-branch", "rename_branch"}, + {"/api/v1/git/stage", "stage"}, + {"/api/v1/git/unstage", "unstage"}, + {"/api/v1/git/discard", "discard"}, + {"/api/v1/git/revert-commit", "revert_commit"}, + {"/api/v1/git/reset", "reset"}, + } + for _, tc := range cases { + t.Run(tc.operation, func(t *testing.T) { + rec := postGitAPI(t, fixture.server, tc.path, "{not json") + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want %d (body %s)", rec.Code, http.StatusBadRequest, rec.Body.String()) + } + result := decodeGitOperationResult(t, rec) + if result.Success { + t.Errorf("success = true, want false") + } + if result.Operation != tc.operation { + t.Errorf("operation = %q, want %q", result.Operation, tc.operation) + } + if !strings.HasPrefix(result.Error, "invalid request: ") { + t.Errorf("error = %q, want an %q prefix", result.Error, "invalid request: ") + } + }) + } +} + +// TestGitHandlers_RejectMissingRequiredFields pins each handler's own +// pre-flight validation message. These are the only guards standing between an +// empty form field and a git invocation with a missing argument. +func TestGitHandlers_RejectMissingRequiredFields(t *testing.T) { + fixture := newGitAPIFixture(t) + + cases := []struct { + name string + path string + body any + operation string + wantError string + }{ + {"rebase without base", "/api/v1/git/rebase", GitRebaseRequest{}, "rebase", "base_branch is required"}, + {"merge without base", "/api/v1/git/merge", GitMergeRequest{}, "merge", "base_branch is required"}, + { + "abort with unknown operation", + "/api/v1/git/abort", + GitAbortRequest{Operation: "cherry-pick"}, + "abort", + "operation must be 'merge' or 'rebase'", + }, + {"commit without message", "/api/v1/git/commit", GitCommitRequest{}, "commit", "message is required"}, + { + "rename-branch without name", + "/api/v1/git/rename-branch", + GitRenameBranchRequest{}, + "rename_branch", + "new_name is required", + }, + {"discard without paths", "/api/v1/git/discard", GitDiscardRequest{}, "discard", "paths are required"}, + { + "revert-commit without sha", + "/api/v1/git/revert-commit", + GitRevertCommitRequest{}, + "revert_commit", + "commit_sha is required", + }, + {"reset without sha", "/api/v1/git/reset", GitResetRequest{}, "reset", "commit_sha is required"}, + { + "reset with unknown mode", + "/api/v1/git/reset", + GitResetRequest{CommitSHA: "HEAD", Mode: "squash"}, + "reset", + "invalid reset mode: squash (must be soft, mixed, or hard)", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := postGitAPI(t, fixture.server, tc.path, tc.body) + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want %d (body %s)", rec.Code, http.StatusBadRequest, rec.Body.String()) + } + result := decodeGitOperationResult(t, rec) + if result.Success { + t.Errorf("success = true, want false") + } + if result.Operation != tc.operation { + t.Errorf("operation = %q, want %q", result.Operation, tc.operation) + } + if result.Error != tc.wantError { + t.Errorf("error = %q, want %q", result.Error, tc.wantError) + } + }) + } +} + +// TestGitOpForRepo_RejectsUnresolvableSubpath covers the shared repo-scope +// barrier. A bad `repo` must be refused before any git command runs, and the +// refusal has to carry the operation the caller asked for so the failure is +// attributable in a multi-repo UI. +func TestGitOpForRepo_RejectsUnresolvableSubpath(t *testing.T) { + fixture := newGitAPIFixture(t) + + cases := []struct { + name string + path string + body any + operation string + wantError string + }{ + {"missing subpath", "/api/v1/git/pull", GitPullRequest{Repo: "nope"}, "pull", "repo subpath not found"}, + { + "traversal", + "/api/v1/git/commit", + GitCommitRequest{Message: "m", Repo: "../escape"}, + "commit", + "invalid repo subpath", + }, + { + "absolute", + "/api/v1/git/stage", + GitStageRequest{Repo: filepath.Join(t.TempDir(), "abs")}, + "stage", + "repo subpath must be relative", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := postGitAPI(t, fixture.server, tc.path, tc.body) + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want %d (body %s)", rec.Code, http.StatusBadRequest, rec.Body.String()) + } + result := decodeGitOperationResult(t, rec) + if result.Operation != tc.operation { + t.Errorf("operation = %q, want %q", result.Operation, tc.operation) + } + if !strings.Contains(result.Error, tc.wantError) { + t.Errorf("error = %q, want it to contain %q", result.Error, tc.wantError) + } + }) + } +} + +// TestHandleGitCommit_CreatesCommitInWorktree asserts the endpoint's real +// effect rather than only its response: the working-tree change is staged and +// committed with exactly the requested message. +func TestHandleGitCommit_CreatesCommitInWorktree(t *testing.T) { + fixture := newGitAPIFixture(t) + writeFileAPI(t, fixture.repo, "three.txt", "three\n") + + rec := postGitAPI(t, fixture.server, "/api/v1/git/commit", GitCommitRequest{ + Message: "handler commit", + StageAll: true, + }) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200 (body %s)", rec.Code, rec.Body.String()) + } + result := decodeGitOperationResult(t, rec) + if !result.Success { + t.Fatalf("commit failed: %+v", result) + } + if got := strings.TrimSpace(runGitAPI(t, fixture.repo, "log", "-1", "--format=%s")); got != "handler commit" { + t.Errorf("HEAD subject = %q, want %q", got, "handler commit") + } + if got := strings.TrimSpace(runGitAPI(t, fixture.repo, "status", "--porcelain")); got != "" { + t.Errorf("worktree not clean after stage_all commit: %q", got) + } +} + +// TestHandleGitStageAndUnstage checks both directions of the index against +// `git status --porcelain`, which is the only place the difference between +// staged and unstaged is observable. +func TestHandleGitStageAndUnstage(t *testing.T) { + fixture := newGitAPIFixture(t) + writeFileAPI(t, fixture.repo, "staged.txt", "staged\n") + + stage := postGitAPI(t, fixture.server, "/api/v1/git/stage", GitStageRequest{Paths: []string{"staged.txt"}}) + if stage.Code != http.StatusOK { + t.Fatalf("stage status = %d (body %s)", stage.Code, stage.Body.String()) + } + if result := decodeGitOperationResult(t, stage); !result.Success { + t.Fatalf("stage failed: %+v", result) + } + if got := strings.TrimSpace(runGitAPI(t, fixture.repo, "status", "--porcelain", "staged.txt")); got != "A staged.txt" { + t.Fatalf("porcelain after stage = %q, want %q", got, "A staged.txt") + } + + unstage := postGitAPI(t, fixture.server, "/api/v1/git/unstage", GitUnstageRequest{Paths: []string{"staged.txt"}}) + if unstage.Code != http.StatusOK { + t.Fatalf("unstage status = %d (body %s)", unstage.Code, unstage.Body.String()) + } + if result := decodeGitOperationResult(t, unstage); !result.Success { + t.Fatalf("unstage failed: %+v", result) + } + if got := strings.TrimSpace(runGitAPI(t, fixture.repo, "status", "--porcelain", "staged.txt")); got != "?? staged.txt" { + t.Errorf("porcelain after unstage = %q, want %q", got, "?? staged.txt") + } +} + +// TestHandleGitDiscard_RestoresTrackedFile asserts the destructive path +// actually restores the committed bytes. +func TestHandleGitDiscard_RestoresTrackedFile(t *testing.T) { + fixture := newGitAPIFixture(t) + writeFileAPI(t, fixture.repo, "one.txt", "locally edited\n") + + rec := postGitAPI(t, fixture.server, "/api/v1/git/discard", GitDiscardRequest{Paths: []string{"one.txt"}}) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + if result := decodeGitOperationResult(t, rec); !result.Success { + t.Fatalf("discard failed: %+v", result) + } + content, err := os.ReadFile(filepath.Join(fixture.repo, "one.txt")) + if err != nil { + t.Fatalf("read one.txt: %v", err) + } + if string(content) != "one\n" { + t.Errorf("one.txt = %q, want the committed %q", string(content), "one\n") + } +} + +// TestHandleGitRenameBranch_MovesCurrentBranch verifies the rename lands on the +// checked-out branch rather than merely returning success. +func TestHandleGitRenameBranch_MovesCurrentBranch(t *testing.T) { + fixture := newGitAPIFixture(t) + + rec := postGitAPI(t, fixture.server, "/api/v1/git/rename-branch", GitRenameBranchRequest{NewName: "feature/renamed"}) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + if result := decodeGitOperationResult(t, rec); !result.Success { + t.Fatalf("rename failed: %+v", result) + } + if got := fixture.branch(t); got != "feature/renamed" { + t.Errorf("current branch = %q, want %q", got, "feature/renamed") + } +} + +// TestHandleGitReset_HardMovesHead asserts the mode is forwarded: a hard reset +// has to move HEAD *and* drop the working-tree file, which a soft reset would +// not do. +func TestHandleGitReset_HardMovesHead(t *testing.T) { + fixture := newGitAPIFixture(t) + target := strings.TrimSpace(runGitAPI(t, fixture.repo, "rev-parse", "HEAD~1")) + + rec := postGitAPI(t, fixture.server, "/api/v1/git/reset", GitResetRequest{CommitSHA: target, Mode: "hard"}) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + if result := decodeGitOperationResult(t, rec); !result.Success { + t.Fatalf("reset failed: %+v", result) + } + if got := fixture.head(t); got != target { + t.Errorf("HEAD = %q, want %q", got, target) + } + if _, err := os.Stat(filepath.Join(fixture.repo, "two.txt")); !errors.Is(err, os.ErrNotExist) { + t.Errorf("two.txt still present after a hard reset (stat err = %v)", err) + } +} + +// TestHandleGitRevertCommit_UncommitsHeadKeepingWork pins what revert_commit +// actually is: a soft un-commit of HEAD, which rewinds history one commit while +// leaving the files staged. Losing the staged work — or rewinding further than +// one commit — would be silent data loss for the user who clicked "undo commit". +func TestHandleGitRevertCommit_UncommitsHeadKeepingWork(t *testing.T) { + fixture := newGitAPIFixture(t) + target := fixture.head(t) + parent := strings.TrimSpace(runGitAPI(t, fixture.repo, "rev-parse", "HEAD~1")) + + rec := postGitAPI(t, fixture.server, "/api/v1/git/revert-commit", GitRevertCommitRequest{CommitSHA: target}) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + if result := decodeGitOperationResult(t, rec); !result.Success { + t.Fatalf("revert failed: %+v", result) + } + if got := fixture.head(t); got != parent { + t.Errorf("HEAD = %q, want the parent commit %q", got, parent) + } + if got := strings.TrimSpace(runGitAPI(t, fixture.repo, "status", "--porcelain", "two.txt")); got != "A two.txt" { + t.Errorf("porcelain for two.txt = %q, want it staged as %q", got, "A two.txt") + } +} + +// TestHandleGitRevertCommit_RefusesOlderCommit covers the guard that keeps the +// soft un-commit from rewinding past HEAD, which would drop the commits in +// between without the caller asking for it. +func TestHandleGitRevertCommit_RefusesOlderCommit(t *testing.T) { + fixture := newGitAPIFixture(t) + head := fixture.head(t) + older := strings.TrimSpace(runGitAPI(t, fixture.repo, "rev-parse", "HEAD~1")) + + rec := postGitAPI(t, fixture.server, "/api/v1/git/revert-commit", GitRevertCommitRequest{CommitSHA: older}) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200 (body %s)", rec.Code, rec.Body.String()) + } + result := decodeGitOperationResult(t, rec) + if result.Success { + t.Errorf("success = true; only the latest commit may be reverted") + } + if result.Error != "can only revert the latest commit" { + t.Errorf("error = %q, want %q", result.Error, "can only revert the latest commit") + } + if got := fixture.head(t); got != head { + t.Errorf("HEAD moved to %q despite the refusal; want it left at %q", got, head) + } +} + +// TestHandleGitShowCommit_ReturnsRequestedCommit pins the URI binding: the sha +// travels through the path parameter, and the response must be about that +// commit specifically. +func TestHandleGitShowCommit_ReturnsRequestedCommit(t *testing.T) { + fixture := newGitAPIFixture(t) + sha := fixture.head(t) + + rec := getGitAPI(t, fixture.server, "/api/v1/git/commit/"+sha) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + var result process.CommitDiffResult + if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { + t.Fatalf("decode commit diff: %v", err) + } + if !result.Success { + t.Fatalf("show commit failed: %+v", result) + } + if result.CommitSHA != sha { + t.Errorf("commit_sha = %q, want %q", result.CommitSHA, sha) + } + if _, ok := result.Files["two.txt"]; !ok { + t.Errorf("files = %v, want it to contain two.txt", mapKeys(result.Files)) + } +} + +// TestHandleGitShowCommit_UnknownCommitReportsInBody covers the failure branch. +// A missing object is a per-commit result failure, not a transport error, so it +// answers 200 with success=false — the frontend renders the message inline +// rather than treating the request as broken. +func TestHandleGitShowCommit_UnknownCommitReportsInBody(t *testing.T) { + fixture := newGitAPIFixture(t) + const missing = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef" + + rec := getGitAPI(t, fixture.server, "/api/v1/git/commit/"+missing) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200 (body %s)", rec.Code, rec.Body.String()) + } + var result process.CommitDiffResult + if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { + t.Fatalf("decode commit diff: %v", err) + } + if result.Success { + t.Errorf("success = true, want false") + } + if result.CommitSHA != missing { + t.Errorf("commit_sha = %q, want the requested sha echoed back", result.CommitSHA) + } + if !strings.Contains(result.Error, "bad object") { + t.Errorf("error = %q, want it to name the bad object", result.Error) + } +} + +// TestHandleGitShowCommit_RejectsUnresolvableRepo covers the `?repo=` branch of +// the same handler, which has its own CommitDiffResult error shape. +func TestHandleGitShowCommit_RejectsUnresolvableRepo(t *testing.T) { + fixture := newGitAPIFixture(t) + sha := fixture.head(t) + + rec := getGitAPI(t, fixture.server, "/api/v1/git/commit/"+sha+"?repo=nope") + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 (body %s)", rec.Code, rec.Body.String()) + } + var result process.CommitDiffResult + if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { + t.Fatalf("decode commit diff: %v", err) + } + if !strings.Contains(result.Error, "repo subpath not found") { + t.Errorf("error = %q, want a repo-subpath failure", result.Error) + } +} + +// TestHandleGitPushAndPull_RoundTripThroughOrigin drives both remote-facing +// handlers against a real bare repository so the assertions are about the +// remote's state, not just a success flag. +func TestHandleGitPushAndPull_RoundTripThroughOrigin(t *testing.T) { + fixture := newGitAPIFixture(t) + head := fixture.head(t) + + push := postGitAPI(t, fixture.server, "/api/v1/git/push", GitPushRequest{SetUpstream: true}) + if push.Code != http.StatusOK { + t.Fatalf("push status = %d (body %s)", push.Code, push.Body.String()) + } + if result := decodeGitOperationResult(t, push); !result.Success { + t.Fatalf("push failed: %+v", result) + } + remoteHead := strings.TrimSpace(runGitAPI(t, fixture.bare, "rev-parse", "refs/heads/feature/work")) + if remoteHead != head { + t.Errorf("origin feature/work = %q, want the pushed HEAD %q", remoteHead, head) + } + + pull := postGitAPI(t, fixture.server, "/api/v1/git/pull", GitPullRequest{}) + if pull.Code != http.StatusOK { + t.Fatalf("pull status = %d (body %s)", pull.Code, pull.Body.String()) + } + if result := decodeGitOperationResult(t, pull); !result.Success { + t.Fatalf("pull failed: %+v", result) + } + if got := fixture.head(t); got != head { + t.Errorf("HEAD moved during a no-op pull: %q != %q", got, head) + } +} + +// TestHandleGitPushPreflight_ReportsRemoteState exercises the preflight +// endpoint, which the changes panel calls before offering a push. +func TestHandleGitPushPreflight_ReportsRemoteState(t *testing.T) { + fixture := newGitAPIFixture(t) + + rec := postGitAPI(t, fixture.server, "/api/v1/git/push-preflight", GitPushPreflightRequest{}) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + result := decodeGitOperationResult(t, rec) + if result.Operation != "push_preflight" { + t.Errorf("operation = %q, want %q", result.Operation, "push_preflight") + } +} + +// advanceOriginMain adds a commit to main and publishes it, so the rebase and +// merge handlers — which both fetch and then operate on `origin/` rather +// than the local ref — have something to integrate. +func (f *gitAPIFixture) advanceOriginMain(t *testing.T) string { + t.Helper() + runGitAPI(t, f.repo, "checkout", "main") + writeFileAPI(t, f.repo, "main-only.txt", "main\n") + runGitAPI(t, f.repo, "add", ".") + runGitAPI(t, f.repo, "commit", "-m", "main moves") + runGitAPI(t, f.repo, "push", "origin", "main") + mainHead := strings.TrimSpace(runGitAPI(t, f.repo, "rev-parse", "HEAD")) + runGitAPI(t, f.repo, "checkout", "feature/work") + return mainHead +} + +// TestHandleGitRebase_ReplaysOntoBase asserts the branch is genuinely replayed: +// after rebasing onto a moved main, main's new commit is an ancestor of HEAD. +func TestHandleGitRebase_ReplaysOntoBase(t *testing.T) { + fixture := newGitAPIFixture(t) + mainHead := fixture.advanceOriginMain(t) + + rec := postGitAPI(t, fixture.server, "/api/v1/git/rebase", GitRebaseRequest{BaseBranch: "main"}) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + if result := decodeGitOperationResult(t, rec); !result.Success { + t.Fatalf("rebase failed: %+v", result) + } + if got := strings.TrimSpace(runGitAPI(t, fixture.repo, "merge-base", "HEAD", "main")); got != mainHead { + t.Errorf("merge-base with main = %q, want main's tip %q — the branch was not replayed", got, mainHead) + } +} + +// TestHandleGitMerge_BringsBaseCommitIn covers the merge counterpart, which +// leaves main's commit reachable from HEAD without rewriting the branch. +func TestHandleGitMerge_BringsBaseCommitIn(t *testing.T) { + fixture := newGitAPIFixture(t) + featureHead := fixture.head(t) + mainHead := fixture.advanceOriginMain(t) + + rec := postGitAPI(t, fixture.server, "/api/v1/git/merge", GitMergeRequest{BaseBranch: "main"}) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + if result := decodeGitOperationResult(t, rec); !result.Success { + t.Fatalf("merge failed: %+v", result) + } + for _, want := range []string{featureHead, mainHead} { + runGitAPI(t, fixture.repo, "merge-base", "--is-ancestor", want, "HEAD") + } +} + +// TestHandleGitAbort_WithNothingInProgress covers the abort handler's runtime +// path: the guard accepts "rebase", git refuses because nothing is in flight, +// and the failure is reported inside a 200 GitOperationResult rather than as a +// transport error. +func TestHandleGitAbort_WithNothingInProgress(t *testing.T) { + fixture := newGitAPIFixture(t) + + rec := postGitAPI(t, fixture.server, "/api/v1/git/abort", GitAbortRequest{Operation: "rebase"}) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200 (body %s)", rec.Code, rec.Body.String()) + } + result := decodeGitOperationResult(t, rec) + if result.Operation != "abort" { + t.Errorf("operation = %q, want %q", result.Operation, "abort") + } + if result.Success { + t.Errorf("success = true, but no rebase was in progress") + } +} + +// TestHandleGitCreatePR_UnsupportedRemoteReportsProviderError pins the +// create-PR success path's error shape. The fixture's origin is a local path, +// which no PR provider claims; the refusal has to reach the caller inside a +// PRCreateResult (not as a transport failure) so the changes panel can explain +// which remotes are supported. +func TestHandleGitCreatePR_UnsupportedRemoteReportsProviderError(t *testing.T) { + fixture := newGitAPIFixture(t) + + rec := postGitAPI(t, fixture.server, "/api/v1/git/create-pr", GitCreatePRRequest{ + Title: "add feature", + Body: "body", + BaseBranch: "main", + }) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200 (body %s)", rec.Code, rec.Body.String()) + } + var result process.PRCreateResult + if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { + t.Fatalf("decode PR result: %v", err) + } + if result.Success { + t.Errorf("success = true, want false") + } + if !strings.Contains(result.Error, "unsupported git remote for PR creation") { + t.Errorf("error = %q, want it to name the unsupported remote", result.Error) + } +} + +// TestHandleGitCreatePR_ValidationErrors covers the two 400 branches, both of +// which answer with a PRCreateResult (not the GitOperationResult shape the +// neighbouring handlers use). +func TestHandleGitCreatePR_ValidationErrors(t *testing.T) { + fixture := newGitAPIFixture(t) + + cases := []struct { + name string + body any + wantError string + }{ + {"malformed body", "{not json", "invalid request: "}, + {"missing title", GitCreatePRRequest{Body: "b"}, "title is required"}, + {"unresolvable repo", GitCreatePRRequest{Title: "t", Repo: "nope"}, "repo subpath not found"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := postGitAPI(t, fixture.server, "/api/v1/git/create-pr", tc.body) + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 (body %s)", rec.Code, rec.Body.String()) + } + var result process.PRCreateResult + if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { + t.Fatalf("decode PR result: %v", err) + } + if result.Success { + t.Errorf("success = true, want false") + } + if !strings.Contains(result.Error, tc.wantError) { + t.Errorf("error = %q, want it to contain %q", result.Error, tc.wantError) + } + }) + } +} + +// TestHandleGitLog_BoundsLimit pins both ends of the limit guard: an +// over-large limit is refused outright, and an unparseable one fails binding. +func TestHandleGitLog_BoundsLimit(t *testing.T) { + fixture := newGitAPIFixture(t) + + cases := []struct { + name string + query string + wantError string + }{ + {"above maximum", "?limit=501", "limit must be between 1 and 500"}, + {"not a number", "?limit=many", "invalid request: "}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := getGitAPI(t, fixture.server, "/api/v1/git/log"+tc.query) + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 (body %s)", rec.Code, rec.Body.String()) + } + var result process.GitLogResult + if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { + t.Fatalf("decode git log: %v", err) + } + if result.Success { + t.Errorf("success = true, want false") + } + if !strings.Contains(result.Error, tc.wantError) { + t.Errorf("error = %q, want it to contain %q", result.Error, tc.wantError) + } + }) + } +} + +// TestHandleGitLog_RejectsUnsafeTargetBranch is the sanitiser test. A valid +// target anchors the log at the merge-base with origin/main, so only the +// branch's own two commits come back. An injection-shaped ref must be dropped +// rather than interpolated into the git arguments — which is observable as the +// handler falling back to the open-ended "recent commits" walk that also +// includes main's initial commit. +func TestHandleGitLog_RejectsUnsafeTargetBranch(t *testing.T) { + fixture := newGitAPIFixture(t) + + anchored := gitLogSubjects(t, fixture.server, "/api/v1/git/log?target_branch=main") + if len(anchored) != 2 || anchored[0] != "feature two" || anchored[1] != "feature one" { + t.Fatalf("anchored log = %v, want exactly the branch's own commits", anchored) + } + + for _, unsafe := range []string{"main;whoami", "main..HEAD", "/etc/passwd", "main.lock", "-main"} { + t.Run(unsafe, func(t *testing.T) { + got := gitLogSubjects(t, fixture.server, "/api/v1/git/log?target_branch="+unsafe) + if len(got) != 3 { + t.Fatalf("log for %q = %v, want the unanchored 3-commit history "+ + "(the ref must be dropped, not passed to git)", unsafe, got) + } + if got[2] != "initial" { + t.Errorf("oldest commit = %q, want %q", got[2], "initial") + } + }) + } +} + +// TestHandleGitLog_HonoursSince covers the explicit-base path, where the caller +// supplies the anchor instead of a branch to merge-base against. +func TestHandleGitLog_HonoursSince(t *testing.T) { + fixture := newGitAPIFixture(t) + base := strings.TrimSpace(runGitAPI(t, fixture.repo, "rev-parse", "HEAD~1")) + + got := gitLogSubjects(t, fixture.server, "/api/v1/git/log?since="+base) + if len(got) != 1 || got[0] != "feature two" { + t.Errorf("log since HEAD~1 = %v, want just [feature two]", got) + } +} + +func gitLogSubjects(t *testing.T, srv *Server, path string) []string { + t.Helper() + rec := getGitAPI(t, srv, path) + if rec.Code != http.StatusOK { + t.Fatalf("git log %s: status = %d (body %s)", path, rec.Code, rec.Body.String()) + } + var result process.GitLogResult + if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { + t.Fatalf("decode git log: %v", err) + } + if !result.Success { + t.Fatalf("git log %s failed: %+v", path, result) + } + subjects := make([]string, 0, len(result.Commits)) + for _, commit := range result.Commits { + subjects = append(subjects, commit.CommitMessage) + } + return subjects +} + +// TestHandleGitCumulativeDiff_RequiresBase covers the query binding, which is +// the only required parameter on the endpoint. +func TestHandleGitCumulativeDiff_RequiresBase(t *testing.T) { + fixture := newGitAPIFixture(t) + + rec := getGitAPI(t, fixture.server, "/api/v1/git/cumulative-diff") + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 (body %s)", rec.Code, rec.Body.String()) + } + var result process.CumulativeDiffResult + if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { + t.Fatalf("decode cumulative diff: %v", err) + } + if !strings.HasPrefix(result.Error, "invalid request: ") { + t.Errorf("error = %q, want an %q prefix", result.Error, "invalid request: ") + } +} + +// TestHandleGitCumulativeDiff_AnchorsOnTargetBranch checks the merge-base +// recomputation: the caller's stale base is replaced by the live divergence +// with origin/main, so the diff carries exactly the branch's own files. +func TestHandleGitCumulativeDiff_AnchorsOnTargetBranch(t *testing.T) { + fixture := newGitAPIFixture(t) + stale := fixture.head(t) // HEAD as base would produce an empty diff + + rec := getGitAPI(t, fixture.server, "/api/v1/git/cumulative-diff?base="+stale+"&target_branch=main") + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + var result process.CumulativeDiffResult + if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { + t.Fatalf("decode cumulative diff: %v", err) + } + if !result.Success { + t.Fatalf("cumulative diff failed: %+v", result) + } + for _, want := range []string{"one.txt", "two.txt"} { + if _, ok := result.Files[want]; !ok { + t.Errorf("files = %v, want it to contain %q", mapKeys(result.Files), want) + } + } + if _, ok := result.Files["README.md"]; ok { + t.Errorf("files include README.md; the diff is not anchored at the merge-base") + } +} + +// TestHandleGitCumulativeDiff_RejectsUnresolvableRepo covers the 400 branch +// that runGitCumulativeDiffForRepo returns before touching git. +func TestHandleGitCumulativeDiff_RejectsUnresolvableRepo(t *testing.T) { + fixture := newGitAPIFixture(t) + + rec := getGitAPI(t, fixture.server, "/api/v1/git/cumulative-diff?base=HEAD&repo=nope") + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 (body %s)", rec.Code, rec.Body.String()) + } + var result process.CumulativeDiffResult + if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { + t.Fatalf("decode cumulative diff: %v", err) + } + if !strings.Contains(result.Error, "repo subpath not found") { + t.Errorf("error = %q, want a repo-subpath failure", result.Error) + } +} + +// TestHandleGitStatus_ReportsWorktreeState asserts the single-repo status +// endpoint reflects the real worktree, including the branch name and the +// classification of each dirty path. +func TestHandleGitStatus_ReportsWorktreeState(t *testing.T) { + fixture := newGitAPIFixture(t) + writeFileAPI(t, fixture.repo, "untracked.txt", "new\n") + writeFileAPI(t, fixture.repo, "one.txt", "edited\n") + + rec := getGitAPI(t, fixture.server, "/api/v1/git/status?fresh=true") + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + var result GitStatusResult + if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { + t.Fatalf("decode git status: %v", err) + } + if !result.Success { + t.Fatalf("git status failed: %+v", result) + } + if result.Branch != "feature/work" { + t.Errorf("branch = %q, want %q", result.Branch, "feature/work") + } + if !slices.Contains(result.Untracked, "untracked.txt") { + t.Errorf("untracked = %v, want it to contain untracked.txt", result.Untracked) + } + if !slices.Contains(result.Modified, "one.txt") { + t.Errorf("modified = %v, want it to contain one.txt", result.Modified) + } + if result.Timestamp == "" { + t.Errorf("timestamp is empty; the response must carry a snapshot time") + } +} + +// TestHandleGitStatus_RejectsUnresolvableRepo covers the tracker-lookup 400. +func TestHandleGitStatus_RejectsUnresolvableRepo(t *testing.T) { + fixture := newGitAPIFixture(t) + + rec := getGitAPI(t, fixture.server, "/api/v1/git/status?repo=nope") + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 (body %s)", rec.Code, rec.Body.String()) + } + var result GitStatusResult + if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { + t.Fatalf("decode git status: %v", err) + } + if result.Success { + t.Errorf("success = true, want false") + } + if !strings.Contains(result.Error, "repo subpath not found") { + t.Errorf("error = %q, want a repo-subpath failure", result.Error) + } +} + +// TestHandleGitStatusMulti_SingleRepoUsesEmptyRepositoryName pins the uniform +// response shape callers rely on: a single-repo workspace still answers with +// the multi shape, tagged with an empty repository name. +func TestHandleGitStatusMulti_SingleRepoUsesEmptyRepositoryName(t *testing.T) { + fixture := newGitAPIFixture(t) + + rec := getGitAPI(t, fixture.server, "/api/v1/git/status/multi") + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + var result MultiRepoGitStatusResult + if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { + t.Fatalf("decode multi status: %v", err) + } + if !result.Success || len(result.Repos) != 1 { + t.Fatalf("multi status = %+v, want exactly one repo entry", result) + } + if result.Repos[0].RepositoryName != "" { + t.Errorf("repository_name = %q, want empty for a single-repo workspace", result.Repos[0].RepositoryName) + } + if result.Repos[0].Status.Branch != "feature/work" { + t.Errorf("branch = %q, want %q", result.Repos[0].Status.Branch, "feature/work") + } +} + +// TestHandleGitError_ClassifiesOperationInProgress pins the one branch of +// handleGitError that is not a generic 500: a busy GitOperator must answer 409 +// with a stable, non-leaking message, because the frontend retries on that +// code and shows the raw error on every other one. +func TestHandleGitError_ClassifiesOperationInProgress(t *testing.T) { + fixture := newGitAPIFixture(t) + + cases := []struct { + name string + err error + wantStatus int + wantError string + }{ + { + "busy operator", + process.ErrOperationInProgress, + http.StatusConflict, + "another git operation is already in progress", + }, + {"other failure", errors.New("fatal: not a git repository"), http.StatusInternalServerError, "fatal: not a git repository"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + fixture.server.handleGitError(c, "rebase", tc.err) + + if rec.Code != tc.wantStatus { + t.Fatalf("status = %d, want %d (body %s)", rec.Code, tc.wantStatus, rec.Body.String()) + } + result := decodeGitOperationResult(t, rec) + if result.Success { + t.Errorf("success = true, want false") + } + if result.Operation != "rebase" { + t.Errorf("operation = %q, want %q", result.Operation, "rebase") + } + if result.Error != tc.wantError { + t.Errorf("error = %q, want %q", result.Error, tc.wantError) + } + }) + } +} diff --git a/apps/backend/internal/agentctl/server/api/git_status_fresh_concurrency_test.go b/apps/backend/internal/agentctl/server/api/git_status_fresh_concurrency_test.go index 7d488bc804..76129c3415 100644 --- a/apps/backend/internal/agentctl/server/api/git_status_fresh_concurrency_test.go +++ b/apps/backend/internal/agentctl/server/api/git_status_fresh_concurrency_test.go @@ -180,54 +180,6 @@ func statusesByRepo(t *testing.T, result MultiRepoGitStatusResult, wantRepos []s return statuses } -func mapKeys[V any](values map[string]V) []string { - keys := make([]string, 0, len(values)) - for key := range values { - keys = append(keys, key) - } - return keys -} - -func assertRepoNames(t *testing.T, got, want []string) { - t.Helper() - gotSet := make(map[string]bool, len(got)) - for _, repo := range got { - gotSet[repo] = true - } - for _, repo := range want { - if !gotSet[repo] { - t.Errorf("repositories %v missing %q", got, repo) - } - } -} - -func newMultiRepoStatusServer(t *testing.T) (*Server, []string) { - t.Helper() - taskRoot := t.TempDir() - repoNames := []string{"alpha", "beta"} - for _, repo := range repoNames { - newStatusTestRepo(t, taskRoot, repo) - } - log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error"}) - cfg := &config.InstanceConfig{WorkDir: taskRoot} - return NewServer(cfg, process.NewManager(cfg, log), nil, nil, log), repoNames -} - -func newStatusTestRepo(t *testing.T, taskRoot, name string) string { - t.Helper() - repoDir := filepath.Join(taskRoot, name) - if err := os.Mkdir(repoDir, 0o755); err != nil { - t.Fatalf("mkdir %s: %v", name, err) - } - runGitAPI(t, repoDir, "init", "--initial-branch=main") - runGitAPI(t, repoDir, "config", "user.email", "test@test.com") - runGitAPI(t, repoDir, "config", "user.name", "Test User") - writeFileAPI(t, repoDir, "README.md", name+"\n") - runGitAPI(t, repoDir, "add", ".") - runGitAPI(t, repoDir, "commit", "-m", "initial") - return repoDir -} - type gitStatusCommandGate struct { events *os.File release *os.File diff --git a/apps/backend/internal/agentctl/server/api/git_status_helpers_test.go b/apps/backend/internal/agentctl/server/api/git_status_helpers_test.go new file mode 100644 index 0000000000..4e5f2ce325 --- /dev/null +++ b/apps/backend/internal/agentctl/server/api/git_status_helpers_test.go @@ -0,0 +1,65 @@ +package api + +import ( + "os" + "path/filepath" + "testing" + + "github.com/kandev/kandev/internal/agentctl/server/config" + "github.com/kandev/kandev/internal/agentctl/server/process" + "github.com/kandev/kandev/internal/common/logger" +) + +// Shared multi-repo status fixtures. These live in their own file rather than +// alongside the concurrency test that first needed them because that file is +// //go:build !windows (it needs mkfifo to gate git), while nothing here is +// platform-specific — and a Windows `go vet` fails on any untagged test that +// reaches for a symbol defined only in the tagged one. + +func newMultiRepoStatusServer(t *testing.T) (*Server, []string) { + t.Helper() + taskRoot := t.TempDir() + repoNames := []string{"alpha", "beta"} + for _, repo := range repoNames { + newStatusTestRepo(t, taskRoot, repo) + } + log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error"}) + cfg := &config.InstanceConfig{WorkDir: taskRoot} + return NewServer(cfg, process.NewManager(cfg, log), nil, nil, log), repoNames +} + +func newStatusTestRepo(t *testing.T, taskRoot, name string) string { + t.Helper() + repoDir := filepath.Join(taskRoot, name) + if err := os.Mkdir(repoDir, 0o755); err != nil { + t.Fatalf("mkdir %s: %v", name, err) + } + runGitAPI(t, repoDir, "init", "--initial-branch=main") + runGitAPI(t, repoDir, "config", "user.email", "test@test.com") + runGitAPI(t, repoDir, "config", "user.name", "Test User") + writeFileAPI(t, repoDir, "README.md", name+"\n") + runGitAPI(t, repoDir, "add", ".") + runGitAPI(t, repoDir, "commit", "-m", "initial") + return repoDir +} + +func assertRepoNames(t *testing.T, got, want []string) { + t.Helper() + gotSet := make(map[string]bool, len(got)) + for _, repo := range got { + gotSet[repo] = true + } + for _, repo := range want { + if !gotSet[repo] { + t.Errorf("repositories %v missing %q", got, repo) + } + } +} + +func mapKeys[V any](values map[string]V) []string { + keys := make([]string, 0, len(values)) + for key := range values { + keys = append(keys, key) + } + return keys +} diff --git a/apps/backend/internal/agentctl/server/api/metrics_handler_test.go b/apps/backend/internal/agentctl/server/api/metrics_handler_test.go new file mode 100644 index 0000000000..2eadf47437 --- /dev/null +++ b/apps/backend/internal/agentctl/server/api/metrics_handler_test.go @@ -0,0 +1,93 @@ +package api + +import ( + "encoding/json" + "net/http" + "reflect" + "testing" + + "github.com/kandev/kandev/internal/system/metrics" +) + +// TestSplitMetrics covers the query-list parser. Blank entries have to be +// dropped rather than passed through, because an empty metric ID reaches the +// collector as an unknown metric. +func TestSplitMetrics(t *testing.T) { + cases := []struct { + name string + raw string + want []string + }{ + {"empty", "", nil}, + {"single", "cpu", []string{"cpu"}}, + {"several with spaces", " cpu , memory ,disk ", []string{"cpu", "memory", "disk"}}, + {"blank entries dropped", "cpu,,memory,", []string{"cpu", "memory"}}, + {"only separators", ",,,", []string{}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := splitMetrics(tc.raw) + if !reflect.DeepEqual(got, tc.want) { + t.Errorf("splitMetrics(%q) = %#v, want %#v", tc.raw, got, tc.want) + } + }) + } +} + +// TestHandleSystemMetrics_StampsExecutionIdentity asserts the snapshot is +// labelled as this executor before it leaves the handler. The dashboard merges +// host and executor snapshots into one list keyed by ID, so an unstamped +// snapshot would collide with the host's. +func TestHandleSystemMetrics_StampsExecutionIdentity(t *testing.T) { + srv := newTestServer(t) + + rec := serverGet(t, srv, "/api/v1/system/metrics") + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + var snapshot struct { + ID string `json:"id"` + Label string `json:"label"` + Kind string `json:"kind"` + Metrics []map[string]any `json:"metrics"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &snapshot); err != nil { + t.Fatalf("decode snapshot %q: %v", rec.Body.String(), err) + } + if snapshot.ID != "agentctl" { + t.Errorf("id = %q, want %q", snapshot.ID, "agentctl") + } + if snapshot.Label != "Execution" { + t.Errorf("label = %q, want %q", snapshot.Label, "Execution") + } + if snapshot.Kind != "execution" { + t.Errorf("kind = %q, want %q", snapshot.Kind, "execution") + } + if len(snapshot.Metrics) != len(metrics.DefaultSettings().Metrics) { + t.Errorf("sampled %d metrics, want the %d defaults", + len(snapshot.Metrics), len(metrics.DefaultSettings().Metrics)) + } +} + +// TestHandleSystemMetrics_HonoursRequestedMetrics pins the selection: asking +// for one metric must sample exactly that one, not the default set. +func TestHandleSystemMetrics_HonoursRequestedMetrics(t *testing.T) { + srv := newTestServer(t) + wanted := metrics.DefaultSettings().Metrics[0] + + rec := serverGet(t, srv, "/api/v1/system/metrics?metrics="+wanted) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + var snapshot struct { + Metrics []struct { + ID string `json:"id"` + } `json:"metrics"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &snapshot); err != nil { + t.Fatalf("decode snapshot %q: %v", rec.Body.String(), err) + } + if len(snapshot.Metrics) != 1 || snapshot.Metrics[0].ID != wanted { + t.Errorf("metrics = %+v, want exactly [%s]", snapshot.Metrics, wanted) + } +} diff --git a/apps/backend/internal/agentctl/server/api/port_listener_shim_unix_test.go b/apps/backend/internal/agentctl/server/api/port_listener_shim_unix_test.go new file mode 100644 index 0000000000..bc06f65423 --- /dev/null +++ b/apps/backend/internal/agentctl/server/api/port_listener_shim_unix_test.go @@ -0,0 +1,209 @@ +//go:build !windows + +package api + +import ( + "encoding/json" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" +) + +// installPortDetectorShim puts a fake `ss`/`lsof` on PATH so the detectors can +// be driven with fixed output. The real commands report whatever the host +// happens to be listening on, which is neither stable nor assertable. +func installPortDetectorShim(t *testing.T, name, stdout string, exitCode int) { + t.Helper() + binDir := t.TempDir() + script := "#!/bin/sh\n" + if stdout != "" { + script += "cat <<'KANDEV_EOF'\n" + stdout + "\nKANDEV_EOF\n" + } + script += "exit " + strconv.Itoa(exitCode) + "\n" + if err := os.WriteFile(filepath.Join(binDir, name), []byte(script), 0o755); err != nil { + t.Fatalf("write %s shim: %v", name, err) + } + t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH")) +} + +func portsByNumber(t *testing.T, ports []ListeningPort) map[int]ListeningPort { + t.Helper() + byPort := make(map[int]ListeningPort, len(ports)) + for _, port := range ports { + if _, dup := byPort[port.Port]; dup { + t.Errorf("port %d reported twice: %+v", port.Port, ports) + } + byPort[port.Port] = port + } + return byPort +} + +const ssShimOutput = `LISTEN 0 511 0.0.0.0:3000 0.0.0.0:* users:(("next-server (v1",pid=16186,fd=24)) +LISTEN 0 511 0.0.0.0:3000 0.0.0.0:* users:(("next-server (v1",pid=16187,fd=25)) +LISTEN 0 128 127.0.0.1:22 0.0.0.0:* users:(("sshd",pid=900,fd=3)) +LISTEN 0 4096 *:9000 *:* users:(("vite",pid=17000,fd=11)) +LISTEN 0 4096 127.0.0.1:5432 0.0.0.0:* +LISTEN 0 4096 +LISTEN 0 4096 garbage 0.0.0.0:* users:(("bogus",pid=1,fd=1))` + +// TestDetectFromSS_ParsesListeners covers every branch of the `ss` parser at +// once: process-name extraction, first-wins de-duplication, the privileged-port +// filter, wildcard-host normalisation, a row with no process column, and two +// malformed rows that must be skipped rather than crash the sweep. +func TestDetectFromSS_ParsesListeners(t *testing.T) { + installPortDetectorShim(t, "ss", ssShimOutput, 0) + + ports, err := detectFromSS() + if err != nil { + t.Fatalf("detectFromSS: %v", err) + } + byPort := portsByNumber(t, ports) + + if len(byPort) != 3 { + t.Fatalf("detected %d ports, want 3 (3000, 9000, 5432): %+v", len(byPort), ports) + } + if got := byPort[3000]; got.Process != "next-server (v1" || got.Address != "0.0.0.0" { + t.Errorf("port 3000 = %+v, want the quoted process name and 0.0.0.0", got) + } + if got := byPort[9000]; got.Address != defaultListenAddr || got.Process != "vite" { + t.Errorf("port 9000 = %+v, want %q normalised to %q", got, "*", defaultListenAddr) + } + if got := byPort[5432]; got.Address != "127.0.0.1" || got.Process != "" { + t.Errorf("port 5432 = %+v, want a loopback listener with no process name", got) + } + if _, listed := byPort[22]; listed { + t.Errorf("port 22 was reported; ports below 1024 are filtered out") + } +} + +// TestDetectFromSS_ReportsCommandFailure covers the error branch, which is what +// pushes detectListeningPorts onto its /proc/net/tcp fallback. +func TestDetectFromSS_ReportsCommandFailure(t *testing.T) { + installPortDetectorShim(t, "ss", "", 1) + + ports, err := detectFromSS() + if err == nil { + t.Fatalf("detectFromSS succeeded with a failing command: %+v", ports) + } + if !strings.Contains(err.Error(), "ss failed") { + t.Errorf("error = %q, want it to name the failed command", err) + } +} + +const lsofShimOutput = `cnext-server +n*:3000 +n127.0.0.1:3000 +csshd +n127.0.0.1:22 +cvite +n[::1]:9000 +nnot-an-address` + +// TestDetectFromLsof_ParsesListeners covers the non-Linux fallback parser: the +// `c` record carries the process name for every `n` record that follows it, and +// the same filtering and de-duplication rules apply as for `ss` (port 3000 is +// bound on two addresses and must be reported once, keeping the first). +func TestDetectFromLsof_ParsesListeners(t *testing.T) { + installPortDetectorShim(t, "lsof", lsofShimOutput, 0) + + ports, err := detectFromLsof() + if err != nil { + t.Fatalf("detectFromLsof: %v", err) + } + byPort := portsByNumber(t, ports) + + if len(byPort) != 2 { + t.Fatalf("detected %d ports, want 2 (3000, 9000): %+v", len(byPort), ports) + } + if got := byPort[3000]; got.Process != "next-server" { + t.Errorf("port 3000 = %+v, want the preceding `c` record's process name", got) + } + if got := byPort[9000]; got.Process != "vite" { + t.Errorf("port 9000 = %+v, want the process name to follow the newest `c` record", got) + } + if _, listed := byPort[22]; listed { + t.Errorf("port 22 was reported; ports below 1024 are filtered out") + } +} + +// TestDetectFromLsof_ReportsCommandFailure covers the last-resort error, which +// is the only way handleListPorts can answer 500. +func TestDetectFromLsof_ReportsCommandFailure(t *testing.T) { + installPortDetectorShim(t, "lsof", "", 3) + + if _, err := detectFromLsof(); err == nil || !strings.Contains(err.Error(), "lsof failed") { + t.Errorf("error = %v, want an lsof failure", err) + } +} + +// TestDetectFromProcNet_FindsRealListener covers the container fallback against +// the kernel's own table. A socket this test just opened has to show up, which +// is the one assertion that proves the hex parsing, the LISTEN-state filter and +// the file walk all agree with what /proc/net/tcp actually contains. +func TestDetectFromProcNet_FindsRealListener(t *testing.T) { + if runtime.GOOS != "linux" { + t.Skip("/proc/net/tcp is Linux-only") + } + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + t.Cleanup(func() { _ = listener.Close() }) + _, portStr, err := net.SplitHostPort(listener.Addr().String()) + if err != nil { + t.Fatalf("split listener address: %v", err) + } + want, err := strconv.Atoi(portStr) + if err != nil { + t.Fatalf("parse listener port: %v", err) + } + + ports, err := detectFromProcNet() + if err != nil { + t.Fatalf("detectFromProcNet: %v", err) + } + byPort := portsByNumber(t, ports) + if _, ok := byPort[want]; !ok { + t.Fatalf("port %d is missing from %+v", want, ports) + } + for _, port := range ports { + if port.Port < 1024 { + t.Errorf("port %d is below the 1024 floor: %+v", port.Port, port) + } + } +} + +// TestHandleListPorts_ReturnsDetectedPorts drives the HTTP endpoint end to end +// with both detectors shimmed, so the assertion holds whichever one the host +// platform selects. +func TestHandleListPorts_ReturnsDetectedPorts(t *testing.T) { + installPortDetectorShim(t, "ss", ssShimOutput, 0) + installPortDetectorShim(t, "lsof", lsofShimOutput, 0) + srv := newTestServer(t) + + rec := httptest.NewRecorder() + srv.Router().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/v1/ports", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200 (body %s)", rec.Code, rec.Body.String()) + } + + var body struct { + Ports []ListeningPort `json:"ports"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode ports: %v", err) + } + byPort := portsByNumber(t, body.Ports) + if _, ok := byPort[3000]; !ok { + t.Errorf("ports = %+v, want the shimmed listener on 3000", body.Ports) + } + if _, ok := byPort[22]; ok { + t.Errorf("ports = %+v, want privileged ports filtered out", body.Ports) + } +} diff --git a/apps/backend/internal/agentctl/server/api/port_listener_test.go b/apps/backend/internal/agentctl/server/api/port_listener_test.go new file mode 100644 index 0000000000..29708912d1 --- /dev/null +++ b/apps/backend/internal/agentctl/server/api/port_listener_test.go @@ -0,0 +1,96 @@ +package api + +import ( + "testing" +) + +// TestParseProcNetLine covers the /proc/net/tcp row parser, which is the +// fallback path used inside minimal containers that ship no `ss`. +func TestParseProcNetLine(t *testing.T) { + cases := []struct { + name string + line string + wantPort int + wantAddr string + wantOK bool + }{ + { + name: "listening ipv4 socket", + line: " 0: 0100007F:1F90 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 12345 1 0000 100 0 0 10 0", + wantPort: 8080, + wantAddr: "127.0.0.1", + wantOK: true, + }, + { + name: "all interfaces", + line: " 1: 00000000:0BB8 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 12346 1 0000 100 0 0 10 0", + wantPort: 3000, + wantAddr: "0.0.0.0", + wantOK: true, + }, + { + name: "established socket is not a listener", + line: " 2: 0100007F:1F90 0100007F:9C40 01 00000000:00000000 00:00000000 00000000 1000 0 12347 1 0000 100 0 0 10 0", + wantPort: 0, + wantOK: false, + }, + { + name: "truncated row", + line: " 3: 0100007F:1F90 00000000:0000", + wantOK: false, + }, + { + name: "local address without a port", + line: " 4: 0100007F 00000000:0000 0A 00000000:00000000 00:00000000 00000000", + wantOK: false, + }, + { + name: "non-hex port", + line: " 5: 0100007F:ZZZZ 00000000:0000 0A 00000000:00000000 00:00000000 00000000", + wantOK: false, + }, + { + name: "blank line", + line: "", + wantOK: false, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + port, addr, ok := parseProcNetLine(tc.line) + if ok != tc.wantOK { + t.Fatalf("ok = %v, want %v (port %d, addr %q)", ok, tc.wantOK, port, addr) + } + if !tc.wantOK { + return + } + if port != tc.wantPort { + t.Errorf("port = %d, want %d", port, tc.wantPort) + } + if addr != tc.wantAddr { + t.Errorf("address = %q, want %q", addr, tc.wantAddr) + } + }) + } +} + +// TestParseHexIP pins the little-endian byte order /proc/net/tcp uses for IPv4. +// Reading it big-endian yields a plausible-looking but wrong address (1.0.0.127 +// instead of 127.0.0.1), which no smoke test would catch. +func TestParseHexIP(t *testing.T) { + cases := map[string]string{ + "0100007F": "127.0.0.1", + "00000000": "0.0.0.0", + "0201A8C0": "192.168.1.2", + "00000000000000000000000000000000": defaultListenAddr, // IPv6 collapses to all-interfaces + "0000000000000000FFFF00000100007F": defaultListenAddr, // IPv4-mapped IPv6 + "ZZZZ": defaultListenAddr, // undecodable + "0100": defaultListenAddr, // too short for an address + "": defaultListenAddr, + } + for input, want := range cases { + if got := parseHexIP(input); got != want { + t.Errorf("parseHexIP(%q) = %q, want %q", input, got, want) + } + } +} diff --git a/apps/backend/internal/agentctl/server/api/processes_test.go b/apps/backend/internal/agentctl/server/api/processes_test.go new file mode 100644 index 0000000000..a637528519 --- /dev/null +++ b/apps/backend/internal/agentctl/server/api/processes_test.go @@ -0,0 +1,391 @@ +package api + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/kandev/kandev/internal/agentctl/server/process" + "github.com/kandev/kandev/internal/agentctl/types" +) + +func processRequest(t *testing.T, srv *Server, method, path string, body any) *httptest.ResponseRecorder { + t.Helper() + var payload []byte + switch v := body.(type) { + case nil: + case string: + payload = []byte(v) + default: + encoded, err := json.Marshal(v) + if err != nil { + t.Fatalf("marshal body: %v", err) + } + payload = encoded + } + req := httptest.NewRequest(method, path, bytes.NewReader(payload)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + srv.Router().ServeHTTP(rec, req) + return rec +} + +func decodeProcessError(t *testing.T, rec *httptest.ResponseRecorder) string { + t.Helper() + var body struct { + Error string `json:"error"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode error body %q: %v", rec.Body.String(), err) + } + return body.Error +} + +// awaitProcessOutput polls the get-process endpoint until the buffered output +// contains marker, and returns the snapshot that carried it. The process must +// still be running: a finished process is reaped out of the runner's map (see +// ProcessRunner.ensureProcessGroupReaped), so its output is only observable +// while it is alive. +func awaitProcessOutput(t *testing.T, srv *Server, id, marker string) process.ProcessInfo { + t.Helper() + deadline := time.Now().Add(15 * time.Second) + var last process.ProcessInfo + for time.Now().Before(deadline) { + rec := processRequest(t, srv, http.MethodGet, "/api/v1/processes/"+id+"?include_output=true", nil) + if rec.Code != http.StatusOK { + t.Fatalf("get process = %d, want 200 — the process was retired before its output could be read (body %s)", + rec.Code, rec.Body.String()) + } + if err := json.Unmarshal(rec.Body.Bytes(), &last); err != nil { + t.Fatalf("decode process info: %v", err) + } + if strings.Contains(processOutputText(last), marker) { + return last + } + time.Sleep(10 * time.Millisecond) + } + t.Fatalf("process %s never emitted %q (last snapshot %+v)", id, marker, last) + return last +} + +// awaitProcessRetired polls until the process is gone from the runner. Exiting +// and being reaped are one step as far as the HTTP surface is concerned: there +// is no window in which a finished process is still fetchable, so this is the +// only terminal state a caller can observe over REST. +func awaitProcessRetired(t *testing.T, srv *Server, id string) { + t.Helper() + deadline := time.Now().Add(15 * time.Second) + for time.Now().Before(deadline) { + if rec := processRequest(t, srv, http.MethodGet, "/api/v1/processes/"+id, nil); rec.Code == http.StatusNotFound { + return + } + time.Sleep(10 * time.Millisecond) + } + t.Fatalf("process %s was still fetchable after it should have exited and been reaped", id) +} + +func processOutputText(info process.ProcessInfo) string { + var builder strings.Builder + for _, chunk := range info.Output { + builder.WriteString(chunk.Data) + } + return builder.String() +} + +// TestHandleStartProcess_Rejections covers each 400: an unparseable body gets a +// fixed message (the handler deliberately does not echo the parse error), while +// the runner's own required-field errors are forwarded verbatim. +func TestHandleStartProcess_Rejections(t *testing.T) { + srv := newTestServer(t) + + cases := []struct { + name string + body any + wantError string + }{ + {"malformed body", "{not json", "invalid request body"}, + {"missing session id", process.StartProcessRequest{Command: "true"}, "session_id is required"}, + {"missing command", process.StartProcessRequest{SessionID: "s1"}, "command is required"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := processRequest(t, srv, http.MethodPost, "/api/v1/processes/start", tc.body) + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 (body %s)", rec.Code, rec.Body.String()) + } + var body startProcessResponse + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode response: %v", err) + } + if body.Process != nil { + t.Errorf("a process was returned alongside the refusal: %+v", body.Process) + } + if body.Error != tc.wantError { + t.Errorf("error = %q, want %q", body.Error, tc.wantError) + } + }) + } +} + +// TestProcessLifecycle_StartListGetCapturesOutput drives a real command through +// every read endpoint: the start response, the session-scoped list, and the +// per-process fetch with buffered output. Asserting the captured stdout is what +// proves the output plumbing is wired, not just the status field. +// +// The command prints and then blocks. A command that exits immediately cannot be +// read back at all — the runner reaps a finished process out of its map, so the +// fetch races the exit and answers 404 as soon as the machine is quick enough +// (which is exactly how this test first failed in CI but not locally). +func TestProcessLifecycle_StartListGetCapturesOutput(t *testing.T) { + srv := newTestServer(t) + + start := processRequest(t, srv, http.MethodPost, "/api/v1/processes/start", process.StartProcessRequest{ + SessionID: "session-a", + Kind: types.ProcessKindCustom, + ScriptName: "marker", + Command: "printf 'kandev-marker\\n'; sleep 120", + }) + if start.Code != http.StatusOK { + t.Fatalf("start status = %d (body %s)", start.Code, start.Body.String()) + } + var started startProcessResponse + if err := json.Unmarshal(start.Body.Bytes(), &started); err != nil { + t.Fatalf("decode start response: %v", err) + } + if started.Process == nil || started.Process.ID == "" { + t.Fatalf("start response carries no process: %s", start.Body.String()) + } + if started.Process.SessionID != "session-a" || started.Process.ScriptName != "marker" { + t.Errorf("process = %+v, want the requested session and script name", started.Process) + } + stopProcessOnCleanup(t, srv, started.Process.ID) + + listed := processRequest(t, srv, http.MethodGet, "/api/v1/processes?session_id=session-a", nil) + if listed.Code != http.StatusOK { + t.Fatalf("list status = %d (body %s)", listed.Code, listed.Body.String()) + } + var infos []process.ProcessInfo + if err := json.Unmarshal(listed.Body.Bytes(), &infos); err != nil { + t.Fatalf("decode list: %v", err) + } + if len(infos) != 1 || infos[0].ID != started.Process.ID { + t.Errorf("list for session-a = %+v, want exactly the started process", infos) + } + + other := processRequest(t, srv, http.MethodGet, "/api/v1/processes?session_id=session-b", nil) + var otherInfos []process.ProcessInfo + if err := json.Unmarshal(other.Body.Bytes(), &otherInfos); err != nil { + t.Fatalf("decode other list: %v", err) + } + if len(otherInfos) != 0 { + t.Errorf("list for session-b = %+v, want no processes; the filter is not applied", otherInfos) + } + + live := awaitProcessOutput(t, srv, started.Process.ID, "kandev-marker") + if live.Status != types.ProcessStatusRunning { + t.Errorf("status = %q, want %q while the command is still blocked", live.Status, types.ProcessStatusRunning) + } + if live.ExitCode != nil { + t.Errorf("exit_code = %v, want nil for a running process", *live.ExitCode) + } + if live.Command != "printf 'kandev-marker\\n'; sleep 120" { + t.Errorf("command = %q, want the command as submitted", live.Command) + } +} + +// TestHandleGetProcess_OmitsOutputByDefault pins the include_output query +// parameter. Buffered output can be megabytes, so the list-facing fetch must +// not carry it unless asked — and must carry it when it is. +func TestHandleGetProcess_OmitsOutputByDefault(t *testing.T) { + srv := newTestServer(t) + id := startTestProcess(t, srv, "session-c", "printf 'kandev-marker\\n'; sleep 120") + awaitProcessOutput(t, srv, id, "kandev-marker") + + rec := processRequest(t, srv, http.MethodGet, "/api/v1/processes/"+id, nil) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + var info process.ProcessInfo + if err := json.Unmarshal(rec.Body.Bytes(), &info); err != nil { + t.Fatalf("decode process info: %v", err) + } + if len(info.Output) != 0 { + t.Errorf("output = %+v, want none without include_output=true", info.Output) + } + if info.ID != id { + t.Errorf("id = %q, want %q", info.ID, id) + } +} + +// TestProcessLifecycle_ExitedProcessIsRetired pins the reaping contract that +// makes the two tests above use a blocking command: once a process exits, the +// runner removes it, so REST has no "exited" state to report — the process +// simply stops existing. Anything that needs the exit code must observe the +// `process_status` event instead. +func TestProcessLifecycle_ExitedProcessIsRetired(t *testing.T) { + srv := newTestServer(t) + id := startTestProcess(t, srv, "session-e", "printf 'done\\n'") + + awaitProcessRetired(t, srv, id) + + listed := processRequest(t, srv, http.MethodGet, "/api/v1/processes?session_id=session-e", nil) + var remaining []process.ProcessInfo + if err := json.Unmarshal(listed.Body.Bytes(), &remaining); err != nil { + t.Fatalf("decode list: %v", err) + } + if len(remaining) != 0 { + t.Errorf("list after exit = %+v, want it emptied", remaining) + } +} + +// TestHandleGetProcess_UnknownIDIs404 covers the miss branch. +func TestHandleGetProcess_UnknownIDIs404(t *testing.T) { + srv := newTestServer(t) + + rec := processRequest(t, srv, http.MethodGet, "/api/v1/processes/no-such-process", nil) + if rec.Code != http.StatusNotFound { + t.Fatalf("status = %d, want 404 (body %s)", rec.Code, rec.Body.String()) + } + if got := decodeProcessError(t, rec); got != "process not found" { + t.Errorf("error = %q, want %q", got, "process not found") + } +} + +// TestHandleStopProcess_Rejections covers the two 400 branches ahead of the +// runner call. +func TestHandleStopProcess_Rejections(t *testing.T) { + srv := newTestServer(t) + + cases := []struct { + name string + body any + wantError string + }{ + {"malformed body", "{not json", "invalid request body"}, + {"missing process id", process.StopProcessRequest{}, "process_id is required"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := processRequest(t, srv, http.MethodPost, "/api/v1/processes/stop", tc.body) + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 (body %s)", rec.Code, rec.Body.String()) + } + var body stopProcessResponse + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode response: %v", err) + } + if body.Success { + t.Errorf("success = true, want false") + } + if body.Error != tc.wantError { + t.Errorf("error = %q, want %q", body.Error, tc.wantError) + } + }) + } +} + +// TestHandleStopProcess_UnknownIDIsIdempotentSuccess pins the deliberate +// asymmetry with the fetch endpoint: stopping something already gone is the +// caller's desired end state, so it answers success rather than 404. The UI +// stop button relies on that to stay usable after a process exits on its own. +func TestHandleStopProcess_UnknownIDIsIdempotentSuccess(t *testing.T) { + srv := newTestServer(t) + + rec := processRequest(t, srv, http.MethodPost, "/api/v1/processes/stop", process.StopProcessRequest{ + ProcessID: "no-such-process", + }) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200 (body %s)", rec.Code, rec.Body.String()) + } + var body stopProcessResponse + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode response: %v", err) + } + if !body.Success || body.Error != "" { + t.Errorf("response = %+v, want an unqualified success", body) + } +} + +// TestHandleStopProcess_RetiresRunningProcess asserts the stop reaches a +// long-running command: the call returns success and the process is retired +// from both the per-session list and the per-id fetch. A `sleep 120` that was +// merely marked stopped would still be listed. +func TestHandleStopProcess_RetiresRunningProcess(t *testing.T) { + srv := newTestServer(t) + id := startTestProcess(t, srv, "session-d", "sleep 120") + + listed := processRequest(t, srv, http.MethodGet, "/api/v1/processes?session_id=session-d", nil) + var before []process.ProcessInfo + if err := json.Unmarshal(listed.Body.Bytes(), &before); err != nil { + t.Fatalf("decode list: %v", err) + } + if len(before) != 1 { + t.Fatalf("list before stop = %+v, want the running process", before) + } + + rec := processRequest(t, srv, http.MethodPost, "/api/v1/processes/stop", process.StopProcessRequest{ProcessID: id}) + if rec.Code != http.StatusOK { + t.Fatalf("stop status = %d (body %s)", rec.Code, rec.Body.String()) + } + var body stopProcessResponse + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode stop response: %v", err) + } + if !body.Success || body.Error != "" { + t.Fatalf("stop reported failure: %+v", body) + } + + after := processRequest(t, srv, http.MethodGet, "/api/v1/processes?session_id=session-d", nil) + var remaining []process.ProcessInfo + if err := json.Unmarshal(after.Body.Bytes(), &remaining); err != nil { + t.Fatalf("decode list: %v", err) + } + if len(remaining) != 0 { + t.Errorf("list after stop = %+v, want it emptied", remaining) + } + if got := processRequest(t, srv, http.MethodGet, "/api/v1/processes/"+id, nil); got.Code != http.StatusNotFound { + t.Errorf("get after stop status = %d, want 404 (body %s)", got.Code, got.Body.String()) + } +} + +func startTestProcess(t *testing.T, srv *Server, sessionID, command string) string { + t.Helper() + rec := processRequest(t, srv, http.MethodPost, "/api/v1/processes/start", process.StartProcessRequest{ + SessionID: sessionID, + Kind: types.ProcessKindCustom, + Command: command, + }) + if rec.Code != http.StatusOK { + t.Fatalf("start status = %d (body %s)", rec.Code, rec.Body.String()) + } + var started startProcessResponse + if err := json.Unmarshal(rec.Body.Bytes(), &started); err != nil { + t.Fatalf("decode start response: %v", err) + } + if started.Process == nil { + t.Fatalf("start response carries no process: %s", rec.Body.String()) + } + stopProcessOnCleanup(t, srv, started.Process.ID) + return started.Process.ID +} + +// stopProcessOnCleanup reaps the subprocess when the test ends, including on an +// early t.Fatal. Several of these tests deliberately start a command that blocks +// for two minutes; without this the process — and the runner goroutines waiting +// on it — outlive the test and trip goleak. Stopping an already-retired process +// is a no-op success, so this is safe for every caller. +func stopProcessOnCleanup(t *testing.T, srv *Server, id string) { + t.Helper() + t.Cleanup(func() { + rec := processRequest(t, srv, http.MethodPost, "/api/v1/processes/stop", process.StopProcessRequest{ + ProcessID: id, + }) + if rec.Code != http.StatusOK { + t.Errorf("cleanup stop of %s = %d (body %s)", id, rec.Code, rec.Body.String()) + } + }) +} diff --git a/apps/backend/internal/agentctl/server/api/server_handlers_test.go b/apps/backend/internal/agentctl/server/api/server_handlers_test.go new file mode 100644 index 0000000000..fb0afcd908 --- /dev/null +++ b/apps/backend/internal/agentctl/server/api/server_handlers_test.go @@ -0,0 +1,308 @@ +package api + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/kandev/kandev/internal/agentctl/server/config" + "github.com/kandev/kandev/internal/agentctl/server/process" +) + +func serverGet(t *testing.T, srv *Server, path string) *httptest.ResponseRecorder { + t.Helper() + rec := httptest.NewRecorder() + srv.Router().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil)) + return rec +} + +func serverPost(t *testing.T, srv *Server, path string) *httptest.ResponseRecorder { + t.Helper() + rec := httptest.NewRecorder() + srv.Router().ServeHTTP(rec, httptest.NewRequest(http.MethodPost, path, strings.NewReader("{}"))) + return rec +} + +// TestHandleHealth_ReportsOKWithTimestamp pins the liveness probe. It is the +// one route exempted from bearer auth, so an executor's readiness check depends +// on both the fixed status string and a parseable RFC3339 timestamp. +func TestHandleHealth_ReportsOKWithTimestamp(t *testing.T) { + srv := newTestServer(t) + + rec := serverGet(t, srv, "/health") + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + var body HealthResponse + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode health: %v", err) + } + if body.Status != "ok" { + t.Errorf("status = %q, want %q", body.Status, "ok") + } + if _, err := time.Parse(time.RFC3339, body.Timestamp); err != nil { + t.Errorf("timestamp %q is not RFC3339: %v", body.Timestamp, err) + } +} + +// TestHandleInfo_EchoesInstanceConfig asserts the endpoint reports this +// instance's own configuration. The backend uses it to confirm it is talking to +// the agentctl it just launched, so a hardcoded or stale value is a real bug. +func TestHandleInfo_EchoesInstanceConfig(t *testing.T) { + log := newTestLogger() + workDir := t.TempDir() + cfg := &config.InstanceConfig{Port: 45321, WorkDir: workDir, AgentCommand: "claude-agent-acp --stdio"} + srv := NewServer(cfg, process.NewManager(cfg, log), nil, nil, log) + + rec := serverGet(t, srv, "/api/v1/info") + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + var body InfoResponse + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode info: %v", err) + } + if body.WorkDir != workDir { + t.Errorf("work_dir = %q, want %q", body.WorkDir, workDir) + } + if body.Port != 45321 { + t.Errorf("port = %d, want %d", body.Port, 45321) + } + if body.AgentCommand != "claude-agent-acp --stdio" { + t.Errorf("agent_command = %q, want the configured command", body.AgentCommand) + } + if body.Version == "" { + t.Errorf("version is empty") + } +} + +// TestHandleStatus_ReportsIdleAgent covers the status endpoint before anything +// has been started: the agent status has to be a real value from the manager +// and the process info map must be present rather than null. +func TestHandleStatus_ReportsIdleAgent(t *testing.T) { + srv := newTestServer(t) + + rec := serverGet(t, srv, "/api/v1/status") + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + var body StatusResponse + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode status: %v", err) + } + if body.AgentStatus != string(srv.procMgr.Status()) { + t.Errorf("agent_status = %q, want the manager's %q", body.AgentStatus, srv.procMgr.Status()) + } + if body.ProcessInfo == nil { + t.Errorf("process_info is null; the field must always be an object") + } +} + +// TestHandleStart_WithoutConfiguredCommandIs500 covers the failure branch of +// the start endpoint. Nothing has called /agent/configure, so the manager has +// no command to launch and the reason must reach the caller. +func TestHandleStart_WithoutConfiguredCommandIs500(t *testing.T) { + srv := newTestServer(t) + + rec := serverPost(t, srv, "/api/v1/start") + if rec.Code != http.StatusInternalServerError { + t.Fatalf("status = %d, want 500 (body %s)", rec.Code, rec.Body.String()) + } + var body StartResponse + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode start response: %v", err) + } + if body.Success { + t.Errorf("success = true, want false") + } + if body.Error == "" { + t.Errorf("error is empty; the launch failure must reach the caller") + } +} + +// TestHandleStop_WhenNothingRunning asserts stopping an idle instance is a +// success, not an error — the backend calls it unconditionally during teardown. +func TestHandleStop_WhenNothingRunning(t *testing.T) { + srv := newTestServer(t) + + rec := serverPost(t, srv, "/api/v1/stop") + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200 (body %s)", rec.Code, rec.Body.String()) + } + var body StopResponse + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode stop response: %v", err) + } + if !body.Success || body.Message != "agent stopped" { + t.Errorf("stop response = %+v, want an unqualified success", body) + } +} + +// TestShellEndpoints_WithoutShell pins the two different no-shell answers. +// Status reports availability inside a 200 so the UI can render a disabled +// terminal pane, while the buffer read is a 503 because there is nothing to +// return at all. +func TestShellEndpoints_WithoutShell(t *testing.T) { + srv := newTestServer(t) + + status := serverGet(t, srv, "/api/v1/shell/status") + if status.Code != http.StatusOK { + t.Fatalf("shell status = %d, want 200 (body %s)", status.Code, status.Body.String()) + } + var statusBody ShellStatusResponse + if err := json.Unmarshal(status.Body.Bytes(), &statusBody); err != nil { + t.Fatalf("decode shell status: %v", err) + } + if statusBody.Available { + t.Errorf("available = true with no shell configured") + } + if statusBody.Error != "shell not available" { + t.Errorf("error = %q, want %q", statusBody.Error, "shell not available") + } + + buffer := serverGet(t, srv, "/api/v1/shell/buffer") + if buffer.Code != http.StatusServiceUnavailable { + t.Fatalf("shell buffer = %d, want 503 (body %s)", buffer.Code, buffer.Body.String()) + } + var bufferBody map[string]string + if err := json.Unmarshal(buffer.Body.Bytes(), &bufferBody); err != nil { + t.Fatalf("decode shell buffer: %v", err) + } + if bufferBody["error"] != "shell not available" { + t.Errorf("error = %q, want %q", bufferBody["error"], "shell not available") + } +} + +// TestShellEndpoints_AfterExplicitStart covers the passthrough-mode path: the +// shell is started without the agent, and both read endpoints then describe a +// live PTY. Asserting the pid and shell path is what distinguishes a genuinely +// spawned process from a status struct that merely says Running. +func TestShellEndpoints_AfterExplicitStart(t *testing.T) { + log := newTestLogger() + workDir := t.TempDir() + cfg := &config.InstanceConfig{WorkDir: workDir, ShellEnabled: true} + procMgr := process.NewManager(cfg, log) + srv := NewServer(cfg, procMgr, nil, nil, log) + t.Cleanup(func() { + if shell := procMgr.Shell(); shell != nil { + if err := shell.Stop(); err != nil { + t.Errorf("stop shell: %v", err) + } + } + }) + + start := serverPost(t, srv, "/api/v1/shell/start") + if start.Code != http.StatusOK { + t.Fatalf("shell start = %d (body %s)", start.Code, start.Body.String()) + } + var startBody map[string]string + if err := json.Unmarshal(start.Body.Bytes(), &startBody); err != nil { + t.Fatalf("decode shell start: %v", err) + } + if startBody["status"] != "shell started" { + t.Errorf("status = %q, want %q", startBody["status"], "shell started") + } + + status := serverGet(t, srv, "/api/v1/shell/status") + if status.Code != http.StatusOK { + t.Fatalf("shell status = %d (body %s)", status.Code, status.Body.String()) + } + var statusBody ShellStatusResponse + if err := json.Unmarshal(status.Body.Bytes(), &statusBody); err != nil { + t.Fatalf("decode shell status: %v", err) + } + if !statusBody.Available || !statusBody.Running { + t.Fatalf("shell status = %+v, want an available, running shell", statusBody) + } + if statusBody.Pid <= 0 { + t.Errorf("pid = %d, want a real process id", statusBody.Pid) + } + if statusBody.Shell == "" { + t.Errorf("shell is empty; the status must name the spawned program") + } + if statusBody.Cwd != workDir { + t.Errorf("cwd = %q, want the workspace root %q", statusBody.Cwd, workDir) + } + + // Drive a marker through the PTY and read it back, so the buffer assertion + // is about captured output rather than merely a 200 with valid JSON. The + // shell echoes its input, so this does not depend on a command running. + const marker = "kandev-shell-marker" + if _, err := procMgr.Shell().Write([]byte("echo " + marker + "\r")); err != nil { + t.Fatalf("write to shell: %v", err) + } + buffered := awaitShellBuffer(t, srv, marker) + if !strings.Contains(buffered, marker) { + t.Errorf("shell buffer = %q, want it to contain %q", buffered, marker) + } +} + +// awaitShellBuffer polls the buffer endpoint until it carries marker. The PTY +// delivers its prompt and the echoed keystrokes asynchronously, so the marker — +// not a fixed wait — is the synchronisation point; the deadline only detects +// failure. +func awaitShellBuffer(t *testing.T, srv *Server, marker string) string { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + var last string + for time.Now().Before(deadline) { + rec := serverGet(t, srv, "/api/v1/shell/buffer") + if rec.Code != http.StatusOK { + t.Fatalf("shell buffer = %d, want 200 (body %s)", rec.Code, rec.Body.String()) + } + var body ShellBufferResponse + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode shell buffer: %v", err) + } + last = body.Data + if strings.Contains(last, marker) { + return last + } + time.Sleep(10 * time.Millisecond) + } + return last +} + +// TestPprofRoutes_GatedOnEnv pins the debug surface behind its environment +// switch. pprof exposes goroutine stacks and heap contents, so registering it +// unconditionally would leak them from every shipped executor. +func TestPprofRoutes_GatedOnEnv(t *testing.T) { + t.Run("disabled by default", func(t *testing.T) { + t.Setenv("KANDEV_DEBUG_PPROF_ENABLED", "") + srv := newTestServer(t) + + for _, path := range []string{"/debug/pprof/", "/debug/pprof/goroutine", "/api/v1/debug/memory"} { + if rec := serverGet(t, srv, path); rec.Code != http.StatusNotFound { + t.Errorf("%s status = %d, want 404 while pprof is disabled", path, rec.Code) + } + } + }) + + t.Run("enabled by env", func(t *testing.T) { + t.Setenv("KANDEV_DEBUG_PPROF_ENABLED", "true") + srv := newTestServer(t) + + for _, path := range []string{"/debug/pprof/", "/debug/pprof/goroutine?debug=1", "/debug/pprof/cmdline"} { + if rec := serverGet(t, srv, path); rec.Code != http.StatusOK { + t.Errorf("%s status = %d, want 200 while pprof is enabled", path, rec.Code) + } + } + + rec := serverGet(t, srv, "/api/v1/debug/memory") + if rec.Code != http.StatusOK { + t.Fatalf("memory status = %d (body %s)", rec.Code, rec.Body.String()) + } + var memory map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &memory); err != nil { + t.Fatalf("decode memory stats: %v", err) + } + for _, key := range []string{"heap_alloc_mb", "heap_objects", "goroutines", "num_gc", "sys_mb"} { + if _, ok := memory[key]; !ok { + t.Errorf("memory stats are missing %q: %v", key, memory) + } + } + }) +} diff --git a/apps/backend/internal/agentctl/server/api/shell_terminal_test.go b/apps/backend/internal/agentctl/server/api/shell_terminal_test.go new file mode 100644 index 0000000000..9c1682433e --- /dev/null +++ b/apps/backend/internal/agentctl/server/api/shell_terminal_test.go @@ -0,0 +1,207 @@ +package api + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gorilla/websocket" +) + +func shellTerminalRequest(t *testing.T, srv *Server, method, path string, body any) *httptest.ResponseRecorder { + t.Helper() + var payload []byte + switch v := body.(type) { + case nil: + case string: + payload = []byte(v) + default: + encoded, err := json.Marshal(v) + if err != nil { + t.Fatalf("marshal body: %v", err) + } + payload = encoded + } + req := httptest.NewRequest(method, path, bytes.NewReader(payload)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + srv.Router().ServeHTTP(rec, req) + return rec +} + +func decodeShellTerminalBody(t *testing.T, rec *httptest.ResponseRecorder) map[string]string { + t.Helper() + body := map[string]string{} + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode %q: %v", rec.Body.String(), err) + } + return body +} + +// TestHandleShellTerminalStart_Rejections covers both guards ahead of the PTY +// spawn. A blank terminal_id would otherwise register a session nothing can +// address again. +func TestHandleShellTerminalStart_Rejections(t *testing.T) { + srv := newTestServer(t) + + cases := []struct { + name string + body any + wantError string + }{ + {"malformed body", "{not json", "invalid request: "}, + {"missing terminal id", shellTerminalStartRequest{Cols: 80, Rows: 24}, "terminal_id is required"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := shellTerminalRequest(t, srv, http.MethodPost, "/api/v1/shell/terminal/start", tc.body) + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 (body %s)", rec.Code, rec.Body.String()) + } + if got := decodeShellTerminalBody(t, rec)["error"]; !strings.Contains(got, tc.wantError) { + t.Errorf("error = %q, want it to contain %q", got, tc.wantError) + } + }) + } +} + +// TestShellTerminalEndpoints_UnknownTerminal pins what each endpoint does for a +// terminal that was never started. The asymmetry is deliberate and load-bearing +// for the UI: reads 404 so a stale tab can detect its terminal is gone, while +// stop succeeds so closing that tab is not an error. +func TestShellTerminalEndpoints_UnknownTerminal(t *testing.T) { + srv := newTestServer(t) + + buffer := shellTerminalRequest(t, srv, http.MethodGet, "/api/v1/shell/terminal/ghost/buffer", nil) + if buffer.Code != http.StatusNotFound { + t.Errorf("buffer status = %d, want 404 (body %s)", buffer.Code, buffer.Body.String()) + } + if got := decodeShellTerminalBody(t, buffer)["error"]; !strings.Contains(got, "not found") { + t.Errorf("buffer error = %q, want a not-found report", got) + } + + stream := shellTerminalRequest(t, srv, http.MethodGet, "/api/v1/shell/terminal/ghost/stream", nil) + if stream.Code != http.StatusNotFound { + t.Errorf("stream status = %d, want 404 (body %s)", stream.Code, stream.Body.String()) + } + if got := decodeShellTerminalBody(t, stream)["error"]; got != "terminal not found" { + t.Errorf("stream error = %q, want %q", got, "terminal not found") + } + + stop := shellTerminalRequest(t, srv, http.MethodDelete, "/api/v1/shell/terminal/ghost", nil) + if stop.Code != http.StatusOK { + t.Fatalf("stop status = %d, want 200 (body %s)", stop.Code, stop.Body.String()) + } + if got := decodeShellTerminalBody(t, stop); got["status"] != "stopped" || got["terminal_id"] != "ghost" { + t.Errorf("stop body = %+v, want a stopped acknowledgement for `ghost`", got) + } +} + +// TestShellTerminalLifecycle drives a real PTY session end to end: start, +// stream input over the binary WebSocket protocol, observe it echoed back, +// resize through the 0x01-prefixed control frame, read the replayed buffer over +// HTTP, then stop. The echo is the only observation that proves the socket +// bytes reach the PTY rather than being swallowed by the read loop. +func TestShellTerminalLifecycle(t *testing.T) { + srv := newTestServer(t) + const terminalID = "term-1" + + start := shellTerminalRequest(t, srv, http.MethodPost, "/api/v1/shell/terminal/start", shellTerminalStartRequest{ + TerminalID: terminalID, + Cols: 100, + Rows: 30, + }) + // Registered the moment the PTY can exist — before the assertions below, + // any of which can t.Fatal and would otherwise leave the shell and its + // goroutines running into goleak's check. + t.Cleanup(func() { + if err := srv.procMgr.ShellManager().StopAll(); err != nil { + t.Errorf("stop all terminals: %v", err) + } + }) + if start.Code != http.StatusOK { + t.Fatalf("start status = %d (body %s)", start.Code, start.Body.String()) + } + if got := decodeShellTerminalBody(t, start); got["status"] != "started" || got["terminal_id"] != terminalID { + t.Fatalf("start body = %+v", got) + } + + httpServer := httptest.NewServer(srv.Router()) + defer httpServer.Close() + conn, _, err := websocket.DefaultDialer.Dial( + "ws"+strings.TrimPrefix(httpServer.URL, "http")+"/api/v1/shell/terminal/"+terminalID+"/stream", nil) + if err != nil { + t.Fatalf("dial terminal stream: %v", err) + } + defer func() { _ = conn.Close() }() + + // A resize control frame must be consumed as a command, never written to + // the PTY — otherwise its JSON would land in the user's command line. + resize, err := json.Marshal(map[string]uint16{"cols": 132, "rows": 43}) + if err != nil { + t.Fatalf("marshal resize: %v", err) + } + if err := conn.WriteMessage(websocket.BinaryMessage, append([]byte{shellResizeByte}, resize...)); err != nil { + t.Fatalf("write resize frame: %v", err) + } + + const marker = "kandev-terminal-marker" + if err := conn.WriteMessage(websocket.BinaryMessage, []byte("echo "+marker+"\r")); err != nil { + t.Fatalf("write terminal input: %v", err) + } + + streamed := readShellTerminalUntil(t, conn, marker) + if strings.Contains(streamed, `"cols"`) { + t.Errorf("resize control frame was forwarded to the PTY: %q", streamed) + } + + buffer := shellTerminalRequest(t, srv, http.MethodGet, "/api/v1/shell/terminal/"+terminalID+"/buffer", nil) + if buffer.Code != http.StatusOK { + t.Fatalf("buffer status = %d (body %s)", buffer.Code, buffer.Body.String()) + } + var replayed ShellBufferResponse + if err := json.Unmarshal(buffer.Body.Bytes(), &replayed); err != nil { + t.Fatalf("decode buffer: %v", err) + } + if !strings.Contains(replayed.Data, marker) { + t.Errorf("buffered output = %q, want it to contain the streamed marker", replayed.Data) + } + + stop := shellTerminalRequest(t, srv, http.MethodDelete, "/api/v1/shell/terminal/"+terminalID, nil) + if stop.Code != http.StatusOK { + t.Fatalf("stop status = %d (body %s)", stop.Code, stop.Body.String()) + } + after := shellTerminalRequest(t, srv, http.MethodGet, "/api/v1/shell/terminal/"+terminalID+"/buffer", nil) + if after.Code != http.StatusNotFound { + t.Errorf("buffer after stop = %d, want 404 (body %s)", after.Code, after.Body.String()) + } +} + +// readShellTerminalUntil accumulates binary frames until the marker appears. +// The PTY emits its prompt and the echoed keystrokes in an unpredictable number +// of frames, so the marker — not a frame count — is the synchronisation point. +func readShellTerminalUntil(t *testing.T, conn *websocket.Conn, marker string) string { + t.Helper() + var seen strings.Builder + deadline := time.Now().Add(wsTestTimeout) + for time.Now().Before(deadline) { + _ = conn.SetReadDeadline(deadline) + messageType, data, err := conn.ReadMessage() + if err != nil { + t.Fatalf("read terminal frame (seen %q): %v", seen.String(), err) + } + if messageType != websocket.BinaryMessage { + t.Fatalf("frame type = %d, want a binary frame", messageType) + } + seen.Write(data) + if strings.Contains(seen.String(), marker) { + return seen.String() + } + } + t.Fatalf("marker %q never arrived; saw %q", marker, seen.String()) + return "" +} diff --git a/apps/backend/internal/agentctl/server/api/workspace_base_branches_test.go b/apps/backend/internal/agentctl/server/api/workspace_base_branches_test.go new file mode 100644 index 0000000000..2734331d7d --- /dev/null +++ b/apps/backend/internal/agentctl/server/api/workspace_base_branches_test.go @@ -0,0 +1,146 @@ +package api + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "testing" +) + +// publishStagingAt creates and pushes `staging` at the given ref, giving the +// fixture a second live upstream branch to compare against. Without a second +// branch, selecting a base branch is indistinguishable from the default. +func (f *gitAPIFixture) publishStagingAt(t *testing.T, ref string) string { + t.Helper() + runGitAPI(t, f.repo, "branch", "staging", ref) + runGitAPI(t, f.repo, "push", "origin", "staging") + return strings.TrimSpace(runGitAPI(t, f.repo, "rev-parse", "staging")) +} + +// joinDetachedBaseBranchRefresh blocks until the goroutine UpdateBaseBranches +// spawns has finished. That goroutine runs RefreshGitStatus with +// context.Background — it does not stop when the request ends — and it shells +// out to git inside the fixture's t.TempDir(), so a test that returned without +// joining it would race its own directory removal. +// +// RefreshGitStatus takes the tracker's updateMu for the whole call, so calling +// it here cannot return until the detached one has released it. That makes it a +// join, not a wait. +func joinDetachedBaseBranchRefresh(t *testing.T, srv *Server) { + t.Helper() + srv.procMgr.GetWorkspaceTracker().RefreshGitStatus(context.Background()) +} + +func gitStatusBaseCommit(t *testing.T, srv *Server) string { + t.Helper() + rec := getGitAPI(t, srv, "/api/v1/git/status?fresh=true") + if rec.Code != http.StatusOK { + t.Fatalf("git status = %d (body %s)", rec.Code, rec.Body.String()) + } + var status GitStatusResult + if err := json.Unmarshal(rec.Body.Bytes(), &status); err != nil { + t.Fatalf("decode git status: %v", err) + } + if !status.Success { + t.Fatalf("git status failed: %+v", status) + } + return status.BaseCommit +} + +// TestHandleSetBaseBranches_RetargetsComparison asserts the endpoint's actual +// effect: after selecting `staging`, the tracker's reported base commit moves +// to the merge-base with that branch. Returning ok:true without re-stamping the +// tracker would leave the changes panel comparing against the old branch until +// the session restarts, which is the bug this endpoint exists to prevent. +func TestHandleSetBaseBranches_RetargetsComparison(t *testing.T) { + fixture := newGitAPIFixture(t) + stagingTip := fixture.publishStagingAt(t, "HEAD~1") + defaultBase := gitStatusBaseCommit(t, fixture.server) + if defaultBase == stagingTip { + t.Fatalf("fixture is degenerate: the default base already equals staging's tip %q", stagingTip) + } + + rec := postGitAPI(t, fixture.server, "/api/v1/workspace/base-branches", SetBaseBranchesRequest{ + BaseBranches: map[string]string{"": "staging"}, + }) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + var body map[string]bool + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode response: %v", err) + } + if !body["ok"] { + t.Errorf("response = %v, want ok:true", body) + } + joinDetachedBaseBranchRefresh(t, fixture.server) + if got := gitStatusBaseCommit(t, fixture.server); got != stagingTip { + t.Errorf("base_commit = %q, want the merge-base with staging %q", got, stagingTip) + } +} + +// TestHandleSetBaseBranches_DropsUnsafeRefs is the sanitiser test. Each of +// these refs is interpolated straight into `git` arguments downstream, so the +// handler must drop them — observable as the tracker keeping the default +// comparison base instead of adopting the rejected ref. +func TestHandleSetBaseBranches_DropsUnsafeRefs(t *testing.T) { + for _, unsafe := range []string{"staging;whoami", "staging..HEAD", "--upload-pack=touch", "/etc/passwd", "staging.lock"} { + t.Run(unsafe, func(t *testing.T) { + fixture := newGitAPIFixture(t) + stagingTip := fixture.publishStagingAt(t, "HEAD~1") + defaultBase := gitStatusBaseCommit(t, fixture.server) + + rec := postGitAPI(t, fixture.server, "/api/v1/workspace/base-branches", SetBaseBranchesRequest{ + BaseBranches: map[string]string{"": unsafe}, + }) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200 (body %s)", rec.Code, rec.Body.String()) + } + joinDetachedBaseBranchRefresh(t, fixture.server) + got := gitStatusBaseCommit(t, fixture.server) + if got == stagingTip { + t.Fatalf("base_commit moved to staging's tip; %q was accepted as a ref", unsafe) + } + if got != defaultBase { + t.Errorf("base_commit = %q, want the untouched default %q", got, defaultBase) + } + }) + } +} + +// TestHandleSetBaseBranches_AcceptsOriginPrefixedRefs pins the one shape the +// allowlist has to special-case: `origin/` is split before validation, +// because the underlying validator rejects a leading path separator. +func TestHandleSetBaseBranches_AcceptsOriginPrefixedRefs(t *testing.T) { + fixture := newGitAPIFixture(t) + stagingTip := fixture.publishStagingAt(t, "HEAD~1") + + rec := postGitAPI(t, fixture.server, "/api/v1/workspace/base-branches", SetBaseBranchesRequest{ + BaseBranches: map[string]string{"": "origin/staging"}, + }) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + joinDetachedBaseBranchRefresh(t, fixture.server) + if got := gitStatusBaseCommit(t, fixture.server); got != stagingTip { + t.Errorf("base_commit = %q, want the merge-base with origin/staging %q", got, stagingTip) + } +} + +// TestHandleSetBaseBranches_RejectsMalformedBody covers the binding guard. +func TestHandleSetBaseBranches_RejectsMalformedBody(t *testing.T) { + fixture := newGitAPIFixture(t) + + rec := postGitAPI(t, fixture.server, "/api/v1/workspace/base-branches", "{not json") + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 (body %s)", rec.Code, rec.Body.String()) + } + var body map[string]string + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode response: %v", err) + } + if body[errKey] != "invalid JSON body" { + t.Errorf("error = %q, want %q", body[errKey], "invalid JSON body") + } +} diff --git a/apps/backend/internal/agentctl/server/api/workspace_handlers_test.go b/apps/backend/internal/agentctl/server/api/workspace_handlers_test.go new file mode 100644 index 0000000000..6550ea1c63 --- /dev/null +++ b/apps/backend/internal/agentctl/server/api/workspace_handlers_test.go @@ -0,0 +1,552 @@ +package api + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/kandev/kandev/internal/agentctl/server/config" + "github.com/kandev/kandev/internal/agentctl/server/process" + "github.com/kandev/kandev/internal/agentctl/types/streams" + "github.com/kandev/kandev/internal/common/logger" +) + +// newWorkspaceFileServer builds a server over a plain (non-git) workspace +// seeded with one file and one nested directory. File handlers never touch +// git, so keeping the fixture git-free makes the assertions about the +// filesystem alone. +func newWorkspaceFileServer(t *testing.T) (*Server, string) { + t.Helper() + workDir := t.TempDir() + if err := os.WriteFile(filepath.Join(workDir, "one.txt"), []byte("one\n"), 0o644); err != nil { + t.Fatalf("seed one.txt: %v", err) + } + if err := os.Mkdir(filepath.Join(workDir, "nested"), 0o755); err != nil { + t.Fatalf("mkdir nested: %v", err) + } + if err := os.WriteFile(filepath.Join(workDir, "nested", "two.txt"), []byte("two\n"), 0o644); err != nil { + t.Fatalf("seed nested/two.txt: %v", err) + } + log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error"}) + cfg := &config.InstanceConfig{WorkDir: workDir} + return NewServer(cfg, process.NewManager(cfg, log), nil, nil, log), workDir +} + +func workspaceRequest(t *testing.T, srv *Server, method, path string, body any) *httptest.ResponseRecorder { + t.Helper() + var reader *bytes.Reader + switch v := body.(type) { + case nil: + reader = bytes.NewReader(nil) + case string: + reader = bytes.NewReader([]byte(v)) + default: + encoded, err := json.Marshal(v) + if err != nil { + t.Fatalf("marshal body: %v", err) + } + reader = bytes.NewReader(encoded) + } + req := httptest.NewRequest(method, path, reader) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + srv.Router().ServeHTTP(rec, req) + return rec +} + +func decodeWorkspaceBody[T any](t *testing.T, rec *httptest.ResponseRecorder) T { + t.Helper() + var body T + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode %q: %v", rec.Body.String(), err) + } + return body +} + +// TestHandleFileTree_ReturnsRequestedDepth pins the depth query parameter: +// depth=1 must stop at the directory entry, depth=2 must descend into it. A +// handler that ignored the parameter would still return a plausible tree. +func TestHandleFileTree_ReturnsRequestedDepth(t *testing.T) { + srv, _ := newWorkspaceFileServer(t) + + shallow := workspaceRequest(t, srv, http.MethodGet, "/api/v1/workspace/tree?depth=1", nil) + if shallow.Code != http.StatusOK { + t.Fatalf("depth=1 status = %d (body %s)", shallow.Code, shallow.Body.String()) + } + root := decodeWorkspaceBody[streams.FileTreeResponse](t, shallow).Root + if root == nil { + t.Fatalf("depth=1 returned no root: %s", shallow.Body.String()) + } + nested := findTreeChild(root, "nested") + if nested == nil { + t.Fatalf("depth=1 tree has no `nested` entry: %+v", childNames(root)) + } + if len(nested.Children) != 0 { + t.Errorf("depth=1 descended into `nested`: %+v", childNames(nested)) + } + + deep := workspaceRequest(t, srv, http.MethodGet, "/api/v1/workspace/tree?depth=2", nil) + if deep.Code != http.StatusOK { + t.Fatalf("depth=2 status = %d (body %s)", deep.Code, deep.Body.String()) + } + deepNested := findTreeChild(decodeWorkspaceBody[streams.FileTreeResponse](t, deep).Root, "nested") + if deepNested == nil || findTreeChild(deepNested, "two.txt") == nil { + t.Errorf("depth=2 did not descend into `nested`: %+v", deepNested) + } +} + +// TestHandleFileTree_RejectsEscapingPath covers the 400 branch: the tracker +// refuses a path outside the workspace and the handler forwards the reason. +func TestHandleFileTree_RejectsEscapingPath(t *testing.T) { + srv, _ := newWorkspaceFileServer(t) + + rec := workspaceRequest(t, srv, http.MethodGet, "/api/v1/workspace/tree?path=../..", nil) + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 (body %s)", rec.Code, rec.Body.String()) + } + if got := decodeWorkspaceBody[streams.FileTreeResponse](t, rec); got.Error == "" { + t.Errorf("error is empty; the refusal reason must reach the caller") + } +} + +func findTreeChild(node *streams.FileTreeNode, name string) *streams.FileTreeNode { + if node == nil { + return nil + } + for _, child := range node.Children { + if child.Name == name { + return child + } + } + return nil +} + +func childNames(node *streams.FileTreeNode) []string { + names := make([]string, 0, len(node.Children)) + for _, child := range node.Children { + names = append(names, child.Name) + } + return names +} + +// TestHandleFileContent_ReturnsFileBytes asserts the content endpoint answers +// with the file's real bytes and size, and echoes the caller's repo-relative +// path rather than the resolved absolute one. +func TestHandleFileContent_ReturnsFileBytes(t *testing.T) { + srv, _ := newWorkspaceFileServer(t) + + rec := workspaceRequest(t, srv, http.MethodGet, "/api/v1/workspace/file/content?path=nested/two.txt", nil) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + got := decodeWorkspaceBody[streams.FileContentResponse](t, rec) + if got.Content != "two\n" { + t.Errorf("content = %q, want %q", got.Content, "two\n") + } + if got.Path != "nested/two.txt" { + t.Errorf("path = %q, want the requested repo-relative path", got.Path) + } + if got.Size != int64(len("two\n")) { + t.Errorf("size = %d, want %d", got.Size, len("two\n")) + } + if got.IsBinary { + t.Errorf("is_binary = true for a text file") + } +} + +// TestHandleFileContent_Rejections covers every 400 branch of the read path. +func TestHandleFileContent_Rejections(t *testing.T) { + srv, _ := newWorkspaceFileServer(t) + + cases := []struct { + name string + query string + wantError string + }{ + {"missing path", "", "path is required"}, + {"unresolvable repo", "?path=one.txt&repo=nope", "repo subpath not found"}, + {"missing file", "?path=absent.txt", "no such file"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := workspaceRequest(t, srv, http.MethodGet, "/api/v1/workspace/file/content"+tc.query, nil) + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 (body %s)", rec.Code, rec.Body.String()) + } + got := decodeWorkspaceBody[streams.FileContentResponse](t, rec) + if !strings.Contains(got.Error, tc.wantError) { + t.Errorf("error = %q, want it to contain %q", got.Error, tc.wantError) + } + }) + } +} + +// TestHandleFileUpdate_AppliesDiff asserts the patch actually lands on disk and +// that the returned hash is the hash of the new content, which is what the +// editor sends back as OriginalHash on the next save. +func TestHandleFileUpdate_AppliesDiff(t *testing.T) { + srv, workDir := newWorkspaceFileServer(t) + + rec := workspaceRequest(t, srv, http.MethodPost, "/api/v1/workspace/file/content", streams.FileUpdateRequest{ + Path: "one.txt", + Diff: "--- one.txt\n+++ one.txt\n@@ -1 +1 @@\n-one\n+patched\n", + }) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + got := decodeWorkspaceBody[streams.FileUpdateResponse](t, rec) + if !got.Success { + t.Fatalf("update failed: %+v", got) + } + if got.NewHash == "" { + t.Errorf("new_hash is empty; the editor needs it for the next conflict check") + } + content, err := os.ReadFile(filepath.Join(workDir, "one.txt")) + if err != nil { + t.Fatalf("read one.txt: %v", err) + } + if string(content) != "patched\n" { + t.Errorf("one.txt = %q, want %q", string(content), "patched\n") + } +} + +// TestHandleFileUpdate_ReportsHashConflict covers the optimistic-concurrency +// branch: a stale OriginalHash with no desired-content fallback must be +// refused rather than silently overwriting a concurrent edit. +func TestHandleFileUpdate_ReportsHashConflict(t *testing.T) { + srv, workDir := newWorkspaceFileServer(t) + + rec := workspaceRequest(t, srv, http.MethodPost, "/api/v1/workspace/file/content", streams.FileUpdateRequest{ + Path: "one.txt", + Diff: "--- one.txt\n+++ one.txt\n@@ -1 +1 @@\n-one\n+patched\n", + OriginalHash: "0000000000000000000000000000000000000000000000000000000000000000", + }) + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 (body %s)", rec.Code, rec.Body.String()) + } + got := decodeWorkspaceBody[streams.FileUpdateResponse](t, rec) + if got.Success { + t.Errorf("success = true, want false") + } + if !strings.Contains(got.Error, "conflict detected") { + t.Errorf("error = %q, want a conflict report", got.Error) + } + content, err := os.ReadFile(filepath.Join(workDir, "one.txt")) + if err != nil { + t.Fatalf("read one.txt: %v", err) + } + if string(content) != "one\n" { + t.Errorf("one.txt = %q; the refused update must not have been written", string(content)) + } +} + +// TestHandleFileUpdate_Rejections covers the pre-flight guards, which run +// before anything reads the file. +func TestHandleFileUpdate_Rejections(t *testing.T) { + srv, _ := newWorkspaceFileServer(t) + + cases := []struct { + name string + body any + wantError string + }{ + {"malformed body", "{not json", "invalid request: "}, + {"missing path", streams.FileUpdateRequest{Diff: "d"}, "path is required"}, + {"missing diff", streams.FileUpdateRequest{Path: "one.txt"}, "diff is required"}, + { + "unresolvable repo", + streams.FileUpdateRequest{Path: "one.txt", Diff: "d", Repo: "nope"}, + "repo subpath not found", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := workspaceRequest(t, srv, http.MethodPost, "/api/v1/workspace/file/content", tc.body) + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 (body %s)", rec.Code, rec.Body.String()) + } + got := decodeWorkspaceBody[streams.FileUpdateResponse](t, rec) + if !strings.Contains(got.Error, tc.wantError) { + t.Errorf("error = %q, want it to contain %q", got.Error, tc.wantError) + } + }) + } +} + +// TestHandleFileCreate_CreatesEmptyFile asserts the created file exists and is +// empty, and that creating over an existing path is refused. +func TestHandleFileCreate_CreatesEmptyFile(t *testing.T) { + srv, workDir := newWorkspaceFileServer(t) + + rec := workspaceRequest(t, srv, http.MethodPost, "/api/v1/workspace/file/create", streams.FileCreateRequest{ + Path: "nested/created.txt", + }) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + if got := decodeWorkspaceBody[streams.FileCreateResponse](t, rec); !got.Success || got.Path != "nested/created.txt" { + t.Fatalf("create response = %+v", got) + } + info, err := os.Stat(filepath.Join(workDir, "nested", "created.txt")) + if err != nil { + t.Fatalf("stat created file: %v", err) + } + if info.Size() != 0 { + t.Errorf("created file size = %d, want 0", info.Size()) + } + + again := workspaceRequest(t, srv, http.MethodPost, "/api/v1/workspace/file/create", streams.FileCreateRequest{ + Path: "one.txt", + }) + if again.Code != http.StatusBadRequest { + t.Fatalf("re-create status = %d, want 400 (body %s)", again.Code, again.Body.String()) + } + if got := decodeWorkspaceBody[streams.FileCreateResponse](t, again); got.Success || got.Error == "" { + t.Errorf("re-create response = %+v, want a refusal with a reason", got) + } +} + +// TestHandleFileCreate_Rejections covers the guards ahead of the filesystem. +func TestHandleFileCreate_Rejections(t *testing.T) { + srv, _ := newWorkspaceFileServer(t) + + cases := []struct { + name string + body any + wantError string + }{ + {"malformed body", "{not json", "invalid request: "}, + {"missing path", streams.FileCreateRequest{}, "path is required"}, + {"unresolvable repo", streams.FileCreateRequest{Path: "x.txt", Repo: "nope"}, "repo subpath not found"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := workspaceRequest(t, srv, http.MethodPost, "/api/v1/workspace/file/create", tc.body) + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 (body %s)", rec.Code, rec.Body.String()) + } + got := decodeWorkspaceBody[streams.FileCreateResponse](t, rec) + if !strings.Contains(got.Error, tc.wantError) { + t.Errorf("error = %q, want it to contain %q", got.Error, tc.wantError) + } + }) + } +} + +// TestHandleFileDelete_RemovesFile asserts the file is gone from disk, and +// that a second delete of the same path is refused rather than reported as a +// success the UI would render as a removed row. +func TestHandleFileDelete_RemovesFile(t *testing.T) { + srv, workDir := newWorkspaceFileServer(t) + + rec := workspaceRequest(t, srv, http.MethodDelete, "/api/v1/workspace/file?path=nested/two.txt", nil) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + if got := decodeWorkspaceBody[streams.FileDeleteResponse](t, rec); !got.Success || got.Path != "nested/two.txt" { + t.Fatalf("delete response = %+v", got) + } + if _, err := os.Stat(filepath.Join(workDir, "nested", "two.txt")); !os.IsNotExist(err) { + t.Errorf("nested/two.txt still exists (stat err = %v)", err) + } + + again := workspaceRequest(t, srv, http.MethodDelete, "/api/v1/workspace/file?path=nested/two.txt", nil) + if again.Code != http.StatusBadRequest { + t.Errorf("second delete status = %d, want 400 (body %s)", again.Code, again.Body.String()) + } +} + +// TestHandleFileDelete_Rejections covers the query-parameter guards. +func TestHandleFileDelete_Rejections(t *testing.T) { + srv, _ := newWorkspaceFileServer(t) + + cases := []struct { + name string + query string + wantError string + }{ + {"missing path", "", "path is required"}, + {"unresolvable repo", "?path=one.txt&repo=nope", "repo subpath not found"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := workspaceRequest(t, srv, http.MethodDelete, "/api/v1/workspace/file"+tc.query, nil) + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 (body %s)", rec.Code, rec.Body.String()) + } + got := decodeWorkspaceBody[streams.FileDeleteResponse](t, rec) + if !strings.Contains(got.Error, tc.wantError) { + t.Errorf("error = %q, want it to contain %q", got.Error, tc.wantError) + } + }) + } +} + +// TestHandleFileRename_MovesFile asserts both ends of the move: the old path is +// gone and the new path carries the original bytes. +func TestHandleFileRename_MovesFile(t *testing.T) { + srv, workDir := newWorkspaceFileServer(t) + + rec := workspaceRequest(t, srv, http.MethodPost, "/api/v1/workspace/file/rename", streams.FileRenameRequest{ + OldPath: "one.txt", + NewPath: "nested/renamed.txt", + }) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + got := decodeWorkspaceBody[streams.FileRenameResponse](t, rec) + if !got.Success || got.OldPath != "one.txt" || got.NewPath != "nested/renamed.txt" { + t.Fatalf("rename response = %+v", got) + } + if _, err := os.Stat(filepath.Join(workDir, "one.txt")); !os.IsNotExist(err) { + t.Errorf("one.txt still exists after rename (stat err = %v)", err) + } + content, err := os.ReadFile(filepath.Join(workDir, "nested", "renamed.txt")) + if err != nil { + t.Fatalf("read renamed file: %v", err) + } + if string(content) != "one\n" { + t.Errorf("renamed file = %q, want the original %q", string(content), "one\n") + } +} + +// TestHandleFileRename_Rejections covers each guard, including the two +// separate repo-scoping joins the handler performs (old and new path). +func TestHandleFileRename_Rejections(t *testing.T) { + srv, _ := newWorkspaceFileServer(t) + + cases := []struct { + name string + body any + wantError string + }{ + {"malformed body", "{not json", "invalid request: "}, + {"missing old path", streams.FileRenameRequest{NewPath: "b.txt"}, "old_path is required"}, + {"missing new path", streams.FileRenameRequest{OldPath: "one.txt"}, "new_path is required"}, + { + "unresolvable repo", + streams.FileRenameRequest{OldPath: "one.txt", NewPath: "b.txt", Repo: "nope"}, + "repo subpath not found", + }, + {"missing source", streams.FileRenameRequest{OldPath: "absent.txt", NewPath: "b.txt"}, ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := workspaceRequest(t, srv, http.MethodPost, "/api/v1/workspace/file/rename", tc.body) + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 (body %s)", rec.Code, rec.Body.String()) + } + got := decodeWorkspaceBody[streams.FileRenameResponse](t, rec) + if got.Success { + t.Errorf("success = true, want false") + } + if got.Error == "" { + t.Fatalf("error is empty; the refusal reason must reach the caller") + } + if !strings.Contains(got.Error, tc.wantError) { + t.Errorf("error = %q, want it to contain %q", got.Error, tc.wantError) + } + }) + } +} + +// TestMustParseInt covers the query-number helper the tree and search handlers +// share. It answers 0 (not an error) for anything unparseable, which is why +// both callers guard on the result being positive. +func TestMustParseInt(t *testing.T) { + cases := map[string]int{ + "7": 7, + "0": 0, + "-3": -3, + "": 0, + "seven": 0, + "1.5": 0, + "9e9": 0, + } + for input, want := range cases { + if got := mustParseInt(input); got != want { + t.Errorf("mustParseInt(%q) = %d, want %d", input, got, want) + } + } +} + +// TestHandleFileContentAtRef_ReadsCommittedBytes asserts the endpoint reads +// from git rather than the working tree: the file is edited on disk and the +// response must still carry the committed content for the requested ref. +func TestHandleFileContentAtRef_ReadsCommittedBytes(t *testing.T) { + fixture := newGitAPIFixture(t) + writeFileAPI(t, fixture.repo, "one.txt", "dirty working tree\n") + + rec := getGitAPI(t, fixture.server, "/api/v1/workspace/file/content-at-ref?path=one.txt&ref=HEAD") + if rec.Code != http.StatusOK { + t.Fatalf("status = %d (body %s)", rec.Code, rec.Body.String()) + } + got := decodeWorkspaceBody[streams.FileContentResponse](t, rec) + if got.Content != "one\n" { + t.Errorf("content = %q, want the committed %q", got.Content, "one\n") + } + if got.Path != "one.txt" { + t.Errorf("path = %q, want %q", got.Path, "one.txt") + } +} + +// TestHandleFileContentAtRef_Rejections covers every guard, including the +// ref that predates the file — a miss inside git, not a bad request shape. +func TestHandleFileContentAtRef_Rejections(t *testing.T) { + fixture := newGitAPIFixture(t) + + cases := []struct { + name string + query string + wantError string + }{ + {"missing path", "?ref=HEAD", "path is required"}, + {"missing ref", "?path=one.txt", "ref is required"}, + {"unresolvable repo", "?path=one.txt&ref=HEAD&repo=nope", "repo subpath not found"}, + {"ref predating the file", "?path=one.txt&ref=main", ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := getGitAPI(t, fixture.server, "/api/v1/workspace/file/content-at-ref"+tc.query) + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 (body %s)", rec.Code, rec.Body.String()) + } + got := decodeWorkspaceBody[streams.FileContentResponse](t, rec) + if got.Error == "" { + t.Fatalf("error is empty; the refusal reason must reach the caller") + } + if !strings.Contains(got.Error, tc.wantError) { + t.Errorf("error = %q, want it to contain %q", got.Error, tc.wantError) + } + }) + } +} + +// TestHandleFileContentAtRef_RequiresRepoOnMultiRepoWorkspace pins the +// multi-repo guard. Without an explicit repo the read would land on the task +// root, which is not itself a git repository, and every ref lookup there fails +// for a reason that has nothing to do with the file the user asked for. +func TestHandleFileContentAtRef_RequiresRepoOnMultiRepoWorkspace(t *testing.T) { + srv, repoNames := newMultiRepoStatusServer(t) + + rec := getGitAPI(t, srv, "/api/v1/workspace/file/content-at-ref?path=README.md&ref=HEAD") + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 (body %s)", rec.Code, rec.Body.String()) + } + if got := decodeWorkspaceBody[streams.FileContentResponse](t, rec); got.Error != "repo is required for multi-repo workspace" { + t.Errorf("error = %q, want the multi-repo refusal", got.Error) + } + + scoped := getGitAPI(t, srv, "/api/v1/workspace/file/content-at-ref?path=README.md&ref=HEAD&repo="+repoNames[0]) + if scoped.Code != http.StatusOK { + t.Fatalf("scoped status = %d (body %s)", scoped.Code, scoped.Body.String()) + } + if got := decodeWorkspaceBody[streams.FileContentResponse](t, scoped); got.Content != repoNames[0]+"\n" { + t.Errorf("content = %q, want %q", got.Content, repoNames[0]+"\n") + } +} diff --git a/apps/backend/internal/agentctl/server/api/workspace_stream_ws_test.go b/apps/backend/internal/agentctl/server/api/workspace_stream_ws_test.go new file mode 100644 index 0000000000..1adf0264c1 --- /dev/null +++ b/apps/backend/internal/agentctl/server/api/workspace_stream_ws_test.go @@ -0,0 +1,277 @@ +package api + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/gorilla/websocket" + "github.com/kandev/kandev/internal/agentctl/types" +) + +const wsTestTimeout = 10 * time.Second + +// recordingShell stands in for the PTY-backed shell the workspace stream +// forwards `shell_input` to. Reads are synchronised because the input loop +// writes from the server goroutine while the test asserts from its own. +type recordingShell struct { + mu sync.Mutex + written []byte + got chan struct{} +} + +func newRecordingShell() *recordingShell { + return &recordingShell{got: make(chan struct{}, 8)} +} + +func (r *recordingShell) Write(p []byte) (int, error) { + r.mu.Lock() + r.written = append(r.written, p...) + r.mu.Unlock() + r.got <- struct{}{} + return len(p), nil +} + +func (r *recordingShell) snapshot() string { + r.mu.Lock() + defer r.mu.Unlock() + return string(r.written) +} + +func (r *recordingShell) awaitWrite(t *testing.T) { + t.Helper() + select { + case <-r.got: + case <-time.After(wsTestTimeout): + t.Fatal("timed out waiting for the input loop to forward shell input") + } +} + +// dialWorkspaceInputLoop runs handleWorkspaceStreamInput behind a real +// WebSocket so the read path, the JSON decoding, and the pong write are all +// exercised end to end. Cleanup closes the client, joins the loop, and shuts +// the server down, which is what keeps goleak quiet. +func dialWorkspaceInputLoop(t *testing.T, shell io.Writer) *websocket.Conn { + t.Helper() + srv := newTestServer(t) + loopReturned := make(chan struct{}) + done := make(chan struct{}) + + httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := srv.upgrader.Upgrade(w, r, nil) + if err != nil { + t.Errorf("upgrade: %v", err) + close(loopReturned) + return + } + defer func() { _ = conn.Close() }() + srv.handleWorkspaceStreamInput(conn, shell, done) + close(loopReturned) + })) + + conn, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(httpServer.URL, "http"), nil) + if err != nil { + httpServer.Close() + t.Fatalf("dial workspace input loop: %v", err) + } + t.Cleanup(func() { + _ = conn.Close() + select { + case <-loopReturned: + case <-time.After(wsTestTimeout): + t.Error("workspace stream input loop did not return after the client disconnected") + } + close(done) + httpServer.Close() + }) + return conn +} + +func readWorkspaceMessage(t *testing.T, conn *websocket.Conn) types.WorkspaceStreamMessage { + t.Helper() + _ = conn.SetReadDeadline(time.Now().Add(wsTestTimeout)) + var msg types.WorkspaceStreamMessage + if err := conn.ReadJSON(&msg); err != nil { + t.Fatalf("read workspace message: %v", err) + } + return msg +} + +func writeWorkspaceMessage(t *testing.T, conn *websocket.Conn, msg types.WorkspaceStreamMessage) { + t.Helper() + if err := conn.WriteJSON(msg); err != nil { + t.Fatalf("write workspace message: %v", err) + } +} + +// TestHandleWorkspaceStreamInput_ForwardsShellInput asserts the bytes reach the +// shell verbatim — no framing, no newline added — because the terminal is a raw +// byte pipe and any decoration would show up as garbage keystrokes. +func TestHandleWorkspaceStreamInput_ForwardsShellInput(t *testing.T) { + shell := newRecordingShell() + conn := dialWorkspaceInputLoop(t, shell) + + writeWorkspaceMessage(t, conn, types.WorkspaceStreamMessage{ + Type: types.WorkspaceMessageTypeShellInput, + Data: "ls -la\r", + }) + shell.awaitWrite(t) + + if got := shell.snapshot(); got != "ls -la\r" { + t.Errorf("shell received %q, want %q", got, "ls -la\r") + } +} + +// TestHandleWorkspaceStreamInput_AnswersPing pins the keepalive: a ping must +// produce a pong on the same connection. The frontend closes and re-dials the +// workspace stream when the pong stops arriving. +func TestHandleWorkspaceStreamInput_AnswersPing(t *testing.T) { + conn := dialWorkspaceInputLoop(t, newRecordingShell()) + + writeWorkspaceMessage(t, conn, types.WorkspaceStreamMessage{Type: types.WorkspaceMessageTypePing}) + + got := readWorkspaceMessage(t, conn) + if got.Type != types.WorkspaceMessageTypePong { + t.Errorf("reply type = %q, want %q", got.Type, types.WorkspaceMessageTypePong) + } + if got.Timestamp == 0 { + t.Errorf("pong carries no timestamp") + } +} + +// TestHandleWorkspaceStreamInput_IgnoresNonInputMessages proves resize and +// unknown message types are consumed without being forwarded to the shell. +// Routing a resize into the PTY as keystrokes would inject its JSON into the +// user's command line. +func TestHandleWorkspaceStreamInput_IgnoresNonInputMessages(t *testing.T) { + shell := newRecordingShell() + conn := dialWorkspaceInputLoop(t, shell) + + writeWorkspaceMessage(t, conn, types.WorkspaceStreamMessage{ + Type: types.WorkspaceMessageTypeShellResize, + Cols: 120, + Rows: 40, + }) + writeWorkspaceMessage(t, conn, types.WorkspaceStreamMessage{Type: "totally-unknown", Data: "ignored"}) + // The ping is ordered after both, and the loop is single-threaded, so its + // pong proves the two earlier messages were fully processed. + writeWorkspaceMessage(t, conn, types.WorkspaceStreamMessage{Type: types.WorkspaceMessageTypePing}) + + if got := readWorkspaceMessage(t, conn); got.Type != types.WorkspaceMessageTypePong { + t.Fatalf("reply type = %q, want %q", got.Type, types.WorkspaceMessageTypePong) + } + if got := shell.snapshot(); got != "" { + t.Errorf("shell received %q; only shell_input may be forwarded", got) + } +} + +// TestHandleWorkspaceStreamWS_ForwardsTrackerEvents drives the full endpoint: +// the greeting frame, then a workspace event published by the tracker while the +// client is attached. The event has to arrive tagged as git_commit with its +// payload intact — this is the fan-out the Commits panel is built on. +// +// The teardown is the interesting part. The forwarding loop only notices a +// departed client on its next write, so after closing the connection the test +// keeps publishing until the handler returns; the channel, not a fixed sleep, +// is what the test waits on. +func TestHandleWorkspaceStreamWS_ForwardsTrackerEvents(t *testing.T) { + srv := newTestServer(t) + handlerReturned := make(chan struct{}) + // sync.Once: a second request to this server — a retry, or a future edit + // that dials twice — would otherwise close an already-closed channel and + // panic on a server goroutine, taking down the whole test binary. + var returnedOnce sync.Once + httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer returnedOnce.Do(func() { close(handlerReturned) }) + srv.Router().ServeHTTP(w, r) + })) + + conn, _, err := websocket.DefaultDialer.Dial( + "ws"+strings.TrimPrefix(httpServer.URL, "http")+"/api/v1/workspace/stream", nil) + if err != nil { + httpServer.Close() + t.Fatalf("dial workspace stream: %v", err) + } + // Registered before any assertion below can t.Fatal. httpServer.Close waits + // for the handler, so it must run after the shutdown loop has released it — + // cleanups run last-registered-first, hence this ordering. + t.Cleanup(httpServer.Close) + t.Cleanup(func() { + _ = conn.Close() + waitForWorkspaceStreamShutdown(t, srv.procMgr.GetWorkspaceTracker().NotifyGitCommit, handlerReturned) + }) + + if got := readWorkspaceMessage(t, conn); got.Type != types.WorkspaceMessageTypeConnected { + t.Fatalf("first frame type = %q, want %q", got.Type, types.WorkspaceMessageTypeConnected) + } + + tracker := srv.procMgr.GetWorkspaceTracker() + tracker.NotifyGitCommit(&types.GitCommitNotification{ + CommitSHA: "1111111111111111111111111111111111111111", + ParentSHA: "2222222222222222222222222222222222222222", + Message: "streamed commit", + }) + + event := readWorkspaceMessage(t, conn) + if event.Type != types.WorkspaceMessageTypeGitCommit { + t.Fatalf("event type = %q, want %q", event.Type, types.WorkspaceMessageTypeGitCommit) + } + if event.GitCommit == nil { + t.Fatalf("git_commit payload is missing: %+v", event) + } + if event.GitCommit.CommitSHA != "1111111111111111111111111111111111111111" { + t.Errorf("commit_sha = %q, want the published sha", event.GitCommit.CommitSHA) + } + if event.GitCommit.Message != "streamed commit" { + t.Errorf("message = %q, want %q", event.GitCommit.Message, "streamed commit") + } + + // Deliberately no ping here: the input goroutine answers a ping by writing + // the pong onto this same connection, while the forwarding loop above is + // also writing to it, and a gorilla *Conn permits only one concurrent + // writer. Ping/pong is covered against the input loop in isolation by + // TestHandleWorkspaceStreamInput_AnswersPing. +} + +// waitForWorkspaceStreamShutdown republishes until the handler's forwarding +// loop attempts a write on the closed connection and returns. The first write +// after a peer close usually succeeds (it lands in the kernel buffer), so one +// event is not enough to observe the disconnect. +func waitForWorkspaceStreamShutdown( + t *testing.T, + publish func(*types.GitCommitNotification), + handlerReturned <-chan struct{}, +) { + t.Helper() + deadline := time.After(wsTestTimeout) + // One timer, reset per iteration: time.After in a loop leaks a timer per + // pass that the runtime cannot collect until it fires. + retry := time.NewTimer(0) + defer retry.Stop() + if !retry.Stop() { + <-retry.C + } + for { + select { + case <-handlerReturned: + return + case <-deadline: + t.Fatal("workspace stream handler did not return after the client disconnected") + default: + } + publish(&types.GitCommitNotification{CommitSHA: "3333333333333333333333333333333333333333"}) + retry.Reset(5 * time.Millisecond) + select { + case <-handlerReturned: + if !retry.Stop() { + <-retry.C + } + return + case <-retry.C: + } + } +}