feat(agents): add user-managed runtime updates (#1950)

This commit is contained in:
Carlos Florêncio
2026-07-27 12:21:47 +01:00
committed by GitHub
parent 279e15b318
commit d0d084bdc6
65 changed files with 4302 additions and 268 deletions
+2 -2
View File
@@ -29,8 +29,8 @@ repos:
pass_filenames: true
- id: go-lint
name: Go lint (changed files only)
entry: bash -c 'unset GIT_DIR GIT_WORK_TREE; cd apps/backend && golangci-lint run --new-from-rev=HEAD'
name: Go lint (PR changed code)
entry: bash -c 'unset GIT_DIR GIT_WORK_TREE; base=$(git merge-base HEAD origin/main 2>/dev/null || git rev-parse HEAD); cd apps/backend && golangci-lint run ./... --new-from-rev="$base" --timeout=5m'
language: system
files: ^apps/backend/.*\.go$
pass_filenames: false
+12 -5
View File
@@ -70,13 +70,13 @@ Connect Kandev to the tools your team already uses — pull issues into the kanb
| Agent | Launch |
|:-------:|:----------:|
| **Claude Code** | `npx -y @agentclientprotocol/claude-agent-acp@0.61.0` |
| **Codex** | `npx -y @agentclientprotocol/codex-acp@1.1.5` |
| **GitHub Copilot** | `npx -y @github/copilot --acp` |
| **Gemini CLI** | `npx -y @google/gemini-cli --acp` |
| **Claude Code** | `npx --yes --prefer-offline @agentclientprotocol/claude-agent-acp` |
| **Codex** | `npx --yes --prefer-offline @agentclientprotocol/codex-acp` |
| **GitHub Copilot** | `npx --yes --prefer-offline @github/copilot --acp` |
| **Gemini CLI** | `npx --yes --prefer-offline @google/gemini-cli --acp` |
| **Amp** | `npx -y amp-acp` |
| **Auggie** | `npx -y @augmentcode/auggie --acp` |
| **OpenCode** | `opencode acp` |
| **OpenCode** | `npx --yes --prefer-offline opencode-ai acp` |
| **Cursor** | `cursor-agent acp` *(requires Cursor Pro)* |
| **Devin** | `devin acp` *(install Devin CLI from Devin Desktop or standalone installer)* |
| **Qwen** | `npx -y @qwen-code/qwen-code --acp` |
@@ -93,6 +93,13 @@ Connect Kandev to the tools your team already uses — pull issues into the kanb
> All agents communicate via [ACP](https://agentclientprotocol.com) (Agent Client Protocol). Some agents support ACP natively, while others use ACP adapter packages that bridge their native protocols. **CLI Passthrough mode** is available when an integration provides a passthrough command. If your agent isn't supported yet, open an issue or submit a PR with the integration. See [Adding a New Agent CLI](docs/add-agent-cli.md) for a step-by-step guide.
Kandev does not pin the managed npm runtimes for Claude, Codex, OpenCode,
Copilot, or Gemini. Normal launches can reuse npm's best-effort execution
cache. To deliberately fetch an upstream release, use **Update agent** in
**Settings > Agents**; Kandev updates the host runtime and refreshes its
advertised models and modes for future sessions without restarting active
sessions. See [Agents and Profiles](docs/public/agents-and-profiles.md#update-a-managed-agent-runtime).
### Bring your own TUI agents
Kandev can run any agent CLI as a TUI inside a terminal, even when it does not speak ACP. Add the command in agent profile settings and the task starts that agent inside a PTY terminal. CLI passthrough keeps the agent's native terminal UX available while still giving Kandev task tracking, worktrees, review, and session management.
@@ -1,29 +1,36 @@
# ACP bridge versions
# Managed npm ACP runtimes
Kandev tests these npm-provided ACP runtimes with the following package pins:
Kandev invokes these managed npm-provided ACP runtimes by unversioned package
name:
| Agent | Package | Tested version | ACP runtime selection |
| --- | --- | --- | --- |
| Claude | `@agentclientprotocol/claude-agent-acp` | `0.61.0` | Exact package spec through `npx` |
| Codex | `@agentclientprotocol/codex-acp` | `1.1.5` | Exact package spec through `npx` |
| OpenCode | `opencode-ai` | `1.18.4` | Installed `opencode` binary |
| Agent | Package | ACP arguments |
| --- | --- | --- |
| Claude | `@agentclientprotocol/claude-agent-acp` | none |
| Codex | `@agentclientprotocol/codex-acp` | none |
| OpenCode | `opencode-ai` | `acp` |
| Copilot | `@github/copilot` | `--acp` |
| Gemini | `@google/gemini-cli` | `--acp` |
Claude and Codex use their exact package specs for normal sessions, container
commands, one-shot inference, and remote installation. The resolved spec is
part of `AgentCommand`, which existing lifecycle diagnostics log as
`agent_command`.
Normal capability probes, sessions, container commands, and one-shot
inference use `npx --yes --prefer-offline` with the package name and arguments
above. This lets npm reuse its execution cache without making the cache a
durable installed-version guarantee. Kandev records the version reported by
the ACP initialize response instead of inferring it from source.
OpenCode intentionally uses the direct `opencode acp` command for discovery,
normal sessions, container commands, and one-shot inference. This keeps startup
offline-compatible and ensures discovery validates the executable actually
launched. Its installer remains pinned to `opencode-ai@1.18.4`, but discovery
accepts any `opencode` executable found on `PATH`; the ACP probe surfaces auth
or protocol-compatibility failures. The ACP initialize response separately
records the runtime-reported agent name and version.
The **Update agent** action in Settings is the explicit freshness boundary for
the Kandev host. It resolves the upstream npm version, refreshes the
unversioned execution-cache entry with online preference, and then launches a
fresh ACP capability probe. Successful probes replace the advertised version,
models, modes, commands, and configuration options used for later launches.
Already-running sessions continue with their existing process.
To update a bridge, change one version constant at a time, confirm the exact
version exists in the configured npm registry, capture only sanitized ACP wire
fixtures, and run the agent command-surface and ACP dialect tests before
changing the documented tested version. For OpenCode, also install the candidate
globally and confirm `opencode --version` before capturing fixtures. Do not add
prompts, file contents, credentials, or other user data to protocol fixtures.
ACP protocol negotiation and advertised capabilities are the compatibility
boundary. Kandev does not maintain an exact package-version allowlist or
silently roll back a runtime whose initialization fails. Package selection and
update commands come only from built-in agent metadata; callers cannot supply
package names, versions, registry URLs, or shell text.
Separately configured passthrough commands, native authentication helpers, and
native-only agents such as Cursor are outside this managed update path. Remote
executors and containers resolve their own unversioned runtime when they
launch; the host Settings action does not update those environments.
@@ -72,6 +72,13 @@ type InferenceAgent interface {
InferenceConfig() *InferenceConfig
}
// ManagedNPMRuntimeAgent is an optional capability for built-in agents whose
// ACP runtime is resolved through npm. Package names and ACP arguments are
// defined by the agent implementation rather than caller-provided input.
type ManagedNPMRuntimeAgent interface {
ManagedNPMRuntime() ManagedNPMRuntimeSpec
}
// PassthroughAgent is an optional capability for agents that support CLI passthrough mode.
type PassthroughAgent interface {
PassthroughConfig() PassthroughConfig
@@ -16,11 +16,7 @@ var claudeACPLogoLight []byte
//go:embed logos/claude_code_dark.svg
var claudeACPLogoDark []byte
const (
claudeACPPackage = "@agentclientprotocol/claude-agent-acp"
claudeACPVersion = "0.61.0"
claudeACPPackageSpec = claudeACPPackage + "@" + claudeACPVersion
)
const claudeACPPackage = "@agentclientprotocol/claude-agent-acp"
// claudeACPPermSettings maps the profile DangerouslySkipPermissions toggle to
// the Claude Code CLI's --dangerously-skip-permissions flag in passthrough mode.
@@ -38,9 +34,10 @@ var claudeACPPermSettings = map[string]PermissionSetting{
}
var (
_ Agent = (*ClaudeACP)(nil)
_ PassthroughAgent = (*ClaudeACP)(nil)
_ InferenceAgent = (*ClaudeACP)(nil)
_ Agent = (*ClaudeACP)(nil)
_ PassthroughAgent = (*ClaudeACP)(nil)
_ InferenceAgent = (*ClaudeACP)(nil)
_ ManagedNPMRuntimeAgent = (*ClaudeACP)(nil)
)
// ClaudeACP implements Agent for the agentclientprotocol claude-agent-acp package.
@@ -110,7 +107,11 @@ func (a *ClaudeACP) IsInstalled(ctx context.Context) (*DiscoveryResult, error) {
}
func (a *ClaudeACP) BuildCommand(opts CommandOptions) Command {
return Cmd("npx", "-y", claudeACPPackageSpec).Build()
return a.ManagedNPMRuntime().CachedACPCommand()
}
func (a *ClaudeACP) ManagedNPMRuntime() ManagedNPMRuntimeSpec {
return ManagedNPMRuntimeSpec{Package: claudeACPPackage}
}
func (a *ClaudeACP) Runtime() *RuntimeConfig {
@@ -118,7 +119,7 @@ func (a *ClaudeACP) Runtime() *RuntimeConfig {
return &RuntimeConfig{
Image: "kandev/multi-agent",
Tag: "latest",
Cmd: Cmd("npx", "-y", claudeACPPackageSpec).Build(),
Cmd: a.ManagedNPMRuntime().CachedACPCommand(),
WorkingDir: "{workspace}",
RequiredEnv: []string{}, // Auth via ANTHROPIC_API_KEY or OAuth credentials file (see RemoteAuth)
Env: map[string]string{
@@ -173,7 +174,7 @@ func (a *ClaudeACP) LoginCommand() *LoginCommand {
func (a *ClaudeACP) InstallScript() string {
// 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 " + claudeACPPackageSpec
return "npm install -g @anthropic-ai/claude-code " + claudeACPPackage
}
func (a *ClaudeACP) BillingType() usage.BillingType { return claudeBillingType() }
@@ -186,6 +187,6 @@ func (a *ClaudeACP) PermissionSettings() map[string]PermissionSetting {
func (a *ClaudeACP) InferenceConfig() *InferenceConfig {
return &InferenceConfig{
Supported: true,
Command: NewCommand("npx", "-y", claudeACPPackageSpec),
Command: a.ManagedNPMRuntime().CachedACPCommand(),
}
}
@@ -6,9 +6,9 @@ import (
"testing"
)
func TestClaudeACPUsesPinnedBridge(t *testing.T) {
func TestClaudeACPUsesManagedRuntime(t *testing.T) {
a := NewClaudeACP()
want := []string{"npx", "-y", "@agentclientprotocol/claude-agent-acp@0.61.0"}
want := []string{"npx", "--yes", "--prefer-offline", "@agentclientprotocol/claude-agent-acp"}
if got := a.BuildCommand(CommandOptions{}).Args(); !slices.Equal(got, want) {
t.Fatalf("BuildCommand = %#v, want %#v", got, want)
@@ -19,7 +19,7 @@ func TestClaudeACPUsesPinnedBridge(t *testing.T) {
if got := a.InferenceConfig().Command.Args(); !slices.Equal(got, want) {
t.Fatalf("Inference Command = %#v, want %#v", got, want)
}
wantInstall := "npm install -g @anthropic-ai/claude-code @agentclientprotocol/claude-agent-acp@0.61.0"
wantInstall := "npm install -g @anthropic-ai/claude-code @agentclientprotocol/claude-agent-acp"
if got := a.InstallScript(); got != wantInstall {
t.Fatalf("InstallScript = %q, want %q", got, wantInstall)
}
+13 -12
View File
@@ -16,16 +16,13 @@ var codexACPLogoLight []byte
//go:embed logos/codex_dark.svg
var codexACPLogoDark []byte
const (
codexACPPackage = "@agentclientprotocol/codex-acp"
codexACPVersion = "1.1.5"
codexACPPackageSpec = codexACPPackage + "@" + codexACPVersion
)
const codexACPPackage = "@agentclientprotocol/codex-acp"
var (
_ Agent = (*CodexACP)(nil)
_ PassthroughAgent = (*CodexACP)(nil)
_ InferenceAgent = (*CodexACP)(nil)
_ Agent = (*CodexACP)(nil)
_ PassthroughAgent = (*CodexACP)(nil)
_ InferenceAgent = (*CodexACP)(nil)
_ ManagedNPMRuntimeAgent = (*CodexACP)(nil)
)
// CodexACP implements Agent for the Agent Client Protocol codex-acp package.
@@ -99,7 +96,11 @@ func (a *CodexACP) IsInstalled(ctx context.Context) (*DiscoveryResult, error) {
}
func (a *CodexACP) BuildCommand(opts CommandOptions) Command {
return Cmd("npx", "-y", codexACPPackageSpec).Build()
return a.ManagedNPMRuntime().CachedACPCommand()
}
func (a *CodexACP) ManagedNPMRuntime() ManagedNPMRuntimeSpec {
return ManagedNPMRuntimeSpec{Package: codexACPPackage}
}
func (a *CodexACP) Runtime() *RuntimeConfig {
@@ -107,7 +108,7 @@ func (a *CodexACP) Runtime() *RuntimeConfig {
return &RuntimeConfig{
Image: "kandev/multi-agent",
Tag: "latest",
Cmd: Cmd("npx", "-y", codexACPPackageSpec).Build(),
Cmd: a.ManagedNPMRuntime().CachedACPCommand(),
WorkingDir: "{workspace}",
RequiredEnv: []string{"OPENAI_API_KEY"},
Env: map[string]string{},
@@ -166,7 +167,7 @@ func (a *CodexACP) LoginCommand() *LoginCommand {
// Install both the user-facing OpenAI codex CLI (which `codex login` runs
// against) and the ACP bridge package used for chat sessions.
func (a *CodexACP) InstallScript() string {
return "npm install -g @openai/codex " + codexACPPackageSpec
return "npm install -g @openai/codex " + codexACPPackage
}
func (a *CodexACP) BillingType() usage.BillingType { return codexBillingType() }
@@ -179,6 +180,6 @@ func (a *CodexACP) PermissionSettings() map[string]PermissionSetting {
func (a *CodexACP) InferenceConfig() *InferenceConfig {
return &InferenceConfig{
Supported: true,
Command: NewCommand("npx", "-y", codexACPPackageSpec),
Command: a.ManagedNPMRuntime().CachedACPCommand(),
}
}
@@ -25,7 +25,7 @@ func TestCodexACP_PermissionSettings_NoBridgeCLIFlags(t *testing.T) {
}
func TestCodexACP_BuildCommand_NoCodexCLIFlags(t *testing.T) {
want := []string{"npx", "-y", codexACPPackageSpec}
want := []string{"npx", "--yes", "--prefer-offline", codexACPPackage}
cmd := NewCodexACP().BuildCommand(CommandOptions{
PermissionValues: map[string]bool{PermissionKeyAutoApprove: true},
})
@@ -36,7 +36,7 @@ func TestCodexACP_BuildCommand_NoCodexCLIFlags(t *testing.T) {
func TestCodexACP_UsesAgentClientProtocolBridge(t *testing.T) {
a := NewCodexACP()
want := []string{"npx", "-y", "@agentclientprotocol/codex-acp@1.1.5"}
want := []string{"npx", "--yes", "--prefer-offline", "@agentclientprotocol/codex-acp"}
if got := a.BuildCommand(CommandOptions{}).Args(); !slices.Equal(got, want) {
t.Fatalf("BuildCommand = %#v, want %#v", got, want)
@@ -47,7 +47,7 @@ func TestCodexACP_UsesAgentClientProtocolBridge(t *testing.T) {
if got := a.InferenceConfig().Command.Args(); !slices.Equal(got, want) {
t.Fatalf("Inference Command = %#v, want %#v", got, want)
}
wantInstall := "npm install -g @openai/codex @agentclientprotocol/codex-acp@1.1.5"
wantInstall := "npm install -g @openai/codex @agentclientprotocol/codex-acp"
if got := a.InstallScript(); got != wantInstall {
t.Fatalf("InstallScript = %q, want %q", got, wantInstall)
}
@@ -15,18 +15,19 @@ var copilotACPLogoLight []byte
//go:embed logos/copilot_dark.svg
var copilotACPLogoDark []byte
const copilotACPPkg = "@github/copilot"
const copilotACPPackage = "@github/copilot"
// copilotNativeBinary is the standalone CLI installed by the @github/copilot
// npm package. When present on PATH we run it directly instead of paying the
// per-launch `npx` registry round-trip.
// npm package. It remains available for discovery and preflight checks, but
// ACP launches always use the exact package pin.
const copilotNativeBinary = "copilot"
var (
_ Agent = (*CopilotACP)(nil)
_ PassthroughAgent = (*CopilotACP)(nil)
_ InferenceAgent = (*CopilotACP)(nil)
_ NativeBinaryAgent = (*CopilotACP)(nil)
_ Agent = (*CopilotACP)(nil)
_ PassthroughAgent = (*CopilotACP)(nil)
_ InferenceAgent = (*CopilotACP)(nil)
_ NativeBinaryAgent = (*CopilotACP)(nil)
_ ManagedNPMRuntimeAgent = (*CopilotACP)(nil)
)
// CopilotACP implements Agent for GitHub Copilot using ACP protocol mode.
@@ -44,7 +45,7 @@ func NewCopilotACP() *CopilotACP {
Supported: true,
Label: "CLI Passthrough",
Description: "Show terminal directly instead of chat interface",
PassthroughCmd: NewCommand("npx", "-y", copilotACPPkg),
PassthroughCmd: NewCommand("npx", "--yes", "--prefer-offline", copilotACPPackage),
ModelFlag: NewParam("--model", "{model}"),
IdleTimeout: 3 * time.Second,
BufferMaxBytes: DefaultBufferMaxBytes,
@@ -89,17 +90,18 @@ func (a *CopilotACP) IsInstalled(ctx context.Context) (*DiscoveryResult, error)
// execution environment. See NativeBinaryAgent.
func (a *CopilotACP) NativeBinaryName() string { return copilotNativeBinary }
func (a *CopilotACP) BuildCommand(opts CommandOptions) Command {
if opts.PreferNativeBinary {
return Cmd(copilotNativeBinary, "--acp").Build()
}
return Cmd("npx", "-y", copilotACPPkg, "--acp").Build()
func (a *CopilotACP) BuildCommand(CommandOptions) Command {
return a.ManagedNPMRuntime().CachedACPCommand()
}
func (a *CopilotACP) ManagedNPMRuntime() ManagedNPMRuntimeSpec {
return ManagedNPMRuntimeSpec{Package: copilotACPPackage, ACPArgs: []string{"--acp"}}
}
func (a *CopilotACP) Runtime() *RuntimeConfig {
canRecover := true
return &RuntimeConfig{
Cmd: Cmd("npx", "-y", copilotACPPkg, "--acp").Build(),
Cmd: a.ManagedNPMRuntime().CachedACPCommand(),
WorkingDir: "{workspace}",
Env: map[string]string{},
ResourceLimits: ResourceLimits{MemoryMB: 4096, CPUCores: 2.0, Timeout: time.Hour},
@@ -126,7 +128,7 @@ func (a *CopilotACP) LoginCommand() *LoginCommand {
}
func (a *CopilotACP) InstallScript() string {
return "npm install -g " + copilotACPPkg
return "npm install -g " + copilotACPPackage
}
func (a *CopilotACP) BillingType() usage.BillingType { return defaultBillingType() }
@@ -186,6 +188,6 @@ var copilotPermSettings = map[string]PermissionSetting{
func (a *CopilotACP) InferenceConfig() *InferenceConfig {
return &InferenceConfig{
Supported: true,
Command: NewCommand("npx", "-y", copilotACPPkg, "--acp"),
Command: a.ManagedNPMRuntime().CachedACPCommand(),
}
}
@@ -1,6 +1,9 @@
package agents
import "testing"
import (
"slices"
"testing"
)
// TestCopilotACP_PermissionSettings_Curated verifies the four curated flag
// suggestions surfaced to the profile-creation UI. `allow_all_tools` is
@@ -47,7 +50,7 @@ func TestCopilotACP_BuildCommand_NoCLIFlagSpecialCasing(t *testing.T) {
ag := NewCopilotACP()
cmd := ag.BuildCommand(CommandOptions{})
got := cmd.Args()
want := []string{"npx", "-y", "@github/copilot", "--acp"}
want := []string{"npx", "--yes", "--prefer-offline", "@github/copilot", "--acp"}
if len(got) != len(want) {
t.Fatalf("argv length mismatch\n got: %#v\n want: %#v", got, want)
}
@@ -58,12 +61,29 @@ func TestCopilotACP_BuildCommand_NoCLIFlagSpecialCasing(t *testing.T) {
}
}
// TestCopilotACP_BuildCommand_PreferNativeBinary verifies that when the
// lifecycle has found the standalone `copilot` CLI in the execution
// environment, BuildCommand emits it directly instead of `npx -y <pkg>` —
// skipping the npm registry round-trip that makes launches slow behind a
// private registry.
func TestCopilotACP_BuildCommand_PreferNativeBinary(t *testing.T) {
func TestCopilotACP_UsesManagedPackageOnEveryNPMCommandSurface(t *testing.T) {
ag := NewCopilotACP()
wantACP := []string{"npx", "--yes", "--prefer-offline", "@github/copilot", "--acp"}
wantPassthrough := []string{"npx", "--yes", "--prefer-offline", "@github/copilot"}
if got := ag.Runtime().Cmd.Args(); !slices.Equal(got, wantACP) {
t.Fatalf("Runtime Cmd = %#v, want %#v", got, wantACP)
}
if got := ag.InferenceConfig().Command.Args(); !slices.Equal(got, wantACP) {
t.Fatalf("Inference Command = %#v, want %#v", got, wantACP)
}
if got := ag.PassthroughConfig().PassthroughCmd.Args(); !slices.Equal(got, wantPassthrough) {
t.Fatalf("Passthrough Cmd = %#v, want %#v", got, wantPassthrough)
}
if got, want := ag.InstallScript(), "npm install -g @github/copilot"; got != want {
t.Fatalf("InstallScript = %q, want %q", got, want)
}
}
// TestCopilotACP_BuildCommand_KeepsManagedPackageWhenNativeBinaryIsPresent
// prevents a globally installed Copilot binary from bypassing the managed npm
// runtime selected for capability discovery and future launches.
func TestCopilotACP_BuildCommand_KeepsManagedPackageWhenNativeBinaryIsPresent(t *testing.T) {
ag := NewCopilotACP()
if name := ag.NativeBinaryName(); name != "copilot" {
@@ -71,7 +91,7 @@ func TestCopilotACP_BuildCommand_PreferNativeBinary(t *testing.T) {
}
native := ag.BuildCommand(CommandOptions{PreferNativeBinary: true}).Args()
wantNative := []string{"copilot", "--acp"}
wantNative := []string{"npx", "--yes", "--prefer-offline", "@github/copilot", "--acp"}
if len(native) != len(wantNative) {
t.Fatalf("native argv mismatch\n got: %#v\n want: %#v", native, wantNative)
}
+14 -9
View File
@@ -15,12 +15,13 @@ var geminiLogoLight []byte
//go:embed logos/gemini_dark.svg
var geminiLogoDark []byte
const geminiPkg = "@google/gemini-cli"
const geminiPackage = "@google/gemini-cli"
var (
_ Agent = (*Gemini)(nil)
_ PassthroughAgent = (*Gemini)(nil)
_ InferenceAgent = (*Gemini)(nil)
_ Agent = (*Gemini)(nil)
_ PassthroughAgent = (*Gemini)(nil)
_ InferenceAgent = (*Gemini)(nil)
_ ManagedNPMRuntimeAgent = (*Gemini)(nil)
)
type Gemini struct {
@@ -35,7 +36,7 @@ func NewGemini() *Gemini {
Supported: true,
Label: "CLI Passthrough",
Description: "Show terminal directly instead of chat interface",
PassthroughCmd: NewCommand("npx", "@google/gemini-cli"),
PassthroughCmd: NewCommand("npx", "--yes", "--prefer-offline", geminiPackage),
ModelFlag: NewParam("--model", "{model}"),
PromptFlag: NewParam("--prompt-interactive", "{prompt}"),
IdleTimeout: 3 * time.Second,
@@ -77,13 +78,17 @@ func (a *Gemini) IsInstalled(ctx context.Context) (*DiscoveryResult, error) {
}
func (a *Gemini) BuildCommand(opts CommandOptions) Command {
return Cmd("npx", "-y", geminiPkg, "--acp").Build()
return a.ManagedNPMRuntime().CachedACPCommand()
}
func (a *Gemini) ManagedNPMRuntime() ManagedNPMRuntimeSpec {
return ManagedNPMRuntimeSpec{Package: geminiPackage, ACPArgs: []string{"--acp"}}
}
func (a *Gemini) Runtime() *RuntimeConfig {
canRecover := false
return &RuntimeConfig{
Cmd: Cmd("npx", "-y", geminiPkg, "--acp").Build(),
Cmd: a.ManagedNPMRuntime().CachedACPCommand(),
WorkingDir: "{workspace}",
Env: map[string]string{},
ResourceLimits: ResourceLimits{MemoryMB: 4096, CPUCores: 2.0, Timeout: time.Hour},
@@ -127,7 +132,7 @@ func (a *Gemini) LoginCommand() *LoginCommand {
}
func (a *Gemini) InstallScript() string {
return "npm install -g " + geminiPkg
return "npm install -g " + geminiPackage
}
func (a *Gemini) BillingType() usage.BillingType { return defaultBillingType() }
@@ -142,6 +147,6 @@ func (a *Gemini) PermissionSettings() map[string]PermissionSetting {
func (a *Gemini) InferenceConfig() *InferenceConfig {
return &InferenceConfig{
Supported: true,
Command: NewCommand("npx", "-y", geminiPkg, "--acp"),
Command: a.ManagedNPMRuntime().CachedACPCommand(),
}
}
@@ -0,0 +1,28 @@
package agents
import (
"slices"
"testing"
)
func TestGeminiUsesManagedPackageOnEveryNPMCommandSurface(t *testing.T) {
ag := NewGemini()
wantACP := []string{"npx", "--yes", "--prefer-offline", "@google/gemini-cli", "--acp"}
wantPassthrough := []string{"npx", "--yes", "--prefer-offline", "@google/gemini-cli"}
if got := ag.BuildCommand(CommandOptions{}).Args(); !slices.Equal(got, wantACP) {
t.Fatalf("BuildCommand = %#v, want %#v", got, wantACP)
}
if got := ag.Runtime().Cmd.Args(); !slices.Equal(got, wantACP) {
t.Fatalf("Runtime Cmd = %#v, want %#v", got, wantACP)
}
if got := ag.InferenceConfig().Command.Args(); !slices.Equal(got, wantACP) {
t.Fatalf("Inference Command = %#v, want %#v", got, wantACP)
}
if got := ag.PassthroughConfig().PassthroughCmd.Args(); !slices.Equal(got, wantPassthrough) {
t.Fatalf("Passthrough Cmd = %#v, want %#v", got, wantPassthrough)
}
if got, want := ag.InstallScript(), "npm install -g @google/gemini-cli"; got != want {
t.Fatalf("InstallScript = %q, want %q", got, want)
}
}
@@ -0,0 +1,35 @@
package agents
// ManagedNPMRuntimeSpec defines a built-in npm-distributed ACP runtime.
// Package and ACPArgs must come from trusted agent metadata, never request
// input, because update jobs execute them directly.
type ManagedNPMRuntimeSpec struct {
Package string
ACPArgs []string
}
// CachedACPCommand returns the normal launch command. The package is
// intentionally unversioned and prefer-offline lets npm reuse a suitable
// execution-cache entry while still fetching when the cache is empty.
func (s ManagedNPMRuntimeSpec) CachedACPCommand() Command {
args := []string{"npx", "--yes", "--prefer-offline", s.Package}
args = append(args, s.ACPArgs...)
return NewCommand(args...)
}
// CacheUpdateCommand returns the explicit cache-refresh command. npm exec
// installs the built-in unversioned package with online freshness before
// running a no-op under the prepared execution environment.
func (s ManagedNPMRuntimeSpec) CacheUpdateCommand() Command {
return NewCommand(
"npm",
"exec",
"--yes",
"--prefer-online",
"--package="+s.Package,
"--",
"node",
"-e",
"",
)
}
@@ -0,0 +1,64 @@
package agents
import (
"slices"
"strings"
"testing"
)
func TestManagedNPMRuntimeContracts(t *testing.T) {
tests := []struct {
name string
agent ManagedNPMRuntimeAgent
wantPackage string
wantACPArgs []string
}{
{"claude", NewClaudeACP(), "@agentclientprotocol/claude-agent-acp", nil},
{"codex", NewCodexACP(), "@agentclientprotocol/codex-acp", nil},
{"opencode", NewOpenCodeACP(), "opencode-ai", []string{"acp"}},
{"copilot", NewCopilotACP(), "@github/copilot", []string{"--acp"}},
{"gemini", NewGemini(), "@google/gemini-cli", []string{"--acp"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
spec := tt.agent.ManagedNPMRuntime()
if got := spec.Package; got != tt.wantPackage {
t.Fatalf("Package = %q, want %q", got, tt.wantPackage)
}
if got := spec.ACPArgs; !slices.Equal(got, tt.wantACPArgs) {
t.Fatalf("ACPArgs = %#v, want %#v", got, tt.wantACPArgs)
}
cached := spec.CachedACPCommand()
wantCached := append([]string{"npx", "--yes", "--prefer-offline", tt.wantPackage}, tt.wantACPArgs...)
if !slices.Equal(cached.Args(), wantCached) {
t.Fatalf("CachedACPCommand = %#v, want %#v", cached.Args(), wantCached)
}
assertUnversionedPackage(t, cached.Args(), tt.wantPackage)
update := spec.CacheUpdateCommand()
wantUpdate := []string{
"npm", "exec", "--yes", "--prefer-online",
"--package=" + tt.wantPackage, "--", "node", "-e", "",
}
if !slices.Equal(update.Args(), wantUpdate) {
t.Fatalf("CacheUpdateCommand = %#v, want %#v", update.Args(), wantUpdate)
}
if strings.Contains(strings.Join(update.Args(), " "), "latest") {
t.Fatalf("CacheUpdateCommand contains explicit latest: %#v", update.Args())
}
})
}
}
func assertUnversionedPackage(t *testing.T, argv []string, wantPackage string) {
t.Helper()
packageArg := argv[3]
if packageArg != wantPackage {
t.Fatalf("package argv = %q, want unversioned %q", packageArg, wantPackage)
}
if packageArg == wantPackage+"@latest" {
t.Fatalf("package argv contains explicit latest: %q", packageArg)
}
}
@@ -16,16 +16,13 @@ var opencodeACPLogoLight []byte
//go:embed logos/opencode_dark.svg
var opencodeACPLogoDark []byte
const (
opencodeACPPackage = "opencode-ai"
opencodeACPVersion = "1.18.4"
opencodeACPPackageSpec = opencodeACPPackage + "@" + opencodeACPVersion
)
const opencodeACPPackage = "opencode-ai"
var (
_ Agent = (*OpenCodeACP)(nil)
_ PassthroughAgent = (*OpenCodeACP)(nil)
_ InferenceAgent = (*OpenCodeACP)(nil)
_ Agent = (*OpenCodeACP)(nil)
_ PassthroughAgent = (*OpenCodeACP)(nil)
_ InferenceAgent = (*OpenCodeACP)(nil)
_ ManagedNPMRuntimeAgent = (*OpenCodeACP)(nil)
)
// OpenCodeACP is the ACP protocol variant of OpenCode.
@@ -88,13 +85,17 @@ func (a *OpenCodeACP) IsInstalled(ctx context.Context) (*DiscoveryResult, error)
}
func (a *OpenCodeACP) BuildCommand(opts CommandOptions) Command {
return Cmd("opencode", "acp").Build()
return a.ManagedNPMRuntime().CachedACPCommand()
}
func (a *OpenCodeACP) ManagedNPMRuntime() ManagedNPMRuntimeSpec {
return ManagedNPMRuntimeSpec{Package: opencodeACPPackage, ACPArgs: []string{"acp"}}
}
func (a *OpenCodeACP) Runtime() *RuntimeConfig {
canRecover := true
return &RuntimeConfig{
Cmd: Cmd("opencode", "acp").Build(),
Cmd: a.ManagedNPMRuntime().CachedACPCommand(),
WorkingDir: "{workspace}",
Env: map[string]string{},
ResourceLimits: ResourceLimits{MemoryMB: 4096, CPUCores: 2.0, Timeout: time.Hour},
@@ -132,7 +133,7 @@ func (a *OpenCodeACP) RemoteAuth() *RemoteAuth {
}
func (a *OpenCodeACP) InstallScript() string {
return "npm install -g " + opencodeACPPackageSpec
return "npm install -g " + opencodeACPPackage
}
func (a *OpenCodeACP) BillingType() usage.BillingType { return defaultBillingType() }
@@ -145,6 +146,6 @@ func (a *OpenCodeACP) PermissionSettings() map[string]PermissionSetting {
func (a *OpenCodeACP) InferenceConfig() *InferenceConfig {
return &InferenceConfig{
Supported: true,
Command: NewCommand("opencode", "acp"),
Command: a.ManagedNPMRuntime().CachedACPCommand(),
}
}
@@ -8,9 +8,9 @@ import (
"testing"
)
func TestOpenCodeACPUsesInstalledBinaryAndPinnedInstaller(t *testing.T) {
func TestOpenCodeACPUsesManagedRuntime(t *testing.T) {
a := NewOpenCodeACP()
want := []string{"opencode", "acp"}
want := []string{"npx", "--yes", "--prefer-offline", "opencode-ai", "acp"}
if got := a.BuildCommand(CommandOptions{}).Args(); !slices.Equal(got, want) {
t.Fatalf("BuildCommand = %#v, want %#v", got, want)
@@ -21,12 +21,12 @@ func TestOpenCodeACPUsesInstalledBinaryAndPinnedInstaller(t *testing.T) {
if got := a.InferenceConfig().Command.Args(); !slices.Equal(got, want) {
t.Fatalf("Inference Command = %#v, want %#v", got, want)
}
if got, wantInstall := a.InstallScript(), "npm install -g opencode-ai@1.18.4"; got != wantInstall {
if got, wantInstall := a.InstallScript(), "npm install -g opencode-ai"; got != wantInstall {
t.Fatalf("InstallScript = %q, want %q", got, wantInstall)
}
}
func TestOpenCodeACPDiscoveryMatchesRuntimeExecutable(t *testing.T) {
func TestOpenCodeACPDiscoveryRecognizesAuthenticationHelper(t *testing.T) {
binaryPath := writeOpenCodeTestBinary(t, "exit 7")
a := NewOpenCodeACP()
@@ -40,9 +40,6 @@ func TestOpenCodeACPDiscoveryMatchesRuntimeExecutable(t *testing.T) {
if result.MatchedPath != binaryPath {
t.Fatalf("IsInstalled() MatchedPath = %q, want %q", result.MatchedPath, binaryPath)
}
if got := a.BuildCommand(CommandOptions{}).Args()[0]; got != filepath.Base(binaryPath) {
t.Fatalf("runtime executable = %q, discovered executable = %q", got, filepath.Base(binaryPath))
}
}
func TestOpenCodeACPDiscoveryDoesNotRunVersionCommand(t *testing.T) {
@@ -523,10 +523,20 @@ const probeTimeout = 60 * time.Second
// probe runs an ACP probe against the given instance and translates the result
// into an AgentCapabilities record suitable for the cache.
func (m *Manager) probe(ctx context.Context, inst *instance, ia agents.InferenceAgent, refresh bool) AgentCapabilities {
return m.probeWithCommand(ctx, inst, ia, refresh, agents.Command{})
}
func (m *Manager) probeWithCommand(
ctx context.Context,
inst *instance,
ia agents.InferenceAgent,
refresh bool,
command agents.Command,
) AgentCapabilities {
probeCtx, cancel := context.WithTimeout(ctx, probeTimeout)
defer cancel()
req := buildProbeRequest(inst, ia, refresh)
req := buildProbeRequest(inst, ia, refresh, command)
resp, err := inst.client.Probe(probeCtx, req)
now := time.Now()
if err != nil {
@@ -600,13 +610,18 @@ func buildProbeRequest(
inst *instance,
ia agents.InferenceAgent,
refresh bool,
command agents.Command,
) *agentctlutil.ProbeRequest {
cfg := ia.InferenceConfig()
probeCommand := cfg.Command
if !command.IsEmpty() {
probeCommand = command
}
return &agentctlutil.ProbeRequest{
AgentID: inst.agentType,
Refresh: refresh,
InferenceConfig: &agentctlutil.InferenceConfigDTO{
Command: cfg.Command.Args(),
Command: probeCommand.Args(),
ModelFlag: cfg.ModelFlag.Args(),
WorkDir: inst.workDir,
StripEnv: agents.StripEnvFor(ia),
@@ -8,6 +8,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"sync"
@@ -25,6 +26,114 @@ import (
"github.com/stretchr/testify/require"
)
func TestManagerExposesRefreshWithCommand(t *testing.T) {
_, ok := reflect.TypeOf((*Manager)(nil)).MethodByName("RefreshWithCommand")
require.True(t, ok, "managed runtime updates need a command-override refresh")
}
func TestRefreshWithCommandUsesOverrideAndPreservesCacheOnAuthFailure(t *testing.T) {
log := newTestLogger(t)
reg := registry.NewRegistry(log)
const agentType = "managed-acp"
require.NoError(t, reg.Register(&installedInferenceAgent{id: agentType}))
var requestedCommand []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/health":
w.WriteHeader(http.StatusOK)
case "/api/v1/inference/probe":
var request agentctlutil.ProbeRequest
require.NoError(t, json.NewDecoder(r.Body).Decode(&request))
requestedCommand = append([]string(nil), request.InferenceConfig.Command...)
w.Header().Set("Content-Type", "application/json")
require.NoError(t, json.NewEncoder(w).Encode(agentctlutil.ProbeResponse{
Success: false,
Error: "login required",
}))
default:
http.NotFound(w, r)
}
}))
defer server.Close()
host, port := serverHostPort(t, server)
mgr := NewManager(reg, host, port, nil, log)
mgr.cache.set(AgentCapabilities{
AgentType: agentType,
AgentVersion: "1.0.0",
Status: StatusOK,
Models: []Model{{ID: "old-model", Name: "Old model"}},
})
mgr.instances[agentType] = &instance{
agentType: agentType,
workDir: t.TempDir(),
client: agentctlclient.NewClient(host, port, log),
}
caps, err := mgr.RefreshWithCommand(
context.Background(),
agentType,
agents.NewCommand("npx", "--yes", "--prefer-offline", "@example/managed-acp"),
)
require.NoError(t, err)
require.Equal(t, StatusAuthRequired, caps.Status)
require.Equal(t,
[]string{"npx", "--yes", "--prefer-offline", "@example/managed-acp"},
requestedCommand,
)
cached, ok := mgr.Get(agentType)
require.True(t, ok)
require.Equal(t, "1.0.0", cached.AgentVersion)
require.Equal(t, "old-model", cached.Models[0].ID)
}
func TestRefreshWithCommandReplacesCacheAfterSuccessfulProbe(t *testing.T) {
log := newTestLogger(t)
reg := registry.NewRegistry(log)
const agentType = "managed-acp"
require.NoError(t, reg.Register(&installedInferenceAgent{id: agentType}))
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/health":
w.WriteHeader(http.StatusOK)
case "/api/v1/inference/probe":
w.Header().Set("Content-Type", "application/json")
require.NoError(t, json.NewEncoder(w).Encode(agentctlutil.ProbeResponse{
Success: true,
AgentVersion: "1.1.0",
Models: []agentctlutil.ProbeModel{{
ID: "new-model",
Name: "New model",
}},
}))
default:
http.NotFound(w, r)
}
}))
defer server.Close()
host, port := serverHostPort(t, server)
mgr := NewManager(reg, host, port, nil, log)
mgr.cache.set(AgentCapabilities{AgentType: agentType, AgentVersion: "1.0.0", Status: StatusOK})
mgr.instances[agentType] = &instance{
agentType: agentType,
workDir: t.TempDir(),
client: agentctlclient.NewClient(host, port, log),
}
_, err := mgr.RefreshWithCommand(
context.Background(),
agentType,
agents.NewCommand("npx", "@example/managed-acp"),
)
require.NoError(t, err)
cached, ok := mgr.Get(agentType)
require.True(t, ok)
require.Equal(t, "1.1.0", cached.AgentVersion)
require.Equal(t, "new-model", cached.Models[0].ID)
}
func TestStopCancelsInFlightBootstrap(t *testing.T) {
log := newTestLogger(t)
reg := registry.NewRegistry(log)
@@ -55,6 +55,26 @@ func (m *Manager) Refresh(ctx context.Context, agentType string) (AgentCapabilit
return caps, nil
}
// RefreshWithCommand probes an agent with a trusted command override. Unlike
// Refresh, it preserves the last successful capability record unless the
// override probe succeeds. Runtime-update callers use this after priming npm's
// cache so a failed new runtime cannot erase the model list currently shown.
func (m *Manager) RefreshWithCommand(
ctx context.Context,
agentType string,
command agents.Command,
) (AgentCapabilities, error) {
inst, ia, err := m.getInstance(ctx, agentType)
if err != nil {
return AgentCapabilities{}, err
}
caps := m.probeWithCommand(ctx, inst, ia, true, command)
if caps.Status == StatusOK {
m.cache.set(caps)
}
return caps, nil
}
// ExecutePrompt runs a sessionless utility prompt against the warm instance
// for the given agent type. Convenience wrapper over ExecutePromptWithMCP
// that opts the call out of MCP tool access — most callers (PR title, commit
@@ -129,7 +129,7 @@ func TestBuildAgentCommand_ResumeFlag(t *testing.T) {
})
}
func TestBuildAgentCommand_PreservesPinnedACPBridgeSpecs(t *testing.T) {
func TestBuildAgentCommand_UsesManagedNPMRuntimes(t *testing.T) {
mgr := newTestManager(t)
tests := []struct {
name string
@@ -139,23 +139,33 @@ func TestBuildAgentCommand_PreservesPinnedACPBridgeSpecs(t *testing.T) {
{
name: "claude",
agent: agents.NewClaudeACP(),
want: "npx -y @agentclientprotocol/claude-agent-acp@0.61.0",
want: "npx --yes --prefer-offline @agentclientprotocol/claude-agent-acp",
},
{
name: "codex",
agent: agents.NewCodexACP(),
want: "npx -y @agentclientprotocol/codex-acp@1.1.5",
want: "npx --yes --prefer-offline @agentclientprotocol/codex-acp",
},
{
name: "opencode",
agent: agents.NewOpenCodeACP(),
want: "opencode acp",
want: "npx --yes --prefer-offline opencode-ai acp",
},
{
name: "copilot",
agent: agents.NewCopilotACP(),
want: "npx --yes --prefer-offline @github/copilot --acp",
},
{
name: "gemini",
agent: agents.NewGemini(),
want: "npx --yes --prefer-offline @google/gemini-cli --acp",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmds, err := mgr.buildAgentCommand(&LaunchRequest{}, nil, tt.agent, false)
cmds, err := mgr.buildAgentCommand(&LaunchRequest{}, nil, tt.agent, true)
require.NoError(t, err)
require.Equal(t, tt.want, cmds.initial)
})
@@ -132,6 +132,7 @@ func (c *Controller) buildAvailableAgentDTO(ctx context.Context, ag agents.Agent
}
loginCommand := buildLoginCommandDTO(ag)
runtimeUpdate := c.buildRuntimeUpdateDTO(ag, availability.Available)
return dto.AvailableAgentDTO{
Name: ag.ID(),
@@ -148,10 +149,38 @@ func (c *Controller) buildAvailableAgentDTO(ctx context.Context, ag agents.Agent
PermissionSettings: permissionSettings,
PassthroughConfig: passthroughConfig,
LoginCommand: loginCommand,
RuntimeUpdate: runtimeUpdate,
UpdatedAt: now,
}
}
func (c *Controller) buildRuntimeUpdateDTO(ag agents.Agent, available bool) *dto.RuntimeUpdateDTO {
if !available {
return nil
}
managed, ok := ag.(agents.ManagedNPMRuntimeAgent)
if !ok {
return nil
}
spec := managed.ManagedNPMRuntime()
if spec.Package == "" {
return nil
}
item := &dto.RuntimeUpdateDTO{Supported: true, Package: spec.Package}
if c.runtimeUpdater != nil {
if caps, found := c.runtimeUpdater.CurrentCapabilities(ag.ID()); found {
item.CurrentVersion = caps.AgentVersion
}
return item
}
if c.hostUtility != nil {
if caps, found := c.hostUtility.Get(ag.ID()); found {
item.CurrentVersion = caps.AgentVersion
}
}
return item
}
// 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 {
@@ -1,12 +1,89 @@
package controller
import (
"context"
"encoding/json"
"testing"
"time"
"github.com/kandev/kandev/internal/agent/agents"
"github.com/kandev/kandev/internal/agent/discovery"
"github.com/kandev/kandev/internal/agent/hostutility"
)
type managedTestAgent struct {
testAgent
spec agents.ManagedNPMRuntimeSpec
}
func (a *managedTestAgent) ManagedNPMRuntime() agents.ManagedNPMRuntimeSpec {
return a.spec
}
func TestAvailableAgentIncludesManagedRuntimeMetadata(t *testing.T) {
ag := &managedTestAgent{
testAgent: testAgent{id: "managed-acp", name: "Managed", enabled: true},
spec: agents.ManagedNPMRuntimeSpec{Package: "@example/managed-acp"},
}
ctrl := newTestController(map[string]agents.Agent{ag.ID(): ag})
ctrl.SetRuntimeUpdater(&fakeRuntimeUpdater{
current: hostutility.AgentCapabilities{AgentVersion: "1.2.3"},
currentFound: true,
})
item := ctrl.buildAvailableAgentDTO(context.Background(), ag, discovery.Availability{
Name: ag.ID(),
Available: true,
}, time.Now())
raw, err := json.Marshal(item)
if err != nil {
t.Fatalf("marshal available agent: %v", err)
}
var payload map[string]any
if err := json.Unmarshal(raw, &payload); err != nil {
t.Fatalf("unmarshal available agent: %v", err)
}
runtimeUpdate, ok := payload["runtime_update"].(map[string]any)
if !ok {
t.Fatal("runtime_update missing, want managed runtime metadata")
}
if runtimeUpdate["package"] != "@example/managed-acp" {
t.Fatalf("package = %#v, want @example/managed-acp", runtimeUpdate["package"])
}
if runtimeUpdate["supported"] != true {
t.Fatalf("supported = %#v, want true", runtimeUpdate["supported"])
}
if runtimeUpdate["current_version"] != "1.2.3" {
t.Fatalf("current_version = %#v, want 1.2.3", runtimeUpdate["current_version"])
}
}
func TestUnavailableManagedAgentOmitsRuntimeMetadata(t *testing.T) {
ag := &managedTestAgent{
testAgent: testAgent{id: "managed-acp", name: "Managed", enabled: true},
spec: agents.ManagedNPMRuntimeSpec{Package: "@example/managed-acp"},
}
ctrl := newTestController(map[string]agents.Agent{ag.ID(): ag})
item := ctrl.buildAvailableAgentDTO(
context.Background(),
ag,
discovery.Availability{Name: ag.ID(), Available: false},
time.Now(),
)
raw, err := json.Marshal(item)
if err != nil {
t.Fatalf("marshal available agent: %v", err)
}
var payload map[string]any
if err := json.Unmarshal(raw, &payload); err != nil {
t.Fatalf("unmarshal available agent: %v", err)
}
if _, exists := payload["runtime_update"]; exists {
t.Fatal("runtime_update present for unavailable agent")
}
}
func TestConfigOptionDTOsPreserveDescriptions(t *testing.T) {
dtos := configOptionDTOs([]hostutility.ConfigOption{{
Type: "select",
@@ -31,7 +31,10 @@ func (c *Controller) EnqueueInstall(name string) (*dto.InstallJobDTO, error) {
if script == "" {
return nil, ErrInstallScriptEmpty
}
job := c.jobStore.Enqueue(name, script)
job, err := c.jobStore.Enqueue(name, script)
if err != nil {
return nil, err
}
// 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.
@@ -0,0 +1,208 @@
package controller
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os/exec"
"strings"
"sync"
"github.com/kandev/kandev/internal/agent/agents"
"github.com/kandev/kandev/internal/agent/hostutility"
"github.com/kandev/kandev/internal/agent/settings/dto"
)
var (
ErrRuntimeUpdateUnsupported = errors.New("agent runtime update unsupported")
ErrRuntimeUpdaterUnavailable = errors.New("agent runtime updater unavailable")
)
// RuntimeUpdater is the external-process and host-probe boundary used by
// managed runtime jobs. Implementations must execute commands as direct argv.
type RuntimeUpdater interface {
CurrentCapabilities(agentName string) (hostutility.AgentCapabilities, bool)
ResolveTarget(ctx context.Context, packageName string) (string, error)
RunUpdate(ctx context.Context, command agents.Command, onChunk func(string)) error
Refresh(
ctx context.Context,
agentName string,
command agents.Command,
) (hostutility.AgentCapabilities, error)
}
type hostRuntimeUpdater struct {
host *hostutility.Manager
executor directCommandExecutor
}
type directCommandExecutor interface {
Output(ctx context.Context, command agents.Command) (string, error)
Stream(ctx context.Context, command agents.Command, onChunk func(string)) error
}
type execDirectCommandExecutor struct{}
func (execDirectCommandExecutor) Output(
ctx context.Context,
command agents.Command,
) (string, error) {
return runDirectCommandOutput(ctx, command)
}
func (execDirectCommandExecutor) Stream(
ctx context.Context,
command agents.Command,
onChunk func(string),
) error {
return runDirectCommand(ctx, command, onChunk)
}
func (u *hostRuntimeUpdater) CurrentCapabilities(agentName string) (hostutility.AgentCapabilities, bool) {
return u.host.Get(agentName)
}
func (u *hostRuntimeUpdater) ResolveTarget(ctx context.Context, packageName string) (string, error) {
command := agents.NewCommand("npm", "view", packageName, "dist-tags.latest", "--json")
output, err := u.executor.Output(ctx, command)
if err != nil {
return "", err
}
var target string
if err := json.Unmarshal([]byte(strings.TrimSpace(output)), &target); err != nil {
return "", fmt.Errorf("parse npm target version: %w", err)
}
if strings.TrimSpace(target) == "" {
return "", errors.New("npm target version is empty")
}
return strings.TrimSpace(target), nil
}
func runDirectCommandOutput(ctx context.Context, command agents.Command) (string, error) {
argv := command.Args()
if len(argv) == 0 {
return "", errors.New("runtime update command is empty")
}
cmd := exec.CommandContext(ctx, argv[0], argv[1:]...)
cmd.Env = filteredInstallEnv()
output, err := cmd.Output()
if err != nil {
return "", err
}
return string(output), nil
}
func (u *hostRuntimeUpdater) RunUpdate(
ctx context.Context,
command agents.Command,
onChunk func(string),
) error {
return u.executor.Stream(ctx, command, onChunk)
}
func (u *hostRuntimeUpdater) Refresh(
ctx context.Context,
agentName string,
command agents.Command,
) (hostutility.AgentCapabilities, error) {
return u.host.RefreshWithCommand(ctx, agentName, command)
}
func runDirectCommand(ctx context.Context, command agents.Command, onChunk func(string)) error {
argv := command.Args()
if len(argv) == 0 {
return errors.New("runtime update command is empty")
}
cmd := exec.CommandContext(ctx, argv[0], argv[1:]...)
cmd.Env = filteredInstallEnv()
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 scanCommandOutput(stdout, onChunk, &wg, errCh)
go scanCommandOutput(stderr, onChunk, &wg, errCh)
wg.Wait()
close(errCh)
if err := cmd.Wait(); err != nil {
return err
}
for scanErr := range errCh {
if scanErr != nil {
return scanErr
}
}
return nil
}
func scanCommandOutput(
reader io.Reader,
onChunk func(string),
wg *sync.WaitGroup,
errCh chan<- error,
) {
defer wg.Done()
scanner := bufio.NewScanner(reader)
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
for scanner.Scan() {
onChunk(scanner.Text() + "\n")
}
if err := scanner.Err(); err != nil {
errCh <- err
}
}
// EnqueueAgentUpdate starts or reuses an update for a built-in managed agent.
func (c *Controller) EnqueueAgentUpdate(name string) (*dto.AgentUpdateJobDTO, error) {
if c.updateJobStore == nil || c.runtimeUpdater == nil {
return nil, ErrRuntimeUpdaterUnavailable
}
ag, ok := c.agentRegistry.Get(name)
if !ok {
return nil, ErrAgentNotFound
}
managed, ok := ag.(agents.ManagedNPMRuntimeAgent)
if !ok {
return nil, ErrRuntimeUpdateUnsupported
}
spec := managed.ManagedNPMRuntime()
if strings.TrimSpace(spec.Package) == "" {
return nil, ErrRuntimeUpdateUnsupported
}
job, err := c.updateJobStore.Enqueue(name, spec)
if err != nil {
return nil, err
}
if snapshot, found := c.updateJobStore.Get(job.ID); found {
return snapshot, nil
}
snapshot := job.snapshot()
return &snapshot, nil
}
func (c *Controller) ListAgentUpdateJobs() []dto.AgentUpdateJobDTO {
if c.updateJobStore == nil {
return nil
}
return c.updateJobStore.ListAll()
}
func (c *Controller) GetAgentUpdateJob(id string) (*dto.AgentUpdateJobDTO, bool) {
if c.updateJobStore == nil {
return nil, false
}
return c.updateJobStore.Get(id)
}
@@ -0,0 +1,343 @@
package controller
import (
"bytes"
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/google/uuid"
"github.com/kandev/kandev/internal/agent/agents"
"github.com/kandev/kandev/internal/agent/hostutility"
"github.com/kandev/kandev/internal/agent/settings/dto"
ws "github.com/kandev/kandev/pkg/websocket"
"go.uber.org/zap"
)
type AgentUpdateJob struct {
ID string
AgentName string
Status dto.AgentUpdateJobStatus
CurrentVersion string
TargetVersion string
Output *ringBuffer
StartedAt time.Time
FinishedAt *time.Time
Error string
RefreshError string
}
type AgentUpdateJobStore struct {
mu sync.Mutex
jobs map[string]*AgentUpdateJob
activeByAgt map[string]*AgentUpdateJob
semaphore chan struct{}
hub JobBroadcaster
log *zap.Logger
updater RuntimeUpdater
maintenance *maintenanceCoordinator
onRefresh func()
}
func NewAgentUpdateJobStore(
hub JobBroadcaster,
log *zap.Logger,
updater RuntimeUpdater,
maintenance *maintenanceCoordinator,
onRefresh func(),
) *AgentUpdateJobStore {
if maintenance == nil {
maintenance = newMaintenanceCoordinator()
}
return &AgentUpdateJobStore{
jobs: make(map[string]*AgentUpdateJob),
activeByAgt: make(map[string]*AgentUpdateJob),
semaphore: make(chan struct{}, jobMaxParallel),
hub: hub,
log: log,
updater: updater,
maintenance: maintenance,
onRefresh: onRefresh,
}
}
func (s *AgentUpdateJobStore) Enqueue(
agentName string,
spec agents.ManagedNPMRuntimeSpec,
) (*AgentUpdateJob, error) {
s.mu.Lock()
if existing, ok := s.activeByAgt[agentName]; ok {
s.mu.Unlock()
return existing, nil
}
job := &AgentUpdateJob{
ID: uuid.NewString(),
AgentName: agentName,
Status: dto.AgentUpdateJobStatusQueued,
Output: newRingBuffer(jobOutputRingSize),
StartedAt: time.Now().UTC(),
}
ref, claimed, err := s.maintenance.claim(agentName, MaintenanceKindUpdate, job.ID)
if err != nil {
s.mu.Unlock()
return nil, err
}
if !claimed {
existing := s.jobs[ref.JobID]
s.mu.Unlock()
return existing, nil
}
s.jobs[job.ID] = job
s.activeByAgt[agentName] = job
s.mu.Unlock()
s.broadcast(ws.ActionAgentUpdateStarted, job.snapshot())
go s.run(job, spec, ref)
return job, nil
}
func (s *AgentUpdateJobStore) Get(jobID string) (*dto.AgentUpdateJobDTO, bool) {
s.mu.Lock()
defer s.mu.Unlock()
job, ok := s.jobs[jobID]
if !ok {
return nil, false
}
snapshot := job.snapshot()
return &snapshot, true
}
func (s *AgentUpdateJobStore) ListAll() []dto.AgentUpdateJobDTO {
s.mu.Lock()
defer s.mu.Unlock()
out := make([]dto.AgentUpdateJobDTO, 0, len(s.jobs))
for _, job := range s.jobs {
out = append(out, job.snapshot())
}
return out
}
func (s *AgentUpdateJobStore) run(
job *AgentUpdateJob,
spec agents.ManagedNPMRuntimeSpec,
ref MaintenanceJobRef,
) {
s.semaphore <- struct{}{}
defer func() { <-s.semaphore }()
ctx, cancel := context.WithTimeout(context.Background(), jobHardTimeout)
defer cancel()
s.setStatus(job, dto.AgentUpdateJobStatusResolving)
if caps, ok := s.updater.CurrentCapabilities(job.AgentName); ok {
s.mu.Lock()
job.CurrentVersion = caps.AgentVersion
s.mu.Unlock()
}
target, err := s.updater.ResolveTarget(ctx, spec.Package)
if err != nil {
s.finishFailed(job, ctx, fmt.Errorf("resolve target version: %w", err), ref)
return
}
s.mu.Lock()
job.TargetVersion = target
s.mu.Unlock()
s.setStatus(job, dto.AgentUpdateJobStatusUpdating)
flusher := newUpdateOutputFlusher(s, job)
err = s.updater.RunUpdate(ctx, spec.CacheUpdateCommand(), flusher.append)
flusher.flush()
if err != nil {
s.finishFailed(job, ctx, fmt.Errorf("update runtime: %w", err), ref)
return
}
s.setStatus(job, dto.AgentUpdateJobStatusRefreshing)
caps, refreshErr := s.updater.Refresh(ctx, job.AgentName, spec.CachedACPCommand())
s.finishRefresh(job, ctx, caps, refreshErr, ref)
}
func (s *AgentUpdateJobStore) setStatus(job *AgentUpdateJob, status dto.AgentUpdateJobStatus) {
s.mu.Lock()
job.Status = status
snapshot := job.snapshot()
s.mu.Unlock()
// A single in-progress action carries every queued-to-active transition so
// clients can upsert one job snapshot without subscribing to phase-specific
// actions. Terminal states use ActionAgentUpdateFinished below.
s.broadcast(ws.ActionAgentUpdateStarted, snapshot)
}
func (s *AgentUpdateJobStore) finishFailed(
job *AgentUpdateJob,
ctx context.Context,
err error,
ref MaintenanceJobRef,
) {
s.mu.Lock()
job.Status = dto.AgentUpdateJobStatusFailed
job.Error = formatUpdateJobError(ctx, err)
// Release the shared claim while the local active entry is still present.
// That makes same-agent retries atomic from the perspective of Enqueue.
s.maintenance.release(job.AgentName, ref)
s.finishLocked(job)
snapshot := job.snapshot()
s.mu.Unlock()
s.broadcast(ws.ActionAgentUpdateFinished, snapshot)
s.scheduleEviction(job.ID)
}
func (s *AgentUpdateJobStore) finishRefresh(
job *AgentUpdateJob,
ctx context.Context,
caps hostutility.AgentCapabilities,
err error,
ref MaintenanceJobRef,
) {
refreshed := false
s.mu.Lock()
switch {
case err != nil:
job.Status = dto.AgentUpdateJobStatusFailed
job.Error = formatUpdateJobError(ctx, fmt.Errorf("refresh capabilities: %w", err))
case caps.Status == hostutility.StatusOK:
job.Status = dto.AgentUpdateJobStatusSucceeded
refreshed = true
case caps.Status == hostutility.StatusAuthRequired:
job.Status = dto.AgentUpdateJobStatusSucceeded
job.RefreshError = caps.Error
if job.RefreshError == "" {
job.RefreshError = "authentication required"
}
default:
job.Status = dto.AgentUpdateJobStatusFailed
job.Error = capabilityRefreshError(caps)
}
// See finishFailed: a retry must not see a stale shared claim after the
// local active entry has been removed.
s.maintenance.release(job.AgentName, ref)
s.finishLocked(job)
snapshot := job.snapshot()
s.mu.Unlock()
if refreshed && s.onRefresh != nil {
s.onRefresh()
}
s.broadcast(ws.ActionAgentUpdateFinished, snapshot)
s.scheduleEviction(job.ID)
}
func (s *AgentUpdateJobStore) finishLocked(job *AgentUpdateJob) {
now := time.Now().UTC()
job.FinishedAt = &now
delete(s.activeByAgt, job.AgentName)
}
func capabilityRefreshError(caps hostutility.AgentCapabilities) string {
if caps.Error != "" {
return "refresh capabilities: " + caps.Error
}
return "refresh capabilities failed with status " + string(caps.Status)
}
func formatUpdateJobError(ctx context.Context, err error) string {
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
return fmt.Sprintf("update timed out after %s", jobHardTimeout)
}
return err.Error()
}
func (s *AgentUpdateJobStore) scheduleEviction(jobID string) {
time.AfterFunc(jobRetention, func() {
s.mu.Lock()
delete(s.jobs, jobID)
s.mu.Unlock()
})
}
func (s *AgentUpdateJobStore) broadcast(action string, payload dto.AgentUpdateJobDTO) {
if s.hub == nil {
return
}
message, _ := ws.NewNotification(action, payload)
//ws:global Managed runtime updates are host-wide Settings state.
s.hub.Broadcast(message)
}
func (j *AgentUpdateJob) snapshot() dto.AgentUpdateJobDTO {
snapshot := dto.AgentUpdateJobDTO{
JobID: j.ID,
AgentName: j.AgentName,
Status: j.Status,
CurrentVersion: j.CurrentVersion,
TargetVersion: j.TargetVersion,
Output: j.Output.String(),
Error: j.Error,
RefreshError: j.RefreshError,
StartedAt: j.StartedAt,
}
if j.FinishedAt != nil {
finished := *j.FinishedAt
snapshot.FinishedAt = &finished
}
return snapshot
}
type updateOutputFlusher struct {
store *AgentUpdateJobStore
job *AgentUpdateJob
mu sync.Mutex
buf bytes.Buffer
timer *time.Timer
}
func newUpdateOutputFlusher(store *AgentUpdateJobStore, job *AgentUpdateJob) *updateOutputFlusher {
return &updateOutputFlusher{store: store, job: job}
}
func (f *updateOutputFlusher) append(chunk string) {
if chunk == "" {
return
}
f.mu.Lock()
f.buf.WriteString(chunk)
_, _ = 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 *updateOutputFlusher) 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}
message, _ := ws.NewNotification(ws.ActionAgentUpdateOutput, payload)
//ws:global Managed runtime update output is host-wide Settings state.
f.store.hub.Broadcast(message)
}
@@ -0,0 +1,404 @@
package controller
import (
"context"
"encoding/json"
"errors"
"strings"
"sync"
"testing"
"time"
"github.com/kandev/kandev/internal/agent/agents"
"github.com/kandev/kandev/internal/agent/hostutility"
"github.com/kandev/kandev/internal/agent/settings/dto"
ws "github.com/kandev/kandev/pkg/websocket"
"go.uber.org/zap"
)
type fakeRuntimeUpdater struct {
mu sync.Mutex
current hostutility.AgentCapabilities
currentFound bool
target string
resolveErr error
runErr error
refreshCaps hostutility.AgentCapabilities
refreshErr error
runCommand []string
refreshCommand []string
updateOutput string
runStarted chan struct{}
releaseRun chan struct{}
runCalls int
refreshCalls int
resolvedPackage string
}
type recordingCommandExecutor struct {
outputCommand []string
output string
}
func (e *recordingCommandExecutor) Output(
_ context.Context,
command agents.Command,
) (string, error) {
e.outputCommand = append([]string(nil), command.Args()...)
return e.output, nil
}
func (e *recordingCommandExecutor) Stream(
context.Context,
agents.Command,
func(string),
) error {
return nil
}
func TestHostRuntimeUpdaterResolvesTargetWithDirectNPMArgv(t *testing.T) {
executor := &recordingCommandExecutor{output: "\"1.2.3\"\n"}
updater := &hostRuntimeUpdater{executor: executor}
target, err := updater.ResolveTarget(context.Background(), "@example/managed-acp")
if err != nil {
t.Fatalf("ResolveTarget: %v", err)
}
if target != "1.2.3" {
t.Fatalf("target = %q, want 1.2.3", target)
}
want := []string{"npm", "view", "@example/managed-acp", "dist-tags.latest", "--json"}
if got := strings.Join(executor.outputCommand, "\x00"); got != strings.Join(want, "\x00") {
t.Fatalf("command = %v, want %v", executor.outputCommand, want)
}
}
func (f *fakeRuntimeUpdater) CurrentCapabilities(string) (hostutility.AgentCapabilities, bool) {
return f.current, f.currentFound
}
func (f *fakeRuntimeUpdater) ResolveTarget(_ context.Context, packageName string) (string, error) {
f.mu.Lock()
f.resolvedPackage = packageName
f.mu.Unlock()
return f.target, f.resolveErr
}
func (f *fakeRuntimeUpdater) RunUpdate(
ctx context.Context,
command agents.Command,
onChunk func(string),
) error {
f.mu.Lock()
f.runCalls++
f.runCommand = append([]string(nil), command.Args()...)
started := f.runStarted
release := f.releaseRun
output := f.updateOutput
err := f.runErr
f.mu.Unlock()
if started != nil {
select {
case <-started:
default:
close(started)
}
}
if release != nil {
select {
case <-release:
case <-ctx.Done():
return ctx.Err()
}
}
onChunk(output)
return err
}
func (f *fakeRuntimeUpdater) Refresh(
_ context.Context,
_ string,
command agents.Command,
) (hostutility.AgentCapabilities, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.refreshCalls++
f.refreshCommand = append([]string(nil), command.Args()...)
return f.refreshCaps, f.refreshErr
}
type updateTerminalBroadcaster struct {
completed chan dto.AgentUpdateJobDTO
}
func newUpdateTerminalBroadcaster() *updateTerminalBroadcaster {
return &updateTerminalBroadcaster{completed: make(chan dto.AgentUpdateJobDTO, 2)}
}
func (b *updateTerminalBroadcaster) Broadcast(message *ws.Message) {
if message.Action != ws.ActionAgentUpdateFinished {
return
}
var job dto.AgentUpdateJobDTO
if json.Unmarshal(message.Payload, &job) != nil {
return
}
select {
case b.completed <- job:
default:
}
}
func newUpdateTestStore(
updater RuntimeUpdater,
maintenance *maintenanceCoordinator,
onRefresh func(),
) (*AgentUpdateJobStore, <-chan dto.AgentUpdateJobDTO) {
hub := newUpdateTerminalBroadcaster()
return NewAgentUpdateJobStore(hub, zap.NewNop(), updater, maintenance, onRefresh), hub.completed
}
func waitForUpdateStatus(
t *testing.T,
completed <-chan dto.AgentUpdateJobDTO,
jobID string,
statuses ...dto.AgentUpdateJobStatus,
) *dto.AgentUpdateJobDTO {
t.Helper()
var snapshot dto.AgentUpdateJobDTO
select {
case snapshot = <-completed:
case <-time.After(2 * time.Second):
t.Fatalf("job %s did not finish in time", jobID)
}
if snapshot.JobID != jobID {
t.Fatalf("finished job = %s, want %s", snapshot.JobID, jobID)
}
for _, status := range statuses {
if snapshot.Status == status {
return &snapshot
}
}
t.Fatalf("job %s finished with status %s, want %v", jobID, snapshot.Status, statuses)
return nil
}
func managedRuntimeSpec() agents.ManagedNPMRuntimeSpec {
return agents.ManagedNPMRuntimeSpec{
Package: "@example/managed-acp",
ACPArgs: []string{"--acp"},
}
}
func TestAgentUpdateJobResolvesUpdatesRefreshesAndStreams(t *testing.T) {
updater := &fakeRuntimeUpdater{
current: hostutility.AgentCapabilities{AgentVersion: "1.0.0"},
currentFound: true,
target: "1.1.0",
refreshCaps: hostutility.AgentCapabilities{
Status: hostutility.StatusOK,
AgentVersion: "1.1.0",
},
updateOutput: "npm prepared runtime\n",
}
refreshed := make(chan struct{}, 1)
store, completed := newUpdateTestStore(
updater, newMaintenanceCoordinator(), func() { refreshed <- struct{}{} },
)
job, err := store.Enqueue("managed-acp", managedRuntimeSpec())
if err != nil {
t.Fatalf("Enqueue: %v", err)
}
final := waitForUpdateStatus(t, completed, job.ID, dto.AgentUpdateJobStatusSucceeded)
if final.CurrentVersion != "1.0.0" || final.TargetVersion != "1.1.0" {
t.Fatalf("versions = %q -> %q, want 1.0.0 -> 1.1.0", final.CurrentVersion, final.TargetVersion)
}
if final.Output != "npm prepared runtime\n" {
t.Fatalf("Output = %q", final.Output)
}
select {
case <-refreshed:
default:
t.Fatal("successful refresh did not invoke catalogue callback")
}
updater.mu.Lock()
defer updater.mu.Unlock()
if updater.resolvedPackage != "@example/managed-acp" {
t.Fatalf("resolved package = %q", updater.resolvedPackage)
}
wantUpdate := "npm exec --yes --prefer-online --package=@example/managed-acp -- node -e "
if got := strings.Join(updater.runCommand, " "); got != wantUpdate {
t.Fatalf("update command = %q, want %q", got, wantUpdate)
}
wantRefresh := "npx --yes --prefer-offline @example/managed-acp --acp"
if got := strings.Join(updater.refreshCommand, " "); got != wantRefresh {
t.Fatalf("refresh command = %q, want %q", got, wantRefresh)
}
}
func TestAgentUpdateAuthRequiredIsPackageSuccessWithRefreshError(t *testing.T) {
updater := &fakeRuntimeUpdater{
target: "1.1.0",
refreshCaps: hostutility.AgentCapabilities{
Status: hostutility.StatusAuthRequired,
Error: "login required",
},
}
refreshed := false
store, completed := newUpdateTestStore(
updater, newMaintenanceCoordinator(), func() { refreshed = true },
)
job, err := store.Enqueue("managed-acp", managedRuntimeSpec())
if err != nil {
t.Fatalf("Enqueue: %v", err)
}
final := waitForUpdateStatus(t, completed, job.ID, dto.AgentUpdateJobStatusSucceeded)
if final.RefreshError != "login required" {
t.Fatalf("RefreshError = %q, want login required", final.RefreshError)
}
if final.Error != "" {
t.Fatalf("Error = %q, want empty", final.Error)
}
if refreshed {
t.Fatal("auth-required refresh must not broadcast a replacement catalogue")
}
}
func TestAgentUpdateRegistryFailureStopsBeforeMutation(t *testing.T) {
updater := &fakeRuntimeUpdater{resolveErr: errors.New("registry unavailable")}
store, completed := newUpdateTestStore(updater, newMaintenanceCoordinator(), nil)
job, err := store.Enqueue("managed-acp", managedRuntimeSpec())
if err != nil {
t.Fatalf("Enqueue: %v", err)
}
final := waitForUpdateStatus(t, completed, job.ID, dto.AgentUpdateJobStatusFailed)
if !strings.Contains(final.Error, "registry unavailable") {
t.Fatalf("Error = %q", final.Error)
}
updater.mu.Lock()
defer updater.mu.Unlock()
if updater.runCalls != 0 || updater.refreshCalls != 0 {
t.Fatalf("calls after registry failure: update=%d refresh=%d", updater.runCalls, updater.refreshCalls)
}
}
func TestAgentUpdateHardFailuresRemainFailed(t *testing.T) {
tests := []struct {
name string
updater *fakeRuntimeUpdater
wantMessage string
}{
{
name: "package update",
updater: &fakeRuntimeUpdater{
target: "1.1.0",
runErr: errors.New("npm exec failed"),
},
wantMessage: "npm exec failed",
},
{
name: "ACP initialization",
updater: &fakeRuntimeUpdater{
target: "1.1.0",
refreshCaps: hostutility.AgentCapabilities{
Status: hostutility.StatusFailed,
Error: "unsupported protocol version",
},
},
wantMessage: "unsupported protocol version",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
refreshed := false
store, completed := newUpdateTestStore(
test.updater, newMaintenanceCoordinator(), func() { refreshed = true },
)
job, err := store.Enqueue("managed-acp", managedRuntimeSpec())
if err != nil {
t.Fatalf("Enqueue: %v", err)
}
final := waitForUpdateStatus(t, completed, job.ID, dto.AgentUpdateJobStatusFailed)
if !strings.Contains(final.Error, test.wantMessage) {
t.Fatalf("Error = %q, want %q", final.Error, test.wantMessage)
}
if refreshed {
t.Fatal("hard failure invoked catalogue refresh callback")
}
})
}
}
func TestAgentUpdateDeduplicatesAndConflictsWithInstall(t *testing.T) {
coordinator := newMaintenanceCoordinator()
updater := &fakeRuntimeUpdater{
target: "1.1.0",
refreshCaps: hostutility.AgentCapabilities{Status: hostutility.StatusOK},
runStarted: make(chan struct{}),
releaseRun: make(chan struct{}),
}
store, completed := newUpdateTestStore(updater, coordinator, nil)
t.Cleanup(func() {
select {
case <-updater.releaseRun:
default:
close(updater.releaseRun)
}
})
first, err := store.Enqueue("managed-acp", managedRuntimeSpec())
if err != nil {
t.Fatalf("first enqueue: %v", err)
}
<-updater.runStarted
second, err := store.Enqueue("managed-acp", managedRuntimeSpec())
if err != nil {
t.Fatalf("second enqueue: %v", err)
}
if first.ID != second.ID {
t.Fatalf("job IDs differ: %s != %s", first.ID, second.ID)
}
installStore := NewJobStore(&captureBroadcaster{}, zap.NewNop(), nil, coordinator)
_, err = installStore.Enqueue("managed-acp", "echo install")
var conflict *MaintenanceConflictError
if !errors.As(err, &conflict) {
t.Fatalf("install conflict error = %v", err)
}
if conflict.Active.JobID != first.ID || conflict.Active.Kind != MaintenanceKindUpdate {
t.Fatalf("active conflict = %#v", conflict.Active)
}
close(updater.releaseRun)
waitForUpdateStatus(t, completed, first.ID, dto.AgentUpdateJobStatusSucceeded)
retry, err := store.Enqueue("managed-acp", managedRuntimeSpec())
if err != nil {
t.Fatalf("retry enqueue: %v", err)
}
if retry.ID == first.ID {
t.Fatal("retry reused a completed update job")
}
waitForUpdateStatus(t, completed, retry.ID, dto.AgentUpdateJobStatusSucceeded)
}
func TestAgentUpdateOutputIsBounded(t *testing.T) {
updater := &fakeRuntimeUpdater{
target: "1.1.0",
refreshCaps: hostutility.AgentCapabilities{Status: hostutility.StatusOK},
updateOutput: strings.Repeat("line contents\n", 7000),
}
store, completed := newUpdateTestStore(updater, newMaintenanceCoordinator(), nil)
job, err := store.Enqueue("managed-acp", managedRuntimeSpec())
if err != nil {
t.Fatalf("Enqueue: %v", err)
}
final := waitForUpdateStatus(t, completed, job.ID, dto.AgentUpdateJobStatusSucceeded)
if len(final.Output) > jobOutputRingSize {
t.Fatalf("output bytes = %d, limit = %d", len(final.Output), jobOutputRingSize)
}
}
@@ -57,6 +57,9 @@ type Controller struct {
modelCache *modelfetcher.Cache
hostUtility *hostutility.Manager
jobStore *JobStore
updateJobStore *AgentUpdateJobStore
runtimeUpdater RuntimeUpdater
maintenance *maintenanceCoordinator
hub JobBroadcaster
logger *logger.Logger
}
@@ -152,6 +155,23 @@ func NewController(repo store.Repository, discoveryRegistry *discovery.Registry,
// unset simply causes the model endpoints to report "not_configured".
func (c *Controller) SetHostUtility(h *hostutility.Manager) {
c.hostUtility = h
if h == nil {
c.runtimeUpdater = nil
c.updateJobStore = nil
return
}
c.SetRuntimeUpdater(&hostRuntimeUpdater{
host: h,
executor: execDirectCommandExecutor{},
})
}
// SetRuntimeUpdater replaces the process/probe boundary used by update jobs.
// Production wires the host utility implementation; embedders may provide a
// deterministic implementation without invoking npm.
func (c *Controller) SetRuntimeUpdater(updater RuntimeUpdater) {
c.runtimeUpdater = updater
c.initializeUpdateJobStore()
}
// SetJobBroadcaster initializes the install job store with a WS broadcaster
@@ -163,8 +183,11 @@ func (c *Controller) SetJobBroadcaster(hub JobBroadcaster) {
c.hub = hub
if hub == nil {
c.jobStore = nil
c.updateJobStore = nil
c.maintenance = nil
return
}
c.maintenance = newMaintenanceCoordinator()
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
@@ -183,7 +206,25 @@ func (c *Controller) SetJobBroadcaster(hub JobBroadcaster) {
}()
}
c.logger.Info("install succeeded", zap.String("agent", agentName))
})
}, c.maintenance)
c.initializeUpdateJobStore()
}
func (c *Controller) initializeUpdateJobStore() {
if c.hub == nil || c.runtimeUpdater == nil {
c.updateJobStore = nil
return
}
if c.maintenance == nil {
c.maintenance = newMaintenanceCoordinator()
}
c.updateJobStore = NewAgentUpdateJobStore(
c.hub,
c.logger.Zap(),
c.runtimeUpdater,
c.maintenance,
c.BroadcastAvailableAgents,
)
}
// BroadcastAvailableAgents fetches the current available-agents snapshot and
@@ -5,6 +5,7 @@ import (
"errors"
"os"
"path/filepath"
"slices"
"strings"
"testing"
@@ -632,16 +633,15 @@ func TestDetectAgents_E2EMockPropagatesSupportsMCP(t *testing.T) {
}
}
// TestController_PreviewAgentCommand_CopilotPrefersNativeBinary verifies the
// command preview reflects the local copilot CLI when it is on PATH — the
// preview assumes the default standalone host — and falls back to npx when it
// is absent. Regresses the report that the preview always showed npx.
func TestController_PreviewAgentCommand_CopilotPrefersNativeBinary(t *testing.T) {
// TestController_PreviewAgentCommand_CopilotKeepsManagedPackage verifies that
// a globally installed Copilot CLI does not make the command preview bypass
// the managed npm runtime.
func TestController_PreviewAgentCommand_CopilotKeepsManagedPackage(t *testing.T) {
controller := newTestController(map[string]agents.Agent{
"copilot-acp": agents.NewCopilotACP(),
})
// copilot on PATH → preview shows the native binary.
// A copilot binary on PATH must not change the previewed launch command.
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "copilot"), []byte("#!/bin/sh\n"), 0o755); err != nil {
t.Fatalf("write fake copilot: %v", err)
@@ -651,17 +651,8 @@ func TestController_PreviewAgentCommand_CopilotPrefersNativeBinary(t *testing.T)
if err != nil {
t.Fatalf("PreviewAgentCommand() error = %v", err)
}
if got := res.Command; len(got) == 0 || got[0] != "copilot" {
t.Errorf("preview with copilot on PATH should start with copilot, got %v", got)
}
// copilot absent → preview falls back to npx.
t.Setenv("PATH", t.TempDir())
res, err = controller.PreviewAgentCommand(context.Background(), "copilot-acp", CommandPreviewRequest{})
if err != nil {
t.Fatalf("PreviewAgentCommand() error = %v", err)
}
if got := res.Command; len(got) == 0 || got[0] != "npx" {
t.Errorf("preview without copilot on PATH should start with npx, got %v", got)
want := []string{"npx", "--yes", "--prefer-offline", "@github/copilot", "--acp"}
if got := res.Command; !slices.Equal(got, want) {
t.Errorf("preview with copilot on PATH = %v, want %v", got, want)
}
}
@@ -125,6 +125,7 @@ type JobStore struct {
hub JobBroadcaster
log *zap.Logger
onSuccess func(agentName string) // invoked when a job succeeds (used to invalidate discovery)
maintenance *maintenanceCoordinator
}
// JobBroadcaster is the subset of the gateway Broadcaster we need.
@@ -133,7 +134,12 @@ type JobBroadcaster interface {
}
// NewJobStore returns a fresh job store wired to the given broadcaster.
func NewJobStore(hub JobBroadcaster, log *zap.Logger, onSuccess func(string)) *JobStore {
func NewJobStore(
hub JobBroadcaster,
log *zap.Logger,
onSuccess func(string),
maintenance *maintenanceCoordinator,
) *JobStore {
return &JobStore{
jobs: make(map[string]*InstallJob),
activeByAgt: make(map[string]*InstallJob),
@@ -141,18 +147,19 @@ func NewJobStore(hub JobBroadcaster, log *zap.Logger, onSuccess func(string)) *J
hub: hub,
log: log,
onSuccess: onSuccess,
maintenance: maintenance,
}
}
// 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 {
func (s *JobStore) Enqueue(agentName, script string) (*InstallJob, error) {
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
return existing, nil
}
job := &InstallJob{
ID: uuid.NewString(),
@@ -161,13 +168,27 @@ func (s *JobStore) Enqueue(agentName, script string) *InstallJob {
Output: newRingBuffer(jobOutputRingSize),
StartedAt: time.Now().UTC(),
}
ref := MaintenanceJobRef{JobID: job.ID, Kind: MaintenanceKindInstall}
if s.maintenance != nil {
active, claimed, err := s.maintenance.claim(agentName, MaintenanceKindInstall, job.ID)
if err != nil {
s.mu.Unlock()
return nil, err
}
if !claimed {
existing := s.jobs[active.JobID]
s.mu.Unlock()
return existing, nil
}
ref = active
}
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
go s.run(job, script, ref)
return job, nil
}
// Get returns a snapshot of the job by ID. ok=false if not found.
@@ -193,7 +214,7 @@ func (s *JobStore) ListAll() []dto.InstallJobDTO {
return out
}
func (s *JobStore) run(job *InstallJob, script string) {
func (s *JobStore) run(job *InstallJob, script string, ref MaintenanceJobRef) {
// Bound parallel installs: queued jobs wait here until a slot frees up.
s.semaphore <- struct{}{}
defer func() { <-s.semaphore }()
@@ -228,9 +249,14 @@ func (s *JobStore) run(job *InstallJob, script string) {
job.ExitCode = &exit
}
}
// Release the shared maintenance claim before its local active entry. This
// keeps a concurrent retry from observing no local job while the shared
// coordinator still points at this completed job.
if s.maintenance != nil {
s.maintenance.release(job.AgentName, ref)
}
// 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.
// triggered from onSuccess or the WS broadcast starts a fresh job.
delete(s.activeByAgt, job.AgentName)
jobID := job.ID
s.mu.Unlock()
@@ -0,0 +1,65 @@
package controller
import (
"fmt"
"sync"
)
type MaintenanceKind string
const (
MaintenanceKindInstall MaintenanceKind = "install"
MaintenanceKindUpdate MaintenanceKind = "update"
)
type MaintenanceJobRef struct {
JobID string `json:"job_id"`
Kind MaintenanceKind `json:"kind"`
}
// MaintenanceConflictError identifies the active opposite-kind operation.
type MaintenanceConflictError struct {
AgentName string
Active MaintenanceJobRef
}
func (e *MaintenanceConflictError) Error() string {
return fmt.Sprintf("%s already has an active %s job", e.AgentName, e.Active.Kind)
}
// maintenanceCoordinator serializes mutating maintenance per agent while
// allowing independent agents to update or install concurrently.
type maintenanceCoordinator struct {
mu sync.Mutex
byAgent map[string]MaintenanceJobRef
}
func newMaintenanceCoordinator() *maintenanceCoordinator {
return &maintenanceCoordinator{byAgent: make(map[string]MaintenanceJobRef)}
}
func (c *maintenanceCoordinator) claim(
agentName string,
kind MaintenanceKind,
jobID string,
) (MaintenanceJobRef, bool, error) {
c.mu.Lock()
defer c.mu.Unlock()
if active, ok := c.byAgent[agentName]; ok {
if active.Kind == kind {
return active, false, nil
}
return active, false, &MaintenanceConflictError{AgentName: agentName, Active: active}
}
ref := MaintenanceJobRef{JobID: jobID, Kind: kind}
c.byAgent[agentName] = ref
return ref, true, nil
}
func (c *maintenanceCoordinator) release(agentName string, ref MaintenanceJobRef) {
c.mu.Lock()
defer c.mu.Unlock()
if current, ok := c.byAgent[agentName]; ok && current == ref {
delete(c.byAgent, agentName)
}
}
@@ -205,9 +205,18 @@ type AvailableAgentDTO struct {
PermissionSettings map[string]PermissionSettingDTO `json:"permission_settings,omitempty"`
PassthroughConfig *PassthroughConfigDTO `json:"passthrough_config,omitempty"`
LoginCommand *LoginCommandDTO `json:"login_command,omitempty"`
RuntimeUpdate *RuntimeUpdateDTO `json:"runtime_update,omitempty"`
UpdatedAt time.Time `json:"updated_at"`
}
// RuntimeUpdateDTO describes a Kandev-managed npm runtime. Package is
// informational; update requests select only the built-in agent name.
type RuntimeUpdateDTO struct {
Supported bool `json:"supported"`
Package string `json:"package"`
CurrentVersion string `json:"current_version,omitempty"`
}
type ListAvailableAgentsResponse struct {
Agents []AvailableAgentDTO `json:"agents"`
Tools []ToolStatusDTO `json:"tools,omitempty"`
@@ -249,6 +258,36 @@ type ListInstallJobsResponse struct {
Jobs []InstallJobDTO `json:"jobs"`
}
// AgentUpdateJobStatus represents one phase of a managed-runtime update.
type AgentUpdateJobStatus string
const (
AgentUpdateJobStatusQueued AgentUpdateJobStatus = "queued"
AgentUpdateJobStatusResolving AgentUpdateJobStatus = "resolving"
AgentUpdateJobStatusUpdating AgentUpdateJobStatus = "updating"
AgentUpdateJobStatusRefreshing AgentUpdateJobStatus = "refreshing"
AgentUpdateJobStatusSucceeded AgentUpdateJobStatus = "succeeded"
AgentUpdateJobStatusFailed AgentUpdateJobStatus = "failed"
)
// AgentUpdateJobDTO is the retained HTTP and WebSocket update snapshot.
type AgentUpdateJobDTO struct {
JobID string `json:"job_id"`
AgentName string `json:"agent_name"`
Status AgentUpdateJobStatus `json:"status"`
CurrentVersion string `json:"current_version,omitempty"`
TargetVersion string `json:"target_version,omitempty"`
Output string `json:"output,omitempty"`
Error string `json:"error,omitempty"`
RefreshError string `json:"refresh_error,omitempty"`
StartedAt time.Time `json:"started_at"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
}
type ListAgentUpdateJobsResponse struct {
Jobs []AgentUpdateJobDTO `json:"jobs"`
}
type AgentProfileMcpConfigDTO struct {
ProfileID string `json:"profile_id"`
Enabled bool `json:"enabled"`
@@ -0,0 +1,246 @@
package handlers
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/kandev/kandev/internal/agent/agents"
"github.com/kandev/kandev/internal/agent/discovery"
"github.com/kandev/kandev/internal/agent/hostutility"
"github.com/kandev/kandev/internal/agent/registry"
"github.com/kandev/kandev/internal/agent/settings/controller"
"github.com/kandev/kandev/internal/agent/settings/dto"
"github.com/kandev/kandev/internal/common/httpmw"
"github.com/kandev/kandev/internal/common/logger"
ws "github.com/kandev/kandev/pkg/websocket"
)
type handlerRuntimeUpdater struct {
started chan struct{}
release chan struct{}
once sync.Once
}
func (u *handlerRuntimeUpdater) CurrentCapabilities(string) (hostutility.AgentCapabilities, bool) {
return hostutility.AgentCapabilities{AgentVersion: "1.0.0"}, true
}
func (u *handlerRuntimeUpdater) ResolveTarget(context.Context, string) (string, error) {
return "1.1.0", nil
}
func (u *handlerRuntimeUpdater) RunUpdate(
ctx context.Context,
_ agents.Command,
onChunk func(string),
) error {
if u.started != nil {
u.once.Do(func() { close(u.started) })
}
if u.release != nil {
select {
case <-u.release:
case <-ctx.Done():
return ctx.Err()
}
}
onChunk("updated\n")
return nil
}
func (u *handlerRuntimeUpdater) Refresh(
context.Context,
string,
agents.Command,
) (hostutility.AgentCapabilities, error) {
return hostutility.AgentCapabilities{
Status: hostutility.StatusOK,
AgentVersion: "1.1.0",
}, nil
}
type updateTerminalBroadcaster struct {
completed chan dto.AgentUpdateJobDTO
}
func newUpdateTerminalBroadcaster() *updateTerminalBroadcaster {
return &updateTerminalBroadcaster{completed: make(chan dto.AgentUpdateJobDTO, 2)}
}
func (b *updateTerminalBroadcaster) Broadcast(message *ws.Message) {
if message.Action != ws.ActionAgentUpdateFinished {
return
}
var job dto.AgentUpdateJobDTO
if json.Unmarshal(message.Payload, &job) != nil {
return
}
select {
case b.completed <- job:
default:
}
}
func waitForTerminalUpdate(
t *testing.T,
completed <-chan dto.AgentUpdateJobDTO,
jobID string,
) dto.AgentUpdateJobDTO {
t.Helper()
select {
case job := <-completed:
if job.JobID != jobID {
t.Fatalf("finished job = %s, want %s", job.JobID, jobID)
}
return job
case <-time.After(2 * time.Second):
t.Fatalf("job %s did not finish in time", jobID)
return dto.AgentUpdateJobDTO{}
}
}
func newAgentUpdateRouter(
t *testing.T,
updater controller.RuntimeUpdater,
) (*gin.Engine, *controller.Controller, <-chan dto.AgentUpdateJobDTO) {
t.Helper()
gin.SetMode(gin.TestMode)
log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"})
if err != nil {
t.Fatalf("NewLogger: %v", err)
}
reg := registry.NewRegistry(log)
reg.LoadDefaults()
discoveryRegistry, err := discovery.LoadRegistry(context.Background(), reg, log)
if err != nil {
t.Fatalf("LoadRegistry: %v", err)
}
ctrl := controller.NewController(nil, discoveryRegistry, reg, nil, log)
ctrl.SetRuntimeUpdater(updater)
router := gin.New()
broadcaster := newUpdateTerminalBroadcaster()
RegisterRoutes(router, ctrl, broadcaster, log, "test-interlock")
return router, ctrl, broadcaster.completed
}
func updateRequest(method, path string) *http.Request {
request := httptest.NewRequest(method, path, nil)
request.Header.Set(httpmw.InterimSettingsInterlockHeader, "test-interlock")
return request
}
func TestAgentUpdateEndpointsAcceptAndRetainJobs(t *testing.T) {
router, _, completed := newAgentUpdateRouter(t, &handlerRuntimeUpdater{})
response := httptest.NewRecorder()
router.ServeHTTP(response, updateRequest(http.MethodPost, "/api/v1/agent-update/claude-acp"))
if response.Code != http.StatusAccepted {
t.Fatalf("POST status = %d, body = %s", response.Code, response.Body.String())
}
var accepted dto.AgentUpdateJobDTO
if err := json.Unmarshal(response.Body.Bytes(), &accepted); err != nil {
t.Fatalf("decode accepted job: %v", err)
}
finished := waitForTerminalUpdate(t, completed, accepted.JobID)
if finished.Status != dto.AgentUpdateJobStatusSucceeded {
t.Fatalf("finished status = %q, want succeeded", finished.Status)
}
getResponse := httptest.NewRecorder()
router.ServeHTTP(getResponse, updateRequest(
http.MethodGet,
"/api/v1/agent-update/jobs/"+accepted.JobID,
))
if getResponse.Code != http.StatusOK {
t.Fatalf("GET job status = %d, body = %s", getResponse.Code, getResponse.Body.String())
}
var retained dto.AgentUpdateJobDTO
if err := json.Unmarshal(getResponse.Body.Bytes(), &retained); err != nil {
t.Fatalf("decode retained job: %v", err)
}
if retained.Status != dto.AgentUpdateJobStatusSucceeded {
t.Fatalf("retained status = %q, want succeeded", retained.Status)
}
listResponse := httptest.NewRecorder()
router.ServeHTTP(listResponse, updateRequest(http.MethodGet, "/api/v1/agent-update/jobs"))
if listResponse.Code != http.StatusOK ||
!strings.Contains(listResponse.Body.String(), accepted.JobID) {
t.Fatalf("list response = %d %s", listResponse.Code, listResponse.Body.String())
}
}
func TestAgentUpdateEndpointReturnsMaintenanceConflict(t *testing.T) {
updater := &handlerRuntimeUpdater{
started: make(chan struct{}),
release: make(chan struct{}),
}
router, _, completed := newAgentUpdateRouter(t, updater)
t.Cleanup(func() {
select {
case <-updater.release:
default:
close(updater.release)
}
})
updateResponse := httptest.NewRecorder()
router.ServeHTTP(updateResponse, updateRequest(
http.MethodPost,
"/api/v1/agent-update/claude-acp",
))
if updateResponse.Code != http.StatusAccepted {
t.Fatalf("update status = %d, body = %s", updateResponse.Code, updateResponse.Body.String())
}
<-updater.started
installResponse := httptest.NewRecorder()
router.ServeHTTP(installResponse, updateRequest(
http.MethodPost,
"/api/v1/agent-install/claude-acp",
))
if installResponse.Code != http.StatusConflict {
t.Fatalf("install status = %d, body = %s", installResponse.Code, installResponse.Body.String())
}
if !strings.Contains(installResponse.Body.String(), `"active_kind":"update"`) {
t.Fatalf("conflict body = %s", installResponse.Body.String())
}
close(updater.release)
var accepted dto.AgentUpdateJobDTO
if err := json.Unmarshal(updateResponse.Body.Bytes(), &accepted); err != nil {
t.Fatalf("decode accepted update: %v", err)
}
finished := waitForTerminalUpdate(t, completed, accepted.JobID)
if finished.Status != dto.AgentUpdateJobStatusSucceeded {
t.Fatalf("finished status = %q, want succeeded", finished.Status)
}
}
func TestAgentUpdateEndpointRejectsUnmanagedAgentAndMissingJob(t *testing.T) {
router, _, _ := newAgentUpdateRouter(t, &handlerRuntimeUpdater{})
unsupported := httptest.NewRecorder()
router.ServeHTTP(unsupported, updateRequest(
http.MethodPost,
"/api/v1/agent-update/cursor-acp",
))
if unsupported.Code != http.StatusBadRequest {
t.Fatalf("unsupported status = %d, body = %s", unsupported.Code, unsupported.Body.String())
}
missing := httptest.NewRecorder()
router.ServeHTTP(missing, updateRequest(
http.MethodGet,
"/api/v1/agent-update/jobs/missing",
))
if missing.Code != http.StatusNotFound {
t.Fatalf("missing status = %d, body = %s", missing.Code, missing.Body.String())
}
}
@@ -66,6 +66,9 @@ func (h *Handlers) registerHTTP(router *gin.Engine) {
api.POST("/agent-install/:agentName", h.interlock, h.httpInstallAgent)
api.GET("/agent-install/jobs", h.httpListInstallJobs)
api.GET("/agent-install/jobs/:id", h.httpGetInstallJob)
api.POST("/agent-update/:agentName", h.interlock, h.httpUpdateAgentRuntime)
api.GET("/agent-update/jobs", h.httpListAgentUpdateJobs)
api.GET("/agent-update/jobs/:id", h.httpGetAgentUpdateJob)
api.PATCH("/agent-profiles/:id", h.interlock, h.httpUpdateProfile)
api.DELETE("/agent-profiles/:id", h.interlock, h.httpDeleteProfile)
api.GET("/agent-profiles/:id/mcp-config", h.httpGetProfileMcpConfig)
@@ -101,27 +104,119 @@ func (h *Handlers) httpListAvailableAgents(c *gin.Context) {
// 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, ok := requireAgentName(c)
if !ok {
return
}
h.enqueueMaintenance(c, name, "install", func() (any, error) {
return h.controller.EnqueueInstall(name)
}, classifyInstallError)
}
func (h *Handlers) httpUpdateAgentRuntime(c *gin.Context) {
name, ok := requireAgentName(c)
if !ok {
return
}
h.enqueueMaintenance(c, name, "update", func() (any, error) {
return h.controller.EnqueueAgentUpdate(name)
}, classifyUpdateError)
}
func requireAgentName(c *gin.Context) (string, bool) {
name := strings.TrimSpace(c.Param("agentName"))
if name == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "agent name is required"})
return "", false
}
return name, true
}
func writeMaintenanceConflictIfPresent(c *gin.Context, err error) bool {
var conflict *controller.MaintenanceConflictError
if !errors.As(err, &conflict) {
return false
}
writeMaintenanceConflict(c, conflict)
return true
}
type maintenanceErrorClassifier func(error) (int, string, bool)
func (h *Handlers) enqueueMaintenance(
c *gin.Context,
name string,
kind string,
enqueue func() (any, error),
classify maintenanceErrorClassifier,
) {
job, err := enqueue()
if err == nil {
c.JSON(http.StatusAccepted, job)
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"})
}
if writeMaintenanceConflictIfPresent(c, err) {
return
}
c.JSON(http.StatusAccepted, job)
if status, message, matched := classify(err); matched {
c.JSON(status, gin.H{"error": message})
return
}
h.logger.Error("failed to enqueue agent maintenance",
zap.String("agent", name), zap.String("kind", kind), zap.Error(err))
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to enqueue agent " + kind})
}
func classifyInstallError(err error) (int, string, bool) {
switch {
case errors.Is(err, controller.ErrAgentNotFound):
return http.StatusNotFound, "agent not found", true
case errors.Is(err, controller.ErrInstallScriptEmpty):
return http.StatusBadRequest, "agent has no install script", true
case errors.Is(err, controller.ErrJobStoreUnavailable):
return http.StatusServiceUnavailable, "install service not ready", true
default:
return 0, "", false
}
}
func classifyUpdateError(err error) (int, string, bool) {
switch {
case errors.Is(err, controller.ErrAgentNotFound):
return http.StatusNotFound, "agent not found", true
case errors.Is(err, controller.ErrRuntimeUpdateUnsupported):
return http.StatusBadRequest, "agent runtime update unsupported", true
case errors.Is(err, controller.ErrRuntimeUpdaterUnavailable):
return http.StatusServiceUnavailable, "agent update service not ready", true
default:
return 0, "", false
}
}
func (h *Handlers) httpListAgentUpdateJobs(c *gin.Context) {
c.JSON(http.StatusOK, dto.ListAgentUpdateJobsResponse{Jobs: h.controller.ListAgentUpdateJobs()})
}
func (h *Handlers) httpGetAgentUpdateJob(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.GetAgentUpdateJob(id)
if !ok {
c.JSON(http.StatusNotFound, gin.H{"error": "job not found"})
return
}
c.JSON(http.StatusOK, job)
}
func writeMaintenanceConflict(c *gin.Context, conflict *controller.MaintenanceConflictError) {
c.JSON(http.StatusConflict, gin.H{
"error": conflict.Error(),
"active_job_id": conflict.Active.JobID,
"active_kind": conflict.Active.Kind,
})
}
func (h *Handlers) httpListInstallJobs(c *gin.Context) {
@@ -49,6 +49,7 @@ func TestRegisterRoutesProtectsEveryStateChangingAgentSettingsRoute(t *testing.T
{method: http.MethodDelete, path: "/api/v1/agents/agent-1"},
{method: http.MethodPost, path: "/api/v1/agents/agent-1/profiles"},
{method: http.MethodPost, path: "/api/v1/agent-install/agent-1"},
{method: http.MethodPost, path: "/api/v1/agent-update/agent-1"},
{method: http.MethodPatch, path: "/api/v1/agent-profiles/profile-1"},
{method: http.MethodDelete, path: "/api/v1/agent-profiles/profile-1"},
{method: http.MethodPost, path: "/api/v1/agent-profiles/profile-1/mcp-config"},
+3
View File
@@ -190,6 +190,9 @@ const (
ActionAgentInstallStarted = "agent.install.started"
ActionAgentInstallOutput = "agent.install.output"
ActionAgentInstallFinished = "agent.install.finished"
ActionAgentUpdateStarted = "agent.update.started"
ActionAgentUpdateOutput = "agent.update.output"
ActionAgentUpdateFinished = "agent.update.finished"
ActionWorkspaceCreated = "workspace.created"
ActionWorkspaceUpdated = "workspace.updated"
ActionWorkspaceDeleted = "workspace.deleted"
+87 -44
View File
@@ -26,8 +26,9 @@ import {
listAvailableAgents,
listInstallJobs,
} from "@/lib/api";
import type { InstallJob } from "@/lib/api";
import type { AgentUpdateJob, InstallJob } from "@/lib/api";
import { useAgentDiscovery } from "@/hooks/domains/settings/use-agent-discovery";
import { useAgentRuntimeUpdates } from "@/hooks/domains/settings/use-agent-runtime-updates";
import { useAvailableAgents } from "@/hooks/domains/settings/use-available-agents";
import { AgentLogo } from "@/components/agent-logo";
import { AddTUIAgentDialog } from "@/components/settings/add-tui-agent-dialog";
@@ -40,6 +41,7 @@ import type {
Agent,
AvailableAgent,
AgentProfile,
RuntimeUpdate,
ToolStatus,
} from "@/lib/types/http";
@@ -199,10 +201,67 @@ type InstalledAgentsSectionProps = {
savedAgentsByName: Map<string, Agent>;
resolveDisplayName: (name: string) => string;
resolveCapabilityStatus: (name: string) => string | undefined;
resolveRuntimeUpdate: (name: string) => RuntimeUpdate | undefined;
installJobs: Record<string, InstallJob>;
updateJobs: Record<string, AgentUpdateJob>;
handleUpdate: (name: string) => Promise<void>;
setTuiDialogOpen: (open: boolean) => void;
handleRescan: () => Promise<void>;
};
function InstalledAgentsHeader({
rescanning,
onOpenShell,
onOpenTuiDialog,
onRescan,
}: {
rescanning: boolean;
onOpenShell: () => void;
onOpenTuiDialog: () => void;
onRescan: () => void;
}) {
return (
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
<div>
<h3 className="text-lg font-semibold">Installed Agents</h3>
<p className="text-sm text-muted-foreground">
Agents detected on this machine are ready to configure.
</p>
</div>
<div className="flex w-full flex-wrap gap-2 sm:w-auto">
<Button
variant="outline"
size="sm"
onClick={onOpenShell}
className="cursor-pointer"
data-testid="open-host-shell"
>
<IconTerminal2 className="h-4 w-4 mr-2" />
Terminal
</Button>
<Button variant="outline" size="sm" onClick={onOpenTuiDialog} className="cursor-pointer">
<IconPlus className="h-4 w-4 mr-2" />
Add TUI Agent
</Button>
<Button
variant="outline"
size="sm"
onClick={onRescan}
disabled={rescanning}
className="cursor-pointer"
>
{rescanning ? (
<IconLoader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<IconRefresh className="h-4 w-4 mr-2" />
)}
Rescan
</Button>
</div>
</div>
);
}
function InstalledAgentsSection({
installedAgents,
discoveryLoading,
@@ -210,6 +269,10 @@ function InstalledAgentsSection({
savedAgentsByName,
resolveDisplayName,
resolveCapabilityStatus,
resolveRuntimeUpdate,
installJobs,
updateJobs,
handleUpdate,
setTuiDialogOpen,
handleRescan,
}: InstalledAgentsSectionProps) {
@@ -217,49 +280,12 @@ function InstalledAgentsSection({
return (
<div className="space-y-4">
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
<div>
<h3 className="text-lg font-semibold">Installed Agents</h3>
<p className="text-sm text-muted-foreground">
Agents detected on this machine are ready to configure.
</p>
</div>
<div className="flex w-full gap-2 sm:w-auto">
<Button
variant="outline"
size="sm"
onClick={() => setShellOpen(true)}
className="cursor-pointer"
data-testid="open-host-shell"
>
<IconTerminal2 className="h-4 w-4 mr-2" />
Terminal
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setTuiDialogOpen(true)}
className="cursor-pointer"
>
<IconPlus className="h-4 w-4 mr-2" />
Add TUI Agent
</Button>
<Button
variant="outline"
size="sm"
onClick={handleRescan}
disabled={rescanning}
className="cursor-pointer"
>
{rescanning ? (
<IconLoader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<IconRefresh className="h-4 w-4 mr-2" />
)}
Rescan
</Button>
</div>
</div>
<InstalledAgentsHeader
rescanning={rescanning}
onOpenShell={() => setShellOpen(true)}
onOpenTuiDialog={() => setTuiDialogOpen(true)}
onRescan={() => void handleRescan()}
/>
<HostShellDialog
open={shellOpen}
onOpenChange={setShellOpen}
@@ -295,6 +321,10 @@ function InstalledAgentsSection({
savedAgent={savedAgentsByName.get(agent.name)}
displayName={resolveDisplayName(agent.name)}
capabilityStatus={resolveCapabilityStatus(agent.name)}
runtimeUpdate={resolveRuntimeUpdate(agent.name)}
installJob={installJobs[agent.name]}
updateJob={updateJobs[agent.name]}
onUpdate={(name) => void handleUpdate(name)}
onAuthComplete={() => void handleRescan()}
/>
))}
@@ -473,6 +503,8 @@ function useAgentPageState() {
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 resolveRuntimeUpdate = (name: string) =>
availableAgents.find((item: AvailableAgent) => item.name === name)?.runtime_update;
const handleRescan = async () => {
if (rescanning) {
@@ -492,6 +524,7 @@ function useAgentPageState() {
};
const { installJobs, handleInstall } = useInstallAgent(handleRescan);
const { updateJobs, handleUpdate } = useAgentRuntimeUpdates();
const handleCreateCustomTUI = async (data: {
display_name: string;
@@ -526,10 +559,13 @@ function useAgentPageState() {
setTuiDialogOpen,
resolveDisplayName,
resolveCapabilityStatus,
resolveRuntimeUpdate,
handleRescan,
handleCreateCustomTUI,
installJobs,
handleInstall,
updateJobs,
handleUpdate,
};
}
@@ -546,10 +582,13 @@ export default function AgentsSettingsPage() {
setTuiDialogOpen,
resolveDisplayName,
resolveCapabilityStatus,
resolveRuntimeUpdate,
handleRescan,
handleCreateCustomTUI,
installJobs,
handleInstall,
updateJobs,
handleUpdate,
} = useAgentPageState();
const { copiedValue, copy } = useCopyCommand();
@@ -571,6 +610,10 @@ export default function AgentsSettingsPage() {
savedAgentsByName={savedAgentsByName}
resolveDisplayName={resolveDisplayName}
resolveCapabilityStatus={resolveCapabilityStatus}
resolveRuntimeUpdate={resolveRuntimeUpdate}
installJobs={installJobs}
updateJobs={updateJobs}
handleUpdate={handleUpdate}
setTuiDialogOpen={setTuiDialogOpen}
handleRescan={handleRescan}
/>
@@ -0,0 +1,143 @@
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import type { ComponentType } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { InstalledAgentCard } from "./installed-agent-card";
const ManagedCard = InstalledAgentCard as ComponentType<Record<string, unknown>>;
const AGENT_NAME = "claude-acp";
const discoveryAgent = {
name: AGENT_NAME,
supports_mcp: true,
installation_paths: [],
available: true,
matched_path: "/usr/bin/npx",
};
const runtimeUpdate = {
supported: true,
package: "@agentclientprotocol/claude-agent-acp",
current_version: "1.0.0",
};
function renderCard(overrides: Record<string, unknown> = {}) {
const onUpdate = vi.fn();
render(
<ManagedCard
agent={discoveryAgent}
savedAgent={undefined}
displayName="Claude"
runtimeUpdate={runtimeUpdate}
onUpdate={onUpdate}
{...overrides}
/>,
);
return onUpdate;
}
afterEach(cleanup);
describe("AgentRuntimeUpdateControl", () => {
it("shows a labeled touch action only for managed installed agents", () => {
const onUpdate = renderCard();
const button = screen.getByRole("button", { name: "Update agent" });
expect(button.className).toContain("min-h-11");
fireEvent.click(button);
expect(onUpdate).toHaveBeenCalledWith(AGENT_NAME);
cleanup();
renderCard({ runtimeUpdate: undefined });
expect(screen.queryByRole("button", { name: "Update agent" })).toBeNull();
});
it("shows current to target progress and a bounded wrapping log", () => {
renderCard({
updateJob: {
job_id: "update-1",
agent_name: AGENT_NAME,
status: "updating",
current_version: "1.0.0",
target_version: "1.1.0",
output: "fetching package\n",
started_at: "2026-07-26T10:00:00Z",
},
});
expect(screen.getByText("1.0.0 → 1.1.0")).not.toBeNull();
expect(screen.getByText("Updating runtime…")).not.toBeNull();
const log = screen.getByTestId("agent-update-log-claude-acp");
expect(log.className).toContain("max-h-40");
expect(log.className).toContain("overflow-y-auto");
expect(log.className).toContain("break-words");
expect(screen.getByRole("button", { name: "Updating agent" }).hasAttribute("disabled")).toBe(
true,
);
});
it("distinguishes refresh warnings from retryable update failures", () => {
const { rerender } = render(
<ManagedCard
agent={discoveryAgent}
savedAgent={undefined}
displayName="Claude"
runtimeUpdate={runtimeUpdate}
onUpdate={vi.fn()}
updateJob={{
job_id: "update-1",
agent_name: AGENT_NAME,
status: "succeeded",
current_version: "1.0.0",
target_version: "1.1.0",
refresh_error: "Authentication required",
started_at: "2026-07-26T10:00:00Z",
}}
/>,
);
expect(
screen.getByText(/runtime updated, but capabilities could not be refreshed/i),
).not.toBeNull();
expect(screen.getByText(/authentication required/i)).not.toBeNull();
rerender(
<ManagedCard
agent={discoveryAgent}
savedAgent={undefined}
displayName="Claude"
runtimeUpdate={runtimeUpdate}
onUpdate={vi.fn()}
updateJob={{
job_id: "update-2",
agent_name: AGENT_NAME,
status: "failed",
current_version: "1.0.0",
error: "Registry unavailable",
started_at: "2026-07-26T10:01:00Z",
}}
/>,
);
expect(screen.getByText("Registry unavailable")).not.toBeNull();
expect(screen.getByRole("button", { name: "Retry update" }).hasAttribute("disabled")).toBe(
false,
);
});
it("disables updates while the same agent is installing", () => {
renderCard({
installJob: {
job_id: "install-1",
agent_name: AGENT_NAME,
status: "running",
started_at: "2026-07-26T10:00:00Z",
},
});
expect(screen.getByRole("button", { name: "Update agent" }).hasAttribute("disabled")).toBe(
true,
);
expect(screen.getByText("Agent installation is in progress.")).not.toBeNull();
});
});
@@ -0,0 +1,170 @@
"use client";
import { IconLoader2, IconRefresh } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import type { AgentUpdateJob, InstallJob } from "@/lib/api";
import type { RuntimeUpdate } from "@/lib/types/http";
const ACTIVE_UPDATE_STATUSES = new Set<AgentUpdateJob["status"]>([
"queued",
"resolving",
"updating",
"refreshing",
]);
function updatePhase(status: AgentUpdateJob["status"] | undefined): string | null {
switch (status) {
case "queued":
return "Update queued…";
case "resolving":
return "Checking latest version…";
case "updating":
return "Updating runtime…";
case "refreshing":
return "Refreshing models…";
default:
return null;
}
}
function updateButtonLabel(status: AgentUpdateJob["status"] | undefined) {
switch (status) {
case "queued":
return "Update queued";
case "resolving":
return "Resolving update";
case "updating":
return "Updating agent";
case "refreshing":
return "Refreshing agent capabilities";
case "failed":
return "Retry update";
default:
return "Update agent";
}
}
function VersionSummary({
runtimeUpdate,
job,
}: {
runtimeUpdate: RuntimeUpdate;
job?: AgentUpdateJob;
}) {
const current = job?.current_version || runtimeUpdate.current_version || "Unknown";
if (job?.target_version) {
return <p className="break-words font-mono text-xs">{`${current} → ${job.target_version}`}</p>;
}
if (job?.status === "resolving") {
return <p className="break-words font-mono text-xs">{`${current} → Checking latest…`}</p>;
}
return <p className="break-words text-xs text-muted-foreground">Current version: {current}</p>;
}
function UpdateResult({ agentName, job }: { agentName: string; job?: AgentUpdateJob }) {
if (!job) return null;
if (job.status === "succeeded" && job.refresh_error) {
return (
<p
className="break-words text-xs text-amber-600 dark:text-amber-400"
role="alert"
data-testid={`agent-update-result-${agentName}`}
>
Runtime updated, but capabilities could not be refreshed: {job.refresh_error}
</p>
);
}
if (job.status === "succeeded") {
return (
<p
className="break-words text-xs text-green-600 dark:text-green-400"
role="status"
data-testid={`agent-update-result-${agentName}`}
>
Runtime updated successfully.
</p>
);
}
if (job.status === "failed") {
return (
<p
className="break-words text-xs text-destructive"
role="alert"
data-testid={`agent-update-result-${agentName}`}
>
{job.error || "The runtime update failed."}
</p>
);
}
return null;
}
export function AgentRuntimeUpdateControl({
agentName,
runtimeUpdate,
job,
installJob,
onUpdate,
}: {
agentName: string;
runtimeUpdate: RuntimeUpdate;
job?: AgentUpdateJob;
installJob?: InstallJob;
onUpdate: (agentName: string) => void;
}) {
if (!runtimeUpdate.supported) return null;
const updateInFlight = Boolean(job && ACTIVE_UPDATE_STATUSES.has(job.status));
const installInFlight = installJob?.status === "queued" || installJob?.status === "running";
const disabled = updateInFlight || installInFlight;
const phase = updatePhase(job?.status);
const buttonLabel = updateButtonLabel(job?.status);
return (
<div className="min-w-0 space-y-2" data-testid={`agent-update-control-${agentName}`}>
<VersionSummary runtimeUpdate={runtimeUpdate} job={job} />
{phase && (
<p
className="flex items-center gap-1.5 text-xs text-muted-foreground"
role="status"
data-testid={`agent-update-phase-${agentName}`}
>
<IconLoader2 className="h-3.5 w-3.5 shrink-0 animate-spin" />
<span className="min-w-0 break-words">{phase}</span>
</p>
)}
{installInFlight && (
<p className="break-words text-xs text-muted-foreground">
Agent installation is in progress.
</p>
)}
{job?.output && (
<pre
data-testid={`agent-update-log-${agentName}`}
className="max-h-40 overflow-x-hidden overflow-y-auto whitespace-pre-wrap break-words rounded-md bg-muted px-2 py-1.5 font-mono text-xs text-muted-foreground"
>
{job.output}
</pre>
)}
<UpdateResult agentName={agentName} job={job} />
<Button
type="button"
variant="outline"
size="sm"
className="min-h-11 w-full cursor-pointer whitespace-normal"
disabled={disabled}
aria-label={buttonLabel}
onClick={() => onUpdate(agentName)}
data-testid={`agent-update-button-${agentName}`}
>
{updateInFlight ? (
<IconLoader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<IconRefresh className="mr-2 h-4 w-4" />
)}
{buttonLabel}
</Button>
</div>
);
}
@@ -9,8 +9,10 @@ import { Card, CardContent } from "@kandev/ui/card";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { AgentLogo } from "@/components/agent-logo";
import { AgentLoginDialog } from "@/components/settings/agent-login-dialog";
import { AgentRuntimeUpdateControl } from "@/components/settings/agent-runtime-update-control";
import { HostShellDialog } from "@/components/settings/host-shell-dialog";
import type { Agent, AgentDiscovery } from "@/lib/types/http";
import type { AgentUpdateJob, InstallJob } from "@/lib/api";
import type { Agent, AgentDiscovery, RuntimeUpdate } from "@/lib/types/http";
type Props = {
agent: AgentDiscovery;
@@ -18,6 +20,10 @@ type Props = {
displayName: string;
/** Capability status from the host utility probe ("ok", "auth_required", etc.). */
capabilityStatus?: string;
runtimeUpdate?: RuntimeUpdate;
updateJob?: AgentUpdateJob;
installJob?: InstallJob;
onUpdate?: (agentName: string) => void;
/**
* Called when the auth/shell dialog closes so the page can refresh
* discovery + availability. Without this the yellow lock stays put even
@@ -26,6 +32,75 @@ type Props = {
onAuthComplete?: () => void;
};
function InstalledAgentIdentity({
agent,
displayName,
configured,
probing,
authRequired,
loginAvailable,
onAuthClick,
}: {
agent: AgentDiscovery;
displayName: string;
configured: boolean;
probing: boolean;
authRequired: boolean;
loginAvailable: boolean;
onAuthClick: () => void;
}) {
return (
<div className="space-y-1">
<div className="flex min-w-0 flex-wrap items-center gap-2">
<AgentLogo agentName={agent.name} size={20} className="shrink-0" />
<h4 className="min-w-0 truncate font-medium">{displayName}</h4>
{agent.supports_mcp && <Badge variant="secondary">MCP</Badge>}
{configured && <Badge variant="outline">Configured</Badge>}
{probing && (
<Tooltip>
<TooltipTrigger asChild>
<span
data-testid={`probing-icon-${agent.name}`}
className="ml-auto flex items-center text-muted-foreground cursor-help"
aria-label="Checking authentication"
>
<IconLoader2 className="h-3.5 w-3.5 animate-spin" />
</span>
</TooltipTrigger>
<TooltipContent>Checking agent capabilities and authentication...</TooltipContent>
</Tooltip>
)}
{authRequired && (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={onAuthClick}
data-testid={`auth-icon-${agent.name}`}
className="ml-auto flex items-center gap-1 rounded-md px-1.5 py-0.5 text-xs text-amber-500 cursor-pointer hover:bg-amber-500/10"
aria-label="Authentication required"
>
<IconLock className="h-3.5 w-3.5" />
</button>
</TooltipTrigger>
<TooltipContent>
{loginAvailable
? "Authentication required - click to open login terminal"
: "Authentication required - click to open a shell and sign in"}
</TooltipContent>
</Tooltip>
)}
</div>
<p
className="text-xs text-muted-foreground line-clamp-2 min-h-[2rem]"
title={agent.matched_path ?? undefined}
>
{agent.matched_path ? `Detected at ${agent.matched_path}` : ""}
</p>
</div>
);
}
/**
* Card rendered under "Installed Agents" - links to the agent profile
* editor and surfaces a yellow lock icon when the capability probe reports
@@ -37,6 +112,10 @@ export function InstalledAgentCard({
savedAgent,
displayName,
capabilityStatus,
runtimeUpdate,
updateJob,
installJob,
onUpdate,
onAuthComplete,
}: Props) {
const configured = Boolean(savedAgent && savedAgent.profiles.length > 0);
@@ -56,57 +135,26 @@ export function InstalledAgentCard({
};
return (
<Card className="flex flex-col">
<CardContent className="py-4 flex flex-col gap-3 flex-1">
<div className="space-y-1">
<div className="flex items-center gap-2">
<AgentLogo agentName={agent.name} size={20} className="shrink-0" />
<h4 className="font-medium">{displayName}</h4>
{agent.supports_mcp && <Badge variant="secondary">MCP</Badge>}
{configured && <Badge variant="outline">Configured</Badge>}
{probing && (
<Tooltip>
<TooltipTrigger asChild>
<span
data-testid={`probing-icon-${agent.name}`}
className="ml-auto flex items-center text-muted-foreground cursor-help"
aria-label="Checking authentication"
>
<IconLoader2 className="h-3.5 w-3.5 animate-spin" />
</span>
</TooltipTrigger>
<TooltipContent>Checking agent capabilities and authentication...</TooltipContent>
</Tooltip>
)}
{authRequired && (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={handleAuthClick}
data-testid={`auth-icon-${agent.name}`}
className="ml-auto flex items-center gap-1 rounded-md px-1.5 py-0.5 text-xs text-amber-500 cursor-pointer hover:bg-amber-500/10"
aria-label="Authentication required"
>
<IconLock className="h-3.5 w-3.5" />
</button>
</TooltipTrigger>
<TooltipContent>
{loginAvailable
? "Authentication required - click to open login terminal"
: "Authentication required - click to open a shell and sign in"}
</TooltipContent>
</Tooltip>
)}
</div>
{/* Reserve two lines so cards align regardless of path length. */}
<p
className="text-xs text-muted-foreground line-clamp-2 min-h-[2rem]"
title={agent.matched_path ?? undefined}
>
{agent.matched_path ? `Detected at ${agent.matched_path}` : ""}
</p>
</div>
<Card className="flex min-w-0 flex-col">
<CardContent className="py-4 flex min-w-0 flex-col gap-3 flex-1">
<InstalledAgentIdentity
agent={agent}
displayName={displayName}
configured={configured}
probing={probing}
authRequired={authRequired}
loginAvailable={loginAvailable}
onAuthClick={handleAuthClick}
/>
{runtimeUpdate?.supported && onUpdate && (
<AgentRuntimeUpdateControl
agentName={agent.name}
runtimeUpdate={runtimeUpdate}
job={updateJob}
installJob={installJob}
onUpdate={onUpdate}
/>
)}
<Button size="sm" className="cursor-pointer mt-auto" asChild>
<Link
href={
@@ -0,0 +1,234 @@
import { expect, type Page, type WebSocketRoute } from "@playwright/test";
const AGENT_NAME = "claude-acp";
const NOW = "2026-07-26T12:00:00.000Z";
type UpdateStatus = "queued" | "resolving" | "updating" | "refreshing" | "succeeded" | "failed";
type UpdateJob = {
job_id: string;
agent_name: string;
status: UpdateStatus;
current_version?: string;
target_version?: string;
output?: string;
error?: string;
refresh_error?: string;
started_at: string;
finished_at?: string;
};
function catalogue(models: Array<{ id: string; name: string }>, displayName = "Claude") {
return {
agents: [
{
name: AGENT_NAME,
display_name: displayName,
description: "Claude ACP runtime",
supports_mcp: true,
installation_paths: ["claude-agent-acp"],
available: true,
matched_path: "/usr/local/bin/claude-agent-acp",
capabilities: {
supports_session_resume: true,
supports_shell: true,
supports_workspace_only: false,
},
model_config: {
default_model: models[0]?.id ?? "",
current_model_id: models[0]?.id,
available_models: models.map((model, index) => ({
...model,
description: `${model.name} model`,
is_default: index === 0,
source: "dynamic",
})),
supports_dynamic_models: true,
status: "ok",
},
runtime_update: {
supported: true,
package: "@agentclientprotocol/claude-agent-acp",
current_version: "0.62.0",
},
updated_at: NOW,
},
],
tools: [],
total: 1,
};
}
function discovery() {
return {
agents: [
{
name: AGENT_NAME,
supports_mcp: true,
installation_paths: ["claude-agent-acp"],
available: true,
matched_path: "/usr/local/bin/claude-agent-acp",
},
],
total: 1,
};
}
function savedAgents() {
return {
agents: [],
total: 0,
};
}
function event(action: string, payload: unknown) {
return JSON.stringify({
id: `runtime-update-${action}`,
type: "notification",
action,
payload,
});
}
export type RuntimeUpdateFixtureOptions = {
retainedJobs?: UpdateJob[];
postResponse?: UpdateJob;
};
export async function installRuntimeUpdateFixture(
page: Page,
options: RuntimeUpdateFixtureOptions = {},
) {
let currentModels = [{ id: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" }];
let retainedJobs = options.retainedJobs ?? [];
let postResponse: UpdateJob =
options.postResponse ??
({
job_id: "runtime-update-job-1",
agent_name: AGENT_NAME,
status: "resolving",
current_version: "0.62.0",
started_at: NOW,
} satisfies UpdateJob);
let postCount = 0;
let socket: WebSocketRoute | undefined;
let clientReady = false;
await page.route("**/api/v1/agents/discovery", (route) =>
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(discovery()),
}),
);
await page.route("**/api/v1/agents/available", (route) =>
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(catalogue(currentModels)),
}),
);
await page.route("**/api/v1/agents", (route) =>
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(savedAgents()),
}),
);
await page.route("**/api/v1/agent-update/**", (route) => {
const request = route.request();
const url = new URL(request.url());
if (request.method() === "GET" && url.pathname.endsWith("/agent-update/jobs")) {
return route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ jobs: retainedJobs }),
});
}
if (request.method() === "POST" && url.pathname.endsWith(`/agent-update/${AGENT_NAME}`)) {
postCount += 1;
return route.fulfill({
status: 202,
contentType: "application/json",
body: JSON.stringify(postResponse),
});
}
return route.fallback();
});
await page.route(`**/api/v1/agent-models/${AGENT_NAME}**`, (route) =>
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
agent_name: AGENT_NAME,
status: "ok",
models: currentModels.map((model, index) => ({
...model,
description: `${model.name} model`,
is_default: index === 0,
source: "dynamic",
})),
current_model_id: currentModels[0]?.id,
modes: [],
commands: [],
error: null,
}),
}),
);
await page.routeWebSocket(/\/ws$/, (ws) => {
socket = ws;
const server = ws.connectToServer();
ws.onMessage((message) => {
clientReady = true;
server.send(message);
});
server.onMessage((message) => ws.send(message));
});
return {
agentName: AGENT_NAME,
setRetainedJobs(jobs: UpdateJob[]) {
retainedJobs = jobs;
},
setPostResponse(job: UpdateJob) {
postResponse = job;
},
postCount: () => postCount,
async emit(action: string, payload: unknown) {
await expect.poll(() => Boolean(socket)).toBe(true);
await expect.poll(() => clientReady).toBe(true);
socket?.send(event(action, payload));
},
async emitUpdate(job: UpdateJob) {
const action =
job.status === "succeeded" || job.status === "failed"
? "agent.update.finished"
: "agent.update.started";
await this.emit(action, job);
},
async emitOutput(chunk: string) {
await this.emit("agent.update.output", {
job_id: "runtime-update-job-1",
agent_name: AGENT_NAME,
chunk,
});
},
async emitCatalogue(models: Array<{ id: string; name: string }>) {
currentModels = models;
await this.emit("agent.available.updated", catalogue(models, "Claude refreshed"));
},
};
}
export function updateJob(overrides: Partial<UpdateJob> = {}): UpdateJob {
return {
job_id: "runtime-update-job-1",
agent_name: AGENT_NAME,
status: "updating",
current_version: "0.62.0",
target_version: "0.63.0",
output: "Downloading @agentclientprotocol/claude-agent-acp…\n",
started_at: NOW,
...overrides,
};
}
@@ -0,0 +1,91 @@
import { test, expect } from "../../fixtures/test-base";
import { installRuntimeUpdateFixture, updateJob } from "./agent-runtime-update-helpers";
test.describe("managed agent runtime updates", () => {
test("streams a successful update and renders refreshed models without a document reload", async ({
testPage,
}) => {
const runtime = await installRuntimeUpdateFixture(testPage);
let documentNavigations = 0;
testPage.on("framenavigated", (frame) => {
if (frame === testPage.mainFrame()) documentNavigations += 1;
});
await testPage.goto("/settings/agents");
const navigationsAfterLoad = documentNavigations;
const control = testPage.getByTestId(`agent-update-control-${runtime.agentName}`);
await expect(control).toBeVisible();
await expect(control).toContainText("Current version: 0.62.0");
await testPage.getByTestId(`agent-update-button-${runtime.agentName}`).click();
expect(runtime.postCount()).toBe(1);
await expect(testPage.getByTestId(`agent-update-phase-${runtime.agentName}`)).toContainText(
"Checking latest version",
);
await runtime.emitUpdate(updateJob());
await runtime.emitOutput("Installed @agentclientprotocol/claude-agent-acp@0.63.0\n");
await expect(testPage.getByTestId(`agent-update-phase-${runtime.agentName}`)).toContainText(
"Updating runtime",
);
await expect(testPage.getByTestId(`agent-update-log-${runtime.agentName}`)).toContainText(
"Installed @agentclientprotocol/claude-agent-acp@0.63.0",
);
await expect(control).toContainText("0.62.0 → 0.63.0");
await runtime.emitUpdate(
updateJob({
status: "succeeded",
output: "Installed @agentclientprotocol/claude-agent-acp@0.63.0\n",
finished_at: "2026-07-26T12:01:00.000Z",
}),
);
await runtime.emitCatalogue([
{ id: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" },
{ id: "claude-opus-5", name: "Claude Opus 5" },
]);
await expect(testPage.getByText("Claude refreshed", { exact: true })).toBeVisible();
await expect(testPage.getByTestId(`agent-update-result-${runtime.agentName}`)).toContainText(
"Runtime updated successfully",
);
expect(documentNavigations).toBe(navigationsAfterLoad);
await testPage.getByRole("link", { name: "Setup Profile" }).click();
await expect(testPage).toHaveURL(/\/settings\/agents\/claude-acp$/);
await expect(testPage.getByRole("heading", { name: "Claude" })).toBeVisible();
const modelPicker = testPage.getByRole("button", { name: "Profile start model settings" });
await expect(modelPicker).toBeVisible();
await modelPicker.click();
await expect(testPage.getByText("Claude Opus 5", { exact: true })).toBeVisible();
});
test("rehydrates a retained failure and lets the operator retry it", async ({ testPage }) => {
const runtime = await installRuntimeUpdateFixture(testPage, {
retainedJobs: [
updateJob({
status: "failed",
error: "Registry lookup failed",
finished_at: "2026-07-26T12:01:00.000Z",
}),
],
postResponse: updateJob({
job_id: "runtime-update-job-2",
status: "resolving",
target_version: undefined,
started_at: "2026-07-26T12:02:00.000Z",
}),
});
await testPage.goto("/settings/agents");
await expect(testPage.getByTestId(`agent-update-result-${runtime.agentName}`)).toContainText(
"Registry lookup failed",
);
const retry = testPage.getByTestId(`agent-update-button-${runtime.agentName}`);
await expect(retry).toHaveText("Retry update");
await retry.click();
expect(runtime.postCount()).toBe(1);
await expect(testPage.getByTestId(`agent-update-phase-${runtime.agentName}`)).toContainText(
"Checking latest version",
);
});
});
@@ -0,0 +1,56 @@
import { test, expect } from "../../fixtures/test-base";
import { installRuntimeUpdateFixture, updateJob } from "./agent-runtime-update-helpers";
test.describe("managed agent runtime updates on mobile", () => {
test("keeps progress, bounded output, and retry touch-reachable without horizontal overflow", async ({
testPage,
}) => {
const runtime = await installRuntimeUpdateFixture(testPage, {
retainedJobs: [
updateJob({
output: Array.from(
{ length: 60 },
(_, index) => `Downloading runtime chunk ${index + 1} for the latest agent package`,
).join("\n"),
}),
],
});
await testPage.goto("/settings/agents");
const control = testPage.getByTestId(`agent-update-control-${runtime.agentName}`);
const log = testPage.getByTestId(`agent-update-log-${runtime.agentName}`);
const button = testPage.getByTestId(`agent-update-button-${runtime.agentName}`);
await control.scrollIntoViewIfNeeded();
await expect(control).toContainText("0.62.0 → 0.63.0");
await expect(testPage.getByTestId(`agent-update-phase-${runtime.agentName}`)).toContainText(
"Updating runtime",
);
await expect(log).toBeInViewport({ ratio: 1 });
await expect(
log.evaluate((element) => element.scrollHeight > element.clientHeight),
).resolves.toBe(true);
await expect(button).toBeInViewport({ ratio: 1 });
const runningButtonBox = await button.boundingBox();
expect(runningButtonBox).not.toBeNull();
expect(runningButtonBox!.height).toBeGreaterThanOrEqual(44);
await expect(testPage.locator("html")).toHaveJSProperty(
"scrollWidth",
await testPage.locator("html").evaluate((element) => element.clientWidth),
);
await runtime.emitUpdate(
updateJob({
status: "failed",
error: "Registry lookup failed",
finished_at: "2026-07-26T12:01:00.000Z",
}),
);
const result = testPage.getByTestId(`agent-update-result-${runtime.agentName}`);
await result.scrollIntoViewIfNeeded();
await expect(result).toContainText("Registry lookup failed");
await expect(button).toHaveText("Retry update");
await button.tap();
expect(runtime.postCount()).toBe(1);
});
});
@@ -0,0 +1,90 @@
"use client";
import { useCallback, useEffect } from "react";
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
import { getAgentUpdateJob, getInstallJob, listAgentUpdateJobs, updateAgent } from "@/lib/api";
import { ApiError } from "@/lib/api/client";
type MaintenanceConflict = {
active_job_id: string;
active_kind: "install" | "update";
};
function maintenanceConflict(error: unknown): MaintenanceConflict | null {
if (!(error instanceof ApiError) || error.status !== 409) return null;
if (!error.body || typeof error.body !== "object") return null;
const body = error.body as Record<string, unknown>;
if (typeof body.active_job_id !== "string") return null;
if (body.active_kind !== "install" && body.active_kind !== "update") return null;
return {
active_job_id: body.active_job_id,
active_kind: body.active_kind,
};
}
export function useAgentRuntimeUpdates() {
const store = useAppStoreApi();
const updateJobs = useAppStore((state) => state.updateJobs.byAgent);
useEffect(() => {
let cancelled = false;
listAgentUpdateJobs({ cache: "no-store" })
.then((response) => {
if (cancelled) return;
for (const job of response.jobs) {
store.getState().upsertAgentUpdateJob(job);
}
})
.catch(() => {
// Retained jobs are an enhancement; live WebSocket events still populate state.
});
return () => {
cancelled = true;
};
}, [store]);
const hydrateConflict = useCallback(
async (agentName: string, conflict: MaintenanceConflict) => {
if (conflict.active_kind === "update") {
const job = await getAgentUpdateJob(conflict.active_job_id, { cache: "no-store" });
store.getState().upsertAgentUpdateJob(job);
return;
}
const job = await getInstallJob(conflict.active_job_id, { cache: "no-store" });
store.getState().upsertInstallJob(job.agent_name ? job : { ...job, agent_name: agentName });
},
[store],
);
const handleUpdate = useCallback(
async (agentName: string) => {
try {
const job = await updateAgent(agentName);
store.getState().upsertAgentUpdateJob(job);
} catch (error) {
const conflict = maintenanceConflict(error);
if (conflict) {
try {
await hydrateConflict(agentName, conflict);
return;
} catch {
// Surface a retryable error below if the retained conflict job vanished.
}
}
const current = store.getState().updateJobs.byAgent[agentName];
if (current && !["succeeded", "failed"].includes(current.status)) return;
store.getState().upsertAgentUpdateJob({
job_id: `local-error-${agentName}-${Date.now()}`,
agent_name: agentName,
status: "failed",
error: error instanceof Error ? error.message : String(error),
started_at: new Date().toISOString(),
});
}
},
[hydrateConflict, store],
);
return { updateJobs, handleUpdate };
}
@@ -0,0 +1,45 @@
import { fetchJson, type ApiRequestOptions } from "../client";
export type AgentUpdateJobStatus =
| "queued"
| "resolving"
| "updating"
| "refreshing"
| "succeeded"
| "failed";
export type AgentUpdateJob = {
job_id: string;
agent_name: string;
status: AgentUpdateJobStatus;
current_version?: string;
target_version?: string;
output?: string;
error?: string;
refresh_error?: string;
started_at: string;
finished_at?: string;
};
export async function updateAgent(
agentName: string,
options?: ApiRequestOptions,
): Promise<AgentUpdateJob> {
return fetchJson<AgentUpdateJob>(`/api/v1/agent-update/${agentName}`, {
...options,
init: { method: "POST", ...(options?.init ?? {}) },
});
}
export async function listAgentUpdateJobs(
options?: ApiRequestOptions,
): Promise<{ jobs: AgentUpdateJob[] }> {
return fetchJson<{ jobs: AgentUpdateJob[] }>("/api/v1/agent-update/jobs", options);
}
export async function getAgentUpdateJob(
jobId: string,
options?: ApiRequestOptions,
): Promise<AgentUpdateJob> {
return fetchJson<AgentUpdateJob>(`/api/v1/agent-update/jobs/${jobId}`, options);
}
+1
View File
@@ -6,6 +6,7 @@ export * from "./domains/kanban-api";
export * from "./domains/session-api";
export * from "./domains/workspace-api";
export * from "./domains/settings-api";
export * from "./domains/agent-update-api";
export * from "./domains/process-api";
export * from "./domains/workflow-api";
export * from "./domains/workflow-sync-api";
@@ -0,0 +1,111 @@
import { describe, expect, it } from "vitest";
import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
import { createSettingsSlice } from "./settings-slice";
import type { SettingsSlice } from "./types";
function makeStore() {
return create<SettingsSlice>()(immer((set, get, store) => createSettingsSlice(set, get, store)));
}
function updateJob(overrides: Record<string, unknown> = {}) {
return {
job_id: "update-1",
agent_name: "claude-acp",
status: "updating",
current_version: "1.0.0",
target_version: "1.1.0",
output: "",
started_at: "2026-07-26T10:00:00Z",
...overrides,
};
}
describe("settings update jobs", () => {
it("rehydrates the newest retained job for each agent", () => {
const store = makeStore();
const actions = store.getState() as SettingsSlice & {
setAgentUpdateJobs: (jobs: ReturnType<typeof updateJob>[]) => void;
};
actions.setAgentUpdateJobs([
updateJob({ job_id: "older", started_at: "2026-07-26T10:00:00Z" }),
updateJob({ job_id: "newer", started_at: "2026-07-26T10:01:00Z" }),
]);
expect(
(store.getState() as SettingsSlice & { updateJobs: { byAgent: Record<string, unknown> } })
.updateJobs.byAgent["claude-acp"],
).toMatchObject({ job_id: "newer" });
});
it("does not let an older HTTP snapshot clobber newer websocket output", () => {
const store = makeStore();
const actions = store.getState() as SettingsSlice & {
upsertAgentUpdateJob: (job: ReturnType<typeof updateJob>) => void;
appendAgentUpdateOutput: (agentName: string, jobId: string, chunk: string) => void;
};
actions.upsertAgentUpdateJob(updateJob({ output: "downloaded\n" }));
actions.appendAgentUpdateOutput("claude-acp", "update-1", "refreshed\n");
actions.upsertAgentUpdateJob(updateJob({ status: "refreshing", output: "downloaded\n" }));
expect(
(
store.getState() as SettingsSlice & {
updateJobs: { byAgent: Record<string, { output?: string; status: string }> };
}
).updateJobs.byAgent["claude-acp"],
).toMatchObject({
output: "downloaded\nrefreshed\n",
status: "refreshing",
});
});
it("drops stale job events after a retry starts", () => {
const store = makeStore();
const actions = store.getState() as SettingsSlice & {
upsertAgentUpdateJob: (job: ReturnType<typeof updateJob>) => void;
};
actions.upsertAgentUpdateJob(
updateJob({ job_id: "retry", started_at: "2026-07-26T10:02:00Z" }),
);
actions.upsertAgentUpdateJob(
updateJob({
job_id: "original",
status: "failed",
started_at: "2026-07-26T10:00:00Z",
}),
);
expect(
(
store.getState() as SettingsSlice & {
updateJobs: { byAgent: Record<string, { job_id: string }> };
}
).updateJobs.byAgent["claude-acp"].job_id,
).toBe("retry");
});
it("keeps only the newest 64 KiB of streamed output", () => {
const store = makeStore();
const actions = store.getState() as SettingsSlice & {
upsertAgentUpdateJob: (job: ReturnType<typeof updateJob>) => void;
appendAgentUpdateOutput: (agentName: string, jobId: string, chunk: string) => void;
};
actions.upsertAgentUpdateJob(updateJob());
actions.appendAgentUpdateOutput("claude-acp", "update-1", `old${"x".repeat(64 * 1024)}tail`);
const output = (
store.getState() as SettingsSlice & {
updateJobs: { byAgent: Record<string, { output: string }> };
}
).updateJobs.byAgent["claude-acp"].output;
expect(output).toHaveLength(64 * 1024);
expect(output.endsWith("tail")).toBe(true);
expect(output.startsWith("old")).toBe(false);
});
});
@@ -9,6 +9,7 @@ export const defaultSettingsState: SettingsSliceState = {
availableAgents: { items: [], tools: [], loading: false, loaded: false },
agentProfiles: { items: [], version: 0 },
installJobs: { byAgent: {} },
updateJobs: { byAgent: {} },
editors: { items: [], loaded: false, loading: false },
prompts: { items: [], loaded: false, loading: false },
secrets: { items: [], loaded: false, loading: false },
@@ -76,6 +77,8 @@ type ImmerSet = Parameters<
StateCreator<SettingsSlice, [["zustand/immer", never]], [], SettingsSlice>
>[0];
const JOB_OUTPUT_MAX = 64 * 1024;
// installJobStartedAtMs parses started_at to epoch ms so we compare on time,
// not lexicographically. RFC3339 strings with variable fractional seconds
// would otherwise misorder ("2026-05-11T10:00:00Z" sorts after
@@ -123,8 +126,8 @@ function createInstallJobActions(
if (!current) return;
const next = (current.output ?? "") + chunk;
// Cap at 64KB; drop oldest chars on overflow so the live tail stays current.
const max = 64 * 1024;
current.output = next.length > max ? next.slice(next.length - max) : next;
current.output =
next.length > JOB_OUTPUT_MAX ? next.slice(next.length - JOB_OUTPUT_MAX) : next;
}),
clearInstallJob: (agentName) =>
set((draft) => {
@@ -133,6 +136,83 @@ function createInstallJobActions(
};
}
function updateStatusRank(status: string): number {
switch (status) {
case "queued":
return 0;
case "resolving":
return 1;
case "updating":
return 2;
case "refreshing":
return 3;
case "succeeded":
case "failed":
return 4;
default:
return -1;
}
}
function mergeJobOutput(current: string | undefined, incoming: string | undefined) {
if (!current) return incoming;
if (!incoming || current === incoming || current.startsWith(incoming)) return current;
if (incoming.startsWith(current)) return incoming;
return incoming.length >= current.length ? incoming : current;
}
function createAgentUpdateJobActions(
set: ImmerSet,
): Pick<
SettingsSlice,
"setAgentUpdateJobs" | "upsertAgentUpdateJob" | "appendAgentUpdateOutput" | "clearAgentUpdateJob"
> {
return {
setAgentUpdateJobs: (jobs) =>
set((draft) => {
const byAgent: Record<string, (typeof jobs)[number]> = {};
for (const job of jobs) {
const current = byAgent[job.agent_name];
if (!current || installJobStartedAtMs(job) > installJobStartedAtMs(current)) {
byAgent[job.agent_name] = job;
}
}
draft.updateJobs.byAgent = byAgent;
}),
upsertAgentUpdateJob: (job) =>
set((draft) => {
const current = draft.updateJobs.byAgent[job.agent_name];
if (
current &&
current.job_id !== job.job_id &&
installJobStartedAtMs(current) > installJobStartedAtMs(job)
) {
return;
}
if (!current || current.job_id !== job.job_id) {
draft.updateJobs.byAgent[job.agent_name] = job;
return;
}
const incomingIsNewer = updateStatusRank(job.status) >= updateStatusRank(current.status);
const merged = incomingIsNewer ? { ...current, ...job } : { ...job, ...current };
merged.output = mergeJobOutput(current.output, job.output);
draft.updateJobs.byAgent[job.agent_name] = merged;
}),
appendAgentUpdateOutput: (agentName, jobId, chunk) =>
set((draft) => {
const current = draft.updateJobs.byAgent[agentName];
if (!current || current.job_id !== jobId) return;
const next = (current.output ?? "") + chunk;
current.output =
next.length > JOB_OUTPUT_MAX ? next.slice(next.length - JOB_OUTPUT_MAX) : next;
}),
clearAgentUpdateJob: (agentName) =>
set((draft) => {
delete draft.updateJobs.byAgent[agentName];
}),
};
}
function createCoreActions(
set: ImmerSet,
): Pick<
@@ -303,5 +383,6 @@ export const createSettingsSlice: StateCreator<
...defaultSettingsState,
...createCoreActions(set),
...createInstallJobActions(set),
...createAgentUpdateJobActions(set),
...createSecretAndSpriteActions(set),
});
@@ -102,6 +102,31 @@ export type InstallJobsState = {
byAgent: Record<string, InstallJob>;
};
export type AgentUpdateJobStatus =
| "queued"
| "resolving"
| "updating"
| "refreshing"
| "succeeded"
| "failed";
export type AgentUpdateJob = {
job_id: string;
agent_name: string;
status: AgentUpdateJobStatus;
current_version?: string;
target_version?: string;
output?: string;
error?: string;
refresh_error?: string;
started_at: string;
finished_at?: string;
};
export type AgentUpdateJobsState = {
byAgent: Record<string, AgentUpdateJob>;
};
export type EditorsState = {
items: EditorOption[];
loaded: boolean;
@@ -223,6 +248,7 @@ export type SettingsSliceState = {
availableAgents: AvailableAgentsState;
agentProfiles: AgentProfilesState;
installJobs: InstallJobsState;
updateJobs: AgentUpdateJobsState;
editors: EditorsState;
prompts: PromptsState;
secrets: SecretsState;
@@ -247,6 +273,10 @@ export type SettingsSliceActions = {
upsertInstallJob: (job: InstallJob) => void;
appendInstallOutput: (agentName: string, chunk: string) => void;
clearInstallJob: (agentName: string) => void;
setAgentUpdateJobs: (jobs: AgentUpdateJob[]) => void;
upsertAgentUpdateJob: (job: AgentUpdateJob) => void;
appendAgentUpdateOutput: (agentName: string, jobId: string, chunk: string) => void;
clearAgentUpdateJob: (agentName: string) => void;
setEditors: (editors: EditorsState["items"]) => void;
setEditorsLoading: (loading: boolean) => void;
setPrompts: (prompts: PromptsState["items"]) => void;
+8 -2
View File
@@ -13,6 +13,7 @@ import type {
import type { SystemHealthResponse } from "@/lib/types/health";
import type { UISliceActions as UIA } from "./slices/ui/types";
import type * as UISliceTypes from "./slices/ui/types";
import type { AgentUpdateJob, InstallJob } from "./slices/settings/types";
import { mergeInitialState } from "./default-state";
import { buildStateOverrides } from "./store-overrides";
import {
@@ -117,6 +118,7 @@ export type AppState = KanbanSlice & {
availableAgents: (typeof defaultSettingsState)["availableAgents"];
agentProfiles: (typeof defaultSettingsState)["agentProfiles"];
installJobs: (typeof defaultSettingsState)["installJobs"];
updateJobs: (typeof defaultSettingsState)["updateJobs"];
editors: (typeof defaultSettingsState)["editors"];
prompts: (typeof defaultSettingsState)["prompts"];
secrets: (typeof defaultSettingsState)["secrets"];
@@ -249,10 +251,14 @@ export type AppState = KanbanSlice & {
) => void;
setAvailableAgentsLoading: (loading: boolean) => void;
setAgentProfiles: (profiles: AgentProfilesState["items"]) => void;
setInstallJobs: (jobs: import("@/lib/state/slices/settings/types").InstallJob[]) => void;
upsertInstallJob: (job: import("@/lib/state/slices/settings/types").InstallJob) => void;
setInstallJobs: (jobs: InstallJob[]) => void;
upsertInstallJob: (job: InstallJob) => void;
appendInstallOutput: (agentName: string, chunk: string) => void;
clearInstallJob: (agentName: string) => void;
setAgentUpdateJobs: (jobs: AgentUpdateJob[]) => void;
upsertAgentUpdateJob: (job: AgentUpdateJob) => void;
appendAgentUpdateOutput: (agentName: string, jobId: string, chunk: string) => void;
clearAgentUpdateJob: (agentName: string) => void;
setRepositories: (workspaceId: string, repositories: Repository[]) => void;
upsertRepository: (workspaceId: string, repository: Repository) => void;
setRepositoriesLoading: (workspaceId: string, loading: boolean) => void;
+22
View File
@@ -134,6 +134,25 @@ export type AgentInstallOutputPayload = {
chunk: string;
};
export type AgentUpdateJobPayload = {
job_id: string;
agent_name: string;
status: "queued" | "resolving" | "updating" | "refreshing" | "succeeded" | "failed";
current_version?: string;
target_version?: string;
output?: string;
error?: string;
refresh_error?: string;
started_at: string;
finished_at?: string;
};
export type AgentUpdateOutputPayload = {
job_id: string;
agent_name: string;
chunk: string;
};
export type TerminalOutputPayload = {
terminalId: string;
data: string;
@@ -510,6 +529,9 @@ export type BackendMessageMap = OfficeBackendMessageMap &
"agent.install.started": BackendMessage<"agent.install.started", AgentInstallJobPayload>;
"agent.install.output": BackendMessage<"agent.install.output", AgentInstallOutputPayload>;
"agent.install.finished": BackendMessage<"agent.install.finished", AgentInstallJobPayload>;
"agent.update.started": BackendMessage<"agent.update.started", AgentUpdateJobPayload>;
"agent.update.output": BackendMessage<"agent.update.output", AgentUpdateOutputPayload>;
"agent.update.finished": BackendMessage<"agent.update.finished", AgentUpdateJobPayload>;
"terminal.output": BackendMessage<"terminal.output", TerminalOutputPayload>;
"diff.update": BackendMessage<"diff.update", DiffUpdatePayload>;
"session.git.event": BackendMessage<"session.git.event", GitEventPayload>;
+7
View File
@@ -198,6 +198,12 @@ export type LoginCommand = {
description?: string;
};
export type RuntimeUpdate = {
supported: boolean;
package: string;
current_version?: string;
};
export type AvailableAgent = {
name: string;
display_name: string;
@@ -213,6 +219,7 @@ export type AvailableAgent = {
permission_settings?: Record<string, PermissionSetting>;
passthrough_config?: PassthroughConfig;
login_command?: LoginCommand;
runtime_update?: RuntimeUpdate;
updated_at: string;
};
+66
View File
@@ -0,0 +1,66 @@
import { describe, expect, it } from "vitest";
import { create, type StoreApi } from "zustand";
import { immer } from "zustand/middleware/immer";
import { createSettingsSlice } from "@/lib/state/slices/settings/settings-slice";
import type { SettingsSlice } from "@/lib/state/slices/settings/types";
import type { AppState } from "@/lib/state/store";
import { registerAgentsHandlers } from "./agents";
function makeStore() {
return create<SettingsSlice>()(
immer((set, get, store) => createSettingsSlice(set, get, store)),
) as unknown as StoreApi<AppState>;
}
function message(action: string, payload: unknown) {
return {
id: `message-${action}`,
type: "notification",
action,
timestamp: "2026-07-26T10:00:00Z",
payload,
};
}
describe("agent runtime update websocket handlers", () => {
it("upserts update snapshots and appends each output chunk once", () => {
const store = makeStore();
const handlers = registerAgentsHandlers(store) as unknown as Record<
string,
(event: ReturnType<typeof message>) => void
>;
const snapshot = {
job_id: "update-1",
agent_name: "claude-acp",
status: "updating",
current_version: "1.0.0",
target_version: "1.1.0",
started_at: "2026-07-26T10:00:00Z",
};
handlers["agent.update.started"](message("agent.update.started", snapshot));
handlers["agent.update.output"](
message("agent.update.output", {
job_id: "update-1",
agent_name: "claude-acp",
chunk: "downloaded\n",
}),
);
handlers["agent.update.finished"](
message("agent.update.finished", {
...snapshot,
status: "succeeded",
output: "downloaded\n",
}),
);
expect(
(
store.getState() as unknown as {
updateJobs: { byAgent: Record<string, { status: string; output: string }> };
}
).updateJobs.byAgent["claude-acp"],
).toMatchObject({ status: "succeeded", output: "downloaded\n" });
});
});
+10
View File
@@ -90,6 +90,16 @@ export function registerAgentsHandlers(store: StoreApi<AppState>): WsHandlers {
"agent.install.finished": (message) => {
store.getState().upsertInstallJob(message.payload);
},
"agent.update.started": (message) => {
store.getState().upsertAgentUpdateJob(message.payload);
},
"agent.update.output": (message) => {
const { agent_name, job_id, chunk } = message.payload;
store.getState().appendAgentUpdateOutput(agent_name, job_id, chunk);
},
"agent.update.finished": (message) => {
store.getState().upsertAgentUpdateJob(message.payload);
},
"agent.updated": (message) => {
store.setState((state) => ({
...state,
@@ -1,6 +1,6 @@
# 0034: Agent Client Protocol Codex ACP Bridge
**Status:** accepted
**Status:** accepted (amended 2026-07-26)
**Date:** 2026-07-10
**Area:** backend, protocol
@@ -10,9 +10,18 @@ Kandev's `codex-acp` agent previously launched `@zed-industries/codex-acp`. That
## Decision
Kandev's `codex-acp` agent launches `npx -y @agentclientprotocol/codex-acp@1.1.5` for ACP chat and one-shot inference sessions. The install script still installs `@openai/codex` for `codex login`, then installs the same pinned ACP bridge package for Kandev sessions.
Kandev's `codex-acp` agent launches the unversioned
`@agentclientprotocol/codex-acp` package for ACP chat and one-shot inference
sessions. Normal launches prefer npm's execution cache. The install script
still installs `@openai/codex` for `codex login`; that native authentication
helper is separate from the managed ACP runtime.
No product spec update is required: the user-facing agent remains `codex-acp`; only the package that supplies the ACP bridge changes.
The host operator can deliberately refresh the ACP package through
**Settings > Agents > Update agent**. Kandev then re-probes the bridge and
replaces the advertised model and configuration catalogue for future
sessions. The shared runtime-management boundary is recorded in
[ADR-2026-07-26](2026-07-26-user-managed-agent-runtime-updates.md) and the
[managed runtime update spec](../specs/agents/runtime-updates.md).
## Consequences
@@ -20,6 +29,11 @@ Codex ACP sessions receive the model catalogue and config options from the Agent
Codex-specific ACP `cli_flags` are not advertised because the bridge entrypoint does not apply the native Codex `-c` config overrides to chat sessions. Kandev still exposes the universal agentctl auto-approve toggle for ACP permission requests and keeps native Codex flags scoped to passthrough mode.
Kandev source no longer determines the exact bridge release. Incident
diagnosis uses the version reported during ACP initialization. Compatibility
is enforced through ACP protocol negotiation and advertised capabilities, so
an upstream same-protocol regression can still require operator intervention.
## Alternatives Considered
- Keep relying on `@zed-industries/codex-acp` and assume npm or local symlinks redirect it. Rejected because Kandev should declare the package it intends to execute and not depend on external aliasing.
@@ -0,0 +1,74 @@
# ADR-2026-07-26-user-managed-agent-runtime-updates: User-Managed Agent Runtime Updates
**Status:** accepted
**Date:** 2026-07-26
**Area:** backend, frontend, protocol
## Context
Kandev launches core ACP agents from npm-distributed runtimes. Exact
repository pins make launches reproducible, but delay upstream models and
capabilities until Kandev reviews, merges, and deploys a dependency update.
Unconditionally resolving `latest` on every launch removes that delay but adds
registry work and makes change timing invisible to the operator.
npm provides an execution cache that can satisfy unversioned package
invocations, but documents it as a best-effort cache rather than durable
installation state. ACP separately exposes a negotiated protocol version and
runtime-advertised capabilities during initialization.
## Decision
Kandev does not maintain exact package-version pins for its managed npm agent
runtimes. Normal launches identify the package without a version or an
explicit `latest` tag and may reuse npm's execution cache.
The install operator owns runtime advancement through a Settings action.
Kandev resolves the current and upstream target versions, executes only the
built-in package update recipe, streams progress, and re-probes the host
runtime after success. Update actions affect future probes and launches; they
never replace an active session.
ACP protocol negotiation, normalized capability discovery, and the existing
per-agent compatibility dialects are the compatibility boundary. Kandev
accepts the risk that an upstream package can contain a behavioral regression
without changing its ACP protocol version. It surfaces initialization or probe
failures and does not silently roll back to a repository-pinned runtime.
The first managed set is Claude, Codex, OpenCode, Copilot, and Gemini. The
Settings action targets the Kandev host runtime only. Remote executors and
containers use their own unversioned runtime resolution when they launch.
Native-only distribution channels and separately distributed passthrough or
authentication helper packages remain outside this boundary.
## Consequences
Operators can opt into newly released models without waiting for a Kandev
release, while ordinary launches can benefit from npm cache reuse. The UI can
attribute an update to a visible current and target version and immediately
show newly advertised models and modes.
Launches are no longer reproducible by Kandev commit alone. An npm cache
eviction, executor rebuild, or fresh machine may resolve a newer runtime even
without an explicit Settings update. Incident diagnosis must therefore record
the runtime-reported agent version rather than infer it from source.
Compatibility depends on upstream ACP discipline and Kandev's dialect layer.
A package can regress while retaining the same protocol version, and the first
operator to update may encounter that regression. Rollback and version
selection are deliberately not provided in this iteration.
## Alternatives Considered
- Exact repository pins with scheduled update pull requests were rejected
because model availability remains coupled to Kandev's review and deployment
cadence.
- Resolving `latest` on every launch was rejected because it adds repeated
registry work and makes runtime changes happen without an explicit operator
action when npm cache metadata becomes stale.
- A Kandev-owned package installation directory and lockfile were rejected for
this iteration because it recreates a package manager and durable version
inventory beyond the requested best-effort npm cache behavior.
- Updating every configured executor from the host Settings page was rejected
because remote credentials, platform differences, partial failure, and
executor ownership require a separate product contract.
+2 -1
View File
@@ -39,7 +39,7 @@ Read individual ADRs for full context. Create new ones via `/record decision` or
| 0031 | [Office skill reference files](0031-office-skill-reference-files.md) | accepted | backend | 2026-07-06 |
| 0032 | [Configurable worktree branch names](0032-configurable-worktree-branch-names.md) | accepted | backend, frontend | 2026-07-07 |
| 0033 | [Durable plan implementation start marker](0033-durable-plan-implementation-start.md) | accepted | backend, frontend | 2026-07-09 |
| 0034 | [Agent Client Protocol Codex ACP Bridge](0034-agentclientprotocol-codex-acp.md) | accepted | backend, protocol | 2026-07-10 |
| 0034 | [Agent Client Protocol Codex ACP Bridge](0034-agentclientprotocol-codex-acp.md) | accepted (amended 2026-07-25) | backend, protocol | 2026-07-10 |
| 0035 | [Version AgentReady events by prompt generation](0035-version-agent-ready-events-by-prompt-generation.md) | accepted | backend | 2026-07-14 |
| 0036 | [Normalize ACP shell output at the adapter boundary](0036-normalize-acp-shell-output-at-adapter-boundary.md) | accepted | backend, frontend, protocol | 2026-07-14 |
| 0037 | [Resource-aware frontend unit tests](0037-resource-aware-frontend-unit-tests.md) | accepted | frontend, infra | 2026-07-14 |
@@ -78,4 +78,5 @@ Read individual ADRs for full context. Create new ones via `/record decision` or
| 2026-07-22-runtime-mutable-task-workspace-sources | [Runtime-Mutable Task Workspace Sources](2026-07-22-runtime-mutable-task-workspace-sources.md) | accepted | backend, frontend, protocol | 2026-07-22 |
| 2026-07-24-opt-in-authentication | [Opt-in Authentication and Per-User Workspace Scoping](2026-07-24-opt-in-authentication.md) | accepted | backend, frontend, protocol, security | 2026-07-24 |
| 2026-07-24-semantic-notification-events | [Semantic notification events come from domain occurrences](2026-07-24-semantic-notification-events.md) | accepted | backend, frontend, desktop | 2026-07-24 |
| 2026-07-26-user-managed-agent-runtime-updates | [User-Managed Agent Runtime Updates](2026-07-26-user-managed-agent-runtime-updates.md) | accepted | backend, frontend, protocol | 2026-07-26 |
| 2026-07-26-single-session-model-switching | [Single-Session Model Switching](2026-07-26-single-session-model-switching.md) | accepted (amended 2026-07-27) | workflow, infra | 2026-07-26 |
@@ -0,0 +1,257 @@
---
spec: docs/specs/agents/runtime-updates.md
decision: docs/decisions/2026-07-26-user-managed-agent-runtime-updates.md
created: 2026-07-26
status: completed
---
# Implementation Plan: Managed Agent Runtime Updates
## Overview
Replace PR 1950's repository-maintained npm pins and scheduled updater with
unversioned, cache-preferring managed ACP launch commands. Then add a
host-scoped, user-triggered update pipeline that refreshes npm's execution
cache, re-probes ACP capabilities, and streams the result into the responsive
Settings > Agents UI. The implementation preserves active sessions and treats
ACP negotiation plus advertised capabilities as the compatibility boundary.
---
## Backend
### Managed npm runtime contract
- Add `ManagedNPMRuntimeSpec` and the optional `ManagedNPMRuntimeAgent`
capability to `apps/backend/internal/agent/agents/agent.go`.
`ManagedNPMRuntimeSpec` owns the hard-coded npm package and ACP argv suffix;
request data never selects either value.
- Add command helpers in
`apps/backend/internal/agent/agents/managed_npm_runtime.go`:
`CachedACPCommand()` emits
`npx --yes --prefer-offline <unversioned-package> <acp-args>`, and
`CacheUpdateCommand()` emits a direct argv command equivalent to
`npm exec --yes --prefer-online --package=<unversioned-package> -- node -e ""`.
The update command primes the same unversioned npm execution-cache key
without relying on each package exposing a version flag.
- Implement the capability for Claude, Codex, OpenCode, Copilot, and Gemini in
their existing files. Use `CachedACPCommand()` from `BuildCommand`,
`Runtime().Cmd`, and `InferenceConfig().Command` so sessions and capability
probes resolve the same runtime. Keep passthrough/authentication helpers
separate where they intentionally use another command.
- Remove all exact version constants/specs from the five agents. Keep remote
install scripts unversioned. Copilot no longer opts its managed ACP launch
into native-binary preference; its native CLI remains available for
discovery and login.
### Runtime update and capability refresh
- Extend `apps/backend/internal/agent/hostutility/public.go` and
`manager.go` with `RefreshWithCommand(ctx, agentType, command)`. It reuses the
existing bounded ACP probe and cache normalization but overrides the
inference command for that probe. The normal `Refresh` path remains
unchanged.
- Add `apps/backend/internal/agent/settings/controller/agent_update.go` with an
`agentRuntimeUpdater` seam for tests and a production implementation that:
reads current version from `hostutility.Manager.Get`, resolves the target
with direct argv `npm view <package> dist-tags.latest --json`, runs only the
built-in `CacheUpdateCommand`, and calls `RefreshWithCommand` with the
cache-preferring ACP command.
- Add `apps/backend/internal/agent/settings/controller/agent_update_job.go`.
`AgentUpdateJobStore` uses the existing 64 KiB ring-buffer, five-minute
timeout/retention, four-worker bound, batched output, and broadcaster
patterns. It transitions through `queued`, `resolving`, `updating`,
`refreshing`, and a terminal state while retaining current/target/refreshed
versions and refresh errors.
- Add a shared same-agent maintenance coordinator in
`apps/backend/internal/agent/settings/controller/maintenance_jobs.go`.
Repeated update requests reuse the active update. An install/update conflict
returns `409 Conflict` with the active maintenance job identity and kind;
neither command is started.
- Classify an authentication-required post-update probe as package success with
`refresh_error`. Registry, npm-exec, timeout, unsupported-protocol, and
non-recoverable initialization failures are terminal failures and retain the
prior capability cache.
- After a successful refresh, call `BroadcastAvailableAgents` so the new
version, models, modes, commands, and configuration options reach open
Settings pages without reload.
### HTTP, DTO, and WebSocket contracts
- Extend `apps/backend/internal/agent/settings/dto/dto.go` with
`RuntimeUpdateDTO`, `AgentUpdateJobStatus`, `AgentUpdateJobDTO`,
`ListAgentUpdateJobsResponse`, and the optional
`AvailableAgentDTO.RuntimeUpdate`.
- Populate runtime metadata in
`apps/backend/internal/agent/settings/controller/agent_discovery.go` only
when an available built-in agent implements `ManagedNPMRuntimeAgent`.
`current_version` comes from the latest successful host capability record.
- Register the three update endpoints in
`apps/backend/internal/agent/settings/handlers/handlers.go`, protected by the
existing Settings interlock for POST. Preserve `202 Accepted` for a newly
queued or deduplicated update and return typed 404/409/503 errors.
- Add `ActionAgentUpdateStarted`, `ActionAgentUpdateOutput`, and
`ActionAgentUpdateFinished` to
`apps/backend/pkg/websocket/actions.go`.
## Frontend
### API, state, and WebSocket hydration
- Extend `apps/web/lib/types/http-agents.ts` with `RuntimeUpdate` metadata.
- Add `AgentUpdateJob`, `updateAgent`, `listAgentUpdateJobs`, and
`getAgentUpdateJob` to `apps/web/lib/api/domains/settings-api.ts` and export
them through the existing API barrels.
- Add `updateJobs` plus set/upsert/append/clear actions to
`apps/web/lib/state/slices/settings/types.ts`,
`settings-slice.ts`, `apps/web/lib/state/store.ts`, and their re-export
surfaces.
- Add typed update payloads/actions to
`apps/web/lib/types/backend.ts` and consume the three notifications in
`apps/web/lib/ws/handlers/agents.ts`. Appended output chunks must not replace
the retained job log.
- Add `useAgentRuntimeUpdates` beside the existing install hook in
`apps/web/app/settings/agents/page.tsx`. It rehydrates retained jobs on
mount, submits updates, handles maintenance conflicts, and relies on
`agent.available.updated` for the refreshed catalogue.
### Installed-agent update control
- Add
`apps/web/components/settings/agent-runtime-update-control.tsx` and compose it
into `installed-agent-card.tsx` only when `runtime_update.supported` is true.
- Show current version (or `Unknown`), target when resolved, the current job
phase, bounded streamed output, refresh-only warnings, retryable failures,
and terminal success. Disable the action while install or update maintenance
is active for the same agent.
- Preserve the existing single-column phone card layout. The labeled update
button has at least a 44 px touch target, version/progress content wraps
vertically, the document remains the primary scroller, and only the bounded
output log gets internal vertical scrolling. No horizontal page scrolling or
hover-only affordance is introduced.
## Documentation and PR replacement
- Delete the scheduled updater workflow, updater scripts/tests, obsolete
pin-oriented plan, and the rejected scheduled-pin ADR added by the current
branch.
- Restore `.github/workflows/lint-action-pinning.yml` and the unrelated GitLab
poller test to their `origin/main` behavior using explicit patches.
- Rewrite `apps/backend/internal/agent/agents/ACP_BRIDGE_VERSIONS.md`,
`README.md`, and
`docs/decisions/0034-agentclientprotocol-codex-acp.md` so they describe
unversioned managed ACP resolution rather than numeric pins.
- Document the Settings update action, host-only scope, active-session
behavior, model refresh, and best-effort npm cache in
`docs/public/agents-and-profiles.md`.
## Tests
- **What:** all five managed agents use the unversioned cache-preferring command
on ACP build/runtime/inference surfaces and expose the correct hard-coded
package metadata.
**File:** tests beside
`apps/backend/internal/agent/agents/{claude_acp,codex_acp,opencode_acp,copilot_acp,gemini}.go`
and `apps/backend/internal/agent/runtime/lifecycle/manager_launch_test.go`.
**How:** table-driven argv assertions; reject `@<version>` and explicit
`latest`.
- **What:** cache update commands use direct argv, online freshness, a
hard-coded package, and no user-controlled shell.
**File:**
`apps/backend/internal/agent/agents/managed_npm_runtime_test.go`.
**How:** unit tests over every managed runtime spec.
- **What:** force refresh probes with the override command and replaces the
host capability cache.
**File:** `apps/backend/internal/agent/hostutility/manager_test.go`.
**How:** fake agentctl probe request/response assertions.
- **What:** target resolution, job states, output bounds, deduplication,
install/update mutual exclusion, refresh success, auth-required refresh, and
hard failures follow the spec.
**File:**
`apps/backend/internal/agent/settings/controller/agent_update_test.go` and
`agent_install_test.go`.
**How:** fake updater/host utility plus real in-memory job scheduling.
- **What:** handler → controller → job-store endpoints return accepted,
retained, not-found, conflict, and interlock responses and broadcast update
events.
**File:**
`apps/backend/internal/agent/settings/handlers/agent_update_handlers_test.go`.
**How:** Gin HTTP integration tests with injected controller seams.
- **What:** the catalogue exposes managed runtime metadata and omits it for
unmanaged/native-only agents.
**File:**
`apps/backend/internal/agent/settings/controller/agent_discovery_test.go`.
**How:** registry and capability-cache fixtures.
- **What:** frontend state merges snapshots and output chunks without
duplication, and the installed card renders idle/running/success/failure
states accessibly.
**File:**
`apps/web/lib/state/slices/settings/settings-slice.test.ts`,
`apps/web/lib/ws/handlers/agents.test.ts`, and
`apps/web/components/settings/agent-runtime-update-control.test.tsx`.
**How:** Vitest store/handler tests and Testing Library component tests.
## E2E Tests
- **Scenario:** given an installed managed agent, starting Update shows
current-to-target versions, reachable progress/output, and terminal success.
**File:**
`apps/web/e2e/tests/settings/agent-runtime-update.spec.ts`.
**What to verify:** stable test IDs, POST submission, retained-job
rehydration, progress text, terminal state, and retry after failure using
deterministic network fixtures while backend integration is covered in Go.
- **Scenario:** given a successful update whose refreshed catalogue adds a
model, the new model appears without a document reload.
**File:** same spec.
**What to verify:** an `agent.available.updated` catalogue replacement is
reflected in the installed agent/profile model surface.
- **Scenario:** given a phone viewport and a running update, all version,
progress, output, and retry controls are touch-reachable without horizontal
overflow.
**File:**
`apps/web/e2e/tests/settings/mobile-agent-runtime-update.spec.ts`.
**What to verify:** labeled 44 px action, wrapped content, bounded log scroll,
page scroll, and `document.scrollWidth <= document.clientWidth`.
## Implementation Waves
Wave 1 (parallel):
- [x] [Task 01: Define unpinned managed runtimes](task-01-unpinned-managed-runtimes.md)
- [x] [Task 02: Remove pin automation and update documentation](task-02-remove-pin-automation.md)
Wave 2:
- [x] [Task 03: Build the backend update pipeline](task-03-backend-update-pipeline.md)
Wave 3:
- [x] [Task 04: Add the Settings update UI](task-04-settings-update-ui.md)
Wave 4:
- [x] [Task 05: Verify the runtime update user flows](task-05-runtime-update-e2e.md)
## Verification
- `cd apps/backend && go test ./internal/agent/agents ./internal/agent/runtime/lifecycle`
- `cd apps/backend && go test ./internal/agent/hostutility ./internal/agent/settings/controller ./internal/agent/settings/handlers`
- `cd apps && pnpm --filter @kandev/web test -- --run lib/state/slices/settings/settings-slice.test.ts lib/ws/handlers/agents.test.ts components/settings/agent-runtime-update-control.test.tsx`
- `cd apps/web && pnpm e2e:run tests/settings/agent-runtime-update.spec.ts`
- `cd apps/web && pnpm e2e:run tests/settings/mobile-agent-runtime-update.spec.ts -- --project=mobile-chrome`
- `node --test scripts/validate-public-docs.test.mjs`
- `node scripts/validate-public-docs.mjs`
- `git diff --check`
- Commit through active hooks, then delegate `/verify` in full mode before
pushing the replacement PR branch.
## Risks
- npm's execution cache is explicitly best-effort. Tests assert command intent,
not durable npm cache internals.
- A same-protocol upstream runtime can still regress. The UI must preserve
prior capability data and expose the failure; rollback remains out of scope.
- Capability probes can require authentication after package installation.
Package success and capability refresh status must remain distinct.
- Existing sessions retain their already-started process. No lifecycle restart
or process replacement belongs in these tasks.
@@ -0,0 +1,54 @@
---
id: "01-unpinned-managed-runtimes"
title: "Define unpinned managed runtimes"
status: done
wave: 1
depends_on: []
plan: "plan.md"
spec: "../../specs/agents/runtime-updates.md"
role: implementer
model_tier: default
---
# Task 01: Define unpinned managed runtimes
## Acceptance
- Claude, Codex, OpenCode, Copilot, and Gemini expose their hard-coded managed
npm package and use an unversioned `--prefer-offline` npx command for every
ACP build/runtime/inference surface.
- The built-in update command uses direct argv with `--prefer-online`; no
version, `latest`, registry, package, or shell text comes from a caller.
- Command-surface tests cover all five agents, and Copilot's managed ACP path no
longer changes to a native binary.
## Verification
- `cd apps/backend && go test ./internal/agent/agents ./internal/agent/runtime/lifecycle`
## Files likely touched
- `apps/backend/internal/agent/agents/agent.go`
- `apps/backend/internal/agent/agents/managed_npm_runtime.go`
- `apps/backend/internal/agent/agents/managed_npm_runtime_test.go`
- `apps/backend/internal/agent/agents/{claude_acp,codex_acp,opencode_acp,copilot_acp,gemini}.go`
- Tests beside those five agent files
- `apps/backend/internal/agent/runtime/lifecycle/manager_launch_test.go`
## Dependencies
None.
## Inputs
- Spec sections `What`, `Scenarios`, and `Out of scope`
- ADR `Decision` and `Consequences`
- Plan sections `Managed npm runtime contract` and `Tests`
- Existing `agents.Command`, `InferenceAgent`, and optional capability patterns
## Output contract
Report intent/acceptance, base/head SHA, changed entry points, spec/ADR sections,
risk tags (`runtime-resolution`, `npm-cache`, `agent-launch`), the exact test
result, and uncertainties. Update only this task file to `done`; do not edit
`plan.md`.
@@ -0,0 +1,65 @@
---
id: "02-remove-pin-automation"
title: "Remove pin automation and update documentation"
status: done
wave: 1
depends_on: []
plan: "plan.md"
spec: "../../specs/agents/runtime-updates.md"
role: implementer
model_tier: default
---
# Task 02: Remove pin automation and update documentation
## Acceptance
- Every workflow, script, test, plan, and ADR that exists only for PR 1950's
scheduled pin updates is removed, and the unrelated GitLab test change is
restored to `origin/main` behavior without destructive git commands.
- Runtime inventory, README, Codex ACP decision, and public agent documentation
describe unversioned managed runtimes plus the explicit host Settings update.
- Public documentation validation passes and no obsolete scheduled-pin
references remain.
## Verification
- `python3 .github/scripts/lint-action-pinning_test.py`
- `python3 .github/scripts/lint-action-pinning.py`
- `node --test scripts/validate-public-docs.test.mjs`
- `node scripts/validate-public-docs.mjs`
- `git diff --check`
- `rg -n "scheduled-core-agent-version-pins|update_agent_versions|claudeACPVersion|codexACPVersion|opencodeACPVersion|copilotACPVersion|geminiVersion" . --glob '!docs/plans/managed-agent-runtime-updates/**'`
## Files likely touched
- `.github/workflows/lint-action-pinning.yml`
- `.github/workflows/update-agent-versions.yml` (delete)
- `.github/scripts/update-agent-versions-workflow_test.py` (delete)
- `scripts/update_agent_versions.py` (delete)
- `scripts/update_agent_versions_test.py` (delete)
- `docs/plans/agent-version-updates/**` (delete)
- `apps/backend/internal/gitlab/poller_health_test.go`
- `apps/backend/internal/agent/agents/ACP_BRIDGE_VERSIONS.md`
- `README.md`
- `docs/decisions/0034-agentclientprotocol-codex-acp.md`
- `docs/public/agents-and-profiles.md`
## Dependencies
None. Do not edit the five agent Go implementations or their tests; Task 01
owns them in the parallel wave.
## Inputs
- Spec `Why`, `What`, and `Out of scope`
- ADR `Decision`, `Consequences`, and rejected pinning alternative
- Plan section `Documentation and PR replacement`
- Current branch diff against `origin/main`
## Output contract
Report intent/acceptance, base/head SHA, deleted/restored/documented files,
spec/ADR sections, risk tags (`pr-replacement`, `docs`, `ci-cleanup`), exact
validation results, and uncertainties. Update only this task file to `done`;
do not edit `plan.md`.
@@ -0,0 +1,68 @@
---
id: "03-backend-update-pipeline"
title: "Build the backend update pipeline"
status: done
wave: 2
depends_on: ["01-unpinned-managed-runtimes"]
plan: "plan.md"
spec: "../../specs/agents/runtime-updates.md"
role: implementer
model_tier: default
---
# Task 03: Build the backend update pipeline
## Acceptance
- Managed installed-agent metadata and the three interlocked update endpoints
expose current/target versions, bounded progress, retained jobs, typed
failures, and same-agent install/update mutual exclusion.
- Update jobs resolve npm metadata and execute only built-in direct argv,
deduplicate while active, refresh ACP capabilities after package success, and
preserve prior capability data on failure.
- Successful capability refresh broadcasts the updated catalogue; auth-required
refresh is reported separately from package success.
## Verification
- `cd apps/backend && go test ./internal/agent/hostutility ./internal/agent/settings/controller ./internal/agent/settings/handlers`
- `cd apps/backend && go test ./pkg/websocket`
## Files likely touched
- `apps/backend/internal/agent/hostutility/public.go`
- `apps/backend/internal/agent/hostutility/manager.go`
- `apps/backend/internal/agent/hostutility/manager_test.go`
- `apps/backend/internal/agent/settings/controller/controller.go`
- `apps/backend/internal/agent/settings/controller/agent_discovery.go`
- `apps/backend/internal/agent/settings/controller/agent_discovery_test.go`
- `apps/backend/internal/agent/settings/controller/agent_install.go`
- `apps/backend/internal/agent/settings/controller/agent_install_test.go`
- `apps/backend/internal/agent/settings/controller/agent_update.go`
- `apps/backend/internal/agent/settings/controller/agent_update_job.go`
- `apps/backend/internal/agent/settings/controller/agent_update_test.go`
- `apps/backend/internal/agent/settings/controller/maintenance_jobs.go`
- `apps/backend/internal/agent/settings/dto/dto.go`
- `apps/backend/internal/agent/settings/handlers/handlers.go`
- `apps/backend/internal/agent/settings/handlers/agent_update_handlers_test.go`
- `apps/backend/pkg/websocket/actions.go`
## Dependencies
Task 01 supplies `ManagedNPMRuntimeAgent`, its package metadata, and the normal
and update command builders.
## Inputs
- Spec `API surface`, `State machine`, `Failure modes`, and scenarios
- Plan `Runtime update and capability refresh` and
`HTTP, DTO, and WebSocket contracts`
- Existing install job store, host-utility `Refresh`, Settings interlock, and
`BroadcastAvailableAgents` patterns
## Output contract
Report intent/acceptance, base/head SHA, changed entry points, named spec/ADR
sections, risk tags (`process-exec`, `job-concurrency`, `websocket`,
`capability-cache`), exact targeted results, and uncertainties. Update only
this task file to `done`; do not edit `plan.md`.
@@ -0,0 +1,70 @@
---
id: "04-settings-update-ui"
title: "Add the Settings update UI"
status: done
wave: 3
depends_on: ["03-backend-update-pipeline"]
plan: "plan.md"
spec: "../../specs/agents/runtime-updates.md"
role: implementer
model_tier: default
---
# Task 04: Add the Settings update UI
## Acceptance
- Installed managed-agent cards expose a labeled update action with current to
target version, queued/running/refreshing progress, bounded output,
success/refresh-warning/failure states, and retry.
- HTTP rehydration and WebSocket snapshots/chunks keep update state accurate
across disconnects without duplicating output; unmanaged agents omit the
control and same-agent maintenance disables it.
- Desktop and phone layouts preserve the existing card composition, at least
44 px touch targets, vertical reachability, and no horizontal overflow.
## Verification
- `cd apps && pnpm --filter @kandev/web test -- --run lib/state/slices/settings/settings-slice.test.ts lib/ws/handlers/agents.test.ts components/settings/agent-runtime-update-control.test.tsx`
- `cd apps/web && pnpm run typecheck`
- `cd apps && pnpm --filter @kandev/web lint`
## Files likely touched
- `apps/web/lib/types/http-agents.ts`
- `apps/web/lib/api/domains/settings-api.ts`
- Existing API export barrels under `apps/web/lib/api/`
- `apps/web/lib/state/slices/settings/types.ts`
- `apps/web/lib/state/slices/settings/settings-slice.ts`
- `apps/web/lib/state/slices/settings/settings-slice.test.ts`
- `apps/web/lib/state/store.ts`
- Existing settings state re-export files
- `apps/web/lib/types/backend.ts`
- `apps/web/lib/ws/handlers/agents.ts`
- `apps/web/lib/ws/handlers/agents.test.ts`
- `apps/web/app/settings/agents/page.tsx`
- `apps/web/components/settings/installed-agent-card.tsx`
- `apps/web/components/settings/agent-runtime-update-control.tsx`
- `apps/web/components/settings/agent-runtime-update-control.test.tsx`
## Dependencies
Task 03 supplies the HTTP DTOs, state machine, conflict response, retained-job
list, and WebSocket actions.
## Inputs
- Spec `What`, `API surface`, `State machine`, and desktop/mobile scenarios
- Plan `API, state, and WebSocket hydration` and
`Installed-agent update control`
- Existing `useInstallAgent`, `InstallAgentCard`, `InstalledAgentCard`, settings
slice, and agent WS handler
- Mobile parity contract: visible labeled action, 44 px target, document
scrolling, bounded internal log, no horizontal overflow
## Output contract
Report intent/acceptance, base/head SHA, changed entry points, named spec
sections, risk tags (`settings-ui`, `state-hydration`, `mobile-parity`,
`accessibility`), exact targeted results, and uncertainties. Update only this
task file to `done`; do not edit `plan.md`.
@@ -0,0 +1,55 @@
---
id: "05-runtime-update-e2e"
title: "Verify the runtime update user flows"
status: done
wave: 4
depends_on: ["03-backend-update-pipeline", "04-settings-update-ui"]
plan: "plan.md"
spec: "../../specs/agents/runtime-updates.md"
role: test-engineer
model_tier: default
---
# Task 05: Verify the runtime update user flows
## Acceptance
- A production-build Playwright flow proves update submission, visible
current-to-target progress/output, terminal success/failure, retained-job
rehydration, and refreshed catalogue/model rendering through the UI.
- Mobile Chrome coverage proves the action is touch-reachable, at least 44 px
high, content/log/retry states remain vertically reachable, and the page
never gains horizontal overflow.
- Tests use deterministic fixtures and stable test IDs; they do not require
registry access or add product-only test hooks.
## Verification
- `cd apps/web && pnpm e2e:run tests/settings/agent-runtime-update.spec.ts`
- `cd apps/web && pnpm e2e:run tests/settings/mobile-agent-runtime-update.spec.ts -- --project=mobile-chrome`
## Files likely touched
- `apps/web/e2e/tests/settings/agent-runtime-update.spec.ts`
- `apps/web/e2e/tests/settings/mobile-agent-runtime-update.spec.ts`
- Existing Settings page objects/helpers only if shared interaction warrants it
- Runtime-update components only for stable `data-testid` attributes or a
directly exposed regression found by the RED test
## Dependencies
Tasks 03 and 04 must be integrated and their targeted verification green.
## Inputs
- Every user-visible scenario in the spec
- Plan `E2E Tests`
- `apps/web/e2e/tests/settings/agent-install-streaming.spec.ts`
- E2E managed-runner, production-build, selector, and mobile interaction rules
## Output contract
Report intent/acceptance, base/head SHA, changed specs/helpers, named spec
scenarios, risk tags (`e2e`, `production-build`, `mobile-chrome`), exact RED
and GREEN commands/results, artifacts inspected, and uncertainties. Update only
this task file to `done`; do not edit `plan.md`.
+29 -1
View File
@@ -22,6 +22,34 @@ The production registry currently shows Auggie, Claude, Codex, Copilot, Gemini,
The status shown on this page is authoritative for the current host. A CLI that works in your interactive shell can still be absent from Kandev when the service has a different `PATH`, home directory, or operating-system user.
### Update a managed agent runtime
Installed Claude, Codex, OpenCode, Copilot, and Gemini cards provide an
**Update agent** action. Kandev invokes these managed npm runtimes without an
exact version or `latest` tag during ordinary launches, so npm can reuse its
best-effort execution cache. The version reported by the agent is the
authoritative current version; Kandev does not infer it from the application
release.
Select **Update agent** to deliberately check npm and refresh the managed
runtime on the Kandev host. The card shows the current and upstream target
versions, streams progress, and remains disabled until the update finishes.
After the package update, Kandev automatically starts a fresh ACP capability
probe. A successful probe replaces the advertised models, modes, configuration
options, commands, and runtime version without a page reload.
The action changes later host probes and sessions only. It does not restart an
active session, update a separately configured passthrough or authentication
helper, or update remote executors and running containers. Those environments
resolve their own unversioned runtime when they launch.
If registry lookup or package execution fails, Kandev keeps the previous
capability catalogue and shows the captured failure. If the package updates but
the follow-up probe requires authentication, the card reports the update plus
the refresh error; authenticate the host agent and refresh again. Update job
history is short-lived and does not survive a backend restart, and npm cache
contents are not a durable Kandev installation record.
### Add a custom terminal agent
Use **Settings > Agents > Add TUI Agent** for a CLI that Kandev does not register. Enter a display name, command, and optional model label. `{{model}}` in the command is replaced by the selected model value, then the entire command is split on whitespace with Go's `strings.Fields`.
@@ -45,7 +73,7 @@ Select an agent, create a profile, then open **Settings > Agents > _Agent_ > _Pr
| Auto-approve all permissions | Answers automatically: the first `allow_once`/`allow_always` option, otherwise the first option supplied by the agent; no options cancels. It is off by default. |
| MCP servers | Adds profile-specific external MCP servers when the agent supports MCP. |
Model, mode, command, and configuration choices are probed from the locally installed CLI and cached. Refresh the profile if an agent update changes them. Probe status can report **auth required**, **not installed**, **not configured**, or **failed**; a saved model name does not prove that the current provider account can use it.
Model, mode, command, and configuration choices are probed from the locally installed CLI and cached. The managed **Update agent** action refreshes them automatically; after other CLI changes, refresh the profile manually. Probe status can report **auth required**, **not installed**, **not configured**, or **failed**; a saved model name does not prove that the current provider account can use it.
### Monitor capability and subscription status
+1
View File
@@ -77,6 +77,7 @@ Roles, governance gates, and granular permissions that apply across human users
| Spec | Status |
|---|---|
| [runtime-updates](agents/runtime-updates.md) | approved |
| [roles](agents/roles.md) | shipped |
| [governance](agents/governance.md) | shipped |
| [granular-permissions](agents/granular-permissions.md) | draft |
+193
View File
@@ -0,0 +1,193 @@
---
status: approved
created: 2026-07-26
owner: Kandev
---
# Managed Agent Runtime Updates
## Why
Operators need newly released agent capabilities and models without waiting for
a Kandev release. They also need normal agent launches to avoid paying an
upstream package-resolution cost on every session when a usable npm execution
cache is already present.
## What
- Kandev launches the managed npm runtime for Claude, Codex, OpenCode, Copilot,
and Gemini by package name without an exact version or an explicit `latest`
tag.
- Normal launches may reuse npm's execution cache. Cache reuse is best-effort;
Kandev does not present it as a durable installed-version guarantee.
- Each supported installed agent has a visible **Update agent** action on the
Settings > Agents page on desktop and mobile.
- Starting an update shows the current runtime version, the upstream target
version, live progress, and the terminal success or failure state.
- A successful package update automatically starts a fresh host capability
probe. The returned runtime version, models, modes, configuration options,
commands, and capability status replace the previous cached values.
- An update affects new host probes, utility calls, and sessions. It does not
restart or mutate an already-running agent session.
- Kandev uses the ACP initialization protocol version and advertised
capabilities as the compatibility boundary. Kandev does not gate managed
npm runtimes by a repository-maintained package-version allowlist.
- Package update commands are defined by Kandev's built-in agent metadata.
Callers cannot submit package names, versions, registry URLs, or shell text.
- Update jobs for the same agent are idempotent while queued or running. An
install and update for the same agent cannot run concurrently.
The initial managed package set is:
| Agent | Managed runtime package |
| --- | --- |
| Claude | `@agentclientprotocol/claude-agent-acp` |
| Codex | `@agentclientprotocol/codex-acp` |
| OpenCode | `opencode-ai` |
| Copilot | `@github/copilot` |
| Gemini | `@google/gemini-cli` |
The managed package is the runtime Kandev uses for ACP capability discovery.
Separately configured passthrough commands and native authentication helpers
remain outside this update action when they use another package or installer.
Decision: [ADR-2026-07-26-user-managed-agent-runtime-updates](../../decisions/2026-07-26-user-managed-agent-runtime-updates.md).
## API surface
### Agent catalogue
Installed-agent catalogue entries expose optional runtime-management metadata:
```json
{
"runtime_update": {
"supported": true,
"package": "@agentclientprotocol/claude-agent-acp",
"current_version": "0.62.0"
}
}
```
`current_version` is omitted when no successful capability probe has reported a
runtime version. Unmanaged agents omit `runtime_update`.
### Update jobs
- `POST /api/v1/agent-update/:agentName` starts or returns the active update
job for a built-in managed agent.
- `GET /api/v1/agent-update/jobs` returns active and recently completed update
jobs.
- `GET /api/v1/agent-update/jobs/:id` returns one retained update job.
- State-changing update requests use the same Settings interlock as agent
installation and profile mutation.
An update job contains:
```json
{
"job_id": "uuid",
"agent_name": "claude-acp",
"status": "resolving",
"current_version": "0.62.0",
"target_version": "0.63.0",
"output": "",
"error": "",
"refresh_error": "",
"started_at": "timestamp",
"finished_at": "timestamp"
}
```
`current_version`, `target_version`, `finished_at`, `error`, and
`refresh_error` are optional until known. The backend emits
`agent.update.started`, `agent.update.output`, and `agent.update.finished`
notifications with the same job identity and state. Output notifications carry
only the appended output chunk.
## State machine
| State | Trigger | Observable behavior |
| --- | --- | --- |
| `queued` | The backend accepts an update request. | The action is disabled and shows that the update is queued. |
| `resolving` | A worker starts the job. | Kandev discovers the current runtime version and upstream npm target. |
| `updating` | Version resolution succeeds. | Kandev streams package-update output and shows current → target. |
| `refreshing` | The package update succeeds. | Kandev re-probes the host runtime and keeps the action disabled. |
| `succeeded` | The capability probe succeeds, or the package updated but capability refresh returned a recoverable error. | The UI shows the installed target. When refresh succeeded, it replaces model and mode data. A refresh-only error is shown without claiming the package update was rolled back. |
| `failed` | Registry lookup or package update fails, the command times out, or ACP initialization is incompatible. | The UI retains the previous model list and shows the captured error and output. |
Jobs are terminal after `succeeded` or `failed`. Retrying creates a new job.
## Failure modes
- If npm registry metadata cannot be resolved, the job fails before changing
the runtime and retains the prior capability data.
- If the package update command fails or times out, the job fails and retains
the prior capability data.
- If the package update succeeds but the capability probe fails because
authentication is required or another recoverable probe error occurs, the
job reports package-update success plus `refresh_error`; the previous model
list remains visible and the operator can authenticate or retry the refresh.
- If the updated runtime negotiates an unsupported ACP protocol version or
cannot initialize, the job fails visibly. Kandev does not silently fall back
to a repository-pinned runtime.
- Raw process output is bounded using the existing in-memory job output limit.
Package-manager credentials and configured registry authentication are never
returned as structured fields.
- Loss of the browser connection does not cancel a running job. Reopening the
page recovers retained job progress through the jobs endpoint.
## Persistence guarantees
- Update jobs and capability data are process-local and do not survive a Kandev
backend restart.
- Completed jobs remain queryable for the existing short job-retention window.
- npm's host cache may survive Kandev restarts, but Kandev does not own or
guarantee that cache.
- After a backend restart, normal host capability probing reports whichever
runtime npm resolves in that environment.
## Scenarios
- **GIVEN** a managed agent with a cached runtime, **WHEN** a new session starts
without an explicit update, **THEN** Kandev invokes the unversioned package
spec and does not require a repository-maintained version pin.
- **GIVEN** Claude reports runtime version `0.62.0` and npm reports `0.63.0`,
**WHEN** the operator selects **Update agent**, **THEN** the card shows
`0.62.0 → 0.63.0` and streams progress until the job is terminal.
- **GIVEN** an update succeeds and the new runtime advertises an additional
model, **WHEN** the automatic capability probe completes, **THEN** the new
model appears without a page reload or manual Rescan.
- **GIVEN** an update is already queued, resolving, updating, or refreshing,
**WHEN** the operator selects the action again, **THEN** Kandev returns the
existing job and does not run a second update.
- **GIVEN** an install is active for an agent, **WHEN** an update is requested
for that agent, **THEN** Kandev returns the active maintenance job rather
than running install and update concurrently.
- **GIVEN** npm registry lookup fails, **WHEN** an update is requested,
**THEN** the card shows a retryable failure and retains the previous models.
- **GIVEN** the package update succeeds but the fresh probe requires
authentication, **WHEN** the job finishes, **THEN** the card reports the new
package version, shows the refresh error, retains the previous models, and
keeps the existing authentication recovery action available.
- **GIVEN** an agent is unmanaged or native-only, **WHEN** Settings renders its
installed card, **THEN** no update action is shown.
- **GIVEN** an update is running on a phone viewport, **WHEN** the operator
views the installed-agent card, **THEN** current and target versions,
progress, output, and retry state are reachable by touch without horizontal
page scrolling.
- **GIVEN** an agent session is already running, **WHEN** its host runtime is
updated, **THEN** the existing session continues unchanged and only later
probes or launches use the updated runtime.
## Out of scope
- Scheduled or automatic package updates.
- Exact package-version pins, version allowlists, rollback, or user-selected
historical versions.
- Updating configured remote executors or every running container from the
host Settings action.
- Restarting or hot-swapping active agent sessions.
- Managing native-only update channels such as Cursor.
- Updating separately distributed passthrough or authentication helper
packages when they are not the managed ACP runtime.