Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent): deliver the OpenCode prompt on stdin, not argv (MUL-5841) (#6552)
Bohan Jiang3c7221492bf7
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex b57157f94c..ca1e7258ee 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -343,6 +343,22 @@ jobs:# that stops matching) is visible in the log instead of passing as "ok".run: go test ./pkg/agent -v -run '^(TestCursorExecutePromptSurvivesPowerShellShim|TestPiExecutePromptSurvivesPowerShellShim|TestPlatformCursorInvocation|TestPlatformCopilotInvocation|TestPlatformPiInvocation)' -count=1 -timeout=5m+ - name: Test Windows OpenCode oversized prompt reaches stdin+ working-directory: server+ # #6538: the daemon inlined the whole task prompt as an argv element,+ # so every OpenCode task whose prompt cleared CreateProcess's 32,767+ # character lpCommandLine limit failed to start at all, with Go+ # reporting ERROR_FILENAME_EXCED_RANGE as the misleading "The filename+ # or extension is too long". Only a real CreateProcess enforces that+ # ceiling, so this cannot run in the ubuntu backend job. The test+ # spawns a native .exe directly (a Chocolatey-installed opencode.exe is+ # a real PE binary, not a .cmd shim) with an oversized prompt and pins+ # that the process starts, argv stays free of the prompt, and the full+ # payload arrives on stdin.+ # -v so a silent skip or a -run pattern that stops matching is visible+ # in the log instead of passing as "ok".+ run: go test ./pkg/agent -v -run '^TestOpencodeExecuteOversizedPromptStartsOnWindows$' -count=1 -timeout=5m+- name: Test bounded Codex cleanup with inherited stdout descendantworking-directory: server# Windows cannot prove whole-tree termination without a Job Object,diff --git a/server/pkg/agent/claude_deadlock_test.go b/server/pkg/agent/claude_deadlock_test.goindex afb87cc293..886a62edaf 100644--- a/server/pkg/agent/claude_deadlock_test.go+++ b/server/pkg/agent/claude_deadlock_test.go@@ -15,7 +15,15 @@ import (// TestMain intercepts when the test binary is re-executed as a fake// child process by the agent backend. The fake's behavior is selected via// CLAUDE_FAKE_MODE; absent that env var, this is a normal `go test` run.+//+// Dispatching here rather than from a Test function is what lets a fake be+// invoked with a real agent CLI's argv: TestMain runs before the testing+// package parses flags, so arguments like `run --format json` never reach it.func TestMain(m *testing.M) {+ if os.Getenv(opencodeStdinHelperEnv) == "1" {+ runFakeOpencodeStdinHelper()+ os.Exit(0)+ }switch mode := os.Getenv("CLAUDE_FAKE_MODE"); mode {case "":os.Exit(m.Run())diff --git a/server/pkg/agent/opencode.go b/server/pkg/agent/opencode.goindex 970064376d..a711a469d2 100644--- a/server/pkg/agent/opencode.go+++ b/server/pkg/agent/opencode.go@@ -10,6 +10,7 @@ import ("path/filepath""runtime""strings"+ "sync""sync/atomic""syscall""time"@@ -97,7 +98,16 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecOargs = append(args, "--session", opts.ResumeSessionID)}args = append(args, filterCustomArgs(opts.CustomArgs, opencodeBlockedArgs, b.cfg.Logger)...)- args = append(args, prompt)+ // The task prompt is delivered on stdin, never argv — see the StdinPipe+ // wiring below. `opencode run` merges its variadic [message..] positional+ // with whatever is piped in, so an invocation that passes no positional+ // makes the piped text the entire run message. Inlining it instead fails+ // hard on Windows: CreateProcess caps lpCommandLine at 32,767 characters+ // (8,191 when a .cmd shim routes the call through cmd.exe), and a prompt+ // carrying the workspace's models and skills clears that on its own — the+ // process then never starts and Go surfaces the misleading "The filename or+ // extension is too long" (#6538). Keeping the prompt off argv also stops it+ // from being echoed into the "agent command" log line below.cmd := exec.CommandContext(runCtx, execPath, args...)hideAgentWindow(cmd)@@ -113,7 +123,7 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecO// signalled. Returning nil here keeps os/exec from racing us with its own// kill; WaitDelay remains the hard backstop.cmd.Cancel = func() error { return nil }- b.cfg.Logger.Info("agent command", "exec", execPath, "args", args)+ b.cfg.Logger.Info("agent command", "exec", execPath, "args", args, "prompt_bytes", len(prompt))cmd.WaitDelay = 10 * time.Secondif opts.Cwd != "" {cmd.Dir = opts.Cwd@@ -164,9 +174,17 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecOcancel()return nil, fmt.Errorf("opencode stdout pipe: %w", err)}+ stdin, err := cmd.StdinPipe()+ if err != nil {+ cancel()+ return nil, fmt.Errorf("opencode stdin pipe: %w", err)+ }+ var closeStdinOnce sync.Once+ closeStdin := func() { closeStdinOnce.Do(func() { _ = stdin.Close() }) }cmd.Stderr = newLogWriter(b.cfg.Logger, "[opencode:stderr] ")if err := cmd.Start(); err != nil {+ closeStdin()cancel()return nil, fmt.Errorf("start opencode: %w", err)}@@ -180,6 +198,19 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecO// skip a process that already exited and avoid signalling a dead pid.procDone := make(chan struct{})+ // Write the prompt from its own goroutine so it cannot deadlock against the+ // stdout reader below: a prompt larger than the OS pipe buffer (~64 KiB)+ // blocks mid-write until OpenCode drains it, and OpenCode cannot drain while+ // nobody is consuming its stdout. Closing stdin is what ends the prompt —+ // OpenCode reads it to EOF (`await Bun.stdin.text()`), so a stdin left open+ // hangs the run forever. Close on every path, success or error.+ writeErrCh := make(chan error, 1)+ go func() {+ _, err := io.WriteString(stdin, prompt)+ closeStdin()+ writeErrCh <- err+ }()+// On cancellation / timeout, terminate opencode (and the tool subprocesses// it spawned) BEFORE unblocking the scanner. The previous implementation// closed the stdout read end immediately, which left opencode writing into@@ -196,6 +227,10 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecOreturn // finished on its own; nothing to terminatecase <-runCtx.Done():}+ // Release a prompt write still blocked on a full stdin pipe — an+ // OpenCode that stopped reading before draining it would otherwise+ // strand that goroutine for the lifetime of the daemon.+ closeStdin()if cmd.Process != nil {signalProcessGroup(cmd.Process, syscall.SIGTERM)select {@@ -220,6 +255,10 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecOclose(procDone)duration := time.Since(startTime)+ // Wait closes the process pipes, so a prompt write still blocked when+ // OpenCode exited has returned by now. The writer sends exactly once.+ writeErr := <-writeErrCh+if runCtx.Err() == context.DeadlineExceeded {scanResult.status = "timeout"scanResult.errMsg = fmt.Sprintf("opencode timed out after %s", timeout)@@ -234,6 +273,25 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecO// the process exit detail so a mid-step crash still surfaces the// signal / exit code that killed it.scanResult.errMsg = fmt.Sprintf("%s; opencode exited with error: %v", scanResult.errMsg, exitErr)+ } else if writeErr != nil && !scanResult.sawTerminalSignal {+ // A failed prompt write is only benign once the run is PROVEN to have+ // finished: OpenCode reads stdin to EOF before it does any work, so a+ // run that reached a terminal signal necessarily received the whole+ // prompt, and an EPIPE recorded after that just means the pipe closed+ // on its way out — failing on it would discard a successful result.+ //+ // Absence of failure is not that proof. status starts at "completed"+ // and processEvents only fails closed on structural evidence, so a+ // child that emits nothing and exits 0 still reports "completed". If+ // the prompt never landed, that is precisely the run we must not pass+ // off as a clean success, so key on sawTerminalSignal instead.+ // Append rather than overwrite so the stream's own diagnosis survives.+ if scanResult.errMsg == "" {+ scanResult.errMsg = fmt.Sprintf("opencode prompt write failed: %v", writeErr)+ } else {+ scanResult.errMsg = fmt.Sprintf("%s; opencode prompt write failed: %v", scanResult.errMsg, writeErr)+ }+ scanResult.status = "failed"}b.cfg.Logger.Info("opencode finished", "pid", cmd.Process.Pid, "status", scanResult.status, "duration", duration.Round(time.Millisecond).String())@@ -273,6 +331,14 @@ type eventResult struct {sessionID stringusage TokenUsage // accumulated token usage across all stepsnoTerminalSignal bool // guard fired: the stream ended without evidence the run actually finished+ // sawTerminalSignal is positive evidence that the run actually finished: a+ // step_finish closed the last step with no continuation pending and with+ // something to show for it. It is NOT the negation of noTerminalSignal — a+ // stream with no events at all sets neither, because there is nothing to+ // fail closed on and nothing that proves completion either. Callers that+ // need "this run really completed" must test this field; status defaults to+ // "completed" and cannot carry that meaning on its own.+ sawTerminalSignal bool}// processEvents reads JSON lines from r, dispatches events to ch, and returns@@ -303,6 +369,7 @@ func (b *opencodeBackend) processEvents(r io.Reader, ch chan<- Message) eventResopenStep := false // between a step_start and its step_finishstepHasContinuationTool := false // current step has a local tool result OpenCode must feed backawaitingContinuation := false // the last step_finish still required another step+ sawStepFinish := false // at least one step closed; see eventResult.sawTerminalSignal// Step bracketing still misses a third shape: a step that opens and closes// cleanly while carrying nothing at all — no text, no tool call, and no@@ -360,6 +427,7 @@ func (b *opencodeBackend) processEvents(r io.Reader, ch chan<- Message) eventRestrySend(ch, Message{Type: MessageStatus, Status: "running"})case "step_finish":openStep = false+ sawStepFinish = trueawaitingContinuation = event.Part.Reason == "tool-calls" ||(event.Part.Reason != "" && stepHasContinuationTool)stepHasContinuationTool = false@@ -416,12 +484,13 @@ func (b *opencodeBackend) processEvents(r io.Reader, ch chan<- Message) eventRes}return eventResult{- status: finalStatus,- errMsg: finalError,- output: output.String(),- sessionID: sessionID,- usage: usage,- noTerminalSignal: noTerminalSignal,+ status: finalStatus,+ errMsg: finalError,+ output: output.String(),+ sessionID: sessionID,+ usage: usage,+ noTerminalSignal: noTerminalSignal,+ sawTerminalSignal: sawStepFinish && !noTerminalSignal,}}diff --git a/server/pkg/agent/opencode_mcp_test.go b/server/pkg/agent/opencode_mcp_test.goindex dd2456b557..1384a519be 100644--- a/server/pkg/agent/opencode_mcp_test.go+++ b/server/pkg/agent/opencode_mcp_test.go@@ -564,6 +564,7 @@ func TestOpencodeBackendOverridesUserOpenCodeConfigContent(t *testing.T) {// the child saw at exec time.func fakeOpencodeScriptCapturingEnv() string {return `#!/bin/sh+cat > /dev/nullif [ -n "$OPENCODE_CAPTURE_FILE" ]; then{printf 'OPENCODE_CONFIG_CONTENT=%s\n' "${OPENCODE_CONFIG_CONTENT-<unset>}"diff --git a/server/pkg/agent/opencode_stdin_helper_test.go b/server/pkg/agent/opencode_stdin_helper_test.gonew file mode 100644index 0000000000..096b75801d--- /dev/null+++ b/server/pkg/agent/opencode_stdin_helper_test.go@@ -0,0 +1,44 @@+package agent++import (+ "fmt"+ "io"+ "os"+ "strings"+)++// Env contract between the OpenCode stdin tests and the helper process they+// re-execute. The helper stands in for a natively-installed `opencode.exe`+// (the Chocolatey shim in #6538 is a real PE binary, not a .cmd wrapper), so+// the backend's argv reaches CreateProcess unmediated.+const (+ opencodeStdinHelperEnv = "MULTICA_OPENCODE_STDIN_HELPER"+ opencodeStdinHelperArgvFile = "MULTICA_OPENCODE_STDIN_HELPER_ARGV_FILE"+ opencodeStdinHelperInFile = "MULTICA_OPENCODE_STDIN_HELPER_STDIN_FILE"+)++// runFakeOpencodeStdinHelper records the argv and stdin the backend handed this+// process, then emits a successful OpenCode event stream. It is dispatched from+// TestMain before the testing flag parser runs, which is what lets the process+// be invoked with OpenCode's own argv (`run --format json ...`) instead of+// -test.* flags.+func runFakeOpencodeStdinHelper() {+ argv := strings.Join(os.Args[1:], "\n")+ if err := os.WriteFile(os.Getenv(opencodeStdinHelperArgvFile), []byte(argv), 0o644); err != nil {+ fmt.Fprintf(os.Stderr, "helper: write argv: %v\n", err)+ os.Exit(1)+ }+ stdin, err := io.ReadAll(os.Stdin)+ if err != nil {+ fmt.Fprintf(os.Stderr, "helper: read stdin: %v\n", err)+ os.Exit(1)+ }+ if err := os.WriteFile(os.Getenv(opencodeStdinHelperInFile), stdin, 0o644); err != nil {+ fmt.Fprintf(os.Stderr, "helper: write stdin: %v\n", err)+ os.Exit(1)+ }++ fmt.Println(`{"type":"step_start","timestamp":1,"sessionID":"ses_fake","part":{"type":"step-start"}}`)+ fmt.Println(`{"type":"text","timestamp":2,"sessionID":"ses_fake","part":{"type":"text","text":"ok"}}`)+ fmt.Println(`{"type":"step_finish","timestamp":3,"sessionID":"ses_fake","part":{"type":"step-finish"}}`)+}diff --git a/server/pkg/agent/opencode_stdin_unix_test.go b/server/pkg/agent/opencode_stdin_unix_test.gonew file mode 100644index 0000000000..876e3642c2--- /dev/null+++ b/server/pkg/agent/opencode_stdin_unix_test.go@@ -0,0 +1,307 @@+//go:build unix++package agent++import (+ "context"+ "fmt"+ "log/slog"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++// opencodeStreamTail is the minimal successful OpenCode event stream the fake+// CLIs below emit once they have recorded what the backend handed them.+const opencodeStreamTail = `printf '%s\n' '{"type":"step_start","timestamp":1,"sessionID":"ses_fake","part":{"type":"step-start"}}'+printf '%s\n' '{"type":"text","timestamp":2,"sessionID":"ses_fake","part":{"type":"text","text":"ok"}}'+printf '%s\n' '{"type":"step_finish","timestamp":3,"sessionID":"ses_fake","part":{"type":"step-finish"}}'+`++// opencodeStdinProbe runs the OpenCode backend against a fake CLI that records+// argv, drains stdin to EOF, and emits a successful OpenCode JSON stream.+func opencodeStdinProbe(t *testing.T, prompt string) ([]string, string, Result) {+ t.Helper()++ dir := t.TempDir()+ argvPath := filepath.Join(dir, "argv.txt")+ stdinPath := filepath.Join(dir, "stdin.txt")++ script := fmt.Sprintf("#!/bin/sh\n"++ ": > %[1]q\n"++ "for a in \"$@\"; do printf '%%s\\n' \"$a\" >> %[1]q; done\n"++ "cat > %[2]q\n", argvPath, stdinPath) + opencodeStreamTail++ fakePath := filepath.Join(dir, "opencode")+ writeTestExecutable(t, fakePath, []byte(script))++ backend, err := New("opencode", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("New(opencode): %v", err)+ }+ session, err := backend.Execute(t.Context(), prompt, ExecOptions{+ Timeout: 30 * time.Second,+ Model: "lanz/Lanz-Medium",+ })+ if err != nil {+ t.Fatalf("Execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()+ result := <-session.Result++ argvRaw, err := os.ReadFile(argvPath)+ if err != nil {+ t.Fatalf("read recorded argv: %v", err)+ }+ stdinRaw, err := os.ReadFile(stdinPath)+ if err != nil {+ t.Fatalf("read recorded stdin: %v", err)+ }+ argv := strings.Split(strings.TrimSuffix(string(argvRaw), "\n"), "\n")+ return argv, string(stdinRaw), result+}++// TestOpencodeExecuteSendsPromptOnStdinNotArgv is the regression for #6538.+// The daemon used to inline the whole task prompt as an argv element, which+// Windows CreateProcess rejects once the command line clears 32,767 characters.+// The prompt must now reach OpenCode byte-for-byte on stdin while argv keeps+// only the daemon's own flags.+func TestOpencodeExecuteSendsPromptOnStdinNotArgv(t *testing.T) {+ t.Parallel()++ prompt := "MULTICA_AGENT_BUILDER_INPUT\n" ++ "{\n" ++ ` "user_request": "专注本机 CPA 有关的所有工作",` + "\n" ++ ` "current_draft": {"instructions": "Run go build -ldflags \"-X main.version=foo\""},` + "\n" ++ ` "available_workspace_skills": [{"description": "- inspect local changes"}]` + "\n" ++ "}"++ argv, stdinGot, result := opencodeStdinProbe(t, prompt)++ if stdinGot != prompt {+ t.Errorf("prompt did not arrive on stdin intact:\n got %q\n want %q", stdinGot, prompt)+ }+ for _, arg := range argv {+ for _, needle := range []string{"MULTICA_AGENT_BUILDER_INPUT", "user_request", "-X", "inspect local"} {+ if strings.Contains(arg, needle) {+ t.Errorf("prompt fragment %q leaked into argv element %q; argv=%v", needle, arg, argv)+ }+ }+ }+ joined := strings.Join(argv, " ")+ for _, want := range []string{"run", "--format json", "--dangerously-skip-permissions", "--model lanz/Lanz-Medium"} {+ if !strings.Contains(joined, want) {+ t.Errorf("expected %q in argv, got %v", want, argv)+ }+ }+ if result.Status != "completed" || result.Output != "ok" {+ t.Fatalf("result = %+v, want completed with output ok", result)+ }+}++// TestOpencodeExecutePromptExceedingWindowsCommandLineLimit pins the exact+// shape reported in #6538: a prompt well past the 32,767-character Windows+// command-line ceiling. On the old argv path this could not even start the+// process on Windows; on stdin it is just bytes.+func TestOpencodeExecutePromptExceedingWindowsCommandLineLimit(t *testing.T) {+ t.Parallel()++ prompt := strings.Repeat("multica opencode workspace skill catalogue 0123456789\n", 800)+ if len(prompt) <= 32767 {+ t.Fatalf("test prompt must exceed the Windows command-line limit, got %d bytes", len(prompt))+ }++ _, stdinGot, result := opencodeStdinProbe(t, prompt)++ if stdinGot != prompt {+ t.Errorf("oversized prompt corrupted on stdin: got %d bytes, want %d", len(stdinGot), len(prompt))+ }+ if result.Status != "completed" {+ t.Fatalf("status = %q, want completed; error=%q", result.Status, result.Error)+ }+}++// TestOpencodeExecuteLargePromptDoesNotDeadlock forces both process pipes past+// capacity: the child floods stdout before reading stdin, while the parent+// writes a large prompt. Only concurrent writing and scanning can advance.+func TestOpencodeExecuteLargePromptDoesNotDeadlock(t *testing.T) {+ t.Parallel()++ dir := t.TempDir()+ stdinPath := filepath.Join(dir, "stdin.txt")+ script := fmt.Sprintf("#!/bin/sh\n"++ "yes '{\"type\":\"noise\",\"pad\":\"0123456789012345678901234567890123456789\"}' | head -n 8000\n"++ "cat > %[1]q\n", stdinPath) + opencodeStreamTail++ fakePath := filepath.Join(dir, "opencode")+ writeTestExecutable(t, fakePath, []byte(script))++ prompt := strings.Repeat("multica opencode stdin payload 0123456789\n", 16_384)+ if len(prompt) < 512*1024 {+ t.Fatalf("test prompt too small: %d bytes", len(prompt))+ }+ backend, err := New("opencode", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("New(opencode): %v", err)+ }+ session, err := backend.Execute(t.Context(), prompt, ExecOptions{Timeout: 30 * time.Second})+ if err != nil {+ t.Fatalf("Execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()+ result := <-session.Result++ stdinRaw, err := os.ReadFile(stdinPath)+ if err != nil {+ t.Fatalf("read recorded stdin: %v", err)+ }+ if string(stdinRaw) != prompt {+ t.Errorf("large stdin prompt corrupted: got %d bytes, want %d", len(stdinRaw), len(prompt))+ }+ if result.Status != "completed" {+ t.Fatalf("status = %q, want completed; error=%q", result.Status, result.Error)+ }+}++// TestOpencodeExecuteIgnoresBenignPromptWriteEPIPE pins that a run which+// produced a complete, successful stream is not failed by a prompt write that+// broke on the way out. A child exiting without draining stdin closes the read+// end under the concurrent write, so the parent sees EPIPE — and whether that+// lands before or after the child exits is pure timing. Reporting it as a+// failure makes the result load-dependent and throws away a good run.+func TestOpencodeExecuteIgnoresBenignPromptWriteEPIPE(t *testing.T) {+ t.Parallel()++ dir := t.TempDir()+ // A complete, successful stream from a child that never reads stdin.+ script := "#!/bin/sh\n" + opencodeStreamTail+ fakePath := filepath.Join(dir, "opencode")+ writeTestExecutable(t, fakePath, []byte(script))++ // Far larger than any pipe buffer, so the write cannot slip through before+ // the child exits: EPIPE here is deterministic, not incidental.+ prompt := strings.Repeat("benign epipe payload 0123456789\n", 40_000)++ backend, err := New("opencode", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("New(opencode): %v", err)+ }+ session, err := backend.Execute(t.Context(), prompt, ExecOptions{Timeout: 30 * time.Second})+ if err != nil {+ t.Fatalf("Execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()+ result := <-session.Result++ if result.Status != "completed" {+ t.Fatalf("status = %q, want completed; error=%q", result.Status, result.Error)+ }+ if result.Output != "ok" {+ t.Errorf("Output = %q, want %q", result.Output, "ok")+ }+}++// TestOpencodeExecuteFailsWhenPromptWriteBreaksAndStreamNeverStarted is the+// counterpart to the test above and guards the false-success it could+// otherwise create. processEvents starts at "completed" and only fails closed+// on structural evidence (an open step, or a step awaiting a continuation), so+// a child that emits NOTHING and exits 0 leaves that default untouched. If the+// prompt write also broke, suppressing it on the strength of that default+// would report a clean, empty success for a run whose prompt never landed.+//+// Suppression must therefore key on a positive terminal signal, not on the+// absence of a negative one.+func TestOpencodeExecuteFailsWhenPromptWriteBreaksAndStreamNeverStarted(t *testing.T) {+ t.Parallel()++ dir := t.TempDir()+ // Emits no events at all and exits 0 without reading stdin.+ fakePath := filepath.Join(dir, "opencode")+ writeTestExecutable(t, fakePath, []byte("#!/bin/sh\nexit 0\n"))++ // Large enough that the write cannot complete before the child exits.+ prompt := strings.Repeat("undelivered prompt payload 0123456789\n", 36_000)++ backend, err := New("opencode", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("New(opencode): %v", err)+ }+ session, err := backend.Execute(t.Context(), prompt, ExecOptions{Timeout: 30 * time.Second})+ if err != nil {+ t.Fatalf("Execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()+ result := <-session.Result++ if result.Status == "completed" {+ t.Fatalf("undelivered prompt reported as success: status=%q output=%q error=%q",+ result.Status, result.Output, result.Error)+ }+ if !strings.Contains(result.Error, "prompt write failed") {+ t.Errorf("error = %q, want it to name the failed prompt write", result.Error)+ }+}++// TestOpencodeExecuteCancelReleasesBlockedPromptWriter covers the cancellation+// half of the stdin contract: a child that never reads stdin leaves the prompt+// writer blocked on a full pipe. Cancelling must close stdin so that goroutine+// unwinds, and the run must still settle as aborted rather than hang.+func TestOpencodeExecuteCancelReleasesBlockedPromptWriter(t *testing.T) {+ t.Parallel()++ dir := t.TempDir()+ // Emit one event so the backend is streaming, then sleep without ever+ // draining stdin — the parent's prompt write wedges on a full pipe.+ script := "#!/bin/sh\n" ++ "printf '%s\\n' '{\"type\":\"step_start\",\"timestamp\":1,\"sessionID\":\"ses_fake\",\"part\":{\"type\":\"step-start\"}}'\n" ++ "sleep 60\n"+ fakePath := filepath.Join(dir, "opencode")+ writeTestExecutable(t, fakePath, []byte(script))++ prompt := strings.Repeat("blocked prompt payload 0123456789\n", 32_768)+ if len(prompt) < 1024*1024 {+ t.Fatalf("test prompt too small to fill the pipe buffer: %d bytes", len(prompt))+ }++ backend, err := New("opencode", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("New(opencode): %v", err)+ }+ // The fake CLI does not trap SIGTERM, so the group dies inside the grace+ // window; this test deliberately leaves opencodeTerminateGraceNanos alone so+ // it stays parallel-safe alongside the cancellation tests that do set it.+ ctx, cancel := context.WithCancel(context.Background())+ session, err := backend.Execute(ctx, prompt, ExecOptions{Timeout: 30 * time.Second})+ if err != nil {+ t.Fatalf("Execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ cancel()++ select {+ case result := <-session.Result:+ if result.Status != "aborted" {+ t.Fatalf("status = %q, want aborted; error=%q", result.Status, result.Error)+ }+ case <-time.After(30 * time.Second):+ t.Fatal("cancelled run never produced a result; the prompt writer likely deadlocked")+ }+}diff --git a/server/pkg/agent/opencode_stdin_windows_test.go b/server/pkg/agent/opencode_stdin_windows_test.gonew file mode 100644index 0000000000..799ca48522--- /dev/null+++ b/server/pkg/agent/opencode_stdin_windows_test.go@@ -0,0 +1,114 @@+//go:build windows++package agent++import (+ "log/slog"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++// TestOpencodeExecuteOversizedPromptStartsOnWindows is the platform regression+// for #6538. It crosses the boundary the bug lived on for real:+//+// Go os/exec -> CreateProcess -> native opencode.exe+//+// CreateProcess caps lpCommandLine at 32,767 characters and rejects anything+// longer with ERROR_FILENAME_EXCED_RANGE (206), which Go surfaces as the+// misleading "The filename or extension is too long". A prompt carrying a+// workspace's models and skills clears that ceiling on its own, so while the+// prompt was an argv element no such task could start at all. Delivering it on+// stdin removes the ceiling: the process must start, argv must stay free of the+// prompt, and the full payload must arrive on stdin byte-for-byte.+//+// No shim is involved — a Chocolatey-installed opencode.exe is a real PE+// binary, so this is the unmediated CreateProcess path.+func TestOpencodeExecuteOversizedPromptStartsOnWindows(t *testing.T) {+ t.Parallel()++ self, err := os.Executable()+ if err != nil {+ t.Fatalf("locate test binary: %v", err)+ }+ dir := t.TempDir()+ argvPath := filepath.Join(dir, "argv.txt")+ stdinPath := filepath.Join(dir, "stdin.txt")++ // Copy the test binary in as the native opencode.exe the backend spawns.+ fakePath := filepath.Join(dir, "opencode.exe")+ selfBytes, err := os.ReadFile(self)+ if err != nil {+ t.Fatalf("read test binary: %v", err)+ }+ writeTestExecutable(t, fakePath, selfBytes)++ // Past the 32,767-character CreateProcess ceiling, in the same shape as the+ // reported 39,629-byte agent-builder payload.+ prompt := "MULTICA_AGENT_BUILDER_INPUT\n" ++ strings.Repeat(`{"available_workspace_skills":[{"description":"- inspect local changes"}]}`+"\n", 600)+ if len(prompt) <= 32767 {+ t.Fatalf("test prompt must exceed the CreateProcess limit, got %d bytes", len(prompt))+ }++ backend, err := New("opencode", Config{+ ExecutablePath: fakePath,+ Logger: slog.Default(),+ Env: map[string]string{+ opencodeStdinHelperEnv: "1",+ opencodeStdinHelperArgvFile: argvPath,+ opencodeStdinHelperInFile: stdinPath,+ },+ })+ if err != nil {+ t.Fatalf("New(opencode): %v", err)+ }++ session, err := backend.Execute(t.Context(), prompt, ExecOptions{+ Timeout: 60 * time.Second,+ Model: "lanz/Lanz-Medium",+ })+ // Before the fix this is exactly where the run died, with+ // "start opencode: fork/exec ...: The filename or extension is too long".+ if err != nil {+ t.Fatalf("Execute failed to start the process with a %d-byte prompt: %v", len(prompt), err)+ }+ go func() {+ for range session.Messages {+ }+ }()+ result := <-session.Result++ stdinRaw, err := os.ReadFile(stdinPath)+ if err != nil {+ t.Fatalf("native child never recorded stdin: %v; result=%+v", err, result)+ }+ if string(stdinRaw) != prompt {+ t.Errorf("oversized prompt corrupted on stdin: got %d bytes, want %d", len(stdinRaw), len(prompt))+ }++ argvRaw, err := os.ReadFile(argvPath)+ if err != nil {+ t.Fatalf("native child never recorded argv: %v; result=%+v", err, result)+ }+ gotArgv := string(argvRaw)+ for _, needle := range []string{"MULTICA_AGENT_BUILDER_INPUT", "available_workspace_skills", "inspect local"} {+ if strings.Contains(gotArgv, needle) {+ t.Errorf("prompt fragment %q leaked into argv: %q", needle, gotArgv)+ }+ }+ if len(gotArgv) > 32767 {+ t.Errorf("argv is %d chars, still past the CreateProcess ceiling", len(gotArgv))+ }+ for _, want := range []string{"run", "--format", "json", "--dangerously-skip-permissions", "--model", "lanz/Lanz-Medium"} {+ if !strings.Contains(gotArgv, want) {+ t.Errorf("expected %q to reach the native child; argv=%q", want, gotArgv)+ }+ }++ if result.Status != "completed" || result.Output != "ok" {+ t.Fatalf("result = %+v, want completed with output ok", result)+ }+}diff --git a/server/pkg/agent/opencode_test.go b/server/pkg/agent/opencode_test.goindex 6c5e77a548..ed8c45f0c4 100644--- a/server/pkg/agent/opencode_test.go+++ b/server/pkg/agent/opencode_test.go@@ -1315,6 +1315,16 @@ if [ -n "$OPENCODE_ARGS_FILE" ]; thenprintf '%s\n' "$arg" >> "$OPENCODE_ARGS_FILE"donefi++# Real OpenCode reads stdin to EOF (await Bun.stdin.text()) before it does any+# work, so the fake must drain it too. A fake that exits without reading closes+# the read end under the daemon's concurrent prompt write, which surfaces as a+# spurious EPIPE whose timing depends on machine load.+if [ -n "$OPENCODE_STDIN_FILE" ]; then+ cat > "$OPENCODE_STDIN_FILE"+else+ cat > /dev/null+fiif [ -n "$OPENCODE_PWD_FILE" ]; thenprintf '%s\n' "$PWD" > "$OPENCODE_PWD_FILE"fi@@ -1436,6 +1446,7 @@ func TestOpencodeBackendNeverEmitsPromptFlag(t *testing.T) {tempDir := t.TempDir()argsFile := filepath.Join(tempDir, "argv.txt")+ stdinFile := filepath.Join(tempDir, "stdin.txt")fakePath := filepath.Join(tempDir, "opencode")writeTestExecutable(t, fakePath, []byte(fakeOpencodeScript()))@@ -1444,7 +1455,10 @@ func TestOpencodeBackendNeverEmitsPromptFlag(t *testing.T) {backend, err := New("opencode", Config{ExecutablePath: fakePath,Logger: slog.Default(),- Env: map[string]string{"OPENCODE_ARGS_FILE": argsFile},+ Env: map[string]string{+ "OPENCODE_ARGS_FILE": argsFile,+ "OPENCODE_STDIN_FILE": stdinFile,+ },})if err != nil {t.Fatalf("new opencode backend: %v", err)@@ -1480,9 +1494,16 @@ func TestOpencodeBackendNeverEmitsPromptFlag(t *testing.T) {if containsString(args, brief) {t.Errorf("SystemPrompt leaked into argv: %v", args)}- // The user prompt is still the final positional arg.- if len(args) == 0 || args[len(args)-1] != "do the thing" {- t.Errorf("expected prompt as final positional arg, got %v", args)+ // The user prompt travels on stdin, not argv (#6538).+ if containsString(args, "do the thing") {+ t.Errorf("user prompt leaked into argv: %v", args)+ }+ stdinRaw, err := os.ReadFile(stdinFile)+ if err != nil {+ t.Fatalf("read stdin file: %v", err)+ }+ if string(stdinRaw) != "do the thing" {+ t.Errorf("prompt did not arrive on stdin: got %q", string(stdinRaw))}}@@ -1720,6 +1741,7 @@ func TestOpencodeBackendBlocksDirOverride(t *testing.T) {// rescue the run; the unclosed step is what fails it.func fakeOpencodeMidToolScript() string {return `#!/bin/sh+cat > /dev/nullprintf '{"type":"step_start","timestamp":1,"sessionID":"ses_fake","part":{"type":"step-start"}}\n'printf '{"type":"tool_use","timestamp":2,"sessionID":"ses_fake","part":{"type":"tool","tool":"read","callID":"functions.read:1","state":{"status":"error","input":{"filePath":"/nope.md"},"error":"File not found"}}}\n'exit 0@@ -1774,6 +1796,7 @@ func TestOpencodeBackendFailsOnStreamEndingMidTool(t *testing.T) {// step_finish and no error event.func fakeOpencodeStepThenExit1Script() string {return `#!/bin/sh+cat > /dev/nullprintf '{"type":"step_start","timestamp":1,"sessionID":"ses_fake","part":{"type":"step-start"}}\n'exit 1`diff --git a/server/pkg/agent/pi_test.go b/server/pkg/agent/pi_test.goindex 4a2726b41b..1e3342e7fb 100644--- a/server/pkg/agent/pi_test.go+++ b/server/pkg/agent/pi_test.go@@ -200,6 +200,12 @@ func TestPiExecuteAttachesStdinPipe(t *testing.T) {func piEventStreamScript(events []string) string {var b strings.Builderb.WriteString("#!/bin/sh\n")+ // Real Pi reads the piped prompt to EOF before emitting events, so the fake+ // must drain stdin too. A fake that exits without reading closes the read end+ // while the backend is still writing the prompt, and the resulting EPIPE is+ // reported as "pi prompt write failed" — a load-dependent flake that has+ // nothing to do with what these tests assert.+ b.WriteString("cat > /dev/null\n")for _, e := range events {b.WriteString("printf '%s\\n' '")b.WriteString(e)