Skip to content

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

Go

MUL-5466 fix(agent): deliver the qwen prompt on stdin, not argv (#7343)

Danila Katalshovbdcb231ba004
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index be437d4b38..deb4fbeb7c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -616,7 +616,7 @@ jobs:
if: ${{ needs.changes.outputs.backend == 'true' }}
working-directory: server
# Agent prompts must never reach a Windows launcher through argv: the
- # official cursor-agent.ps1 and pi.ps1 launch native children with
+ # official cursor-agent.ps1, pi.ps1, and qwen.ps1 launch native children with
# `$args`, and PowerShell re-serialises them onto the child command
# line. Under
# Legacy native argument passing (powershell.exe 5.1, pwsh <= 7.2) a
@@ -627,7 +627,7 @@ jobs:
# the backend job still runs the full package on Linux.
# -v so a silent skip (no PowerShell host resolved, or a -run pattern
# 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
+ run: go test ./pkg/agent -v -run '^(TestCursorExecutePromptSurvivesPowerShellShim|TestPiExecutePromptSurvivesPowerShellShim|TestQwenExecutePromptSurvivesPowerShellShim|TestPlatformCursorInvocation|TestPlatformCopilotInvocation|TestPlatformPiInvocation|TestPlatformQwenInvocation)' -count=1 -timeout=5m
- name: Test Windows OpenCode oversized prompt reaches stdin
if: ${{ needs.changes.outputs.backend == 'true' }}
diff --git a/server/pkg/agent/qwen.go b/server/pkg/agent/qwen.go
index f8036dcb7f..ec17899134 100644
--- a/server/pkg/agent/qwen.go
+++ b/server/pkg/agent/qwen.go
@@ -4,15 +4,17 @@ import (
"context"
"encoding/json"
"fmt"
+ "io"
"log/slog"
"os/exec"
"strings"
+ "sync"
"time"
)
// qwenBackend drives Qwen Code's native non-interactive JSONL protocol:
-// qwen -p <prompt> --output-format stream-json. The event schema is based on
-// Qwen Code 0.20.0 captures in testdata/qwen-code-0.20.0-stream-json.jsonl.
+// qwen --output-format stream-json, prompt on stdin. The event schema is based
+// on Qwen Code 0.20.0 captures in testdata/qwen-code-0.20.0-stream-json.jsonl.
type qwenBackend struct {
cfg Config
}
@@ -45,8 +47,20 @@ var qwenBlockedArgs = map[string]blockedArgMode{
"--core-tools": blockedWithValue,
}
-func buildQwenArgs(prompt string, opts ExecOptions, logger *slog.Logger) []string {
- args := []string{"-p", prompt, "--output-format", "stream-json"}
+// buildQwenArgs assembles the argv for a one-shot qwen invocation.
+//
+// The prompt is deliberately NOT part of argv. Qwen Code's headless mode
+// reads a non-interactive prompt from stdin when none is given via -p, and
+// putting the (arbitrarily large, user-influenced) prompt text on the command
+// line is not safe on Windows: even after routing qwen.cmd through
+// qwen.ps1 directly (qwen_invocation_windows.go), PowerShell's own argument
+// re-serialisation does not survive a value containing embedded double quotes
+// — the same class of failure cursor-agent hit before it moved its prompt to
+// stdin (#5649). This is that fix's qwen equivalent (#6082). Only fixed,
+// content-free flags remain in argv; --mcp-config's payload also goes through
+// a temp file for the same reason, not inline JSON.
+func buildQwenArgs(opts ExecOptions, logger *slog.Logger) []string {
+ args := []string{"--output-format", "stream-json"}
if opts.Model != "" {
args = append(args, "--model", opts.Model)
}
@@ -64,16 +78,17 @@ func buildQwenArgs(prompt string, opts ExecOptions, logger *slog.Logger) []strin
}
func (b *qwenBackend) Execute(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {
- execPath := b.cfg.ExecutablePath
- if execPath == "" {
- execPath = "qwen"
+ execName := b.cfg.ExecutablePath
+ if execName == "" {
+ execName = "qwen"
}
- if _, err := exec.LookPath(execPath); err != nil {
- return nil, fmt.Errorf("qwen executable not found at %q: %w", execPath, err)
+ lookedUp, err := exec.LookPath(execName)
+ if err != nil {
+ return nil, fmt.Errorf("qwen executable not found at %q: %w", execName, err)
}
timeout := opts.Timeout
runCtx, cancel := runContext(ctx, timeout)
- args := buildQwenArgs(prompt, opts, b.cfg.Logger)
+ args := buildQwenArgs(opts, b.cfg.Logger)
// Qwen Code 0.20.0 accepts a JSON string or a file path through
// --mcp-config. Materialise a managed config into a 0600 temp file so it
@@ -96,9 +111,8 @@ func (b *qwenBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
mcpFileCleanup()
}
}()
- cmd := b.cfg.commandAt(execPath).exec(runCtx, args...)
+ cmd, _, _ := b.cfg.commandAt(execName).execVia(runCtx, chooseQwenInvocation, lookedUp, args, b.cfg.Logger)
hideAgentWindow(cmd)
- // args contain the task prompt; the shared logger preserves only flag names.
b.cfg.logAgentCommand(cmd, newAgentCommandLogArgs(args))
cmd.WaitDelay = 10 * time.Second
if opts.Cwd != "" {
@@ -111,9 +125,17 @@ func (b *qwenBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
cancel()
return nil, fmt.Errorf("qwen stdout pipe: %w", err)
}
+ stdin, err := cmd.StdinPipe()
+ if err != nil {
+ cancel()
+ return nil, fmt.Errorf("qwen stdin pipe: %w", err)
+ }
+ var closeStdinOnce sync.Once
+ closeStdin := func() { closeStdinOnce.Do(func() { _ = stdin.Close() }) }
stderrBuf := newStderrTail(newLogWriter(b.cfg.Logger, "[qwen:stderr] "), agentStderrTailBytes)
cmd.Stderr = stderrBuf
if err := cmd.Start(); err != nil {
+ closeStdin()
cancel()
return nil, fmt.Errorf("start qwen: %w", err)
}
@@ -121,6 +143,19 @@ func (b *qwenBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
mcpFileCleanup = nil
b.cfg.Logger.Info("qwen started", "pid", cmd.Process.Pid, "cwd", opts.Cwd, "model", opts.Model)
+ // The prompt is delivered on stdin (see buildQwenArgs). Write it from its
+ // own goroutine so it cannot deadlock against the stdout reader below: a
+ // prompt larger than the OS pipe buffer blocks mid-write until the child
+ // drains it, and the child cannot drain while we are not yet reading its
+ // stdout. Closing stdin is what signals end-of-prompt — qwen reads to
+ // EOF — so we always close, on both the success and error paths.
+ writeErrCh := make(chan error, 1)
+ go func() {
+ _, err := io.WriteString(stdin, prompt)
+ closeStdin()
+ writeErrCh <- err
+ }()
+
msgCh := make(chan Message, 256)
resCh := make(chan Result, 1)
go func() {
@@ -135,6 +170,10 @@ func (b *qwenBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
state := qwenStreamState{model: opts.Model, usage: make(map[string]TokenUsage)}
go func() {
<-runCtx.Done()
+ // Closing stdin releases a prompt write still blocked on a full pipe
+ // (e.g. the child died before draining it), so that goroutine cannot
+ // leak.
+ closeStdin()
_ = stdout.Close()
}()
@@ -160,7 +199,12 @@ func (b *qwenBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
exitErr := cmd.Wait()
duration := time.Since(started)
- status, output, errMsg := finalizeStreamResult("qwen", timeout, runCtx.Err(), nil, exitErr, state.sessionID, streamTerminalState{
+ // Wait has already closed the stdin pipe, so a prompt write still
+ // blocked on a full pipe has returned by now; the writer sends exactly
+ // once.
+ writeErr := <-writeErrCh
+
+ status, output, errMsg := finalizeStreamResult("qwen", timeout, runCtx.Err(), writeErr, exitErr, state.sessionID, streamTerminalState{
lastAssistantText: state.lastAssistantText,
finalResultText: state.finalResultText,
sawResult: state.sawResult,
diff --git a/server/pkg/agent/qwen_invocation.go b/server/pkg/agent/qwen_invocation.go
new file mode 100644
index 0000000000..737f9aa49b
--- /dev/null
+++ b/server/pkg/agent/qwen_invocation.go
@@ -0,0 +1,26 @@
+package agent
+
+import "log/slog"
+
+// chooseQwenInvocation selects the actual program (argv[0]) and the full argv
+// to spawn a Qwen Code run.
+//
+// Background:
+// - On macOS/Linux the npm-installed `qwen` binstub is a shebang script that
+// execs node with the JS entrypoint, so argv passes through unchanged.
+// - On Windows npm ships qwen.cmd instead. CreateProcess for a .cmd file goes
+// through cmd.exe, and %* in a .cmd batch file is expanded by re-tokenising
+// the original command line. To keep the stream protocol and custom flags
+// out of that re-tokenisation path, we resolve qwen.ps1 next to the .cmd and
+// invoke PowerShell with `-File <ps1>` directly, letting Go pass each argv
+// as a separate token. The task prompt itself is delivered through stdin
+// and never appears in argv (#6082).
+//
+// The Windows-specific behaviour is implemented in qwen_invocation_windows.go;
+// on other platforms we fall through to a passthrough.
+func chooseQwenInvocation(execName, lookedUp string, args []string, logger *slog.Logger) (string, []string) {
+ if argv0, full, ok := platformQwenInvocation(lookedUp, args, logger); ok {
+ return argv0, full
+ }
+ return execName, args
+}
diff --git a/server/pkg/agent/qwen_invocation_other.go b/server/pkg/agent/qwen_invocation_other.go
new file mode 100644
index 0000000000..3d629f2202
--- /dev/null
+++ b/server/pkg/agent/qwen_invocation_other.go
@@ -0,0 +1,12 @@
+//go:build !windows
+
+package agent
+
+import "log/slog"
+
+// platformQwenInvocation is a no-op on non-Windows platforms: Qwen Code's
+// binstub invokes node directly via shebang and Go's os/exec can pass argv
+// unchanged.
+func platformQwenInvocation(_ string, _ []string, _ *slog.Logger) (string, []string, bool) {
+ return "", nil, false
+}
diff --git a/server/pkg/agent/qwen_invocation_test.go b/server/pkg/agent/qwen_invocation_test.go
new file mode 100644
index 0000000000..cdc1ec909d
--- /dev/null
+++ b/server/pkg/agent/qwen_invocation_test.go
@@ -0,0 +1,74 @@
+package agent
+
+import (
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "io"
+ "log/slog"
+ "path/filepath"
+ "reflect"
+ "testing"
+)
+
+// TestChooseQwenInvocation_PassthroughForNonLauncher verifies that when the
+// resolved executable is not a Windows .cmd/.bat launcher, both argv[0] and
+// the argv list are returned unchanged on every platform. This guards against
+// accidental rewriting on macOS/Linux and for direct binary launches on
+// Windows.
+func TestChooseQwenInvocation_PassthroughForNonLauncher(t *testing.T) {
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+
+ execName := "qwen"
+ lookedUp := filepath.Join(t.TempDir(), "qwen") // no .cmd / .bat
+ args := []string{"--output-format", "stream-json", "--yolo"}
+
+ gotExec, gotArgs := chooseQwenInvocation(execName, lookedUp, args, logger)
+
+ if gotExec != execName {
+ t.Errorf("argv0 changed unexpectedly: got %q want %q", gotExec, execName)
+ }
+ if !reflect.DeepEqual(gotArgs, args) {
+ t.Errorf("argv changed unexpectedly:\n got %#v\n want %#v", gotArgs, args)
+ }
+}
+
+// TestQwenLaunchesThroughTheInvocationChooser pins the wiring half of #6082.
+// The chooser only protects a run that goes through it, and a qwen.go that
+// builds its process with Command.exec spawns the npm qwen.cmd launcher
+// directly again — every symptom returns while the Windows tests in
+// qwen_invocation_windows_test.go keep passing, because they exercise the
+// chooser rather than the backend. The assertion is on the source since the
+// two launch paths are indistinguishable at runtime on macOS/Linux, where the
+// chooser is a passthrough.
+func TestQwenLaunchesThroughTheInvocationChooser(t *testing.T) {
+ t.Parallel()
+
+ file, err := parser.ParseFile(token.NewFileSet(), "qwen.go", nil, 0)
+ if err != nil {
+ t.Fatalf("parse qwen.go: %v", err)
+ }
+
+ routed := false
+ ast.Inspect(file, func(n ast.Node) bool {
+ call, ok := n.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ sel, ok := call.Fun.(*ast.SelectorExpr)
+ if !ok || sel.Sel.Name != "execVia" {
+ return true
+ }
+ for _, arg := range call.Args {
+ if ident, ok := arg.(*ast.Ident); ok && ident.Name == "chooseQwenInvocation" {
+ routed = true
+ }
+ }
+ return true
+ })
+
+ if !routed {
+ t.Fatal("qwen.go must spawn through Command.execVia with chooseQwenInvocation; " +
+ "launching the resolved executable directly hands the managed argv back to cmd.exe re-tokenisation on Windows (GH #6082)")
+ }
+}
diff --git a/server/pkg/agent/qwen_invocation_windows.go b/server/pkg/agent/qwen_invocation_windows.go
new file mode 100644
index 0000000000..524e61e0bc
--- /dev/null
+++ b/server/pkg/agent/qwen_invocation_windows.go
@@ -0,0 +1,13 @@
+//go:build windows
+
+package agent
+
+import "log/slog"
+
+// platformQwenInvocation rewrites qwen.cmd → PowerShell -File qwen.ps1 on
+// Windows to avoid cmd.exe %* re-tokenisation of the managed argv (see #6082).
+// The prompt itself travels on stdin. rewriteCmdToPS1 is defined in
+// cursor_invocation_windows.go.
+func platformQwenInvocation(lookedUp string, args []string, logger *slog.Logger) (string, []string, bool) {
+ return rewriteCmdToPS1("qwen", lookedUp, args, logger)
+}
diff --git a/server/pkg/agent/qwen_invocation_windows_test.go b/server/pkg/agent/qwen_invocation_windows_test.go
new file mode 100644
index 0000000000..d0737836df
--- /dev/null
+++ b/server/pkg/agent/qwen_invocation_windows_test.go
@@ -0,0 +1,110 @@
+//go:build windows
+
+package agent
+
+import (
+ "io"
+ "log/slog"
+ "path/filepath"
+ "reflect"
+ "testing"
+)
+
+// TestPlatformQwenInvocation_RewritesCmdLauncherToPowerShellFile is the core
+// Windows test for #6082: when LookPath resolves qwen to the npm-generated
+// .cmd launcher and a sibling qwen.ps1 exists, we should invoke PowerShell
+// with -File <ps1> and forward every managed arg unchanged. The task prompt is
+// deliberately absent here because it is delivered on stdin.
+func TestPlatformQwenInvocation_RewritesCmdLauncherToPowerShellFile(t *testing.T) {
+ dir := t.TempDir()
+ cmdPath := filepath.Join(dir, "qwen.cmd")
+ ps1Path := filepath.Join(dir, "qwen.ps1")
+ writeFile(t, cmdPath, "@echo off\r\npowershell -NoProfile -ExecutionPolicy Bypass -File \"%~dp0qwen.ps1\" %*\r\n")
+ writeFile(t, ps1Path, "# fake qwen.ps1\r\n")
+
+ fakePS := filepath.Join(dir, "powershell.exe")
+ writeFile(t, fakePS, "")
+ stubPowerShell(t, fakePS, true)
+
+ args := []string{
+ "--output-format", "stream-json",
+ "--yolo",
+ }
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+
+ gotExec, gotArgs, ok := platformQwenInvocation(cmdPath, args, logger)
+ if !ok {
+ t.Fatalf("expected platform rewrite to be applied, got ok=false")
+ }
+ if gotExec != fakePS {
+ t.Errorf("argv0: got %q want %q", gotExec, fakePS)
+ }
+
+ wantArgs := append([]string{
+ "-NoProfile",
+ "-ExecutionPolicy", "Bypass",
+ "-File", ps1Path,
+ }, args...)
+ if !reflect.DeepEqual(gotArgs, wantArgs) {
+ t.Errorf("argv mismatch:\n got %#v\n want %#v", gotArgs, wantArgs)
+ }
+
+ // Without the protocol flags Qwen answers in plain text and the daemon
+ // never sees a stream-json result event.
+ if idx := prefixIndex(gotArgs, []string{"--output-format", "stream-json"}); idx < 0 {
+ t.Errorf("the stream-json protocol flags did not survive: %#v", gotArgs)
+ }
+}
+
+// TestPlatformQwenInvocation_SkipsWhenNotCmdOrBat ensures we leave argv alone
+// when qwen resolves to something that isn't a batch launcher (the npm
+// shebang binstub on macOS/Linux, or a real binary on Windows).
+func TestPlatformQwenInvocation_SkipsWhenNotCmdOrBat(t *testing.T) {
+ dir := t.TempDir()
+ exePath := filepath.Join(dir, "qwen.exe")
+ writeFile(t, exePath, "")
+ // A sibling .ps1 must not trick us into rewriting a non-launcher exec.
+ writeFile(t, filepath.Join(dir, "qwen.ps1"), "")
+
+ stubPowerShell(t, filepath.Join(dir, "powershell.exe"), true)
+
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ if _, _, ok := platformQwenInvocation(exePath, []string{"--output-format", "stream-json"}, logger); ok {
+ t.Fatalf("expected ok=false for non-.cmd/.bat launcher")
+ }
+}
+
+// TestPlatformQwenInvocation_SkipsWhenPS1Missing covers a partial install
+// where the .cmd was found but its companion .ps1 is gone. We must fall back
+// to the original launcher rather than synthesise an invalid powershell -File
+// invocation.
+func TestPlatformQwenInvocation_SkipsWhenPS1Missing(t *testing.T) {
+ dir := t.TempDir()
+ cmdPath := filepath.Join(dir, "qwen.cmd")
+ writeFile(t, cmdPath, "@echo off\r\n")
+
+ stubPowerShell(t, filepath.Join(dir, "powershell.exe"), true)
+
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ if _, _, ok := platformQwenInvocation(cmdPath, []string{"--output-format", "stream-json"}, logger); ok {
+ t.Fatalf("expected ok=false when qwen.ps1 is missing")
+ }
+}
+
+// TestPlatformQwenInvocation_SkipsWhenPowerShellMissing covers a stripped down
+// environment in which neither pwsh.exe nor powershell.exe can be resolved. We
+// must not fabricate an empty-string argv[0].
+func TestPlatformQwenInvocation_SkipsWhenPowerShellMissing(t *testing.T) {
+ dir := t.TempDir()
+ cmdPath := filepath.Join(dir, "qwen.cmd")
+ ps1Path := filepath.Join(dir, "qwen.ps1")
+ writeFile(t, cmdPath, "@echo off\r\n")
+ writeFile(t, ps1Path, "# fake\r\n")
+
+ stubPowerShell(t, "", false)
+
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ if _, _, ok := platformQwenInvocation(cmdPath, []string{"--output-format", "stream-json"}, logger); ok {
+ t.Fatalf("expected ok=false when no powershell host is available")
+ }
+}
diff --git a/server/pkg/agent/qwen_stdin_windows_test.go b/server/pkg/agent/qwen_stdin_windows_test.go
new file mode 100644
index 0000000000..2ad2db979b
--- /dev/null
+++ b/server/pkg/agent/qwen_stdin_windows_test.go
@@ -0,0 +1,153 @@
+//go:build windows
+
+package agent
+
+import (
+ "fmt"
+ "io"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+const (
+ qwenShimHelperEnv = "MULTICA_QWEN_SHIM_HELPER"
+ qwenShimHelperArgvFile = "MULTICA_QWEN_SHIM_ARGV_FILE"
+ qwenShimHelperInFile = "MULTICA_QWEN_SHIM_STDIN_FILE"
+)
+
+// TestQwenShimHelperProcess is re-executed by the fake qwen.ps1 as its native
+// child. It records the argv and stdin that made it through PowerShell, emits a
+// successful Qwen event stream, and exits before the Go test framework writes
+// its own output to stdout.
+func TestQwenShimHelperProcess(t *testing.T) {
+ if os.Getenv(qwenShimHelperEnv) != "1" {
+ t.Skip("helper process; only runs when re-executed by the shim")
+ }
+
+ var forwarded []string
+ for i, arg := range os.Args {
+ if arg == "--" {
+ forwarded = os.Args[i+1:]
+ break
+ }
+ }
+ if err := os.WriteFile(os.Getenv(qwenShimHelperArgvFile), []byte(strings.Join(forwarded, "\n")), 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(qwenShimHelperInFile), stdin, 0o644); err != nil {
+ fmt.Fprintf(os.Stderr, "helper: write stdin: %v\n", err)
+ os.Exit(1)
+ }
+
+ fmt.Println(`{"type":"system","subtype":"init","session_id":"sess-qwen-windows","model":"qwen-test"}`)
+ fmt.Println(`{"type":"result","subtype":"success","session_id":"sess-qwen-windows","is_error":false,"result":"PONG"}`)
+ os.Exit(0)
+}
+
+// TestQwenExecutePromptSurvivesPowerShellShim exercises the complete Windows
+// production boundary behind #6082:
+//
+// Go -> powershell -File qwen.ps1 -> native child
+//
+// The prompt must be absent from the argv PowerShell re-serialises and must be
+// inherited by the native child on stdin without byte changes. Every available
+// PowerShell host is exercised because Windows PowerShell 5.1 and current pwsh
+// use different native argument-passing modes.
+func TestQwenExecutePromptSurvivesPowerShellShim(t *testing.T) {
+ hosts := availablePowerShellHosts()
+ if len(hosts) == 0 {
+ t.Skip("no PowerShell host available")
+ }
+ for _, host := range hosts {
+ t.Run(filepath.Base(host), func(t *testing.T) {
+ stubPowerShell(t, host, true)
+ assertQwenPromptSurvivesShim(t)
+ })
+ }
+}
+
+func assertQwenPromptSurvivesShim(t *testing.T) {
+ t.Helper()
+
+ 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")
+
+ cmdPath := filepath.Join(dir, "qwen.cmd")
+ writeFile(t, cmdPath, "@echo off\r\npowershell -NoProfile -ExecutionPolicy Bypass -File \"%~dp0qwen.ps1\" %*\r\n")
+ ps1 := fmt.Sprintf(""+
+ "$env:%s = '1'\r\n"+
+ "$env:%s = '%s'\r\n"+
+ "$env:%s = '%s'\r\n"+
+ "& '%s' '-test.run=^TestQwenShimHelperProcess$' '--' $args\r\n"+
+ "exit $LASTEXITCODE\r\n",
+ qwenShimHelperEnv,
+ qwenShimHelperArgvFile, argvPath,
+ qwenShimHelperInFile, stdinPath,
+ self)
+ writeFile(t, filepath.Join(dir, "qwen.ps1"), ps1)
+
+ prompt := "First line with \"double quotes\".\n" +
+ "Unicode: 你好,世界 — symbols: & 100% ^done"
+ backend, err := New("qwen", Config{ExecutablePath: cmdPath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("New(qwen): %v", err)
+ }
+ session, err := backend.Execute(t.Context(), prompt, ExecOptions{
+ Model: "qwen-test",
+ Timeout: 60 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("Execute: %v", err)
+ }
+ _, result := awaitQwenResult(t, session)
+
+ argvRaw, err := os.ReadFile(argvPath)
+ if err != nil {
+ t.Fatalf("native child never recorded argv: %v; result=%+v", err, result)
+ }
+ stdinRaw, err := os.ReadFile(stdinPath)
+ if err != nil {
+ t.Fatalf("native child never recorded stdin: %v; result=%+v", err, result)
+ }
+ argv := strings.Split(strings.TrimSuffix(string(argvRaw), "\n"), "\n")
+ for _, arg := range argv {
+ for _, fragment := range []string{"First line", "double quotes", "你好", "100%", "^done"} {
+ if strings.Contains(arg, fragment) {
+ t.Errorf("prompt fragment %q leaked into native child argv element %q", fragment, arg)
+ }
+ }
+ }
+ if idx := prefixIndex(argv, []string{"--output-format", "stream-json"}); idx < 0 {
+ t.Errorf("stream-json protocol flags did not reach native child; argv=%q", argv)
+ }
+ if idx := prefixIndex(argv, []string{"--model", "qwen-test"}); idx < 0 {
+ t.Errorf("managed model flags did not reach native child; argv=%q", argv)
+ }
+ if idx := prefixIndex(argv, []string{"--yolo"}); idx < 0 {
+ t.Errorf("managed permission flag did not reach native child; argv=%q", argv)
+ }
+ if idx := prefixIndex(argv, []string{"-p"}); idx >= 0 {
+ t.Errorf("prompt flag must stay out of argv; argv=%q", argv)
+ }
+ if string(stdinRaw) != prompt {
+ t.Errorf("prompt did not survive Go -> PowerShell -> native child:\n got %q\n want %q", string(stdinRaw), prompt)
+ }
+ if result.Status != "completed" || result.Output != "PONG" || result.SessionID != "sess-qwen-windows" {
+ t.Fatalf("unexpected result: %+v", result)
+ }
+}
diff --git a/server/pkg/agent/qwen_test.go b/server/pkg/agent/qwen_test.go
index f4609a6307..2dc10d5648 100644
--- a/server/pkg/agent/qwen_test.go
+++ b/server/pkg/agent/qwen_test.go
@@ -25,7 +25,7 @@ func TestNewReturnsQwenBackend(t *testing.T) {
func TestBuildQwenArgsKeepsProtocolManaged(t *testing.T) {
t.Parallel()
- args := buildQwenArgs("task prompt", ExecOptions{
+ args := buildQwenArgs(ExecOptions{
Model: "qwen3.8-max-preview",
ResumeSessionID: "session-1",
ExtraArgs: []string{"--output-format", "text", "--sandbox"},
@@ -42,7 +42,11 @@ func TestBuildQwenArgsKeepsProtocolManaged(t *testing.T) {
t.Fatalf("managed argument %q leaked into %v", forbidden, args)
}
}
- wantPrefix := []string{"-p", "task prompt", "--output-format", "stream-json", "--model", "qwen3.8-max-preview", "--resume", "session-1"}
+ // The prompt is never part of argv (see buildQwenArgs) — it goes on stdin.
+ if strings.Contains(joined, "-p ") || strings.HasPrefix(joined, "-p") {
+ t.Fatalf("-p must not appear in argv, prompt is delivered on stdin: %v", args)
+ }
+ wantPrefix := []string{"--output-format", "stream-json", "--model", "qwen3.8-max-preview", "--resume", "session-1"}
if len(args) < len(wantPrefix) {
t.Fatalf("args too short: %v", args)
}
@@ -66,7 +70,7 @@ func TestBuildQwenArgsYoloAlwaysPresent(t *testing.T) {
t.Parallel()
// --yolo must be injected even when custom_args is empty: Qwen's
// non-interactive mode otherwise filters out shell, edit, and write tools.
- args := buildQwenArgs("task", ExecOptions{}, slog.Default())
+ args := buildQwenArgs(ExecOptions{}, slog.Default())
if !strings.Contains(strings.Join(args, " "), "--yolo") {
t.Fatalf("--yolo missing from base args %v", args)
}
@@ -75,6 +79,7 @@ func TestBuildQwenArgsYoloAlwaysPresent(t *testing.T) {
func fakeQwenScript() string {
return `#!/bin/sh
if [ -n "$QWEN_ARGS_FILE" ]; then printf '%s\n' "$@" > "$QWEN_ARGS_FILE"; fi
+if [ -n "$QWEN_STDIN_FILE" ]; then cat > "$QWEN_STDIN_FILE"; fi
while [ "$#" -gt 0 ]; do
if [ "$1" = "--mcp-config" ] && [ -n "$QWEN_MCP_CAPTURE_FILE" ]; then cp "$2" "$QWEN_MCP_CAPTURE_FILE"; break; fi
shift
@@ -183,6 +188,37 @@ func TestQwenBackendPreservesSuccessfulResumeSession(t *testing.T) {
}
}
+// TestQwenBackendDeliversPromptOnStdin is the round-trip regression guard for
+// #6082/#5649: the prompt must reach the child intact — including embedded
+// double quotes, an em dash, and a shell-metacharacter-laden fragment — none
+// of it ever having touched argv or a Windows/PowerShell command line. If
+// buildQwenArgs regressed to putting the prompt back on argv, this would
+// still pass (the fake script only inspects stdin), so
+// TestBuildQwenArgsKeepsProtocolManaged's "-p must not appear in argv" check
+// is what actually catches that regression; this test guards the other half
+// of the contract — that stdin delivery actually carries the bytes through.
+func TestQwenBackendDeliversPromptOnStdin(t *testing.T) {
+ t.Parallel()
+ stdinPath := filepath.Join(t.TempDir(), "qwen.stdin")
+ backend := newFakeQwenBackend(t, map[string]string{"QWEN_STDIN_FILE": stdinPath})
+ prompt := `go build -ldflags "-X main.version=foo" — mind the em dash & the quotes"`
+ session, err := backend.Execute(context.Background(), prompt, ExecOptions{Model: "qwen-test", Timeout: 5 * time.Second})
+ if err != nil {
+ t.Fatalf("Execute: %v", err)
+ }
+ _, result := awaitQwenResult(t, session)
+ if result.Status != "completed" {
+ t.Fatalf("result = %+v", result)
+ }
+ got, err := os.ReadFile(stdinPath)
+ if err != nil {
+ t.Fatalf("read captured stdin: %v", err)
+ }
+ if string(got) != prompt {
+ t.Fatalf("stdin content = %q, want %q", got, prompt)
+ }
+}
+
func newQwenTestContext() (context.Context, context.CancelFunc) {
return context.WithCancel(context.Background())
}