diff --git a/.dockerignore b/.dockerignore index 17f7223828..e7e640cd6b 100644 --- a/.dockerignore +++ b/.dockerignore @@ -2,17 +2,30 @@ .git .gitignore -# Build artifacts -apps/backend/bin/ -apps/web/.next/ -apps/web/out/ -dist/ +# Build artifacts (any depth) +**/.next +**/out +**/.turbo +**/tsconfig.tsbuildinfo +apps/backend/bin +apps/web/dist +apps/landing/dist +# Don't ignore apps/cli/{bin,dist} or apps/packages/*/dist — copied at build time + +# Loose Go build outputs in apps/backend/ (go build with no -o) +apps/backend/kandev +apps/backend/agentctl +apps/backend/mock-agent +apps/backend/acpdbg +apps/backend/acp-debug + +# Local SQLite databases +**/*.db +**/*.db-wal +**/*.db-shm # Dependencies (rebuilt in Docker) -node_modules/ -apps/web/node_modules/ -apps/cli/node_modules/ -apps/packages/*/node_modules/ +**/node_modules # IDE and editor files .vscode/ @@ -36,12 +49,16 @@ docs/ k8s/ *.md !apps/web/src/**/*.md +# Needed by apps/web build scripts (generate-changelog.mjs, +# generate-release-notes.mjs) at the repo root inside the builder stage. +!CHANGELOG.md LICENSE # Test artifacts coverage/ +**/playwright-report +**/test-results *.test.ts -*.test.go **/*_test.go # Agent/Claude config diff --git a/.github/workflows/e2e-tests.yml b/.github/workflows/e2e-tests.yml index b1f6f8080c..ac50ad6c53 100644 --- a/.github/workflows/e2e-tests.yml +++ b/.github/workflows/e2e-tests.yml @@ -49,7 +49,7 @@ jobs: - name: Set up pnpm uses: pnpm/action-setup@v4 with: - version: "9" + version: "9.15.9" - name: Set up Node.js uses: actions/setup-node@v6 @@ -105,7 +105,7 @@ jobs: - name: Set up pnpm uses: pnpm/action-setup@v4 with: - version: "9" + version: "9.15.9" - name: Set up Node.js uses: actions/setup-node@v6 @@ -261,7 +261,7 @@ jobs: - name: Set up pnpm uses: pnpm/action-setup@v4 with: - version: "9" + version: "9.15.9" - name: Set up Node.js uses: actions/setup-node@v6 diff --git a/.github/workflows/frontend-tests.yml b/.github/workflows/frontend-tests.yml index 0033344f08..5378f954eb 100644 --- a/.github/workflows/frontend-tests.yml +++ b/.github/workflows/frontend-tests.yml @@ -51,7 +51,7 @@ jobs: - name: Set up pnpm uses: pnpm/action-setup@v4 with: - version: "9" + version: "9.15.9" - name: Set up Node.js uses: actions/setup-node@v6 diff --git a/.github/workflows/preview-env.yml b/.github/workflows/preview-env.yml index cfbd988edf..f4edd4d884 100644 --- a/.github/workflows/preview-env.yml +++ b/.github/workflows/preview-env.yml @@ -37,7 +37,7 @@ jobs: - uses: pnpm/action-setup@v4 with: - version: "9" + version: "9.15.9" - uses: actions/setup-node@v6 with: @@ -94,7 +94,7 @@ jobs: - uses: pnpm/action-setup@v4 with: - version: "9" + version: "9.15.9" - uses: actions/setup-node@v6 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6b65ad3832..df6d32670b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -60,7 +60,7 @@ jobs: - uses: pnpm/action-setup@v4 with: - version: "9" + version: "9.15.9" - uses: actions/setup-node@v6 with: @@ -251,7 +251,7 @@ jobs: ref: ${{ needs.prepare.outputs.tag }} - uses: pnpm/action-setup@v4 with: - version: "9" + version: "9.15.9" - uses: actions/setup-node@v6 with: node-version: "24" @@ -280,7 +280,7 @@ jobs: ref: ${{ needs.prepare.outputs.tag }} - uses: pnpm/action-setup@v4 with: - version: "9" + version: "9.15.9" - uses: actions/setup-node@v6 with: node-version: "24" @@ -512,7 +512,7 @@ jobs: - uses: pnpm/action-setup@v4 with: - version: "9" + version: "9.15.9" - uses: actions/setup-node@v6 with: diff --git a/CHANGELOG.md b/CHANGELOG.md index fe108bcc13..9ad7f6c726 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,33 @@ All notable changes to Kandev. +## 0.43.0 - 2026-05-11 + +### Bug Fixes + +- resolve subtask base_branch correctly across repos ([#870](https://github.com/kdlbs/kandev/pull/870)) +- skip NEXT_PUBLIC_KANDEV_API_PORT in production single-port mode ([#872](https://github.com/kdlbs/kandev/pull/872)) + +## 0.42.0 - 2026-05-11 + +### Features + +- streaming agent install, PTY login terminal, docker container UX ([#869](https://github.com/kdlbs/kandev/pull/869)) +- add CI hover popover on PR top-bar button ([#846](https://github.com/kdlbs/kandev/pull/846)) +- prettify Kandev MCP tool titles in chat ([#858](https://github.com/kdlbs/kandev/pull/858)) +- show repo name and enable multi-select in pipeline view ([#831](https://github.com/kdlbs/kandev/pull/831)) +- extend implement plan button with fresh-agent path and server-side plan mode ([#832](https://github.com/kdlbs/kandev/pull/832)) + +### Bug Fixes + +- keep task and session state in sync on tool-event wake ([#865](https://github.com/kdlbs/kandev/pull/865)) +- close kanban preview when opening the edit dialog ([#868](https://github.com/kdlbs/kandev/pull/868)) +- wire logging.outputPath from config to logger ([#866](https://github.com/kdlbs/kandev/pull/866)) +- harden release package publishing ([#862](https://github.com/kdlbs/kandev/pull/862)) +- unify Kandev branding ([#863](https://github.com/kdlbs/kandev/pull/863)) +- warn on duplicate custom prompt name instead of 500 ([#859](https://github.com/kdlbs/kandev/pull/859)) +- mobile task switcher sheet skeleton while snapshot loads ([#860](https://github.com/kdlbs/kandev/pull/860)) + ## 0.41.0 - 2026-05-09 ### Features diff --git a/Dockerfile b/Dockerfile index be5dbc2d00..ea3c3f727a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -30,7 +30,8 @@ RUN go build -ldflags "-s -w" -o /out/kandev ./cmd/kandev && \ # --------------------------------------------------------------------------- FROM node:24-slim AS web-builder -RUN corepack enable && corepack prepare pnpm@latest --activate +ARG PNPM_VERSION=9.15.9 +RUN corepack enable && corepack prepare pnpm@${PNPM_VERSION} --activate WORKDIR /build/apps @@ -47,6 +48,11 @@ RUN pnpm install --frozen-lockfile # Copy full source for build COPY apps/ ./ +# CHANGELOG.md lives at the repo root in source; the web build scripts +# (generate-changelog.mjs, generate-release-notes.mjs) resolve it via +# `${WEB_ROOT}/../../CHANGELOG.md`. Mirror that layout inside the builder. +COPY CHANGELOG.md /build/CHANGELOG.md + # Build shared packages, web app, and CLI RUN pnpm --filter @kandev/web build && \ pnpm --filter kandev build @@ -56,10 +62,13 @@ RUN pnpm --filter @kandev/web build && \ # --------------------------------------------------------------------------- FROM node:24-bookworm-slim AS runtime -# Install only essential runtime dependencies, then clean up +# Install only essential runtime dependencies, then clean up. +# gh is included because the GitHub integration (PR review, webhooks) shells out +# to it for auth fallback when GITHUB_TOKEN is not set. RUN apt-get update && \ apt-get install -y --no-install-recommends \ git \ + gh \ ca-certificates \ gosu \ tini \ @@ -102,10 +111,14 @@ RUN cd /usr/local/lib/kandev-cli && npm install --omit=dev && \ # Kandev home directory (DB, worktrees, sessions, repos) VOLUME ["/data"] -# Environment defaults for containerized operation +# Environment defaults for containerized operation. +# NPM_CONFIG_PREFIX points npm global installs at the PV so user-installed +# agent CLIs (claude-code, codex, auggie, ...) survive pod restarts. ENV KANDEV_NO_BROWSER=1 \ KANDEV_HOME_DIR=/data \ KANDEV_DOCKER_ENABLED=false \ + NPM_CONFIG_PREFIX=/data/.npm-global \ + PATH=/data/.npm-global/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ HOSTNAME=0.0.0.0 \ NODE_ENV=production diff --git a/apps/backend/cmd/kandev/adapters.go b/apps/backend/cmd/kandev/adapters.go index fc5ec499ff..54c11b4e5b 100644 --- a/apps/backend/cmd/kandev/adapters.go +++ b/apps/backend/cmd/kandev/adapters.go @@ -93,6 +93,7 @@ func (a *lifecycleAdapter) LaunchAgent(ctx context.Context, req *executor.Launch RepositoryID: req.RepositoryID, RepositoryPath: req.RepositoryPath, BaseBranch: req.BaseBranch, + DefaultBranch: req.DefaultBranch, CheckoutBranch: req.CheckoutBranch, WorktreeBranchPrefix: req.WorktreeBranchPrefix, PullBeforeWorktree: req.PullBeforeWorktree, @@ -111,6 +112,7 @@ func (a *lifecycleAdapter) LaunchAgent(ctx context.Context, req *executor.Launch RepositoryURL: r.RepositoryURL, RepoName: r.RepoName, BaseBranch: r.BaseBranch, + DefaultBranch: r.DefaultBranch, CheckoutBranch: r.CheckoutBranch, WorktreeID: r.WorktreeID, WorktreeBranchPrefix: r.WorktreeBranchPrefix, diff --git a/apps/backend/cmd/kandev/helpers.go b/apps/backend/cmd/kandev/helpers.go index 71950c56bd..b69361925c 100644 --- a/apps/backend/cmd/kandev/helpers.go +++ b/apps/backend/cmd/kandev/helpers.go @@ -20,7 +20,9 @@ import ( agenthandlers "github.com/kandev/kandev/internal/agent/handlers" "github.com/kandev/kandev/internal/agent/hostutility" "github.com/kandev/kandev/internal/agent/lifecycle" + "github.com/kandev/kandev/internal/agent/loginpty" "github.com/kandev/kandev/internal/agent/mcpconfig" + "github.com/kandev/kandev/internal/agent/registry" agentsettingscontroller "github.com/kandev/kandev/internal/agent/settings/controller" agentsettingshandlers "github.com/kandev/kandev/internal/agent/settings/handlers" "github.com/kandev/kandev/internal/agentctl/client" @@ -415,6 +417,7 @@ type routeParams struct { services *Services agentSettingsController *agentsettingscontroller.Controller agentList taskhandlers.AgentLister + agentRegistry *registry.Registry userCtrl *usercontroller.Controller notificationCtrl *notificationcontroller.Controller editorCtrl *editorcontroller.Controller @@ -578,6 +581,18 @@ func registerSecondaryRoutes( agentsettingshandlers.RegisterRoutes(p.router, p.agentSettingsController, p.gateway.Hub, p.log) p.log.Debug("Registered Agent Settings handlers (HTTP)") + // Login PTY: spawns agent login commands under a PTY on the kandev host + // (claude auth login, auggie login, ...). The user explicitly closes the + // dialog when done, so invalidate the discovery cache on every session + // end regardless of exit code — rescanning is cheap and correctly picks + // up new auth state for agents whose login flow lives inside the TUI + // (e.g. gemini) where the process keeps running after auth completes. + loginMgr := loginpty.NewManager(p.log, func(_ string, _ int, _ error) { + p.agentSettingsController.InvalidateDiscoveryCache() + }) + loginpty.NewHandlers(loginMgr, p.agentRegistry, p.log.Zap(), nil).RegisterRoutes(p.router) + p.log.Debug("Registered Login PTY handlers (HTTP + WebSocket)") + userhandlers.RegisterRoutes(p.router, p.gateway.Dispatcher, p.userCtrl, p.log) p.log.Debug("Registered User handlers (HTTP + WebSocket)") diff --git a/apps/backend/cmd/kandev/main.go b/apps/backend/cmd/kandev/main.go index 6aff72c903..1cb5d1f736 100644 --- a/apps/backend/cmd/kandev/main.go +++ b/apps/backend/cmd/kandev/main.go @@ -133,8 +133,13 @@ func realMain() int { // 2. Initialize logger log, err := logger.NewLogger(logger.LoggingConfig{ - Level: cfg.Logging.Level, - Format: cfg.Logging.Format, + Level: cfg.Logging.Level, + Format: cfg.Logging.Format, + OutputPath: cfg.Logging.OutputPath, + MaxSizeMB: cfg.Logging.MaxSizeMB, + MaxBackups: cfg.Logging.MaxBackups, + MaxAgeDays: cfg.Logging.MaxAgeDays, + Compress: cfg.Logging.Compress, }) if err != nil { fmt.Fprintf(os.Stderr, "Failed to initialize logger: %v\n", err) @@ -326,7 +331,7 @@ func startAgentInfrastructure( // ============================================ log.Info("Initializing Orchestrator...") - orchestratorSvc, msgCreator, err := provideOrchestrator(cfg, log, eventBus, repos.Task, services.Task, services.User, + orchestratorSvc, msgCreator, err := provideOrchestrator(cfg, log, dbPool, eventBus, repos.Task, services.Task, services.User, lifecycleMgr, agentRegistry, services.Workflow, repos.Secrets, repoCloner) if err != nil { log.Error("Failed to initialize orchestrator", zap.Error(err)) @@ -554,6 +559,7 @@ func buildHTTPServer( services: services, agentSettingsController: agentSettingsController, agentList: agentRegistry, + agentRegistry: agentRegistry, userCtrl: usercontroller.NewController(services.User), notificationCtrl: notificationCtrl, editorCtrl: editorcontroller.NewController(services.Editor), diff --git a/apps/backend/cmd/kandev/orchestrator.go b/apps/backend/cmd/kandev/orchestrator.go index 0db11f75d7..a83e71e307 100644 --- a/apps/backend/cmd/kandev/orchestrator.go +++ b/apps/backend/cmd/kandev/orchestrator.go @@ -7,6 +7,7 @@ import ( "fmt" "os" "path/filepath" + "strconv" "strings" "go.uber.org/zap" @@ -15,10 +16,12 @@ import ( "github.com/kandev/kandev/internal/agent/registry" "github.com/kandev/kandev/internal/common/config" "github.com/kandev/kandev/internal/common/logger" + "github.com/kandev/kandev/internal/db" "github.com/kandev/kandev/internal/events/bus" jirapkg "github.com/kandev/kandev/internal/jira" linearpkg "github.com/kandev/kandev/internal/linear" "github.com/kandev/kandev/internal/orchestrator" + "github.com/kandev/kandev/internal/orchestrator/messagequeue" "github.com/kandev/kandev/internal/repoclone" "github.com/kandev/kandev/internal/secrets" taskmodels "github.com/kandev/kandev/internal/task/models" @@ -34,6 +37,7 @@ const defaultEventNamespace = "default" func provideOrchestrator( cfg *config.Config, log *logger.Logger, + pool *db.Pool, eventBus bus.EventBus, taskRepo *sqliterepo.Repository, taskSvc *taskservice.Service, @@ -63,7 +67,17 @@ func provideOrchestrator( zap.String("event_namespace", namespace), zap.String("queue_group", serviceCfg.QueueGroup), zap.Int("agent_standalone_port", cfg.Agent.StandalonePort)) - orchestratorSvc := orchestrator.NewService(serviceCfg, eventBus, agentManagerClient, taskRepoAdapter, taskRepo, userSvc, secretStore, log) + + queueRepo, err := messagequeue.NewSQLiteRepository(pool.Writer(), pool.Reader()) + if err != nil { + return nil, nil, fmt.Errorf("init message queue repo: %w", err) + } + maxPerSession := resolveQueueMaxPerSession(log) + msgQueue := messagequeue.NewService(queueRepo, maxPerSession, log) + log.Info("Message queue initialized", + zap.Int("max_per_session", maxPerSession)) + + orchestratorSvc := orchestrator.NewService(serviceCfg, eventBus, agentManagerClient, taskRepoAdapter, taskRepo, userSvc, secretStore, msgQueue, log) taskSvc.SetExecutionStopper(orchestratorSvc) taskSvc.SetGitArchiveCapture(orchestratorSvc) @@ -117,6 +131,25 @@ func provideOrchestrator( return orchestratorSvc, msgCreator, nil } +// resolveQueueMaxPerSession honors the KANDEV_QUEUE_MAX_PER_SESSION env var, +// falling back to messagequeue.DefaultMaxPerSession (10) when unset or invalid. +// Values <= 0 disable the cap entirely (callers can still flood queues — only +// useful in tests / specialized deployments). +func resolveQueueMaxPerSession(log *logger.Logger) int { + raw := strings.TrimSpace(os.Getenv("KANDEV_QUEUE_MAX_PER_SESSION")) + if raw == "" { + return messagequeue.DefaultMaxPerSession + } + n, err := strconv.Atoi(raw) + if err != nil { + log.Warn("KANDEV_QUEUE_MAX_PER_SESSION is not a number, using default", + zap.String("value", raw), + zap.Int("default", messagequeue.DefaultMaxPerSession)) + return messagequeue.DefaultMaxPerSession + } + return n +} + func resolveEventNamespace(cfg *config.Config) string { if cfg == nil { return defaultEventNamespace diff --git a/apps/backend/config/workflows/plan-and-build.yml b/apps/backend/config/workflows/plan-and-build.yml index 337f4bcbd1..6862737c4c 100644 --- a/apps/backend/config/workflows/plan-and-build.yml +++ b/apps/backend/config/workflows/plan-and-build.yml @@ -53,6 +53,8 @@ steps: on_enter: - type: enable_plan_mode - type: auto_start_agent + on_exit: + - type: disable_plan_mode - id: implementation name: Implementation diff --git a/apps/backend/go.mod b/apps/backend/go.mod index 19118df39c..2db8acdccc 100644 --- a/apps/backend/go.mod +++ b/apps/backend/go.mod @@ -109,6 +109,7 @@ require ( google.golang.org/grpc v1.80.0 // indirect google.golang.org/protobuf v1.36.11 // indirect gopkg.in/ini.v1 v1.67.0 // indirect + gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect gotest.tools/v3 v3.5.2 // indirect ) diff --git a/apps/backend/go.sum b/apps/backend/go.sum index 682bc62122..c8fac48f30 100644 --- a/apps/backend/go.sum +++ b/apps/backend/go.sum @@ -683,6 +683,8 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EV gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= +gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/apps/backend/internal/agent/agents/agent.go b/apps/backend/internal/agent/agents/agent.go index 9aa5a4c37a..bf2fbf476c 100644 --- a/apps/backend/internal/agent/agents/agent.go +++ b/apps/backend/internal/agent/agents/agent.go @@ -70,6 +70,25 @@ type PassthroughAgent interface { BuildPassthroughCommand(opts PassthroughOptions) Command } +// LoginCommand describes an interactive CLI command for authenticating with +// an agent. The kandev backend runs this under a PTY so the UI can render a +// terminal and route keystrokes to the underlying process. +type LoginCommand struct { + // Cmd is the command + args to spawn, e.g. []string{"claude", "auth", "login"}. + Cmd []string + // Description renders above the terminal as a one-line hint, e.g. + // "Authenticate with your Anthropic account." + Description string +} + +// LoginAgent is an optional capability for agents that need an interactive +// login flow (browser OAuth callback, token prompt, etc.). Implement it to +// surface a "Login" button in the UI that opens a PTY-backed terminal running +// LoginCommand(). +type LoginAgent interface { + LoginCommand() *LoginCommand +} + // IsPassthroughOnly returns true if the agent only supports passthrough mode // and should not have interactive MCP tools (e.g. ask_user_question) registered. func IsPassthroughOnly(a Agent) bool { diff --git a/apps/backend/internal/agent/agents/auggie.go b/apps/backend/internal/agent/agents/auggie.go index 22b70b7983..601822a4a5 100644 --- a/apps/backend/internal/agent/agents/auggie.go +++ b/apps/backend/internal/agent/agents/auggie.go @@ -127,6 +127,14 @@ func (a *Auggie) RemoteAuth() *RemoteAuth { } } +// Verified per Augment Code docs: "Run `auggie login` and follow the prompts." +func (a *Auggie) LoginCommand() *LoginCommand { + return &LoginCommand{ + Cmd: []string{"auggie", "login"}, + Description: "Sign in with your Augment Code account.", + } +} + func (a *Auggie) InstallScript() string { return "npm install -g " + auggiePkg } diff --git a/apps/backend/internal/agent/agents/claude_acp.go b/apps/backend/internal/agent/agents/claude_acp.go index 7f65bfaa34..6614ff28d9 100644 --- a/apps/backend/internal/agent/agents/claude_acp.go +++ b/apps/backend/internal/agent/agents/claude_acp.go @@ -127,8 +127,20 @@ chmod 600 "${HOME}/.claude.json"`, } } +// Verified: `claude --help` documents `claude auth login` as the dedicated +// sign-in subcommand (also `claude auth logout` / `claude auth status`). +// Source: https://code.claude.com/docs/en/cli-reference +func (a *ClaudeACP) LoginCommand() *LoginCommand { + return &LoginCommand{ + Cmd: []string{"claude", "auth", "login"}, + Description: "Sign in with your Anthropic account.", + } +} + func (a *ClaudeACP) InstallScript() string { - return "npm install -g " + claudeACPPkg + // Install both the user-facing Anthropic CLI (which IsInstalled probes for + // and which `claude /login` runs against) and the ACP bridge package. + return "npm install -g @anthropic-ai/claude-code " + claudeACPPkg } func (a *ClaudeACP) PermissionSettings() map[string]PermissionSetting { diff --git a/apps/backend/internal/agent/agents/codex_acp.go b/apps/backend/internal/agent/agents/codex_acp.go index a373cf39b4..7a8a268596 100644 --- a/apps/backend/internal/agent/agents/codex_acp.go +++ b/apps/backend/internal/agent/agents/codex_acp.go @@ -125,8 +125,22 @@ func (a *CodexACP) RemoteAuth() *RemoteAuth { } } +// Verified against `codex --help`: `codex login --device-auth` is the +// dedicated sign-in subcommand. Device-auth prints a code + URL that works +// even when the kandev process can't open a browser (containers, SSH, +// headless dev boxes), and falls back to a local browser flow otherwise. +func (a *CodexACP) LoginCommand() *LoginCommand { + return &LoginCommand{ + Cmd: []string{"codex", "login", "--device-auth"}, + Description: "Sign in with your OpenAI account.", + } +} + +// Install both the user-facing OpenAI codex CLI (which `codex login` runs +// against) and the ACP bridge package — the bridge wraps codex internally +// and depends on it being on PATH. func (a *CodexACP) InstallScript() string { - return "npm install -g " + codexACPPkg + return "npm install -g @openai/codex " + codexACPPkg } func (a *CodexACP) PermissionSettings() map[string]PermissionSetting { diff --git a/apps/backend/internal/agent/agents/copilot_acp.go b/apps/backend/internal/agent/agents/copilot_acp.go index fd73bc21fd..f6bae2683b 100644 --- a/apps/backend/internal/agent/agents/copilot_acp.go +++ b/apps/backend/internal/agent/agents/copilot_acp.go @@ -100,6 +100,15 @@ func (a *CopilotACP) Runtime() *RuntimeConfig { func (a *CopilotACP) RemoteAuth() *RemoteAuth { return nil } +// Verified per the user: `copilot login` is the dedicated sign-in +// subcommand for the GitHub Copilot CLI. +func (a *CopilotACP) LoginCommand() *LoginCommand { + return &LoginCommand{ + Cmd: []string{"copilot", "login"}, + Description: "Sign in with your GitHub account.", + } +} + func (a *CopilotACP) InstallScript() string { return "npm install -g " + copilotACPPkg } @@ -118,8 +127,12 @@ func (a *CopilotACP) PermissionSettings() map[string]PermissionSetting { // frames. Only `--allow-all-tools` and the other `--allow-all-*` flags do. var copilotPermSettings = map[string]PermissionSetting{ "allow_all_tools": { - Supported: true, - Default: false, + Supported: true, + // Enabled by default so autonomous runs don't stall on per-tool-call + // permission_request frames. kandev's UI can still surface and approve + // them, but for typical orchestration it's just noise. The other + // --allow-all-* toggles stay off as security defaults. + Default: true, Label: "Allow all tools", Description: "Skip confirmation for every tool call (--allow-all-tools)", ApplyMethod: PermissionApplyMethodCLIFlag, diff --git a/apps/backend/internal/agent/agents/copilot_acp_test.go b/apps/backend/internal/agent/agents/copilot_acp_test.go index b262eb74bf..db4a10e46e 100644 --- a/apps/backend/internal/agent/agents/copilot_acp_test.go +++ b/apps/backend/internal/agent/agents/copilot_acp_test.go @@ -3,15 +3,23 @@ package agents import "testing" // TestCopilotACP_PermissionSettings_Curated verifies the four curated flag -// suggestions surfaced to the profile-creation UI. These seed new profiles -// (all disabled by default) and are the origin of the fix for Copilot's -// permission-prompt-every-tool-call behaviour reported by users. +// suggestions surfaced to the profile-creation UI. `allow_all_tools` is +// enabled by default so autonomous runs don't stall on per-tool-call +// permission prompts; the other --allow-all-* and --no-ask-user toggles +// stay off as safe defaults. func TestCopilotACP_PermissionSettings_Curated(t *testing.T) { ag := NewCopilotACP() settings := ag.PermissionSettings() - wantKeys := []string{"allow_all_tools", "allow_all_paths", "allow_all_urls", "no_ask_user"} - for _, k := range wantKeys { + // Pin the expected default for each curated key. Anything not listed + // here defaults off. + wantDefault := map[string]bool{ + "allow_all_tools": true, + "allow_all_paths": false, + "allow_all_urls": false, + "no_ask_user": false, + } + for k, want := range wantDefault { s, ok := settings[k] if !ok { t.Fatalf("missing curated setting %q", k) @@ -19,8 +27,8 @@ func TestCopilotACP_PermissionSettings_Curated(t *testing.T) { if !s.Supported { t.Errorf("%q should be Supported=true", k) } - if s.Default { - t.Errorf("%q should default to Enabled=false so new profiles are safe", k) + if s.Default != want { + t.Errorf("%q Default = %v, want %v", k, s.Default, want) } if s.ApplyMethod != "cli_flag" { t.Errorf("%q should apply as cli_flag, got %q", k, s.ApplyMethod) diff --git a/apps/backend/internal/agent/agents/gemini.go b/apps/backend/internal/agent/agents/gemini.go index 10166baa07..822e0bbddb 100644 --- a/apps/backend/internal/agent/agents/gemini.go +++ b/apps/backend/internal/agent/agents/gemini.go @@ -114,6 +114,16 @@ func (a *Gemini) RemoteAuth() *RemoteAuth { } } +// Gemini has no dedicated login subcommand — the first run of `gemini` drops +// the user into the TUI's "Sign in with Google" flow. Spawn the bare CLI +// under the PTY so the user can complete that flow inline. +func (a *Gemini) LoginCommand() *LoginCommand { + return &LoginCommand{ + Cmd: []string{"gemini"}, + Description: "Sign in with your Google account (use the TUI's Sign in option, then quit).", + } +} + func (a *Gemini) InstallScript() string { return "npm install -g " + geminiPkg } diff --git a/apps/backend/internal/agent/agents/mock.go b/apps/backend/internal/agent/agents/mock.go index 81ab747957..b4bf74f5e2 100644 --- a/apps/backend/internal/agent/agents/mock.go +++ b/apps/backend/internal/agent/agents/mock.go @@ -111,7 +111,21 @@ func (a *MockAgent) Runtime() *RuntimeConfig { // requires no credentials. The empty methods list signals "no auth needed". func (a *MockAgent) RemoteAuth() *RemoteAuth { return &RemoteAuth{} } -func (a *MockAgent) InstallScript() string { return "" } +// InstallScript returns a deterministic short-lived shell script so e2e tests +// can exercise the install streaming endpoint without depending on npm. +func (a *MockAgent) InstallScript() string { + return "echo mock-install: step 1 && echo mock-install: step 2 && echo mock-install: done" +} + +// LoginCommand exposes a deterministic interactive command for e2e PTY tests. +// `cat` echoes any input back to the user; tests send "exit\n" or kill the +// session to terminate. +func (a *MockAgent) LoginCommand() *LoginCommand { + return &LoginCommand{ + Cmd: []string{"cat"}, + Description: "Mock login (echoes input).", + } +} func (a *MockAgent) PermissionSettings() map[string]PermissionSetting { return emptyPermSettings diff --git a/apps/backend/internal/agent/lifecycle/env_preparer.go b/apps/backend/internal/agent/lifecycle/env_preparer.go index e9b7a5b6d0..83cc9ae181 100644 --- a/apps/backend/internal/agent/lifecycle/env_preparer.go +++ b/apps/backend/internal/agent/lifecycle/env_preparer.go @@ -29,6 +29,7 @@ type RepoPrepareSpec struct { RepositoryPath string RepoName string BaseBranch string + DefaultBranch string // Repository's default_branch, used as fallback when BaseBranch is missing CheckoutBranch string WorktreeID string WorktreeBranch string @@ -51,6 +52,7 @@ type EnvPrepareRequest struct { SetupScript string RepoSetupScript string // Repository-level setup script (e.g. "make install") BaseBranch string + DefaultBranch string // Repository's default_branch, used as fallback when BaseBranch is missing CheckoutBranch string WorktreeID string WorktreeBranch string @@ -86,6 +88,7 @@ func (r *EnvPrepareRequest) RepoSpecs() []RepoPrepareSpec { RepositoryPath: r.RepositoryPath, RepoName: r.RepoName, BaseBranch: r.BaseBranch, + DefaultBranch: r.DefaultBranch, CheckoutBranch: r.CheckoutBranch, WorktreeID: r.WorktreeID, WorktreeBranch: r.WorktreeBranch, diff --git a/apps/backend/internal/agent/lifecycle/env_preparer_worktree.go b/apps/backend/internal/agent/lifecycle/env_preparer_worktree.go index a0ef0b8a8d..bdb66c3732 100644 --- a/apps/backend/internal/agent/lifecycle/env_preparer_worktree.go +++ b/apps/backend/internal/agent/lifecycle/env_preparer_worktree.go @@ -166,6 +166,7 @@ func (p *WorktreePreparer) createWorktreeWithSync( RepositoryID: req.RepositoryID, RepositoryPath: req.RepositoryPath, BaseBranch: req.BaseBranch, + FallbackBaseBranch: req.DefaultBranch, CheckoutBranch: req.CheckoutBranch, WorktreeBranchPrefix: req.WorktreeBranchPrefix, PullBeforeWorktree: req.PullBeforeWorktree, @@ -191,6 +192,14 @@ func (p *WorktreePreparer) createWorktreeWithSync( } completeStepSuccess(&step) + if wt.BaseBranchFallbackWarning != "" { + step.Warning = wt.BaseBranchFallbackWarning + step.WarningDetail = wt.BaseBranchFallbackDetail + } + // wt.FetchWarning is surfaced in the separate "Fetch PR branch" step + // rendered later in the pipeline. It can only be non-empty when + // req.CheckoutBranch != "" (it is set inside fetchBranchToLocal), so the + // two warnings always co-occur and FetchWarning is never silently dropped. steps = append(steps, step) reportProgress(onProgress, step, stepIdx, totalSteps) return wt, steps, stepIdx + 1, nil @@ -356,6 +365,7 @@ func (p *WorktreePreparer) prepareOneRepo( subReq.RepositoryPath = spec.RepositoryPath subReq.RepoName = spec.RepoName subReq.BaseBranch = spec.BaseBranch + subReq.DefaultBranch = spec.DefaultBranch subReq.CheckoutBranch = spec.CheckoutBranch subReq.WorktreeID = spec.WorktreeID subReq.WorktreeBranchPrefix = spec.WorktreeBranchPrefix diff --git a/apps/backend/internal/agent/lifecycle/manager_launch.go b/apps/backend/internal/agent/lifecycle/manager_launch.go index de780fd788..9c9b83bc89 100644 --- a/apps/backend/internal/agent/lifecycle/manager_launch.go +++ b/apps/backend/internal/agent/lifecycle/manager_launch.go @@ -472,6 +472,7 @@ func buildEnvPrepareRequest(req *LaunchRequest, workspacePath string, execName e SetupScript: req.SetupScript, RepoSetupScript: repoSetupScript, BaseBranch: req.BaseBranch, + DefaultBranch: req.DefaultBranch, CheckoutBranch: req.CheckoutBranch, WorktreeBranch: getMetadataString(req.Metadata, MetadataKeyWorktreeBranch), WorktreeBranchPrefix: req.WorktreeBranchPrefix, @@ -495,6 +496,7 @@ func buildEnvPrepareRequest(req *LaunchRequest, workspacePath string, execName e RepositoryPath: r.RepositoryPath, RepoName: r.RepoName, BaseBranch: r.BaseBranch, + DefaultBranch: r.DefaultBranch, CheckoutBranch: r.CheckoutBranch, WorktreeID: r.WorktreeID, WorktreeBranchPrefix: r.WorktreeBranchPrefix, diff --git a/apps/backend/internal/agent/lifecycle/types.go b/apps/backend/internal/agent/lifecycle/types.go index a7ff2d45d0..b181333413 100644 --- a/apps/backend/internal/agent/lifecycle/types.go +++ b/apps/backend/internal/agent/lifecycle/types.go @@ -281,6 +281,7 @@ type RepoLaunchSpec struct { RepositoryURL string // Clone URL for remote executors that need to clone RepoName string // Repository name used as subdirectory inside TaskDirName BaseBranch string + DefaultBranch string // Repository's default_branch, used as fallback when BaseBranch is missing CheckoutBranch string WorktreeID string // Existing worktree ID to reuse (skip creation if set) WorktreeBranchPrefix string @@ -323,6 +324,7 @@ type LaunchRequest struct { RepositoryID string // Repository ID for worktree tracking RepositoryPath string // Path to the main repository (for worktree creation) BaseBranch string // Base branch for the worktree (e.g., "main") + DefaultBranch string // Repository's default_branch, used as fallback when BaseBranch is missing CheckoutBranch string // Branch to fetch and checkout after worktree creation (e.g., PR head branch) WorktreeBranchPrefix string // Branch prefix for worktree branches PullBeforeWorktree bool // Whether to pull from remote before creating the worktree @@ -354,6 +356,7 @@ func (r *LaunchRequest) RepoSpecs() []RepoLaunchSpec { RepositoryPath: r.RepositoryPath, RepoName: r.RepoName, BaseBranch: r.BaseBranch, + DefaultBranch: r.DefaultBranch, CheckoutBranch: r.CheckoutBranch, WorktreeID: r.WorktreeID, WorktreeBranchPrefix: r.WorktreeBranchPrefix, diff --git a/apps/backend/internal/agent/loginpty/handlers.go b/apps/backend/internal/agent/loginpty/handlers.go new file mode 100644 index 0000000000..d1bffdccc4 --- /dev/null +++ b/apps/backend/internal/agent/loginpty/handlers.go @@ -0,0 +1,346 @@ +package loginpty + +import ( + "encoding/json" + "net/http" + "net/url" + "os" + "os/exec" + "strings" + + "github.com/gin-gonic/gin" + gorillaws "github.com/gorilla/websocket" + "go.uber.org/zap" + + "github.com/kandev/kandev/internal/agent/agents" + "github.com/kandev/kandev/internal/agent/registry" +) + +// LoginCommandLookup returns the agent's LoginCommand or nil. Implemented by +// the registry so we don't import agent/settings here. +type LoginCommandLookup interface { + Get(id string) (agents.Agent, bool) +} + +// Handlers wraps the manager + agent registry to expose HTTP/WS endpoints. +type Handlers struct { + mgr *Manager + registry *registry.Registry + logger *zap.Logger + upgrader gorillaws.Upgrader +} + +// NewHandlers constructs Handlers. If checkOrigin is nil, the upgrader uses +// the default localhost-friendly check below — needed because gorilla's +// stock CheckOrigin rejects cross-origin (e.g. Next dev on :37429 → backend +// on :38429). +func NewHandlers(mgr *Manager, reg *registry.Registry, log *zap.Logger, checkOrigin func(*http.Request) bool) *Handlers { + if checkOrigin == nil { + checkOrigin = defaultCheckOrigin + } + up := gorillaws.Upgrader{ + ReadBufferSize: 4096, + WriteBufferSize: 4096, + CheckOrigin: checkOrigin, + } + return &Handlers{ + mgr: mgr, + registry: reg, + logger: log, + upgrader: up, + } +} + +// defaultCheckOrigin mirrors the policy used by the existing terminal +// handler: allow no-origin requests (non-browser clients), allow loopback +// origins (dev), otherwise require Origin host to match Request host. +// +// Loopback is matched by exact hostname after parsing — a HasPrefix check +// against `http://localhost` would also accept `http://localhost.attacker.tld`, +// which a hostile page could use to slip through the dev exception. +func defaultCheckOrigin(r *http.Request) bool { + origin := r.Header.Get("Origin") + if origin == "" { + return true + } + originURL, err := url.Parse(origin) + if err != nil { + return false + } + switch originURL.Hostname() { + case "localhost", "127.0.0.1", "::1": + return true + } + host := r.Host + if host == "" { + host = r.URL.Host + } + // Strip port for flexibility (but keep IPv6 brackets intact). + if colonIdx := strings.LastIndex(host, ":"); colonIdx != -1 { + if !strings.Contains(host, "]") || colonIdx > strings.Index(host, "]") { + host = host[:colonIdx] + } + } + return originURL.Hostname() == host +} + +// RegisterRoutes mounts the login-pty endpoints on the given router. +// Routes are split into agents/* (lookup by agent name) and sessions/* (lookup +// by session ID) so gin doesn't see two routes sharing a wildcard slot with +// different param names. +// +// The /host-shell/start route reuses the same session-manager infrastructure +// to spawn a plain user shell — handy for ad-hoc install/setup commands the +// install button doesn't cover. +func (h *Handlers) RegisterRoutes(r *gin.Engine) { + api := r.Group("/api/v1") + api.POST("/agent-login/agents/:agentName/start", h.httpStart) + api.POST("/agent-login/sessions/:sessionID/stop", h.httpStop) + api.POST("/agent-login/sessions/:sessionID/resize", h.httpResize) + api.GET("/agent-login/sessions/:sessionID/status", h.httpStatus) + api.GET("/agent-login/sessions/:sessionID/stream", h.handleStream) + api.POST("/host-shell/start", h.httpStartHostShell) +} + +// hostShellAgentID is the synthetic key the session manager uses for host +// shell sessions so they don't collide with agent login sessions. +const hostShellAgentID = "_host_shell" + +// httpStartHostShell spawns the user's $SHELL (or /bin/bash, then /bin/sh) +// under a PTY. Returns the standard session snapshot — the client uses the +// same stop/resize/stream endpoints. +func (h *Handlers) httpStartHostShell(c *gin.Context) { + var req startRequest + _ = c.ShouldBindJSON(&req) + + shell := detectShell() + sess, err := h.mgr.Start(hostShellAgentID, []string{shell}, req.Cols, req.Rows) + if err != nil && err != ErrSessionAlreadyRunning { + h.logger.Warn("host shell start failed", zap.Error(err)) + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + c.JSON(http.StatusOK, sess.Status()) +} + +// detectShell picks a sensible interactive shell, preferring $SHELL. +func detectShell() string { + if s := os.Getenv("SHELL"); s != "" { + if _, err := exec.LookPath(s); err == nil { + return s + } + } + for _, candidate := range []string{"/bin/bash", "/bin/zsh", "/bin/sh"} { + if _, err := os.Stat(candidate); err == nil { + return candidate + } + } + return "/bin/sh" +} + +type startRequest struct { + Cols uint16 `json:"cols"` + Rows uint16 `json:"rows"` +} + +func (h *Handlers) httpStart(c *gin.Context) { + name := strings.TrimSpace(c.Param("agentName")) + if name == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "agent name is required"}) + return + } + ag, ok := h.registry.Get(name) + if !ok { + c.JSON(http.StatusNotFound, gin.H{"error": "agent not found"}) + return + } + loginAg, ok := ag.(agents.LoginAgent) + if !ok { + c.JSON(http.StatusBadRequest, gin.H{"error": "agent has no login command"}) + return + } + lc := loginAg.LoginCommand() + if lc == nil || len(lc.Cmd) == 0 { + c.JSON(http.StatusBadRequest, gin.H{"error": "agent has no login command"}) + return + } + + var req startRequest + _ = c.ShouldBindJSON(&req) // body is optional + + // Wrap the agent's login command so that when the login process exits + // (Ctrl+C, /quit, success exit, anything) the PTY drops the user into + // their normal shell instead of becoming a dead terminal. The user can + // then re-run the login, install a missing dep, or just close the + // dialog. + // + // `sh -c '"$@"; exec "${SHELL:-/bin/sh}"' wrapper ` lets sh do + // the argv parsing - no shell-escaping required on our side. + // + // `trap 'true' INT` stops the wrapper sh from dying when Ctrl+C is + // pressed (non-interactive sh exits on SIGINT by default). The child + // (codex/auggie/...) still receives SIGINT directly via the foreground + // process group, and exec(2) resets the trap to SIG_DFL in the child + // - so the agent dies as expected and sh survives to exec the shell. + wrapped := append( + []string{"sh", "-c", `trap 'true' INT; "$@"; exec "${SHELL:-/bin/sh}"`, "kandev-login-wrapper"}, + lc.Cmd..., + ) + sess, err := h.mgr.Start(name, wrapped, req.Cols, req.Rows) + if err != nil && err != ErrSessionAlreadyRunning { + h.logger.Warn("login session start failed", + zap.String("agent", name), + zap.Error(err), + ) + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + c.JSON(http.StatusOK, sess.Status()) +} + +func (h *Handlers) httpStop(c *gin.Context) { + id := c.Param("sessionID") + sess := h.mgr.GetByID(id) + if sess == nil { + c.JSON(http.StatusNotFound, gin.H{"error": "session not found"}) + return + } + sess.stop() + c.JSON(http.StatusOK, gin.H{"ok": true}) +} + +type resizeRequest struct { + Cols uint16 `json:"cols"` + Rows uint16 `json:"rows"` +} + +func (h *Handlers) httpResize(c *gin.Context) { + id := c.Param("sessionID") + sess := h.mgr.GetByID(id) + if sess == nil { + c.JSON(http.StatusNotFound, gin.H{"error": "session not found"}) + return + } + var req resizeRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"}) + return + } + if err := sess.Resize(req.Cols, req.Rows); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + c.JSON(http.StatusOK, gin.H{"ok": true}) +} + +func (h *Handlers) httpStatus(c *gin.Context) { + id := c.Param("sessionID") + sess := h.mgr.GetByID(id) + if sess == nil { + c.JSON(http.StatusNotFound, gin.H{"error": "session not found"}) + return + } + c.JSON(http.StatusOK, sess.Status()) +} + +// handleStream upgrades to WS and proxies bytes both directions: +// - server → client: PTY output as BinaryMessage frames +// - client → server: +// - BinaryMessage frames = raw input to PTY (keystrokes) +// - TextMessage frames = JSON control msg: {"type":"resize","cols":N,"rows":M} +// +// On session exit the subscriber channel is closed; the writer goroutine +// detects this, sends a final TextMessage {"type":"exit","exit_code":N}, +// and the connection is closed. +func (h *Handlers) handleStream(c *gin.Context) { + id := c.Param("sessionID") + sess := h.mgr.GetByID(id) + if sess == nil { + c.JSON(http.StatusNotFound, gin.H{"error": "session not found"}) + return + } + + conn, err := h.upgrader.Upgrade(c.Writer, c.Request, nil) + if err != nil { + h.logger.Warn("login pty ws upgrade failed", + zap.String("session_id", id), + zap.Error(err), + ) + return + } + defer func() { _ = conn.Close() }() + + // Send buffered output up-front so a late-joining UI catches up. + if buf := sess.BufferedOutput(); len(buf) > 0 { + _ = conn.WriteMessage(gorillaws.BinaryMessage, buf) + } + + out := make(chan []byte, 128) + sess.Subscribe(out) + defer sess.Unsubscribe(out) + + done := make(chan struct{}) + // disconnect is closed by the reader on client disconnect so the writer + // can exit even when the PTY is silent (e.g. idle browser-OAuth flows). + // Without this, an abrupt client disconnect during an idle session leaks + // the writer goroutine for up to IdleTimeout. + disconnect := make(chan struct{}) + + // Writer: forward PTY output → client. + go func() { + defer close(done) + for { + select { + case data, ok := <-out: + if !ok { + // Channel closed: session ended. Send a final exit notice. + status := sess.Status() + payload := map[string]any{"type": "exit"} + if status.ExitCode != nil { + payload["exit_code"] = *status.ExitCode + } + b, _ := json.Marshal(payload) + _ = conn.WriteMessage(gorillaws.TextMessage, b) + return + } + if err := conn.WriteMessage(gorillaws.BinaryMessage, data); err != nil { + return + } + case <-disconnect: + return + } + } + }() + + // Reader: forward client → PTY (binary = input, text = JSON control). + for { + mt, data, err := conn.ReadMessage() + if err != nil { + break + } + switch mt { + case gorillaws.BinaryMessage: + if _, err := sess.Write(data); err != nil { + h.logger.Debug("pty write error", zap.Error(err)) + } + case gorillaws.TextMessage: + h.handleControlMessage(sess, data) + } + } + close(disconnect) + <-done +} + +func (h *Handlers) handleControlMessage(sess *Session, data []byte) { + var msg struct { + Type string `json:"type"` + Cols uint16 `json:"cols"` + Rows uint16 `json:"rows"` + } + if err := json.Unmarshal(data, &msg); err != nil { + return + } + if msg.Type == "resize" { + _ = sess.Resize(msg.Cols, msg.Rows) + } +} diff --git a/apps/backend/internal/agent/loginpty/manager.go b/apps/backend/internal/agent/loginpty/manager.go new file mode 100644 index 0000000000..a7b3e9ad50 --- /dev/null +++ b/apps/backend/internal/agent/loginpty/manager.go @@ -0,0 +1,490 @@ +// Package loginpty runs an agent's interactive login command under a PTY on +// the kandev host. The UI surfaces this as a terminal so users can complete +// browser-based or token-prompt auth flows without shelling into the +// container. +// +// Sessions are keyed by agent ID — at most one login PTY per agent runs at a +// time, since concurrent logins for the same agent would race on the same +// HOME dotfile. The session terminates when the command exits, on idle +// timeout, or on explicit Stop. +package loginpty + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "os/exec" + "sync" + "time" + + "github.com/creack/pty" + "github.com/google/uuid" + "github.com/kandev/kandev/internal/common/logger" + "go.uber.org/zap" +) + +const ( + // IdleTimeout terminates a session that hasn't produced output for this long. + // Picked to fit typical browser-OAuth flows (open browser → grant → callback). + IdleTimeout = 10 * time.Minute + + // HardTimeout is the wall-clock upper bound; covers stuck sessions. + HardTimeout = 30 * time.Minute + + // outputBufferSize is the rolling buffer of recent PTY output kept for + // late subscribers. Login flows are usually short so 16KB is plenty. + outputBufferSize = 16 * 1024 +) + +// Errors surfaced to callers. +var ( + ErrSessionAlreadyRunning = errors.New("login session already running for this agent") + ErrSessionNotFound = errors.New("login session not found") + ErrSessionNotRunning = errors.New("login session is not running") +) + +// Manager owns active login sessions and dispatches lifecycle callbacks. +type Manager struct { + mu sync.Mutex + sessions map[string]*Session // key: agentID + byID map[string]*Session // key: sessionID + log *logger.Logger + + // onExit is invoked from a goroutine when a session terminates (with the + // agent ID and exit code). Used by callers to invalidate discovery cache + // and broadcast updated availability. Optional. + onExit func(agentID string, exitCode int, exitErr error) +} + +// NewManager constructs a Manager. onExit may be nil. +func NewManager(log *logger.Logger, onExit func(agentID string, exitCode int, exitErr error)) *Manager { + return &Manager{ + sessions: map[string]*Session{}, + byID: map[string]*Session{}, + log: log.WithFields(zap.String("component", "login-pty")), + onExit: onExit, + } +} + +// Start spawns a PTY-backed process for the agent. Returns the session +// snapshot. Fails with ErrSessionAlreadyRunning if a session for this agent +// is already active. +func (m *Manager) Start(agentID string, cmd []string, cols, rows uint16) (*Session, error) { + if len(cmd) == 0 { + return nil, errors.New("empty command") + } + m.mu.Lock() + if existing, ok := m.sessions[agentID]; ok { + m.mu.Unlock() + _ = existing.Status() // touch + return existing, ErrSessionAlreadyRunning + } + + if cols == 0 { + cols = 80 + } + if rows == 0 { + rows = 24 + } + + sess := &Session{ + ID: uuid.NewString(), + AgentID: agentID, + Cmd: append([]string(nil), cmd...), + subscribers: map[chan<- []byte]struct{}{}, + log: m.log.WithFields(zap.String("agent", agentID)), + startedAt: time.Now(), + } + + if err := sess.start(cmd, cols, rows); err != nil { + m.mu.Unlock() + return nil, err + } + + m.sessions[agentID] = sess + m.byID[sess.ID] = sess + m.mu.Unlock() + + go m.supervise(sess) + return sess, nil +} + +// Get returns a session by agent ID (or nil). +func (m *Manager) Get(agentID string) *Session { + m.mu.Lock() + defer m.mu.Unlock() + return m.sessions[agentID] +} + +// GetByID returns a session by session ID (or nil). +func (m *Manager) GetByID(sessionID string) *Session { + m.mu.Lock() + defer m.mu.Unlock() + return m.byID[sessionID] +} + +// Stop terminates the agent's session if one is running. +func (m *Manager) Stop(agentID string) error { + m.mu.Lock() + sess, ok := m.sessions[agentID] + m.mu.Unlock() + if !ok { + return ErrSessionNotFound + } + sess.stop() + return nil +} + +// supervise watches the session's lifetime: waits on the process, enforces +// timeouts, then deletes the session from the manager and notifies onExit. +func (m *Manager) supervise(sess *Session) { + ctx, cancel := context.WithTimeout(context.Background(), HardTimeout) + defer cancel() + + exited := make(chan exitInfo, 1) + go func() { + err := sess.waitForCommand() + exited <- exitInfo{ + code: exitCodeFromError(err), + err: err, + } + }() + + idle := time.NewTimer(IdleTimeout) + defer idle.Stop() + + var info exitInfo +loop: + for { + select { + case info = <-exited: + break loop + case <-idle.C: + sess.log.Info("login session idle timeout — terminating") + sess.stop() + case <-ctx.Done(): + sess.log.Info("login session hard timeout — terminating") + sess.stop() + case <-sess.activityCh: + // Reset idle timer on output activity. + if !idle.Stop() { + select { + case <-idle.C: + default: + } + } + idle.Reset(IdleTimeout) + } + } + + // Wait for readLoop to drain remaining PTY output before flipping running=false + // or closing subscribers. Otherwise late Subscribe callers (or BufferedOutput + // readers) could observe an empty session even though the process produced + // output. The pty is closed by stop() in timeout paths and by the child + // exit in the natural path; either way readLoop returns shortly after. + // Cap the wait so a stuck PTY can't deadlock cleanup. + select { + case <-sess.readDone: + case <-time.After(2 * time.Second): + sess.log.Warn("readLoop did not exit in time during supervise cleanup") + } + + m.mu.Lock() + delete(m.sessions, sess.AgentID) + delete(m.byID, sess.ID) + m.mu.Unlock() + + sess.mu.Lock() + now := time.Now() + sess.finishedAt = &now + sess.exitCode = &info.code + sess.running = false + durationMs := now.Sub(sess.startedAt).Milliseconds() + sess.mu.Unlock() + + // Log the exit so we can tell apart "agent exited 0 silently" (e.g. + // already-authed) from "agent crashed". Suppress the noisy EOF error, + // which is just normal PTY closure. + exitErr := "" + if info.err != nil && info.err != io.EOF { + exitErr = info.err.Error() + } + sess.log.Info("login session ended", + zap.String("session_id", sess.ID), + zap.Int("exit_code", info.code), + zap.String("err", exitErr), + zap.Int64("duration_ms", durationMs), + ) + + sess.broadcastClose() + + if m.onExit != nil { + m.onExit(sess.AgentID, info.code, info.err) + } +} + +type exitInfo struct { + code int + err error +} + +func exitCodeFromError(err error) int { + if err == nil { + return 0 + } + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + return exitErr.ExitCode() + } + return -1 +} + +// Session is a single login PTY process plus its subscriber set. +// Exported fields are stable; everything else is internal. +type Session struct { + ID string + AgentID string + Cmd []string + + mu sync.Mutex + cmd *exec.Cmd + pty *os.File + running bool + startedAt time.Time + finishedAt *time.Time + exitCode *int + + subMu sync.Mutex + subscribers map[chan<- []byte]struct{} + subClosed bool // set under subMu by broadcastClose; once true, Subscribe closes the channel immediately + + bufMu sync.Mutex + buffer []byte + + activityCh chan struct{} // notifications to supervise loop on output + readDone chan struct{} // closed when readLoop exits (all PTY output drained) + + log *logger.Logger +} + +func (s *Session) start(cmd []string, cols, rows uint16) error { + s.activityCh = make(chan struct{}, 1) + s.readDone = make(chan struct{}) + c := exec.Command(cmd[0], cmd[1:]...) // #nosec G204 — command is hard-coded per agent + c.Env = buildLoginEnv() + + f, err := pty.StartWithSize(c, &pty.Winsize{Cols: cols, Rows: rows}) + if err != nil { + return fmt.Errorf("start pty: %w", err) + } + + s.cmd = c + s.pty = f + s.running = true + s.log.Info("login session started", + zap.String("session_id", s.ID), + zap.Strings("cmd", cmd), + zap.Int("pid", c.Process.Pid), + ) + go s.readLoop() + return nil +} + +func (s *Session) readLoop() { + defer close(s.readDone) + buf := make([]byte, 4096) + for { + n, err := s.pty.Read(buf) + if n > 0 { + data := make([]byte, n) + copy(data, buf[:n]) + s.appendBuffer(data) + s.broadcast(data) + select { + case s.activityCh <- struct{}{}: + default: + } + } + if err != nil { + if err != io.EOF { + s.log.Debug("pty read ended", zap.Error(err)) + } + return + } + } +} + +func (s *Session) appendBuffer(data []byte) { + s.bufMu.Lock() + defer s.bufMu.Unlock() + s.buffer = append(s.buffer, data...) + if len(s.buffer) > outputBufferSize { + s.buffer = s.buffer[len(s.buffer)-outputBufferSize:] + } +} + +// BufferedOutput returns a copy of the rolling output buffer for catching up +// new WS subscribers. +func (s *Session) BufferedOutput() []byte { + s.bufMu.Lock() + defer s.bufMu.Unlock() + if len(s.buffer) == 0 { + return nil + } + out := make([]byte, len(s.buffer)) + copy(out, s.buffer) + return out +} + +// Subscribe registers a channel for PTY output. The channel is non-blocking: +// if it fills up, chunks are dropped (the subscriber falls behind). +// +// If the session has already ended (broadcastClose ran), the channel is +// closed immediately so the caller's reader returns rather than blocking +// forever on a channel that nothing will ever send to or close. +// +// Both the close-check and the map insertion happen under subMu so a +// concurrent broadcastClose cannot race in between (which would otherwise +// leave the late subscriber registered in a fresh empty map with nothing +// to ever close it). +func (s *Session) Subscribe(ch chan<- []byte) { + s.subMu.Lock() + defer s.subMu.Unlock() + if s.subClosed { + close(ch) + return + } + s.subscribers[ch] = struct{}{} +} + +// Unsubscribe removes a channel from the subscriber set. +func (s *Session) Unsubscribe(ch chan<- []byte) { + s.subMu.Lock() + defer s.subMu.Unlock() + delete(s.subscribers, ch) +} + +func (s *Session) broadcast(data []byte) { + s.subMu.Lock() + defer s.subMu.Unlock() + for ch := range s.subscribers { + select { + case ch <- data: + default: + } + } +} + +// broadcastClose closes any remaining subscriber channels — used to wake WS +// loops on session exit. subClosed is set under subMu so any concurrent +// Subscribe taking subMu after this either observes subClosed and closes +// its own channel, or completed before us and is already in the snapshot. +func (s *Session) broadcastClose() { + s.subMu.Lock() + subs := s.subscribers + s.subscribers = map[chan<- []byte]struct{}{} + s.subClosed = true + s.subMu.Unlock() + for ch := range subs { + close(ch) + } +} + +// Write sends user input to the underlying process via the PTY. +func (s *Session) Write(p []byte) (int, error) { + s.mu.Lock() + pf := s.pty + running := s.running + s.mu.Unlock() + if !running || pf == nil { + return 0, ErrSessionNotRunning + } + return pf.Write(p) +} + +// Resize updates the PTY window size. +func (s *Session) Resize(cols, rows uint16) error { + s.mu.Lock() + pf := s.pty + running := s.running + s.mu.Unlock() + if !running || pf == nil { + return ErrSessionNotRunning + } + return pty.Setsize(pf, &pty.Winsize{Cols: cols, Rows: rows}) +} + +// Status snapshot for HTTP responses. +type Status struct { + ID string `json:"session_id"` + AgentID string `json:"agent_id"` + Cmd []string `json:"cmd"` + Running bool `json:"running"` + StartedAt time.Time `json:"started_at"` + FinishedAt *time.Time `json:"finished_at,omitempty"` + ExitCode *int `json:"exit_code,omitempty"` +} + +// Status returns a value snapshot of the session. +func (s *Session) Status() Status { + s.mu.Lock() + defer s.mu.Unlock() + st := Status{ + ID: s.ID, + AgentID: s.AgentID, + Cmd: append([]string(nil), s.Cmd...), + Running: s.running, + StartedAt: s.startedAt, + } + if s.finishedAt != nil { + f := *s.finishedAt + st.FinishedAt = &f + } + if s.exitCode != nil { + e := *s.exitCode + st.ExitCode = &e + } + return st +} + +// stop tears the PTY down idempotently. The `!s.running` guard is flipped +// *under the same lock* that we use to read pty/cmd, so concurrent callers +// (timeout case in supervise + external Manager.Stop, etc.) don't double- +// close the file descriptor on the way out. A double Close on *os.File is +// safe in isolation, but if the OS recycles the fd between the two Close() +// calls, the second close hits a different open file. +func (s *Session) stop() { + s.mu.Lock() + if !s.running { + s.mu.Unlock() + return + } + s.running = false + pf := s.pty + cmd := s.cmd + s.mu.Unlock() + + if pf != nil { + _ = pf.Close() + } + if cmd != nil && cmd.Process != nil { + _ = cmd.Process.Kill() + } +} + +func (s *Session) waitForCommand() error { + if s.cmd == nil { + return nil + } + return s.cmd.Wait() +} + +// buildLoginEnv composes the environment for the login subprocess. The user's +// HOME (where agents write credentials) is inherited from the kandev process. +func buildLoginEnv() []string { + env := os.Environ() + env = append(env, "TERM=xterm-256color", "LANG=C.UTF-8", "LC_ALL=C.UTF-8") + return env +} diff --git a/apps/backend/internal/agent/loginpty/manager_test.go b/apps/backend/internal/agent/loginpty/manager_test.go new file mode 100644 index 0000000000..2805a59ec0 --- /dev/null +++ b/apps/backend/internal/agent/loginpty/manager_test.go @@ -0,0 +1,159 @@ +package loginpty + +import ( + "bytes" + "errors" + "sync" + "testing" + "time" + + "github.com/kandev/kandev/internal/common/logger" +) + +func newTestManager(t *testing.T, onExit func(string, int, error)) *Manager { + t.Helper() + log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"}) + if err != nil { + t.Fatalf("logger: %v", err) + } + return NewManager(log, onExit) +} + +// drainOutput consumes the subscriber channel until it closes; returns all bytes received. +func drainOutput(sess *Session) []byte { + ch := make(chan []byte, 32) + sess.Subscribe(ch) + defer sess.Unsubscribe(ch) + + var buf bytes.Buffer + deadline := time.After(2 * time.Second) + for { + select { + case data, ok := <-ch: + if !ok { + return buf.Bytes() + } + buf.Write(data) + case <-deadline: + return buf.Bytes() + } + } +} + +func TestStart_RunsCommandAndExits(t *testing.T) { + exited := make(chan struct { + agent string + code int + }, 1) + mgr := newTestManager(t, func(agent string, code int, _ error) { + exited <- struct { + agent string + code int + }{agent, code} + }) + + sess, err := mgr.Start("test-agent", []string{"sh", "-c", "echo hello && exit 0"}, 80, 24) + if err != nil { + t.Fatalf("Start: %v", err) + } + if sess.ID == "" { + t.Fatal("expected session id") + } + + // Subscribe right away to catch the output (some may be missed if we race + // the readLoop; BufferedOutput() compensates after exit). + got := drainOutput(sess) + + select { + case info := <-exited: + if info.agent != "test-agent" { + t.Errorf("agent = %s", info.agent) + } + if info.code != 0 { + t.Errorf("code = %d, want 0", info.code) + } + case <-time.After(3 * time.Second): + t.Fatal("supervise loop did not fire onExit") + } + + // Output may have been received via the subscriber or buffered; check both. + combined := append([]byte(nil), got...) + combined = append(combined, sess.BufferedOutput()...) + if !bytes.Contains(combined, []byte("hello")) { + t.Errorf("expected 'hello' in output, got %q", combined) + } +} + +func TestStart_IdempotentPerAgent(t *testing.T) { + mgr := newTestManager(t, nil) + + first, err := mgr.Start("test-agent", []string{"sh", "-c", "sleep 5"}, 80, 24) + if err != nil { + t.Fatalf("first start: %v", err) + } + t.Cleanup(func() { _ = mgr.Stop("test-agent") }) + + second, err := mgr.Start("test-agent", []string{"sh", "-c", "sleep 5"}, 80, 24) + if !errors.Is(err, ErrSessionAlreadyRunning) { + t.Fatalf("err = %v, want ErrSessionAlreadyRunning", err) + } + if first.ID != second.ID { + t.Errorf("expected same session id, got %s and %s", first.ID, second.ID) + } +} + +func TestStart_EmptyCommand(t *testing.T) { + mgr := newTestManager(t, nil) + _, err := mgr.Start("test-agent", nil, 80, 24) + if err == nil { + t.Fatal("expected error for empty command") + } +} + +func TestStop_TerminatesRunningSession(t *testing.T) { + var wg sync.WaitGroup + wg.Add(1) + mgr := newTestManager(t, func(_ string, _ int, _ error) { + wg.Done() + }) + + _, err := mgr.Start("test-agent", []string{"sh", "-c", "sleep 30"}, 80, 24) + if err != nil { + t.Fatalf("Start: %v", err) + } + + if err := mgr.Stop("test-agent"); err != nil { + t.Fatalf("Stop: %v", err) + } + + done := make(chan struct{}) + go func() { wg.Wait(); close(done) }() + select { + case <-done: + case <-time.After(3 * time.Second): + t.Fatal("session did not exit after Stop") + } +} + +func TestWriteAndResize_WhenNotRunning(t *testing.T) { + mgr := newTestManager(t, nil) + sess, err := mgr.Start("test-agent", []string{"true"}, 80, 24) + if err != nil { + t.Fatalf("Start: %v", err) + } + // Wait for exit. + deadline := time.After(2 * time.Second) + for sess.Status().Running { + select { + case <-deadline: + t.Fatal("session never exited") + case <-time.After(20 * time.Millisecond): + } + } + if _, err := sess.Write([]byte("x")); !errors.Is(err, ErrSessionNotRunning) { + t.Errorf("Write err = %v, want ErrSessionNotRunning", err) + } + if err := sess.Resize(120, 40); !errors.Is(err, ErrSessionNotRunning) { + t.Errorf("Resize err = %v, want ErrSessionNotRunning", err) + } +} diff --git a/apps/backend/internal/agent/settings/controller/agent_discovery.go b/apps/backend/internal/agent/settings/controller/agent_discovery.go index 0ee25e52e2..d8f5d2461c 100644 --- a/apps/backend/internal/agent/settings/controller/agent_discovery.go +++ b/apps/backend/internal/agent/settings/controller/agent_discovery.go @@ -23,6 +23,10 @@ func (c *Controller) ListDiscovery(ctx context.Context) (*dto.ListDiscoveryRespo } payload := make([]dto.AgentDiscoveryDTO, 0, len(results)) for _, result := range results { + var loginCmd *dto.LoginCommandDTO + if ag, ok := c.agentRegistry.Get(result.Name); ok { + loginCmd = buildLoginCommandDTO(ag) + } payload = append(payload, dto.AgentDiscoveryDTO{ Name: result.Name, SupportsMCP: result.SupportsMCP, @@ -30,6 +34,7 @@ func (c *Controller) ListDiscovery(ctx context.Context) (*dto.ListDiscoveryRespo InstallationPaths: result.InstallationPaths, Available: result.Available, MatchedPath: result.MatchedPath, + LoginCommand: loginCmd, }) } return &dto.ListDiscoveryResponse{Agents: payload, Total: len(payload)}, nil @@ -120,6 +125,8 @@ func (c *Controller) buildAvailableAgentDTO(ctx context.Context, ag agents.Agent } } + loginCommand := buildLoginCommandDTO(ag) + return dto.AvailableAgentDTO{ Name: ag.ID(), DisplayName: displayName, @@ -134,10 +141,28 @@ func (c *Controller) buildAvailableAgentDTO(ctx context.Context, ag agents.Agent ModelConfig: modelConfig, PermissionSettings: permissionSettings, PassthroughConfig: passthroughConfig, + LoginCommand: loginCommand, UpdatedAt: now, } } +// buildLoginCommandDTO surfaces the interactive login command for agents that +// implement LoginAgent. Nil for agents without an interactive login. +func buildLoginCommandDTO(ag agents.Agent) *dto.LoginCommandDTO { + loginAg, ok := ag.(agents.LoginAgent) + if !ok { + return nil + } + lc := loginAg.LoginCommand() + if lc == nil || len(lc.Cmd) == 0 { + return nil + } + return &dto.LoginCommandDTO{ + Cmd: lc.Cmd, + Description: lc.Description, + } +} + // buildModelConfigFromHostUtility reads cached ACP probe data for the agent // type and produces a ModelConfigDTO with models, modes, and status. Agents // not in the probe cache (e.g. the mock agent used in E2E tests, which diff --git a/apps/backend/internal/agent/settings/controller/agent_install.go b/apps/backend/internal/agent/settings/controller/agent_install.go new file mode 100644 index 0000000000..8b702ae768 --- /dev/null +++ b/apps/backend/internal/agent/settings/controller/agent_install.go @@ -0,0 +1,62 @@ +package controller + +import ( + "errors" + "strings" + + "github.com/kandev/kandev/internal/agent/settings/dto" +) + +// ErrInstallScriptEmpty is returned when the agent has no install script defined. +var ErrInstallScriptEmpty = errors.New("agent has no install script") + +// ErrJobStoreUnavailable is returned when SetJobBroadcaster hasn't been called +// — i.e. handlers haven't registered yet, so there's no WS hub to stream to. +var ErrJobStoreUnavailable = errors.New("install job store unavailable") + +// EnqueueInstall starts (or returns the existing) async install job for the +// named agent. The script is hard-coded by the agent type, so no user input is +// ever shelled. Clients subscribe to WS notifications (agent.install.started, +// agent.install.output, agent.install.finished) for live progress, or poll +// /agent-install/jobs/:id for a snapshot. +func (c *Controller) EnqueueInstall(name string) (*dto.InstallJobDTO, error) { + if c.jobStore == nil { + return nil, ErrJobStoreUnavailable + } + ag, ok := c.agentRegistry.Get(name) + if !ok { + return nil, ErrAgentNotFound + } + script := strings.TrimSpace(ag.InstallScript()) + if script == "" { + return nil, ErrInstallScriptEmpty + } + job := c.jobStore.Enqueue(name, script) + // Get() takes the store mutex, so it's race-free; calling job.snapshot() + // directly here would read job.Status without the lock while the spawned + // goroutine may be writing it. + if snap, ok := c.jobStore.Get(job.ID); ok { + return snap, nil + } + // Job was evicted between Enqueue and Get (extremely unlikely with the + // configured retention window). Fall back to the unguarded snapshot. + snap := job.snapshot() + return &snap, nil +} + +// ListInstallJobs returns a snapshot of every active or recently-finished +// install job. Used by the UI on page mount to recover in-flight installs. +func (c *Controller) ListInstallJobs() []dto.InstallJobDTO { + if c.jobStore == nil { + return nil + } + return c.jobStore.ListAll() +} + +// GetInstallJob returns a snapshot of one job by ID, or nil if not found. +func (c *Controller) GetInstallJob(id string) (*dto.InstallJobDTO, bool) { + if c.jobStore == nil { + return nil, false + } + return c.jobStore.Get(id) +} diff --git a/apps/backend/internal/agent/settings/controller/agent_install_test.go b/apps/backend/internal/agent/settings/controller/agent_install_test.go new file mode 100644 index 0000000000..f4248d7492 --- /dev/null +++ b/apps/backend/internal/agent/settings/controller/agent_install_test.go @@ -0,0 +1,244 @@ +package controller + +import ( + "context" + "errors" + "strings" + "sync" + "testing" + "time" + + "github.com/kandev/kandev/internal/agent/agents" + "github.com/kandev/kandev/internal/agent/settings/dto" + ws "github.com/kandev/kandev/pkg/websocket" +) + +// installScriptAgent extends testAgent so we can set a non-empty install script. +type installScriptAgent struct { + testAgent + script string +} + +func (a *installScriptAgent) InstallScript() string { return a.script } + +// captureBroadcaster captures all WS messages emitted during the test. +type captureBroadcaster struct { + mu sync.Mutex + msg []*ws.Message +} + +func (b *captureBroadcaster) Broadcast(m *ws.Message) { + b.mu.Lock() + defer b.mu.Unlock() + b.msg = append(b.msg, m) +} + +func (b *captureBroadcaster) actions() []string { + b.mu.Lock() + defer b.mu.Unlock() + out := make([]string, len(b.msg)) + for i, m := range b.msg { + out[i] = m.Action + } + return out +} + +// withStubStreamingRunner swaps streamingInstallRunner for the duration of +// the test. The stub invokes onChunk synchronously to make ordering deterministic. +func withStubStreamingRunner(t *testing.T, fn func(ctx context.Context, script string, onChunk func(string)) error) { + t.Helper() + prev := streamingInstallRunner + streamingInstallRunner = fn + t.Cleanup(func() { streamingInstallRunner = prev }) +} + +func newInstallController(t *testing.T, ag agents.Agent) (*Controller, *captureBroadcaster) { + t.Helper() + ctrl := newTestController(map[string]agents.Agent{ag.ID(): ag}) + hub := &captureBroadcaster{} + ctrl.SetJobBroadcaster(hub) + return ctrl, hub +} + +// waitForStatus polls until the job hits one of the terminal statuses or the +// deadline expires. +func waitForStatus(t *testing.T, ctrl *Controller, jobID string, want ...dto.InstallJobStatus) *dto.InstallJobDTO { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + snap, ok := ctrl.GetInstallJob(jobID) + if ok { + for _, w := range want { + if snap.Status == w { + return snap + } + } + } + time.Sleep(10 * time.Millisecond) + } + t.Fatalf("job %s did not reach status %v in time", jobID, want) + return nil +} + +func TestEnqueueInstall_StreamsAndSucceeds(t *testing.T) { + ag := &installScriptAgent{ + testAgent: testAgent{id: "test-agent", name: "test-agent", enabled: true}, + script: "echo ok", + } + ctrl, hub := newInstallController(t, ag) + + withStubStreamingRunner(t, func(_ context.Context, _ string, onChunk func(string)) error { + onChunk("installing...\n") + onChunk("done\n") + return nil + }) + + snap, err := ctrl.EnqueueInstall("test-agent") + if err != nil { + t.Fatalf("EnqueueInstall() error = %v", err) + } + if snap.JobID == "" { + t.Fatal("expected job_id") + } + + final := waitForStatus(t, ctrl, snap.JobID, dto.InstallJobStatusSucceeded) + if !strings.Contains(final.Output, "installing...") || !strings.Contains(final.Output, "done") { + t.Errorf("output missing stream chunks, got %q", final.Output) + } + if final.ExitCode == nil || *final.ExitCode != 0 { + t.Errorf("ExitCode = %v, want 0", final.ExitCode) + } + + // Must have broadcast a started and a finished message; output messages + // land in between but exact count depends on the flush timing. + actions := hub.actions() + if len(actions) < 2 { + t.Fatalf("expected ≥2 broadcasts, got %v", actions) + } + if actions[0] != ws.ActionAgentInstallStarted { + t.Errorf("first action = %s, want %s", actions[0], ws.ActionAgentInstallStarted) + } + if actions[len(actions)-1] != ws.ActionAgentInstallFinished { + t.Errorf("last action = %s, want %s", actions[len(actions)-1], ws.ActionAgentInstallFinished) + } +} + +func TestEnqueueInstall_Failure(t *testing.T) { + ag := &installScriptAgent{ + testAgent: testAgent{id: "test-agent", name: "test-agent", enabled: true}, + script: "exit 1", + } + ctrl, _ := newInstallController(t, ag) + + withStubStreamingRunner(t, func(_ context.Context, _ string, onChunk func(string)) error { + onChunk("npm ERR! boom\n") + return errors.New("exit status 1") + }) + + snap, err := ctrl.EnqueueInstall("test-agent") + if err != nil { + t.Fatalf("EnqueueInstall() error = %v", err) + } + + final := waitForStatus(t, ctrl, snap.JobID, dto.InstallJobStatusFailed) + if final.Error == "" { + t.Error("Error empty on failed install") + } + if !strings.Contains(final.Output, "npm ERR!") { + t.Errorf("Output missing stderr, got %q", final.Output) + } +} + +func TestEnqueueInstall_IdempotentWhileRunning(t *testing.T) { + ag := &installScriptAgent{ + testAgent: testAgent{id: "test-agent", name: "test-agent", enabled: true}, + script: "sleep", + } + ctrl, _ := newInstallController(t, ag) + + // Block the runner so the first job stays in 'running' while we call + // EnqueueInstall a second time. + release := make(chan struct{}) + withStubStreamingRunner(t, func(ctx context.Context, _ string, _ func(string)) error { + select { + case <-release: + return nil + case <-ctx.Done(): + return ctx.Err() + } + }) + + first, err := ctrl.EnqueueInstall("test-agent") + if err != nil { + t.Fatalf("first enqueue: %v", err) + } + second, err := ctrl.EnqueueInstall("test-agent") + if err != nil { + t.Fatalf("second enqueue: %v", err) + } + if first.JobID != second.JobID { + t.Errorf("expected same job_id, got %s and %s", first.JobID, second.JobID) + } + + // Release the runner and wait for the goroutine to finish before the test + // returns. Otherwise withStubStreamingRunner's restore cleanup races with + // the still-running goroutine's read of streamingInstallRunner. + close(release) + waitForStatus(t, ctrl, first.JobID, dto.InstallJobStatusSucceeded, dto.InstallJobStatusFailed) +} + +func TestEnqueueInstall_AgentNotFound(t *testing.T) { + ag := &installScriptAgent{ + testAgent: testAgent{id: "test-agent", name: "test-agent", enabled: true}, + script: "echo ok", + } + ctrl, _ := newInstallController(t, ag) + + _, err := ctrl.EnqueueInstall("missing") + if !errors.Is(err, ErrAgentNotFound) { + t.Fatalf("err = %v, want ErrAgentNotFound", err) + } +} + +func TestEnqueueInstall_EmptyScript(t *testing.T) { + ag := &installScriptAgent{ + testAgent: testAgent{id: "test-agent", name: "test-agent", enabled: true}, + script: " ", + } + ctrl, _ := newInstallController(t, ag) + + _, err := ctrl.EnqueueInstall("test-agent") + if !errors.Is(err, ErrInstallScriptEmpty) { + t.Fatalf("err = %v, want ErrInstallScriptEmpty", err) + } +} + +func TestEnqueueInstall_NoJobStore(t *testing.T) { + ag := &installScriptAgent{ + testAgent: testAgent{id: "test-agent", name: "test-agent", enabled: true}, + script: "echo ok", + } + // Construct without calling SetJobBroadcaster. + ctrl := newTestController(map[string]agents.Agent{ag.ID(): ag}) + + _, err := ctrl.EnqueueInstall("test-agent") + if !errors.Is(err, ErrJobStoreUnavailable) { + t.Fatalf("err = %v, want ErrJobStoreUnavailable", err) + } +} + +func TestRingBuffer_DropsOldestOnLineBoundary(t *testing.T) { + rb := newRingBuffer(20) + _, _ = rb.Write([]byte("first line\n")) + _, _ = rb.Write([]byte("second line\n")) + _, _ = rb.Write([]byte("third\n")) + got := rb.String() + // "first line\n" must have been evicted; the buffer holds the tail starting + // after the next newline boundary. + if strings.Contains(got, "first") { + t.Errorf("ring buffer should have evicted 'first', got %q", got) + } + if !strings.Contains(got, "third") { + t.Errorf("ring buffer missing newest write, got %q", got) + } +} diff --git a/apps/backend/internal/agent/settings/controller/controller.go b/apps/backend/internal/agent/settings/controller/controller.go index 403c2aabfd..50b4a1ad7e 100644 --- a/apps/backend/internal/agent/settings/controller/controller.go +++ b/apps/backend/internal/agent/settings/controller/controller.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "strings" + "time" "github.com/kandev/kandev/internal/agent/discovery" agentdto "github.com/kandev/kandev/internal/agent/dto" @@ -14,6 +15,7 @@ import ( "github.com/kandev/kandev/internal/agent/settings/modelfetcher" "github.com/kandev/kandev/internal/agent/settings/store" "github.com/kandev/kandev/internal/common/logger" + ws "github.com/kandev/kandev/pkg/websocket" "go.uber.org/zap" ) @@ -50,6 +52,8 @@ type Controller struct { mcpService *mcpconfig.Service modelCache *modelfetcher.Cache hostUtility *hostutility.Manager + jobStore *JobStore + hub JobBroadcaster logger *logger.Logger } @@ -88,3 +92,59 @@ func NewController(repo store.Repository, discoveryRegistry *discovery.Registry, func (c *Controller) SetHostUtility(h *hostutility.Manager) { c.hostUtility = h } + +// SetJobBroadcaster initializes the install job store with a WS broadcaster +// for streaming install progress. Called once during handler registration. +// If unset (hub == nil), the streaming install API returns +// ErrJobStoreUnavailable — without this guard a nil hub would silently +// degrade to a non-broadcasting store and the UI would never see progress. +func (c *Controller) SetJobBroadcaster(hub JobBroadcaster) { + c.hub = hub + if hub == nil { + c.jobStore = nil + return + } + c.jobStore = NewJobStore(hub, c.logger.Zap(), func(agentName string) { + c.InvalidateDiscoveryCache() + // Kick a fresh capability probe immediately so the UI doesn't sit on + // stale "not_installed" until the next periodic poll. When the probe + // finishes, re-broadcast the updated availability so any open profile + // page transitions out of "Probing…" without a manual refresh. + if c.hostUtility != nil { + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + if _, err := c.hostUtility.Refresh(ctx, agentName); err != nil { + c.logger.Debug("post-install capability refresh failed", + zap.String("agent", agentName), zap.Error(err)) + } + c.BroadcastAvailableAgents() + }() + } + c.logger.Info("install succeeded", zap.String("agent", agentName)) + }) +} + +// BroadcastAvailableAgents fetches the current available-agents snapshot and +// pushes it over WS as `agent.available.updated`. Used after install + probe +// so the UI flips from "probing" to the resolved status without a refresh. +func (c *Controller) BroadcastAvailableAgents() { + if c.hub == nil { + return + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + resp, err := c.ListAvailableAgents(ctx) + if err != nil { + c.logger.Debug("broadcast available agents: list failed", zap.Error(err)) + return + } + msg, err := ws.NewNotification(ws.ActionAgentAvailableUpdated, map[string]any{ + "agents": resp.Agents, + "tools": resp.Tools, + }) + if err != nil { + return + } + c.hub.Broadcast(msg) +} diff --git a/apps/backend/internal/agent/settings/controller/install_job.go b/apps/backend/internal/agent/settings/controller/install_job.go new file mode 100644 index 0000000000..f171b82278 --- /dev/null +++ b/apps/backend/internal/agent/settings/controller/install_job.go @@ -0,0 +1,387 @@ +package controller + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "io" + "os/exec" + "sync" + "time" + + "github.com/google/uuid" + "github.com/kandev/kandev/internal/agent/settings/dto" + ws "github.com/kandev/kandev/pkg/websocket" + "go.uber.org/zap" +) + +// Install job lifecycle: +// +// queued → running → succeeded +// ↘ failed +// +// Jobs are kept in memory for jobRetention after they finish so the UI can +// pick up the final state on reload before they evict. + +const ( + jobOutputRingSize = 64 * 1024 + jobRetention = 5 * time.Minute + jobMaxParallel = 4 + jobHardTimeout = 5 * time.Minute + outputFlushPeriod = 50 * time.Millisecond + outputFlushMaxSize = 4 * 1024 +) + +// InstallJob tracks a single install attempt. +type InstallJob struct { + ID string + AgentName string + Status dto.InstallJobStatus + Output *ringBuffer + StartedAt time.Time + FinishedAt *time.Time + ExitCode *int + Error string + + cancel context.CancelFunc +} + +// streamingInstallRunner exec's the script under a context, streaming each line +// to the provided callback. Swappable in tests. +var streamingInstallRunner = defaultStreamingInstallRunner + +func defaultStreamingInstallRunner( + ctx context.Context, + script string, + onChunk func(chunk string), +) error { + cmd := exec.CommandContext(ctx, "/bin/sh", "-c", script) + stdout, err := cmd.StdoutPipe() + if err != nil { + return err + } + stderr, err := cmd.StderrPipe() + if err != nil { + return err + } + if err := cmd.Start(); err != nil { + return err + } + + errCh := make(chan error, 2) + var wg sync.WaitGroup + wg.Add(2) + go pumpLines(stdout, onChunk, &wg, errCh) + go pumpLines(stderr, onChunk, &wg, errCh) + wg.Wait() + close(errCh) + + waitErr := cmd.Wait() + if waitErr != nil { + return waitErr + } + // If cmd.Wait succeeded but a scanner failed (e.g. token too long), + // surface the read error so the job is marked failed rather than + // silently succeeded with truncated output. + for scanErr := range errCh { + if scanErr != nil { + return scanErr + } + } + return nil +} + +func pumpLines(r io.Reader, onChunk func(string), wg *sync.WaitGroup, errCh chan<- error) { + defer wg.Done() + scanner := bufio.NewScanner(r) + // Lift the default 64KB limit — npm output can have long lines. + scanner.Buffer(make([]byte, 0, 64*1024), 1*1024*1024) + for scanner.Scan() { + onChunk(scanner.Text() + "\n") + } + if err := scanner.Err(); err != nil { + errCh <- err + } +} + +// JobStore owns active and recently-completed install jobs. +type JobStore struct { + mu sync.Mutex + jobs map[string]*InstallJob // by job_id + activeByAgt map[string]*InstallJob // by agent name (current/queued) + semaphore chan struct{} // bounded concurrency + hub JobBroadcaster + log *zap.Logger + onSuccess func(agentName string) // invoked when a job succeeds (used to invalidate discovery) +} + +// JobBroadcaster is the subset of the gateway Broadcaster we need. +type JobBroadcaster interface { + Broadcast(msg *ws.Message) +} + +// NewJobStore returns a fresh job store wired to the given broadcaster. +func NewJobStore(hub JobBroadcaster, log *zap.Logger, onSuccess func(string)) *JobStore { + return &JobStore{ + jobs: make(map[string]*InstallJob), + activeByAgt: make(map[string]*InstallJob), + semaphore: make(chan struct{}, jobMaxParallel), + hub: hub, + log: log, + onSuccess: onSuccess, + } +} + +// Enqueue starts (or returns an existing) install job for the named agent +// running the given hard-coded script. The script is supplied by the agent +// type, not by the request — no user-supplied shell input. +func (s *JobStore) Enqueue(agentName, script string) *InstallJob { + s.mu.Lock() + // Idempotent: a running/queued job for this agent reuses the same job_id. + if existing, ok := s.activeByAgt[agentName]; ok { + s.mu.Unlock() + return existing + } + job := &InstallJob{ + ID: uuid.NewString(), + AgentName: agentName, + Status: dto.InstallJobStatusQueued, + Output: newRingBuffer(jobOutputRingSize), + StartedAt: time.Now().UTC(), + } + s.jobs[job.ID] = job + s.activeByAgt[agentName] = job + s.mu.Unlock() + + s.broadcast(ws.ActionAgentInstallStarted, job.snapshot()) + go s.run(job, script) + return job +} + +// Get returns a snapshot of the job by ID. ok=false if not found. +func (s *JobStore) Get(jobID string) (*dto.InstallJobDTO, bool) { + s.mu.Lock() + defer s.mu.Unlock() + job, ok := s.jobs[jobID] + if !ok { + return nil, false + } + snap := job.snapshot() + return &snap, true +} + +// ListAll returns snapshots of every job currently retained (active + recently finished). +func (s *JobStore) ListAll() []dto.InstallJobDTO { + s.mu.Lock() + defer s.mu.Unlock() + out := make([]dto.InstallJobDTO, 0, len(s.jobs)) + for _, j := range s.jobs { + out = append(out, j.snapshot()) + } + return out +} + +func (s *JobStore) run(job *InstallJob, script string) { + // Bound parallel installs: queued jobs wait here until a slot frees up. + s.semaphore <- struct{}{} + defer func() { <-s.semaphore }() + + ctx, cancel := context.WithTimeout(context.Background(), jobHardTimeout) + s.mu.Lock() + job.cancel = cancel + job.Status = dto.InstallJobStatusRunning + s.mu.Unlock() + defer cancel() + + // Re-broadcast started so the UI flips queued→running. + s.broadcast(ws.ActionAgentInstallStarted, job.snapshot()) + + flusher := newOutputFlusher(s, job) + defer flusher.flush() + + err := streamingInstallRunner(ctx, script, flusher.append) + flusher.flush() + + s.mu.Lock() + now := time.Now().UTC() + job.FinishedAt = &now + if err == nil { + job.Status = dto.InstallJobStatusSucceeded + exit := 0 + job.ExitCode = &exit + } else { + job.Status = dto.InstallJobStatusFailed + job.Error = formatJobError(ctx, err) + if exit, ok := exitCodeOf(err); ok { + job.ExitCode = &exit + } + } + // Free the per-agent slot before notifying so a retry/auto-rescan + // triggered from onSuccess or the WS broadcast starts a fresh job + // instead of being deduped against this finished one. + delete(s.activeByAgt, job.AgentName) + jobID := job.ID + s.mu.Unlock() + + if err == nil && s.onSuccess != nil { + s.onSuccess(job.AgentName) + } + + s.broadcast(ws.ActionAgentInstallFinished, job.snapshot()) + + // Evict the finished job after retention. + time.AfterFunc(jobRetention, func() { + s.mu.Lock() + delete(s.jobs, jobID) + s.mu.Unlock() + }) +} + +func (s *JobStore) broadcast(action string, payload dto.InstallJobDTO) { + if s.hub == nil { + return + } + msg, _ := ws.NewNotification(action, payload) + s.hub.Broadcast(msg) +} + +func formatJobError(ctx context.Context, err error) string { + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + return fmt.Sprintf("install timed out after %s", jobHardTimeout) + } + return err.Error() +} + +func exitCodeOf(err error) (int, bool) { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + return exitErr.ExitCode(), true + } + return 0, false +} + +// snapshot returns a value copy of the job under the store lock. +// Caller is responsible for holding s.mu *or* calling on a job not yet inserted. +func (j *InstallJob) snapshot() dto.InstallJobDTO { + snap := dto.InstallJobDTO{ + JobID: j.ID, + Name: j.AgentName, + Status: j.Status, + Output: j.Output.String(), + StartedAt: j.StartedAt, + Error: j.Error, + } + if j.FinishedAt != nil { + finishedCopy := *j.FinishedAt + snap.FinishedAt = &finishedCopy + } + if j.ExitCode != nil { + exitCopy := *j.ExitCode + snap.ExitCode = &exitCopy + } + return snap +} + +// outputFlusher batches output chunks into broadcasts to limit WS message rate. +type outputFlusher struct { + store *JobStore + job *InstallJob + mu sync.Mutex + buf bytes.Buffer + timer *time.Timer +} + +func newOutputFlusher(store *JobStore, job *InstallJob) *outputFlusher { + return &outputFlusher{store: store, job: job} +} + +func (f *outputFlusher) append(chunk string) { + if chunk == "" { + return + } + f.mu.Lock() + f.buf.WriteString(chunk) + // Always append to the persistent ring buffer immediately so snapshots are + // up-to-date; broadcasts are batched. ringBuffer.Write never errs. + _, _ = f.job.Output.Write([]byte(chunk)) + size := f.buf.Len() + if size >= outputFlushMaxSize { + f.mu.Unlock() + f.flush() + return + } + if f.timer == nil { + f.timer = time.AfterFunc(outputFlushPeriod, f.flush) + } + f.mu.Unlock() +} + +func (f *outputFlusher) flush() { + f.mu.Lock() + if f.timer != nil { + f.timer.Stop() + f.timer = nil + } + if f.buf.Len() == 0 { + f.mu.Unlock() + return + } + chunk := f.buf.String() + f.buf.Reset() + f.mu.Unlock() + + if f.store.hub == nil { + return + } + payload := struct { + JobID string `json:"job_id"` + AgentName string `json:"agent_name"` + Chunk string `json:"chunk"` + }{ + JobID: f.job.ID, + AgentName: f.job.AgentName, + Chunk: chunk, + } + msg, _ := ws.NewNotification(ws.ActionAgentInstallOutput, payload) + f.store.hub.Broadcast(msg) +} + +// ringBuffer is a fixed-size byte buffer that drops the oldest data when full. +// Concurrent Write + String is safe. +type ringBuffer struct { + mu sync.Mutex + data []byte + cap int +} + +func newRingBuffer(cap int) *ringBuffer { + return &ringBuffer{cap: cap, data: make([]byte, 0, cap)} +} + +func (r *ringBuffer) Write(b []byte) (int, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.data = append(r.data, b...) + if len(r.data) > r.cap { + excess := len(r.data) - r.cap + // Compact: drop oldest 'excess' bytes plus enough to land on a line + // boundary, so the UI doesn't see a half-line. + nlIdx := bytes.IndexByte(r.data[excess:], '\n') + if nlIdx >= 0 { + excess += nlIdx + 1 + } + if excess > len(r.data) { + excess = len(r.data) + } + r.data = append(r.data[:0], r.data[excess:]...) + } + return len(b), nil +} + +func (r *ringBuffer) String() string { + r.mu.Lock() + defer r.mu.Unlock() + return string(r.data) +} diff --git a/apps/backend/internal/agent/settings/controller/profile_crud_test.go b/apps/backend/internal/agent/settings/controller/profile_crud_test.go index 8600de20d6..b3364e4592 100644 --- a/apps/backend/internal/agent/settings/controller/profile_crud_test.go +++ b/apps/backend/internal/agent/settings/controller/profile_crud_test.go @@ -8,14 +8,16 @@ import ( ) // TestSeedCLIFlags_FromCopilot verifies that a fresh Copilot profile gets -// the four curated CLI-flag suggestions with Enabled=false, so users see -// them in the UI but nothing changes subprocess behaviour until opt-in. +// the four curated CLI-flag suggestions seeded with the expected default +// state. `--allow-all-tools` is on by default so autonomous runs don't +// stall on per-tool-call permission prompts; the other --allow-all-* and +// --no-ask-user flags stay off as safe defaults until users opt in. func TestSeedCLIFlags_FromCopilot(t *testing.T) { ag := agents.NewCopilotACP() flags := seedCLIFlags(ag) wantFlags := map[string]bool{ - "--allow-all-tools": false, + "--allow-all-tools": true, "--allow-all-paths": false, "--allow-all-urls": false, "--no-ask-user": false, diff --git a/apps/backend/internal/agent/settings/dto/dto.go b/apps/backend/internal/agent/settings/dto/dto.go index 027f87823e..f2eb6b9ec1 100644 --- a/apps/backend/internal/agent/settings/dto/dto.go +++ b/apps/backend/internal/agent/settings/dto/dto.go @@ -63,12 +63,21 @@ type ListAgentsResponse struct { } type AgentDiscoveryDTO struct { - Name string `json:"name"` - SupportsMCP bool `json:"supports_mcp"` - MCPConfigPath string `json:"mcp_config_path,omitempty"` - InstallationPaths []string `json:"installation_paths,omitempty"` - Available bool `json:"available"` - MatchedPath string `json:"matched_path,omitempty"` + Name string `json:"name"` + SupportsMCP bool `json:"supports_mcp"` + MCPConfigPath string `json:"mcp_config_path,omitempty"` + InstallationPaths []string `json:"installation_paths,omitempty"` + Available bool `json:"available"` + MatchedPath string `json:"matched_path,omitempty"` + LoginCommand *LoginCommandDTO `json:"login_command,omitempty"` +} + +// LoginCommandDTO describes an interactive login command surfaced to the UI. +// The frontend uses it to render a "Login" button that opens a PTY terminal +// running the named command. +type LoginCommandDTO struct { + Cmd []string `json:"cmd"` + Description string `json:"description,omitempty"` } type ListDiscoveryResponse struct { @@ -150,6 +159,7 @@ type AvailableAgentDTO struct { ModelConfig ModelConfigDTO `json:"model_config"` PermissionSettings map[string]PermissionSettingDTO `json:"permission_settings,omitempty"` PassthroughConfig *PassthroughConfigDTO `json:"passthrough_config,omitempty"` + LoginCommand *LoginCommandDTO `json:"login_command,omitempty"` UpdatedAt time.Time `json:"updated_at"` } @@ -159,6 +169,41 @@ type ListAvailableAgentsResponse struct { Total int `json:"total"` } +// InstallJobStatus represents the state of an install job. +type InstallJobStatus string + +const ( + InstallJobStatusQueued InstallJobStatus = "queued" + InstallJobStatusRunning InstallJobStatus = "running" + InstallJobStatusSucceeded InstallJobStatus = "succeeded" + InstallJobStatusFailed InstallJobStatus = "failed" +) + +// InstallJobDTO is the snapshot of an install job returned via HTTP and +// broadcast via WS. +type InstallJobDTO struct { + JobID string `json:"job_id"` + Name string `json:"agent_name"` + Status InstallJobStatus `json:"status"` + Output string `json:"output,omitempty"` + Error string `json:"error,omitempty"` + ExitCode *int `json:"exit_code,omitempty"` + StartedAt time.Time `json:"started_at"` + FinishedAt *time.Time `json:"finished_at,omitempty"` +} + +// EnqueueInstallResponse is returned by POST /agent-install/:agentName. +// The install runs asynchronously; clients subscribe to WS notifications +// (agent.install.started/output/finished) or poll GET /agent-install/jobs. +type EnqueueInstallResponse struct { + JobID string `json:"job_id"` +} + +// ListInstallJobsResponse wraps the snapshot list for the jobs endpoint. +type ListInstallJobsResponse struct { + Jobs []InstallJobDTO `json:"jobs"` +} + type AgentProfileMcpConfigDTO struct { ProfileID string `json:"profile_id"` Enabled bool `json:"enabled"` diff --git a/apps/backend/internal/agent/settings/handlers/handlers.go b/apps/backend/internal/agent/settings/handlers/handlers.go index 4fe3aaf27a..9fae20e683 100644 --- a/apps/backend/internal/agent/settings/handlers/handlers.go +++ b/apps/backend/internal/agent/settings/handlers/handlers.go @@ -39,6 +39,9 @@ func NewHandlers(ctrl *controller.Controller, hub Broadcaster, log *logger.Logge } func RegisterRoutes(router *gin.Engine, ctrl *controller.Controller, hub Broadcaster, log *logger.Logger) { + // Wire the install job store with the same broadcaster used by other + // agent-settings notifications so streaming install events reach the UI. + ctrl.SetJobBroadcaster(hub) handlers := NewHandlers(ctrl, hub, log) handlers.registerHTTP(router) } @@ -57,6 +60,9 @@ func (h *Handlers) registerHTTP(router *gin.Engine) { api.GET("/agents/:id/logo", h.httpGetAgentLogo) api.GET("/agent-models/:agentName", h.httpGetAgentModels) api.POST("/agent-command-preview/:agentName", h.httpPreviewAgentCommand) + api.POST("/agent-install/:agentName", h.httpInstallAgent) + api.GET("/agent-install/jobs", h.httpListInstallJobs) + api.GET("/agent-install/jobs/:id", h.httpGetInstallJob) api.PATCH("/agent-profiles/:id", h.httpUpdateProfile) api.DELETE("/agent-profiles/:id", h.httpDeleteProfile) api.GET("/agent-profiles/:id/mcp-config", h.httpGetProfileMcpConfig) @@ -85,6 +91,54 @@ func (h *Handlers) httpListAvailableAgents(c *gin.Context) { c.JSON(http.StatusOK, resp) } +// httpInstallAgent enqueues an async install and returns the job snapshot. +// The install runs in a goroutine; clients track progress via WS +// (agent.install.started/output/finished) or by polling /agent-install/jobs/:id. +// +// Idempotent: a second POST for the same agent while a job is running returns +// the existing job_id rather than starting a duplicate. +func (h *Handlers) httpInstallAgent(c *gin.Context) { + name := strings.TrimSpace(c.Param("agentName")) + if name == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "agent name is required"}) + return + } + job, err := h.controller.EnqueueInstall(name) + if err != nil { + switch { + case errors.Is(err, controller.ErrAgentNotFound): + c.JSON(http.StatusNotFound, gin.H{"error": "agent not found"}) + case errors.Is(err, controller.ErrInstallScriptEmpty): + c.JSON(http.StatusBadRequest, gin.H{"error": "agent has no install script"}) + case errors.Is(err, controller.ErrJobStoreUnavailable): + c.JSON(http.StatusServiceUnavailable, gin.H{"error": "install service not ready"}) + default: + h.logger.Error("failed to enqueue install", zap.String("agent", name), zap.Error(err)) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to enqueue install"}) + } + return + } + c.JSON(http.StatusAccepted, job) +} + +func (h *Handlers) httpListInstallJobs(c *gin.Context) { + c.JSON(http.StatusOK, dto.ListInstallJobsResponse{Jobs: h.controller.ListInstallJobs()}) +} + +func (h *Handlers) httpGetInstallJob(c *gin.Context) { + id := strings.TrimSpace(c.Param("id")) + if id == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "job id is required"}) + return + } + job, ok := h.controller.GetInstallJob(id) + if !ok { + c.JSON(http.StatusNotFound, gin.H{"error": "job not found"}) + return + } + c.JSON(http.StatusOK, job) +} + func (h *Handlers) broadcastAvailableAgentsAsync() { if h.hub == nil { return diff --git a/apps/backend/internal/common/config/config.go b/apps/backend/internal/common/config/config.go index e53f964be4..c0873b8d2c 100644 --- a/apps/backend/internal/common/config/config.go +++ b/apps/backend/internal/common/config/config.go @@ -140,6 +140,13 @@ type LoggingConfig struct { Level string `mapstructure:"level"` Format string `mapstructure:"format"` OutputPath string `mapstructure:"outputPath"` + + // Rotation options — apply only when OutputPath is a file path + // (ignored for stdout/stderr). Backed by lumberjack. + MaxSizeMB int `mapstructure:"maxSizeMb"` + MaxBackups int `mapstructure:"maxBackups"` + MaxAgeDays int `mapstructure:"maxAgeDays"` + Compress bool `mapstructure:"compress"` } // RepositoryDiscoveryConfig holds configuration for local repository scanning. @@ -271,6 +278,10 @@ func setDefaults(v *viper.Viper) { v.SetDefault("logging.level", "info") v.SetDefault("logging.format", detectDefaultLogFormat()) v.SetDefault("logging.outputPath", "stdout") + v.SetDefault("logging.maxSizeMb", 100) + v.SetDefault("logging.maxBackups", 5) + v.SetDefault("logging.maxAgeDays", 30) + v.SetDefault("logging.compress", true) // Repository discovery defaults v.SetDefault("repositoryDiscovery.roots", []string{}) diff --git a/apps/backend/internal/common/logger/logger.go b/apps/backend/internal/common/logger/logger.go index 803461e9fd..204f69b4df 100644 --- a/apps/backend/internal/common/logger/logger.go +++ b/apps/backend/internal/common/logger/logger.go @@ -8,6 +8,7 @@ import ( "go.uber.org/zap" "go.uber.org/zap/zapcore" + "gopkg.in/natefinch/lumberjack.v2" "github.com/kandev/kandev/internal/common/logger/buffer" ) @@ -25,6 +26,13 @@ type LoggingConfig struct { Level string `mapstructure:"level"` // debug, info, warn, error Format string `mapstructure:"format"` // json, console OutputPath string `mapstructure:"output_path"` // stdout, stderr, or file path + + // Rotation options — apply only when OutputPath is a file path + // (ignored for stdout/stderr). Backed by lumberjack. + MaxSizeMB int `mapstructure:"max_size_mb"` // rotate when file exceeds this size; 0 = lumberjack default (100MB) + MaxBackups int `mapstructure:"max_backups"` // max number of rotated files to retain; 0 = unlimited + MaxAgeDays int `mapstructure:"max_age_days"` // max age of rotated files; 0 = unlimited + Compress bool `mapstructure:"compress"` // gzip rotated files } // Logger wraps zap.Logger to provide structured logging with helper methods. @@ -94,11 +102,13 @@ func NewLogger(cfg LoggingConfig) (*Logger, error) { case "stderr": writeSyncer = zapcore.AddSync(os.Stderr) default: - file, err := os.OpenFile(cfg.OutputPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return nil, err - } - writeSyncer = zapcore.AddSync(file) + writeSyncer = zapcore.AddSync(&lumberjack.Logger{ + Filename: cfg.OutputPath, + MaxSize: cfg.MaxSizeMB, + MaxBackups: cfg.MaxBackups, + MaxAge: cfg.MaxAgeDays, + Compress: cfg.Compress, + }) } outputCore := zapcore.NewCore(encoder, writeSyncer, level) diff --git a/apps/backend/internal/github/branch_protection.go b/apps/backend/internal/github/branch_protection.go new file mode 100644 index 0000000000..7abfa70ff6 --- /dev/null +++ b/apps/backend/internal/github/branch_protection.go @@ -0,0 +1,119 @@ +package github + +import ( + "context" + "sync" + "time" +) + +// BranchProtection captures the subset of a GitHub branch protection rule that +// the CI popover surfaces ("N approvals required to merge"). Stored values +// have a fixed TTL so changes to the protection rule on GitHub propagate +// without restarting the backend. +type BranchProtection struct { + RequiredApprovingReviewCount int + HasRule bool // false when GitHub returned 404 (no rule) + FetchedAt time.Time +} + +// branchProtectionCacheTTL is how long a cached protection lookup stays +// authoritative before a refetch is allowed. One hour balances API quota +// (4-PRs-per-cycle GraphQL polling) against rule-change latency (rare). +const branchProtectionCacheTTL = time.Hour + +// branchProtectionCache is an in-memory TTL cache keyed by +// "owner/repo@base_branch". Concurrent reads share the RLock; concurrent +// cache misses for the same key may each issue their own GitHub fetch and +// race to set() the result — values are deterministic so the loser's +// write is harmless, and the extra round-trips are bounded by the 1h TTL. +// Stale entries are evicted on read so the map cannot grow unbounded over +// a long-running process: callers always observe an active TTL window. +type branchProtectionCache struct { + mu sync.RWMutex + m map[string]BranchProtection + ttl time.Duration +} + +func newBranchProtectionCache() *branchProtectionCache { + return &branchProtectionCache{ + m: make(map[string]BranchProtection), + ttl: branchProtectionCacheTTL, + } +} + +func (c *branchProtectionCache) get(key string) (BranchProtection, bool) { + c.mu.RLock() + bp, ok := c.m[key] + c.mu.RUnlock() + if !ok { + return BranchProtection{}, false + } + if time.Since(bp.FetchedAt) <= c.ttl { + return bp, true + } + // Evict the stale entry so the map doesn't grow unbounded across + // long-running deployments with many distinct (owner, repo, branch) + // keys. Recheck under the write lock so a concurrent set() that just + // landed isn't clobbered. + c.mu.Lock() + if cur, present := c.m[key]; present && time.Since(cur.FetchedAt) > c.ttl { + delete(c.m, key) + } + c.mu.Unlock() + return BranchProtection{}, false +} + +func (c *branchProtectionCache) set(key string, bp BranchProtection) { + c.mu.Lock() + defer c.mu.Unlock() + c.m[key] = bp +} + +func branchProtectionKey(owner, repo, branch string) string { + return owner + "/" + repo + "@" + branch +} + +// BranchProtectionFetcher is implemented by the live GitHub clients (PAT, gh +// CLI). The mock client returns a sentinel "no rule" so e2e tests get +// deterministic results unless they seed via the mock controller. +type BranchProtectionFetcher interface { + FetchBranchProtection(ctx context.Context, owner, repo, branch string) (BranchProtection, error) +} + +// fetchRequiredReviews returns the branch-protection-derived +// RequiredApprovingReviewCount for (owner, repo, branch), or nil if: +// - the active client doesn't implement BranchProtectionFetcher, +// - the upstream call errors (token lacks scope, network down, etc.), +// - the repo has no protection rule on the base branch. +// +// Result is cached for branchProtectionCacheTTL. nil never gets cached so a +// transient error is retried on the next sync. +func (s *Service) fetchRequiredReviews(ctx context.Context, owner, repo, branch string) *int { + if owner == "" || repo == "" || branch == "" { + return nil + } + key := branchProtectionKey(owner, repo, branch) + if bp, ok := s.protectionCache.get(key); ok { + if !bp.HasRule { + return nil + } + n := bp.RequiredApprovingReviewCount + return &n + } + fetcher, ok := s.client.(BranchProtectionFetcher) + if !ok { + return nil + } + bp, err := fetcher.FetchBranchProtection(ctx, owner, repo, branch) + if err != nil { + // Don't cache errors — next sync retries. + return nil + } + bp.FetchedAt = time.Now().UTC() + s.protectionCache.set(key, bp) + if !bp.HasRule { + return nil + } + n := bp.RequiredApprovingReviewCount + return &n +} diff --git a/apps/backend/internal/github/branch_protection_test.go b/apps/backend/internal/github/branch_protection_test.go new file mode 100644 index 0000000000..475adf365a --- /dev/null +++ b/apps/backend/internal/github/branch_protection_test.go @@ -0,0 +1,138 @@ +package github + +import ( + "context" + "errors" + "sync/atomic" + "testing" + "testing/synctest" + "time" +) + +// fakeBPFetcher is a minimal BranchProtectionFetcher for testing the +// service-level cache wiring. It records call counts and returns canned +// values per (owner, repo, branch) key. +type fakeBPFetcher struct { + calls atomic.Int64 + bp BranchProtection + err error +} + +func (f *fakeBPFetcher) FetchBranchProtection(_ context.Context, _, _, _ string) (BranchProtection, error) { + f.calls.Add(1) + return f.bp, f.err +} + +// minimal Client surface — only the bits fetchRequiredReviews needs (it +// asserts the client implements BranchProtectionFetcher; everything else +// can be nil-valued). +type fakeBPClient struct { + *fakeBPFetcher + Client +} + +func newServiceWithBPFetcher(f *fakeBPFetcher) *Service { + return &Service{ + client: fakeBPClient{fakeBPFetcher: f}, + protectionCache: newBranchProtectionCache(), + } +} + +func TestBranchProtectionCache_GetSet_TTL(t *testing.T) { + // synctest.Test advances time in virtual ticks so a 60ms sleep is + // instantaneous wall-clock — keeps the suite fast and deterministic + // (no real sleeps that flake on heavily loaded CI runners). + synctest.Test(t, func(t *testing.T) { + c := newBranchProtectionCache() + c.ttl = 50 * time.Millisecond + key := "o/r@main" + c.set(key, BranchProtection{HasRule: true, RequiredApprovingReviewCount: 2, FetchedAt: time.Now()}) + got, ok := c.get(key) + if !ok || got.RequiredApprovingReviewCount != 2 { + t.Fatalf("fresh entry: got=%+v ok=%v", got, ok) + } + time.Sleep(60 * time.Millisecond) + if _, ok := c.get(key); ok { + t.Fatalf("stale entry should not be returned") + } + }) +} + +func TestBranchProtectionCache_StaleEntryIsEvicted(t *testing.T) { + c := newBranchProtectionCache() + c.ttl = 1 * time.Millisecond + c.set("o/r@main", BranchProtection{HasRule: true, FetchedAt: time.Now().Add(-time.Hour)}) + if _, ok := c.get("o/r@main"); ok { + t.Fatalf("expected stale miss") + } + c.mu.RLock() + _, present := c.m["o/r@main"] + c.mu.RUnlock() + if present { + t.Fatalf("stale entry should have been deleted from map") + } +} + +func TestFetchRequiredReviews_CacheHit(t *testing.T) { + f := &fakeBPFetcher{bp: BranchProtection{HasRule: true, RequiredApprovingReviewCount: 3}} + s := newServiceWithBPFetcher(f) + if got := s.fetchRequiredReviews(context.Background(), "o", "r", "main"); got == nil || *got != 3 { + t.Fatalf("first call: %v", got) + } + if got := s.fetchRequiredReviews(context.Background(), "o", "r", "main"); got == nil || *got != 3 { + t.Fatalf("cached call: %v", got) + } + if calls := f.calls.Load(); calls != 1 { + t.Fatalf("fetcher called %d times, want 1 (cache miss + hit)", calls) + } +} + +func TestFetchRequiredReviews_NoRuleIsCached(t *testing.T) { + f := &fakeBPFetcher{bp: BranchProtection{HasRule: false}} + s := newServiceWithBPFetcher(f) + if got := s.fetchRequiredReviews(context.Background(), "o", "r", "main"); got != nil { + t.Fatalf("expected nil for no-rule, got %v", got) + } + // Second call must not hit the network — the negative result is cached + // so we don't re-query upstream every poll. + _ = s.fetchRequiredReviews(context.Background(), "o", "r", "main") + if calls := f.calls.Load(); calls != 1 { + t.Fatalf("fetcher called %d times, want 1", calls) + } +} + +func TestFetchRequiredReviews_ErrorIsNotCached(t *testing.T) { + f := &fakeBPFetcher{err: errors.New("boom")} + s := newServiceWithBPFetcher(f) + if got := s.fetchRequiredReviews(context.Background(), "o", "r", "main"); got != nil { + t.Fatalf("expected nil on error, got %v", got) + } + if got := s.fetchRequiredReviews(context.Background(), "o", "r", "main"); got != nil { + t.Fatalf("expected nil on retry, got %v", got) + } + if calls := f.calls.Load(); calls != 2 { + t.Fatalf("fetcher called %d times, want 2 (error not cached)", calls) + } +} + +func TestFetchRequiredReviews_ClientWithoutFetcherReturnsNil(t *testing.T) { + // noop client doesn't satisfy BranchProtectionFetcher. + s := &Service{client: nil, protectionCache: newBranchProtectionCache()} + if got := s.fetchRequiredReviews(context.Background(), "o", "r", "main"); got != nil { + t.Fatalf("expected nil when client lacks BranchProtectionFetcher, got %v", got) + } +} + +func TestFetchRequiredReviews_TTLRefetch(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + f := &fakeBPFetcher{bp: BranchProtection{HasRule: true, RequiredApprovingReviewCount: 1}} + s := newServiceWithBPFetcher(f) + s.protectionCache.ttl = 50 * time.Millisecond + _ = s.fetchRequiredReviews(context.Background(), "o", "r", "main") + time.Sleep(60 * time.Millisecond) + _ = s.fetchRequiredReviews(context.Background(), "o", "r", "main") + if calls := f.calls.Load(); calls != 2 { + t.Fatalf("fetcher called %d times, want 2 (refetch after TTL)", calls) + } + }) +} diff --git a/apps/backend/internal/github/client_helpers.go b/apps/backend/internal/github/client_helpers.go index ff16c2292e..7df629414a 100644 --- a/apps/backend/internal/github/client_helpers.go +++ b/apps/backend/internal/github/client_helpers.go @@ -91,17 +91,103 @@ func getPRStatus(ctx context.Context, c Client, owner, repo string, number int) reviewState, pendingReviewCount := deriveReviewSyncState(pr, reviews) total, passing := countCheckResults(checks) return &PRStatus{ - PR: pr, - ReviewState: reviewState, - ChecksState: computeOverallCheckStatus(checks), - MergeableState: pr.MergeableState, - ReviewCount: len(reviews), + PR: pr, + ReviewState: reviewState, + ChecksState: computeOverallCheckStatus(checks), + MergeableState: pr.MergeableState, + // ReviewCount is the number of distinct reviewers whose latest review + // state is APPROVED — it's the value the popover renders as + // "Approved (N)" / "Approved N / M required". Counting raw review + // entries (`len(reviews)`) double-counts authors who left multiple + // reviews and also includes COMMENTED / CHANGES_REQUESTED rows. + ReviewCount: countApprovedReviewers(reviews), PendingReviewCount: pendingReviewCount, ChecksTotal: total, ChecksPassing: passing, + // REST path actually counted check runs + reviews — distinguish + // from the batched-GraphQL path that only carries rollup state. + ChecksPopulated: true, + ReviewCountsPopulated: true, }, nil } +// reviewSample is a normalized review row consumed by latestReviewStateByAuthor. +// Adapter functions below convert PRReview (REST) and reviewNode (GraphQL) +// to this shape so the per-reviewer dedup rule is only spelled out once. +type reviewSample struct { + author string + state string + at time.Time +} + +// latestReviewStateByAuthor reduces a list of reviews to "one entry per +// reviewer, latest binding state wins". COMMENTED and PENDING never +// override a prior APPROVED / CHANGES_REQUESTED for the same author so a +// reviewer who approved-then-commented still counts as approved. +// Anonymous reviewers (deleted users) get a unique synthetic key so each +// review still counts independently. +func latestReviewStateByAuthor(samples []reviewSample) map[string]reviewSample { + byAuthor := make(map[string]reviewSample, len(samples)) + for _, s := range samples { + key := s.author + if key == "" { + key = ":" + s.at.UTC().Format(time.RFC3339Nano) + } + state := strings.ToUpper(s.state) + if state != reviewStateApproved && state != reviewStateChangesRequested { + if _, ok := byAuthor[key]; ok { + continue + } + } + prev, ok := byAuthor[key] + if !ok || !s.at.Before(prev.at) { + byAuthor[key] = reviewSample{author: s.author, state: state, at: s.at} + } + } + return byAuthor +} + +// countApprovedAuthors counts distinct reviewers whose latest binding state is +// APPROVED. Shared between the REST and GraphQL count helpers. +func countApprovedAuthors(samples []reviewSample) int { + count := 0 + for _, s := range latestReviewStateByAuthor(samples) { + if s.state == reviewStateApproved { + count++ + } + } + return count +} + +// reduceReviewSummary collapses the per-author map into a single overall +// review state. CHANGES_REQUESTED wins across authors; APPROVED otherwise; +// "" when nothing is binding. Shared between REST and GraphQL paths. +func reduceReviewSummary(samples []reviewSample) string { + hasApproval := false + for _, l := range latestReviewStateByAuthor(samples) { + switch l.state { + case reviewStateChangesRequested: + return computedReviewStateChangesRequested + case reviewStateApproved: + hasApproval = true + } + } + if hasApproval { + return computedReviewStateApproved + } + return "" +} + +// countApprovedReviewers returns the number of distinct authors whose latest +// review state is APPROVED. REST-path adapter over the shared helper. +func countApprovedReviewers(reviews []PRReview) int { + samples := make([]reviewSample, len(reviews)) + for i, r := range reviews { + samples[i] = reviewSample{author: r.Author, state: r.State, at: r.CreatedAt} + } + return countApprovedAuthors(samples) +} + // countCheckResults returns (total, passing) counts using the same logic as // computeOverallCheckStatus: skipped/neutral and still-running checks are // excluded from the total so the X/Y badge communicates pass rate rather diff --git a/apps/backend/internal/github/client_helpers_test.go b/apps/backend/internal/github/client_helpers_test.go index 6500215993..5a869c4d92 100644 --- a/apps/backend/internal/github/client_helpers_test.go +++ b/apps/backend/internal/github/client_helpers_test.go @@ -471,3 +471,123 @@ func TestHasChangesRequested(t *testing.T) { }) } } + +// --- Reviewer dedup helpers (countApprovedReviewers + reduceReviewSummary) --- + +func TestCountApprovedReviewers(t *testing.T) { + t0 := time.Date(2025, 5, 1, 12, 0, 0, 0, time.UTC) + mk := func(author, state string, offset time.Duration) PRReview { + return PRReview{Author: author, State: state, CreatedAt: t0.Add(offset)} + } + cases := []struct { + name string + reviews []PRReview + want int + }{ + {name: "empty", reviews: []PRReview{}, want: 0}, + { + name: "single approval", + reviews: []PRReview{mk("alice", reviewStateApproved, 0)}, + want: 1, + }, + { + name: "dedup same author latest wins", + reviews: []PRReview{ + mk("alice", reviewStateChangesRequested, 0), + mk("alice", reviewStateApproved, time.Hour), + }, + want: 1, + }, + { + name: "COMMENTED does not replace prior APPROVED", + reviews: []PRReview{ + mk("alice", reviewStateApproved, 0), + mk("alice", "COMMENTED", time.Hour), + }, + want: 1, + }, + { + name: "PENDING never counts even alone", + reviews: []PRReview{mk("alice", "PENDING", 0)}, + want: 0, + }, + { + name: "two distinct approvers", + reviews: []PRReview{ + mk("alice", reviewStateApproved, 0), + mk("bob", reviewStateApproved, time.Hour), + }, + want: 2, + }, + { + name: "approve then change-request reverts", + reviews: []PRReview{ + mk("alice", reviewStateApproved, 0), + mk("alice", reviewStateChangesRequested, time.Hour), + }, + want: 0, + }, + { + name: "anonymous reviewers counted separately", + reviews: []PRReview{ + mk("", reviewStateApproved, 0), + mk("", reviewStateApproved, time.Hour), + }, + want: 2, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := countApprovedReviewers(tc.reviews); got != tc.want { + t.Fatalf("countApprovedReviewers = %d, want %d", got, tc.want) + } + }) + } +} + +func TestReduceReviewSummary(t *testing.T) { + t0 := time.Date(2025, 5, 1, 12, 0, 0, 0, time.UTC) + mk := func(author, state string, offset time.Duration) reviewSample { + return reviewSample{author: author, state: state, at: t0.Add(offset)} + } + cases := []struct { + name string + in []reviewSample + want string + }{ + {name: "empty", in: nil, want: ""}, + { + name: "single approval", + in: []reviewSample{mk("a", reviewStateApproved, 0)}, + want: computedReviewStateApproved, + }, + { + name: "changes requested wins across authors", + in: []reviewSample{ + mk("a", reviewStateApproved, 0), + mk("b", reviewStateChangesRequested, time.Hour), + }, + want: computedReviewStateChangesRequested, + }, + { + name: "later approval supersedes earlier changes-requested from same author", + in: []reviewSample{ + mk("a", reviewStateChangesRequested, 0), + mk("a", reviewStateApproved, time.Hour), + }, + want: computedReviewStateApproved, + }, + { + name: "only comments returns empty", + in: []reviewSample{mk("a", "COMMENTED", 0)}, + want: "", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := reduceReviewSummary(tc.in); got != tc.want { + t.Fatalf("reduceReviewSummary = %q, want %q", got, tc.want) + } + }) + } +} diff --git a/apps/backend/internal/github/gh_client.go b/apps/backend/internal/github/gh_client.go index 73c9ba7ebb..17ac5156b7 100644 --- a/apps/backend/internal/github/gh_client.go +++ b/apps/backend/internal/github/gh_client.go @@ -505,6 +505,65 @@ func (c *GHClient) GetPRStatus(ctx context.Context, owner, repo string, number i return getPRStatus(ctx, c, owner, repo, number) } +// FetchBranchProtection looks up branch protection via `gh api`. A 404 from +// `gh` (no rule) and a 403 (token lacks Administration: Read scope) are both +// treated as "no rule we can see" so callers cache the negative result and +// don't burn rate-limit quota on every poll. The string match is permissive +// across formats so a future `gh` CLI release that tweaks the wording +// doesn't silently break the cache. +func (c *GHClient) FetchBranchProtection(ctx context.Context, owner, repo, branch string) (BranchProtection, error) { + out, err := c.run(ctx, "api", + fmt.Sprintf("repos/%s/%s/branches/%s/protection", owner, repo, branch)) + if err != nil { + if isNotFoundErr(err) || isForbiddenErr(err) { + return BranchProtection{HasRule: false}, nil + } + return BranchProtection{}, err + } + var raw struct { + RequiredPullRequestReviews *struct { + RequiredApprovingReviewCount int `json:"required_approving_review_count"` + } `json:"required_pull_request_reviews"` + } + if err := json.Unmarshal([]byte(out), &raw); err != nil { + return BranchProtection{}, fmt.Errorf("decode branch protection: %w", err) + } + if raw.RequiredPullRequestReviews == nil { + return BranchProtection{HasRule: true}, nil + } + return BranchProtection{ + HasRule: true, + RequiredApprovingReviewCount: raw.RequiredPullRequestReviews.RequiredApprovingReviewCount, + }, nil +} + +// isNotFoundErr matches the formats the `gh` CLI uses to report a 404 across +// recent versions: "HTTP 404", "HTTP 404: ...", and "404 Not Found". +// Restrictive enough that an unrelated 404 substring (e.g. inside a JSON +// payload accidentally rendered into stderr) is unlikely to false-match. +func isNotFoundErr(err error) bool { + if err == nil { + return false + } + s := err.Error() + return strings.Contains(s, "HTTP 404") || + strings.Contains(s, "404 Not Found") || + strings.Contains(s, "status: 404") +} + +// isForbiddenErr matches the formats the `gh` CLI uses to report a 403, used +// by the branch-protection lookup to silently fall back to "no rule" when +// the token lacks Administration: Read scope. +func isForbiddenErr(err error) bool { + if err == nil { + return false + } + s := err.Error() + return strings.Contains(s, "HTTP 403") || + strings.Contains(s, "403 Forbidden") || + strings.Contains(s, "status: 403") +} + func (c *GHClient) ListPRFiles(ctx context.Context, owner, repo string, number int) ([]PRFile, error) { out, err := c.run(ctx, "api", fmt.Sprintf("repos/%s/%s/pulls/%d/files", owner, repo, number), diff --git a/apps/backend/internal/github/gh_client_test.go b/apps/backend/internal/github/gh_client_test.go index dac69d689b..4836ecc459 100644 --- a/apps/backend/internal/github/gh_client_test.go +++ b/apps/backend/internal/github/gh_client_test.go @@ -1,10 +1,57 @@ package github import ( + "errors" "testing" "time" ) +func TestIsNotFoundErr(t *testing.T) { + cases := []struct { + name string + err error + want bool + }{ + {"nil", nil, false}, + {"HTTP 404", errors.New("gh api: HTTP 404"), true}, + {"HTTP 404 with suffix", errors.New("gh: HTTP 404: Not Found (404)"), true}, + {"404 Not Found", errors.New("404 Not Found"), true}, + {"status: 404", errors.New("request failed (status: 404)"), true}, + {"unrelated 500", errors.New("HTTP 500: server error"), false}, + {"unrelated text", errors.New("connection refused"), false}, + {"403 not 404", errors.New("HTTP 403: Forbidden"), false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := isNotFoundErr(tc.err); got != tc.want { + t.Fatalf("isNotFoundErr(%v) = %v, want %v", tc.err, got, tc.want) + } + }) + } +} + +func TestIsForbiddenErr(t *testing.T) { + cases := []struct { + name string + err error + want bool + }{ + {"nil", nil, false}, + {"HTTP 403", errors.New("gh api: HTTP 403"), true}, + {"403 Forbidden", errors.New("403 Forbidden"), true}, + {"status: 403", errors.New("request failed (status: 403)"), true}, + {"404 not 403", errors.New("HTTP 404"), false}, + {"500 not 403", errors.New("HTTP 500"), false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := isForbiddenErr(tc.err); got != tc.want { + t.Fatalf("isForbiddenErr(%v) = %v, want %v", tc.err, got, tc.want) + } + }) + } +} + func TestParseTimePtr(t *testing.T) { tests := []struct { name string diff --git a/apps/backend/internal/github/graphql.go b/apps/backend/internal/github/graphql.go index 5cd5fe4e19..a4fed0dc1e 100644 --- a/apps/backend/internal/github/graphql.go +++ b/apps/backend/internal/github/graphql.go @@ -94,6 +94,12 @@ type batchedPRResult struct { ReviewRequests struct { TotalCount int `json:"totalCount"` } `json:"reviewRequests"` + ReviewThreads struct { + TotalCount int `json:"totalCount"` + Nodes []struct { + IsResolved bool `json:"isResolved"` + } `json:"nodes"` + } `json:"reviewThreads"` Commits struct { Nodes []struct { Commit struct { @@ -184,6 +190,7 @@ func prFieldsBlock() string { `author { login } createdAt updatedAt mergedAt closedAt ` + `reviews(last: 100) { nodes { state author { login } submittedAt } } ` + `reviewRequests(first: 0) { totalCount } ` + + `reviewThreads(first: 100) { totalCount nodes { isResolved } } ` + `commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }` } @@ -236,59 +243,61 @@ func convertBatchedPRResult(raw *batchedPRResult, owner, repo string, number int if len(raw.Commits.Nodes) > 0 && raw.Commits.Nodes[0].Commit.StatusCheckRollup != nil { checksState = strings.ToLower(raw.Commits.Nodes[0].Commit.StatusCheckRollup.State) } + // Count unresolved threads from the fetched nodes. When the page is + // capped (totalCount > nodes), fall back to totalCount for the + // resolved-vs-unresolved estimate so the popover doesn't undercount on + // busy PRs. The fallback is conservative: we have no way to tell from + // the truncated page how many of the un-fetched threads are resolved, + // so attribute the unseen tail to "unresolved" — the popover's value + // is meant to be actionable, not exact, and over-reporting is safer + // than silently hiding open feedback. + unresolved := 0 + for _, t := range raw.ReviewThreads.Nodes { + if !t.IsResolved { + unresolved++ + } + } + if total := raw.ReviewThreads.TotalCount; total > len(raw.ReviewThreads.Nodes) { + unresolved += total - len(raw.ReviewThreads.Nodes) + } return &PRStatus{ - PR: pr, - ReviewState: reviewState, - ChecksState: checksState, - MergeableState: pr.MergeableState, + PR: pr, + ReviewState: reviewState, + ChecksState: checksState, + MergeableState: pr.MergeableState, + ReviewCount: countApprovedReviewerNodes(raw.Reviews.Nodes), + PendingReviewCount: raw.ReviewRequests.TotalCount, + ReviewCountsPopulated: true, + UnresolvedReviewThreads: unresolved, + UnresolvedReviewThreadsPopulated: true, } } +// reviewNodesToSamples converts the GraphQL reviewNode shape to the shared +// reviewSample slice used by the dedup helpers in client_helpers.go. +func reviewNodesToSamples(nodes []reviewNode) []reviewSample { + samples := make([]reviewSample, len(nodes)) + for i, n := range nodes { + samples[i] = reviewSample{author: n.Author.Login, state: n.State, at: n.SubmittedAt} + } + return samples +} + +// countApprovedReviewerNodes returns the number of distinct authors whose +// latest review state is APPROVED, on the GraphQL reviewNode shape. Thin +// adapter over countApprovedAuthors so REST and GraphQL agree on what +// "Approved (N)" means. +func countApprovedReviewerNodes(nodes []reviewNode) int { + return countApprovedAuthors(reviewNodesToSamples(nodes)) +} + // summarizeReviewState collapses the review history to a single -// "approved"/"changes_requested"/"" value matching the existing -// service-side summary. Per-reviewer dedup: each reviewer's most-recent -// review wins, so a CHANGES_REQUESTED followed by an APPROVED from the -// same author resolves to APPROVED. CHANGES_REQUESTED beats APPROVED across -// distinct reviewers. +// "approved"/"changes_requested"/"" value. Per-reviewer dedup: each +// reviewer's most-recent binding review wins, so a CHANGES_REQUESTED +// followed by APPROVED from the same author resolves to APPROVED. +// CHANGES_REQUESTED beats APPROVED across distinct reviewers. func summarizeReviewState(nodes []reviewNode) string { - type latest struct { - state string - at time.Time - } - byAuthor := map[string]latest{} - for _, n := range nodes { - // Anonymous reviewers (deleted users) get a unique bucket so each - // review still counts independently. - key := n.Author.Login - if key == "" { - key = ":" + n.SubmittedAt.UTC().Format(time.RFC3339Nano) - } - state := strings.ToUpper(n.State) - // COMMENTED and PENDING are non-binding states and shouldn't replace - // a prior APPROVED / CHANGES_REQUESTED for the same reviewer. - if state != reviewStateApproved && state != reviewStateChangesRequested { - if _, ok := byAuthor[key]; ok { - continue - } - } - prev, ok := byAuthor[key] - if !ok || !n.SubmittedAt.Before(prev.at) { - byAuthor[key] = latest{state: state, at: n.SubmittedAt} - } - } - hasApproval := false - for _, l := range byAuthor { - switch l.state { - case reviewStateChangesRequested: - return computedReviewStateChangesRequested - case reviewStateApproved: - hasApproval = true - } - } - if hasApproval { - return computedReviewStateApproved - } - return "" + return reduceReviewSummary(reviewNodesToSamples(nodes)) } // PATClient.ExecuteGraphQL satisfies GraphQLExecutor by POSTing to /graphql. diff --git a/apps/backend/internal/github/mock_client.go b/apps/backend/internal/github/mock_client.go index 6c1a707341..74db6dcbf6 100644 --- a/apps/backend/internal/github/mock_client.go +++ b/apps/backend/internal/github/mock_client.go @@ -51,6 +51,8 @@ type repoKey struct { type MockClient struct { mu sync.RWMutex user string + authenticated bool + authError string prs map[prKey]*PR prsByBranch map[branchKey]*PR orgs []GitHubOrg @@ -67,23 +69,26 @@ type MockClient struct { // NewMockClient creates a new MockClient with default values. func NewMockClient() *MockClient { return &MockClient{ - user: mockDefaultUser, - prs: make(map[prKey]*PR), - prsByBranch: make(map[branchKey]*PR), - repos: make(map[string][]GitHubRepo), - branches: make(map[repoKey][]RepoBranch), - reviews: make(map[prKey][]PRReview), - comments: make(map[prKey][]PRComment), - checks: make(map[checkKey][]CheckRun), - files: make(map[prKey][]PRFile), - commits: make(map[prKey][]PRCommitInfo), + user: mockDefaultUser, + authenticated: true, + prs: make(map[prKey]*PR), + prsByBranch: make(map[branchKey]*PR), + repos: make(map[string][]GitHubRepo), + branches: make(map[repoKey][]RepoBranch), + reviews: make(map[prKey][]PRReview), + comments: make(map[prKey][]PRComment), + checks: make(map[checkKey][]CheckRun), + files: make(map[prKey][]PRFile), + commits: make(map[prKey][]PRCommitInfo), } } // --- Client interface implementation --- func (m *MockClient) IsAuthenticated(context.Context) (bool, error) { - return true, nil + m.mu.RLock() + defer m.mu.RUnlock() + return m.authenticated, nil } func (m *MockClient) GetAuthenticatedUser(context.Context) (string, error) { @@ -270,6 +275,16 @@ func (m *MockClient) SetUser(username string) { m.user = username } +// SetAuthHealth toggles the authenticated state for the e2e auth-lost test. +// When authenticated=false the popover renders the "Reconnect GitHub" branch. +// authError is an opaque message preserved for diagnostics. +func (m *MockClient) SetAuthHealth(authenticated bool, authError string) { + m.mu.Lock() + defer m.mu.Unlock() + m.authenticated = authenticated + m.authError = authError +} + // AddPR adds a PR to the mock data store, indexed by owner/repo/number and branch. func (m *MockClient) AddPR(pr *PR) { m.mu.Lock() @@ -327,6 +342,34 @@ func (m *MockClient) AddCheckRuns(owner, repo, ref string, checks []CheckRun) { m.checks[k] = append(m.checks[k], checks...) } +// ReplaceCheckRuns overwrites the check runs for a ref. Used by the e2e mock +// controller so a follow-up seed call yields deterministic state. +func (m *MockClient) ReplaceCheckRuns(owner, repo, ref string, checks []CheckRun) { + m.mu.Lock() + defer m.mu.Unlock() + cp := make([]CheckRun, len(checks)) + copy(cp, checks) + m.checks[checkKey{owner, repo, ref}] = cp +} + +// ReplaceReviews overwrites the reviews for a PR. +func (m *MockClient) ReplaceReviews(owner, repo string, number int, reviews []PRReview) { + m.mu.Lock() + defer m.mu.Unlock() + cp := make([]PRReview, len(reviews)) + copy(cp, reviews) + m.reviews[prKey{owner, repo, number}] = cp +} + +// ReplaceComments overwrites the comments for a PR. +func (m *MockClient) ReplaceComments(owner, repo string, number int, comments []PRComment) { + m.mu.Lock() + defer m.mu.Unlock() + cp := make([]PRComment, len(comments)) + copy(cp, comments) + m.comments[prKey{owner, repo, number}] = cp +} + // AddPRFiles appends files for a PR. func (m *MockClient) AddPRFiles(owner, repo string, number int, files []PRFile) { m.mu.Lock() @@ -348,6 +391,8 @@ func (m *MockClient) Reset() { m.mu.Lock() defer m.mu.Unlock() m.user = mockDefaultUser + m.authenticated = true + m.authError = "" m.prs = make(map[prKey]*PR) m.prsByBranch = make(map[branchKey]*PR) m.orgs = nil diff --git a/apps/backend/internal/github/mock_controller.go b/apps/backend/internal/github/mock_controller.go index 18ebb41bfb..eee21bda92 100644 --- a/apps/backend/internal/github/mock_controller.go +++ b/apps/backend/internal/github/mock_controller.go @@ -1,6 +1,8 @@ package github import ( + "context" + "fmt" "net/http" "time" @@ -41,6 +43,8 @@ func (c *MockController) RegisterRoutes(router *gin.Engine) { api.POST("/commits", c.addPRCommits) api.POST("/branches", c.addBranches) api.POST("/task-prs", c.associateTaskPR) + api.POST("/pr-feedback", c.seedPRFeedback) + api.PUT("/auth-health", c.setAuthHealth) api.DELETE("/reset", c.reset) } @@ -188,25 +192,39 @@ func (c *MockController) addBranches(ctx *gin.Context) { ctx.JSON(http.StatusOK, gin.H{"added": len(req.Branches)}) } -// associateTaskPR directly creates a github_task_prs record for E2E testing. +// associateTaskPRRequest is the JSON body for the mock-controller's +// associateTaskPR endpoint. Pointer fields are optional — leave them nil +// to skip the corresponding TaskPR column update. +type associateTaskPRRequest struct { + TaskID string `json:"task_id"` + Owner string `json:"owner"` + Repo string `json:"repo"` + PRNumber int `json:"pr_number"` + PRURL string `json:"pr_url"` + PRTitle string `json:"pr_title"` + HeadBranch string `json:"head_branch"` + BaseBranch string `json:"base_branch"` + AuthorLogin string `json:"author_login"` + State string `json:"state"` + ReviewState string `json:"review_state"` + ChecksState string `json:"checks_state"` + MergeableState string `json:"mergeable_state"` + Additions int `json:"additions"` + Deletions int `json:"deletions"` + ReviewCount *int `json:"review_count,omitempty"` + PendingReviewCount *int `json:"pending_review_count,omitempty"` + RequiredReviews *int `json:"required_reviews,omitempty"` + ChecksTotal *int `json:"checks_total,omitempty"` + ChecksPassing *int `json:"checks_passing,omitempty"` + UnresolvedReviewThreads *int `json:"unresolved_review_threads,omitempty"` +} + +// associateTaskPR directly creates (or replaces) a github_task_prs record for +// E2E testing. Repeating the call with the same (task_id, owner, repo, +// pr_number) updates the row so tests can drive the live-refresh +// scenario by re-POSTing with new aggregate counts. func (c *MockController) associateTaskPR(ctx *gin.Context) { - var req struct { - TaskID string `json:"task_id"` - Owner string `json:"owner"` - Repo string `json:"repo"` - PRNumber int `json:"pr_number"` - PRURL string `json:"pr_url"` - PRTitle string `json:"pr_title"` - HeadBranch string `json:"head_branch"` - BaseBranch string `json:"base_branch"` - AuthorLogin string `json:"author_login"` - State string `json:"state"` - ReviewState string `json:"review_state"` - ChecksState string `json:"checks_state"` - MergeableState string `json:"mergeable_state"` - Additions int `json:"additions"` - Deletions int `json:"deletions"` - } + var req associateTaskPRRequest if err := ctx.ShouldBindJSON(&req); err != nil { ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) return @@ -215,6 +233,26 @@ func (c *MockController) associateTaskPR(ctx *gin.Context) { req.State = defaultPRState } now := time.Now().UTC() + tp := buildTaskPRFromRequest(&req, now) + if err := c.store.ReplaceTaskPR(ctx.Request.Context(), tp); err != nil { + ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + c.ensureMockPRForRequest(ctx.Request.Context(), &req, now) + // Publish the event so the frontend Zustand store picks up the new PR + // without requiring a page reload — mirrors real AssociatePRWithTask. + if c.eventBus != nil { + event := bus.NewEvent(events.GitHubTaskPRUpdated, "github", tp) + if err := c.eventBus.Publish(ctx.Request.Context(), events.GitHubTaskPRUpdated, event); err != nil { + c.logger.Debug("mock: failed to publish task PR updated event", zap.Error(err)) + } + } + ctx.JSON(http.StatusCreated, tp) +} + +// buildTaskPRFromRequest copies the required fields from the JSON body into +// a TaskPR and applies the optional pointer fields when present. +func buildTaskPRFromRequest(req *associateTaskPRRequest, now time.Time) *TaskPR { tp := &TaskPR{ TaskID: req.TaskID, Owner: req.Owner, @@ -233,19 +271,122 @@ func (c *MockController) associateTaskPR(ctx *gin.Context) { Deletions: req.Deletions, CreatedAt: now, } - if err := c.store.CreateTaskPR(ctx.Request.Context(), tp); err != nil { - ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + if req.ReviewCount != nil { + tp.ReviewCount = *req.ReviewCount + } + if req.PendingReviewCount != nil { + tp.PendingReviewCount = *req.PendingReviewCount + } + if req.RequiredReviews != nil { + v := *req.RequiredReviews + tp.RequiredReviews = &v + } + if req.ChecksTotal != nil { + tp.ChecksTotal = *req.ChecksTotal + } + if req.ChecksPassing != nil { + tp.ChecksPassing = *req.ChecksPassing + } + if req.UnresolvedReviewThreads != nil { + tp.UnresolvedReviewThreads = *req.UnresolvedReviewThreads + } + return tp +} + +// ensureMockPRForRequest seeds a synthetic PR in the mock client so the lazy +// PRFeedback path can resolve check runs by HeadSHA. Skipped when the PR was +// already seeded explicitly via addPRs (tests that pin a head_sha for +// matching check_runs must not have it overwritten). +func (c *MockController) ensureMockPRForRequest(ctx context.Context, req *associateTaskPRRequest, now time.Time) { + if existing, _ := c.mock.GetPR(ctx, req.Owner, req.Repo, req.PRNumber); existing != nil { return } - // Publish the event so the frontend Zustand store picks up the new PR - // without requiring a page reload — mirrors real AssociatePRWithTask. - if c.eventBus != nil { - event := bus.NewEvent(events.GitHubTaskPRUpdated, "github", tp) - if err := c.eventBus.Publish(ctx.Request.Context(), events.GitHubTaskPRUpdated, event); err != nil { - c.logger.Debug("mock: failed to publish task PR updated event", zap.Error(err)) - } + c.mock.AddPR(&PR{ + Number: req.PRNumber, + Title: req.PRTitle, + URL: req.PRURL, + HTMLURL: req.PRURL, + State: req.State, + HeadBranch: req.HeadBranch, + HeadSHA: mockHeadSHA(req.Owner, req.Repo, req.PRNumber), + BaseBranch: req.BaseBranch, + AuthorLogin: req.AuthorLogin, + RepoOwner: req.Owner, + RepoName: req.Repo, + Additions: req.Additions, + Deletions: req.Deletions, + CreatedAt: now, + UpdatedAt: now, + }) +} + +// seedPRFeedback registers checks (and optionally reviews / comments) for a +// specific PR. The PR must already exist in the mock client (associateTaskPR +// synthesizes one). The check ref is the PR's HeadSHA so getPRFeedback +// resolves them via ListCheckRuns. +func (c *MockController) seedPRFeedback(ctx *gin.Context) { + var req struct { + Owner string `json:"owner"` + Repo string `json:"repo"` + PRNumber int `json:"pr_number"` + Checks []CheckRun `json:"checks"` + Reviews []PRReview `json:"reviews"` + Comments []PRComment `json:"comments"` } - ctx.JSON(http.StatusCreated, tp) + if err := ctx.ShouldBindJSON(&req); err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) + return + } + if req.Owner == "" || req.Repo == "" || req.PRNumber == 0 { + ctx.JSON(http.StatusBadRequest, gin.H{"error": "owner, repo, pr_number are required"}) + return + } + headSHA := mockHeadSHA(req.Owner, req.Repo, req.PRNumber) + // If associateTaskPR ran first, an underlying PR row exists with this + // HeadSHA. Otherwise synthesize a minimal one so getPRFeedback's GetPR + // call doesn't fail. + if pr, err := c.mock.GetPR(ctx.Request.Context(), req.Owner, req.Repo, req.PRNumber); err != nil || pr == nil { + c.mock.AddPR(&PR{ + Number: req.PRNumber, + RepoOwner: req.Owner, + RepoName: req.Repo, + HeadSHA: headSHA, + CreatedAt: time.Now().UTC(), + UpdatedAt: time.Now().UTC(), + }) + } + // Replace prior seeded checks/reviews/comments so a follow-up call gives + // deterministic state; helpful for tests that drive a "then a check + // finishes" transition. + c.mock.ReplaceCheckRuns(req.Owner, req.Repo, headSHA, req.Checks) + c.mock.ReplaceReviews(req.Owner, req.Repo, req.PRNumber, req.Reviews) + c.mock.ReplaceComments(req.Owner, req.Repo, req.PRNumber, req.Comments) + ctx.JSON(http.StatusOK, gin.H{ + "checks": len(req.Checks), + "reviews": len(req.Reviews), + "comments": len(req.Comments), + }) +} + +// setAuthHealth toggles the mock client's authenticated state so e2e tests +// can drive the "Reconnect GitHub" branch in the popover. +func (c *MockController) setAuthHealth(ctx *gin.Context) { + var req struct { + Authenticated bool `json:"authenticated"` + Error string `json:"error"` + } + if err := ctx.ShouldBindJSON(&req); err != nil { + ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) + return + } + c.mock.SetAuthHealth(req.Authenticated, req.Error) + ctx.JSON(http.StatusOK, gin.H{"authenticated": req.Authenticated}) +} + +// mockHeadSHA produces a deterministic synthetic head SHA for a (owner, repo, +// pr_number) tuple so test seed calls can compute the same key. +func mockHeadSHA(owner, repo string, prNumber int) string { + return fmt.Sprintf("mocksha-%s-%s-%d", owner, repo, prNumber) } func (c *MockController) reset(ctx *gin.Context) { diff --git a/apps/backend/internal/github/models.go b/apps/backend/internal/github/models.go index 433d65606b..5b86740698 100644 --- a/apps/backend/internal/github/models.go +++ b/apps/backend/internal/github/models.go @@ -92,8 +92,29 @@ type PRStatus struct { MergeableState string `json:"mergeable_state"` // "clean", "blocked", "behind", "dirty", "has_hooks", "unstable", "draft", "unknown", "" ReviewCount int `json:"review_count"` PendingReviewCount int `json:"pending_review_count"` + RequiredReviews *int `json:"required_reviews,omitempty"` // nil when no branch protection rule found ChecksTotal int `json:"checks_total"` ChecksPassing int `json:"checks_passing"` + // ChecksPopulated reports whether the sync path actually computed + // ChecksTotal / ChecksPassing. The batched GraphQL poller doesn't (it + // only carries the rollup state), so SyncTaskPR uses this flag to + // decide whether to overwrite the persisted counts. A value of true + // with both counts at 0 is a real "no checks" answer; a value of false + // means "I didn't look, keep what's there." + ChecksPopulated bool `json:"checks_populated,omitempty"` + UnresolvedReviewThreads int `json:"unresolved_review_threads"` + // UnresolvedReviewThreadsPopulated mirrors ChecksPopulated for the + // review-threads field. The REST path (getPRStatus) doesn't fetch + // review threads, so it leaves the field at zero; SyncTaskPR uses + // this flag to avoid clobbering a non-zero value set by the GraphQL + // path during a subsequent REST sync. + UnresolvedReviewThreadsPopulated bool `json:"unresolved_review_threads_populated,omitempty"` + // ReviewCountsPopulated covers ReviewCount + PendingReviewCount. Both + // REST and GraphQL paths compute these now, but historically only the + // REST path did, so without the guard a GraphQL poll would clobber + // the REST value back to 0 (the popover's "Approved (1)" turning + // into "Approved (0)" until a new REST call landed). + ReviewCountsPopulated bool `json:"review_counts_populated,omitempty"` } // PRSearchPage is a paginated slice of PR search results, with the total @@ -137,31 +158,37 @@ type PRWatch struct { // repository this PR belongs to (multi-repo tasks can have one PR per repo). // Empty for legacy rows persisted before multi-repo support. type TaskPR struct { - ID string `json:"id" db:"id"` - TaskID string `json:"task_id" db:"task_id"` - RepositoryID string `json:"repository_id,omitempty" db:"repository_id"` - Owner string `json:"owner" db:"owner"` - Repo string `json:"repo" db:"repo"` - PRNumber int `json:"pr_number" db:"pr_number"` - PRURL string `json:"pr_url" db:"pr_url"` - PRTitle string `json:"pr_title" db:"pr_title"` - HeadBranch string `json:"head_branch" db:"head_branch"` - BaseBranch string `json:"base_branch" db:"base_branch"` - AuthorLogin string `json:"author_login" db:"author_login"` - State string `json:"state" db:"state"` // open, closed, merged - ReviewState string `json:"review_state" db:"review_state"` // approved, changes_requested, pending, "" - ChecksState string `json:"checks_state" db:"checks_state"` // success, failure, pending, "" - MergeableState string `json:"mergeable_state" db:"mergeable_state"` // clean, blocked, behind, dirty, has_hooks, unstable, draft, unknown, "" - ReviewCount int `json:"review_count" db:"review_count"` - PendingReviewCount int `json:"pending_review_count" db:"pending_review_count"` - CommentCount int `json:"comment_count" db:"comment_count"` - Additions int `json:"additions" db:"additions"` - Deletions int `json:"deletions" db:"deletions"` - CreatedAt time.Time `json:"created_at" db:"created_at"` - MergedAt *time.Time `json:"merged_at,omitempty" db:"merged_at"` - ClosedAt *time.Time `json:"closed_at,omitempty" db:"closed_at"` - LastSyncedAt *time.Time `json:"last_synced_at,omitempty" db:"last_synced_at"` - UpdatedAt time.Time `json:"updated_at" db:"updated_at"` + ID string `json:"id" db:"id"` + TaskID string `json:"task_id" db:"task_id"` + RepositoryID string `json:"repository_id,omitempty" db:"repository_id"` + Owner string `json:"owner" db:"owner"` + Repo string `json:"repo" db:"repo"` + PRNumber int `json:"pr_number" db:"pr_number"` + PRURL string `json:"pr_url" db:"pr_url"` + PRTitle string `json:"pr_title" db:"pr_title"` + HeadBranch string `json:"head_branch" db:"head_branch"` + BaseBranch string `json:"base_branch" db:"base_branch"` + AuthorLogin string `json:"author_login" db:"author_login"` + State string `json:"state" db:"state"` // open, closed, merged + ReviewState string `json:"review_state" db:"review_state"` // approved, changes_requested, pending, "" + ChecksState string `json:"checks_state" db:"checks_state"` // success, failure, pending, "" + MergeableState string `json:"mergeable_state" db:"mergeable_state"` // clean, blocked, behind, dirty, has_hooks, unstable, draft, unknown, "" + ReviewCount int `json:"review_count" db:"review_count"` + PendingReviewCount int `json:"pending_review_count" db:"pending_review_count"` + // RequiredReviews is the branch protection's required_approving_review_count. + // Nil when no protection rule exists or the token lacks scope to read it. + RequiredReviews *int `json:"required_reviews,omitempty" db:"required_reviews"` + CommentCount int `json:"comment_count" db:"comment_count"` + UnresolvedReviewThreads int `json:"unresolved_review_threads" db:"unresolved_review_threads"` + ChecksTotal int `json:"checks_total" db:"checks_total"` + ChecksPassing int `json:"checks_passing" db:"checks_passing"` + Additions int `json:"additions" db:"additions"` + Deletions int `json:"deletions" db:"deletions"` + CreatedAt time.Time `json:"created_at" db:"created_at"` + MergedAt *time.Time `json:"merged_at,omitempty" db:"merged_at"` + ClosedAt *time.Time `json:"closed_at,omitempty" db:"closed_at"` + LastSyncedAt *time.Time `json:"last_synced_at,omitempty" db:"last_synced_at"` + UpdatedAt time.Time `json:"updated_at" db:"updated_at"` } // RepoFilter identifies a GitHub repository for review watch filtering. diff --git a/apps/backend/internal/github/pat_client.go b/apps/backend/internal/github/pat_client.go index 5383b21b38..be45ec0738 100644 --- a/apps/backend/internal/github/pat_client.go +++ b/apps/backend/internal/github/pat_client.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -551,6 +552,37 @@ func parseNextLink(header string) string { return "" } +// FetchBranchProtection looks up the branch protection rule on a repo's base +// branch via the REST API. A 404 is treated as "no rule configured" and a 403 +// is treated as "no rule we can see" (token lacks Administration: Read scope). +// Both return HasRule=false with no error so the cache stores the negative +// result and we don't burn rate-limit quota retrying every poll cycle. +// Other errors propagate so callers can decide whether to retry. +func (c *PATClient) FetchBranchProtection(ctx context.Context, owner, repo, branch string) (BranchProtection, error) { + endpoint := fmt.Sprintf("/repos/%s/%s/branches/%s/protection", owner, repo, branch) + var raw struct { + RequiredPullRequestReviews *struct { + RequiredApprovingReviewCount int `json:"required_approving_review_count"` + } `json:"required_pull_request_reviews"` + } + if err := c.get(ctx, endpoint, &raw); err != nil { + var apiErr *GitHubAPIError + if errors.As(err, &apiErr) { + if apiErr.StatusCode == http.StatusNotFound || apiErr.StatusCode == http.StatusForbidden { + return BranchProtection{HasRule: false}, nil + } + } + return BranchProtection{}, err + } + if raw.RequiredPullRequestReviews == nil { + return BranchProtection{HasRule: true}, nil + } + return BranchProtection{ + HasRule: true, + RequiredApprovingReviewCount: raw.RequiredPullRequestReviews.RequiredApprovingReviewCount, + }, nil +} + // patPR is the JSON shape from the GitHub REST API for PRs. type patPR struct { Number int `json:"number"` diff --git a/apps/backend/internal/github/pat_client_test.go b/apps/backend/internal/github/pat_client_test.go index 7902b8aa7a..a9e7605218 100644 --- a/apps/backend/internal/github/pat_client_test.go +++ b/apps/backend/internal/github/pat_client_test.go @@ -297,6 +297,80 @@ func TestPATClient_MarksExhaustedFromRateLimitBody(t *testing.T) { } } +func TestPATClient_FetchBranchProtection(t *testing.T) { + cases := []struct { + name string + status int + body string + wantHasRule bool + wantRequired int + wantErr bool + }{ + { + name: "200 with required reviews", + status: http.StatusOK, + body: `{"required_pull_request_reviews":{"required_approving_review_count":2}}`, + wantHasRule: true, + wantRequired: 2, + }, + { + name: "200 with rule but no required reviews block", + status: http.StatusOK, + body: `{"required_pull_request_reviews":null}`, + wantHasRule: true, + }, + { + name: "404 maps to no rule", + status: http.StatusNotFound, + body: `{"message":"Branch not protected"}`, + wantHasRule: false, + }, + { + name: "403 (no admin scope) maps to no rule", + status: http.StatusForbidden, + body: `{"message":"Resource not accessible by integration"}`, + wantHasRule: false, + }, + { + name: "500 propagates as error", + status: http.StatusInternalServerError, + body: `{"message":"server error"}`, + wantErr: true, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + wantPath := "/repos/o/r/branches/main/protection" + if r.URL.Path != wantPath { + t.Fatalf("path = %q, want %q", r.URL.Path, wantPath) + } + w.WriteHeader(tc.status) + _, _ = w.Write([]byte(tc.body)) + })) + t.Cleanup(srv.Close) + c := newPATClientPointingAt(t, srv.URL) + bp, err := c.FetchBranchProtection(context.Background(), "o", "r", "main") + if tc.wantErr { + if err == nil { + t.Fatal("want error, got nil") + } + return + } + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if bp.HasRule != tc.wantHasRule { + t.Fatalf("HasRule = %v, want %v", bp.HasRule, tc.wantHasRule) + } + if bp.RequiredApprovingReviewCount != tc.wantRequired { + t.Fatalf("RequiredApprovingReviewCount = %d, want %d", + bp.RequiredApprovingReviewCount, tc.wantRequired) + } + }) + } +} + // newPATClientPointingAt builds a PATClient whose underlying HTTP client // reroutes any github API URL to the given test server. func newPATClientPointingAt(t *testing.T, baseURL string) *PATClient { diff --git a/apps/backend/internal/github/service.go b/apps/backend/internal/github/service.go index 47e6a0b041..8a1cd638c9 100644 --- a/apps/backend/internal/github/service.go +++ b/apps/backend/internal/github/service.go @@ -71,21 +71,23 @@ type Service struct { taskEventSubs []bus.Subscription searchCache *ttlCache prStatusCache *ttlCache + protectionCache *branchProtectionCache rateTracker *RateTracker } // NewService creates a new GitHub service. func NewService(client Client, authMethod string, secrets SecretProvider, store *Store, eventBus bus.EventBus, log *logger.Logger) *Service { return &Service{ - client: client, - authMethod: authMethod, - secrets: secrets, - store: store, - eventBus: eventBus, - logger: log, - searchCache: newTTLCache(), - prStatusCache: newTTLCache(), - rateTracker: NewRateTracker(eventBus, log), + client: client, + authMethod: authMethod, + secrets: secrets, + store: store, + eventBus: eventBus, + logger: log, + searchCache: newTTLCache(), + prStatusCache: newTTLCache(), + protectionCache: newBranchProtectionCache(), + rateTracker: NewRateTracker(eventBus, log), } } @@ -753,6 +755,51 @@ func (s *Service) SyncTaskPR(ctx context.Context, taskID string, status *PRStatu return err } + // Some sync paths (notably the batched GraphQL poller) don't populate + // ChecksTotal / ChecksPassing — they only carry the rollup state. The + // caller sets status.ChecksPopulated=true when it actually counted + // checks; otherwise we preserve the persisted values so the popover + // doesn't flap to "0/0" between a rich REST sync and a lightweight + // GraphQL one. When the populated counter says 0/0 it really is 0/0 + // (e.g. all workflows were removed from the PR), so we honor it. + nextChecksTotal, nextChecksPassing := tp.ChecksTotal, tp.ChecksPassing + if status.ChecksPopulated { + nextChecksTotal = status.ChecksTotal + nextChecksPassing = status.ChecksPassing + } + // Same Populated/preserve dance for unresolved review threads — the + // REST path doesn't fetch them, so blindly writing status.UnresolvedReviewThreads + // would clobber the non-zero value set by the GraphQL path on every poll. + nextUnresolved := tp.UnresolvedReviewThreads + if status.UnresolvedReviewThreadsPopulated { + nextUnresolved = status.UnresolvedReviewThreads + } + // Review counts: only overwrite when the caller actually computed them. + // Both REST and GraphQL paths now populate these, but a partial sync + // path that doesn't would otherwise reset the popover's "Approved (N)" + // to zero. + nextReviewCount, nextPendingReviewCount := tp.ReviewCount, tp.PendingReviewCount + if status.ReviewCountsPopulated { + nextReviewCount = status.ReviewCount + nextPendingReviewCount = status.PendingReviewCount + } + // PRs can be retargeted to a different base branch; pick up the new + // branch from status.PR before resolving branch-protection so we don't + // indefinitely surface the wrong rule. + nextBaseBranch := tp.BaseBranch + if status.PR.BaseBranch != "" && status.PR.BaseBranch != tp.BaseBranch { + nextBaseBranch = status.PR.BaseBranch + } + // RequiredReviews comes from branch protection, fetched separately. + // Treat nil as "unknown — don't touch"; only write when the caller has it + // or our cache resolves the rule for this base branch. + nextRequiredReviews := tp.RequiredReviews + if status.RequiredReviews != nil { + nextRequiredReviews = status.RequiredReviews + } else if fetched := s.fetchRequiredReviews(ctx, tp.Owner, tp.Repo, nextBaseBranch); fetched != nil { + nextRequiredReviews = fetched + } + changed := tp.State != status.PR.State || tp.PRTitle != status.PR.Title || tp.Additions != status.PR.Additions || @@ -760,8 +807,13 @@ func (s *Service) SyncTaskPR(ctx context.Context, taskID string, status *PRStatu tp.ReviewState != status.ReviewState || tp.ChecksState != status.ChecksState || tp.MergeableState != status.MergeableState || - tp.ReviewCount != status.ReviewCount || - tp.PendingReviewCount != status.PendingReviewCount || + tp.ReviewCount != nextReviewCount || + tp.PendingReviewCount != nextPendingReviewCount || + !intPtrEqual(tp.RequiredReviews, nextRequiredReviews) || + tp.ChecksTotal != nextChecksTotal || + tp.ChecksPassing != nextChecksPassing || + tp.UnresolvedReviewThreads != nextUnresolved || + tp.BaseBranch != nextBaseBranch || !timeEqual(tp.MergedAt, status.PR.MergedAt) || !timeEqual(tp.ClosedAt, status.PR.ClosedAt) @@ -774,8 +826,13 @@ func (s *Service) SyncTaskPR(ctx context.Context, taskID string, status *PRStatu tp.ReviewState = status.ReviewState tp.ChecksState = status.ChecksState tp.MergeableState = status.MergeableState - tp.ReviewCount = status.ReviewCount - tp.PendingReviewCount = status.PendingReviewCount + tp.ReviewCount = nextReviewCount + tp.PendingReviewCount = nextPendingReviewCount + tp.RequiredReviews = nextRequiredReviews + tp.ChecksTotal = nextChecksTotal + tp.ChecksPassing = nextChecksPassing + tp.UnresolvedReviewThreads = nextUnresolved + tp.BaseBranch = nextBaseBranch // CommentCount is no longer updated from polling -- only refreshed on-demand now := time.Now().UTC() tp.LastSyncedAt = &now @@ -804,6 +861,17 @@ func timeEqual(a, b *time.Time) bool { return a.Equal(*b) } +// intPtrEqual compares two nullable int pointers for equality. +func intPtrEqual(a, b *int) bool { + if a == nil && b == nil { + return true + } + if a == nil || b == nil { + return false + } + return *a == *b +} + // --- PR info and feedback (live) --- // GetPR fetches basic PR details from GitHub. diff --git a/apps/backend/internal/github/service_test.go b/apps/backend/internal/github/service_test.go index 4cc69bf4e3..6f32e8e078 100644 --- a/apps/backend/internal/github/service_test.go +++ b/apps/backend/internal/github/service_test.go @@ -910,6 +910,253 @@ func TestSyncTaskPR_PublishesEventOnMergeableStateChange(t *testing.T) { } } +// TestSyncTaskPR_ChecksPopulated_PreservesOnLightweightSync verifies the +// "preserve when batch sync didn't populate" path: a PRStatus with +// ChecksPopulated=false must NOT clobber the persisted ChecksTotal / +// ChecksPassing, even when status carries 0/0. +func TestSyncTaskPR_ChecksPopulated_PreservesOnLightweightSync(t *testing.T) { + svc, store, _ := setupSyncTest(t) + ctx := context.Background() + if err := store.CreateTaskPR(ctx, &TaskPR{ + TaskID: "t1", + Owner: "owner", + Repo: "repo", + PRNumber: 1, + PRURL: "https://github.com/owner/repo/pull/1", + HeadBranch: "feat", + BaseBranch: "main", + State: "open", + ChecksTotal: 10, + ChecksPassing: 7, + }); err != nil { + t.Fatalf("create: %v", err) + } + status := &PRStatus{ + PR: &PR{Number: 1, State: "open", RepoOwner: "owner", RepoName: "repo"}, + ChecksTotal: 0, + ChecksPassing: 0, + ChecksPopulated: false, // batched GraphQL path: didn't count + } + if err := svc.SyncTaskPR(ctx, "t1", status); err != nil { + t.Fatalf("sync: %v", err) + } + stored, err := store.GetTaskPR(ctx, "t1") + if err != nil { + t.Fatalf("get: %v", err) + } + if stored.ChecksTotal != 10 || stored.ChecksPassing != 7 { + t.Fatalf("counts clobbered: total=%d passing=%d (want 10/7)", stored.ChecksTotal, stored.ChecksPassing) + } +} + +// TestSyncTaskPR_ChecksPopulated_AcceptsRealZero verifies the design fix: +// when the rich sync path explicitly reports 0/0 (workflows removed from +// the PR), we DO honor the new value instead of clinging to stale totals. +func TestSyncTaskPR_ChecksPopulated_AcceptsRealZero(t *testing.T) { + svc, store, _ := setupSyncTest(t) + ctx := context.Background() + if err := store.CreateTaskPR(ctx, &TaskPR{ + TaskID: "t1", Owner: "o", Repo: "r", PRNumber: 1, PRURL: "u", + HeadBranch: "feat", BaseBranch: "main", State: "open", + ChecksTotal: 5, ChecksPassing: 5, + }); err != nil { + t.Fatalf("create: %v", err) + } + status := &PRStatus{ + PR: &PR{Number: 1, State: "open", RepoOwner: "o", RepoName: "r"}, + ChecksTotal: 0, + ChecksPassing: 0, + ChecksPopulated: true, // REST path: counted to zero + } + if err := svc.SyncTaskPR(ctx, "t1", status); err != nil { + t.Fatalf("sync: %v", err) + } + stored, _ := store.GetTaskPR(ctx, "t1") + if stored.ChecksTotal != 0 || stored.ChecksPassing != 0 { + t.Fatalf("real-zero not honored: total=%d passing=%d", stored.ChecksTotal, stored.ChecksPassing) + } +} + +// TestSyncTaskPR_ReviewCounts_PreservesOnLightweightSync covers the same +// preserve-on-not-populated dance for ReviewCount/PendingReviewCount as the +// checks/threads variants. A partial sync path (status.ReviewCountsPopulated +// = false) must not reset the popover's "Approved (N)" line to zero. +func TestSyncTaskPR_ReviewCounts_PreservesOnLightweightSync(t *testing.T) { + svc, store, eb := setupSyncTest(t) + ctx := context.Background() + if err := store.CreateTaskPR(ctx, &TaskPR{ + TaskID: "t1", Owner: "o", Repo: "r", PRNumber: 1, PRURL: "u", + HeadBranch: "feat", BaseBranch: "main", State: "open", + ReviewCount: 2, PendingReviewCount: 1, + }); err != nil { + t.Fatalf("create: %v", err) + } + status := &PRStatus{ + PR: &PR{Number: 1, State: "open", RepoOwner: "o", RepoName: "r"}, + ReviewCount: 0, + PendingReviewCount: 0, + ReviewCountsPopulated: false, + } + if err := svc.SyncTaskPR(ctx, "t1", status); err != nil { + t.Fatalf("sync: %v", err) + } + stored, _ := store.GetTaskPR(ctx, "t1") + if stored.ReviewCount != 2 || stored.PendingReviewCount != 1 { + t.Fatalf("review counts clobbered: review=%d pending=%d (want 2/1)", + stored.ReviewCount, stored.PendingReviewCount) + } + if got := eb.publishedCount(); got != 0 { + t.Fatalf("expected no event when nothing changed, got %d", got) + } +} + +// TestSyncTaskPR_ReviewCounts_AcceptsRealZero is the symmetric case: when the +// caller actually counted reviewers and reports zero, we honor it (e.g. all +// approvals dismissed) instead of clinging to the previous non-zero values. +func TestSyncTaskPR_ReviewCounts_AcceptsRealZero(t *testing.T) { + svc, store, _ := setupSyncTest(t) + ctx := context.Background() + if err := store.CreateTaskPR(ctx, &TaskPR{ + TaskID: "t1", Owner: "o", Repo: "r", PRNumber: 1, PRURL: "u", + HeadBranch: "feat", BaseBranch: "main", State: "open", + ReviewCount: 2, PendingReviewCount: 1, + }); err != nil { + t.Fatalf("create: %v", err) + } + status := &PRStatus{ + PR: &PR{Number: 1, State: "open", RepoOwner: "o", RepoName: "r"}, + ReviewCount: 0, + PendingReviewCount: 0, + ReviewCountsPopulated: true, + } + if err := svc.SyncTaskPR(ctx, "t1", status); err != nil { + t.Fatalf("sync: %v", err) + } + stored, _ := store.GetTaskPR(ctx, "t1") + if stored.ReviewCount != 0 || stored.PendingReviewCount != 0 { + t.Fatalf("real-zero not honored: review=%d pending=%d", + stored.ReviewCount, stored.PendingReviewCount) + } +} + +// TestSyncTaskPR_UnresolvedThreads_PreservesOnLightweightSync verifies the +// REST single-PR poller (which doesn't fetch review threads) does NOT +// clobber the value set by the GraphQL batched poller. Without the +// UnresolvedReviewThreadsPopulated guard, every REST sync would flip the +// count to 0 and emit a spurious github.task_pr.updated event. +func TestSyncTaskPR_UnresolvedThreads_PreservesOnLightweightSync(t *testing.T) { + svc, store, eb := setupSyncTest(t) + ctx := context.Background() + if err := store.CreateTaskPR(ctx, &TaskPR{ + TaskID: "t1", Owner: "o", Repo: "r", PRNumber: 1, PRURL: "u", + HeadBranch: "feat", BaseBranch: "main", State: "open", + UnresolvedReviewThreads: 3, + }); err != nil { + t.Fatalf("create: %v", err) + } + status := &PRStatus{ + PR: &PR{Number: 1, State: "open", RepoOwner: "o", RepoName: "r"}, + UnresolvedReviewThreads: 0, + UnresolvedReviewThreadsPopulated: false, // REST path: didn't look + } + if err := svc.SyncTaskPR(ctx, "t1", status); err != nil { + t.Fatalf("sync: %v", err) + } + stored, _ := store.GetTaskPR(ctx, "t1") + if stored.UnresolvedReviewThreads != 3 { + t.Fatalf("threads clobbered: got %d, want 3", stored.UnresolvedReviewThreads) + } + if got := eb.publishedCount(); got != 0 { + t.Fatalf("expected no event when nothing changed, got %d", got) + } +} + +// TestSyncTaskPR_BaseBranchRetarget covers the case where a PR is retargeted +// to a different base branch upstream — the new branch must be persisted so +// future branch-protection lookups key off the right value. +func TestSyncTaskPR_BaseBranchRetarget(t *testing.T) { + svc, store, _ := setupSyncTest(t) + ctx := context.Background() + if err := store.CreateTaskPR(ctx, &TaskPR{ + TaskID: "t1", Owner: "o", Repo: "r", PRNumber: 1, PRURL: "u", + HeadBranch: "feat", BaseBranch: "main", State: "open", + }); err != nil { + t.Fatalf("create: %v", err) + } + status := &PRStatus{ + PR: &PR{ + Number: 1, State: "open", RepoOwner: "o", RepoName: "r", + BaseBranch: "develop", + }, + } + if err := svc.SyncTaskPR(ctx, "t1", status); err != nil { + t.Fatalf("sync: %v", err) + } + stored, _ := store.GetTaskPR(ctx, "t1") + if stored.BaseBranch != "develop" { + t.Fatalf("base branch not updated: got %q want develop", stored.BaseBranch) + } +} + +// TestSyncTaskPR_NewFieldsPublishEvent guards that a change to any of the +// CI-popover-relevant fields (UnresolvedReviewThreads, RequiredReviews, +// ChecksTotal, ChecksPassing) triggers a github.task_pr.updated event so the +// frontend popover refreshes via WS. +func TestSyncTaskPR_NewFieldsPublishEvent(t *testing.T) { + required2 := 2 + cases := []struct { + name string + init TaskPR + status PRStatus + }{ + { + name: "unresolved threads change", + init: TaskPR{TaskID: "t1", Owner: "o", Repo: "r", PRNumber: 1, PRURL: "u", + HeadBranch: "feat", BaseBranch: "main", State: "open"}, + status: PRStatus{ + PR: &PR{Number: 1, State: "open", RepoOwner: "o", RepoName: "r"}, + UnresolvedReviewThreads: 3, + UnresolvedReviewThreadsPopulated: true, + }, + }, + { + name: "required reviews change", + init: TaskPR{TaskID: "t1", Owner: "o", Repo: "r", PRNumber: 1, PRURL: "u", + HeadBranch: "feat", BaseBranch: "main", State: "open"}, + status: PRStatus{ + PR: &PR{Number: 1, State: "open", RepoOwner: "o", RepoName: "r"}, + RequiredReviews: &required2, + }, + }, + { + name: "checks total change", + init: TaskPR{TaskID: "t1", Owner: "o", Repo: "r", PRNumber: 1, PRURL: "u", + HeadBranch: "feat", BaseBranch: "main", State: "open"}, + status: PRStatus{ + PR: &PR{Number: 1, State: "open", RepoOwner: "o", RepoName: "r"}, + ChecksTotal: 5, + ChecksPassing: 3, + ChecksPopulated: true, + }, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + svc, store, eb := setupSyncTest(t) + ctx := context.Background() + if err := store.CreateTaskPR(ctx, &tc.init); err != nil { + t.Fatalf("create: %v", err) + } + if err := svc.SyncTaskPR(ctx, "t1", &tc.status); err != nil { + t.Fatalf("sync: %v", err) + } + if got := eb.publishedCount(); got != 1 { + t.Fatalf("expected 1 event, got %d", got) + } + }) + } +} + func TestTimeEqual(t *testing.T) { now := time.Now() later := now.Add(time.Second) diff --git a/apps/backend/internal/github/store.go b/apps/backend/internal/github/store.go index 151de13bfe..8991bf4afa 100644 --- a/apps/backend/internal/github/store.go +++ b/apps/backend/internal/github/store.go @@ -74,7 +74,11 @@ const createTablesSQL = ` mergeable_state TEXT NOT NULL DEFAULT '', review_count INTEGER DEFAULT 0, pending_review_count INTEGER DEFAULT 0, + required_reviews INTEGER, comment_count INTEGER DEFAULT 0, + unresolved_review_threads INTEGER DEFAULT 0, + checks_total INTEGER DEFAULT 0, + checks_passing INTEGER DEFAULT 0, additions INTEGER DEFAULT 0, deletions INTEGER DEFAULT 0, created_at DATETIME NOT NULL, @@ -163,6 +167,13 @@ func (s *Store) initSchema() error { // Phase 4 (multi-repo): per-repo PR association on github_task_prs. _, _ = s.db.Exec(`ALTER TABLE github_task_prs ADD COLUMN repository_id TEXT NOT NULL DEFAULT ''`) _, _ = s.db.Exec(`ALTER TABLE github_pr_watches ADD COLUMN repository_id TEXT NOT NULL DEFAULT ''`) + // CI popover: aggregate counts + branch protection's required_approving_review_count + // + unresolved review-threads, surfaced in the PR top-bar hover popover so the + // frontend can render the counts row without a second round-trip. + _, _ = s.db.Exec(`ALTER TABLE github_task_prs ADD COLUMN required_reviews INTEGER`) + _, _ = s.db.Exec(`ALTER TABLE github_task_prs ADD COLUMN unresolved_review_threads INTEGER DEFAULT 0`) + _, _ = s.db.Exec(`ALTER TABLE github_task_prs ADD COLUMN checks_total INTEGER DEFAULT 0`) + _, _ = s.db.Exec(`ALTER TABLE github_task_prs ADD COLUMN checks_passing INTEGER DEFAULT 0`) if err := s.migratePRTablesForMultiRepo(); err != nil { return fmt.Errorf("migrate PR tables for multi-repo: %w", err) } @@ -360,7 +371,11 @@ func (s *Store) migratePRTablesForMultiRepo() error { mergeable_state TEXT NOT NULL DEFAULT '', review_count INTEGER DEFAULT 0, pending_review_count INTEGER DEFAULT 0, + required_reviews INTEGER, comment_count INTEGER DEFAULT 0, + unresolved_review_threads INTEGER DEFAULT 0, + checks_total INTEGER DEFAULT 0, + checks_passing INTEGER DEFAULT 0, additions INTEGER DEFAULT 0, deletions INTEGER DEFAULT 0, created_at DATETIME NOT NULL, @@ -580,11 +595,13 @@ func (s *Store) CreateTaskPR(ctx context.Context, tp *TaskPR) error { tp.UpdatedAt = now _, err := s.db.ExecContext(ctx, ` INSERT INTO github_task_prs (id, task_id, repository_id, owner, repo, pr_number, pr_url, pr_title, head_branch, base_branch, author_login, - state, review_state, checks_state, mergeable_state, review_count, pending_review_count, comment_count, additions, deletions, + state, review_state, checks_state, mergeable_state, review_count, pending_review_count, required_reviews, comment_count, + unresolved_review_threads, checks_total, checks_passing, additions, deletions, created_at, merged_at, closed_at, last_synced_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, tp.ID, tp.TaskID, tp.RepositoryID, tp.Owner, tp.Repo, tp.PRNumber, tp.PRURL, tp.PRTitle, tp.HeadBranch, tp.BaseBranch, tp.AuthorLogin, - tp.State, tp.ReviewState, tp.ChecksState, tp.MergeableState, tp.ReviewCount, tp.PendingReviewCount, tp.CommentCount, tp.Additions, tp.Deletions, + tp.State, tp.ReviewState, tp.ChecksState, tp.MergeableState, tp.ReviewCount, tp.PendingReviewCount, tp.RequiredReviews, tp.CommentCount, + tp.UnresolvedReviewThreads, tp.ChecksTotal, tp.ChecksPassing, tp.Additions, tp.Deletions, tp.CreatedAt, tp.MergedAt, tp.ClosedAt, tp.LastSyncedAt, tp.UpdatedAt) return err } @@ -713,11 +730,13 @@ func (s *Store) ReplaceTaskPR(ctx context.Context, tp *TaskPR) error { } if _, err := tx.ExecContext(ctx, ` INSERT INTO github_task_prs (id, task_id, repository_id, owner, repo, pr_number, pr_url, pr_title, head_branch, base_branch, author_login, - state, review_state, checks_state, mergeable_state, review_count, pending_review_count, comment_count, additions, deletions, + state, review_state, checks_state, mergeable_state, review_count, pending_review_count, required_reviews, comment_count, + unresolved_review_threads, checks_total, checks_passing, additions, deletions, created_at, merged_at, closed_at, last_synced_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, tp.ID, tp.TaskID, tp.RepositoryID, tp.Owner, tp.Repo, tp.PRNumber, tp.PRURL, tp.PRTitle, tp.HeadBranch, tp.BaseBranch, tp.AuthorLogin, - tp.State, tp.ReviewState, tp.ChecksState, tp.MergeableState, tp.ReviewCount, tp.PendingReviewCount, tp.CommentCount, tp.Additions, tp.Deletions, + tp.State, tp.ReviewState, tp.ChecksState, tp.MergeableState, tp.ReviewCount, tp.PendingReviewCount, tp.RequiredReviews, tp.CommentCount, + tp.UnresolvedReviewThreads, tp.ChecksTotal, tp.ChecksPassing, tp.Additions, tp.Deletions, tp.CreatedAt, tp.MergedAt, tp.ClosedAt, tp.LastSyncedAt, tp.UpdatedAt); err != nil { return err } @@ -729,13 +748,15 @@ func (s *Store) UpdateTaskPR(ctx context.Context, tp *TaskPR) error { tp.UpdatedAt = time.Now().UTC() _, err := s.db.ExecContext(ctx, ` UPDATE github_task_prs SET state = ?, review_state = ?, checks_state = ?, mergeable_state = ?, - review_count = ?, pending_review_count = ?, comment_count = ?, - additions = ?, deletions = ?, pr_title = ?, + review_count = ?, pending_review_count = ?, required_reviews = ?, comment_count = ?, + unresolved_review_threads = ?, checks_total = ?, checks_passing = ?, + additions = ?, deletions = ?, pr_title = ?, base_branch = ?, merged_at = ?, closed_at = ?, last_synced_at = ?, updated_at = ? WHERE id = ?`, tp.State, tp.ReviewState, tp.ChecksState, tp.MergeableState, - tp.ReviewCount, tp.PendingReviewCount, tp.CommentCount, - tp.Additions, tp.Deletions, tp.PRTitle, + tp.ReviewCount, tp.PendingReviewCount, tp.RequiredReviews, tp.CommentCount, + tp.UnresolvedReviewThreads, tp.ChecksTotal, tp.ChecksPassing, + tp.Additions, tp.Deletions, tp.PRTitle, tp.BaseBranch, tp.MergedAt, tp.ClosedAt, tp.LastSyncedAt, tp.UpdatedAt, tp.ID) return err } diff --git a/apps/backend/internal/health/checks.go b/apps/backend/internal/health/checks.go index 169fd6ca36..eeecb408a2 100644 --- a/apps/backend/internal/health/checks.go +++ b/apps/backend/internal/health/checks.go @@ -54,7 +54,7 @@ func (c *GitHubChecker) Check(_ context.Context) []Issue { Title: "GitHub integration unavailable", Message: "Install the gh CLI and run 'gh auth login', or add a GITHUB_TOKEN secret.", Severity: SeverityWarning, - FixURL: "/settings/workspace/{workspaceId}/github", + FixURL: "/settings/integrations/github", FixLabel: "Configure GitHub", }} } @@ -65,7 +65,7 @@ func (c *GitHubChecker) Check(_ context.Context) []Issue { Title: "GitHub not authenticated", Message: "Run 'gh auth login' or add a GITHUB_TOKEN secret.", Severity: SeverityWarning, - FixURL: "/settings/workspace/{workspaceId}/github", + FixURL: "/settings/integrations/github", FixLabel: "Configure GitHub", }} } @@ -91,7 +91,7 @@ func (c *GitHubChecker) rateLimitIssues() []Issue { Title: fmt.Sprintf("GitHub API rate limit exhausted (%s)", status.Resource), Message: rateLimitMessage(status), Severity: SeverityWarning, - FixURL: "/settings/workspace/{workspaceId}/github", + FixURL: "/settings/integrations/github", FixLabel: "View status", }) } @@ -153,7 +153,7 @@ func (c *AgentChecker) Check(ctx context.Context) []Issue { ID: "no_agents", Category: "agents", Title: "No AI agents detected", - Message: "Install an AI coding agent (e.g. Claude Code, Codex) to start using KanDev.", + Message: "Install an AI coding agent (e.g. Claude Code, Codex) to start using Kandev.", Severity: SeverityWarning, FixURL: "/settings/agents", FixLabel: "Configure Agents", diff --git a/apps/backend/internal/health/checks_test.go b/apps/backend/internal/health/checks_test.go index 31f07dd2c5..8dcf7a5e3c 100644 --- a/apps/backend/internal/health/checks_test.go +++ b/apps/backend/internal/health/checks_test.go @@ -18,6 +18,11 @@ type mockGitHubProvider struct { func (m *mockGitHubProvider) IsAuthenticated() bool { return m.authenticated } func (m *mockGitHubProvider) AuthMethod() string { return m.authMethod } +// expectedGitHubFixURL is the live route in apps/web/app/settings/integrations/github. +// Kept here so a typo or accidental rename breaks a single test instead of +// shipping a 404 to users. +const expectedGitHubFixURL = "/settings/integrations/github" + func TestGitHubChecker_NilProvider(t *testing.T) { checker := NewGitHubChecker(nil) issues := checker.Check(context.Background()) @@ -33,6 +38,9 @@ func TestGitHubChecker_NilProvider(t *testing.T) { if issues[0].Category != "github" { t.Errorf("category = %q, want %q", issues[0].Category, "github") } + if issues[0].FixURL != expectedGitHubFixURL { + t.Errorf("FixURL = %q, want %q", issues[0].FixURL, expectedGitHubFixURL) + } } func TestGitHubChecker_NotAuthenticated(t *testing.T) { @@ -47,6 +55,9 @@ func TestGitHubChecker_NotAuthenticated(t *testing.T) { if issues[0].Severity != SeverityWarning { t.Errorf("severity = %q, want %q", issues[0].Severity, SeverityWarning) } + if issues[0].FixURL != expectedGitHubFixURL { + t.Errorf("FixURL = %q, want %q", issues[0].FixURL, expectedGitHubFixURL) + } } func TestGitHubChecker_Authenticated(t *testing.T) { @@ -81,6 +92,9 @@ func TestGitHubChecker_AuthenticatedButRateLimited(t *testing.T) { if !strings.Contains(issues[0].Message, "resets in") { t.Errorf("message should include reset countdown, got %q", issues[0].Message) } + if issues[0].FixURL != expectedGitHubFixURL { + t.Errorf("FixURL = %q, want %q", issues[0].FixURL, expectedGitHubFixURL) + } } func TestGitHubChecker_AuthenticatedRateProviderEmpty(t *testing.T) { diff --git a/apps/backend/internal/integration/test_server_test.go b/apps/backend/internal/integration/test_server_test.go index 4b50966167..176267a254 100644 --- a/apps/backend/internal/integration/test_server_test.go +++ b/apps/backend/internal/integration/test_server_test.go @@ -282,7 +282,7 @@ func NewOrchestratorTestServer(t *testing.T) *OrchestratorTestServer { // Create orchestrator service cfg := orchestrator.DefaultServiceConfig() cfg.Scheduler.ProcessInterval = 50 * time.Millisecond // Faster for tests - orchestratorSvc := orchestrator.NewService(cfg, eventBus, agentManager, taskRepoAdapter, taskRepo, nil, nil, log) + orchestratorSvc := orchestrator.NewService(cfg, eventBus, agentManager, taskRepoAdapter, taskRepo, nil, nil, nil, log) // Wire message creator for message persistence (similar to cmd/kandev/orchestrator.go) msgCreator := &testMessageCreatorAdapter{svc: taskSvc} diff --git a/apps/backend/internal/mcp/handlers/handlers.go b/apps/backend/internal/mcp/handlers/handlers.go index 9c6601cbd3..6e60a1e8cb 100644 --- a/apps/backend/internal/mcp/handlers/handlers.go +++ b/apps/backend/internal/mcp/handlers/handlers.go @@ -450,7 +450,7 @@ func (h *Handlers) resolveTaskRepositories( parentID, sourceTaskID string, explicit []mcpRepositoryInput, ) (taskRepoResult, error) { - explicitRepos := explicitRepoInputs(explicit) + explicitRepos := h.explicitRepoInputsWithDefaults(ctx, explicit) if parentID != "" { parent, err := h.taskSvc.GetTask(ctx, parentID) @@ -504,27 +504,47 @@ func (h *Handlers) resolveTaskRepositories( return taskRepoResult{}, nil } -// explicitRepoInputs maps the MCP-side explicit repo list to service inputs. -// Returns nil when no explicit repos were supplied so callers can distinguish -// "agent didn't pass repos" from "agent passed an empty list". -func explicitRepoInputs(explicit []mcpRepositoryInput) []service.TaskRepositoryInput { +// explicitRepoInputsWithDefaults maps the MCP-side explicit repo list to +// service inputs. Returns nil when no explicit repos were supplied so callers +// can distinguish "agent didn't pass repos" from "agent passed an empty list". +// +// When an explicit entry pins a repository_id without a base_branch, the +// repository's default_branch is filled in. This anchors cross-repo subtasks +// (a parent on feature/foo creating a child in another repo) to a known-good +// branch instead of an empty value that would force every downstream consumer +// to recompute the default. +func (h *Handlers) explicitRepoInputsWithDefaults(ctx context.Context, explicit []mcpRepositoryInput) []service.TaskRepositoryInput { if len(explicit) == 0 { return nil } repos := make([]service.TaskRepositoryInput, 0, len(explicit)) for _, r := range explicit { + baseBranch := r.BaseBranch + if baseBranch == "" && r.RepositoryID != "" && h.taskSvc != nil { + if repo, err := h.taskSvc.GetRepository(ctx, r.RepositoryID); err == nil && repo != nil { + baseBranch = repo.DefaultBranch + } + } repos = append(repos, service.TaskRepositoryInput{ RepositoryID: r.RepositoryID, LocalPath: r.LocalPath, GitHubURL: r.GitHubURL, - BaseBranch: r.BaseBranch, + BaseBranch: baseBranch, }) } return repos } // inheritedRepoInputs maps an existing task's repository list onto service -// inputs for a new task that inherits from it. +// inputs for a new task that inherits from it. RepositoryID and BaseBranch +// carry over so a same-repo subtask branches off the same point as the +// parent (sibling branches off the same base, ergonomically aligned for +// stacked PRs). CheckoutBranch is dropped on purpose: two worktrees cannot +// share a working branch, so the subtask's session generates a fresh one. +// Agents that need a different base for a same-repo subtask must pass +// base_branch explicitly. If the inherited base_branch is missing on the +// remote at launch time, the worktree manager's fallback recovers to the +// repository's default_branch and surfaces a warning. func inheritedRepoInputs(src []*models.TaskRepository) []service.TaskRepositoryInput { if len(src) == 0 { return nil @@ -535,9 +555,8 @@ func inheritedRepoInputs(src []*models.TaskRepository) []service.TaskRepositoryI continue } repos = append(repos, service.TaskRepositoryInput{ - RepositoryID: r.RepositoryID, - BaseBranch: r.BaseBranch, - CheckoutBranch: r.CheckoutBranch, + RepositoryID: r.RepositoryID, + BaseBranch: r.BaseBranch, }) } return repos @@ -716,6 +735,12 @@ func (h *Handlers) handleMessageTask(ctx context.Context, msg *ws.Message) (*ws. status, err := h.dispatchTaskMessage(ctx, req.TaskID, session, wrappedPrompt, senderMeta) if err != nil { + var qfErr *queueFullDispatchError + if errors.As(err, &qfErr) { + return ws.NewError(msg.ID, msg.Action, messagequeue.QueueFullErrorCode, + fmt.Sprintf("target task has %d queued messages (max %d) — retry after the next turn completes", qfErr.queueSize, qfErr.max), + qfErr.toPayload()) + } return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil) } @@ -852,6 +877,50 @@ func conversationCursor(messages []*models.Message) string { return messages[len(messages)-1].ID } +// queueFullDispatchError is returned by dispatchTaskMessage when an inter-task +// message can't be queued because the target session's queue is full. It +// carries enough metadata for handleMessageTask to surface a structured +// "queue_full" error to the calling agent so its LLM can decide whether to +// retry, abort, or message a different task. +type queueFullDispatchError struct { + sessionID string + queueSize int + max int + entries []messagequeue.QueuedMessage +} + +func (e *queueFullDispatchError) Error() string { + return fmt.Sprintf("queue full: %d/%d messages pending for session %s", e.queueSize, e.max, e.sessionID) +} + +// toPayload builds the structured "data" body for the MCP error response. +// Sender / queued_at fields surface enough context for the LLM to reason about +// the wedge state without leaking the queued message contents. +func (e *queueFullDispatchError) toPayload() map[string]interface{} { + queued := make([]map[string]interface{}, 0, len(e.entries)) + for _, entry := range e.entries { + queued = append(queued, map[string]interface{}{ + "id": entry.ID, + "sender": entry.QueuedBy, + "queued_at": entry.QueuedAt, + }) + } + // The WS error envelope already carries the code; we duplicate it here so + // callers reading the structured details body still see it without parsing + // the envelope. Tests assert on details.error directly. + return map[string]interface{}{ + errorField: messagequeue.QueueFullErrorCode, + "queue_size": e.queueSize, + "max": e.max, + "retry_after": "next_turn", + "queued_messages": queued, + } +} + +// errorField names the well-known structured details key used to surface error +// codes in MCP tool responses (extracted to satisfy goconst's repeated-string rule). +const errorField = "error" + // dispatchTaskMessage routes a message to the right delivery path based on session state. // Returns the action taken: "queued", "sent", or "started". // @@ -873,7 +942,16 @@ func (h *Handlers) dispatchTaskMessage(ctx context.Context, taskID string, sessi if queue == nil { return "", errors.New("message queue not available") } - if _, err := queue.QueueMessageWithMetadata(ctx, session.ID, taskID, prompt, "", "agent", false, nil, metadata); err != nil { + if _, err := queue.QueueMessageWithMetadata(ctx, session.ID, taskID, prompt, "", messagequeue.QueuedByAgent, false, nil, metadata); err != nil { + if errors.Is(err, messagequeue.ErrQueueFull) { + status := queue.GetStatus(ctx, session.ID) + return "", &queueFullDispatchError{ + sessionID: session.ID, + queueSize: status.Count, + max: status.Max, + entries: status.Entries, + } + } return "", fmt.Errorf("failed to queue message: %w", err) } h.publishQueueStatusEvent(ctx, session.ID, queue) @@ -957,8 +1035,9 @@ func (h *Handlers) publishQueueStatusEvent(ctx context.Context, sessionID string "mcp-handlers", map[string]interface{}{ "session_id": sessionID, - "is_queued": status.IsQueued, - "message": status.Message, + "entries": status.Entries, + "count": status.Count, + "max": status.Max, }, )) } diff --git a/apps/backend/internal/mcp/handlers/handlers_test.go b/apps/backend/internal/mcp/handlers/handlers_test.go index 3ac93bfcbd..f9aa04e72d 100644 --- a/apps/backend/internal/mcp/handlers/handlers_test.go +++ b/apps/backend/internal/mcp/handlers/handlers_test.go @@ -266,26 +266,37 @@ func TestResolveTaskRepositories_NoInputs_ReturnsEmpty(t *testing.T) { // --- Integration tests using real task service --- // seedParentWithRepo creates a workspace, workflow, repository, and a parent -// task linked to that repository. Returns the parent task ID. +// task linked to that repository. Returns the parent task ID. The parent's +// task_repository row is anchored to a non-default branch ("pr-metrics") on +// purpose so inheritance tests can assert what subtasks do with the parent's +// branch (same-repo subtasks inherit it for stacked-PR ergonomics; the +// worktree manager's fallback rescues launches if the branch went stale). func seedParentWithRepo(t *testing.T, svc *service.Service, repo *sqliterepo.Repository) string { t.Helper() ctx := context.Background() require.NoError(t, repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Test"})) require.NoError(t, repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf-1", WorkspaceID: "ws-1", Name: "Board"})) - require.NoError(t, repo.CreateRepository(ctx, &models.Repository{ID: "repo-parent", WorkspaceID: "ws-1", Name: "Parent Repo"})) + require.NoError(t, repo.CreateRepository(ctx, &models.Repository{ + ID: "repo-parent", WorkspaceID: "ws-1", Name: "Parent Repo", DefaultBranch: "main", + })) parent, err := svc.CreateTask(ctx, &service.CreateTaskRequest{ WorkspaceID: "ws-1", WorkflowID: "wf-1", Title: "Parent task", Repositories: []service.TaskRepositoryInput{ - {RepositoryID: "repo-parent", BaseBranch: "main"}, + {RepositoryID: "repo-parent", BaseBranch: "pr-metrics"}, }, }) require.NoError(t, err) return parent.ID } -func TestResolveTaskRepositories_ParentWithoutExplicitRepos_InheritsAll(t *testing.T) { +// TestResolveTaskRepositories_ParentWithoutExplicitRepos_InheritsRepoAndBaseBranch +// asserts the same-repo subtask path: the parent's RepositoryID and +// BaseBranch carry over so the subtask branches off the same starting point +// (sibling branches, ergonomic for stacked PRs). CheckoutBranch is dropped +// because two worktrees cannot share a working branch. +func TestResolveTaskRepositories_ParentWithoutExplicitRepos_InheritsRepoAndBaseBranch(t *testing.T) { svc, repo := newTestTaskService(t) parentID := seedParentWithRepo(t, svc, repo) @@ -296,10 +307,79 @@ func TestResolveTaskRepositories_ParentWithoutExplicitRepos_InheritsAll(t *testi require.NoError(t, err) require.Len(t, result.Repos, 1, "subtask without explicit repos inherits parent's repos") assert.Equal(t, "repo-parent", result.Repos[0].RepositoryID) + assert.Equal(t, "pr-metrics", result.Repos[0].BaseBranch, "same-repo subtask should inherit parent's base_branch for stacked-PR ergonomics") + assert.Empty(t, result.Repos[0].CheckoutBranch, "subtask must not inherit parent's checkout_branch (worktrees cannot share a branch)") assert.Equal(t, "ws-1", result.WorkspaceID) assert.Equal(t, "wf-1", result.WorkflowID) } +// TestCreateSubtaskFromParent_SameRepoInheritsParentBaseBranch is the +// end-to-end check that the parent's base_branch is persisted onto the +// subtask's task_repository row when the subtask targets the same repo. +// This is the desired behaviour: agents stacking work on top of a parent +// PR get a subtask anchored to the same starting point. The worktree +// manager's fallback (covered in worktree tests) is the safety net for +// cases where the inherited branch later goes stale. +func TestCreateSubtaskFromParent_SameRepoInheritsParentBaseBranch(t *testing.T) { + svc, repo := newTestTaskService(t) + ctx := context.Background() + parentID := seedParentWithRepo(t, svc, repo) + + log := testLogger(t) + h := &Handlers{taskSvc: svc, logger: log.WithFields()} + + resolved, err := h.resolveTaskRepositories(ctx, parentID, "", nil) + require.NoError(t, err) + + subtask, err := svc.CreateTask(ctx, &service.CreateTaskRequest{ + WorkspaceID: resolved.WorkspaceID, + WorkflowID: resolved.WorkflowID, + ParentID: parentID, + Title: "Child", + Description: "do the thing", + Repositories: resolved.Repos, + }) + require.NoError(t, err) + require.Len(t, subtask.Repositories, 1) + assert.Equal(t, "repo-parent", subtask.Repositories[0].RepositoryID) + assert.Equal(t, "pr-metrics", subtask.Repositories[0].BaseBranch, "same-repo subtask should inherit parent's base_branch") +} + +// TestCreateSubtaskFromParent_DifferentRepoUsesNewRepoDefault verifies the +// cross-repo path: when the agent points the subtask at a different repo +// (via repository_id / repository_url / local_path) without an explicit +// base_branch, the subtask anchors to that repo's default_branch — never +// the parent's branch. +func TestCreateSubtaskFromParent_DifferentRepoUsesNewRepoDefault(t *testing.T) { + svc, repo := newTestTaskService(t) + ctx := context.Background() + parentID := seedParentWithRepo(t, svc, repo) + + require.NoError(t, repo.CreateRepository(ctx, &models.Repository{ + ID: "repo-sibling", WorkspaceID: "ws-1", Name: "Sibling", DefaultBranch: "trunk", + })) + + log := testLogger(t) + h := &Handlers{taskSvc: svc, logger: log.WithFields()} + + explicit := []mcpRepositoryInput{{RepositoryID: "repo-sibling"}} + resolved, err := h.resolveTaskRepositories(ctx, parentID, "", explicit) + require.NoError(t, err) + + subtask, err := svc.CreateTask(ctx, &service.CreateTaskRequest{ + WorkspaceID: resolved.WorkspaceID, + WorkflowID: resolved.WorkflowID, + ParentID: parentID, + Title: "Cross-repo child", + Description: "do the thing", + Repositories: resolved.Repos, + }) + require.NoError(t, err) + require.Len(t, subtask.Repositories, 1) + assert.Equal(t, "repo-sibling", subtask.Repositories[0].RepositoryID) + assert.Equal(t, "trunk", subtask.Repositories[0].BaseBranch, "cross-repo subtask should anchor to the new repo's default_branch, not parent's pr-metrics") +} + func TestResolveTaskRepositories_ParentWithExplicitRepos_OverridesRepoButInheritsWorkspace(t *testing.T) { svc, repo := newTestTaskService(t) parentID := seedParentWithRepo(t, svc, repo) diff --git a/apps/backend/internal/mcp/handlers/message_task_test.go b/apps/backend/internal/mcp/handlers/message_task_test.go index 534d3f51ba..657e5a84d0 100644 --- a/apps/backend/internal/mcp/handlers/message_task_test.go +++ b/apps/backend/internal/mcp/handlers/message_task_test.go @@ -85,7 +85,7 @@ func (f *fakeOrchestrator) GetMessageQueue() *messagequeue.Service { return f.qu func newMessageTaskHandler(t *testing.T, svc *service.Service) (*Handlers, *fakeOrchestrator) { t.Helper() log := testLogger(t) - orch := &fakeOrchestrator{queue: messagequeue.NewService(log)} + orch := &fakeOrchestrator{queue: messagequeue.NewServiceMemory(log)} h := &Handlers{ taskSvc: svc, sessionLauncher: orch, @@ -205,17 +205,49 @@ func TestHandleMessageTask_RunningSession_Queues(t *testing.T) { // and structured sender metadata so the drain path can write a Message row // the UI can render with a sender badge. status := orch.queue.GetStatus(context.Background(), sess.ID) - require.True(t, status.IsQueued) - assert.Contains(t, status.Message.Content, "follow-up message") - assert.Contains(t, status.Message.Content, "") - assert.Contains(t, status.Message.Content, "Sender task") - assert.Equal(t, sender.ID, status.Message.Metadata["sender_task_id"]) - assert.Equal(t, "Sender task", status.Message.Metadata["sender_task_title"]) - assert.Equal(t, "sender-sess-1", status.Message.Metadata["sender_session_id"]) + require.Equal(t, 1, status.Count) + entry := status.Entries[0] + assert.Contains(t, entry.Content, "follow-up message") + assert.Contains(t, entry.Content, "") + assert.Contains(t, entry.Content, "Sender task") + assert.Equal(t, sender.ID, entry.Metadata["sender_task_id"]) + assert.Equal(t, "Sender task", entry.Metadata["sender_task_title"]) + assert.Equal(t, "sender-sess-1", entry.Metadata["sender_session_id"]) assert.Empty(t, orch.promptCalls) assert.Empty(t, orch.startCreatedCalls) } +func TestHandleMessageTask_QueueFull_ReturnsStructuredError(t *testing.T) { + svc, repo := newTestTaskService(t) + sender, target, sess := seedTaskWithSession(t, svc, repo, models.TaskSessionStateRunning) + + h, orch := newMessageTaskHandler(t, svc) + + // Saturate the receiver's queue. + for i := 0; i < messagequeue.DefaultMaxPerSession; i++ { + _, err := orch.queue.QueueMessageWithMetadata(context.Background(), sess.ID, target.ID, + "prefill", "", "agent", false, nil, nil) + require.NoError(t, err) + } + + msg := makeWSMessage(t, ws.ActionMCPMessageTask, senderPayload(target.ID, "overflow message", sender.ID)) + resp, err := h.handleMessageTask(context.Background(), msg) + require.NoError(t, err) + require.NotNil(t, resp) + assert.Equal(t, ws.MessageTypeError, resp.Type) + + var errResp ws.ErrorPayload + require.NoError(t, json.Unmarshal(resp.Payload, &errResp)) + assert.Equal(t, "queue_full", errResp.Code) + assert.Equal(t, "queue_full", errResp.Details["error"]) + assert.EqualValues(t, messagequeue.DefaultMaxPerSession, errResp.Details["queue_size"]) + assert.EqualValues(t, messagequeue.DefaultMaxPerSession, errResp.Details["max"]) + assert.Equal(t, "next_turn", errResp.Details["retry_after"]) + queued, ok := errResp.Details["queued_messages"].([]interface{}) + require.True(t, ok, "queued_messages should be an array") + assert.Len(t, queued, messagequeue.DefaultMaxPerSession) +} + func TestHandleMessageTask_WaitingForInput_PromptsAgent(t *testing.T) { svc, repo := newTestTaskService(t) sender, target, sess := seedTaskWithSession(t, svc, repo, models.TaskSessionStateWaitingForInput) diff --git a/apps/backend/internal/mcp/server/config_handlers.go b/apps/backend/internal/mcp/server/config_handlers.go index 268c86f13f..8a5ad17de6 100644 --- a/apps/backend/internal/mcp/server/config_handlers.go +++ b/apps/backend/internal/mcp/server/config_handlers.go @@ -28,7 +28,7 @@ func (s *Server) registerConfigWorkflowTools() { ) s.mcpServer.AddTool( mcp.NewTool("list_repositories_kandev", - mcp.WithDescription("List repositories in a workspace. Use this to find a repository_id to attach to create_task_kandev when the task should target a specific codebase."), + mcp.WithDescription("List repositories in a workspace. Use this to find a repository_id to attach to create_task_kandev when the task should target a specific codebase. Each repository entry includes default_branch — use it to pick or confirm a base_branch when creating a subtask in a different repo."), mcp.WithString("workspace_id", mcp.Required(), mcp.Description("The workspace ID")), ), s.wrapHandler("list_repositories_kandev", s.listRepositoriesHandler()), diff --git a/apps/backend/internal/mcp/server/server.go b/apps/backend/internal/mcp/server/server.go index 5fa83def93..be3ac1de70 100644 --- a/apps/backend/internal/mcp/server/server.go +++ b/apps/backend/internal/mcp/server/server.go @@ -444,6 +444,10 @@ WHEN TO OMIT parent_id (top-level task): IMPORTANT: - Subtasks inherit workspace, workflow, agent profile, and executor from the parent - Subtasks inherit the parent's repository unless you supply repository_url, repository_id, or local_path — in which case the subtask targets that repo instead (must live in the parent's workspace) +- base_branch behaviour: + - Same repo as parent (no repo args): subtask inherits the parent's base_branch (sibling branches off the same starting point — useful for PR stacks) + - Different repo (you passed repository_url / repository_id / local_path): subtask defaults to that repo's default_branch + - Pass base_branch explicitly to override either default. Use list_repositories_kandev to see each repo's default_branch. - Top-level tasks need a repository via repository_url, repository_id, or local_path - 'description' is the sub-agent's initial prompt — be specific and detailed - Set start_agent=false to create without starting an agent` @@ -476,7 +480,7 @@ IMPORTANT: mcp.WithString("repository_id", mcp.Description("Repository ID. Required for top-level tasks unless local_path or repository_url is provided. For subtasks: optional — supply only when the subtask should target a different repo than the parent.")), mcp.WithString("local_path", mcp.Description("Local repository folder path (e.g. '/Users/me/projects/myrepo'). Will create/find the repository automatically. Preferred for local worktree flow. For subtasks: supply only when the subtask should target a different repo than the parent.")), mcp.WithString("repository_url", mcp.Description("GitHub repository URL (e.g. 'https://github.com/owner/repo'). The repository will be cloned automatically on first use. For subtasks: supply only when the subtask should target a different repo than the parent.")), - mcp.WithString("base_branch", mcp.Description("Base branch for the repository (e.g. 'main'). Optional, defaults to repository's default branch.")), + mcp.WithString("base_branch", mcp.Description("Base branch for the repository (e.g. 'main'). Optional. Defaults: same-repo subtasks inherit the parent's base_branch; cross-repo subtasks and top-level tasks fall back to the repository's default_branch (visible via list_repositories_kandev).")), ), s.wrapHandler("create_task_kandev", s.createTaskHandler()), ) diff --git a/apps/backend/internal/orchestrator/event_handlers_agent.go b/apps/backend/internal/orchestrator/event_handlers_agent.go index 6cfb5e492c..5521d26f06 100644 --- a/apps/backend/internal/orchestrator/event_handlers_agent.go +++ b/apps/backend/internal/orchestrator/event_handlers_agent.go @@ -55,13 +55,14 @@ func (s *Service) publishQueueStatusEvent(ctx context.Context, sessionID string) queueStatus := s.messageQueue.GetStatus(ctx, sessionID) eventData := map[string]interface{}{ "session_id": sessionID, - "is_queued": queueStatus.IsQueued, - "message": queueStatus.Message, + "entries": queueStatus.Entries, + "count": queueStatus.Count, + "max": queueStatus.Max, } s.logger.Debug("publishing queue status changed event", zap.String("session_id", sessionID), - zap.Bool("is_queued", queueStatus.IsQueued)) + zap.Int("count", queueStatus.Count)) _ = s.eventBus.Publish(ctx, events.MessageQueueStatusChanged, bus.NewEvent( events.MessageQueueStatusChanged, @@ -242,8 +243,7 @@ func (s *Service) handleAgentReady(ctx context.Context, data watcher.AgentEventD queueStatus := s.messageQueue.GetStatus(ctx, data.SessionID) s.logger.Info("checking for queued messages", zap.String("session_id", data.SessionID), - zap.Bool("is_queued", queueStatus.IsQueued), - zap.Any("message", queueStatus.Message)) + zap.Int("count", queueStatus.Count)) // Passthrough sessions: deliver queued messages via PTY stdin instead of ACP. if s.agentManager.IsPassthroughSession(ctx, data.SessionID) { diff --git a/apps/backend/internal/orchestrator/event_handlers_pending_move_test.go b/apps/backend/internal/orchestrator/event_handlers_pending_move_test.go index 0eced2dda6..b6ca06ac01 100644 --- a/apps/backend/internal/orchestrator/event_handlers_pending_move_test.go +++ b/apps/backend/internal/orchestrator/event_handlers_pending_move_test.go @@ -160,7 +160,7 @@ func buildPendingMoveScenario(t *testing.T) *pendingMoveScenario { workflowStepGetter: stepGetter, taskRepo: taskRepo, agentManager: agentMgr, - messageQueue: messagequeue.NewService(log), + messageQueue: messagequeue.NewServiceMemory(log), executor: exec, scheduler: sched, } @@ -400,7 +400,7 @@ func (sc *pendingMoveScenario) assertHandoffDeliveredOrQueued(t *testing.T) { implPrompts := capturedPromptsForExecution(sc.agentMgr, sc.implRelaunchExec) implQueued := sc.svc.messageQueue.GetStatus(sc.ctx, sc.implSessionID) - if len(implPrompts) == 0 && !implQueued.IsQueued { + if len(implPrompts) == 0 && implQueued.Count == 0 { t.Error("hand-off prompt was neither delivered to the impl session nor queued for it") return } @@ -409,9 +409,10 @@ func (sc *pendingMoveScenario) assertHandoffDeliveredOrQueued(t *testing.T) { return } } - if implQueued.IsQueued && implQueued.Message != nil && - strings.Contains(implQueued.Message.Content, "fibonacci.py has two bugs") { - return + for _, entry := range implQueued.Entries { + if strings.Contains(entry.Content, "fibonacci.py has two bugs") { + return + } } t.Errorf("hand-off prompt was neither delivered nor queued with the expected content") } @@ -564,7 +565,7 @@ func TestHandleAgentBootReady_DoesNotTriggerOnTurnComplete(t *testing.T) { workflowStepGetter: stepGetter, taskRepo: taskRepo, agentManager: agentMgr, - messageQueue: messagequeue.NewService(log), + messageQueue: messagequeue.NewServiceMemory(log), executor: exec, } svc.SetWorkflowStepGetter(stepGetter) diff --git a/apps/backend/internal/orchestrator/event_handlers_queue_test.go b/apps/backend/internal/orchestrator/event_handlers_queue_test.go index e6460a5410..ea16f330c0 100644 --- a/apps/backend/internal/orchestrator/event_handlers_queue_test.go +++ b/apps/backend/internal/orchestrator/event_handlers_queue_test.go @@ -42,11 +42,11 @@ func TestExecuteQueuedMessage_RequeuesWhenResetInProgress(t *testing.T) { svc.executeQueuedMessage("s1", queuedMsg) status := svc.messageQueue.GetStatus(ctx, "s1") - if !status.IsQueued || status.Message == nil { - t.Fatalf("expected queued message to be requeued when reset is in progress") + if status.Count != 1 { + t.Fatalf("expected queued message to be requeued when reset is in progress, count=%d", status.Count) } - if status.Message.Content != "hello" { - t.Fatalf("expected queued content to be preserved, got %q", status.Message.Content) + if status.Entries[0].Content != "hello" { + t.Fatalf("expected queued content to be preserved, got %q", status.Entries[0].Content) } } diff --git a/apps/backend/internal/orchestrator/event_handlers_streaming.go b/apps/backend/internal/orchestrator/event_handlers_streaming.go index aac4baa61b..2175befb36 100644 --- a/apps/backend/internal/orchestrator/event_handlers_streaming.go +++ b/apps/backend/internal/orchestrator/event_handlers_streaming.go @@ -221,10 +221,12 @@ func (s *Service) handleToolCallEvent(ctx context.Context, payload *lifecycle.Ag zap.String("tool_call_id", payload.Data.ToolCallID)) } - // Allow tool calls to wake session from WAITING_FOR_INPUT - // This ensures that when user responds to a clarification and the agent continues, - // the session properly transitions to RUNNING - s.updateTaskSessionState(ctx, payload.TaskID, payload.SessionID, models.TaskSessionStateRunning, "", true) + // Allow tool calls to wake session from WAITING_FOR_INPUT. + // Use setSessionRunning (not updateTaskSessionState) so the task is + // flipped to IN_PROGRESS in lockstep — otherwise an out-of-turn tool + // event (e.g. a Monitor watcher firing after on_turn_complete moved + // the task to REVIEW) leaves session=RUNNING with task=REVIEW. + s.setSessionRunning(ctx, payload.TaskID, payload.SessionID) } } @@ -331,11 +333,12 @@ func (s *Service) handleToolUpdateEvent(ctx context.Context, payload *lifecycle. zap.Error(err)) } - // Update session state for completion events - // Allow tool completions to wake session from WAITING_FOR_INPUT + // Update session state for completion events. + // Use setSessionRunning so the task flips to IN_PROGRESS alongside — + // see comment in handleToolCallEvent for the REVIEW/RUNNING split bug. if payload.Data.ToolStatus == agentEventComplete || payload.Data.ToolStatus == agentEventCompleted || payload.Data.ToolStatus == "success" || payload.Data.ToolStatus == agentEventError || payload.Data.ToolStatus == agentEventFailed { - s.updateTaskSessionState(ctx, payload.TaskID, payload.SessionID, models.TaskSessionStateRunning, "", true) + s.setSessionRunning(ctx, payload.TaskID, payload.SessionID) } } } @@ -484,7 +487,25 @@ func (s *Service) setSessionWaitingForInput(ctx context.Context, taskID, session } func (s *Service) setSessionRunning(ctx context.Context, taskID, sessionID string, preloadedSession ...*models.TaskSession) { - s.updateTaskSessionState(ctx, taskID, sessionID, models.TaskSessionStateRunning, "", true, preloadedSession...) + // Resolve session up front so we can guard the task write against terminal + // states. updateTaskSessionState silently no-ops for terminal sessions, so + // without this guard a buffered tool event arriving after a CANCELLED / + // FAILED / COMPLETED session would still clobber tasks.state to IN_PROGRESS. + var session *models.TaskSession + if len(preloadedSession) > 0 && preloadedSession[0] != nil { + session = preloadedSession[0] + } else { + var err error + session, err = s.repo.GetTaskSession(ctx, sessionID) + if err != nil { + return + } + } + if isTerminalSessionState(session.State) { + return + } + + s.updateTaskSessionState(ctx, taskID, sessionID, models.TaskSessionStateRunning, "", true, session) if err := s.taskRepo.UpdateTaskState(ctx, taskID, v1.TaskStateInProgress); err != nil { s.logger.Error("failed to update task state to IN_PROGRESS", diff --git a/apps/backend/internal/orchestrator/event_handlers_streaming_test.go b/apps/backend/internal/orchestrator/event_handlers_streaming_test.go index dced66dfaf..6a2664ce30 100644 --- a/apps/backend/internal/orchestrator/event_handlers_streaming_test.go +++ b/apps/backend/internal/orchestrator/event_handlers_streaming_test.go @@ -10,6 +10,8 @@ import ( "github.com/kandev/kandev/internal/agent/lifecycle" "github.com/kandev/kandev/internal/agentctl/types/streams" "github.com/kandev/kandev/internal/events/bus" + "github.com/kandev/kandev/internal/task/models" + v1 "github.com/kandev/kandev/pkg/api/v1" ) // recordingEventBus records published events for assertions. @@ -114,3 +116,97 @@ func TestHandleSessionModeEvent(t *testing.T) { require.Empty(t, eb.events) }) } + +// TestToolEventsWakeSessionAndTaskTogether locks in the fix for the +// REVIEW + RUNNING split: when an out-of-turn tool event (e.g. a Monitor +// watcher firing after on_turn_complete moved the task to REVIEW) wakes +// the session from WAITING_FOR_INPUT, the task must flip to IN_PROGRESS +// in lockstep instead of being left at REVIEW. +func TestToolEventsWakeSessionAndTaskTogether(t *testing.T) { + ctx := context.Background() + + cases := []struct { + name string + fire func(*Service) + }{ + { + name: "tool_call event", + fire: func(svc *Service) { + svc.handleToolCallEvent(ctx, &lifecycle.AgentStreamEventPayload{ + TaskID: "t1", + SessionID: "s1", + Data: &lifecycle.AgentStreamEventData{ + ToolCallID: "tc1", + ToolStatus: "running", + }, + }) + }, + }, + { + name: "tool_update completion event", + fire: func(svc *Service) { + svc.handleToolUpdateEvent(ctx, &lifecycle.AgentStreamEventPayload{ + TaskID: "t1", + SessionID: "s1", + Data: &lifecycle.AgentStreamEventData{ + ToolCallID: "tc1", + ToolStatus: agentEventComplete, + }, + }) + }, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + repo := setupTestRepo(t) + seedSession(t, repo, "t1", "s1", "step1") + + // Simulate post-on_turn_complete state: session WAITING, task REVIEW. + session, err := repo.GetTaskSession(ctx, "s1") + require.NoError(t, err) + session.State = models.TaskSessionStateWaitingForInput + require.NoError(t, repo.UpdateTaskSession(ctx, session)) + + taskRepo := newMockTaskRepo() + svc := createTestService(repo, newMockStepGetter(), taskRepo) + svc.messageCreator = &mockMessageCreator{} + + tc.fire(svc) + + updatedSession, err := repo.GetTaskSession(ctx, "s1") + require.NoError(t, err) + require.Equal(t, models.TaskSessionStateRunning, updatedSession.State, + "session should be woken to RUNNING") + require.Equal(t, v1.TaskStateInProgress, taskRepo.updatedStates["t1"], + "task must move to IN_PROGRESS in lockstep — leaving it at REVIEW is the bug") + }) + + t.Run(tc.name+" does not clobber terminal session", func(t *testing.T) { + // Inverse edge case: a buffered tool event arriving after the + // session is already terminal must NOT silently flip tasks.state + // to IN_PROGRESS while the session itself stays terminal. + repo := setupTestRepo(t) + seedSession(t, repo, "t1", "s1", "step1") + + session, err := repo.GetTaskSession(ctx, "s1") + require.NoError(t, err) + session.State = models.TaskSessionStateCancelled + require.NoError(t, repo.UpdateTaskSession(ctx, session)) + + taskRepo := newMockTaskRepo() + svc := createTestService(repo, newMockStepGetter(), taskRepo) + svc.messageCreator = &mockMessageCreator{} + + tc.fire(svc) + + updatedSession, err := repo.GetTaskSession(ctx, "s1") + require.NoError(t, err) + require.Equal(t, models.TaskSessionStateCancelled, updatedSession.State, + "terminal session must not be revived by a stale tool event") + _, taskWritten := taskRepo.updatedStates["t1"] + require.False(t, taskWritten, + "task state must not be clobbered when session is terminal") + }) + } +} diff --git a/apps/backend/internal/orchestrator/event_handlers_test.go b/apps/backend/internal/orchestrator/event_handlers_test.go index cf642679b9..769b9aaa80 100644 --- a/apps/backend/internal/orchestrator/event_handlers_test.go +++ b/apps/backend/internal/orchestrator/event_handlers_test.go @@ -443,7 +443,7 @@ func createTestServiceWithAgent(repo *sqliterepo.Repository, stepGetter *mockSte workflowStepGetter: stepGetter, taskRepo: taskRepo, agentManager: agentMgr, - messageQueue: messagequeue.NewService(log), + messageQueue: messagequeue.NewServiceMemory(log), } } @@ -574,7 +574,7 @@ func TestHandleAgentReadyGuards(t *testing.T) { t.Fatalf("expected workflow step to remain step1, got %q", updatedTask.WorkflowStepID) } status := svc.messageQueue.GetStatus(ctx, "s1") - if !status.IsQueued { + if status.Count == 0 { t.Fatalf("expected queued message to remain queued") } }) @@ -680,11 +680,11 @@ func TestExecuteQueuedMessage_RequeuesTransientPromptFailure(t *testing.T) { svc.executeQueuedMessage("s1", queuedMsg) status := svc.messageQueue.GetStatus(ctx, "s1") - if !status.IsQueued || status.Message == nil { - t.Fatalf("expected queued message to be requeued after transient failure") + if status.Count != 1 { + t.Fatalf("expected queued message to be requeued after transient failure, count=%d", status.Count) } - if status.Message.Content != "hello" { - t.Fatalf("expected queued content to be preserved, got %q", status.Message.Content) + if status.Entries[0].Content != "hello" { + t.Fatalf("expected queued content to be preserved, got %q", status.Entries[0].Content) } } @@ -729,7 +729,7 @@ func TestExecuteQueuedMessage_FiresOnTurnStart(t *testing.T) { repo: repo, taskRepo: taskRepo, agentManager: agentMgr, - messageQueue: messagequeue.NewService(log), + messageQueue: messagequeue.NewServiceMemory(log), } svc.SetWorkflowStepGetter(stepGetter) svc.executor = executor.NewExecutor(agentMgr, repo, log, executor.ExecutorConfig{}) @@ -784,7 +784,7 @@ func TestExecuteQueuedMessage_NoOnTurnStart_StepUnchanged(t *testing.T) { repo: repo, taskRepo: taskRepo, agentManager: agentMgr, - messageQueue: messagequeue.NewService(log), + messageQueue: messagequeue.NewServiceMemory(log), } svc.SetWorkflowStepGetter(stepGetter) svc.executor = executor.NewExecutor(agentMgr, repo, log, executor.ExecutorConfig{}) @@ -819,7 +819,7 @@ func createTestServiceWithScheduler(repo *sqliterepo.Repository, stepGetter *moc workflowStepGetter: stepGetter, taskRepo: taskRepo, agentManager: agentMgr, - messageQueue: messagequeue.NewService(log), + messageQueue: messagequeue.NewServiceMemory(log), executor: exec, scheduler: sched, } @@ -1074,8 +1074,8 @@ func TestHandleAgentReady_PassthroughQueuedMessage(t *testing.T) { // Queue should be empty after delivery status := svc.messageQueue.GetStatus(ctx, "s1") - if status.IsQueued { - t.Error("expected queue to be empty after delivery") + if status.Count != 0 { + t.Errorf("expected queue to be empty after delivery, count=%d", status.Count) } }) diff --git a/apps/backend/internal/orchestrator/event_handlers_workflow.go b/apps/backend/internal/orchestrator/event_handlers_workflow.go index be663c0061..ceb9462d6c 100644 --- a/apps/backend/internal/orchestrator/event_handlers_workflow.go +++ b/apps/backend/internal/orchestrator/event_handlers_workflow.go @@ -568,7 +568,13 @@ func (s *Service) reuseSessionForStep(ctx context.Context, taskID string, curren // and gets delivered to the wrong agent the next time that previous // session is reused (e.g. on the on_turn_complete bounce back). if s.messageQueue != nil { - s.messageQueue.TransferSession(ctx, currentSession.ID, existing.ID) + if err := s.messageQueue.TransferSession(ctx, currentSession.ID, existing.ID); err != nil { + // Fail closed: the workflow switch reuses an existing session, but + // orphaning a queued hand-off prompt on the previous session would + // silently misroute the next prompt. Stop here and surface the + // error so the caller can decide whether to retry. + return nil, fmt.Errorf("transfer queued state to reused session: %w", err) + } } s.completeAndStopSession(ctx, taskID, currentSession) @@ -650,7 +656,17 @@ func (s *Service) createNewSessionForStep(ctx context.Context, taskID string, cu // pending move from the old session to the new one — the queue is keyed by // session ID, and without this the prompt would never reach the new agent. if s.messageQueue != nil { - s.messageQueue.TransferSession(ctx, currentSession.ID, newSession.ID) + if err := s.messageQueue.TransferSession(ctx, currentSession.ID, newSession.ID); err != nil { + s.logger.Error("transfer queue to new session failed; queued prompts on the previous session will not be drained", + zap.String("from_session_id", currentSession.ID), + zap.String("to_session_id", newSession.ID), + zap.Error(err)) + // Continue anyway: the new session is already created and committed + // upstream. Failing closed here would leave the workflow in a + // half-switched state (new session exists but caller thinks it + // failed). The error is surfaced via logs and the orphaned entries + // stay safely in the old session for manual recovery. + } } // Promote the new session to primary so it's loaded when navigating back to this task. @@ -1416,6 +1432,22 @@ func (s *Service) clearSessionPlanMode(ctx context.Context, session *models.Task s.setSessionPlanMode(ctx, session, false) } +// SetSessionPlanModeByID looks up the session and writes plan_mode in its metadata. +// Skips passthrough sessions, which manage plan mode in the underlying CLI. +// Public entry point for client-driven plan-mode toggles (e.g. the "Implement plan" +// affordance) so the change is server-authoritative and survives page refresh. +func (s *Service) SetSessionPlanModeByID(ctx context.Context, sessionID string, enabled bool) error { + session, err := s.repo.GetTaskSession(ctx, sessionID) + if err != nil { + return err + } + if s.agentManager.IsPassthroughSession(ctx, session.ID) { + return nil + } + s.setSessionPlanMode(ctx, session, enabled) + return nil +} + // setSessionPlanMode sets or clears plan mode in session metadata. // Uses targeted metadata update to avoid overwriting other session fields. func (s *Service) setSessionPlanMode(ctx context.Context, session *models.TaskSession, enabled bool) { diff --git a/apps/backend/internal/orchestrator/event_handlers_workflow_moved_test.go b/apps/backend/internal/orchestrator/event_handlers_workflow_moved_test.go index 497cd8879b..a143c9a57c 100644 --- a/apps/backend/internal/orchestrator/event_handlers_workflow_moved_test.go +++ b/apps/backend/internal/orchestrator/event_handlers_workflow_moved_test.go @@ -312,12 +312,9 @@ func TestHandleTaskMovedWithSession(t *testing.T) { deadline := time.Now().Add(2 * time.Second) for { status := svc.messageQueue.GetStatus(ctx, "s1") - if status.IsQueued { - if status.Message == nil { - t.Fatal("expected queued message payload") - } - if status.Message.TaskID != "t1" { - t.Fatalf("expected queued task_id t1, got %s", status.Message.TaskID) + if status.Count > 0 { + if status.Entries[0].TaskID != "t1" { + t.Fatalf("expected queued task_id t1, got %s", status.Entries[0].TaskID) } break } diff --git a/apps/backend/internal/orchestrator/event_handlers_workflow_profile_test.go b/apps/backend/internal/orchestrator/event_handlers_workflow_profile_test.go index 5232ec0555..5265c755cd 100644 --- a/apps/backend/internal/orchestrator/event_handlers_workflow_profile_test.go +++ b/apps/backend/internal/orchestrator/event_handlers_workflow_profile_test.go @@ -127,7 +127,7 @@ func TestSwitchSessionForStep(t *testing.T) { workflowStepGetter: newMockStepGetter(), taskRepo: taskRepo, agentManager: agentMgr, - messageQueue: messagequeue.NewService(log), + messageQueue: messagequeue.NewServiceMemory(log), executor: exec, scheduler: sched, } @@ -231,7 +231,7 @@ func TestSwitchSessionForStep_ReusesExistingProfileSession(t *testing.T) { workflowStepGetter: newMockStepGetter(), taskRepo: taskRepo, agentManager: agentMgr, - messageQueue: messagequeue.NewService(log), + messageQueue: messagequeue.NewServiceMemory(log), executor: exec, scheduler: sched, } @@ -359,7 +359,7 @@ func TestSwitchSessionForStep_ReusesPreviouslyLaunchedSession(t *testing.T) { workflowStepGetter: newMockStepGetter(), taskRepo: taskRepo, agentManager: agentMgr, - messageQueue: messagequeue.NewService(log), + messageQueue: messagequeue.NewServiceMemory(log), executor: exec, scheduler: sched, } @@ -451,7 +451,7 @@ func TestSwitchSessionForStep_ReusesFailedSession(t *testing.T) { workflowStepGetter: newMockStepGetter(), taskRepo: taskRepo, agentManager: agentMgr, - messageQueue: messagequeue.NewService(log), + messageQueue: messagequeue.NewServiceMemory(log), executor: exec, scheduler: sched, } @@ -542,7 +542,7 @@ func TestProcessOnEnter_ProfileSwitch(t *testing.T) { workflowStepGetter: sg, taskRepo: taskRepo, agentManager: agentMgr, - messageQueue: messagequeue.NewService(log), + messageQueue: messagequeue.NewServiceMemory(log), executor: exec, scheduler: sched, } @@ -779,7 +779,7 @@ func TestSwitchSessionForStep_PreservesOldSessionOnFailure(t *testing.T) { workflowStepGetter: newMockStepGetter(), taskRepo: taskRepo, agentManager: agentMgr, - messageQueue: messagequeue.NewService(log), + messageQueue: messagequeue.NewServiceMemory(log), executor: exec, scheduler: sched, } diff --git a/apps/backend/internal/orchestrator/event_handlers_workflow_triggers_test.go b/apps/backend/internal/orchestrator/event_handlers_workflow_triggers_test.go index 9d39455390..87e319ba9c 100644 --- a/apps/backend/internal/orchestrator/event_handlers_workflow_triggers_test.go +++ b/apps/backend/internal/orchestrator/event_handlers_workflow_triggers_test.go @@ -402,8 +402,8 @@ func TestProcessOnEnter(t *testing.T) { t.Fatalf("agent received %q, want %q", got, "user queued msg") } - if status := svc.messageQueue.GetStatus(ctx, "s1"); status.IsQueued { - t.Fatalf("expected queue to be drained, still queued: %+v", status.Message) + if status := svc.messageQueue.GetStatus(ctx, "s1"); status.Count != 0 { + t.Fatalf("expected queue to be drained, count=%d entries=%+v", status.Count, status.Entries) } }) @@ -429,14 +429,11 @@ func TestProcessOnEnter(t *testing.T) { deadline := time.Now().Add(2 * time.Second) for { status := svc.messageQueue.GetStatus(ctx, "s1") - if status.IsQueued { - if status.Message == nil { - t.Fatal("expected queued message payload") + if status.Count > 0 { + if status.Entries[0].TaskID != "t1" { + t.Fatalf("expected queued task_id t1, got %s", status.Entries[0].TaskID) } - if status.Message.TaskID != "t1" { - t.Fatalf("expected queued task_id t1, got %s", status.Message.TaskID) - } - if status.Message.Content == "" { + if status.Entries[0].Content == "" { t.Fatal("expected queued content to be populated") } break @@ -590,6 +587,69 @@ func TestProcessOnExit(t *testing.T) { }) } +func TestSetSessionPlanModeByID(t *testing.T) { + ctx := context.Background() + + t.Run("clears plan mode when enabled=false", func(t *testing.T) { + repo := setupTestRepo(t) + seedSession(t, repo, "t1", "s1", "step1") + _ = repo.UpdateSessionMetadata(ctx, "s1", map[string]interface{}{"plan_mode": true}) + + svc := createTestService(repo, newMockStepGetter(), newMockTaskRepo()) + + if err := svc.SetSessionPlanModeByID(ctx, "s1", false); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + updated, _ := repo.GetTaskSession(ctx, "s1") + if pm, _ := updated.Metadata["plan_mode"].(bool); pm { + t.Error("expected plan_mode to be cleared") + } + }) + + t.Run("sets plan mode when enabled=true", func(t *testing.T) { + repo := setupTestRepo(t) + seedSession(t, repo, "t1", "s1", "step1") + + svc := createTestService(repo, newMockStepGetter(), newMockTaskRepo()) + + if err := svc.SetSessionPlanModeByID(ctx, "s1", true); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + updated, _ := repo.GetTaskSession(ctx, "s1") + if pm, ok := updated.Metadata["plan_mode"].(bool); !ok || !pm { + t.Error("expected plan_mode to be true") + } + }) + + t.Run("no-op for passthrough session", func(t *testing.T) { + repo := setupTestRepo(t) + seedSession(t, repo, "t1", "s1", "step1") + _ = repo.UpdateSessionMetadata(ctx, "s1", map[string]interface{}{"plan_mode": true}) + + svc := createTestServiceWithAgent(repo, newMockStepGetter(), newMockTaskRepo(), &mockAgentManager{isPassthrough: true}) + + if err := svc.SetSessionPlanModeByID(ctx, "s1", false); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + updated, _ := repo.GetTaskSession(ctx, "s1") + if pm, ok := updated.Metadata["plan_mode"].(bool); !ok || !pm { + t.Error("expected plan_mode to remain true for passthrough session") + } + }) + + t.Run("propagates session lookup error", func(t *testing.T) { + repo := setupTestRepo(t) + svc := createTestService(repo, newMockStepGetter(), newMockTaskRepo()) + + if err := svc.SetSessionPlanModeByID(ctx, "missing", false); err == nil { + t.Error("expected error for missing session") + } + }) +} + func TestProcessOnEnterPassthrough(t *testing.T) { ctx := context.Background() diff --git a/apps/backend/internal/orchestrator/executor/executor.go b/apps/backend/internal/orchestrator/executor/executor.go index 80770a62d9..31f85dcc7d 100644 --- a/apps/backend/internal/orchestrator/executor/executor.go +++ b/apps/backend/internal/orchestrator/executor/executor.go @@ -257,6 +257,7 @@ type LaunchAgentRequest struct { RepositoryID string // Repository ID for worktree tracking RepositoryPath string // Path to the main repository (for worktree creation) BaseBranch string // Base branch for the worktree (e.g., "main") + DefaultBranch string // Repository's default_branch, used as a fallback when BaseBranch is missing CheckoutBranch string // Branch to fetch and checkout after worktree creation (e.g., PR head branch) WorktreeBranchPrefix string // Branch prefix for worktree branches PullBeforeWorktree bool // Whether to pull from remote before creating the worktree @@ -282,6 +283,7 @@ type RepoSpec struct { RepositoryURL string RepoName string BaseBranch string + DefaultBranch string // Repository's default_branch, used as fallback when BaseBranch is missing CheckoutBranch string WorktreeID string WorktreeBranchPrefix string diff --git a/apps/backend/internal/orchestrator/executor/executor_execute.go b/apps/backend/internal/orchestrator/executor/executor_execute.go index 00a12038cb..9880ed8f18 100644 --- a/apps/backend/internal/orchestrator/executor/executor_execute.go +++ b/apps/backend/internal/orchestrator/executor/executor_execute.go @@ -654,6 +654,7 @@ func buildRepoSpecs(allRepos []*repoInfo) []RepoSpec { spec.RepoName = info.Repository.Name spec.RepoSetupScript = info.Repository.SetupScript spec.RepoCleanupScript = info.Repository.CleanupScript + spec.DefaultBranch = info.Repository.DefaultBranch } // Containerized executors need a clone URL; reuse the same helper as // the single-repo path (best-effort — skipped if Repository is nil). @@ -676,6 +677,9 @@ func (e *Executor) applyRepositoryConfig(req *LaunchAgentRequest, task *v1.Task, req.CheckoutBranch = repoInfo.CheckoutBranch req.WorktreeBranchPrefix = repoInfo.WorktreeBranchPrefix req.PullBeforeWorktree = repoInfo.PullBeforeWorktree + if repoInfo.Repository != nil { + req.DefaultBranch = repoInfo.Repository.DefaultBranch + } // Task directory mode: place worktree inside per-task directory if req.UseWorktree && repoInfo.Repository != nil && repoInfo.Repository.Name != "" { req.TaskDirName = worktree.SemanticWorktreeName(task.Title, worktree.SmallSuffix(3)) diff --git a/apps/backend/internal/orchestrator/handlers/handlers.go b/apps/backend/internal/orchestrator/handlers/handlers.go index cbed2ecf6a..c74330178b 100644 --- a/apps/backend/internal/orchestrator/handlers/handlers.go +++ b/apps/backend/internal/orchestrator/handlers/handlers.go @@ -41,6 +41,7 @@ func (h *Handlers) RegisterHandlers(d *ws.Dispatcher) { d.RegisterFunc(ws.ActionSessionStop, h.wsStopSession) d.RegisterFunc(ws.ActionSessionDelete, h.wsDeleteSession) d.RegisterFunc(ws.ActionSessionSetPrimary, h.wsSetPrimarySession) + d.RegisterFunc(ws.ActionSessionSetPlanMode, h.wsSetPlanMode) d.RegisterFunc(ws.ActionGitHubCheckSessionPR, h.wsCheckSessionPR) } @@ -147,6 +148,34 @@ func (h *Handlers) wsResetContext(ctx context.Context, msg *ws.Message) (*ws.Mes }) } +type wsSetPlanModeRequest struct { + SessionID string `json:"session_id"` + Enabled bool `json:"enabled"` +} + +func (h *Handlers) wsSetPlanMode(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + var req wsSetPlanModeRequest + if err := msg.ParsePayload(&req); err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if req.SessionID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "session_id is required", nil) + } + + if err := h.service.SetSessionPlanModeByID(ctx, req.SessionID, req.Enabled); err != nil { + h.logger.Error("failed to set session plan mode", + zap.String("session_id", req.SessionID), + zap.Bool("enabled", req.Enabled), + zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to set plan mode: "+err.Error(), nil) + } + return ws.NewResponse(msg.ID, msg.Action, map[string]any{ + "success": true, + "session_id": req.SessionID, + "enabled": req.Enabled, + }) +} + type wsRecoverSessionRequest struct { TaskID string `json:"task_id"` SessionID string `json:"session_id"` diff --git a/apps/backend/internal/orchestrator/handlers/queue_handlers.go b/apps/backend/internal/orchestrator/handlers/queue_handlers.go index 32a0eea08f..e9c9d5442b 100644 --- a/apps/backend/internal/orchestrator/handlers/queue_handlers.go +++ b/apps/backend/internal/orchestrator/handlers/queue_handlers.go @@ -2,6 +2,7 @@ package handlers import ( "context" + "errors" "github.com/kandev/kandev/internal/common/logger" "github.com/kandev/kandev/internal/events" @@ -11,23 +12,37 @@ import ( "go.uber.org/zap" ) -// QueueService defines the interface for message queue operations +const ( + // queueErrorCodeEntryNotFound is surfaced when an edit/remove targets an entry + // that has already been drained (atomic-take won the race). + queueErrorCodeEntryNotFound = "entry_not_found" + + // Payload field names — extracted to satisfy goconst (≥3 occurrences). + fieldSessionID = "session_id" + fieldEntryID = "entry_id" + fieldQueueSize = "queue_size" + fieldMax = "max" +) + +// QueueService is the surface the handlers depend on. Real implementation lives +// in messagequeue.Service. type QueueService interface { QueueMessage(ctx context.Context, sessionID, taskID, content, model, userID string, planMode bool, attachments []messagequeue.MessageAttachment) (*messagequeue.QueuedMessage, error) - CancelQueued(ctx context.Context, sessionID string) (*messagequeue.QueuedMessage, error) + AppendContent(ctx context.Context, sessionID, taskID, content, model, userID string, planMode bool, attachments []messagequeue.MessageAttachment) (*messagequeue.QueuedMessage, bool, error) + UpdateMessage(ctx context.Context, sessionID, entryID, content string, attachments []messagequeue.MessageAttachment, queuedBy string) error + RemoveEntry(ctx context.Context, sessionID, entryID string) error + CancelAll(ctx context.Context, sessionID string) (int, error) GetStatus(ctx context.Context, sessionID string) *messagequeue.QueueStatus - UpdateMessage(ctx context.Context, sessionID, content string) error - AppendContent(ctx context.Context, sessionID, content string) error } -// QueueHandlers handles message queue operations +// QueueHandlers handles WebSocket message-queue operations. type QueueHandlers struct { queueService QueueService eventBus bus.EventBus logger *logger.Logger } -// NewQueueHandlers creates a new QueueHandlers instance +// NewQueueHandlers creates a new QueueHandlers instance. func NewQueueHandlers(queueService QueueService, eventBus bus.EventBus, log *logger.Logger) *QueueHandlers { return &QueueHandlers{ queueService: queueService, @@ -36,17 +51,16 @@ func NewQueueHandlers(queueService QueueService, eventBus bus.EventBus, log *log } } -// RegisterHandlers registers queue handlers with the dispatcher +// RegisterHandlers registers queue handlers with the dispatcher. func (h *QueueHandlers) RegisterHandlers(d *ws.Dispatcher) { d.RegisterFunc(ws.ActionMessageQueueAdd, h.wsQueueMessage) - d.RegisterFunc(ws.ActionMessageQueueCancel, h.wsCancelQueue) + d.RegisterFunc(ws.ActionMessageQueueCancel, h.wsCancelAll) d.RegisterFunc(ws.ActionMessageQueueGet, h.wsGetQueueStatus) d.RegisterFunc(ws.ActionMessageQueueUpdate, h.wsUpdateMessage) d.RegisterFunc(ws.ActionMessageQueueAppend, h.wsAppendToQueue) + d.RegisterFunc(ws.ActionMessageQueueRemove, h.wsRemoveEntry) } -// WebSocket Handlers - type wsQueueMessageRequest struct { SessionID string `json:"session_id"` TaskID string `json:"task_id"` @@ -72,37 +86,41 @@ func (h *QueueHandlers) wsQueueMessage(ctx context.Context, msg *ws.Message) (*w if req.Content == "" && len(req.Attachments) == 0 { return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "content or attachments are required", nil) } + if req.UserID == messagequeue.QueuedByAgent { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "user_id may not impersonate the agent identity", nil) + } - queued, err := h.queueService.QueueMessage(ctx, req.SessionID, req.TaskID, req.Content, req.Model, req.UserID, req.PlanMode, req.Attachments) + // Default empty user_id to QueuedByUser so the entry has a non-empty owner; + // the UpdateMessage handler relies on this so its filter against agent + // entries (queued_by="agent") is always meaningful. + queuedBy := req.UserID + if queuedBy == "" { + queuedBy = messagequeue.QueuedByUser + } + queued, err := h.queueService.QueueMessage(ctx, req.SessionID, req.TaskID, req.Content, req.Model, queuedBy, req.PlanMode, req.Attachments) if err != nil { + if errors.Is(err, messagequeue.ErrQueueFull) { + status := h.queueService.GetStatus(ctx, req.SessionID) + return ws.NewError(msg.ID, msg.Action, messagequeue.QueueFullErrorCode, "Queue is full", + map[string]interface{}{ + fieldQueueSize: status.Count, + fieldMax: status.Max, + }) + } h.logger.Error("failed to queue message", zap.Error(err)) return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to queue message", nil) } - // Publish queue status changed event for real-time updates - if h.eventBus != nil { - status := h.queueService.GetStatus(ctx, req.SessionID) - eventData := map[string]interface{}{ - "session_id": req.SessionID, - "is_queued": status.IsQueued, - "message": status.Message, - } - _ = h.eventBus.Publish(ctx, events.MessageQueueStatusChanged, bus.NewEvent( - events.MessageQueueStatusChanged, - "queue-handlers", - eventData, - )) - } - + h.publishStatus(ctx, req.SessionID) return ws.NewResponse(msg.ID, msg.Action, queued) } -type wsCancelQueueRequest struct { +type wsCancelAllRequest struct { SessionID string `json:"session_id"` } -func (h *QueueHandlers) wsCancelQueue(ctx context.Context, msg *ws.Message) (*ws.Message, error) { - var req wsCancelQueueRequest +func (h *QueueHandlers) wsCancelAll(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + var req wsCancelAllRequest if err := msg.ParsePayload(&req); err != nil { return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) } @@ -111,27 +129,16 @@ func (h *QueueHandlers) wsCancelQueue(ctx context.Context, msg *ws.Message) (*ws return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "session_id is required", nil) } - cancelled, err := h.queueService.CancelQueued(ctx, req.SessionID) + removed, err := h.queueService.CancelAll(ctx, req.SessionID) if err != nil { - return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, err.Error(), nil) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil) } - // Publish queue status changed event - if h.eventBus != nil { - status := h.queueService.GetStatus(ctx, req.SessionID) - eventData := map[string]interface{}{ - "session_id": req.SessionID, - "is_queued": status.IsQueued, - "message": status.Message, - } - _ = h.eventBus.Publish(ctx, events.MessageQueueStatusChanged, bus.NewEvent( - events.MessageQueueStatusChanged, - "queue-handlers", - eventData, - )) - } - - return ws.NewResponse(msg.ID, msg.Action, cancelled) + h.publishStatus(ctx, req.SessionID) + return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{ + fieldSessionID: req.SessionID, + "removed": removed, + }) } type wsGetQueueStatusRequest struct { @@ -153,8 +160,11 @@ func (h *QueueHandlers) wsGetQueueStatus(ctx context.Context, msg *ws.Message) ( } type wsUpdateMessageRequest struct { - SessionID string `json:"session_id"` - Content string `json:"content"` + SessionID string `json:"session_id"` + EntryID string `json:"entry_id"` + Content string `json:"content"` + Attachments []messagequeue.MessageAttachment `json:"attachments,omitempty"` + UserID string `json:"user_id,omitempty"` } func (h *QueueHandlers) wsUpdateMessage(ctx context.Context, msg *ws.Message) (*ws.Message, error) { @@ -162,37 +172,71 @@ func (h *QueueHandlers) wsUpdateMessage(ctx context.Context, msg *ws.Message) (* if err := msg.ParsePayload(&req); err != nil { return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) } - if req.SessionID == "" { + // Required so publishStatus can broadcast the post-update list to other + // connected clients; without it they'd be left with a stale view. return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "session_id is required", nil) } - - // Don't allow updating to empty content - user should cancel instead - if req.Content == "" { - return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "content cannot be empty", nil) + if req.EntryID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "entry_id is required", nil) + } + if req.Content == "" && len(req.Attachments) == 0 { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "content or attachments are required", nil) } - if err := h.queueService.UpdateMessage(ctx, req.SessionID, req.Content); err != nil { - return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, err.Error(), nil) + // Reject any client-supplied identity that would impersonate the agent. + // Without this guard a hostile WS client could send user_id="agent" to + // satisfy the `WHERE queued_by = ?` filter on inter-task entries and + // overwrite their content. The reserved sentinel must be settable only + // from the inter-task dispatch path inside the backend. + if req.UserID == messagequeue.QueuedByAgent { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "user_id may not impersonate the agent identity", nil) } - - status := h.queueService.GetStatus(ctx, req.SessionID) - - // Publish queue status changed event - if h.eventBus != nil { - eventData := map[string]interface{}{ - "session_id": req.SessionID, - "is_queued": status.IsQueued, - "message": status.Message, + // Default empty user_id to QueuedByUser so the UpdateContent guard always + // runs against a non-empty owner. Agent entries (queued_by="agent") then + // fail the filter, mirroring the canEdit UI gate at the WS layer. + queuedBy := req.UserID + if queuedBy == "" { + queuedBy = messagequeue.QueuedByUser + } + if err := h.queueService.UpdateMessage(ctx, req.SessionID, req.EntryID, req.Content, req.Attachments, queuedBy); err != nil { + if errors.Is(err, messagequeue.ErrEntryNotFound) { + return ws.NewError(msg.ID, msg.Action, queueErrorCodeEntryNotFound, "Queue entry was already drained or not owned by caller", nil) } - _ = h.eventBus.Publish(ctx, events.MessageQueueStatusChanged, bus.NewEvent( - events.MessageQueueStatusChanged, - "queue-handlers", - eventData, - )) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil) } - return ws.NewResponse(msg.ID, msg.Action, status) + h.publishStatus(ctx, req.SessionID) + return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{fieldEntryID: req.EntryID}) +} + +type wsRemoveEntryRequest struct { + SessionID string `json:"session_id"` + EntryID string `json:"entry_id"` +} + +func (h *QueueHandlers) wsRemoveEntry(ctx context.Context, msg *ws.Message) (*ws.Message, error) { + var req wsRemoveEntryRequest + if err := msg.ParsePayload(&req); err != nil { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) + } + if req.SessionID == "" { + // Required so publishStatus can broadcast the post-removal list. + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "session_id is required", nil) + } + if req.EntryID == "" { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "entry_id is required", nil) + } + + if err := h.queueService.RemoveEntry(ctx, req.SessionID, req.EntryID); err != nil { + if errors.Is(err, messagequeue.ErrEntryNotFound) { + return ws.NewError(msg.ID, msg.Action, queueErrorCodeEntryNotFound, "Queue entry was already drained", nil) + } + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil) + } + + h.publishStatus(ctx, req.SessionID) + return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{fieldEntryID: req.EntryID}) } type wsAppendToQueueRequest struct { @@ -219,33 +263,50 @@ func (h *QueueHandlers) wsAppendToQueue(ctx context.Context, msg *ws.Message) (* if req.Content == "" { return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "content is required", nil) } - - // Try to append to existing queued message; if none exists, create a new one - if err := h.queueService.AppendContent(ctx, req.SessionID, req.Content); err != nil { - _, queueErr := h.queueService.QueueMessage( - ctx, req.SessionID, req.TaskID, req.Content, req.Model, req.UserID, req.PlanMode, nil, - ) - if queueErr != nil { - h.logger.Error("failed to queue message on append fallback", zap.Error(queueErr)) - return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to queue message", nil) - } + if req.UserID == messagequeue.QueuedByAgent { + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "user_id may not impersonate the agent identity", nil) } - status := h.queueService.GetStatus(ctx, req.SessionID) - - // Publish queue status changed event - if h.eventBus != nil { - eventData := map[string]interface{}{ - "session_id": req.SessionID, - "is_queued": status.IsQueued, - "message": status.Message, + queuedBy := req.UserID + if queuedBy == "" { + queuedBy = messagequeue.QueuedByUser + } + queued, appended, err := h.queueService.AppendContent(ctx, req.SessionID, req.TaskID, req.Content, req.Model, queuedBy, req.PlanMode, nil) + if err != nil { + if errors.Is(err, messagequeue.ErrQueueFull) { + status := h.queueService.GetStatus(ctx, req.SessionID) + return ws.NewError(msg.ID, msg.Action, messagequeue.QueueFullErrorCode, "Queue is full", + map[string]interface{}{ + fieldQueueSize: status.Count, + fieldMax: status.Max, + }) } - _ = h.eventBus.Publish(ctx, events.MessageQueueStatusChanged, bus.NewEvent( - events.MessageQueueStatusChanged, - "queue-handlers", - eventData, - )) + h.logger.Error("failed to append to queue", zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to queue message", nil) } - return ws.NewResponse(msg.ID, msg.Action, status) + h.publishStatus(ctx, req.SessionID) + return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{ + fieldEntryID: queued.ID, + "was_append": appended, + }) +} + +// publishStatus emits the latest QueueStatus on the event bus so the frontend +// updates its store after every mutation. +func (h *QueueHandlers) publishStatus(ctx context.Context, sessionID string) { + if h.eventBus == nil { + return + } + status := h.queueService.GetStatus(ctx, sessionID) + _ = h.eventBus.Publish(ctx, events.MessageQueueStatusChanged, bus.NewEvent( + events.MessageQueueStatusChanged, + "queue-handlers", + map[string]interface{}{ + fieldSessionID: sessionID, + "entries": status.Entries, + "count": status.Count, + fieldMax: status.Max, + }, + )) } diff --git a/apps/backend/internal/orchestrator/handlers/queue_handlers_test.go b/apps/backend/internal/orchestrator/handlers/queue_handlers_test.go index 5a862c218a..7dd97c943e 100644 --- a/apps/backend/internal/orchestrator/handlers/queue_handlers_test.go +++ b/apps/backend/internal/orchestrator/handlers/queue_handlers_test.go @@ -3,7 +3,6 @@ package handlers import ( "context" "encoding/json" - "errors" "testing" "time" @@ -15,102 +14,38 @@ import ( "github.com/stretchr/testify/require" ) -// mockQueueService is a simple mock implementation of QueueService -type mockQueueService struct { - queueMessageFunc func(ctx context.Context, sessionID, taskID, content, model, userID string, planMode bool, attachments []messagequeue.MessageAttachment) (*messagequeue.QueuedMessage, error) - cancelQueuedFunc func(ctx context.Context, sessionID string) (*messagequeue.QueuedMessage, error) - getStatusFunc func(ctx context.Context, sessionID string) *messagequeue.QueueStatus - updateMessageFunc func(ctx context.Context, sessionID, content string) error - appendContentFunc func(ctx context.Context, sessionID, content string) error -} +// mockEventBus is a no-op event bus for handler tests. +type mockEventBus struct{} -func (m *mockQueueService) QueueMessage(ctx context.Context, sessionID, taskID, content, model, userID string, planMode bool, attachments []messagequeue.MessageAttachment) (*messagequeue.QueuedMessage, error) { - if m.queueMessageFunc != nil { - return m.queueMessageFunc(ctx, sessionID, taskID, content, model, userID, planMode, attachments) - } - return nil, nil -} - -func (m *mockQueueService) CancelQueued(ctx context.Context, sessionID string) (*messagequeue.QueuedMessage, error) { - if m.cancelQueuedFunc != nil { - return m.cancelQueuedFunc(ctx, sessionID) - } - return nil, nil -} - -func (m *mockQueueService) GetStatus(ctx context.Context, sessionID string) *messagequeue.QueueStatus { - if m.getStatusFunc != nil { - return m.getStatusFunc(ctx, sessionID) - } - return &messagequeue.QueueStatus{} -} - -func (m *mockQueueService) UpdateMessage(ctx context.Context, sessionID, content string) error { - if m.updateMessageFunc != nil { - return m.updateMessageFunc(ctx, sessionID, content) - } +func (m *mockEventBus) Publish(_ context.Context, _ string, _ *bus.Event) error { return nil } - -func (m *mockQueueService) AppendContent(ctx context.Context, sessionID, content string) error { - if m.appendContentFunc != nil { - return m.appendContentFunc(ctx, sessionID, content) - } - return errors.New("no queued message") -} - -// mockEventBus is a simple mock event bus -type mockEventBus struct { - publishFunc func(ctx context.Context, subject string, event *bus.Event) error - subscribeFunc func(subject string, handler bus.EventHandler) (bus.Subscription, error) -} - -func (m *mockEventBus) Publish(ctx context.Context, subject string, event *bus.Event) error { - if m.publishFunc != nil { - return m.publishFunc(ctx, subject, event) - } - return nil -} - -func (m *mockEventBus) Subscribe(subject string, handler bus.EventHandler) (bus.Subscription, error) { - if m.subscribeFunc != nil { - return m.subscribeFunc(subject, handler) - } +func (m *mockEventBus) Subscribe(_ string, _ bus.EventHandler) (bus.Subscription, error) { return nil, nil } - -func (m *mockEventBus) QueueSubscribe(subject, queue string, handler bus.EventHandler) (bus.Subscription, error) { +func (m *mockEventBus) QueueSubscribe(_, _ string, _ bus.EventHandler) (bus.Subscription, error) { return nil, nil } - -func (m *mockEventBus) Request(ctx context.Context, subject string, event *bus.Event, timeout time.Duration) (*bus.Event, error) { +func (m *mockEventBus) Request(_ context.Context, _ string, _ *bus.Event, _ time.Duration) (*bus.Event, error) { return nil, nil } +func (m *mockEventBus) Close() {} +func (m *mockEventBus) IsConnected() bool { return true } -func (m *mockEventBus) Close() { - // no-op -} - -func (m *mockEventBus) IsConnected() bool { - return true -} - -func setupQueueHandlers(t *testing.T) (*QueueHandlers, *mockQueueService, *mockEventBus) { +func setupQueueHandlers(t *testing.T) (*QueueHandlers, *messagequeue.Service) { + t.Helper() log, err := logger.NewLogger(logger.LoggingConfig{ Level: "error", Format: "console", - OutputPath: "stdout", + OutputPath: "stderr", }) require.NoError(t, err) - - mockQueue := &mockQueueService{} - mockBus := &mockEventBus{} - handlers := NewQueueHandlers(mockQueue, mockBus, log) - - return handlers, mockQueue, mockBus + svc := messagequeue.NewServiceMemory(log) + return NewQueueHandlers(svc, &mockEventBus{}, log), svc } func createTestMessage(t *testing.T, action string, payload interface{}) *ws.Message { + t.Helper() data, err := json.Marshal(payload) require.NoError(t, err) return &ws.Message{ @@ -121,472 +56,324 @@ func createTestMessage(t *testing.T, action string, payload interface{}) *ws.Mes } } +func parseError(t *testing.T, response *ws.Message) ws.ErrorPayload { + t.Helper() + var errorPayload ws.ErrorPayload + require.NoError(t, json.Unmarshal(response.Payload, &errorPayload)) + return errorPayload +} + func TestWsQueueMessage(t *testing.T) { - t.Run("successfully queues a message", func(t *testing.T) { - handlers, mockQueue, mockBus := setupQueueHandlers(t) + t.Run("queues a message", func(t *testing.T) { + handlers, _ := setupQueueHandlers(t) ctx := context.Background() - queuedMsg := &messagequeue.QueuedMessage{ - ID: "queue-1", - SessionID: "session-1", - TaskID: "task-1", - Content: "test message", - } - - mockQueue.queueMessageFunc = func(ctx context.Context, sessionID, taskID, content, model, userID string, planMode bool, attachments []messagequeue.MessageAttachment) (*messagequeue.QueuedMessage, error) { - assert.Equal(t, "session-1", sessionID) - assert.Equal(t, "task-1", taskID) - assert.Equal(t, "test message", content) - return queuedMsg, nil - } - - mockQueue.getStatusFunc = func(ctx context.Context, sessionID string) *messagequeue.QueueStatus { - return &messagequeue.QueueStatus{ - IsQueued: true, - Message: queuedMsg, - } - } - - mockBus.publishFunc = func(ctx context.Context, subject string, event *bus.Event) error { - return nil - } - msg := createTestMessage(t, ws.ActionMessageQueueAdd, map[string]interface{}{ "session_id": "session-1", "task_id": "task-1", "content": "test message", - "model": "model-1", "user_id": "user-1", - "plan_mode": false, }) response, err := handlers.wsQueueMessage(ctx, msg) - require.NoError(t, err) assert.Equal(t, ws.MessageTypeResponse, response.Type) }) - t.Run("returns error when session_id missing", func(t *testing.T) { - handlers, _, _ := setupQueueHandlers(t) - ctx := context.Background() - - msg := createTestMessage(t, ws.ActionMessageQueueAdd, map[string]interface{}{ - "task_id": "task-1", - "content": "test", - }) - - response, err := handlers.wsQueueMessage(ctx, msg) - + t.Run("rejects missing session_id", func(t *testing.T) { + handlers, _ := setupQueueHandlers(t) + response, err := handlers.wsQueueMessage(context.Background(), + createTestMessage(t, ws.ActionMessageQueueAdd, map[string]interface{}{"task_id": "t", "content": "x"})) require.NoError(t, err) assert.Equal(t, ws.MessageTypeError, response.Type) - - var errorPayload ws.ErrorPayload - err = json.Unmarshal(response.Payload, &errorPayload) - require.NoError(t, err) - assert.Contains(t, errorPayload.Message, "session_id is required") + assert.Contains(t, parseError(t, response).Message, "session_id is required") }) - t.Run("returns error when task_id missing", func(t *testing.T) { - handlers, _, _ := setupQueueHandlers(t) - ctx := context.Background() - - msg := createTestMessage(t, ws.ActionMessageQueueAdd, map[string]interface{}{ - "session_id": "session-1", - "content": "test", - }) - - response, err := handlers.wsQueueMessage(ctx, msg) - + t.Run("rejects missing task_id", func(t *testing.T) { + handlers, _ := setupQueueHandlers(t) + response, err := handlers.wsQueueMessage(context.Background(), + createTestMessage(t, ws.ActionMessageQueueAdd, map[string]interface{}{"session_id": "s", "content": "x"})) require.NoError(t, err) assert.Equal(t, ws.MessageTypeError, response.Type) - - var errorPayload ws.ErrorPayload - err = json.Unmarshal(response.Payload, &errorPayload) - require.NoError(t, err) - assert.Contains(t, errorPayload.Message, "task_id is required") + assert.Contains(t, parseError(t, response).Message, "task_id is required") }) - t.Run("returns error when both content and attachments missing", func(t *testing.T) { - handlers, _, _ := setupQueueHandlers(t) - ctx := context.Background() - - msg := createTestMessage(t, ws.ActionMessageQueueAdd, map[string]interface{}{ - "session_id": "session-1", - "task_id": "task-1", - }) - - response, err := handlers.wsQueueMessage(ctx, msg) - + t.Run("rejects missing content and attachments", func(t *testing.T) { + handlers, _ := setupQueueHandlers(t) + response, err := handlers.wsQueueMessage(context.Background(), + createTestMessage(t, ws.ActionMessageQueueAdd, map[string]interface{}{"session_id": "s", "task_id": "t"})) require.NoError(t, err) assert.Equal(t, ws.MessageTypeError, response.Type) - - var errorPayload ws.ErrorPayload - err = json.Unmarshal(response.Payload, &errorPayload) - require.NoError(t, err) - assert.Contains(t, errorPayload.Message, "content or attachments are required") + assert.Contains(t, parseError(t, response).Message, "content or attachments are required") }) - t.Run("handles service error", func(t *testing.T) { - handlers, mockQueue, _ := setupQueueHandlers(t) + t.Run("returns queue_full when over cap", func(t *testing.T) { + handlers, svc := setupQueueHandlers(t) ctx := context.Background() - mockQueue.queueMessageFunc = func(ctx context.Context, sessionID, taskID, content, model, userID string, planMode bool, attachments []messagequeue.MessageAttachment) (*messagequeue.QueuedMessage, error) { - return nil, errors.New("service error") + // Saturate the queue. + for i := 0; i < messagequeue.DefaultMaxPerSession; i++ { + _, err := svc.QueueMessage(ctx, "s", "t", "x", "", "u", false, nil) + require.NoError(t, err) } - msg := createTestMessage(t, ws.ActionMessageQueueAdd, map[string]interface{}{ - "session_id": "session-1", - "task_id": "task-1", - "content": "test", - }) - - response, err := handlers.wsQueueMessage(ctx, msg) - + response, err := handlers.wsQueueMessage(ctx, createTestMessage(t, ws.ActionMessageQueueAdd, map[string]interface{}{ + "session_id": "s", + "task_id": "t", + "content": "overflow", + "user_id": "u", + })) require.NoError(t, err) assert.Equal(t, ws.MessageTypeError, response.Type) - - var errorPayload ws.ErrorPayload - err = json.Unmarshal(response.Payload, &errorPayload) - require.NoError(t, err) - assert.Contains(t, errorPayload.Message, "Failed to queue message") + errPayload := parseError(t, response) + assert.Equal(t, "queue_full", errPayload.Code) + assert.EqualValues(t, messagequeue.DefaultMaxPerSession, errPayload.Details["queue_size"]) + assert.EqualValues(t, messagequeue.DefaultMaxPerSession, errPayload.Details["max"]) }) } -func TestWsCancelQueue(t *testing.T) { - t.Run("successfully cancels queued message", func(t *testing.T) { - handlers, mockQueue, mockBus := setupQueueHandlers(t) +func TestWsCancelAll(t *testing.T) { + t.Run("clears the queue", func(t *testing.T) { + handlers, svc := setupQueueHandlers(t) ctx := context.Background() - cancelledMsg := &messagequeue.QueuedMessage{ - ID: "queue-1", - SessionID: "session-1", - Content: "cancelled", + for i := 0; i < 3; i++ { + _, err := svc.QueueMessage(ctx, "s", "t", "x", "", "u", false, nil) + require.NoError(t, err) } - mockQueue.cancelQueuedFunc = func(ctx context.Context, sessionID string) (*messagequeue.QueuedMessage, error) { - return cancelledMsg, nil - } - - mockQueue.getStatusFunc = func(ctx context.Context, sessionID string) *messagequeue.QueueStatus { - return &messagequeue.QueueStatus{ - IsQueued: false, - Message: nil, - } - } - - mockBus.publishFunc = func(ctx context.Context, subject string, event *bus.Event) error { - return nil - } - - msg := createTestMessage(t, ws.ActionMessageQueueCancel, map[string]interface{}{ - "session_id": "session-1", - }) - - response, err := handlers.wsCancelQueue(ctx, msg) - + response, err := handlers.wsCancelAll(ctx, + createTestMessage(t, ws.ActionMessageQueueCancel, map[string]interface{}{"session_id": "s"})) require.NoError(t, err) assert.Equal(t, ws.MessageTypeResponse, response.Type) + + var payload map[string]interface{} + require.NoError(t, json.Unmarshal(response.Payload, &payload)) + assert.EqualValues(t, 3, payload["removed"]) + + assert.Equal(t, 0, svc.GetStatus(ctx, "s").Count) }) - t.Run("returns error when session_id missing", func(t *testing.T) { - handlers, _, _ := setupQueueHandlers(t) - ctx := context.Background() - - msg := createTestMessage(t, ws.ActionMessageQueueCancel, map[string]interface{}{}) - - response, err := handlers.wsCancelQueue(ctx, msg) - - require.NoError(t, err) - assert.Equal(t, ws.MessageTypeError, response.Type) - - var errorPayload ws.ErrorPayload - err = json.Unmarshal(response.Payload, &errorPayload) - require.NoError(t, err) - assert.Contains(t, errorPayload.Message, "session_id is required") - }) - - t.Run("handles service error", func(t *testing.T) { - handlers, mockQueue, _ := setupQueueHandlers(t) - ctx := context.Background() - - mockQueue.cancelQueuedFunc = func(ctx context.Context, sessionID string) (*messagequeue.QueuedMessage, error) { - return nil, errors.New("no message") - } - - msg := createTestMessage(t, ws.ActionMessageQueueCancel, map[string]interface{}{ - "session_id": "session-1", - }) - - response, err := handlers.wsCancelQueue(ctx, msg) - + t.Run("rejects missing session_id", func(t *testing.T) { + handlers, _ := setupQueueHandlers(t) + response, err := handlers.wsCancelAll(context.Background(), + createTestMessage(t, ws.ActionMessageQueueCancel, map[string]interface{}{})) require.NoError(t, err) assert.Equal(t, ws.MessageTypeError, response.Type) + assert.Contains(t, parseError(t, response).Message, "session_id is required") }) } func TestWsGetQueueStatus(t *testing.T) { - t.Run("successfully gets queue status", func(t *testing.T) { - handlers, mockQueue, _ := setupQueueHandlers(t) + t.Run("returns ordered list", func(t *testing.T) { + handlers, svc := setupQueueHandlers(t) ctx := context.Background() - status := &messagequeue.QueueStatus{ - IsQueued: true, - Message: &messagequeue.QueuedMessage{ - ID: "queue-1", - Content: "test", - }, + for _, body := range []string{"a", "b", "c"} { + _, err := svc.QueueMessage(ctx, "s", "t", body, "", "u", false, nil) + require.NoError(t, err) } - mockQueue.getStatusFunc = func(ctx context.Context, sessionID string) *messagequeue.QueueStatus { - return status - } - - msg := createTestMessage(t, ws.ActionMessageQueueGet, map[string]interface{}{ - "session_id": "session-1", - }) - - response, err := handlers.wsGetQueueStatus(ctx, msg) - + response, err := handlers.wsGetQueueStatus(ctx, + createTestMessage(t, ws.ActionMessageQueueGet, map[string]interface{}{"session_id": "s"})) require.NoError(t, err) assert.Equal(t, ws.MessageTypeResponse, response.Type) + + var status messagequeue.QueueStatus + require.NoError(t, json.Unmarshal(response.Payload, &status)) + assert.Equal(t, 3, status.Count) + assert.Equal(t, "a", status.Entries[0].Content) + assert.Equal(t, "c", status.Entries[2].Content) }) - t.Run("returns error when session_id missing", func(t *testing.T) { - handlers, _, _ := setupQueueHandlers(t) - ctx := context.Background() - - msg := createTestMessage(t, ws.ActionMessageQueueGet, map[string]interface{}{}) - - response, err := handlers.wsGetQueueStatus(ctx, msg) - + t.Run("rejects missing session_id", func(t *testing.T) { + handlers, _ := setupQueueHandlers(t) + response, err := handlers.wsGetQueueStatus(context.Background(), + createTestMessage(t, ws.ActionMessageQueueGet, map[string]interface{}{})) require.NoError(t, err) assert.Equal(t, ws.MessageTypeError, response.Type) - - var errorPayload ws.ErrorPayload - err = json.Unmarshal(response.Payload, &errorPayload) - require.NoError(t, err) - assert.Contains(t, errorPayload.Message, "session_id is required") + assert.Contains(t, parseError(t, response).Message, "session_id is required") }) } func TestWsUpdateMessage(t *testing.T) { - t.Run("successfully updates message", func(t *testing.T) { - handlers, mockQueue, mockBus := setupQueueHandlers(t) + t.Run("updates an entry", func(t *testing.T) { + handlers, svc := setupQueueHandlers(t) ctx := context.Background() - mockQueue.updateMessageFunc = func(ctx context.Context, sessionID, content string) error { - assert.Equal(t, "session-1", sessionID) - assert.Equal(t, "updated content", content) - return nil - } - - mockQueue.getStatusFunc = func(ctx context.Context, sessionID string) *messagequeue.QueueStatus { - return &messagequeue.QueueStatus{ - IsQueued: true, - Message: &messagequeue.QueuedMessage{ - ID: "queue-1", - Content: "updated content", - }, - } - } - - mockBus.publishFunc = func(ctx context.Context, subject string, event *bus.Event) error { - return nil - } - - msg := createTestMessage(t, ws.ActionMessageQueueUpdate, map[string]interface{}{ - "session_id": "session-1", - "content": "updated content", - }) - - response, err := handlers.wsUpdateMessage(ctx, msg) + queued, err := svc.QueueMessage(ctx, "s", "t", "original", "", "u", false, nil) + require.NoError(t, err) + response, err := handlers.wsUpdateMessage(ctx, + createTestMessage(t, ws.ActionMessageQueueUpdate, map[string]interface{}{ + "session_id": "s", + "entry_id": queued.ID, + "content": "edited", + "user_id": "u", + })) require.NoError(t, err) assert.Equal(t, ws.MessageTypeResponse, response.Type) + assert.Equal(t, "edited", svc.GetStatus(ctx, "s").Entries[0].Content) }) - t.Run("returns error when session_id missing", func(t *testing.T) { - handlers, _, _ := setupQueueHandlers(t) + t.Run("returns entry_not_found when drained", func(t *testing.T) { + handlers, svc := setupQueueHandlers(t) ctx := context.Background() - msg := createTestMessage(t, ws.ActionMessageQueueUpdate, map[string]interface{}{ - "content": "test", - }) - - response, err := handlers.wsUpdateMessage(ctx, msg) + queued, _ := svc.QueueMessage(ctx, "s", "t", "x", "", "u", false, nil) + _, _ = svc.TakeQueued(ctx, "s") + response, err := handlers.wsUpdateMessage(ctx, + createTestMessage(t, ws.ActionMessageQueueUpdate, map[string]interface{}{ + "session_id": "s", + "entry_id": queued.ID, + "content": "edit", + "user_id": "u", + })) require.NoError(t, err) assert.Equal(t, ws.MessageTypeError, response.Type) - - var errorPayload ws.ErrorPayload - err = json.Unmarshal(response.Payload, &errorPayload) - require.NoError(t, err) - assert.Contains(t, errorPayload.Message, "session_id is required") + assert.Equal(t, "entry_not_found", parseError(t, response).Code) }) - t.Run("returns error when content is empty", func(t *testing.T) { - handlers, _, _ := setupQueueHandlers(t) - ctx := context.Background() - - msg := createTestMessage(t, ws.ActionMessageQueueUpdate, map[string]interface{}{ - "session_id": "session-1", - "content": "", - }) - - response, err := handlers.wsUpdateMessage(ctx, msg) - + t.Run("rejects missing session_id", func(t *testing.T) { + handlers, _ := setupQueueHandlers(t) + response, err := handlers.wsUpdateMessage(context.Background(), + createTestMessage(t, ws.ActionMessageQueueUpdate, map[string]interface{}{"entry_id": "e", "content": "x"})) require.NoError(t, err) assert.Equal(t, ws.MessageTypeError, response.Type) - - var errorPayload ws.ErrorPayload - err = json.Unmarshal(response.Payload, &errorPayload) - require.NoError(t, err) - assert.Contains(t, errorPayload.Message, "content cannot be empty") + assert.Contains(t, parseError(t, response).Message, "session_id is required") }) - t.Run("handles service error", func(t *testing.T) { - handlers, mockQueue, _ := setupQueueHandlers(t) - ctx := context.Background() - - mockQueue.updateMessageFunc = func(ctx context.Context, sessionID, content string) error { - return errors.New("no message") - } - - msg := createTestMessage(t, ws.ActionMessageQueueUpdate, map[string]interface{}{ - "session_id": "session-1", - "content": "test", - }) - - response, err := handlers.wsUpdateMessage(ctx, msg) - + t.Run("rejects missing entry_id", func(t *testing.T) { + handlers, _ := setupQueueHandlers(t) + response, err := handlers.wsUpdateMessage(context.Background(), + createTestMessage(t, ws.ActionMessageQueueUpdate, map[string]interface{}{"session_id": "s", "content": "x"})) require.NoError(t, err) assert.Equal(t, ws.MessageTypeError, response.Type) + assert.Contains(t, parseError(t, response).Message, "entry_id is required") + }) + + t.Run("rejects when content and attachments missing", func(t *testing.T) { + handlers, _ := setupQueueHandlers(t) + response, err := handlers.wsUpdateMessage(context.Background(), + createTestMessage(t, ws.ActionMessageQueueUpdate, map[string]interface{}{"session_id": "s", "entry_id": "e"})) + require.NoError(t, err) + assert.Equal(t, ws.MessageTypeError, response.Type) + assert.Contains(t, parseError(t, response).Message, "content or attachments are required") + }) + + t.Run("rejects user_id impersonating the agent identity", func(t *testing.T) { + handlers, svc := setupQueueHandlers(t) + ctx := context.Background() + queued, _ := svc.QueueMessageWithMetadata(ctx, "s", "t", "agent prompt", "", messagequeue.QueuedByAgent, false, nil, nil) + + response, err := handlers.wsUpdateMessage(ctx, + createTestMessage(t, ws.ActionMessageQueueUpdate, map[string]interface{}{ + "session_id": "s", + "entry_id": queued.ID, + "content": "hijack", + "user_id": messagequeue.QueuedByAgent, + })) + require.NoError(t, err) + assert.Equal(t, ws.MessageTypeError, response.Type) + assert.Contains(t, parseError(t, response).Message, "may not impersonate the agent identity") + + // And confirm the agent entry was not overwritten. + entries := svc.GetStatus(ctx, "s").Entries + require.Len(t, entries, 1) + assert.Equal(t, "agent prompt", entries[0].Content) + }) +} + +func TestWsRemoveEntry(t *testing.T) { + t.Run("removes a single entry", func(t *testing.T) { + handlers, svc := setupQueueHandlers(t) + ctx := context.Background() + + a, _ := svc.QueueMessage(ctx, "s", "t", "a", "", "u", false, nil) + _, _ = svc.QueueMessage(ctx, "s", "t", "b", "", "u", false, nil) + + response, err := handlers.wsRemoveEntry(ctx, + createTestMessage(t, ws.ActionMessageQueueRemove, map[string]interface{}{ + "session_id": "s", + "entry_id": a.ID, + })) + require.NoError(t, err) + assert.Equal(t, ws.MessageTypeResponse, response.Type) + status := svc.GetStatus(ctx, "s") + assert.Equal(t, 1, status.Count) + assert.Equal(t, "b", status.Entries[0].Content) + }) + + t.Run("returns entry_not_found when missing", func(t *testing.T) { + handlers, _ := setupQueueHandlers(t) + response, err := handlers.wsRemoveEntry(context.Background(), + createTestMessage(t, ws.ActionMessageQueueRemove, map[string]interface{}{ + "session_id": "s", + "entry_id": "ghost", + })) + require.NoError(t, err) + assert.Equal(t, ws.MessageTypeError, response.Type) + assert.Equal(t, "entry_not_found", parseError(t, response).Code) + }) + + t.Run("rejects missing session_id", func(t *testing.T) { + handlers, _ := setupQueueHandlers(t) + response, err := handlers.wsRemoveEntry(context.Background(), + createTestMessage(t, ws.ActionMessageQueueRemove, map[string]interface{}{"entry_id": "e"})) + require.NoError(t, err) + assert.Equal(t, ws.MessageTypeError, response.Type) + assert.Contains(t, parseError(t, response).Message, "session_id is required") }) } func TestWsAppendToQueue(t *testing.T) { - t.Run("appends to existing queued message", func(t *testing.T) { - handlers, mockQueue, mockBus := setupQueueHandlers(t) + t.Run("appends to tail when same sender", func(t *testing.T) { + handlers, svc := setupQueueHandlers(t) ctx := context.Background() - mockQueue.appendContentFunc = func(ctx context.Context, sessionID, content string) error { - assert.Equal(t, "session-1", sessionID) - assert.Equal(t, "new comment", content) - return nil - } - - mockQueue.getStatusFunc = func(ctx context.Context, sessionID string) *messagequeue.QueueStatus { - return &messagequeue.QueueStatus{ - IsQueued: true, - Message: &messagequeue.QueuedMessage{ - ID: "queue-1", - Content: "original\n\n---\n\nnew comment", - }, - } - } - - mockBus.publishFunc = func(ctx context.Context, subject string, event *bus.Event) error { - return nil - } - - msg := createTestMessage(t, ws.ActionMessageQueueAppend, map[string]interface{}{ - "session_id": "session-1", - "task_id": "task-1", - "content": "new comment", - }) - - response, err := handlers.wsAppendToQueue(ctx, msg) + _, err := svc.QueueMessage(ctx, "s", "t", "first", "", "user-1", false, nil) + require.NoError(t, err) + response, err := handlers.wsAppendToQueue(ctx, + createTestMessage(t, ws.ActionMessageQueueAppend, map[string]interface{}{ + "session_id": "s", + "task_id": "t", + "content": "second", + "user_id": "user-1", + })) require.NoError(t, err) assert.Equal(t, ws.MessageTypeResponse, response.Type) + assert.Equal(t, 1, svc.GetStatus(ctx, "s").Count) + assert.Contains(t, svc.GetStatus(ctx, "s").Entries[0].Content, "first\n\n---\n\nsecond") }) - t.Run("creates new queued message when none exists", func(t *testing.T) { - handlers, mockQueue, mockBus := setupQueueHandlers(t) + t.Run("inserts when queue empty", func(t *testing.T) { + handlers, svc := setupQueueHandlers(t) ctx := context.Background() - // AppendContent returns error (no existing message) - mockQueue.appendContentFunc = func(ctx context.Context, sessionID, content string) error { - return errors.New("no queued message") - } - - // Falls back to QueueMessage - mockQueue.queueMessageFunc = func(ctx context.Context, sessionID, taskID, content, model, userID string, planMode bool, attachments []messagequeue.MessageAttachment) (*messagequeue.QueuedMessage, error) { - assert.Equal(t, "session-1", sessionID) - assert.Equal(t, "task-1", taskID) - assert.Equal(t, "new comment", content) - return &messagequeue.QueuedMessage{ID: "queue-1", Content: content}, nil - } - - mockQueue.getStatusFunc = func(ctx context.Context, sessionID string) *messagequeue.QueueStatus { - return &messagequeue.QueueStatus{ - IsQueued: true, - Message: &messagequeue.QueuedMessage{ID: "queue-1", Content: "new comment"}, - } - } - - mockBus.publishFunc = func(ctx context.Context, subject string, event *bus.Event) error { - return nil - } - - msg := createTestMessage(t, ws.ActionMessageQueueAppend, map[string]interface{}{ - "session_id": "session-1", - "task_id": "task-1", - "content": "new comment", - }) - - response, err := handlers.wsAppendToQueue(ctx, msg) - + response, err := handlers.wsAppendToQueue(ctx, + createTestMessage(t, ws.ActionMessageQueueAppend, map[string]interface{}{ + "session_id": "s", + "task_id": "t", + "content": "fresh", + "user_id": "u", + })) require.NoError(t, err) assert.Equal(t, ws.MessageTypeResponse, response.Type) + assert.Equal(t, 1, svc.GetStatus(ctx, "s").Count) }) - t.Run("returns error when content is empty", func(t *testing.T) { - handlers, _, _ := setupQueueHandlers(t) - ctx := context.Background() - - msg := createTestMessage(t, ws.ActionMessageQueueAppend, map[string]interface{}{ - "session_id": "session-1", - "task_id": "task-1", - "content": "", - }) - - response, err := handlers.wsAppendToQueue(ctx, msg) - - require.NoError(t, err) - assert.Equal(t, ws.MessageTypeError, response.Type) - - var errorPayload ws.ErrorPayload - err = json.Unmarshal(response.Payload, &errorPayload) - require.NoError(t, err) - assert.Contains(t, errorPayload.Message, "content is required") - }) - - t.Run("returns error when session_id missing", func(t *testing.T) { - handlers, _, _ := setupQueueHandlers(t) - ctx := context.Background() - - msg := createTestMessage(t, ws.ActionMessageQueueAppend, map[string]interface{}{ - "task_id": "task-1", - "content": "test", - }) - - response, err := handlers.wsAppendToQueue(ctx, msg) - + t.Run("rejects missing fields", func(t *testing.T) { + handlers, _ := setupQueueHandlers(t) + response, err := handlers.wsAppendToQueue(context.Background(), + createTestMessage(t, ws.ActionMessageQueueAppend, map[string]interface{}{ + "session_id": "s", + "task_id": "t", + "content": "", + })) require.NoError(t, err) assert.Equal(t, ws.MessageTypeError, response.Type) - }) -} - -func TestRegisterHandlers(t *testing.T) { - t.Run("registers all queue handlers", func(t *testing.T) { - handlers, _, _ := setupQueueHandlers(t) - dispatcher := ws.NewDispatcher() - - handlers.RegisterHandlers(dispatcher) - - // Verify handlers are registered by checking we can access them - // This is a basic smoke test - assert.NotNil(t, dispatcher) + assert.Contains(t, parseError(t, response).Message, "content is required") }) } diff --git a/apps/backend/internal/orchestrator/messagequeue/repository.go b/apps/backend/internal/orchestrator/messagequeue/repository.go new file mode 100644 index 0000000000..0186d1d957 --- /dev/null +++ b/apps/backend/internal/orchestrator/messagequeue/repository.go @@ -0,0 +1,56 @@ +package messagequeue + +import "context" + +// Repository abstracts persistent storage of queued messages and pending moves. +// Operations on queued messages are atomic per session. +type Repository interface { + // Insert appends a new entry at the tail of the session's FIFO queue. + // Returns ErrQueueFull if maxPerSession > 0 and the count would exceed it. + Insert(ctx context.Context, msg *QueuedMessage, maxPerSession int) error + + // AppendOrInsertTail concatenates content onto the tail entry when the tail + // exists AND its QueuedBy matches the supplied queuedBy. Otherwise inserts a + // new entry. Returns the resulting entry and whether the call appended (true) + // or inserted (false). Honors maxPerSession when inserting. + AppendOrInsertTail(ctx context.Context, sessionID, taskID, content, model, queuedBy string, planMode bool, attachments []MessageAttachment, metadata map[string]interface{}, maxPerSession int) (*QueuedMessage, bool, error) + + // ListBySession returns all entries for a session ordered by position ascending. + ListBySession(ctx context.Context, sessionID string) ([]QueuedMessage, error) + + // CountBySession returns the number of entries for a session. + CountBySession(ctx context.Context, sessionID string) (int, error) + + // TakeHead atomically returns and deletes the lowest-position entry for the + // session. Returns nil, nil if the queue is empty. + TakeHead(ctx context.Context, sessionID string) (*QueuedMessage, error) + + // UpdateContent replaces the content/attachments of an entry. The session + // scope (`AND session_id = ?`) is mandatory so a caller can't update an + // entry by guessing its UUID across sessions. If queuedBy is non-empty the + // update only succeeds when the entry's queued_by also matches. Returns + // ErrEntryNotFound when no row matches all guards. + UpdateContent(ctx context.Context, sessionID, entryID, content string, attachments []MessageAttachment, queuedBy string) error + + // DeleteByID removes a single entry. The session scope (`AND session_id = ?`) + // is mandatory so a caller can't delete an entry by guessing its UUID across + // sessions — the queue_full MCP payload deliberately discloses sibling-task + // entry IDs, so without this guard a hostile agent could prune another + // task's queue. Returns ErrEntryNotFound when no row matches. + DeleteByID(ctx context.Context, sessionID, entryID string) error + + // DeleteAllBySession removes every entry for a session. Returns the count of + // rows removed. + DeleteAllBySession(ctx context.Context, sessionID string) (int, error) + + // TransferSession moves all entries (and any pending move) from oldSessionID + // to newSessionID. Used on workflow session switches. + TransferSession(ctx context.Context, oldSessionID, newSessionID string) error + + // SetPendingMove upserts the deferred workflow move for a session. + SetPendingMove(ctx context.Context, sessionID string, move *PendingMove) error + + // TakePendingMove returns and removes the deferred move for a session. + // Returns nil, nil if absent. + TakePendingMove(ctx context.Context, sessionID string) (*PendingMove, error) +} diff --git a/apps/backend/internal/orchestrator/messagequeue/repository_memory.go b/apps/backend/internal/orchestrator/messagequeue/repository_memory.go new file mode 100644 index 0000000000..cb6c6f355d --- /dev/null +++ b/apps/backend/internal/orchestrator/messagequeue/repository_memory.go @@ -0,0 +1,233 @@ +package messagequeue + +import ( + "context" + "sort" + "sync" + "time" + + "github.com/google/uuid" +) + +// memoryRepository is an in-memory Repository implementation used in tests and +// any deployment that explicitly opts into ephemeral queueing. +type memoryRepository struct { + mu sync.Mutex + entries map[string][]*QueuedMessage // sessionID -> ordered list (head = index 0) + nextPosition map[string]int64 // sessionID -> monotonic counter + pendingMoves map[string]*PendingMove +} + +// NewMemoryRepository returns an in-memory Repository. Suitable for tests. +func NewMemoryRepository() Repository { + return &memoryRepository{ + entries: make(map[string][]*QueuedMessage), + nextPosition: make(map[string]int64), + pendingMoves: make(map[string]*PendingMove), + } +} + +func (r *memoryRepository) Insert(_ context.Context, msg *QueuedMessage, maxPerSession int) error { + r.mu.Lock() + defer r.mu.Unlock() + return r.insertLocked(msg, maxPerSession) +} + +// insertLocked performs the actual insert. Caller must already hold r.mu. +func (r *memoryRepository) insertLocked(msg *QueuedMessage, maxPerSession int) error { + list := r.entries[msg.SessionID] + if maxPerSession > 0 && len(list) >= maxPerSession { + return ErrQueueFull + } + if msg.ID == "" { + msg.ID = uuid.New().String() + } + if msg.QueuedAt.IsZero() { + msg.QueuedAt = time.Now().UTC() + } + r.nextPosition[msg.SessionID]++ + msg.Position = r.nextPosition[msg.SessionID] + clone := *msg + r.entries[msg.SessionID] = append(list, &clone) + return nil +} + +// AppendOrInsertTail must hold the lock for the entire check-then-insert path +// so two concurrent same-sender callers can't both observe "no matching tail" +// and race to insert separate entries (which would violate the +// append-or-insert semantics the SQLite repo achieves with a transaction). +func (r *memoryRepository) AppendOrInsertTail(_ context.Context, sessionID, taskID, content, model, queuedBy string, planMode bool, attachments []MessageAttachment, metadata map[string]interface{}, maxPerSession int) (*QueuedMessage, bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + + list := r.entries[sessionID] + if len(list) > 0 { + tail := list[len(list)-1] + if tail.QueuedBy == queuedBy { + tail.Content = tail.Content + "\n\n---\n\n" + content + out := *tail + return &out, true, nil + } + } + + msg := &QueuedMessage{ + SessionID: sessionID, + TaskID: taskID, + Content: content, + Model: model, + PlanMode: planMode, + Attachments: attachments, + Metadata: metadata, + QueuedBy: queuedBy, + } + if err := r.insertLocked(msg, maxPerSession); err != nil { + return nil, false, err + } + return msg, false, nil +} + +func (r *memoryRepository) ListBySession(_ context.Context, sessionID string) ([]QueuedMessage, error) { + r.mu.Lock() + defer r.mu.Unlock() + list := r.entries[sessionID] + out := make([]QueuedMessage, len(list)) + for i, m := range list { + out[i] = *m + } + sort.Slice(out, func(i, j int) bool { return out[i].Position < out[j].Position }) + return out, nil +} + +func (r *memoryRepository) CountBySession(_ context.Context, sessionID string) (int, error) { + r.mu.Lock() + defer r.mu.Unlock() + return len(r.entries[sessionID]), nil +} + +func (r *memoryRepository) TakeHead(_ context.Context, sessionID string) (*QueuedMessage, error) { + r.mu.Lock() + defer r.mu.Unlock() + list := r.entries[sessionID] + if len(list) == 0 { + return nil, nil + } + head := list[0] + r.entries[sessionID] = list[1:] + if len(r.entries[sessionID]) == 0 { + delete(r.entries, sessionID) + delete(r.nextPosition, sessionID) + } + out := *head + return &out, nil +} + +func (r *memoryRepository) UpdateContent(_ context.Context, sessionID, entryID, content string, attachments []MessageAttachment, queuedBy string) error { + r.mu.Lock() + defer r.mu.Unlock() + list, ok := r.entries[sessionID] + if !ok { + return ErrEntryNotFound + } + for _, m := range list { + if m.ID != entryID { + continue + } + if queuedBy != "" && m.QueuedBy != queuedBy { + return ErrEntryNotFound + } + m.Content = content + m.Attachments = attachments + return nil + } + return ErrEntryNotFound +} + +func (r *memoryRepository) DeleteByID(_ context.Context, sessionID, entryID string) error { + r.mu.Lock() + defer r.mu.Unlock() + list, ok := r.entries[sessionID] + if !ok { + return ErrEntryNotFound + } + for i, m := range list { + if m.ID != entryID { + continue + } + r.entries[sessionID] = append(list[:i], list[i+1:]...) + if len(r.entries[sessionID]) == 0 { + delete(r.entries, sessionID) + delete(r.nextPosition, sessionID) + } + return nil + } + return ErrEntryNotFound +} + +func (r *memoryRepository) DeleteAllBySession(_ context.Context, sessionID string) (int, error) { + r.mu.Lock() + defer r.mu.Unlock() + n := len(r.entries[sessionID]) + delete(r.entries, sessionID) + delete(r.nextPosition, sessionID) + return n, nil +} + +func (r *memoryRepository) TransferSession(_ context.Context, oldSessionID, newSessionID string) error { + r.mu.Lock() + defer r.mu.Unlock() + if list, ok := r.entries[oldSessionID]; ok { + // Mirror the SQLite repo: shift transferred positions past the + // destination's max so source entries always sort *after* anything + // already queued there. Without this, a transfer into a non-empty + // destination would mix orderings and break FIFO drain. + var destMax int64 + for _, m := range r.entries[newSessionID] { + if m.Position > destMax { + destMax = m.Position + } + } + for _, m := range list { + m.SessionID = newSessionID + m.Position += destMax + } + r.entries[newSessionID] = append(r.entries[newSessionID], list...) + // Recompute nextPosition for the destination so future inserts keep + // monotonic ordering. + var maxPos int64 + for _, m := range r.entries[newSessionID] { + if m.Position > maxPos { + maxPos = m.Position + } + } + r.nextPosition[newSessionID] = maxPos + delete(r.entries, oldSessionID) + delete(r.nextPosition, oldSessionID) + } + if move, ok := r.pendingMoves[oldSessionID]; ok { + r.pendingMoves[newSessionID] = move + delete(r.pendingMoves, oldSessionID) + } + return nil +} + +func (r *memoryRepository) SetPendingMove(_ context.Context, sessionID string, move *PendingMove) error { + r.mu.Lock() + defer r.mu.Unlock() + if move.QueuedAt.IsZero() { + move.QueuedAt = time.Now().UTC() + } + clone := *move + r.pendingMoves[sessionID] = &clone + return nil +} + +func (r *memoryRepository) TakePendingMove(_ context.Context, sessionID string) (*PendingMove, error) { + r.mu.Lock() + defer r.mu.Unlock() + move, ok := r.pendingMoves[sessionID] + if !ok { + return nil, nil + } + delete(r.pendingMoves, sessionID) + return move, nil +} diff --git a/apps/backend/internal/orchestrator/messagequeue/repository_sqlite.go b/apps/backend/internal/orchestrator/messagequeue/repository_sqlite.go new file mode 100644 index 0000000000..db5dd7a565 --- /dev/null +++ b/apps/backend/internal/orchestrator/messagequeue/repository_sqlite.go @@ -0,0 +1,480 @@ +package messagequeue + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jmoiron/sqlx" +) + +// sqliteRepository persists queued messages and pending moves. +type sqliteRepository struct { + db *sqlx.DB // writer + ro *sqlx.DB // reader +} + +// NewSQLiteRepository creates a SQLite-backed Repository. The supplied writer +// and reader are taken from the shared DB pool. initSchema runs idempotently. +func NewSQLiteRepository(writer, reader *sqlx.DB) (Repository, error) { + r := &sqliteRepository{db: writer, ro: reader} + if err := r.initSchema(); err != nil { + return nil, fmt.Errorf("messagequeue: init schema: %w", err) + } + return r, nil +} + +func (r *sqliteRepository) initSchema() error { + _, err := r.db.Exec(` + CREATE TABLE IF NOT EXISTS queued_messages ( + id TEXT PRIMARY KEY, + session_id TEXT NOT NULL, + task_id TEXT NOT NULL, + position INTEGER NOT NULL, + content TEXT NOT NULL DEFAULT '', + model TEXT NOT NULL DEFAULT '', + plan_mode INTEGER NOT NULL DEFAULT 0, + attachments_json TEXT NOT NULL DEFAULT '[]', + metadata_json TEXT NOT NULL DEFAULT '{}', + queued_at TIMESTAMP NOT NULL, + queued_by TEXT NOT NULL DEFAULT '' + ); + CREATE INDEX IF NOT EXISTS idx_queued_messages_session_position ON queued_messages(session_id, position); + + CREATE TABLE IF NOT EXISTS pending_moves ( + id TEXT PRIMARY KEY, + session_id TEXT NOT NULL UNIQUE, + task_id TEXT NOT NULL DEFAULT '', + workflow_id TEXT NOT NULL DEFAULT '', + workflow_step_id TEXT NOT NULL DEFAULT '', + step_position INTEGER NOT NULL DEFAULT 0, + queued_at TIMESTAMP NOT NULL + ); + `) + return err +} + +func (r *sqliteRepository) Insert(ctx context.Context, msg *QueuedMessage, maxPerSession int) error { + tx, err := r.db.BeginTxx(ctx, nil) + if err != nil { + return fmt.Errorf("begin insert tx: %w", err) + } + defer func() { _ = tx.Rollback() }() + + if maxPerSession > 0 { + var count int + if err := tx.GetContext(ctx, &count, r.db.Rebind(`SELECT COUNT(*) FROM queued_messages WHERE session_id = ?`), msg.SessionID); err != nil { + return fmt.Errorf("count: %w", err) + } + if count >= maxPerSession { + return ErrQueueFull + } + } + + var maxPos sql.NullInt64 + if err := tx.GetContext(ctx, &maxPos, r.db.Rebind(`SELECT MAX(position) FROM queued_messages WHERE session_id = ?`), msg.SessionID); err != nil { + return fmt.Errorf("max position: %w", err) + } + msg.Position = maxPos.Int64 + 1 + if msg.ID == "" { + msg.ID = uuid.New().String() + } + if msg.QueuedAt.IsZero() { + msg.QueuedAt = time.Now().UTC() + } + + attachmentsJSON, err := marshalAttachments(msg.Attachments) + if err != nil { + return err + } + metadataJSON, err := marshalMetadata(msg.Metadata) + if err != nil { + return err + } + + if _, err := tx.ExecContext(ctx, r.db.Rebind(` + INSERT INTO queued_messages + (id, session_id, task_id, position, content, model, plan_mode, attachments_json, metadata_json, queued_at, queued_by) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `), + msg.ID, msg.SessionID, msg.TaskID, msg.Position, msg.Content, msg.Model, + boolToInt(msg.PlanMode), attachmentsJSON, metadataJSON, msg.QueuedAt, msg.QueuedBy, + ); err != nil { + return fmt.Errorf("insert queued_messages: %w", err) + } + return tx.Commit() +} + +func (r *sqliteRepository) AppendOrInsertTail(ctx context.Context, sessionID, taskID, content, model, queuedBy string, planMode bool, attachments []MessageAttachment, metadata map[string]interface{}, maxPerSession int) (*QueuedMessage, bool, error) { + tx, err := r.db.BeginTxx(ctx, nil) + if err != nil { + return nil, false, fmt.Errorf("begin append tx: %w", err) + } + defer func() { _ = tx.Rollback() }() + + tail, err := r.scanTail(ctx, tx, sessionID) + if err != nil { + return nil, false, err + } + if tail != nil && tail.QueuedBy == queuedBy { + newContent := tail.Content + "\n\n---\n\n" + content + if _, err := tx.ExecContext(ctx, r.db.Rebind(`UPDATE queued_messages SET content = ? WHERE id = ?`), newContent, tail.ID); err != nil { + return nil, false, fmt.Errorf("append update: %w", err) + } + tail.Content = newContent + if err := tx.Commit(); err != nil { + return nil, false, err + } + return tail, true, nil + } + + // No matching tail — insert a fresh entry while still inside the same tx. + if maxPerSession > 0 { + var count int + if err := tx.GetContext(ctx, &count, r.db.Rebind(`SELECT COUNT(*) FROM queued_messages WHERE session_id = ?`), sessionID); err != nil { + return nil, false, fmt.Errorf("count: %w", err) + } + if count >= maxPerSession { + return nil, false, ErrQueueFull + } + } + var maxPos sql.NullInt64 + if err := tx.GetContext(ctx, &maxPos, r.db.Rebind(`SELECT MAX(position) FROM queued_messages WHERE session_id = ?`), sessionID); err != nil { + return nil, false, fmt.Errorf("max position: %w", err) + } + + msg := &QueuedMessage{ + ID: uuid.New().String(), + SessionID: sessionID, + TaskID: taskID, + Position: maxPos.Int64 + 1, + Content: content, + Model: model, + PlanMode: planMode, + Attachments: attachments, + Metadata: metadata, + QueuedAt: time.Now().UTC(), + QueuedBy: queuedBy, + } + attachmentsJSON, err := marshalAttachments(attachments) + if err != nil { + return nil, false, err + } + metadataJSON, err := marshalMetadata(metadata) + if err != nil { + return nil, false, err + } + if _, err := tx.ExecContext(ctx, r.db.Rebind(` + INSERT INTO queued_messages + (id, session_id, task_id, position, content, model, plan_mode, attachments_json, metadata_json, queued_at, queued_by) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `), + msg.ID, msg.SessionID, msg.TaskID, msg.Position, msg.Content, msg.Model, + boolToInt(msg.PlanMode), attachmentsJSON, metadataJSON, msg.QueuedAt, msg.QueuedBy, + ); err != nil { + return nil, false, fmt.Errorf("insert queued_messages: %w", err) + } + if err := tx.Commit(); err != nil { + return nil, false, err + } + return msg, false, nil +} + +func (r *sqliteRepository) ListBySession(ctx context.Context, sessionID string) ([]QueuedMessage, error) { + rows, err := r.ro.QueryxContext(ctx, r.ro.Rebind(` + SELECT id, session_id, task_id, position, content, model, plan_mode, + attachments_json, metadata_json, queued_at, queued_by + FROM queued_messages + WHERE session_id = ? + ORDER BY position ASC + `), sessionID) + if err != nil { + return nil, fmt.Errorf("list queued: %w", err) + } + defer func() { _ = rows.Close() }() + + var out []QueuedMessage + for rows.Next() { + msg, err := scanQueuedRow(rows) + if err != nil { + return nil, err + } + out = append(out, *msg) + } + return out, rows.Err() +} + +func (r *sqliteRepository) CountBySession(ctx context.Context, sessionID string) (int, error) { + var n int + err := r.ro.GetContext(ctx, &n, r.ro.Rebind(`SELECT COUNT(*) FROM queued_messages WHERE session_id = ?`), sessionID) + return n, err +} + +func (r *sqliteRepository) TakeHead(ctx context.Context, sessionID string) (*QueuedMessage, error) { + tx, err := r.db.BeginTxx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin take tx: %w", err) + } + defer func() { _ = tx.Rollback() }() + + row := tx.QueryRowxContext(ctx, r.db.Rebind(` + SELECT id, session_id, task_id, position, content, model, plan_mode, + attachments_json, metadata_json, queued_at, queued_by + FROM queued_messages + WHERE session_id = ? + ORDER BY position ASC + LIMIT 1 + `), sessionID) + msg, err := scanQueuedRow(row) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + return nil, fmt.Errorf("take head: %w", err) + } + // Two concurrent TakeHead calls can both observe the same head row in + // their respective DEFERRED transactions; one wins the DELETE, the other + // finds RowsAffected()==0 after waiting on the writer lock. Returning the + // already-drained message in that case would let the orchestrator dispatch + // it twice. Treat the lost race as "queue empty for now" so the caller + // retries on the next agent.ready instead. + res, err := tx.ExecContext(ctx, r.db.Rebind(`DELETE FROM queued_messages WHERE id = ?`), msg.ID) + if err != nil { + return nil, fmt.Errorf("delete head: %w", err) + } + affected, err := res.RowsAffected() + if err != nil { + return nil, fmt.Errorf("delete head rows affected: %w", err) + } + if affected == 0 { + return nil, nil + } + if err := tx.Commit(); err != nil { + return nil, err + } + return msg, nil +} + +func (r *sqliteRepository) UpdateContent(ctx context.Context, sessionID, entryID, content string, attachments []MessageAttachment, queuedBy string) error { + attachmentsJSON, err := marshalAttachments(attachments) + if err != nil { + return err + } + var query string + args := []interface{}{content, attachmentsJSON, entryID, sessionID} + if queuedBy != "" { + query = `UPDATE queued_messages SET content = ?, attachments_json = ? WHERE id = ? AND session_id = ? AND queued_by = ?` + args = append(args, queuedBy) + } else { + query = `UPDATE queued_messages SET content = ?, attachments_json = ? WHERE id = ? AND session_id = ?` + } + res, err := r.db.ExecContext(ctx, r.db.Rebind(query), args...) + if err != nil { + return fmt.Errorf("update queued: %w", err) + } + n, err := res.RowsAffected() + if err != nil { + return err + } + if n == 0 { + return ErrEntryNotFound + } + return nil +} + +func (r *sqliteRepository) DeleteByID(ctx context.Context, sessionID, entryID string) error { + res, err := r.db.ExecContext(ctx, r.db.Rebind(`DELETE FROM queued_messages WHERE id = ? AND session_id = ?`), entryID, sessionID) + if err != nil { + return fmt.Errorf("delete queued: %w", err) + } + n, err := res.RowsAffected() + if err != nil { + return err + } + if n == 0 { + return ErrEntryNotFound + } + return nil +} + +func (r *sqliteRepository) DeleteAllBySession(ctx context.Context, sessionID string) (int, error) { + res, err := r.db.ExecContext(ctx, r.db.Rebind(`DELETE FROM queued_messages WHERE session_id = ?`), sessionID) + if err != nil { + return 0, fmt.Errorf("delete all queued: %w", err) + } + n, err := res.RowsAffected() + return int(n), err +} + +func (r *sqliteRepository) TransferSession(ctx context.Context, oldSessionID, newSessionID string) error { + tx, err := r.db.BeginTxx(ctx, nil) + if err != nil { + return fmt.Errorf("begin transfer tx: %w", err) + } + defer func() { _ = tx.Rollback() }() + + // Shift positions on the destination so transferred entries land at the tail + // without colliding on the (session_id, position) implicit ordering. + var destMax sql.NullInt64 + if err := tx.GetContext(ctx, &destMax, r.db.Rebind(`SELECT MAX(position) FROM queued_messages WHERE session_id = ?`), newSessionID); err != nil { + return fmt.Errorf("transfer max: %w", err) + } + if _, err := tx.ExecContext(ctx, r.db.Rebind(` + UPDATE queued_messages + SET session_id = ?, position = position + ? + WHERE session_id = ? + `), newSessionID, destMax.Int64, oldSessionID); err != nil { + return fmt.Errorf("transfer queued: %w", err) + } + + if _, err := tx.ExecContext(ctx, r.db.Rebind(` + DELETE FROM pending_moves WHERE session_id = ? + `), newSessionID); err != nil { + return fmt.Errorf("clear dest pending move: %w", err) + } + if _, err := tx.ExecContext(ctx, r.db.Rebind(` + UPDATE pending_moves SET session_id = ? WHERE session_id = ? + `), newSessionID, oldSessionID); err != nil { + return fmt.Errorf("transfer pending move: %w", err) + } + return tx.Commit() +} + +func (r *sqliteRepository) SetPendingMove(ctx context.Context, sessionID string, move *PendingMove) error { + if move.QueuedAt.IsZero() { + move.QueuedAt = time.Now().UTC() + } + _, err := r.db.ExecContext(ctx, r.db.Rebind(` + INSERT INTO pending_moves (id, session_id, task_id, workflow_id, workflow_step_id, step_position, queued_at) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(session_id) DO UPDATE SET + task_id = excluded.task_id, + workflow_id = excluded.workflow_id, + workflow_step_id = excluded.workflow_step_id, + step_position = excluded.step_position, + queued_at = excluded.queued_at + `), + uuid.New().String(), sessionID, move.TaskID, move.WorkflowID, move.WorkflowStepID, move.Position, move.QueuedAt, + ) + if err != nil { + return fmt.Errorf("upsert pending move: %w", err) + } + return nil +} + +func (r *sqliteRepository) TakePendingMove(ctx context.Context, sessionID string) (*PendingMove, error) { + tx, err := r.db.BeginTxx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin take pending tx: %w", err) + } + defer func() { _ = tx.Rollback() }() + + var ( + taskID, workflowID, workflowStepID string + position int + queuedAt time.Time + ) + if err := tx.QueryRowxContext(ctx, r.db.Rebind(` + SELECT task_id, workflow_id, workflow_step_id, step_position, queued_at + FROM pending_moves WHERE session_id = ? + `), sessionID).Scan(&taskID, &workflowID, &workflowStepID, &position, &queuedAt); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + return nil, fmt.Errorf("read pending move: %w", err) + } + if _, err := tx.ExecContext(ctx, r.db.Rebind(`DELETE FROM pending_moves WHERE session_id = ?`), sessionID); err != nil { + return nil, fmt.Errorf("delete pending move: %w", err) + } + if err := tx.Commit(); err != nil { + return nil, err + } + return &PendingMove{ + TaskID: taskID, + WorkflowID: workflowID, + WorkflowStepID: workflowStepID, + Position: position, + QueuedAt: queuedAt, + }, nil +} + +// scanTail reads the highest-position entry for a session within an active +// transaction. Returns nil, nil when the queue is empty. +func (r *sqliteRepository) scanTail(ctx context.Context, tx *sqlx.Tx, sessionID string) (*QueuedMessage, error) { + row := tx.QueryRowxContext(ctx, r.db.Rebind(` + SELECT id, session_id, task_id, position, content, model, plan_mode, + attachments_json, metadata_json, queued_at, queued_by + FROM queued_messages + WHERE session_id = ? + ORDER BY position DESC + LIMIT 1 + `), sessionID) + msg, err := scanQueuedRow(row) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + return nil, fmt.Errorf("scan tail: %w", err) + } + return msg, nil +} + +// scanQueuedRow scans a single queued_messages row from any sqlx-compatible row source. +func scanQueuedRow(scanner interface{ Scan(dest ...any) error }) (*QueuedMessage, error) { + var ( + msg QueuedMessage + planModeInt int + attachmentsJSON, metaJSON string + ) + if err := scanner.Scan( + &msg.ID, &msg.SessionID, &msg.TaskID, &msg.Position, &msg.Content, &msg.Model, + &planModeInt, &attachmentsJSON, &metaJSON, &msg.QueuedAt, &msg.QueuedBy, + ); err != nil { + return nil, err + } + msg.PlanMode = planModeInt != 0 + if attachmentsJSON != "" && attachmentsJSON != "[]" { + if err := json.Unmarshal([]byte(attachmentsJSON), &msg.Attachments); err != nil { + return nil, fmt.Errorf("unmarshal attachments: %w", err) + } + } + if metaJSON != "" && metaJSON != "{}" { + if err := json.Unmarshal([]byte(metaJSON), &msg.Metadata); err != nil { + return nil, fmt.Errorf("unmarshal metadata: %w", err) + } + } + return &msg, nil +} + +func marshalAttachments(att []MessageAttachment) (string, error) { + if len(att) == 0 { + return "[]", nil + } + b, err := json.Marshal(att) + if err != nil { + return "", fmt.Errorf("marshal attachments: %w", err) + } + return string(b), nil +} + +func marshalMetadata(meta map[string]interface{}) (string, error) { + if len(meta) == 0 { + return "{}", nil + } + b, err := json.Marshal(meta) + if err != nil { + return "", fmt.Errorf("marshal metadata: %w", err) + } + return string(b), nil +} + +func boolToInt(b bool) int { + if b { + return 1 + } + return 0 +} diff --git a/apps/backend/internal/orchestrator/messagequeue/repository_sqlite_test.go b/apps/backend/internal/orchestrator/messagequeue/repository_sqlite_test.go new file mode 100644 index 0000000000..783ac5bb74 --- /dev/null +++ b/apps/backend/internal/orchestrator/messagequeue/repository_sqlite_test.go @@ -0,0 +1,346 @@ +package messagequeue + +import ( + "context" + "database/sql" + "errors" + "sync" + "sync/atomic" + "testing" + + "github.com/jmoiron/sqlx" + _ "github.com/mattn/go-sqlite3" +) + +func newTestSQLiteRepo(t *testing.T) Repository { + t.Helper() + raw, err := sql.Open("sqlite3", "file::memory:?cache=shared&_foreign_keys=on") + if err != nil { + t.Fatalf("open sqlite: %v", err) + } + raw.SetMaxOpenConns(1) + raw.SetMaxIdleConns(1) + db := sqlx.NewDb(raw, "sqlite3") + t.Cleanup(func() { _ = db.Close() }) + repo, err := NewSQLiteRepository(db, db) + if err != nil { + t.Fatalf("NewSQLiteRepository: %v", err) + } + return repo +} + +func TestSQLiteRepository_InsertList(t *testing.T) { + repo := newTestSQLiteRepo(t) + ctx := context.Background() + + for i, body := range []string{"a", "b", "c"} { + msg := &QueuedMessage{ + SessionID: "s1", TaskID: "t1", Content: body, QueuedBy: "user-1", + } + if err := repo.Insert(ctx, msg, 10); err != nil { + t.Fatalf("insert %d: %v", i, err) + } + if msg.ID == "" { + t.Errorf("insert %d: expected ID to be assigned", i) + } + } + + entries, err := repo.ListBySession(ctx, "s1") + if err != nil { + t.Fatalf("list: %v", err) + } + if len(entries) != 3 { + t.Fatalf("expected 3 entries, got %d", len(entries)) + } + for i, want := range []string{"a", "b", "c"} { + if entries[i].Content != want { + t.Errorf("entry %d content: got %q want %q", i, entries[i].Content, want) + } + } + if entries[0].Position >= entries[1].Position || entries[1].Position >= entries[2].Position { + t.Errorf("positions not monotonic: %d, %d, %d", entries[0].Position, entries[1].Position, entries[2].Position) + } +} + +func TestSQLiteRepository_InsertRejectsOverflow(t *testing.T) { + repo := newTestSQLiteRepo(t) + ctx := context.Background() + + for i := 0; i < 10; i++ { + if err := repo.Insert(ctx, &QueuedMessage{SessionID: "s1", TaskID: "t1", QueuedBy: "user"}, 10); err != nil { + t.Fatalf("insert %d: %v", i, err) + } + } + err := repo.Insert(ctx, &QueuedMessage{SessionID: "s1", TaskID: "t1", QueuedBy: "user"}, 10) + if !errors.Is(err, ErrQueueFull) { + t.Fatalf("expected ErrQueueFull, got %v", err) + } +} + +func TestSQLiteRepository_TakeHeadFIFO(t *testing.T) { + repo := newTestSQLiteRepo(t) + ctx := context.Background() + + for _, body := range []string{"first", "second", "third"} { + if err := repo.Insert(ctx, &QueuedMessage{SessionID: "s1", TaskID: "t1", Content: body, QueuedBy: "u"}, 0); err != nil { + t.Fatalf("insert: %v", err) + } + } + for _, want := range []string{"first", "second", "third"} { + got, err := repo.TakeHead(ctx, "s1") + if err != nil { + t.Fatalf("take: %v", err) + } + if got == nil { + t.Fatalf("take: nil for %q", want) + } + if got.Content != want { + t.Errorf("take: got %q, want %q", got.Content, want) + } + } + got, err := repo.TakeHead(ctx, "s1") + if err != nil { + t.Fatalf("take empty: %v", err) + } + if got != nil { + t.Errorf("expected nil head on empty queue, got %+v", got) + } +} + +func TestSQLiteRepository_AppendOrInsertTail(t *testing.T) { + repo := newTestSQLiteRepo(t) + ctx := context.Background() + + out, appended, err := repo.AppendOrInsertTail(ctx, "s1", "t1", "first", "", "user", false, nil, nil, 10) + if err != nil { + t.Fatalf("append (initial): %v", err) + } + if appended { + t.Error("first call should insert, not append") + } + if out.Content != "first" { + t.Errorf("first content: got %q", out.Content) + } + + out, appended, err = repo.AppendOrInsertTail(ctx, "s1", "t1", "extra", "", "user", false, nil, nil, 10) + if err != nil { + t.Fatalf("append (same sender): %v", err) + } + if !appended { + t.Error("same-sender call should append") + } + if out.Content != "first\n\n---\n\nextra" { + t.Errorf("appended content: got %q", out.Content) + } + + out, appended, err = repo.AppendOrInsertTail(ctx, "s1", "t1", "from agent", "", "agent", false, nil, nil, 10) + if err != nil { + t.Fatalf("append (different sender): %v", err) + } + if appended { + t.Error("different-sender call should insert, not append") + } + if out.Content != "from agent" { + t.Errorf("agent content: got %q", out.Content) + } + + entries, err := repo.ListBySession(ctx, "s1") + if err != nil { + t.Fatalf("list: %v", err) + } + if len(entries) != 2 { + t.Fatalf("expected 2 entries (user-coalesced + agent), got %d", len(entries)) + } +} + +func TestSQLiteRepository_UpdateContent(t *testing.T) { + repo := newTestSQLiteRepo(t) + ctx := context.Background() + + msg := &QueuedMessage{SessionID: "s1", TaskID: "t1", Content: "original", QueuedBy: "user-1"} + if err := repo.Insert(ctx, msg, 0); err != nil { + t.Fatalf("insert: %v", err) + } + + if err := repo.UpdateContent(ctx, "s1", msg.ID, "updated", nil, "user-1"); err != nil { + t.Fatalf("update (matching sender): %v", err) + } + entries, _ := repo.ListBySession(ctx, "s1") + if entries[0].Content != "updated" { + t.Errorf("content after update: got %q", entries[0].Content) + } + + err := repo.UpdateContent(ctx, "s1", msg.ID, "intruder", nil, "user-2") + if !errors.Is(err, ErrEntryNotFound) { + t.Errorf("expected ErrEntryNotFound for non-matching sender, got %v", err) + } + + // Cross-session: same entry id but a different session must not match. + err = repo.UpdateContent(ctx, "s-attacker", msg.ID, "hijack", nil, "user-1") + if !errors.Is(err, ErrEntryNotFound) { + t.Errorf("expected ErrEntryNotFound for cross-session update, got %v", err) + } + + err = repo.UpdateContent(ctx, "s1", "nonexistent", "x", nil, "") + if !errors.Is(err, ErrEntryNotFound) { + t.Errorf("expected ErrEntryNotFound for unknown id, got %v", err) + } +} + +func TestSQLiteRepository_DeleteByID(t *testing.T) { + repo := newTestSQLiteRepo(t) + ctx := context.Background() + + msg := &QueuedMessage{SessionID: "s1", TaskID: "t1", Content: "x", QueuedBy: "u"} + if err := repo.Insert(ctx, msg, 0); err != nil { + t.Fatalf("insert: %v", err) + } + + // Cross-session deletion attempt: must not affect the row. + if err := repo.DeleteByID(ctx, "s-attacker", msg.ID); !errors.Is(err, ErrEntryNotFound) { + t.Errorf("expected ErrEntryNotFound for cross-session delete, got %v", err) + } + count, _ := repo.CountBySession(ctx, "s1") + if count != 1 { + t.Errorf("entry should survive cross-session delete attempt, got count=%d", count) + } + + if err := repo.DeleteByID(ctx, "s1", msg.ID); err != nil { + t.Fatalf("delete: %v", err) + } + if err := repo.DeleteByID(ctx, "s1", msg.ID); !errors.Is(err, ErrEntryNotFound) { + t.Errorf("expected ErrEntryNotFound on second delete, got %v", err) + } +} + +func TestSQLiteRepository_DeleteAllBySession(t *testing.T) { + repo := newTestSQLiteRepo(t) + ctx := context.Background() + + for i := 0; i < 5; i++ { + _ = repo.Insert(ctx, &QueuedMessage{SessionID: "s1", TaskID: "t1", QueuedBy: "u"}, 0) + } + _ = repo.Insert(ctx, &QueuedMessage{SessionID: "s2", TaskID: "t1", QueuedBy: "u"}, 0) + + n, err := repo.DeleteAllBySession(ctx, "s1") + if err != nil { + t.Fatalf("delete all: %v", err) + } + if n != 5 { + t.Errorf("deleted: got %d, want 5", n) + } + count, _ := repo.CountBySession(ctx, "s1") + if count != 0 { + t.Errorf("s1 count after delete-all: %d", count) + } + count, _ = repo.CountBySession(ctx, "s2") + if count != 1 { + t.Errorf("s2 count: got %d, want 1", count) + } +} + +func TestSQLiteRepository_TransferSession(t *testing.T) { + repo := newTestSQLiteRepo(t) + ctx := context.Background() + + _ = repo.Insert(ctx, &QueuedMessage{SessionID: "s-old", TaskID: "t1", Content: "a", QueuedBy: "u"}, 0) + _ = repo.Insert(ctx, &QueuedMessage{SessionID: "s-old", TaskID: "t1", Content: "b", QueuedBy: "u"}, 0) + _ = repo.Insert(ctx, &QueuedMessage{SessionID: "s-new", TaskID: "t1", Content: "existing", QueuedBy: "u"}, 0) + + if err := repo.TransferSession(ctx, "s-old", "s-new"); err != nil { + t.Fatalf("transfer: %v", err) + } + + entries, err := repo.ListBySession(ctx, "s-new") + if err != nil { + t.Fatalf("list: %v", err) + } + if len(entries) != 3 { + t.Fatalf("expected 3 entries on dest after transfer, got %d", len(entries)) + } + if entries[0].Content != "existing" { + t.Errorf("destination tail order broken: head=%q", entries[0].Content) + } + + count, _ := repo.CountBySession(ctx, "s-old") + if count != 0 { + t.Errorf("source still has %d entries after transfer", count) + } +} + +func TestSQLiteRepository_PendingMove(t *testing.T) { + repo := newTestSQLiteRepo(t) + ctx := context.Background() + + if move, err := repo.TakePendingMove(ctx, "s1"); err != nil || move != nil { + t.Fatalf("expected nil move on empty, got %v err=%v", move, err) + } + + move := &PendingMove{TaskID: "t1", WorkflowID: "w1", WorkflowStepID: "step-A", Position: 0} + if err := repo.SetPendingMove(ctx, "s1", move); err != nil { + t.Fatalf("set pending: %v", err) + } + + // Upsert: replace with new target. + move.WorkflowStepID = "step-B" + if err := repo.SetPendingMove(ctx, "s1", move); err != nil { + t.Fatalf("upsert pending: %v", err) + } + + got, err := repo.TakePendingMove(ctx, "s1") + if err != nil { + t.Fatalf("take: %v", err) + } + if got == nil || got.WorkflowStepID != "step-B" { + t.Errorf("expected step-B after upsert, got %+v", got) + } + + // Take again -> nil. + got, err = repo.TakePendingMove(ctx, "s1") + if err != nil || got != nil { + t.Errorf("expected empty after take, got %+v err=%v", got, err) + } +} + +// TestSQLiteRepository_ConcurrentInsertCap exercises the cap under contention: +// 50 goroutines insert into one session with cap=10. Exactly 10 should succeed. +func TestSQLiteRepository_ConcurrentInsertCap(t *testing.T) { + repo := newTestSQLiteRepo(t) + ctx := context.Background() + + const goroutines = 50 + const max = 10 + + var ( + wg sync.WaitGroup + ok atomic.Int32 + full atomic.Int32 + other atomic.Int32 + ) + wg.Add(goroutines) + for i := 0; i < goroutines; i++ { + go func() { + defer wg.Done() + err := repo.Insert(ctx, &QueuedMessage{SessionID: "s1", TaskID: "t1", QueuedBy: "u"}, max) + switch { + case err == nil: + ok.Add(1) + case errors.Is(err, ErrQueueFull): + full.Add(1) + default: + other.Add(1) + } + }() + } + wg.Wait() + + if other.Load() != 0 { + t.Errorf("unexpected non-cap errors: %d", other.Load()) + } + if ok.Load() != int32(max) { + t.Errorf("expected exactly %d successful inserts, got %d", max, ok.Load()) + } + if full.Load() != int32(goroutines-max) { + t.Errorf("expected %d ErrQueueFull, got %d", goroutines-max, full.Load()) + } +} diff --git a/apps/backend/internal/orchestrator/messagequeue/service.go b/apps/backend/internal/orchestrator/messagequeue/service.go index 2d52fb0484..4dfbc994ee 100644 --- a/apps/backend/internal/orchestrator/messagequeue/service.go +++ b/apps/backend/internal/orchestrator/messagequeue/service.go @@ -1,91 +1,51 @@ +// Package messagequeue persists per-session FIFO message queues and deferred +// workflow moves. The queue lets a user (or another agent via the +// message_task_kandev MCP tool) enqueue follow-up prompts while the target +// session is still busy with a turn; handleAgentReady drains one entry per +// turn after each turn completes. +// +// Storage is abstracted behind Repository (SQLite in production, in-memory +// for tests). The service enforces a per-session cap (default 10) and surfaces +// overflow as ErrQueueFull rather than silently dropping the new message. package messagequeue import ( "context" - "fmt" - "sync" - "time" + "errors" - "github.com/google/uuid" "github.com/kandev/kandev/internal/common/logger" "go.uber.org/zap" ) -// Service manages queued messages for sessions. -// Uses in-memory storage as queued messages are best-effort and transient. +// Service manages queued messages for sessions, backed by Repository. type Service struct { - // In-memory storage: sessionID -> QueuedMessage - queued map[string]*QueuedMessage - // In-memory storage: sessionID -> PendingMove (deferred move_task_kandev moves) - pendingMoves map[string]*PendingMove - mu sync.RWMutex - logger *logger.Logger + repo Repository + maxPerSession int + logger *logger.Logger } -// NewService creates a new message queue service -func NewService(log *logger.Logger) *Service { +// NewService creates a Service backed by the supplied repository. maxPerSession +// is the per-session cap (entries beyond this return ErrQueueFull on insert); +// pass 0 to disable the cap. +func NewService(repo Repository, maxPerSession int, log *logger.Logger) *Service { return &Service{ - queued: make(map[string]*QueuedMessage), - pendingMoves: make(map[string]*PendingMove), - logger: log.WithFields(zap.String("component", "message-queue")), + repo: repo, + maxPerSession: maxPerSession, + logger: log.WithFields(zap.String("component", "message-queue")), } } -// TransferSession moves any queued message and pending move from one session -// to another. Used by workflow session switches (when a target step has a -// different agent profile and switchSessionForStep creates a new session) so -// a prompt queued by move_task_kandev on the old session reaches the new one. -// Existing entries on the destination session are preserved if no source entry -// is present; otherwise the source entry replaces the destination entry. -func (s *Service) TransferSession(ctx context.Context, oldSessionID, newSessionID string) { - s.mu.Lock() - defer s.mu.Unlock() - - if msg, ok := s.queued[oldSessionID]; ok { - msg.SessionID = newSessionID - s.queued[newSessionID] = msg - delete(s.queued, oldSessionID) - s.logger.Info("transferred queued message between sessions", - zap.String("from_session_id", oldSessionID), - zap.String("to_session_id", newSessionID), - zap.String("queue_id", msg.ID)) - } - - if move, ok := s.pendingMoves[oldSessionID]; ok { - s.pendingMoves[newSessionID] = move - delete(s.pendingMoves, oldSessionID) - s.logger.Info("transferred pending move between sessions", - zap.String("from_session_id", oldSessionID), - zap.String("to_session_id", newSessionID)) - } +// NewServiceMemory returns a Service backed by an in-memory repository. +// Convenience constructor for tests; cap defaults to 10 for parity with prod. +func NewServiceMemory(log *logger.Logger) *Service { + return NewService(NewMemoryRepository(), DefaultMaxPerSession, log) } -// SetPendingMove records a pending move for a session (replaces any existing one). -// The move is applied by handleAgentReady when the agent's current turn completes. -func (s *Service) SetPendingMove(ctx context.Context, sessionID string, move *PendingMove) { - s.mu.Lock() - defer s.mu.Unlock() - move.QueuedAt = time.Now() - s.pendingMoves[sessionID] = move - s.logger.Info("pending move recorded", - zap.String("session_id", sessionID), - zap.String("task_id", move.TaskID), - zap.String("workflow_step_id", move.WorkflowStepID)) -} +// MaxPerSession returns the configured per-session cap. +func (s *Service) MaxPerSession() int { return s.maxPerSession } -// TakePendingMove retrieves and removes the pending move for a session. -func (s *Service) TakePendingMove(ctx context.Context, sessionID string) (*PendingMove, bool) { - s.mu.Lock() - defer s.mu.Unlock() - move, exists := s.pendingMoves[sessionID] - if !exists { - return nil, false - } - delete(s.pendingMoves, sessionID) - return move, true -} - -// QueueMessage queues a message for a session (replaces existing queued message) +// QueueMessage appends a new entry to the session's FIFO queue. Returns +// ErrQueueFull when the cap is exceeded. func (s *Service) QueueMessage(ctx context.Context, sessionID, taskID, content, model, userID string, planMode bool, attachments []MessageAttachment) (*QueuedMessage, error) { return s.QueueMessageWithMetadata(ctx, sessionID, taskID, content, model, userID, planMode, attachments, nil) } @@ -94,11 +54,7 @@ func (s *Service) QueueMessage(ctx context.Context, sessionID, taskID, content, // is propagated to the resulting Message row when the queued message is // drained (e.g. sender_task_id for messages sent via message_task_kandev). func (s *Service) QueueMessageWithMetadata(ctx context.Context, sessionID, taskID, content, model, userID string, planMode bool, attachments []MessageAttachment, metadata map[string]interface{}) (*QueuedMessage, error) { - s.mu.Lock() - defer s.mu.Unlock() - msg := &QueuedMessage{ - ID: uuid.New().String(), SessionID: sessionID, TaskID: taskID, Content: content, @@ -106,101 +62,164 @@ func (s *Service) QueueMessageWithMetadata(ctx context.Context, sessionID, taskI PlanMode: planMode, Attachments: attachments, Metadata: metadata, - QueuedAt: time.Now(), QueuedBy: userID, } - - s.queued[sessionID] = msg + if err := s.repo.Insert(ctx, msg, s.maxPerSession); err != nil { + if errors.Is(err, ErrQueueFull) { + s.logger.Info("queue full", + zap.String("session_id", sessionID), + zap.Int("max", s.maxPerSession)) + } + return nil, err + } s.logger.Info("message queued", zap.String("session_id", sessionID), zap.String("task_id", taskID), + zap.String("entry_id", msg.ID), + zap.Int64("position", msg.Position), zap.Int("content_length", len(content))) - return msg, nil } -// TakeQueued retrieves and removes the queued message for a session -func (s *Service) TakeQueued(ctx context.Context, sessionID string) (*QueuedMessage, bool) { - s.mu.Lock() - defer s.mu.Unlock() +// AppendContent appends content onto the session's tail entry when the tail's +// queued_by matches userID. Otherwise inserts a new entry. Returns +// ErrQueueFull when an insert would exceed the cap. +func (s *Service) AppendContent(ctx context.Context, sessionID, taskID, content, model, userID string, planMode bool, attachments []MessageAttachment) (*QueuedMessage, bool, error) { + msg, appended, err := s.repo.AppendOrInsertTail(ctx, sessionID, taskID, content, model, userID, planMode, attachments, nil, s.maxPerSession) + if err != nil { + return nil, false, err + } + s.logger.Info("queue append-or-insert", + zap.String("session_id", sessionID), + zap.String("entry_id", msg.ID), + zap.Bool("appended", appended)) + return msg, appended, nil +} - msg, exists := s.queued[sessionID] - if !exists { +// TakeQueued atomically removes and returns the head entry. Returns nil, false +// when the queue is empty. +func (s *Service) TakeQueued(ctx context.Context, sessionID string) (*QueuedMessage, bool) { + msg, err := s.repo.TakeHead(ctx, sessionID) + if err != nil { + s.logger.Error("take head failed", + zap.String("session_id", sessionID), + zap.Error(err)) + return nil, false + } + if msg == nil { return nil, false } - - delete(s.queued, sessionID) s.logger.Info("message dequeued", zap.String("session_id", sessionID), - zap.String("queue_id", msg.ID)) - + zap.String("entry_id", msg.ID)) return msg, true } -// CancelQueued removes a queued message without consuming it -func (s *Service) CancelQueued(ctx context.Context, sessionID string) (*QueuedMessage, error) { - s.mu.Lock() - defer s.mu.Unlock() - - msg, exists := s.queued[sessionID] - if !exists { - return nil, fmt.Errorf("no queued message for session %s", sessionID) +// UpdateMessage replaces the content (and optionally attachments) of a queued +// entry. The sessionID scope is mandatory — callers can't update an entry by +// guessing its UUID across sessions. Returns ErrEntryNotFound when the entry +// was already drained, the session doesn't own it, or the queuedBy guard +// rejects the caller. +func (s *Service) UpdateMessage(ctx context.Context, sessionID, entryID, content string, attachments []MessageAttachment, queuedBy string) error { + if err := s.repo.UpdateContent(ctx, sessionID, entryID, content, attachments, queuedBy); err != nil { + return err } - - delete(s.queued, sessionID) - s.logger.Info("message queue cancelled", + s.logger.Info("queued entry updated", zap.String("session_id", sessionID), - zap.String("queue_id", msg.ID)) - - return msg, nil + zap.String("entry_id", entryID)) + return nil } -// GetStatus returns the queue status for a session +// RemoveEntry deletes a single entry. The sessionID scope is mandatory — see +// the rationale on the Repository.DeleteByID contract for why. Returns +// ErrEntryNotFound when no entry matches. +func (s *Service) RemoveEntry(ctx context.Context, sessionID, entryID string) error { + if err := s.repo.DeleteByID(ctx, sessionID, entryID); err != nil { + return err + } + s.logger.Info("queued entry removed", + zap.String("session_id", sessionID), + zap.String("entry_id", entryID)) + return nil +} + +// CancelAll clears every queued entry for a session. Returns the number of +// rows removed. +func (s *Service) CancelAll(ctx context.Context, sessionID string) (int, error) { + n, err := s.repo.DeleteAllBySession(ctx, sessionID) + if err != nil { + return 0, err + } + s.logger.Info("queue cancel-all", + zap.String("session_id", sessionID), + zap.Int("removed", n)) + return n, nil +} + +// GetStatus returns the full pending list and capacity info for a session. func (s *Service) GetStatus(ctx context.Context, sessionID string) *QueueStatus { - s.mu.RLock() - defer s.mu.RUnlock() - - msg, exists := s.queued[sessionID] + entries, err := s.repo.ListBySession(ctx, sessionID) + if err != nil { + s.logger.Error("list queued failed", + zap.String("session_id", sessionID), + zap.Error(err)) + return &QueueStatus{Entries: []QueuedMessage{}, Count: 0, Max: s.maxPerSession} + } + if entries == nil { + entries = []QueuedMessage{} + } return &QueueStatus{ - IsQueued: exists, - Message: msg, + Entries: entries, + Count: len(entries), + Max: s.maxPerSession, } } -// AppendContent appends content to an existing queued message. -// Returns an error if no message is queued (caller should use QueueMessage instead). -func (s *Service) AppendContent(ctx context.Context, sessionID, content string) error { - s.mu.Lock() - defer s.mu.Unlock() - - msg, exists := s.queued[sessionID] - if !exists { - return fmt.Errorf("no queued message for session %s", sessionID) +// TransferSession moves any queued messages and pending move from one session +// to another. Used by workflow session switches. Returns an error so the +// caller can fail closed instead of silently leaving entries orphaned on the +// old session — a transfer that no-ops without a signal would let the workflow +// step move forward while the queue sticks behind. +func (s *Service) TransferSession(ctx context.Context, oldSessionID, newSessionID string) error { + if err := s.repo.TransferSession(ctx, oldSessionID, newSessionID); err != nil { + s.logger.Error("transfer session failed", + zap.String("from_session_id", oldSessionID), + zap.String("to_session_id", newSessionID), + zap.Error(err)) + return err } - - msg.Content = msg.Content + "\n\n---\n\n" + content - s.logger.Info("content appended to queued message", - zap.String("session_id", sessionID), - zap.Int("appended_length", len(content)), - zap.Int("total_length", len(msg.Content))) - + s.logger.Info("transferred queue between sessions", + zap.String("from_session_id", oldSessionID), + zap.String("to_session_id", newSessionID)) return nil } -// UpdateMessage updates an existing queued message (for arrow up editing) -func (s *Service) UpdateMessage(ctx context.Context, sessionID, content string) error { - s.mu.Lock() - defer s.mu.Unlock() - - msg, exists := s.queued[sessionID] - if !exists { - return fmt.Errorf("no queued message for session %s", sessionID) +// SetPendingMove records a pending move for a session (replaces any existing one). +// The move is applied by handleAgentReady when the agent's current turn completes. +func (s *Service) SetPendingMove(ctx context.Context, sessionID string, move *PendingMove) { + if err := s.repo.SetPendingMove(ctx, sessionID, move); err != nil { + s.logger.Error("set pending move failed", + zap.String("session_id", sessionID), + zap.Error(err)) + return } - - msg.Content = content - s.logger.Info("queued message updated", + s.logger.Info("pending move recorded", zap.String("session_id", sessionID), - zap.Int("new_length", len(content))) - - return nil + zap.String("task_id", move.TaskID), + zap.String("workflow_step_id", move.WorkflowStepID)) +} + +// TakePendingMove retrieves and removes the pending move for a session. +func (s *Service) TakePendingMove(ctx context.Context, sessionID string) (*PendingMove, bool) { + move, err := s.repo.TakePendingMove(ctx, sessionID) + if err != nil { + s.logger.Error("take pending move failed", + zap.String("session_id", sessionID), + zap.Error(err)) + return nil, false + } + if move == nil { + return nil, false + } + return move, true } diff --git a/apps/backend/internal/orchestrator/messagequeue/service_test.go b/apps/backend/internal/orchestrator/messagequeue/service_test.go index b0a8a0606b..142c6bca9b 100644 --- a/apps/backend/internal/orchestrator/messagequeue/service_test.go +++ b/apps/backend/internal/orchestrator/messagequeue/service_test.go @@ -2,7 +2,9 @@ package messagequeue import ( "context" + "errors" "sync" + "sync/atomic" "testing" "time" @@ -12,53 +14,56 @@ import ( ) func setupService(t *testing.T) *Service { + t.Helper() log, err := logger.NewLogger(logger.LoggingConfig{ Level: "error", Format: "console", - OutputPath: "stdout", + OutputPath: "stderr", }) require.NoError(t, err) - return NewService(log) + return NewServiceMemory(log) } func TestQueueMessage(t *testing.T) { - t.Run("successfully queues a message", func(t *testing.T) { + t.Run("appends new entries", func(t *testing.T) { svc := setupService(t) ctx := context.Background() msg, err := svc.QueueMessage(ctx, "session-1", "task-1", "test content", "model-1", "user-1", false, nil) - require.NoError(t, err) assert.NotEmpty(t, msg.ID) assert.Equal(t, "session-1", msg.SessionID) - assert.Equal(t, "task-1", msg.TaskID) assert.Equal(t, "test content", msg.Content) - assert.Equal(t, "model-1", msg.Model) assert.Equal(t, "user-1", msg.QueuedBy) - assert.False(t, msg.PlanMode) assert.NotZero(t, msg.QueuedAt) + assert.Equal(t, int64(1), msg.Position) }) - t.Run("replaces existing queued message for same session", func(t *testing.T) { + t.Run("multiple messages produce ordered list", func(t *testing.T) { svc := setupService(t) ctx := context.Background() - // Queue first message - msg1, err := svc.QueueMessage(ctx, "session-1", "task-1", "first message", "model-1", "user-1", false, nil) - require.NoError(t, err) - - // Queue second message for same session - msg2, err := svc.QueueMessage(ctx, "session-1", "task-1", "second message", "model-1", "user-1", false, nil) - require.NoError(t, err) - - // IDs should be different - assert.NotEqual(t, msg1.ID, msg2.ID) - - // Only the second message should be queued + for _, body := range []string{"first", "second", "third"} { + _, err := svc.QueueMessage(ctx, "session-1", "task-1", body, "", "user-1", false, nil) + require.NoError(t, err) + } status := svc.GetStatus(ctx, "session-1") - assert.True(t, status.IsQueued) - assert.Equal(t, msg2.ID, status.Message.ID) - assert.Equal(t, "second message", status.Message.Content) + require.Equal(t, 3, status.Count) + assert.Equal(t, "first", status.Entries[0].Content) + assert.Equal(t, "second", status.Entries[1].Content) + assert.Equal(t, "third", status.Entries[2].Content) + }) + + t.Run("rejects overflow with ErrQueueFull", func(t *testing.T) { + svc := setupService(t) + ctx := context.Background() + + for i := 0; i < DefaultMaxPerSession; i++ { + _, err := svc.QueueMessage(ctx, "s", "t", "x", "", "u", false, nil) + require.NoError(t, err) + } + _, err := svc.QueueMessage(ctx, "s", "t", "x", "", "u", false, nil) + assert.ErrorIs(t, err, ErrQueueFull) }) t.Run("queues messages with attachments", func(t *testing.T) { @@ -68,461 +73,344 @@ func TestQueueMessage(t *testing.T) { attachments := []MessageAttachment{ {Type: "image", Data: "base64data", MimeType: "image/png"}, } - - msg, err := svc.QueueMessage(ctx, "session-1", "task-1", "message with attachment", "model-1", "user-1", false, attachments) - + msg, err := svc.QueueMessage(ctx, "session-1", "task-1", "with attachment", "", "user-1", false, attachments) require.NoError(t, err) assert.Len(t, msg.Attachments, 1) assert.Equal(t, "image", msg.Attachments[0].Type) }) - - t.Run("supports plan mode flag", func(t *testing.T) { - svc := setupService(t) - ctx := context.Background() - - msg, err := svc.QueueMessage(ctx, "session-1", "task-1", "plan mode message", "model-1", "user-1", true, nil) - - require.NoError(t, err) - assert.True(t, msg.PlanMode) - }) } -func TestTransferSession(t *testing.T) { - t.Run("moves queued message and pending move from old to new session", func(t *testing.T) { +func TestAppendContent(t *testing.T) { + t.Run("appends to tail when same sender", func(t *testing.T) { svc := setupService(t) ctx := context.Background() - _, err := svc.QueueMessage(ctx, "old-sess", "task-1", "hand-off prompt", "", "mcp-move-task", false, nil) + _, err := svc.QueueMessage(ctx, "s", "t", "first", "", "user", false, nil) require.NoError(t, err) - svc.SetPendingMove(ctx, "old-sess", &PendingMove{ - TaskID: "task-1", - WorkflowStepID: "step-b", - }) - svc.TransferSession(ctx, "old-sess", "new-sess") + _, appended, err := svc.AppendContent(ctx, "s", "t", "second", "", "user", false, nil) + require.NoError(t, err) + assert.True(t, appended) - // Old session is empty. - _, exists := svc.TakeQueued(ctx, "old-sess") - assert.False(t, exists) - _, exists = svc.TakePendingMove(ctx, "old-sess") - assert.False(t, exists) - - // New session has both. - msg, exists := svc.TakeQueued(ctx, "new-sess") - require.True(t, exists) - assert.Equal(t, "hand-off prompt", msg.Content) - assert.Equal(t, "new-sess", msg.SessionID) - - move, exists := svc.TakePendingMove(ctx, "new-sess") - require.True(t, exists) - assert.Equal(t, "step-b", move.WorkflowStepID) + status := svc.GetStatus(ctx, "s") + require.Equal(t, 1, status.Count) + assert.Equal(t, "first\n\n---\n\nsecond", status.Entries[0].Content) }) - t.Run("no-op when source session is empty", func(t *testing.T) { + t.Run("inserts new entry when tail is different sender", func(t *testing.T) { svc := setupService(t) ctx := context.Background() - svc.TransferSession(ctx, "empty-sess", "new-sess") + _, err := svc.QueueMessage(ctx, "s", "t", "from user", "", "user", false, nil) + require.NoError(t, err) - _, exists := svc.TakeQueued(ctx, "new-sess") - assert.False(t, exists) + _, appended, err := svc.AppendContent(ctx, "s", "t", "from agent", "", "agent", false, nil) + require.NoError(t, err) + assert.False(t, appended) + + status := svc.GetStatus(ctx, "s") + assert.Equal(t, 2, status.Count) }) -} -func TestPendingMove(t *testing.T) { - t.Run("set then take returns the move and clears it", func(t *testing.T) { + t.Run("inserts new entry when queue empty", func(t *testing.T) { svc := setupService(t) ctx := context.Background() - svc.SetPendingMove(ctx, "session-1", &PendingMove{ - TaskID: "task-1", - WorkflowID: "wf-1", - WorkflowStepID: "step-2", - Position: 3, - }) + _, appended, err := svc.AppendContent(ctx, "s", "t", "fresh", "", "user", false, nil) + require.NoError(t, err) + assert.False(t, appended) - got, exists := svc.TakePendingMove(ctx, "session-1") - require.True(t, exists) - assert.Equal(t, "task-1", got.TaskID) - assert.Equal(t, "step-2", got.WorkflowStepID) - assert.Equal(t, 3, got.Position) - assert.NotZero(t, got.QueuedAt) - - // Idempotent — second take returns nothing. - _, exists = svc.TakePendingMove(ctx, "session-1") - assert.False(t, exists) - }) - - t.Run("setting twice replaces the previous move", func(t *testing.T) { - svc := setupService(t) - ctx := context.Background() - - svc.SetPendingMove(ctx, "session-1", &PendingMove{TaskID: "task-1", WorkflowStepID: "step-a"}) - svc.SetPendingMove(ctx, "session-1", &PendingMove{TaskID: "task-1", WorkflowStepID: "step-b"}) - - got, exists := svc.TakePendingMove(ctx, "session-1") - require.True(t, exists) - assert.Equal(t, "step-b", got.WorkflowStepID) + status := svc.GetStatus(ctx, "s") + require.Equal(t, 1, status.Count) + assert.Equal(t, "fresh", status.Entries[0].Content) }) } func TestTakeQueued(t *testing.T) { - t.Run("retrieves and removes queued message", func(t *testing.T) { + t.Run("returns entries in FIFO order", func(t *testing.T) { svc := setupService(t) ctx := context.Background() - // Queue a message - original, err := svc.QueueMessage(ctx, "session-1", "task-1", "test content", "model-1", "user-1", false, nil) - require.NoError(t, err) - - // Take the message - msg, exists := svc.TakeQueued(ctx, "session-1") - - assert.True(t, exists) - assert.Equal(t, original.ID, msg.ID) - assert.Equal(t, "test content", msg.Content) - - // Should be removed after taking - status := svc.GetStatus(ctx, "session-1") - assert.False(t, status.IsQueued) - assert.Nil(t, status.Message) + for _, body := range []string{"first", "second", "third"} { + _, err := svc.QueueMessage(ctx, "s", "t", body, "", "u", false, nil) + require.NoError(t, err) + } + for _, want := range []string{"first", "second", "third"} { + msg, ok := svc.TakeQueued(ctx, "s") + require.True(t, ok, "queue empty before %q", want) + assert.Equal(t, want, msg.Content) + } + _, ok := svc.TakeQueued(ctx, "s") + assert.False(t, ok) }) - t.Run("returns false when no message queued", func(t *testing.T) { + t.Run("returns false when empty", func(t *testing.T) { svc := setupService(t) ctx := context.Background() - msg, exists := svc.TakeQueued(ctx, "session-1") - - assert.False(t, exists) + msg, ok := svc.TakeQueued(ctx, "s") + assert.False(t, ok) assert.Nil(t, msg) }) - - t.Run("is idempotent - second take returns false", func(t *testing.T) { - svc := setupService(t) - ctx := context.Background() - - // Queue and take once - _, err := svc.QueueMessage(ctx, "session-1", "task-1", "test", "model-1", "user-1", false, nil) - require.NoError(t, err) - _, exists := svc.TakeQueued(ctx, "session-1") - require.True(t, exists) - - // Second take should return false - _, exists = svc.TakeQueued(ctx, "session-1") - assert.False(t, exists) - }) -} - -func TestCancelQueued(t *testing.T) { - t.Run("cancels and removes queued message", func(t *testing.T) { - svc := setupService(t) - ctx := context.Background() - - // Queue a message - original, err := svc.QueueMessage(ctx, "session-1", "task-1", "test content", "model-1", "user-1", false, nil) - require.NoError(t, err) - - // Cancel it - cancelled, err := svc.CancelQueued(ctx, "session-1") - - require.NoError(t, err) - assert.Equal(t, original.ID, cancelled.ID) - - // Should be removed - status := svc.GetStatus(ctx, "session-1") - assert.False(t, status.IsQueued) - }) - - t.Run("returns error when no message queued", func(t *testing.T) { - svc := setupService(t) - ctx := context.Background() - - _, err := svc.CancelQueued(ctx, "session-1") - - assert.Error(t, err) - assert.Contains(t, err.Error(), "no queued message") - }) -} - -func TestGetStatus(t *testing.T) { - t.Run("returns queued status with message", func(t *testing.T) { - svc := setupService(t) - ctx := context.Background() - - msg, err := svc.QueueMessage(ctx, "session-1", "task-1", "test", "model-1", "user-1", false, nil) - require.NoError(t, err) - - status := svc.GetStatus(ctx, "session-1") - - assert.True(t, status.IsQueued) - assert.NotNil(t, status.Message) - assert.Equal(t, msg.ID, status.Message.ID) - }) - - t.Run("returns not queued status when no message", func(t *testing.T) { - svc := setupService(t) - ctx := context.Background() - - status := svc.GetStatus(ctx, "session-1") - - assert.False(t, status.IsQueued) - assert.Nil(t, status.Message) - }) -} - -func TestAppendContent(t *testing.T) { - t.Run("appends content to existing queued message", func(t *testing.T) { - svc := setupService(t) - ctx := context.Background() - - _, err := svc.QueueMessage(ctx, "session-1", "task-1", "original content", "model-1", "user-1", false, nil) - require.NoError(t, err) - - err = svc.AppendContent(ctx, "session-1", "appended content") - require.NoError(t, err) - - status := svc.GetStatus(ctx, "session-1") - assert.True(t, status.IsQueued) - assert.Equal(t, "original content\n\n---\n\nappended content", status.Message.Content) - }) - - t.Run("appends multiple times", func(t *testing.T) { - svc := setupService(t) - ctx := context.Background() - - _, err := svc.QueueMessage(ctx, "session-1", "task-1", "first", "model-1", "user-1", false, nil) - require.NoError(t, err) - - require.NoError(t, svc.AppendContent(ctx, "session-1", "second")) - require.NoError(t, svc.AppendContent(ctx, "session-1", "third")) - - status := svc.GetStatus(ctx, "session-1") - assert.Equal(t, "first\n\n---\n\nsecond\n\n---\n\nthird", status.Message.Content) - }) - - t.Run("returns error when no message queued", func(t *testing.T) { - svc := setupService(t) - ctx := context.Background() - - err := svc.AppendContent(ctx, "session-1", "content") - assert.Error(t, err) - assert.Contains(t, err.Error(), "no queued message") - }) - - t.Run("preserves message ID after append", func(t *testing.T) { - svc := setupService(t) - ctx := context.Background() - - msg, err := svc.QueueMessage(ctx, "session-1", "task-1", "original", "model-1", "user-1", false, nil) - require.NoError(t, err) - originalID := msg.ID - - require.NoError(t, svc.AppendContent(ctx, "session-1", "extra")) - - status := svc.GetStatus(ctx, "session-1") - assert.Equal(t, originalID, status.Message.ID) - }) } func TestUpdateMessage(t *testing.T) { - t.Run("updates existing queued message content", func(t *testing.T) { + t.Run("updates content and survives in list", func(t *testing.T) { svc := setupService(t) ctx := context.Background() - // Queue a message - msg, err := svc.QueueMessage(ctx, "session-1", "task-1", "original content", "model-1", "user-1", false, nil) - require.NoError(t, err) - originalID := msg.ID - - // Update it - err = svc.UpdateMessage(ctx, "session-1", "updated content") - + msg, err := svc.QueueMessage(ctx, "s", "t", "original", "", "user-1", false, nil) require.NoError(t, err) - // Verify update - status := svc.GetStatus(ctx, "session-1") - assert.True(t, status.IsQueued) - assert.Equal(t, originalID, status.Message.ID) - assert.Equal(t, "updated content", status.Message.Content) + require.NoError(t, svc.UpdateMessage(ctx, "s", msg.ID, "edited", nil, "user-1")) + + status := svc.GetStatus(ctx, "s") + require.Equal(t, 1, status.Count) + assert.Equal(t, "edited", status.Entries[0].Content) + assert.Equal(t, msg.ID, status.Entries[0].ID) }) - t.Run("returns error when no message queued", func(t *testing.T) { + t.Run("rejects update from foreign sender", func(t *testing.T) { svc := setupService(t) ctx := context.Background() - err := svc.UpdateMessage(ctx, "session-1", "new content") + msg, err := svc.QueueMessage(ctx, "s", "t", "x", "", "user-1", false, nil) + require.NoError(t, err) - assert.Error(t, err) - assert.Contains(t, err.Error(), "no queued message") + err = svc.UpdateMessage(ctx, "s", msg.ID, "intruder", nil, "user-2") + assert.ErrorIs(t, err, ErrEntryNotFound) }) - t.Run("allows empty content updates", func(t *testing.T) { + t.Run("rejects update from foreign session", func(t *testing.T) { svc := setupService(t) ctx := context.Background() - // Queue a message - _, err := svc.QueueMessage(ctx, "session-1", "task-1", "original", "model-1", "user-1", false, nil) + msg, err := svc.QueueMessage(ctx, "s-victim", "t", "x", "", "user-1", false, nil) require.NoError(t, err) - // Update to empty (validation happens at handler level) - err = svc.UpdateMessage(ctx, "session-1", "") + err = svc.UpdateMessage(ctx, "s-attacker", msg.ID, "hijack", nil, "user-1") + assert.ErrorIs(t, err, ErrEntryNotFound) + }) - require.NoError(t, err) - status := svc.GetStatus(ctx, "session-1") - assert.Equal(t, "", status.Message.Content) + t.Run("returns ErrEntryNotFound for missing id", func(t *testing.T) { + svc := setupService(t) + ctx := context.Background() + err := svc.UpdateMessage(ctx, "s", "missing", "x", nil, "") + assert.ErrorIs(t, err, ErrEntryNotFound) }) } -func TestConcurrentAccess(t *testing.T) { - t.Run("handles concurrent queue operations safely", func(t *testing.T) { +func TestRemoveEntry(t *testing.T) { + t.Run("removes the targeted entry", func(t *testing.T) { svc := setupService(t) ctx := context.Background() - var wg sync.WaitGroup - numGoroutines := 100 + _, _ = svc.QueueMessage(ctx, "s", "t", "a", "", "u", false, nil) + b, _ := svc.QueueMessage(ctx, "s", "t", "b", "", "u", false, nil) + _, _ = svc.QueueMessage(ctx, "s", "t", "c", "", "u", false, nil) - // Concurrently queue messages to different sessions - for i := 0; i < numGoroutines; i++ { - wg.Add(1) - go func(idx int) { - defer wg.Done() - sessionID := "session-" + string(rune('A'+idx%26)) - _, err := svc.QueueMessage(ctx, sessionID, "task-1", "content", "model-1", "user-1", false, nil) - assert.NoError(t, err) - }(i) - } + require.NoError(t, svc.RemoveEntry(ctx, "s", b.ID)) - wg.Wait() + status := svc.GetStatus(ctx, "s") + assert.Equal(t, 2, status.Count) + assert.Equal(t, "a", status.Entries[0].Content) + assert.Equal(t, "c", status.Entries[1].Content) - // Verify all sessions have messages - sessionIDs := make(map[string]bool) - for i := 0; i < numGoroutines; i++ { - sessionID := "session-" + string(rune('A'+i%26)) - sessionIDs[sessionID] = true - } - - for sessionID := range sessionIDs { - status := svc.GetStatus(ctx, sessionID) - assert.True(t, status.IsQueued, "session %s should be queued", sessionID) - } + err := svc.RemoveEntry(ctx, "s", b.ID) + assert.ErrorIs(t, err, ErrEntryNotFound) }) - t.Run("handles concurrent take operations safely", func(t *testing.T) { + t.Run("rejects deletion from a foreign session", func(t *testing.T) { svc := setupService(t) ctx := context.Background() - // Queue a message - _, err := svc.QueueMessage(ctx, "session-1", "task-1", "test", "model-1", "user-1", false, nil) - require.NoError(t, err) + victim, _ := svc.QueueMessage(ctx, "s-victim", "t", "victim entry", "", "u", false, nil) - var wg sync.WaitGroup - successCount := 0 - var mu sync.Mutex + // Attacker knows the entry id (e.g. leaked via queue_full payload from + // a sibling task) and tries to remove it scoped to a different session. + err := svc.RemoveEntry(ctx, "s-attacker", victim.ID) + assert.ErrorIs(t, err, ErrEntryNotFound) - // Try to take the message from multiple goroutines - for i := 0; i < 10; i++ { - wg.Add(1) - go func() { - defer wg.Done() - _, exists := svc.TakeQueued(ctx, "session-1") - if exists { - mu.Lock() - successCount++ - mu.Unlock() - } - }() - } - - wg.Wait() - - // Only one should succeed - assert.Equal(t, 1, successCount, "only one goroutine should successfully take the message") - - // Message should be gone - status := svc.GetStatus(ctx, "session-1") - assert.False(t, status.IsQueued) - }) - - t.Run("handles concurrent updates and reads safely", func(t *testing.T) { - svc := setupService(t) - ctx := context.Background() - - // Queue initial message - _, err := svc.QueueMessage(ctx, "session-1", "task-1", "initial", "model-1", "user-1", false, nil) - require.NoError(t, err) - - var wg sync.WaitGroup - numUpdates := 50 - numReads := 50 - - // Concurrent updates - for i := 0; i < numUpdates; i++ { - wg.Add(1) - go func(idx int) { - defer wg.Done() - _ = svc.UpdateMessage(ctx, "session-1", "update-"+string(rune('0'+idx%10))) - }(i) - } - - // Concurrent reads - for i := 0; i < numReads; i++ { - wg.Add(1) - go func() { - defer wg.Done() - status := svc.GetStatus(ctx, "session-1") - assert.True(t, status.IsQueued) - }() - } - - wg.Wait() - - // Final state should be consistent - status := svc.GetStatus(ctx, "session-1") - assert.True(t, status.IsQueued) - assert.NotEmpty(t, status.Message.Content) + // Victim entry must still be present. + status := svc.GetStatus(ctx, "s-victim") + assert.Equal(t, 1, status.Count) }) } -func TestMultipleSessionsIsolation(t *testing.T) { - t.Run("sessions are isolated from each other", func(t *testing.T) { +func TestCancelAll(t *testing.T) { + svc := setupService(t) + ctx := context.Background() + + for i := 0; i < 4; i++ { + _, err := svc.QueueMessage(ctx, "s", "t", "x", "", "u", false, nil) + require.NoError(t, err) + } + n, err := svc.CancelAll(ctx, "s") + require.NoError(t, err) + assert.Equal(t, 4, n) + + status := svc.GetStatus(ctx, "s") + assert.Equal(t, 0, status.Count) +} + +func TestGetStatus(t *testing.T) { + t.Run("empty queue returns zero count and configured max", func(t *testing.T) { svc := setupService(t) ctx := context.Background() - // Queue messages for multiple sessions - _, err := svc.QueueMessage(ctx, "session-1", "task-1", "message-1", "model-1", "user-1", false, nil) - require.NoError(t, err) - - _, err = svc.QueueMessage(ctx, "session-2", "task-2", "message-2", "model-1", "user-1", false, nil) - require.NoError(t, err) - - // Take from session-1 - msg1, exists := svc.TakeQueued(ctx, "session-1") - require.True(t, exists) - assert.Equal(t, "message-1", msg1.Content) - - // session-2 should still have its message - status2 := svc.GetStatus(ctx, "session-2") - assert.True(t, status2.IsQueued) - assert.Equal(t, "message-2", status2.Message.Content) - - // session-1 should be empty - status1 := svc.GetStatus(ctx, "session-1") - assert.False(t, status1.IsQueued) + status := svc.GetStatus(ctx, "s") + assert.Equal(t, 0, status.Count) + assert.Empty(t, status.Entries) + assert.Equal(t, DefaultMaxPerSession, status.Max) }) -} -func TestQueuedMessageTimestamp(t *testing.T) { - t.Run("sets queued timestamp correctly", func(t *testing.T) { + t.Run("returns ordered entries", func(t *testing.T) { svc := setupService(t) ctx := context.Background() - before := time.Now() - msg, err := svc.QueueMessage(ctx, "session-1", "task-1", "test", "model-1", "user-1", false, nil) - after := time.Now() - - require.NoError(t, err) - assert.True(t, msg.QueuedAt.After(before) || msg.QueuedAt.Equal(before)) - assert.True(t, msg.QueuedAt.Before(after) || msg.QueuedAt.Equal(after)) + for _, body := range []string{"a", "b", "c"} { + _, err := svc.QueueMessage(ctx, "s", "t", body, "", "u", false, nil) + require.NoError(t, err) + } + status := svc.GetStatus(ctx, "s") + require.Equal(t, 3, status.Count) + assert.Equal(t, "a", status.Entries[0].Content) + assert.Equal(t, "c", status.Entries[2].Content) }) } + +func TestTransferSession(t *testing.T) { + t.Run("moves entries and pending move", func(t *testing.T) { + svc := setupService(t) + ctx := context.Background() + + _, err := svc.QueueMessage(ctx, "old", "task-1", "hand-off", "", "u", false, nil) + require.NoError(t, err) + svc.SetPendingMove(ctx, "old", &PendingMove{TaskID: "task-1", WorkflowStepID: "step-b"}) + + require.NoError(t, svc.TransferSession(ctx, "old", "new")) + + _, ok := svc.TakeQueued(ctx, "old") + assert.False(t, ok) + _, ok = svc.TakePendingMove(ctx, "old") + assert.False(t, ok) + + msg, ok := svc.TakeQueued(ctx, "new") + require.True(t, ok) + assert.Equal(t, "hand-off", msg.Content) + assert.Equal(t, "new", msg.SessionID) + + move, ok := svc.TakePendingMove(ctx, "new") + require.True(t, ok) + assert.Equal(t, "step-b", move.WorkflowStepID) + }) + + t.Run("no-op when source empty", func(t *testing.T) { + svc := setupService(t) + ctx := context.Background() + require.NoError(t, svc.TransferSession(ctx, "empty", "new")) + _, ok := svc.TakeQueued(ctx, "new") + assert.False(t, ok) + }) +} + +func TestPendingMove(t *testing.T) { + t.Run("set then take returns and clears", func(t *testing.T) { + svc := setupService(t) + ctx := context.Background() + + svc.SetPendingMove(ctx, "s", &PendingMove{TaskID: "t1", WorkflowID: "w1", WorkflowStepID: "step-2", Position: 3}) + + got, ok := svc.TakePendingMove(ctx, "s") + require.True(t, ok) + assert.Equal(t, "t1", got.TaskID) + assert.Equal(t, "step-2", got.WorkflowStepID) + assert.Equal(t, 3, got.Position) + assert.NotZero(t, got.QueuedAt) + + _, ok = svc.TakePendingMove(ctx, "s") + assert.False(t, ok) + }) + + t.Run("setting twice replaces previous", func(t *testing.T) { + svc := setupService(t) + ctx := context.Background() + + svc.SetPendingMove(ctx, "s", &PendingMove{TaskID: "t1", WorkflowStepID: "a"}) + svc.SetPendingMove(ctx, "s", &PendingMove{TaskID: "t1", WorkflowStepID: "b"}) + + got, ok := svc.TakePendingMove(ctx, "s") + require.True(t, ok) + assert.Equal(t, "b", got.WorkflowStepID) + }) +} + +func TestConcurrentInsertCap(t *testing.T) { + svc := setupService(t) + ctx := context.Background() + + const goroutines = 50 + var ( + wg sync.WaitGroup + ok atomic.Int32 + full atomic.Int32 + bad atomic.Int32 + ) + wg.Add(goroutines) + for i := 0; i < goroutines; i++ { + go func() { + defer wg.Done() + _, err := svc.QueueMessage(ctx, "s", "t", "x", "", "u", false, nil) + switch { + case err == nil: + ok.Add(1) + case errors.Is(err, ErrQueueFull): + full.Add(1) + default: + bad.Add(1) + } + }() + } + wg.Wait() + + assert.Equal(t, int32(0), bad.Load()) + assert.Equal(t, int32(DefaultMaxPerSession), ok.Load()) + assert.Equal(t, int32(goroutines-DefaultMaxPerSession), full.Load()) +} + +func TestConcurrentTakeIdempotent(t *testing.T) { + svc := setupService(t) + ctx := context.Background() + + _, err := svc.QueueMessage(ctx, "s", "t", "single", "", "u", false, nil) + require.NoError(t, err) + + var ( + wg sync.WaitGroup + hits atomic.Int32 + ) + for i := 0; i < 10; i++ { + wg.Add(1) + go func() { + defer wg.Done() + if _, ok := svc.TakeQueued(ctx, "s"); ok { + hits.Add(1) + } + }() + } + wg.Wait() + assert.Equal(t, int32(1), hits.Load()) +} + +func TestQueuedTimestamp(t *testing.T) { + svc := setupService(t) + ctx := context.Background() + + before := time.Now().Add(-time.Second) + msg, err := svc.QueueMessage(ctx, "s", "t", "x", "", "u", false, nil) + after := time.Now().Add(time.Second) + + require.NoError(t, err) + assert.True(t, msg.QueuedAt.After(before)) + assert.True(t, msg.QueuedAt.Before(after)) +} diff --git a/apps/backend/internal/orchestrator/messagequeue/types.go b/apps/backend/internal/orchestrator/messagequeue/types.go index 9e55f7012c..ad0dc356b3 100644 --- a/apps/backend/internal/orchestrator/messagequeue/types.go +++ b/apps/backend/internal/orchestrator/messagequeue/types.go @@ -1,38 +1,71 @@ package messagequeue -import "time" +import ( + "errors" + "time" +) -// QueuedMessage represents a message queued for a session +// DefaultMaxPerSession is the default cap for queued messages per session +// when the env var KANDEV_QUEUE_MAX_PER_SESSION is unset or invalid. +const DefaultMaxPerSession = 10 + +// Sender identities written to QueuedMessage.QueuedBy. The handlers default +// any empty user-supplied identity to QueuedByUser so the UpdateMessage +// ownership guard always runs against a non-empty value, and inter-task +// dispatch hardcodes QueuedByAgent so user clients can never overwrite an +// agent-authored entry. +const ( + QueuedByUser = "user" + QueuedByAgent = "agent" +) + +// QueueFullErrorCode is the well-known WS / MCP error code surfaced when an +// insert would exceed the per-session cap. Shared between the user-side WS +// handlers and the inter-task MCP handler so the wire contract stays in sync. +const QueueFullErrorCode = "queue_full" + +// Errors returned by the queue service / repository. +var ( + // ErrQueueFull is returned when an insert would exceed the per-session cap. + ErrQueueFull = errors.New("queue full") + // ErrEntryNotFound is returned when an operation targets an entry that no + // longer exists (e.g. it was drained between fetch and update). + ErrEntryNotFound = errors.New("queue entry not found") +) + +// QueuedMessage represents a single FIFO entry queued for a session. type QueuedMessage struct { - ID string `json:"id"` // Unique queue entry ID - SessionID string `json:"session_id"` // Task session ID - TaskID string `json:"task_id"` // Task ID - Content string `json:"content"` // Message content - Model string `json:"model"` // Optional model override - PlanMode bool `json:"plan_mode"` // Plan mode enabled - Attachments []MessageAttachment `json:"attachments"` // Image attachments - Metadata map[string]interface{} `json:"metadata,omitempty"` // Extra metadata (e.g. sender_task_id) merged into the resulting Message - QueuedAt time.Time `json:"queued_at"` // When queued - QueuedBy string `json:"queued_by"` // User ID who queued + ID string `json:"id"` + SessionID string `json:"session_id"` + TaskID string `json:"task_id"` + Position int64 `json:"position"` // FIFO order (lower = head) + Content string `json:"content"` + Model string `json:"model"` + PlanMode bool `json:"plan_mode"` + Attachments []MessageAttachment `json:"attachments"` + Metadata map[string]interface{} `json:"metadata,omitempty"` + QueuedAt time.Time `json:"queued_at"` + QueuedBy string `json:"queued_by"` } -// MessageAttachment represents an attachment (image) in a queued message +// MessageAttachment represents an attachment (image) in a queued message. type MessageAttachment struct { - Type string `json:"type"` // "image" - Data string `json:"data"` // Base64 data - MimeType string `json:"mime_type"` // MIME type + Type string `json:"type"` + Data string `json:"data"` + MimeType string `json:"mime_type"` } -// QueueStatus represents the queue status for a session +// QueueStatus is the per-session view returned to clients: full ordered list of +// pending entries plus capacity info. type QueueStatus struct { - IsQueued bool `json:"is_queued"` // Whether a message is queued - Message *QueuedMessage `json:"message"` // The queued message (nil if not queued) + Entries []QueuedMessage `json:"entries"` + Count int `json:"count"` + Max int `json:"max"` } // PendingMove represents a workflow step move requested by an agent (via // move_task_kandev) while its turn is still active. Applied by handleAgentReady -// once the turn ends, to avoid racing the on_enter processing against the -// agent's running turn. +// once the turn ends. type PendingMove struct { TaskID string `json:"task_id"` WorkflowID string `json:"workflow_id"` diff --git a/apps/backend/internal/orchestrator/service.go b/apps/backend/internal/orchestrator/service.go index 7c57e518ad..14c38eb075 100644 --- a/apps/backend/internal/orchestrator/service.go +++ b/apps/backend/internal/orchestrator/service.go @@ -297,7 +297,10 @@ type Status struct { LastHeartbeat time.Time `json:"last_heartbeat"` } -// NewService creates a new orchestrator service +// NewService creates a new orchestrator service. msgQueue is the persistent +// message queue service (constructed externally so cmd/kandev can wire it to +// the shared SQLite pool); pass nil to default to an in-memory queue, which +// suits tests but loses entries on restart. func NewService( cfg ServiceConfig, eventBus bus.EventBus, @@ -306,6 +309,7 @@ func NewService( repo repoStore, shellPrefs executor.ShellPreferenceProvider, secretStore secrets.SecretStore, + msgQueue *messagequeue.Service, log *logger.Logger, ) *Service { svcLogger := log.WithFields(zap.String("component", "orchestrator")) @@ -323,8 +327,9 @@ func NewService( // Create the scheduler with queue, executor, and task repository sched := scheduler.NewScheduler(taskQueue, exec, taskRepo, log, cfg.Scheduler) - // Create the message queue service - msgQueue := messagequeue.NewService(log) + if msgQueue == nil { + msgQueue = messagequeue.NewServiceMemory(log) + } // Create the service (watcher will be created after we have handlers) s := &Service{ diff --git a/apps/backend/internal/orchestrator/workflow_e2e_test.go b/apps/backend/internal/orchestrator/workflow_e2e_test.go index c1fc8cbef5..c4c187997b 100644 --- a/apps/backend/internal/orchestrator/workflow_e2e_test.go +++ b/apps/backend/internal/orchestrator/workflow_e2e_test.go @@ -312,7 +312,7 @@ func createEngineService(t *testing.T, repo *sqliterepo.Repository, sg *mockStep repo: repo, taskRepo: newMockTaskRepo(), agentManager: agentMgr, - messageQueue: messagequeue.NewService(log), + messageQueue: messagequeue.NewServiceMemory(log), executor: executor.NewExecutor(agentMgr, repo, log, executor.ExecutorConfig{}), } svc.SetWorkflowStepGetter(sg) @@ -381,8 +381,9 @@ func assertResetCalls(t *testing.T, agentMgr *mockAgentManager, expectCount int) func assertQueueState(t *testing.T, ctx context.Context, svc *Service, sessionID string, expectQueued bool) { t.Helper() status := svc.messageQueue.GetStatus(ctx, sessionID) - if status.IsQueued != expectQueued { - t.Errorf("queue.IsQueued = %v, want %v", status.IsQueued, expectQueued) + queued := status.Count > 0 + if queued != expectQueued { + t.Errorf("queue is queued = %v, want %v (count=%d)", queued, expectQueued, status.Count) } } diff --git a/apps/backend/internal/prompts/handlers/handlers.go b/apps/backend/internal/prompts/handlers/handlers.go index f1b8448751..111d14aa9a 100644 --- a/apps/backend/internal/prompts/handlers/handlers.go +++ b/apps/backend/internal/prompts/handlers/handlers.go @@ -1,6 +1,7 @@ package handlers import ( + "errors" "net/http" "github.com/gin-gonic/gin" @@ -51,12 +52,15 @@ func (h *Handlers) httpCreatePrompt(c *gin.Context) { } resp, err := h.controller.CreatePrompt(c.Request.Context(), req) if err != nil { - status := http.StatusInternalServerError - if err == service.ErrInvalidPrompt { - status = http.StatusBadRequest + status, message := http.StatusInternalServerError, "failed to create prompt" + switch { + case errors.Is(err, service.ErrInvalidPrompt): + status, message = http.StatusBadRequest, err.Error() + case errors.Is(err, service.ErrPromptAlreadyExists): + status, message = http.StatusConflict, err.Error() } - h.logger.Error("failed to create prompt", zap.Error(err)) - c.JSON(status, gin.H{"error": "failed to create prompt"}) + logRejection(h.logger, "create prompt rejected", "failed to create prompt", err, status) + c.JSON(status, gin.H{"error": message}) return } c.JSON(http.StatusOK, resp) @@ -70,20 +74,32 @@ func (h *Handlers) httpUpdatePrompt(c *gin.Context) { } resp, err := h.controller.UpdatePrompt(c.Request.Context(), c.Param("id"), req) if err != nil { - status := http.StatusInternalServerError - switch err { - case service.ErrInvalidPrompt: - status = http.StatusBadRequest - case service.ErrPromptNotFound: - status = http.StatusNotFound + status, message := http.StatusInternalServerError, "failed to update prompt" + switch { + case errors.Is(err, service.ErrInvalidPrompt): + status, message = http.StatusBadRequest, err.Error() + case errors.Is(err, service.ErrPromptNotFound): + status, message = http.StatusNotFound, err.Error() + case errors.Is(err, service.ErrPromptAlreadyExists): + status, message = http.StatusConflict, err.Error() } - h.logger.Error("failed to update prompt", zap.Error(err)) - c.JSON(status, gin.H{"error": "failed to update prompt"}) + logRejection(h.logger, "update prompt rejected", "failed to update prompt", err, status) + c.JSON(status, gin.H{"error": message}) return } c.JSON(http.StatusOK, resp) } +// logRejection keeps the error-rate dashboard clean by logging client-driven +// 4xx outcomes at Info level and reserving Error for unexpected 500s. +func logRejection(log *logger.Logger, infoMsg, errorMsg string, err error, status int) { + if status >= http.StatusInternalServerError { + log.Error(errorMsg, zap.Error(err)) + return + } + log.Info(infoMsg, zap.Error(err), zap.Int("status", status)) +} + func (h *Handlers) httpDeletePrompt(c *gin.Context) { if err := h.controller.DeletePrompt(c.Request.Context(), c.Param("id")); err != nil { h.logger.Error("failed to delete prompt", zap.Error(err)) diff --git a/apps/backend/internal/prompts/handlers/handlers_test.go b/apps/backend/internal/prompts/handlers/handlers_test.go new file mode 100644 index 0000000000..eb4f04347a --- /dev/null +++ b/apps/backend/internal/prompts/handlers/handlers_test.go @@ -0,0 +1,114 @@ +package handlers + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + + "github.com/gin-gonic/gin" + "github.com/jmoiron/sqlx" + + "github.com/kandev/kandev/internal/common/logger" + "github.com/kandev/kandev/internal/db" + "github.com/kandev/kandev/internal/prompts/controller" + "github.com/kandev/kandev/internal/prompts/service" + promptstore "github.com/kandev/kandev/internal/prompts/store" +) + +func newTestRouter(t *testing.T) (*gin.Engine, func()) { + t.Helper() + gin.SetMode(gin.TestMode) + + tmpDir := t.TempDir() + dbConn, err := db.OpenSQLite(filepath.Join(tmpDir, "test.db")) + if err != nil { + t.Fatalf("open sqlite: %v", err) + } + sqlxDB := sqlx.NewDb(dbConn, "sqlite3") + repo, repoCleanup, err := promptstore.Provide(sqlxDB, sqlxDB) + if err != nil { + t.Fatalf("provide repo: %v", err) + } + svc := service.NewService(repo) + ctrl := controller.NewController(svc) + log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"}) + + router := gin.New() + RegisterRoutes(router, ctrl, log) + + cleanup := func() { + if err := sqlxDB.Close(); err != nil { + t.Errorf("close sqlite: %v", err) + } + if err := repoCleanup(); err != nil { + t.Errorf("close repo: %v", err) + } + } + return router, cleanup +} + +func postJSON(t *testing.T, router *gin.Engine, path string, body any) *httptest.ResponseRecorder { + t.Helper() + buf, err := json.Marshal(body) + if err != nil { + t.Fatalf("marshal body: %v", err) + } + req := httptest.NewRequest(http.MethodPost, path, bytes.NewReader(buf)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + return rec +} + +// Duplicate prompt name on POST /api/v1/prompts must surface as 409 with a +// human-readable error message — not a generic 500 — so the frontend can show +// a useful warning rather than crashing the user out of the create form. +func TestHTTPCreatePrompt_DuplicateName_Returns409(t *testing.T) { + router, cleanup := newTestRouter(t) + defer cleanup() + + first := postJSON(t, router, "/api/v1/prompts", map[string]string{ + "name": "dupe", "content": "first", + }) + if first.Code != http.StatusOK { + t.Fatalf("seed prompt: status %d body %s", first.Code, first.Body.String()) + } + + second := postJSON(t, router, "/api/v1/prompts", map[string]string{ + "name": "dupe", "content": "second", + }) + if second.Code != http.StatusConflict { + t.Fatalf("expected 409, got %d body %s", second.Code, second.Body.String()) + } + + var resp struct { + Error string `json:"error"` + } + if err := json.Unmarshal(second.Body.Bytes(), &resp); err != nil { + t.Fatalf("unmarshal response: %v", err) + } + if resp.Error == "" { + t.Fatal("expected non-empty error message") + } + if !bytes.Contains([]byte(resp.Error), []byte("already exists")) { + t.Fatalf("expected 'already exists' in message, got %q", resp.Error) + } +} + +// Built-in prompts (seeded with names like "code-review") share the unique +// name space with user-created prompts, so creating a custom prompt that +// collides with a built-in must also return 409, not 500. +func TestHTTPCreatePrompt_BuiltinName_Returns409(t *testing.T) { + router, cleanup := newTestRouter(t) + defer cleanup() + + rec := postJSON(t, router, "/api/v1/prompts", map[string]string{ + "name": "code-review", "content": "shadow", + }) + if rec.Code != http.StatusConflict { + t.Fatalf("expected 409, got %d body %s", rec.Code, rec.Body.String()) + } +} diff --git a/apps/backend/internal/prompts/service/service.go b/apps/backend/internal/prompts/service/service.go index f2047f4a75..aaa275e338 100644 --- a/apps/backend/internal/prompts/service/service.go +++ b/apps/backend/internal/prompts/service/service.go @@ -2,6 +2,7 @@ package service import ( "context" + "database/sql" "errors" "strings" @@ -10,8 +11,9 @@ import ( ) var ( - ErrPromptNotFound = errors.New("prompt not found") - ErrInvalidPrompt = errors.New("invalid prompt") + ErrPromptNotFound = errors.New("prompt not found") + ErrInvalidPrompt = errors.New("invalid prompt") + ErrPromptAlreadyExists = errors.New("prompt with this name already exists") ) type Service struct { @@ -32,16 +34,48 @@ func (s *Service) CreatePrompt(ctx context.Context, name, content string) (*mode if name == "" || content == "" { return nil, ErrInvalidPrompt } + if err := s.assertNameAvailable(ctx, name, ""); err != nil { + return nil, err + } prompt := &models.Prompt{ Name: name, Content: content, } if err := s.repo.CreatePrompt(ctx, prompt); err != nil { - return nil, err + return nil, translateNameConflict(err) } return prompt, nil } +// translateNameConflict closes the TOCTOU window between assertNameAvailable +// and the write: the SQLite UNIQUE index on custom_prompts.name is the only +// authoritative guard, and a concurrent write that loses the race surfaces a +// "UNIQUE constraint failed" driver error which would otherwise fall through +// to a generic 500. +func translateNameConflict(err error) error { + if err != nil && strings.Contains(err.Error(), "UNIQUE constraint failed") { + return ErrPromptAlreadyExists + } + return err +} + +// assertNameAvailable returns ErrPromptAlreadyExists if a different prompt with +// the given name already exists. excludeID lets callers exclude the prompt +// being updated so unchanged-name saves do not falsely trip. +func (s *Service) assertNameAvailable(ctx context.Context, name, excludeID string) error { + existing, err := s.repo.GetPromptByName(ctx, name) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil + } + return err + } + if existing.ID == excludeID { + return nil + } + return ErrPromptAlreadyExists +} + func (s *Service) UpdatePrompt(ctx context.Context, promptID string, name *string, content *string) (*models.Prompt, error) { prompt, err := s.repo.GetPromptByID(ctx, promptID) if err != nil { @@ -52,6 +86,11 @@ func (s *Service) UpdatePrompt(ctx context.Context, promptID string, name *strin if trimmed == "" { return nil, ErrInvalidPrompt } + if trimmed != prompt.Name { + if err := s.assertNameAvailable(ctx, trimmed, prompt.ID); err != nil { + return nil, err + } + } prompt.Name = trimmed } if content != nil { @@ -62,7 +101,7 @@ func (s *Service) UpdatePrompt(ctx context.Context, promptID string, name *strin prompt.Content = trimmed } if err := s.repo.UpdatePrompt(ctx, prompt); err != nil { - return nil, err + return nil, translateNameConflict(err) } return prompt, nil } diff --git a/apps/backend/internal/prompts/service/service_test.go b/apps/backend/internal/prompts/service/service_test.go index b7a22dc197..5b60ca372e 100644 --- a/apps/backend/internal/prompts/service/service_test.go +++ b/apps/backend/internal/prompts/service/service_test.go @@ -2,11 +2,14 @@ package service import ( "context" + "database/sql" + "errors" "path/filepath" "testing" "github.com/jmoiron/sqlx" "github.com/kandev/kandev/internal/db" + "github.com/kandev/kandev/internal/prompts/models" promptstore "github.com/kandev/kandev/internal/prompts/store" ) @@ -69,3 +72,104 @@ func TestService_UpdatePrompt(t *testing.T) { t.Fatalf("expected content %q, got %q", content, updated.Content) } } + +func TestService_CreatePromptDuplicateName(t *testing.T) { + svc, cleanup := createService(t) + defer cleanup() + ctx := context.Background() + + if _, err := svc.CreatePrompt(ctx, "shared-name", "first"); err != nil { + t.Fatalf("seed prompt: %v", err) + } + if _, err := svc.CreatePrompt(ctx, "shared-name", "second"); err != ErrPromptAlreadyExists { + t.Fatalf("expected ErrPromptAlreadyExists, got %v", err) + } + // Trimmed input still detected. + if _, err := svc.CreatePrompt(ctx, " shared-name ", "third"); err != ErrPromptAlreadyExists { + t.Fatalf("expected ErrPromptAlreadyExists for trimmed name, got %v", err) + } +} + +func TestService_UpdatePromptRenameToExisting(t *testing.T) { + svc, cleanup := createService(t) + defer cleanup() + ctx := context.Background() + + if _, err := svc.CreatePrompt(ctx, "alpha", "a"); err != nil { + t.Fatalf("seed alpha: %v", err) + } + beta, err := svc.CreatePrompt(ctx, "beta", "b") + if err != nil { + t.Fatalf("seed beta: %v", err) + } + + rename := "alpha" + if _, err := svc.UpdatePrompt(ctx, beta.ID, &rename, nil); err != ErrPromptAlreadyExists { + t.Fatalf("expected ErrPromptAlreadyExists, got %v", err) + } +} + +// Saving a prompt without changing its name (e.g. content-only edit, or sending +// the same name through the PATCH) must not trip the duplicate-name guard. +func TestService_UpdatePromptSameName(t *testing.T) { + svc, cleanup := createService(t) + defer cleanup() + ctx := context.Background() + + prompt, err := svc.CreatePrompt(ctx, "stable", "v1") + if err != nil { + t.Fatalf("seed prompt: %v", err) + } + + sameName := "stable" + newContent := "v2" + updated, err := svc.UpdatePrompt(ctx, prompt.ID, &sameName, &newContent) + if err != nil { + t.Fatalf("update with same name: %v", err) + } + if updated.Content != newContent { + t.Fatalf("expected content %q, got %q", newContent, updated.Content) + } +} + +// raceRepo simulates a TOCTOU loss against the SQLite UNIQUE index: the +// pre-check sees no row, but the write fails because a concurrent insert +// landed first. The service must translate that into ErrPromptAlreadyExists +// rather than letting the raw driver error fall through to a 500. +type raceRepo struct { + promptstore.Repository + createErr error + updateErr error +} + +func (r *raceRepo) GetPromptByID(_ context.Context, id string) (*models.Prompt, error) { + return &models.Prompt{ID: id, Name: "old", Content: "x"}, nil +} + +func (r *raceRepo) GetPromptByName(_ context.Context, _ string) (*models.Prompt, error) { + return nil, sql.ErrNoRows +} + +func (r *raceRepo) CreatePrompt(_ context.Context, _ *models.Prompt) error { return r.createErr } +func (r *raceRepo) UpdatePrompt(_ context.Context, _ *models.Prompt) error { return r.updateErr } + +func TestService_CreatePrompt_TranslatesUniqueConstraintRace(t *testing.T) { + svc := NewService(&raceRepo{ + createErr: errors.New("UNIQUE constraint failed: custom_prompts.name"), + }) + + if _, err := svc.CreatePrompt(context.Background(), "any", "content"); err != ErrPromptAlreadyExists { + t.Fatalf("expected ErrPromptAlreadyExists, got %v", err) + } +} + +func TestService_UpdatePrompt_TranslatesUniqueConstraintRace(t *testing.T) { + svc := NewService(&raceRepo{ + updateErr: errors.New("UNIQUE constraint failed: custom_prompts.name"), + }) + + rename := "new-name" + if _, err := svc.UpdatePrompt(context.Background(), "id-1", &rename, nil); err != ErrPromptAlreadyExists { + t.Fatalf("expected ErrPromptAlreadyExists, got %v", err) + } +} diff --git a/apps/backend/internal/worktree/manager.go b/apps/backend/internal/worktree/manager.go index d26276d674..21de729b18 100644 --- a/apps/backend/internal/worktree/manager.go +++ b/apps/backend/internal/worktree/manager.go @@ -274,9 +274,44 @@ func (m *Manager) Create(ctx context.Context, req CreateRequest) (*Worktree, err baseRef = m.pullBaseBranch(ctx, req.RepositoryPath, req.BaseBranch, req.OnSyncProgress) } - // Check base branch exists + // Check base branch exists. When the requested branch is missing and the + // caller supplied a FallbackBaseBranch (typically the repo's default_branch) + // that does exist, recover automatically and surface a non-fatal warning on + // the resulting worktree. This handles the common case where a parent task + // was anchored to a PR head or fresh branch that has been deleted upstream + // or never existed in a sibling repo. + fallbackWarning, fallbackDetail := "", "" if !m.branchExists(ctx, req.RepositoryPath, baseRef) { - return nil, fmt.Errorf("%w: %s", ErrInvalidBaseBranch, baseRef) + fallback := strings.TrimSpace(req.FallbackBaseBranch) + if fallback == "" || fallback == baseRef { + return nil, fmt.Errorf("%w: %s", ErrInvalidBaseBranch, baseRef) + } + // Best-effort fetch of the fallback so it is available locally in + // containerized / shallow-clone environments where the fallback may + // only exist on the remote. pullBaseBranch may resolve the name to a + // remote-tracking ref (e.g. "main" -> "origin/main") which we must use + // for the existence check and downstream git operations. + resolvedFallback := fallback + if req.PullBeforeWorktree { + resolvedFallback = m.pullBaseBranch(ctx, req.RepositoryPath, fallback, nil) + } + if !m.branchExists(ctx, req.RepositoryPath, resolvedFallback) { + return nil, fmt.Errorf("%w: %s (fallback %q also not found)", ErrInvalidBaseBranch, baseRef, fallback) + } + m.logger.Warn("requested base branch not found, falling back", + zap.String("repository_path", req.RepositoryPath), + zap.String("requested_branch", baseRef), + zap.String("fallback_branch", fallback)) + // Use req.BaseBranch (the user-supplied name) in the user-facing warning + // rather than baseRef, which may carry an internal "origin/" form + // produced by pullBaseBranch when PullBeforeWorktree is set. + fallbackWarning = fmt.Sprintf("Requested base branch %q not found, used %q instead", req.BaseBranch, fallback) + fallbackDetail = fmt.Sprintf("git rev-parse --verify %s failed; recovered using fallback branch %q (typically the repository's default_branch)", baseRef, fallback) + baseRef = resolvedFallback + // Reflect the resolved branch in the persisted worktree record so + // downstream consumers (UI, queries, debug logs) see the actual base + // rather than the requested-but-missing one. + req.BaseBranch = fallback } // Worktrees are always placed under ~/.kandev/tasks/{taskDir}/{repo}/. @@ -285,7 +320,15 @@ func (m *Manager) Create(ctx context.Context, req CreateRequest) (*Worktree, err if req.TaskDirName == "" || req.RepoName == "" { return nil, ErrTaskDirRequired } - return m.createInTaskDir(ctx, req, baseRef) + wt, err := m.createInTaskDir(ctx, req, baseRef) + if err != nil { + return nil, err + } + if fallbackWarning != "" { + wt.BaseBranchFallbackWarning = fallbackWarning + wt.BaseBranchFallbackDetail = fallbackDetail + } + return wt, nil } // createInTaskDir creates a worktree inside the task directory structure: diff --git a/apps/backend/internal/worktree/manager_base_branch_fallback_test.go b/apps/backend/internal/worktree/manager_base_branch_fallback_test.go new file mode 100644 index 0000000000..674b3e95b6 --- /dev/null +++ b/apps/backend/internal/worktree/manager_base_branch_fallback_test.go @@ -0,0 +1,142 @@ +package worktree + +import ( + "context" + "errors" + "strings" + "testing" +) + +// TestCreateWorktree_BaseBranchFallback_RecoversWhenRequestedMissing covers +// the regression where a subtask inherited a stale base_branch (e.g. the +// parent's PR head) that did not exist in a freshly inherited worktree. With +// FallbackBaseBranch populated (typically the repo's default_branch) the +// manager retries with the fallback and surfaces a non-fatal warning instead +// of failing the launch. +func TestCreateWorktree_BaseBranchFallback_RecoversWhenRequestedMissing(t *testing.T) { + cfg := newTestConfig(t) + mgr, err := NewManager(cfg, newMockStore(), newTestLogger()) + if err != nil { + t.Fatalf("NewManager failed: %v", err) + } + repoPath := initGitRepoForWorktreeTest(t) + + wt, err := mgr.Create(context.Background(), CreateRequest{ + TaskID: "task-1", + SessionID: "session-1", + TaskTitle: "Inherits stale branch", + RepositoryID: "repo-1", + RepositoryPath: repoPath, + BaseBranch: "pr-metrics", + FallbackBaseBranch: "main", + TaskDirName: "task-1", + RepoName: "repo-1", + }) + if err != nil { + t.Fatalf("Create() unexpected error: %v", err) + } + if wt.BaseBranch != "main" { + t.Fatalf("worktree BaseBranch = %q, want %q", wt.BaseBranch, "main") + } + if wt.BaseBranchFallbackWarning == "" { + t.Fatal("expected BaseBranchFallbackWarning to be set when fallback was used") + } + if !strings.Contains(wt.BaseBranchFallbackWarning, "pr-metrics") { + t.Fatalf("warning %q does not mention requested branch", wt.BaseBranchFallbackWarning) + } + if !strings.Contains(wt.BaseBranchFallbackWarning, "main") { + t.Fatalf("warning %q does not mention fallback branch", wt.BaseBranchFallbackWarning) + } + if wt.BaseBranchFallbackDetail == "" { + t.Fatal("expected BaseBranchFallbackDetail to be set when fallback was used") + } +} + +// TestCreateWorktree_BaseBranchFallback_NoFallbackProvided keeps the legacy +// loud failure when the caller did not supply a FallbackBaseBranch — we must +// not silently invent a branch out of thin air. +func TestCreateWorktree_BaseBranchFallback_NoFallbackProvided(t *testing.T) { + cfg := newTestConfig(t) + mgr, err := NewManager(cfg, newMockStore(), newTestLogger()) + if err != nil { + t.Fatalf("NewManager failed: %v", err) + } + repoPath := initGitRepoForWorktreeTest(t) + + _, err = mgr.Create(context.Background(), CreateRequest{ + TaskID: "task-1", + SessionID: "session-1", + RepositoryID: "repo-1", + RepositoryPath: repoPath, + BaseBranch: "pr-metrics", + TaskDirName: "task-1", + RepoName: "repo-1", + }) + if !errors.Is(err, ErrInvalidBaseBranch) { + t.Fatalf("Create() err = %v, want ErrInvalidBaseBranch", err) + } +} + +// TestCreateWorktree_BaseBranchFallback_FallbackAlsoMissing surfaces the +// original error when neither branch exists — the fallback only helps when it +// actually exists in the repository. +func TestCreateWorktree_BaseBranchFallback_FallbackAlsoMissing(t *testing.T) { + cfg := newTestConfig(t) + mgr, err := NewManager(cfg, newMockStore(), newTestLogger()) + if err != nil { + t.Fatalf("NewManager failed: %v", err) + } + repoPath := initGitRepoForWorktreeTest(t) + + _, err = mgr.Create(context.Background(), CreateRequest{ + TaskID: "task-1", + SessionID: "session-1", + RepositoryID: "repo-1", + RepositoryPath: repoPath, + BaseBranch: "pr-metrics", + FallbackBaseBranch: "release", // also missing in this repo + TaskDirName: "task-1", + RepoName: "repo-1", + }) + if !errors.Is(err, ErrInvalidBaseBranch) { + t.Fatalf("Create() err = %v, want ErrInvalidBaseBranch", err) + } + // The error must name both branches so an operator can tell at a glance + // that a fallback was attempted and also failed. + msg := err.Error() + if !strings.Contains(msg, "pr-metrics") || !strings.Contains(msg, "release") { + t.Fatalf("error %q should mention both requested and fallback branches", msg) + } +} + +// TestCreateWorktree_BaseBranchFallback_NotUsedWhenBaseExists guards against +// the fallback being applied unnecessarily — when the requested branch is +// valid the worktree uses it and no warning is emitted. +func TestCreateWorktree_BaseBranchFallback_NotUsedWhenBaseExists(t *testing.T) { + cfg := newTestConfig(t) + mgr, err := NewManager(cfg, newMockStore(), newTestLogger()) + if err != nil { + t.Fatalf("NewManager failed: %v", err) + } + repoPath := initGitRepoForWorktreeTest(t) + + wt, err := mgr.Create(context.Background(), CreateRequest{ + TaskID: "task-1", + SessionID: "session-1", + RepositoryID: "repo-1", + RepositoryPath: repoPath, + BaseBranch: "main", + FallbackBaseBranch: "feature/pr-branch", // exists, but should never be used + TaskDirName: "task-1", + RepoName: "repo-1", + }) + if err != nil { + t.Fatalf("Create() unexpected error: %v", err) + } + if wt.BaseBranch != "main" { + t.Fatalf("worktree BaseBranch = %q, want %q", wt.BaseBranch, "main") + } + if wt.BaseBranchFallbackWarning != "" { + t.Fatalf("expected no fallback warning, got %q", wt.BaseBranchFallbackWarning) + } +} diff --git a/apps/backend/internal/worktree/worktree.go b/apps/backend/internal/worktree/worktree.go index 3ff00e3d49..c592800cb5 100644 --- a/apps/backend/internal/worktree/worktree.go +++ b/apps/backend/internal/worktree/worktree.go @@ -72,6 +72,17 @@ type Worktree struct { // FetchWarningDetail contains the raw git command output for debugging. // Shown as collapsible content alongside the user-friendly FetchWarning. FetchWarningDetail string `json:"fetch_warning_detail,omitempty"` + + // BaseBranchFallbackWarning is set when the requested BaseBranch did not + // exist in the repository and the worktree was created from a fallback + // branch (typically the repository's default_branch) instead. Empty when + // the original BaseBranch was used. + BaseBranchFallbackWarning string `json:"base_branch_fallback_warning,omitempty"` + + // BaseBranchFallbackDetail mirrors FetchWarningDetail: a longer message + // describing why the original branch was not used. Surfaced as collapsible + // detail alongside BaseBranchFallbackWarning. + BaseBranchFallbackDetail string `json:"base_branch_fallback_detail,omitempty"` } // CreateRequest contains the parameters for creating a new worktree. @@ -97,6 +108,12 @@ type CreateRequest struct { // Typically "main" or "master". BaseBranch string + // FallbackBaseBranch is an optional branch to retry with when BaseBranch + // does not exist in the repository. Typically populated with the + // repository's default_branch by the caller. When empty, a missing + // BaseBranch returns ErrInvalidBaseBranch as before. + FallbackBaseBranch string + // CheckoutBranch is a branch to fetch from origin and check out directly in the // worktree. If the branch is already checked out in another worktree, a unique // fallback branch is created using the original name with a random suffix. diff --git a/apps/backend/pkg/websocket/actions.go b/apps/backend/pkg/websocket/actions.go index 3023d40d0c..16dd70aa83 100644 --- a/apps/backend/pkg/websocket/actions.go +++ b/apps/backend/pkg/websocket/actions.go @@ -84,6 +84,7 @@ const ( ActionSessionStop = "session.stop" ActionSessionDelete = "session.delete" ActionSessionSetPrimary = "session.set_primary" + ActionSessionSetPlanMode = "session.set_plan_mode" // Agent actions ActionAgentList = "agent.list" @@ -108,10 +109,11 @@ const ( // Message Queue actions ActionMessageQueueAdd = "message.queue.add" - ActionMessageQueueCancel = "message.queue.cancel" + ActionMessageQueueCancel = "message.queue.cancel" // Clears the entire queue for a session ActionMessageQueueGet = "message.queue.get" ActionMessageQueueUpdate = "message.queue.update" ActionMessageQueueAppend = "message.queue.append" + ActionMessageQueueRemove = "message.queue.remove" // Delete a single entry by id ActionMessageQueueStatusChanged = "message.queue.status_changed" // Notification: queue status changed // Workflow template/step actions @@ -159,6 +161,9 @@ const ( ActionTaskPlanReverted = "task.plan.reverted" ActionAgentUpdated = "agent.updated" ActionAgentAvailableUpdated = "agent.available.updated" + ActionAgentInstallStarted = "agent.install.started" + ActionAgentInstallOutput = "agent.install.output" + ActionAgentInstallFinished = "agent.install.finished" ActionWorkspaceCreated = "workspace.created" ActionWorkspaceUpdated = "workspace.updated" ActionWorkspaceDeleted = "workspace.deleted" diff --git a/apps/cli/package.json b/apps/cli/package.json index 1a576be34f..80cc07b9cd 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -1,6 +1,6 @@ { "name": "kandev", - "version": "0.41.0", + "version": "0.43.0", "private": false, "description": "Launcher for Kandev — manage tasks, orchestrate agents, review changes, and ship value", "license": "AGPL-3.0-only", diff --git a/apps/cli/src/release-config.test.ts b/apps/cli/src/release-config.test.ts new file mode 100644 index 0000000000..70e1ff868d --- /dev/null +++ b/apps/cli/src/release-config.test.ts @@ -0,0 +1,171 @@ +import { readdirSync, readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { describe, expect, it } from "vitest"; + +const repoRoot = resolve(__dirname, "../../.."); + +function readRepoFile(path: string): string { + return readFileSync(resolve(repoRoot, path), "utf8"); +} + +function workflowFiles(): string[] { + const workflowDir = resolve(repoRoot, ".github/workflows"); + return readdirSync(workflowDir) + .filter((name) => name.endsWith(".yml") || name.endsWith(".yaml")) + .map((name) => `.github/workflows/${name}`); +} + +function extractDockerPnpmVersion(dockerfile: string): string | undefined { + return dockerfile.match(/^ARG PNPM_VERSION=([0-9]+\.[0-9]+\.[0-9]+)$/m)?.[1]; +} + +function indentation(line: string): number { + return line.search(/\S/); +} + +function isBlankOrComment(line: string): boolean { + const trimmed = line.trim(); + return trimmed.length === 0 || trimmed.startsWith("#"); +} + +function parseVersionLine(line: string): string | undefined { + const match = line.match(/^\s*version:\s*(?:"([^"]+)"|'([^']+)'|([^"'\s#]+))\s*(?:#.*)?$/); + return match?.[1] ?? match?.[2] ?? match?.[3]; +} + +function findVersionInWithBlock( + lines: string[], + start: number, + withIndent: number, +): string | undefined { + for (let index = start; index < lines.length; index += 1) { + const line = lines[index]; + if (isBlankOrComment(line)) { + continue; + } + if (indentation(line) <= withIndent) { + return undefined; + } + + const version = parseVersionLine(line); + if (version !== undefined) { + return version; + } + } + + return undefined; +} + +function findPnpmSetupVersion( + lines: string[], + start: number, + stepIndent: number, +): string | undefined { + for (let index = start; index < lines.length; index += 1) { + const line = lines[index]; + if (isBlankOrComment(line)) { + continue; + } + if (indentation(line) <= stepIndent) { + return undefined; + } + + const withMatch = line.match(/^(\s*)with:\s*(?:#.*)?$/); + if (withMatch !== null) { + return findVersionInWithBlock(lines, index + 1, withMatch[1].length); + } + } + + return undefined; +} + +function matchPnpmSetupUsesLine(line: string): RegExpMatchArray | null { + return line.match(/^(\s*)(?:-\s*)?uses:\s*["']?pnpm\/action-setup@v\d+["']?\s*(?:#.*)?$/); +} + +function findStepIndent(lines: string[], usesLineIndex: number, usesIndent: number): number { + if (lines[usesLineIndex].trimStart().startsWith("- ")) { + return usesIndent; + } + + for (let index = usesLineIndex - 1; index >= 0; index -= 1) { + const line = lines[index]; + if (isBlankOrComment(line)) { + continue; + } + + const lineIndent = indentation(line); + if (lineIndent < usesIndent && line.slice(lineIndent).startsWith("- ")) { + return lineIndent; + } + } + + return Math.max(0, usesIndent - 2); +} + +function extractWorkflowPnpmVersions(workflow: string): Array { + const lines = workflow.split(/\r?\n/); + const versions: Array = []; + + for (let index = 0; index < lines.length; index += 1) { + const line = lines[index]; + const setupMatch = matchPnpmSetupUsesLine(line); + if (setupMatch !== null) { + const stepIndent = findStepIndent(lines, index, setupMatch[1].length); + versions.push(findPnpmSetupVersion(lines, index + 1, stepIndent)); + } + } + + return versions; +} + +function assertWorkflowPnpmVersions(file: string, expectedVersion: string): number { + const versions = extractWorkflowPnpmVersions(readRepoFile(file)); + for (const version of versions) { + if (version === undefined) { + expect(version, `${file}: pnpm/action-setup step is missing a version pin`).toBeDefined(); + continue; + } + + expect(version, `${file}: pnpm/action-setup version must match Dockerfile PNPM_VERSION`).toBe( + expectedVersion, + ); + } + + return versions.length; +} + +describe("release package manager version", () => { + it("pins pnpm consistently for Docker and GitHub Actions", () => { + const dockerfile = readRepoFile("Dockerfile"); + const dockerPnpmVersion = extractDockerPnpmVersion(dockerfile); + + expect(dockerfile).not.toContain("pnpm@latest"); + expect(dockerPnpmVersion, "Dockerfile: PNPM_VERSION must be pinned").toBeDefined(); + if (dockerPnpmVersion === undefined) { + throw new Error("Dockerfile: PNPM_VERSION must be pinned"); + } + + const workflowSetupCount = workflowFiles().reduce( + (count, file) => count + assertWorkflowPnpmVersions(file, dockerPnpmVersion), + 0, + ); + expect(workflowSetupCount).toBeGreaterThan(0); + }); +}); + +describe("release npm publishing", () => { + it("skips packages that are already published on npm", () => { + const script = readRepoFile("scripts/release/publish-npm.sh"); + + expect(script).toContain('npm view "${pkg}@${VERSION}" version --silent'); + expect(script).toMatch( + /if package_already_published "\$pkg"; then\s+record_already_published "\$pkg"\s+continue\s+fi/, + ); + expect(script).toMatch( + /if package_already_published "kandev"; then\s+record_already_published "kandev"/, + ); + expect(script).toContain("EPUBLISHCONFLICT"); + expect(script).toContain("treated as idempotent success"); + }); +}); diff --git a/apps/cli/src/shared.test.ts b/apps/cli/src/shared.test.ts new file mode 100644 index 0000000000..c3056356d8 --- /dev/null +++ b/apps/cli/src/shared.test.ts @@ -0,0 +1,61 @@ +import { afterEach, describe, expect, it } from "vitest"; + +import { buildWebEnv, type PortConfig } from "./shared"; + +const ports: PortConfig = { + backendPort: 38429, + webPort: 37429, + agentctlPort: 36429, + backendUrl: "http://localhost:38429", +}; + +describe("buildWebEnv", () => { + const originalApiPort = process.env.NEXT_PUBLIC_KANDEV_API_PORT; + afterEach(() => { + if (originalApiPort === undefined) { + delete process.env.NEXT_PUBLIC_KANDEV_API_PORT; + } else { + process.env.NEXT_PUBLIC_KANDEV_API_PORT = originalApiPort; + } + }); + + it("sets NEXT_PUBLIC_KANDEV_API_PORT in dev mode so the browser knows the backend port", () => { + const env = buildWebEnv({ ports }); + + expect(env.NEXT_PUBLIC_KANDEV_API_PORT).toBe("38429"); + expect(env.NODE_ENV).not.toBe("production"); + }); + + it("does not set NEXT_PUBLIC_KANDEV_API_PORT in production single-port mode", () => { + // The Go backend reverse-proxies Next.js, so the client must use same-origin. + // A non-empty value would cause the client to build cross-origin URLs like + // `https://host:38429/...` that aren't reachable behind a reverse proxy. + const env = buildWebEnv({ ports, production: true }); + + expect(env.NEXT_PUBLIC_KANDEV_API_PORT).toBeUndefined(); + expect(env.NODE_ENV).toBe("production"); + }); + + it("strips a host-level NEXT_PUBLIC_KANDEV_API_PORT in production", () => { + // If an operator has the var in their shell/Docker env, the process.env + // spread would otherwise leak it into the Next.js process and reintroduce + // the cross-origin URL problem this fix addresses. + process.env.NEXT_PUBLIC_KANDEV_API_PORT = "99999"; + + const env = buildWebEnv({ ports, production: true }); + + expect(env.NEXT_PUBLIC_KANDEV_API_PORT).toBeUndefined(); + }); + + it("always sets KANDEV_API_BASE_URL for SSR fetches", () => { + expect(buildWebEnv({ ports }).KANDEV_API_BASE_URL).toBe("http://localhost:38429"); + expect(buildWebEnv({ ports, production: true }).KANDEV_API_BASE_URL).toBe( + "http://localhost:38429", + ); + }); + + it("enables debug flag when requested", () => { + expect(buildWebEnv({ ports, debug: true }).NEXT_PUBLIC_KANDEV_DEBUG).toBe("true"); + expect(buildWebEnv({ ports }).NEXT_PUBLIC_KANDEV_DEBUG).toBeUndefined(); + }); +}); diff --git a/apps/cli/src/shared.ts b/apps/cli/src/shared.ts index 71ac99f0a7..42c5a71170 100644 --- a/apps/cli/src/shared.ts +++ b/apps/cli/src/shared.ts @@ -85,9 +85,6 @@ export function buildWebEnv(options: WebEnvOptions): NodeJS.ProcessEnv { ...process.env, // Server-side: full localhost URL for SSR fetches (Next.js SSR → Go backend) KANDEV_API_BASE_URL: ports.backendUrl, - // Client-side: port injection for dev mode (browser on web port, API on backend port). - // In production, the backend reverse-proxies Next.js so the client uses same-origin. - NEXT_PUBLIC_KANDEV_API_PORT: String(ports.backendPort), PORT: String(ports.webPort), // Ensure Next.js standalone server binds to 127.0.0.1 so localhost health checks work. // Without this, HOSTNAME from the host environment can cause binding issues. @@ -96,6 +93,18 @@ export function buildWebEnv(options: WebEnvOptions): NodeJS.ProcessEnv { if (production) { (env as Record).NODE_ENV = "production"; + // Explicitly unset so a host-level NEXT_PUBLIC_KANDEV_API_PORT (from a .env + // file, Docker env, or CI variable) cannot leak through the process.env + // spread above and reintroduce the cross-origin URL problem. + delete env.NEXT_PUBLIC_KANDEV_API_PORT; + } else { + // Dev mode only: browser hits the web port directly, so the client needs to + // know the backend port for API calls. In production the Go backend + // reverse-proxies Next.js on a single port, so the client uses same-origin + // and this var must NOT be set — otherwise the client builds cross-origin + // URLs like `https://host:38429/...` that aren't reachable behind a + // reverse proxy / ingress / Cloudflare tunnel. + env.NEXT_PUBLIC_KANDEV_API_PORT = String(ports.backendPort); } if (debug) { diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx index cb899c8e44..2e23c3b00b 100644 --- a/apps/web/app/layout.tsx +++ b/apps/web/app/layout.tsx @@ -17,7 +17,7 @@ import { SidebarViewsSyncBridge } from "@/components/sidebar-views-sync-bridge"; import { LogBufferBridge } from "@/components/log-buffer-bridge"; export const metadata: Metadata = { - title: "KanDev - AI Kanban", + title: "Kandev - AI Kanban", description: "AI-powered workflow management for developers", }; @@ -43,7 +43,7 @@ export default function RootLayout({ return ( - + {apiPort || debugMode ? ( diff --git a/apps/web/app/manifest.json b/apps/web/app/manifest.json index ac969cb4de..e91af37667 100644 --- a/apps/web/app/manifest.json +++ b/apps/web/app/manifest.json @@ -1,6 +1,6 @@ { - "name": "KanDev", - "short_name": "KanDev", + "name": "Kandev", + "short_name": "Kandev", "icons": [ { "src": "/web-app-manifest-192x192.png", diff --git a/apps/web/app/settings/agents/[agentId]/profile-mcp-config-card.tsx b/apps/web/app/settings/agents/[agentId]/profile-mcp-config-card.tsx index 124c0cacc3..0ad50ff444 100644 --- a/apps/web/app/settings/agents/[agentId]/profile-mcp-config-card.tsx +++ b/apps/web/app/settings/agents/[agentId]/profile-mcp-config-card.tsx @@ -191,7 +191,7 @@ function McpServersEditor({ - ✓ KanDev MCP + ✓ Kandev MCP diff --git a/apps/web/app/settings/agents/page.tsx b/apps/web/app/settings/agents/page.tsx index 4b93d7f221..dd0f05b7ae 100644 --- a/apps/web/app/settings/agents/page.tsx +++ b/apps/web/app/settings/agents/page.tsx @@ -1,6 +1,6 @@ "use client"; -import { useCallback, useMemo, useState } from "react"; +import { useCallback, useEffect, useMemo, useState } from "react"; import Link from "next/link"; import { IconAlertTriangle, @@ -9,7 +9,7 @@ import { IconDownload, IconExternalLink, IconPlus, - IconSettings, + IconTerminal2, } from "@tabler/icons-react"; import { Badge } from "@kandev/ui/badge"; import { Button } from "@kandev/ui/button"; @@ -18,14 +18,20 @@ import { Separator } from "@kandev/ui/separator"; import { useAppStore } from "@/components/state-provider"; import { createCustomTUIAgent, + installAgent, listAgentDiscovery, listAgents, listAvailableAgents, + listInstallJobs, } from "@/lib/api"; +import type { InstallJob } from "@/lib/api"; import { useAgentDiscovery } from "@/hooks/domains/settings/use-agent-discovery"; import { useAvailableAgents } from "@/hooks/domains/settings/use-available-agents"; import { AgentLogo } from "@/components/agent-logo"; import { AddTUIAgentDialog } from "@/components/settings/add-tui-agent-dialog"; +import { HostShellDialog } from "@/components/settings/host-shell-dialog"; +import { InstallAgentCard } from "@/components/settings/install-agent-card"; +import { InstalledAgentCard } from "@/components/settings/installed-agent-card"; import { toAgentProfileOption } from "@/lib/state/slices/settings/types"; import type { AgentDiscovery, @@ -84,73 +90,33 @@ function CopyButton({ ); } -type AgentCardProps = { - agent: AgentDiscovery; - savedAgent: Agent | undefined; - displayName: string; -}; - -function AgentCard({ agent, savedAgent, displayName }: AgentCardProps) { - const configured = Boolean(savedAgent && savedAgent.profiles.length > 0); - const hasAgentRecord = Boolean(savedAgent); - return ( - - -
-
- -

{displayName}

- {agent.supports_mcp && MCP} - {configured && Configured} -
- {agent.matched_path && ( -

Detected at {agent.matched_path}

- )} -
- -
-
- ); -} - function InstallCard({ agent, copiedValue, onCopy, + job, + onInstall, }: { agent: AvailableAgent; copiedValue: string | null; onCopy: (text: string) => void; + job: InstallJob | undefined; + onInstall: (name: string) => void; }) { return ( - - -
- -

{agent.display_name}

-
- {agent.description && ( -

{agent.description}

- )} - {agent.install_script && ( + {agent.install_script} - )} -
-
+ ) : null + } + /> ); } @@ -230,6 +196,7 @@ type InstalledAgentsSectionProps = { rescanning: boolean; savedAgentsByName: Map; resolveDisplayName: (name: string) => string; + resolveCapabilityStatus: (name: string) => string | undefined; setTuiDialogOpen: (open: boolean) => void; handleRescan: () => Promise; }; @@ -240,9 +207,12 @@ function InstalledAgentsSection({ rescanning, savedAgentsByName, resolveDisplayName, + resolveCapabilityStatus, setTuiDialogOpen, handleRescan, }: InstalledAgentsSectionProps) { + const [shellOpen, setShellOpen] = useState(false); + return (
@@ -253,6 +223,16 @@ function InstalledAgentsSection({

+
+ { + // Rescan after the user closes the shell - they may have installed + // an agent CLI or fixed an auth issue inside the terminal. + void handleRescan(); + }} + /> {installedAgents.length === 0 && ( @@ -293,11 +282,13 @@ function InstalledAgentsSection({
{installedAgents.map((agent: AgentDiscovery) => ( - void handleRescan()} /> ))}
@@ -310,11 +301,15 @@ function SuggestInstallSection({ tools, copiedValue, onCopy, + installJobs, + onInstall, }: { notInstalledAgents: AvailableAgent[]; tools: ToolStatus[]; copiedValue: string | null; onCopy: (text: string) => void; + installJobs: Record; + onInstall: (name: string) => void; }) { const notInstalledTools = tools.filter((t) => !t.available); if (notInstalledAgents.length === 0 && notInstalledTools.length === 0) return null; @@ -325,13 +320,21 @@ function SuggestInstallSection({

Available to Install

- Install an agent CLI globally, then log in with the agent and click Rescan above. + Click Install to run the agent's install script on the kandev host. Progress streams + live; you can start multiple installs in parallel.

{notInstalledAgents.map((agent) => ( - + ))} {notInstalledTools.map((tool) => ( @@ -369,6 +372,73 @@ function AgentProfilesSection({ savedAgents }: AgentProfilesSectionProps) { ); } +/** + * Install state is held in the store (driven by WS events + * agent.install.{started,output,finished}). This hook: + * - Rehydrates jobs on mount so a page reload picks up in-flight installs. + * - Subscribes to agent.available.updated → calls onSuccess() to rescan. + * - Exposes handleInstall(name) which POSTs to enqueue (idempotent on the + * server: clicking again while running returns the same job_id). + */ +function useInstallAgent(onSuccess: () => Promise) { + const installJobs = useAppStore((state) => state.installJobs.byAgent); + const upsertInstallJob = useAppStore((state) => state.upsertInstallJob); + + useEffect(() => { + let cancelled = false; + listInstallJobs() + .then((resp) => { + if (cancelled) return; + // Upsert per-job rather than wholesale-replace: if a WS event + // already seeded an in-flight job with output chunks between page + // mount and this HTTP response, the snapshot from the server may + // be older, and a full replace would clobber the live output. + for (const job of resp.jobs) upsertInstallJob(job); + }) + .catch(() => { + /* page mount; ignore */ + }); + return () => { + cancelled = true; + }; + }, [upsertInstallJob]); + + // When any install finishes successfully, trigger the page-level rescan so + // the agent disappears from "Available to Install" and shows up under + // "Installed Agents". + useEffect(() => { + const succeeded = Object.values(installJobs).filter((j) => j.status === "succeeded"); + if (succeeded.length > 0) { + void onSuccess(); + } + // Intentionally only depends on the count of succeeded jobs to avoid + // re-firing on every output chunk during a running install. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [Object.values(installJobs).filter((j) => j.status === "succeeded").length]); + + const handleInstall = useCallback( + async (name: string) => { + try { + const job = await installAgent(name); + // The WS event will normally arrive first, but seed the store in case + // the WS round-trip is slower than the HTTP response. + upsertInstallJob(job); + } catch (err) { + upsertInstallJob({ + job_id: `local-error-${name}`, + agent_name: name, + status: "failed", + error: err instanceof Error ? err.message : String(err), + started_at: new Date().toISOString(), + }); + } + }, + [upsertInstallJob], + ); + + return { installJobs, handleInstall }; +} + function useAgentPageState() { const { items: discoveryAgents, loading: discoveryLoading } = useAgentDiscovery(); const savedAgents = useAppStore((state) => state.settingsAgents.items); @@ -394,6 +464,8 @@ function useAgentPageState() { ); const resolveDisplayName = (name: string) => availableAgents.find((item: AvailableAgent) => item.name === name)?.display_name ?? name; + const resolveCapabilityStatus = (name: string) => + availableAgents.find((item: AvailableAgent) => item.name === name)?.model_config?.status; const handleRescan = async () => { if (rescanning) return; @@ -410,6 +482,8 @@ function useAgentPageState() { } }; + const { installJobs, handleInstall } = useInstallAgent(handleRescan); + const handleCreateCustomTUI = async (data: { display_name: string; model?: string; @@ -442,8 +516,11 @@ function useAgentPageState() { tuiDialogOpen, setTuiDialogOpen, resolveDisplayName, + resolveCapabilityStatus, handleRescan, handleCreateCustomTUI, + installJobs, + handleInstall, }; } @@ -459,8 +536,11 @@ export default function AgentsSettingsPage() { tuiDialogOpen, setTuiDialogOpen, resolveDisplayName, + resolveCapabilityStatus, handleRescan, handleCreateCustomTUI, + installJobs, + handleInstall, } = useAgentPageState(); const { copiedValue, copy } = useCopyCommand(); @@ -481,6 +561,7 @@ export default function AgentsSettingsPage() { rescanning={rescanning} savedAgentsByName={savedAgentsByName} resolveDisplayName={resolveDisplayName} + resolveCapabilityStatus={resolveCapabilityStatus} setTuiDialogOpen={setTuiDialogOpen} handleRescan={handleRescan} /> @@ -490,6 +571,8 @@ export default function AgentsSettingsPage() { tools={tools} copiedValue={copiedValue} onCopy={copy} + installJobs={installJobs} + onInstall={handleInstall} /> diff --git a/apps/web/app/settings/layout.tsx b/apps/web/app/settings/layout.tsx index 5082949d6f..c2fd5ccd99 100644 --- a/apps/web/app/settings/layout.tsx +++ b/apps/web/app/settings/layout.tsx @@ -1,6 +1,12 @@ import { SettingsLayoutClient } from "@/components/settings/settings-layout-client"; import { StateHydrator } from "@/components/state-hydrator"; -import { listAgents, listExecutors, listWorkspaces } from "@/lib/api"; +import { + listAgentDiscovery, + listAgents, + listAvailableAgents, + listExecutors, + listWorkspaces, +} from "@/lib/api"; import { toAgentProfileOption } from "@/lib/state/slices/settings/types"; export default function SettingsLayout({ children }: { children: React.ReactNode }) { @@ -10,10 +16,15 @@ export default function SettingsLayout({ children }: { children: React.ReactNode async function SettingsLayoutServer({ children }: { children: React.ReactNode }) { let initialState = {}; try { - const [workspaces, executors, agents] = await Promise.all([ + // Fetch discovery + available agents alongside the DB-backed list so a + // hard refresh of /settings/agents/[name] (where no profile exists yet) + // can still render the agent from the discovered set. + const [workspaces, executors, agents, discovery, available] = await Promise.all([ listWorkspaces({ cache: "no-store" }), listExecutors({ cache: "no-store" }), listAgents({ cache: "no-store" }), + listAgentDiscovery({ cache: "no-store" }), + listAvailableAgents({ cache: "no-store" }), ]); initialState = { workspaces: { @@ -38,6 +49,17 @@ async function SettingsLayoutServer({ children }: { children: React.ReactNode }) settingsAgents: { items: agents.agents, }, + agentDiscovery: { + items: discovery.agents, + loading: false, + loaded: true, + }, + availableAgents: { + items: available.agents, + tools: available.tools ?? [], + loading: false, + loaded: true, + }, settingsData: { executorsLoaded: true, agentsLoaded: true, diff --git a/apps/web/app/stats/stats-page-client.tsx b/apps/web/app/stats/stats-page-client.tsx index f61576c029..1288883fbc 100644 --- a/apps/web/app/stats/stats-page-client.tsx +++ b/apps/web/app/stats/stats-page-client.tsx @@ -293,7 +293,7 @@ function buildStatsSummary( ? `${git_stats.total_commits} commits, +${git_stats.total_insertions.toLocaleString()}/-${git_stats.total_deletions.toLocaleString()}` : "no git activity"; return [ - `*KanDev Stats — ${rangeLabel}*`, + `*Kandev Stats — ${rangeLabel}*`, `- Tasks: ${global.total_tasks} total (${global.completed_tasks} done, ${global.in_progress_tasks} in progress) · ${completion} completion`, `- Completed (${rangeLabel}): ${completedInRange}`, `- Time: ${formatDuration(global.total_duration_ms)} total · ${formatDuration(global.avg_duration_ms_per_task)} avg/task`, diff --git a/apps/web/components/github/github-status.tsx b/apps/web/components/github/github-status.tsx index 5b483cf887..90abc4a313 100644 --- a/apps/web/components/github/github-status.tsx +++ b/apps/web/components/github/github-status.tsx @@ -3,22 +3,30 @@ import { useState, useCallback } from "react"; import { IconCheck, + IconChevronDown, + IconChevronRight, + IconInfoCircle, IconX, IconRefresh, IconKey, IconTrash, IconEye, IconEyeOff, + IconTerminal2, } from "@tabler/icons-react"; import { Badge } from "@kandev/ui/badge"; import { Button } from "@kandev/ui/button"; +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@kandev/ui/collapsible"; import { Input } from "@kandev/ui/input"; import { Spinner } from "@kandev/ui/spinner"; +import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip"; +import { useAppStore } from "@/components/state-provider"; import { useGitHubStatus } from "@/hooks/domains/github/use-github-status"; import { useToast } from "@/components/toast-provider"; import { configureGitHubToken, clearGitHubToken } from "@/lib/api/domains/github-api"; import type { AuthDiagnostics } from "@/lib/types/github"; import { GitHubRateLimitDisplay } from "./github-rate-limit"; +import { HostShellDialog } from "@/components/settings/host-shell-dialog"; function DiagnosticsOutput({ diagnostics }: { diagnostics: AuthDiagnostics }) { return ( @@ -109,7 +117,7 @@ function TokenConfigForm({ onSuccess }: { onSuccess: () => void }) {

Create a{" "} void }) { ); } +type StatusForNotConnected = { + diagnostics?: AuthDiagnostics; +}; + +function NotConnectedView({ + status, + refresh, + ghAuthOpen, + setGhAuthOpen, +}: { + status: StatusForNotConnected | null; + refresh: () => void; + ghAuthOpen: boolean; + setGhAuthOpen: (open: boolean) => void; +}) { + // gh installed → CLI sign-in is the recommended path (browser-driven OAuth, + // no PAT to manage). When it's missing we drop to PAT-only. + const ghInstalled = useAppStore((state) => + state.availableAgents.tools.some((t) => t.name === "gh" && t.available), + ); + const [tokenOpen, setTokenOpen] = useState(false); + const [diagOpen, setDiagOpen] = useState(false); + + return ( +

+ ); +} + +function DiagnosticsDisclosure({ + diagnostics, + open, + onOpenChange, +}: { + diagnostics: AuthDiagnostics; + open: boolean; + onOpenChange: (open: boolean) => void; +}) { + return ( + + + + + + + + + ); +} + +function PrimaryCLISignIn({ onClick }: { onClick: () => void }) { + return ( +
+
+

Sign in with the GitHub CLI

+

+ Recommended. Opens a terminal that runs{" "} + gh auth login with browser-based + authentication. +

+
+ +
+ ); +} + +function CLIUnavailableHint() { + return ( +
+ ); +} + export function GitHubStatusCard() { const { status, loaded, loading, refresh } = useGitHubStatus(); const { toast } = useToast(); const [clearing, setClearing] = useState(false); + const [ghAuthOpen, setGhAuthOpen] = useState(false); const handleClearToken = useCallback(async () => { setClearing(true); @@ -152,38 +333,12 @@ export function GitHubStatusCard() { if (!status || !status.authenticated) { return ( -
-
- - Not connected to GitHub - -
- - {/* Token configuration form */} -
-

Configure GitHub Token

- -
- - {/* Alternative methods */} -
-

Other authentication methods:

-
    -
  • - Environment variable — set{" "} - GITHUB_TOKEN when starting Kandev -
  • -
  • - GitHub CLI — run{" "} - gh auth login -
  • -
-
- {status?.diagnostics && } -
+ ); } diff --git a/apps/web/components/github/pr-ci-popover.tsx b/apps/web/components/github/pr-ci-popover.tsx new file mode 100644 index 0000000000..01c2640776 --- /dev/null +++ b/apps/web/components/github/pr-ci-popover.tsx @@ -0,0 +1,569 @@ +"use client"; + +import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react"; +import { + IconCheck, + IconCircleCheck, + IconCircleDot, + IconCircleX, + IconExternalLink, + IconGitPullRequest, + IconMessageCircle, + IconPlus, +} from "@tabler/icons-react"; +import { Button } from "@kandev/ui/button"; +import { useToast } from "@/components/toast-provider"; +import { useAppStore } from "@/components/state-provider"; +import { useCommentsStore } from "@/lib/state/slices/comments"; +import type { PRFeedbackComment } from "@/lib/state/slices/comments"; +import { useGitHubStatus } from "@/hooks/domains/github/use-github-status"; +import { usePRCIPopover } from "@/hooks/domains/github/use-pr-ci-popover"; +import { + bucketCheck, + bucketCheckCounts, + groupChecksByWorkflow, + type CheckBucket, + type WorkflowGroup, +} from "@/lib/github/check-buckets"; +import type { CheckRun, TaskPR } from "@/lib/types/github"; + +type CountsView = { + passed: number; + inProgress: number; + failed: number; +}; + +const CHECK_GROUP_ORDER: CheckBucket[] = ["passed", "in_progress", "failed"]; + +function countForBucket(counts: CountsView, kind: CheckBucket): number { + if (kind === "passed") return counts.passed; + if (kind === "in_progress") return counts.inProgress; + return counts.failed; +} + +function deriveAggregateCounts(pr: TaskPR): CountsView { + // Pre-load: if checks_total is populated, derive a coarse split using + // checks_state to attribute the "non-passing" remainder. This is good + // enough for the instant render — the lazy PRFeedback fetch refines. + const total = pr.checks_total; + const passing = pr.checks_passing; + const remaining = Math.max(0, total - passing); + if (pr.checks_state === "failure") { + return { passed: passing, failed: remaining, inProgress: 0 }; + } + if (pr.checks_state === "pending") { + return { passed: passing, failed: 0, inProgress: remaining }; + } + if (pr.checks_state === "success") { + return { passed: total, failed: 0, inProgress: 0 }; + } + return { passed: passing, failed: 0, inProgress: remaining }; +} + +function PRCIPopoverHeader({ pr }: { pr: TaskPR }) { + const checksUrl = `${pr.pr_url}/checks`; + return ( + + ); +} + +function CheckGroupIcon({ kind }: { kind: CheckBucket }) { + if (kind === "passed") return ; + if (kind === "in_progress") + return ; + return ; +} + +function bucketLabel(kind: CheckBucket): string { + if (kind === "passed") return "Passed"; + if (kind === "in_progress") return "In progress"; + return "Failed"; +} + +function CheckGroupHeader({ kind, count }: { kind: CheckBucket; count: number }) { + const label = bucketLabel(kind); + return ( +
+
+ + {label} +
+ + {count} + +
+ ); +} + +function PRWorkflowRow({ + group, + onAddAsContext, +}: { + group: WorkflowGroup; + onAddAsContext: ((message: string) => void) | null; +}) { + // For an in-progress workflow, "0/1 ran" reads as "nothing finished" + // and confuses people: did it start? It's clearer to just report how + // many jobs are running. (Failed workflows go to a different bucket, + // so an in_progress group never has failed jobs.) + const badge = + group.bucket === "in_progress" + ? `${group.inProgress} running` + : `${group.passed}/${group.total} passed`; + return ( +
{ + if (group.htmlUrl) window.open(group.htmlUrl, "_blank", "noopener,noreferrer"); + }} + > + + {group.workflow} + + {badge} + {group.htmlUrl && ( + + )} + {group.bucket === "failed" && onAddAsContext && ( + + )} +
+ ); +} + +function buildWorkflowMessage(group: WorkflowGroup): string { + const failed = group.jobs.filter((j) => bucketCheck(j) === "failed"); + const lines: string[] = [ + `### Workflow **${group.workflow}** has ${failed.length} failing job${failed.length !== 1 ? "s" : ""}.`, + "", + ]; + for (const job of failed) { + lines.push(`- **${job.name}** — ${job.conclusion || job.status}`); + if (job.output) lines.push(` ${job.output}`); + if (job.html_url) lines.push(` ${job.html_url}`); + } + lines.push("", "Please investigate and fix."); + return lines.join("\n"); +} + +function PRCheckGroup({ + kind, + count, + workflows, + isLoading, + onAddAsContext, +}: { + kind: CheckBucket; + count: number; + workflows?: WorkflowGroup[]; + isLoading: boolean; + onAddAsContext: ((message: string) => void) | null; +}) { + if (count <= 0 && (!workflows || workflows.length === 0)) return null; + const showRows = kind !== "passed"; + const hasWorkflows = !!workflows && workflows.length > 0; + return ( +
+ + {showRows && ( +
+ {hasWorkflows && + workflows!.map((g) => ( + + ))} + {!hasWorkflows && isLoading + ? Array.from({ length: Math.min(2, count || 1) }).map((_, i) => ( +
+ )) + : null} +
+ )} +
+ ); +} + +/** + * Stacked progress bar mirroring TodoIndicator's bar but split into three + * segments — green (passed), yellow (in_progress), red (failed) — each + * sized proportionally to its count. The leading "pass rate" label gives + * the same at-a-glance number TodoIndicator shows ("6/10 (60%)"). + * + * Skipped/cancelled-but-not-failed jobs aren't counted toward the total + * (they never enter any bucket), so the bar always reflects the actionable + * picture: how close are we to "all green". + */ +function PRChecksProgressBar({ counts }: { counts: CountsView }) { + const total = counts.passed + counts.inProgress + counts.failed; + if (total === 0) return null; + const pct = (n: number) => (n / total) * 100; + const passedPct = pct(counts.passed); + const inProgressPct = pct(counts.inProgress); + const failedPct = pct(counts.failed); + const completePct = Math.round(passedPct); + return ( +
+
+ Pass rate + + {counts.passed}/{total} ({completePct}%) + +
+
+ {passedPct > 0 && ( +
+ )} + {inProgressPct > 0 && ( +
+ )} + {failedPct > 0 && ( +
+ )} +
+
+ ); +} + +function PRChecksSection({ + pr, + feedback, + isFetching, + onAddAsContext, +}: { + pr: TaskPR; + feedback: { checks?: CheckRun[] } | null; + isFetching: boolean; + onAddAsContext: ((message: string) => void) | null; +}) { + const aggregateCounts = useMemo(() => deriveAggregateCounts(pr), [pr]); + + const { precise, byBucket } = useMemo(() => { + // Treat empty `feedback.checks` the same as "feedback not loaded yet" so + // we keep showing the aggregate counts. Some mock paths return empty + // arrays without errors, and we don't want the popover to flash 0/0/0. + if (!feedback?.checks || feedback.checks.length === 0) { + return { precise: null as CountsView | null, byBucket: null }; + } + const counts = bucketCheckCounts(feedback.checks); + const precise: CountsView = { + passed: counts.passed, + inProgress: counts.inProgress, + failed: counts.failed, + }; + const groups = groupChecksByWorkflow(feedback.checks); + const byBucket: Record = { + passed: groups.filter((g) => g.bucket === "passed"), + in_progress: groups.filter((g) => g.bucket === "in_progress"), + failed: groups.filter((g) => g.bucket === "failed"), + }; + return { precise, byBucket }; + }, [feedback]); + + const counts = precise ?? aggregateCounts; + // "No checks at all": the lazy fetch has settled (not isFetching) and there + // are no checks anywhere — neither in PRFeedback nor in the aggregate. + const noChecksAtAll = + !isFetching && pr.checks_total === 0 && (!feedback || (feedback.checks?.length ?? 0) === 0); + if (noChecksAtAll) { + return ( +
+
+ No checks have started +
+
+ ); + } + return ( +
+ + {CHECK_GROUP_ORDER.map((kind) => { + const value = countForBucket(counts, kind); + return ( + + ); + })} +
+ ); +} + +function PRReviewRow({ pr }: { pr: TaskPR }) { + const required = pr.required_reviews ?? null; + const approved = pr.review_count; + const requested = pr.pending_review_count; + + let label: string; + let icon: ReactNode; + if (pr.review_state === "approved") { + icon = ; + label = "Approved"; + } else if (pr.review_state === "changes_requested") { + icon = ; + label = "Changes requested"; + } else { + // Default branch covers "no reviews yet", "review pending", and any + // unknown state. Always rendered (no early-return) so a fresh PR + // still surfaces its review status. + icon = ; + label = "Awaiting review"; + } + // Counts live on the right edge, mirroring the check-group rows. + // Use "K / M" when a required-minimum is known, otherwise just the + // approved count. The "(K requested)" suffix slides in when reviewers + // have been pinged but haven't submitted a review. + let countText: string; + if (required != null) countText = `${approved} / ${required}`; + else countText = `${approved}`; + if (requested > 0) countText += ` · ${requested} requested`; + return ( +
+
+ {icon} + {label} +
+ {countText} +
+ ); +} + +function PRCommentsRow({ pr }: { pr: TaskPR }) { + if (!pr.unresolved_review_threads || pr.unresolved_review_threads <= 0) return null; + return ( +
+ + + {pr.unresolved_review_threads} unresolved comment + {pr.unresolved_review_threads === 1 ? "" : "s"} + +
+ ); +} + +function elapsedLabel(elapsed: number | null): string { + if (elapsed == null) return ""; + if (elapsed === 0) return "updated just now"; + return `updated ${formatElapsedShort(elapsed)} ago`; +} + +function PRPopoverFooter({ lastUpdatedAt }: { lastUpdatedAt: number | null }) { + // Capture a "now" snapshot only inside the setInterval callback (an event + // handler — no impurity in render, no setState during commit). When no + // tick has fired yet, fall back to lastUpdatedAt so the rendered elapsed + // is 0 ("just now"). + const [now, setNow] = useState(null); + useEffect(() => { + if (lastUpdatedAt == null) return; + const id = setInterval(() => setNow(Date.now()), 10_000); + return () => clearInterval(id); + }, [lastUpdatedAt]); + const elapsed = + lastUpdatedAt == null + ? null + : Math.max(0, Math.floor(((now ?? lastUpdatedAt) - lastUpdatedAt) / 1000)); + if (lastUpdatedAt == null) return null; + return ( +
+ + {elapsedLabel(elapsed)} + +
+ ); +} + +function formatElapsedShort(seconds: number): string { + if (seconds < 60) return `${seconds}s`; + const minutes = Math.floor(seconds / 60); + if (minutes < 60) return `${minutes}m`; + const hours = Math.floor(minutes / 60); + return `${hours}h`; +} + +function ReconnectGitHubBlock() { + return ( +
+ GitHub authentication lost. + + Reconnect GitHub + +
+ ); +} + +export function PRCIPopover({ + pr, + enabled, + onOpenDetailPanel, +}: { + pr: TaskPR; + enabled: boolean; + onOpenDetailPanel?: () => void; +}) { + const ghStatus = useAppStore((s) => s.githubStatus.status); + const authLost = ghStatus !== null && !ghStatus.authenticated; + // Trigger an initial status load from the same hook the rest of the app uses. + useGitHubStatus(); + const { feedback, isFetching, lastUpdatedAt } = usePRCIPopover(pr, enabled && !authLost); + const onAddAsContext = useAddCheckToContext(pr); + + return ( +
e.stopPropagation()} + > + + {authLost ? ( + + ) : ( + <> + +
+ + +
+ + )} + {onOpenDetailPanel && ( + + )} + +
+ ); +} + +// --- Add-to-context wiring (mirrors pr-detail-panel.tsx for failed checks) --- +function useAddCheckToContext(pr: TaskPR): ((message: string) => void) | null { + const sessionId = useAppStore((s) => s.tasks.activeSessionId); + const addComment = useCommentsStore((s) => s.addComment); + const { toast } = useToast(); + const prNumber = pr.pr_number; + // Always call useCallback (rules-of-hooks) before bailing out, so the + // returned callback identity is stable across renders unless its inputs + // change. Without memoization the popover would create a new function + // every parent render, defeating PRWorkflowRow's cheap reference equality. + const handler = useCallback( + (message: string) => { + if (!sessionId) return; + const comment: PRFeedbackComment = { + id: `pr-feedback-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`, + sessionId, + text: message, + createdAt: new Date().toISOString(), + status: "pending", + source: "pr-feedback", + prNumber, + feedbackType: "check", + content: message, + }; + addComment(comment); + toast({ description: "Added to chat context" }); + }, + [sessionId, prNumber, addComment, toast], + ); + return sessionId ? handler : null; +} + +// Multi-PR aggregate popover deferred — multi-PR tasks currently keep the +// existing DropdownMenu trigger (no hover popover). The aggregate component +// will land alongside that hover variant when it ships, see follow-up. diff --git a/apps/web/components/github/pr-status-chip.tsx b/apps/web/components/github/pr-status-chip.tsx new file mode 100644 index 0000000000..bf5403b716 --- /dev/null +++ b/apps/web/components/github/pr-status-chip.tsx @@ -0,0 +1,118 @@ +"use client"; + +import { useRef } from "react"; +import { + IconCircleCheckFilled, + IconCircleXFilled, + IconChecklist, + IconLoader2, + IconPointFilled, +} from "@tabler/icons-react"; +import { HoverCard, HoverCardContent, HoverCardTrigger } from "@kandev/ui/hover-card"; +import { useTaskPR } from "@/hooks/domains/github/use-task-pr"; +import { usePRFeedbackBackgroundSync } from "@/hooks/domains/github/use-pr-ci-popover"; +import { PRCIPopover } from "@/components/github/pr-ci-popover"; +import { isPRReadyToMerge } from "@/components/github/pr-task-icon"; +import type { TaskPR } from "@/lib/types/github"; + +const HOVER_OPEN_DELAY_MS = 150; +const HOVER_CLOSE_DELAY_MS = 150; + +type ChipStatus = "passed" | "failed" | "in_progress" | "merged" | "closed" | "neutral"; + +function chipStatus(pr: TaskPR): ChipStatus { + if (pr.state === "merged") return "merged"; + if (pr.state === "closed") return "closed"; + if (pr.review_state === "changes_requested" || pr.checks_state === "failure") return "failed"; + // Pending checks / pending review must beat checks_state === "success" so a + // PR with all checks green but reviewers still outstanding renders as + // in-progress, not passed. Without this order, the chip flips to green the + // moment CI finishes and ignores the human gate. + if (pr.checks_state === "pending" || pr.review_state === "pending") return "in_progress"; + if (pr.checks_state === "success") return "passed"; + return "neutral"; +} + +/** + * Compact CI indicator for the chat status bar — a "CI" prefix icon plus a + * status glyph that mirrors the popover's bucket colors: + * passed → green check + * failed → red X + * in progress → yellow spinner + * merged → purple dot + * neutral → muted dot + * + * Hovering opens the full PRCIPopover anchored to the top edge so the card + * expands upward (the chip sits just above the chat input). + * + * Returns null when the task has no PR yet. + */ +export function PRStatusChip({ taskId }: { taskId: string | null }) { + const { pr } = useTaskPR(taskId); + // Subscribe at the chip level so the cache warms even when the + // top-bar PR button isn't mounted (e.g. small viewport that hides it). + usePRFeedbackBackgroundSync(pr); + if (!pr) return null; + return ; +} + +function PRStatusChipInner({ pr }: { pr: TaskPR }) { + const status = chipStatus(pr); + const triggerRef = useRef(null); + return ( + + + + + { + // Radix HoverCard treats the trigger as outside the content's + // bounding box, so a click on the chip would auto-close the + // popover. Filter out trigger clicks so clicking the chip is + // a no-op while the popover stays open via hover. + if (triggerRef.current && triggerRef.current.contains(e.target as Node)) { + e.preventDefault(); + } + }} + > + + + + ); +} + +function ChipStatusGlyph({ status }: { status: ChipStatus }) { + switch (status) { + case "passed": + return