Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-7520 fix(agent): support OpenCode 2.x runtimes (#8596)

Bohan Jiang80aa31c1ab70
diff --git a/server/internal/daemon/opencode_v2_mcp_wiring_test.go b/server/internal/daemon/opencode_v2_mcp_wiring_test.go
new file mode 100644
index 0000000000..04f3260697
--- /dev/null
+++ b/server/internal/daemon/opencode_v2_mcp_wiring_test.go
@@ -0,0 +1,84 @@
+package daemon
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+
+ agentpkg "github.com/multica-ai/multica/server/pkg/agent"
+)
+
+// TestOpenCodeV2RefusesSynthesizedMCPWithoutAgentConfig covers the seam between
+// what the daemon composes and what the OpenCode backend accepts.
+//
+// ExecOptions.McpConfig is not agent.mcp_config. The daemon folds several
+// sources into it — workspace MCP servers bound to the agent (at claim), the
+// task's integration servers and the plugin-hook tool server (at run, via
+// mergeTaskRemoteMCPConfig), and the runtime's own servers. An agent with no MCP
+// configuration of its own therefore still reaches a 2.x runtime carrying
+// servers, and that run is refused.
+//
+// This is here rather than in pkg/agent because only this side can use the real
+// merge helper: pkg/agent cannot import the daemon. It pins both halves — that
+// the daemon really does synthesize a config from nothing, and that the refusal
+// fires on the result.
+func TestOpenCodeV2RefusesSynthesizedMCPWithoutAgentConfig(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("fake CLI is a shell script")
+ }
+
+ // What a task with integration or plugin-hook tools contributes. The agent
+ // itself has nothing configured: base is nil.
+ overlay := json.RawMessage(`{"mcpServers":{"composio-github":{"type":"remote","url":"https://example.invalid/mcp","headers":{"Authorization":"Bearer FAKE-WIRING-TOKEN"}}}}`)
+ composed, err := mergeTaskRemoteMCPConfig(nil, overlay)
+ if err != nil {
+ t.Fatalf("merge task remote MCP config: %v", err)
+ }
+ if len(composed) == 0 {
+ t.Fatal("expected the daemon to synthesize an MCP config from a nil agent config")
+ }
+
+ dir := t.TempDir()
+ fakeCLI := filepath.Join(dir, "opencode")
+ if err := os.WriteFile(fakeCLI, []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
+ t.Fatalf("write fake cli: %v", err)
+ }
+
+ backend, err := agentpkg.New("opencode", agentpkg.Config{
+ ExecutablePath: fakeCLI,
+ CLIVersion: "opencode v2.0.10",
+ BuiltinRuntime: true,
+ Logger: slog.Default(),
+ })
+ if err != nil {
+ t.Fatalf("new opencode backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ _, execErr := backend.Execute(ctx, "prompt-ignored", agentpkg.ExecOptions{
+ Cwd: t.TempDir(),
+ McpConfig: composed,
+ Timeout: 5 * time.Second,
+ })
+ if !errors.Is(execErr, agentpkg.ErrOpenCodeV2MCPUnsupported) {
+ t.Fatalf("expected the composed MCP config to be refused, got %v", execErr)
+ }
+
+ // The operator's way out has to be reachable. Naming agent.mcp_config alone
+ // would point at a field that is already empty in exactly this case.
+ message := execErr.Error()
+ for _, want := range []string{"1.x", "workspace", "integration", "plugin"} {
+ if !strings.Contains(message, want) {
+ t.Fatalf("refusal should name the %q recovery path for non-agent MCP sources: %s", want, message)
+ }
+ }
+}
diff --git a/server/pkg/agent/opencode.go b/server/pkg/agent/opencode.go
index 70279c62f3..69a2595ac7 100644
--- a/server/pkg/agent/opencode.go
+++ b/server/pkg/agent/opencode.go
@@ -44,6 +44,10 @@ var opencodeBlockedArgs = map[string]blockedArgMode{
// and reading streaming JSON events from stdout — the same pattern as Claude.
type opencodeBackend struct {
cfg Config
+ // session is per-run state, set by Execute on the copy it scans with, so
+ // the cancellation handler can interrupt the session server-side. It is nil
+ // on the Backend New returns and on any backend built directly by a test.
+ session *opencodeSessionTracker
}
// opencodeSeparatesReasoning recognizes the released OpenCode 1.x wire contract.
@@ -84,6 +88,10 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecO
timeout := opts.Timeout
runCtx, cancel := runContext(ctx, timeout)
+ // See opencode_v2.go for what 2.x changed and why the differences are
+ // handled together rather than one flag at a time.
+ usesV2 := opencodeUsesV2Contract(b.cfg)
+
args := []string{"run", "--format", "json", "--dangerously-skip-permissions"}
// Anchor OpenCode's project discovery (AGENTS.md walk-up + .opencode/skills/
// project config scan) at the task workdir. Without this, OpenCode falls
@@ -94,13 +102,28 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecO
// PWD is also overridden below because OpenCode prefers PWD over cwd when
// `--dir` is absent and uses it as the starting point for any further
// path resolution.
- if opts.Cwd != "" {
+ //
+ // 2.x removed `--dir` outright and anchors on the process cwd instead, which
+ // cmd.Dir and the PWD override below already provide. Passing it there is
+ // not a no-op: the CLI rejects the unknown flag and the run dies before it
+ // starts (GH #8586).
+ if opts.Cwd != "" && !usesV2 {
args = append(args, "--dir", opts.Cwd)
}
- if opts.Model != "" {
- args = append(args, "--model", opts.Model)
+ model := opts.Model
+ if usesV2 {
+ // 2.x dropped `--variant` and reads the variant off the model string.
+ folded, ok := opencodeModelArg(model, opts.ThinkingLevel)
+ if !ok {
+ b.cfg.Logger.Warn("opencode: thinking level needs an explicit model on OpenCode 2.x; ignoring",
+ "thinkingLevel", opts.ThinkingLevel)
+ }
+ model = folded
+ }
+ if model != "" {
+ args = append(args, "--model", model)
}
- if opts.ThinkingLevel != "" {
+ if opts.ThinkingLevel != "" && !usesV2 {
args = append(args, "--variant", opts.ThinkingLevel)
}
// OpenCode's `run` subcommand has no --prompt flag — passing one makes the
@@ -128,7 +151,11 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecO
// out of OS process listings; the shared command logger separately redacts
// argv values.
- cmd := b.cfg.commandAt(execPath).exec(runCtx, args...)
+ runtimeCmd := b.cfg.commandAt(execPath)
+ // run carries this invocation's session id. Execute scans with it instead of
+ // b so two runs sharing a Backend value cannot observe each other's session.
+ run := &opencodeBackend{cfg: b.cfg, session: &opencodeSessionTracker{}}
+ cmd := runtimeCmd.exec(runCtx, args...)
hideAgentWindow(cmd)
// Take over context cancellation. The default kills the whole group the
// instant runCtx is done; we instead drive a graceful, group-wide
@@ -160,30 +187,56 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecO
if opts.Cwd != "" {
env = append(env, "PWD="+opts.Cwd)
}
- // Project agent.mcp_config into OpenCode via OPENCODE_CONFIG_CONTENT —
- // OpenCode's general inline-config injection mechanism that merges at
- // "local" scope (after the project-config loop, before remote / managed
- // configs). MCP is the only field we currently project there; if a
- // future Multica field needs the same channel it would assemble a
- // combined OpenCode config slice before the env append.
+ // Project agent.mcp_config into OpenCode. The channel differs by major:
//
- // This deliberately leaves <workdir>/opencode.json untouched — the
- // workdir is reused across turns for the same (agent, issue), and any
- // agent- or user-written model / tools / permission settings in it must
- // survive across runs.
- mcpContent, err := buildOpenCodeMCPConfigContent(opts.McpConfig)
- if err != nil {
- cancel()
- return nil, err
- }
- if mcpContent != "" {
- if _, dup := b.cfg.Env["OPENCODE_CONFIG_CONTENT"]; dup {
- b.cfg.Logger.Warn("agent.custom_env sets OPENCODE_CONFIG_CONTENT but agent.mcp_config takes precedence and overrides it")
+ // On 1.x, OPENCODE_CONFIG_CONTENT — OpenCode's general inline-config
+ // injection mechanism that merges at "local" scope (after the
+ // project-config loop, before remote / managed configs). MCP is the only
+ // field we currently project there; if a future Multica field needs the
+ // same channel it would assemble a combined OpenCode config slice before
+ // the env append. That path deliberately leaves <workdir>/opencode.json
+ // untouched — the workdir is reused across turns for the same
+ // (agent, issue), and any agent- or user-written model / tools /
+ // permission settings in it must survive across runs.
+ //
+ // 2.x stopped honouring that env var, and the only channel it left puts the
+ // credentials in the agent's own working tree, where the agent can commit
+ // them. Such runs are refused rather than started without their servers —
+ // see ErrOpenCodeV2MCPUnsupported.
+ if usesV2 {
+ if err := opencodeCheckMCPSupport(opts.McpConfig); err != nil {
+ cancel()
+ return nil, err
+ }
+ } else {
+ mcpContent, err := buildOpenCodeMCPConfigContent(opts.McpConfig)
+ if err != nil {
+ cancel()
+ return nil, err
+ }
+ if mcpContent != "" {
+ if _, dup := b.cfg.Env["OPENCODE_CONFIG_CONTENT"]; dup {
+ b.cfg.Logger.Warn("agent.custom_env sets OPENCODE_CONFIG_CONTENT but agent.mcp_config takes precedence and overrides it")
+ }
+ env = append(env, "OPENCODE_CONFIG_CONTENT="+mcpContent)
}
- env = append(env, "OPENCODE_CONFIG_CONTENT="+mcpContent)
}
cmd.Env = env
+ // Capture how this run reaches its OpenCode service, so a later interrupt
+ // talks to the same one. `--server` can arrive through agent.custom_args, and
+ // the default background service is resolved from the process environment and
+ // working directory — an interrupt missing any of that would report success
+ // against a different service while this session kept running.
+ interruptServer, interruptStandalone := opencodeConnectionFromArgs(args)
+ interruptConn := opencodeRunConnection{
+ cmd: runtimeCmd,
+ server: interruptServer,
+ standalone: interruptStandalone,
+ env: env,
+ dir: opts.Cwd,
+ }
+
stdout, err := cmd.StdoutPipe()
if err != nil {
cancel()
@@ -246,6 +299,15 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecO
// OpenCode that stopped reading before draining it would otherwise
// strand that goroutine for the lifetime of the daemon.
closeStdin()
+ // On 2.x the process below is only a client; the run itself belongs to a
+ // background service that survives every signal sent here. Ask the
+ // service to stop the session first, otherwise the agent keeps working —
+ // calling tools and writing to the workdir — after this task is already
+ // recorded as cancelled. Best effort: the signalling below is unchanged
+ // and still runs whether or not this succeeds.
+ if usesV2 {
+ opencodeInterruptSession(interruptConn, run.session.get(), b.cfg.Logger)
+ }
if cmd.Process != nil {
signalProcessGroup(cmd, syscall.SIGTERM)
select {
@@ -263,7 +325,7 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecO
defer close(resCh)
startTime := time.Now()
- scanResult := b.processEvents(stdout, msgCh)
+ scanResult := run.processEvents(stdout, msgCh)
// Wait for process exit, then release the cancellation handler.
exitErr := cmd.Wait()
@@ -420,6 +482,9 @@ func (b *opencodeBackend) processEvents(r io.Reader, ch chan<- Message) eventRes
if event.SessionID != "" {
sessionID = event.SessionID
+ // Publish it for the cancellation handler, which needs a session id
+ // to interrupt a 2.x run server-side. No-op when b has no tracker.
+ b.session.set(event.SessionID)
}
switch event.Type {
diff --git a/server/pkg/agent/opencode_v2.go b/server/pkg/agent/opencode_v2.go
new file mode 100644
index 0000000000..f7c6f34ebc
--- /dev/null
+++ b/server/pkg/agent/opencode_v2.go
@@ -0,0 +1,289 @@
+package agent
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "strings"
+ "sync"
+ "time"
+)
+
+// OpenCode 2.0 reorganised the contract `opencode run` speaks. Four things the
+// daemon depends on changed at once, and only the first announces itself:
+//
+// - `--dir` was removed. The task workdir now comes from the process cwd,
+// which the backend already sets (together with PWD).
+// - `--variant` was removed. A model variant now rides along inside the model
+// string as `provider/model#variant`.
+// - OPENCODE_CONFIG_CONTENT is no longer honoured, and the only channel left
+// for MCP puts credentials somewhere the agent can commit them. Such runs
+// are refused — see ErrOpenCodeV2MCPUnsupported.
+// - `opencode run` became a thin client in front of a resident background
+// service, so signalling the client's process group no longer stops the
+// work that run started.
+//
+// The two removed flags fail loudly — `Unrecognized flag: --dir`, exit 1 within
+// ~130ms (GH #8586), and the same for `--variant` on any agent with a thinking
+// level. The other two do not announce themselves at all: before this file, a
+// run that merely dropped `--dir` started fine and then executed without its MCP
+// servers and without a working cancel. Handling them together is what keeps
+// fixing the loud failure from exposing the quiet ones.
+//
+// Everything else the backend relies on was checked against 2.0.10 and is
+// unchanged across the two majors — the `--format json` event vocabulary,
+// `--session` resume, `.opencode/skills/` discovery, AGENTS.md, and
+// `--dangerously-skip-permissions` (still accepted and still honoured) — so
+// none of it is branched on here.
+
+// opencodeInterruptTimeout bounds the session-interrupt call made while a run
+// is being cancelled. It is deliberately short: the interrupt is an extra step
+// in front of the termination path that already works, so a service that does
+// not answer promptly must not delay the signals behind it.
+const opencodeInterruptTimeout = 5 * time.Second
+
+// opencodeUsesV2Contract reports whether the resolved OpenCode CLI speaks the
+// 2.x contract described above.
+//
+// Scoped to BuiltinRuntime for the same reason opencodeSeparatesReasoning is: a
+// custom runtime profile wraps a binary this package did not choose, and its
+// reported version string does not establish which usage convention that binary
+// speaks. Reading "2.x" off a wrapper that actually execs OpenCode 1.x would
+// break a runtime that works today, so anything unrecognised keeps the 1.x
+// argv. A custom profile pointed at OpenCode 2.x therefore stays broken until
+// someone can map profiles onto capabilities directly — which is the same
+// trade-off the reasoning check already makes, and strictly better than
+// regressing working 1.x profiles on a guess.
+func opencodeUsesV2Contract(cfg Config) bool {
+ if !cfg.BuiltinRuntime {
+ return false
+ }
+ // parseSemver scans for a semver token anywhere in the string, which is what
+ // this needs: 2.x reports `opencode v2.0.10` where 1.x reports a bare
+ // `1.18.31`, and extractVersionLine keeps whichever whole line it matched.
+ version, err := parseSemver(strings.TrimSpace(cfg.CLIVersion))
+ if err != nil {
+ return false
+ }
+ return version.Major >= 2
+}
+
+// opencodeModelArg folds a thinking level into the model string for the 2.x
+// contract, which has no `--variant` flag and instead reads the variant off the
+// model as `provider/model#variant`.
+//
+// The second return reports whether the thinking level was representable. It is
+// false only when there is a level but no model to attach it to: 2.x resolves
+// the default model server-side, so there is no model string to append to and
+// the level cannot be expressed at all. Callers warn rather than fail, because
+// losing the reasoning effort is not worth failing an otherwise valid task.
+func opencodeModelArg(model, thinkingLevel string) (string, bool) {
+ if thinkingLevel == "" {
+ return model, true
+ }
+ if model == "" {
+ return model, false
+ }
+ // A model that already carries a variant was pinned deliberately (by
+ // agent.model or custom_args); it wins over the agent-level thinking level
+ // rather than growing a second `#` that OpenCode would reject.
+ if strings.Contains(model, "#") {
+ return model, true
+ }
+ return model + "#" + thinkingLevel, true
+}
+
+// ErrOpenCodeV2MCPUnsupported reports that the MCP servers Multica manages for
+// a task cannot be delivered to an OpenCode 2.x runtime yet.
+//
+// The message deliberately does not name agent.mcp_config. ExecOptions.McpConfig
+// is the *composed* set, and only one of its sources is the agent's own column:
+// the daemon also folds in the workspace MCP servers bound to the agent (at
+// claim), the task's integration/Composio servers and the plugin-hook tool
+// server (at run), and the runtime's own servers on top of those. A task whose
+// agent has no MCP configuration at all still arrives here with a non-empty
+// config, so an error telling the operator to edit agent.mcp_config would point
+// at a field that may be empty already and would not release the task.
+//
+// 2.x honours no environment channel for config — OPENCODE_CONFIG_CONTENT (the
+// 1.x channel), OPENCODE_CLI_CONFIG_CONTENT, OPENCODE_CONFIG and
+// OPENCODE_CONFIG_DIR were each checked against 2.0.10, with and without
+// --standalone, and none of them reach the session. The only channel that works
+// is <workdir>/opencode.json, and MCP entries carry bearer headers, OAuth client
+// secrets and environment values.
+//
+// Writing them there is not safe today. The workdir is the agent's own working
+// tree, and in local-directory mode it is the user's checkout: the agent can
+// commit that file mid-run with an ordinary `git add -A`, which puts the
+// credential in Git history where no end-of-task cleanup can reach it. File
+// permissions do not help, because the committing process is the same user.
+//
+// Failing here is deliberate. Running the task anyway would silently drop every
+// MCP server the agent was configured with, which is harder to diagnose than a
+// refusal naming the cause.
+//
+// The way out is known and measured, and wants its own change (MUL-7523):
+// `--standalone` gives the run a private server that inherits the daemon's
+// environment, and 2.x then resolves `{env:NAME}` placeholders inside the
+// config, so the file can carry references while the secrets stay in the
+// process environment. That costs a server start per run and changes the
+// process topology cancellation depends on, so it is not something to fold into
+// a compatibility fix.
+var ErrOpenCodeV2MCPUnsupported = errors.New(
+ "opencode: Multica-managed MCP servers cannot be delivered to an OpenCode 2.x runtime yet. " +
+ "2.x accepts MCP configuration only through a file in the task working directory, where " +
+ "the agent's own commits would capture the servers' credentials. " +
+ "To run this task: point the agent at an OpenCode 1.x runtime, or remove the MCP servers " +
+ "Multica supplies it — these can come from the agent's MCP configuration, workspace MCP " +
+ "servers bound to the agent, the workspace's integration tools, or an installed plugin's " +
+ "hook tools")
+
+// opencodeCheckMCPSupport fails a 2.x run that carries MCP configuration, rather
+// than starting it without the servers it was supposed to get.
+func opencodeCheckMCPSupport(raw json.RawMessage) error {
+ if len(raw) == 0 {
+ return nil
+ }
+ // An mcp_config that translates to no servers asks for nothing, so there is
+ // nothing to refuse.
+ servers, err := translateMCPConfigForOpenCode(raw)
+ if err != nil {
+ return err
+ }
+ if len(servers) == 0 {
+ return nil
+ }
+ return ErrOpenCodeV2MCPUnsupported
+}
+
+// opencodeSessionTracker carries the session id observed on a run's event
+// stream over to that run's cancellation handler, which needs it to interrupt
+// the session server-side.
+//
+// It exists because the two live in different goroutines: the scanner learns the
+// id from the first event that carries one, while the cancellation handler is
+// parked on the context. Execute gives every run its own tracker, so two runs
+// sharing a Backend value cannot see each other's session.
+type opencodeSessionTracker struct {
+ mu sync.Mutex
+ id string
+}
+
+// set records the first session id seen. Safe on a nil tracker so backends built
+// without one (every unit test that drives processEvents directly) need no
+// special casing.
+func (t *opencodeSessionTracker) set(id string) {
+ if t == nil || id == "" {
+ return
+ }
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if t.id == "" {
+ t.id = id
+ }
+}
+
+// get returns the observed session id, or "" if no event carried one yet.
+func (t *opencodeSessionTracker) get() string {
+ if t == nil {
+ return ""
+ }
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ return t.id
+}
+
+// opencodeRunConnection is the connection context a run was launched with, so
+// its interrupt reaches the same service the work is actually running on.
+//
+// `opencode run` accepts `--server <url>` (and users can pass one through
+// agent.custom_args), and it resolves the default background service relative to
+// the process environment and working directory. An interrupt that dropped any
+// of that would report success against a different service while the real
+// session kept running.
+type opencodeRunConnection struct {
+ cmd Command
+ // server is the `--server` value the run was launched with, if any.
+ server string
+ // standalone reports that the run owns a private server. That server is a
+ // child of the client, so the existing process-group signalling already
+ // stops it and no interrupt is needed.
+ standalone bool
+ // env and dir mirror the run's process environment and working directory,
+ // which is how the CLI discovers the default service.
+ env []string
+ dir string
+}
+
+// opencodeConnectionFromArgs reads the connection flags out of a run's final
+// argv, after custom_args have been merged in.
+func opencodeConnectionFromArgs(args []string) (server string, standalone bool) {
+ for i, arg := range args {
+ switch {
+ case arg == "--standalone":
+ standalone = true
+ case arg == "--server" && i+1 < len(args):
+ server = args[i+1]
+ case strings.HasPrefix(arg, "--server="):
+ server = strings.TrimPrefix(arg, "--server=")
+ }
+ }
+ return server, standalone
+}
+
+// opencodeInterruptSession asks the OpenCode 2.x service to stop a session. On
+// 2.x this is the only thing that actually stops a run.
+//
+// `opencode run` is a thin client: the work happens inside a background service
+// that outlives it, so the SIGTERM→SIGKILL the backend sends to the client's
+// process group leaves the agent running — still calling tools, still writing to
+// the workdir — after Multica has already recorded the task as finished.
+// Reproduced against 2.0.10: with the client confirmed dead, a shell command the
+// agent had started went on to complete 35 seconds later.
+//
+// Best effort by construction. This runs in front of the existing termination
+// path and never replaces it, so an unreachable service, a session id that was
+// never observed, or a non-zero exit all degrade to exactly the behaviour
+// without it. It deliberately does not use the run's context: by the time this
+// is called that context is already cancelled, which is what triggered it.
+func opencodeInterruptSession(conn opencodeRunConnection, sessionID string, logger *slog.Logger) {
+ if sessionID == "" {
+ return
+ }
+ if conn.standalone {
+ // A private server dies with the process group below; interrupting the
+ // default service here would signal an unrelated session.
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), opencodeInterruptTimeout)
+ defer cancel()
+
+ args := []string{"api", "POST", "/api/session/" + sessionID + "/interrupt"}
+ if conn.server != "" {
+ args = append(args, "--server", conn.server)
+ }
+ cmd := conn.cmd.exec(ctx, args...)
+ hideAgentWindow(cmd)
+ // Same environment and working directory as the run, because that is what
+ // the CLI uses to find the default background service.
+ cmd.Env = conn.env
+ cmd.Dir = conn.dir
+ // combinedOutputOwned rather than cmd.CombinedOutput: the context timeout
+ // alone does not bound this call. CombinedOutput waits for EOF on the output
+ // pipes, and an `api` process that exits while a descendant still holds them
+ // keeps the read blocked — with the termination path behind it stuck too.
+ // runOwned puts the call in its own process tree, applies a WaitDelay to the
+ // pipe wait, and kills whatever is left.
+ out, err := combinedOutputOwned(cmd, logger)
+ if err != nil {
+ if logger != nil {
+ logger.Warn("opencode: session interrupt failed; the agent may keep running server-side",
+ "session", sessionID, "server", conn.server, "error", err, "output", strings.TrimSpace(string(out)))
+ }
+ return
+ }
+ if logger != nil {
+ logger.Info("opencode: session interrupted", "session", sessionID, "server", conn.server)
+ }
+}
diff --git a/server/pkg/agent/opencode_v2_test.go b/server/pkg/agent/opencode_v2_test.go
new file mode 100644
index 0000000000..2a22caeac7
--- /dev/null
+++ b/server/pkg/agent/opencode_v2_test.go
@@ -0,0 +1,614 @@
+package agent
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+// TestOpencodeUsesV2Contract pins which version strings switch the backend onto
+// the 2.x argv. The shapes matter: extractVersionLine keeps the whole matched
+// line, and 2.x reports `opencode v2.0.10` where 1.x reports a bare `1.18.31`,
+// so a prefix test against "2." would miss every real 2.x runtime.
+func TestOpencodeUsesV2Contract(t *testing.T) {
+ t.Parallel()
+
+ cases := []struct {
+ name string
+ version string
+ builtin bool
+ want bool
+ }{
+ {"v2 as reported by the real CLI", "opencode v2.0.10", true, true},
+ {"v2 bare semver", "2.0.10", true, true},
+ {"v2 with leading v", "v2.1.0", true, true},
+ {"future major", "opencode v3.0.0", true, true},
+ {"v1 bare semver as reported by the real CLI", "1.18.31", true, false},
+ {"v1 oldest supported", "1.1.54", true, false},
+ {"unknown version fails closed onto 1.x", "", true, false},
+ {"unparsable version fails closed onto 1.x", "opencode nightly", true, false},
+ // A custom runtime profile wraps a binary this package did not choose,
+ // so its version string does not establish the usage convention. Acting
+ // on it would break working 1.x profiles on a guess.
+ {"custom runtime never switches", "opencode v2.0.10", false, false},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ cfg := Config{CLIVersion: tc.version, BuiltinRuntime: tc.builtin}
+ if got := opencodeUsesV2Contract(cfg); got != tc.want {
+ t.Fatalf("opencodeUsesV2Contract(%q, builtin=%v) = %v, want %v",
+ tc.version, tc.builtin, got, tc.want)
+ }
+ })
+ }
+}
+
+// TestOpencodeModelArg covers folding the thinking level into the model string,
+// which is how 2.x expresses what 1.x passed as `--variant`.
+func TestOpencodeModelArg(t *testing.T) {
+ t.Parallel()
+
+ cases := []struct {
+ name string
+ model string
+ thinkingLevel string
+ wantModel string
+ wantOK bool
+ }{
+ {"no thinking level leaves the model alone", "anthropic/claude-sonnet-4-5", "", "anthropic/claude-sonnet-4-5", true},
+ {"level folds onto the model", "anthropic/claude-sonnet-4-5", "high", "anthropic/claude-sonnet-4-5#high", true},
+ {"neither set", "", "", "", true},
+ // 2.x resolves the default model server-side, so there is no model
+ // string to attach the variant to and the level cannot be expressed.
+ {"level without a model is not representable", "", "high", "", false},
+ // An explicitly pinned variant wins rather than growing a second '#',
+ // which OpenCode would reject.
+ {"explicit variant on the model wins", "anthropic/claude-sonnet-4-5#max", "high", "anthropic/claude-sonnet-4-5#max", true},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ gotModel, gotOK := opencodeModelArg(tc.model, tc.thinkingLevel)
+ if gotModel != tc.wantModel || gotOK != tc.wantOK {
+ t.Fatalf("opencodeModelArg(%q, %q) = (%q, %v), want (%q, %v)",
+ tc.model, tc.thinkingLevel, gotModel, gotOK, tc.wantModel, tc.wantOK)
+ }
+ })
+ }
+}
+
+const testMCPConfig = `{"mcpServers":{"probe":{"command":"node","args":["probe.js"]}}}`
+
+// TestOpencodeCheckMCPSupport pins the refusal. 2.x has no channel that can
+// carry MCP credentials without putting them where the agent can commit them,
+// so a configured run fails instead of quietly starting without its servers.
+func TestOpencodeCheckMCPSupport(t *testing.T) {
+ t.Parallel()
+
+ cases := []struct {
+ name string
+ raw string
+ wantErr bool
+ }{
+ {"no mcp config", "", false},
+ {"empty object asks for nothing", `{"mcpServers":{}}`, false},
+ {"configured servers are refused", testMCPConfig, true},
+ {"native opencode shape is refused too", `{"mcp":{"probe":{"type":"local","command":["x"]}}}`, true},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ var raw json.RawMessage
+ if tc.raw != "" {
+ raw = json.RawMessage(tc.raw)
+ }
+ err := opencodeCheckMCPSupport(raw)
+ if tc.wantErr {
+ if !errors.Is(err, ErrOpenCodeV2MCPUnsupported) {
+ t.Fatalf("expected ErrOpenCodeV2MCPUnsupported, got %v", err)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+ })
+ }
+}
+
+// TestOpencodeV2ExecuteRefusesMCPConfig is the end-to-end half: the run must
+// fail before anything starts, and nothing may be written into the workdir —
+// that file is the whole reason MCP is refused here.
+func TestOpencodeV2ExecuteRefusesMCPConfig(t *testing.T) {
+ t.Parallel()
+
+ tempDir := t.TempDir()
+ marker := filepath.Join(tempDir, "started.txt")
+ fakePath := filepath.Join(tempDir, "opencode")
+ writeTestExecutable(t, fakePath, []byte("#!/bin/sh\ntouch \""+marker+"\"\n"))
+
+ workDir := t.TempDir()
+
+ backend, err := New("opencode", Config{
+ ExecutablePath: fakePath,
+ CLIVersion: "opencode v2.0.10",
+ BuiltinRuntime: true,
+ Logger: slog.Default(),
+ })
+ if err != nil {
+ t.Fatalf("new opencode backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ _, execErr := backend.Execute(ctx, "prompt-ignored", ExecOptions{
+ Cwd: workDir,
+ McpConfig: json.RawMessage(testMCPConfig),
+ Timeout: 5 * time.Second,
+ })
+ if !errors.Is(execErr, ErrOpenCodeV2MCPUnsupported) {
+ t.Fatalf("expected the run to be refused, got %v", execErr)
+ }
+
+ if _, err := os.Stat(marker); !os.IsNotExist(err) {
+ t.Fatalf("refused run still started the CLI, stat err = %v", err)
+ }
+ if _, err := os.Stat(filepath.Join(workDir, "opencode.json")); !os.IsNotExist(err) {
+ t.Fatalf("refused run still wrote a config into the workdir, stat err = %v", err)
+ }
+}
+
+// TestOpencodeV1StillDeliversMCPConfig guards the other side of the refusal:
+// 1.x is unaffected and still projects mcp_config through its env channel.
+func TestOpencodeV1StillDeliversMCPConfig(t *testing.T) {
+ t.Parallel()
+
+ tempDir := t.TempDir()
+ envFile := filepath.Join(tempDir, "env.txt")
+ fakePath := filepath.Join(tempDir, "opencode")
+ script := "#!/bin/sh\ncat > /dev/null\nprintf '%s\\n' \"$OPENCODE_CONFIG_CONTENT\" > \"" + envFile + "\"\n" +
+ "printf '{\"type\":\"step_start\",\"sessionID\":\"ses\",\"part\":{}}\\n'\n" +
+ "printf '{\"type\":\"step_finish\",\"sessionID\":\"ses\",\"part\":{}}\\n'\n"
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ backend, err := New("opencode", Config{
+ ExecutablePath: fakePath,
+ CLIVersion: "1.18.31",
+ BuiltinRuntime: true,
+ Logger: slog.Default(),
+ })
+ if err != nil {
+ t.Fatalf("new opencode backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{
+ Cwd: t.TempDir(),
+ McpConfig: json.RawMessage(testMCPConfig),
+ Timeout: 5 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("1.x must still accept mcp_config: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+ <-session.Result
+
+ got, err := os.ReadFile(envFile)
+ if err != nil {
+ t.Fatalf("read env capture: %v", err)
+ }
+ if !strings.Contains(string(got), "probe") {
+ t.Fatalf("1.x lost its MCP env injection: %q", got)
+ }
+}
+
+// TestOpencodeV2ArgvOmitsDirAndFoldsVariant is the end-to-end regression for
+// GH #8586: on a 2.x runtime the daemon must not pass `--dir` (the CLI rejects
+// the unknown flag and the run dies before it starts) and must express the
+// thinking level through the model string instead of `--variant`.
+func TestOpencodeV2ArgvOmitsDirAndFoldsVariant(t *testing.T) {
+ t.Parallel()
+
+ tempDir := t.TempDir()
+ argsFile := filepath.Join(tempDir, "argv.txt")
+ pwdFile := filepath.Join(tempDir, "pwd.txt")
+ fakePath := filepath.Join(tempDir, "opencode")
+ writeTestExecutable(t, fakePath, []byte(fakeOpencodeScript()))
+
+ workDir := t.TempDir()
+
+ backend, err := New("opencode", Config{
+ ExecutablePath: fakePath,
+ CLIVersion: "opencode v2.0.10",
+ BuiltinRuntime: true,
+ Logger: slog.Default(),
+ Env: map[string]string{
+ "OPENCODE_ARGS_FILE": argsFile,
+ "OPENCODE_PWD_FILE": pwdFile,
+ },
+ })
+ if err != nil {
+ t.Fatalf("new opencode backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{
+ Cwd: workDir,
+ Model: "anthropic/claude-sonnet-4-5",
+ ThinkingLevel: "high",
+ Timeout: 5 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+ <-session.Result
+
+ raw, err := os.ReadFile(argsFile)
+ if err != nil {
+ t.Fatalf("read args file: %v", err)
+ }
+ args := strings.Split(strings.TrimSpace(string(raw)), "\n")
+
+ if containsString(args, "--dir") {
+ t.Fatalf("2.x argv must not carry --dir, got %q", args)
+ }
+ if containsString(args, "--variant") {
+ t.Fatalf("2.x argv must not carry --variant, got %q", args)
+ }
+ if !containsString(args, "anthropic/claude-sonnet-4-5#high") {
+ t.Fatalf("expected the thinking level folded into the model string, got %q", args)
+ }
+
+ // Dropping --dir is only safe because cwd still anchors discovery, so the
+ // PWD the child sees must remain the task workdir.
+ gotPWD, err := os.ReadFile(pwdFile)
+ if err != nil {
+ t.Fatalf("read PWD file: %v", err)
+ }
+ if strings.TrimSpace(string(gotPWD)) != workDir {
+ t.Fatalf("expected PWD %q, got %q", workDir, strings.TrimSpace(string(gotPWD)))
+ }
+}
+
+// TestOpencodeV1ArgvKeepsDirAndVariant is the other half of the contract: the
+// 1.x path is what every existing runtime uses and must not shift.
+func TestOpencodeV1ArgvKeepsDirAndVariant(t *testing.T) {
+ t.Parallel()
+
+ tempDir := t.TempDir()
+ argsFile := filepath.Join(tempDir, "argv.txt")
+ fakePath := filepath.Join(tempDir, "opencode")
+ writeTestExecutable(t, fakePath, []byte(fakeOpencodeScript()))
+
+ workDir := t.TempDir()
+
+ backend, err := New("opencode", Config{
+ ExecutablePath: fakePath,
+ CLIVersion: "1.18.31",
+ BuiltinRuntime: true,
+ Logger: slog.Default(),
+ Env: map[string]string{"OPENCODE_ARGS_FILE": argsFile},
+ })
+ if err != nil {
+ t.Fatalf("new opencode backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{
+ Cwd: workDir,
+ Model: "anthropic/claude-sonnet-4-5",
+ ThinkingLevel: "high",
+ Timeout: 5 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+ <-session.Result
+
+ raw, err := os.ReadFile(argsFile)
+ if err != nil {
+ t.Fatalf("read args file: %v", err)
+ }
+ args := strings.Split(strings.TrimSpace(string(raw)), "\n")
+
+ if !containsString(args, "--dir") {
+ t.Fatalf("1.x argv must still carry --dir, got %q", args)
+ }
+ if !containsString(args, "--variant") {
+ t.Fatalf("1.x argv must still carry --variant, got %q", args)
+ }
+ if containsString(args, "anthropic/claude-sonnet-4-5#high") {
+ t.Fatalf("1.x must not fold the variant into the model, got %q", args)
+ }
+}
+
+func TestOpencodeConnectionFromArgs(t *testing.T) {
+ t.Parallel()
+
+ cases := []struct {
+ name string
+ args []string
+ wantServer string
+ wantStandalone bool
+ }{
+ {"nothing", []string{"run", "--format", "json"}, "", false},
+ {"separate value", []string{"run", "--server", "http://127.0.0.1:4096"}, "http://127.0.0.1:4096", false},
+ {"inline value", []string{"run", "--server=http://127.0.0.1:4096"}, "http://127.0.0.1:4096", false},
+ {"standalone", []string{"run", "--standalone"}, "", true},
+ {"trailing --server with no value is ignored", []string{"run", "--server"}, "", false},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ server, standalone := opencodeConnectionFromArgs(tc.args)
+ if server != tc.wantServer || standalone != tc.wantStandalone {
+ t.Fatalf("opencodeConnectionFromArgs(%q) = (%q, %v), want (%q, %v)",
+ tc.args, server, standalone, tc.wantServer, tc.wantStandalone)
+ }
+ })
+ }
+}
+
+// TestOpencodeSessionTracker covers the handoff the cancellation path depends
+// on, including the nil receiver every direct-processEvents test relies on.
+func TestOpencodeSessionTracker(t *testing.T) {
+ t.Parallel()
+
+ var nilTracker *opencodeSessionTracker
+ nilTracker.set("ses_ignored") // must not panic
+ if got := nilTracker.get(); got != "" {
+ t.Fatalf("nil tracker should report no session, got %q", got)
+ }
+
+ tracker := &opencodeSessionTracker{}
+ tracker.set("")
+ if got := tracker.get(); got != "" {
+ t.Fatalf("empty session id must be ignored, got %q", got)
+ }
+ tracker.set("ses_first")
+ tracker.set("ses_second")
+ if got := tracker.get(); got != "ses_first" {
+ t.Fatalf("tracker should keep the first session id, got %q", got)
+ }
+}
+
+// TestOpencodeProcessEventsPublishesSession pins that the scanner hands the
+// session id to the tracker. Without it the cancellation path has no id to
+// interrupt and a cancelled 2.x run keeps going server-side.
+func TestOpencodeProcessEventsPublishesSession(t *testing.T) {
+ t.Parallel()
+
+ b := &opencodeBackend{cfg: Config{Logger: slog.Default()}, session: &opencodeSessionTracker{}}
+ ch := make(chan Message, 8)
+ lines := `{"type":"step_start","timestamp":1,"sessionID":"ses_abc","part":{}}` + "\n" +
+ `{"type":"step_finish","timestamp":2,"sessionID":"ses_abc","part":{}}` + "\n"
+
+ go func() {
+ b.processEvents(strings.NewReader(lines), ch)
+ close(ch)
+ }()
+ for range ch {
+ }
+
+ if got := b.session.get(); got != "ses_abc" {
+ t.Fatalf("expected the scanner to publish the session id, got %q", got)
+ }
+}
+
+func TestOpencodeInterruptSessionWithoutSessionIsNoop(t *testing.T) {
+ t.Parallel()
+
+ tempDir := t.TempDir()
+ marker := filepath.Join(tempDir, "called.txt")
+ fakePath := filepath.Join(tempDir, "opencode")
+ writeTestExecutable(t, fakePath, []byte("#!/bin/sh\ntouch \""+marker+"\"\n"))
+
+ opencodeInterruptSession(opencodeRunConnection{cmd: NewCommand(fakePath, nil)}, "", slog.Default())
+
+ if _, err := os.Stat(marker); !os.IsNotExist(err) {
+ t.Fatalf("interrupt must not run the CLI without a session id, stat err = %v", err)
+ }
+}
+
+// TestOpencodeInterruptSessionStandaloneIsNoop: a private server is a child of
+// the client, so the process-group signalling already stops it. Interrupting the
+// default service here would signal an unrelated session.
+func TestOpencodeInterruptSessionStandaloneIsNoop(t *testing.T) {
+ t.Parallel()
+
+ tempDir := t.TempDir()
+ marker := filepath.Join(tempDir, "called.txt")
+ fakePath := filepath.Join(tempDir, "opencode")
+ writeTestExecutable(t, fakePath, []byte("#!/bin/sh\ntouch \""+marker+"\"\n"))
+
+ conn := opencodeRunConnection{cmd: NewCommand(fakePath, nil), standalone: true}
+ opencodeInterruptSession(conn, "ses_abc", slog.Default())
+
+ if _, err := os.Stat(marker); !os.IsNotExist(err) {
+ t.Fatalf("interrupt must not run for a standalone run, stat err = %v", err)
+ }
+}
+
+// TestOpencodeInterruptSessionUsesRunConnection pins that the interrupt reaches
+// the same service the run used. A run launched against `--server <url>` whose
+// interrupt goes to the default background service reports success while the
+// real session keeps working.
+func TestOpencodeInterruptSessionUsesRunConnection(t *testing.T) {
+ t.Parallel()
+
+ tempDir := t.TempDir()
+ capture := filepath.Join(tempDir, "capture.txt")
+ fakePath := filepath.Join(tempDir, "opencode")
+ script := "#!/bin/sh\n" +
+ "{ printf 'env=%s\\n' \"$MULTICA_TEST_ENV\"; printf 'cwd=%s\\n' \"$PWD\"; " +
+ "for arg in \"$@\"; do printf '%s\\n' \"$arg\"; done; } > \"" + capture + "\"\n"
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ workDir := t.TempDir()
+ conn := opencodeRunConnection{
+ cmd: NewCommand(fakePath, nil),
+ server: "http://127.0.0.1:54321",
+ env: []string{"MULTICA_TEST_ENV=task-marker"},
+ dir: workDir,
+ }
+ opencodeInterruptSession(conn, "ses_abc", slog.Default())
+
+ raw, err := os.ReadFile(capture)
+ if err != nil {
+ t.Fatalf("read capture: %v", err)
+ }
+ got := string(raw)
+
+ // The shell reports $PWD with symlinks resolved, which on macOS turns
+ // /tmp into /private/tmp.
+ wantCwd := workDir
+ if resolved, err := filepath.EvalSymlinks(workDir); err == nil {
+ wantCwd = resolved
+ }
+
+ for _, want := range []string{
+ "api", "POST", "/api/session/ses_abc/interrupt",
+ "--server", "http://127.0.0.1:54321",
+ "env=task-marker",
+ "cwd=" + wantCwd,
+ } {
+ if !strings.Contains(got, want) {
+ t.Fatalf("interrupt lost %q from the run connection:\n%s", want, got)
+ }
+ }
+}
+
+// TestOpencodeInterruptSessionBoundsPipeWait: CombinedOutput waits for EOF on
+// the output pipes, so an `api` process that exits while a descendant still
+// holds them would block the termination path behind this call indefinitely.
+func TestOpencodeInterruptSessionBoundsPipeWait(t *testing.T) {
+ t.Parallel()
+
+ tempDir := t.TempDir()
+ fakePath := filepath.Join(tempDir, "opencode")
+ // Exits immediately but leaves a descendant holding stdout/stderr.
+ writeTestExecutable(t, fakePath, []byte("#!/bin/sh\nsleep 7 &\nexit 0\n"))
+
+ start := time.Now()
+ opencodeInterruptSession(opencodeRunConnection{cmd: NewCommand(fakePath, nil)}, "ses_abc", slog.Default())
+ if elapsed := time.Since(start); elapsed > opencodeInterruptTimeout+time.Second {
+ t.Fatalf("interrupt exceeded its bound waiting for descendant pipe EOF: %s", elapsed)
+ }
+}
+
+// TestOpencodeInterruptSessionSurvivesFailure keeps the call best-effort: a
+// service that is gone or answers non-zero must not stop the caller, because
+// the process-group signalling behind it is what the 1.x path always relied on.
+func TestOpencodeInterruptSessionSurvivesFailure(t *testing.T) {
+ t.Parallel()
+
+ tempDir := t.TempDir()
+ fakePath := filepath.Join(tempDir, "opencode")
+ writeTestExecutable(t, fakePath, []byte("#!/bin/sh\necho 'connection refused' >&2\nexit 1\n"))
+
+ opencodeInterruptSession(opencodeRunConnection{cmd: NewCommand(fakePath, nil)}, "ses_abc", slog.Default())
+}
+
+// TestOpencodeV2CancelInterruptsThroughRunConnection is the end-to-end version
+// of the connection test: it proves Execute actually threads the run's server
+// selection, environment and workdir into the interrupt. A unit test on
+// opencodeInterruptSession alone would keep passing if that wiring regressed,
+// and the failure mode is quiet — the interrupt reports success against the
+// default service while the real session keeps working.
+func TestOpencodeV2CancelInterruptsThroughRunConnection(t *testing.T) {
+ t.Parallel()
+
+ tempDir := t.TempDir()
+ capture := filepath.Join(tempDir, "interrupt.txt")
+ fakePath := filepath.Join(tempDir, "opencode")
+ // `api` invocations record their context; `run` streams one event and then
+ // blocks so the test can cancel it mid-flight.
+ script := "#!/bin/sh\n" +
+ "if [ \"$1\" = \"api\" ]; then\n" +
+ " { printf 'env=%s\\n' \"$MULTICA_TEST_ENV\"; for arg in \"$@\"; do printf '%s\\n' \"$arg\"; done; } > \"" + capture + "\"\n" +
+ " exit 0\n" +
+ "fi\n" +
+ "cat > /dev/null\n" +
+ "printf '{\"type\":\"text\",\"sessionID\":\"ses_live\",\"part\":{\"type\":\"text\",\"text\":\"ready\"}}\\n'\n" +
+ "while :; do sleep 1; done\n"
+ writeTestExecutable(t, fakePath, []byte(script))
+
+ backend, err := New("opencode", Config{
+ ExecutablePath: fakePath,
+ CLIVersion: "opencode v2.0.10",
+ BuiltinRuntime: true,
+ Logger: slog.Default(),
+ Env: map[string]string{"MULTICA_TEST_ENV": "task-marker"},
+ })
+ if err != nil {
+ t.Fatalf("new opencode backend: %v", err)
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ workDir := t.TempDir()
+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{
+ Cwd: workDir,
+ Timeout: 20 * time.Second,
+ CustomArgs: []string{"--server", "http://127.0.0.1:54321"},
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+
+ select {
+ case <-session.Messages:
+ case <-time.After(10 * time.Second):
+ t.Fatal("fake CLI never became ready")
+ }
+
+ cancel()
+ for range session.Messages {
+ }
+ <-session.Result
+
+ raw, err := os.ReadFile(capture)
+ if err != nil {
+ t.Fatalf("cancelling a 2.x run did not interrupt the session: %v", err)
+ }
+ got := string(raw)
+ for _, want := range []string{
+ "/api/session/ses_live/interrupt",
+ "--server", "http://127.0.0.1:54321",
+ "env=task-marker",
+ } {
+ if !strings.Contains(got, want) {
+ t.Fatalf("cancel lost %q from the run connection:\n%s", want, got)
+ }
+ }
+}