Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-3305: feat(agent): add qoder CLI as a choice of agent provider. (#2461)
DylanLi78342a39ce86
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex 747fc41c81..7ec38a43b0 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -149,6 +149,7 @@ The daemon auto-detects these AI CLIs on your PATH:| [Cursor Agent](https://cursor.com/) | `cursor-agent` | Cursor's headless coding agent || Kimi | `kimi` | Moonshot coding agent || Kiro CLI | `kiro-cli` | Kiro ACP coding agent |+| [Qoder CLI](https://docs.qoder.com/) | `qodercli` | Qoder ACP coding agent |You need at least one installed. The daemon registers each detected CLI as an available runtime.@@ -220,6 +221,10 @@ Agent-specific overrides:| `MULTICA_KIMI_MODEL` | Override the Kimi model used || `MULTICA_KIRO_PATH` | Custom path to the `kiro-cli` binary || `MULTICA_KIRO_MODEL` | Override the Kiro model used |+| `MULTICA_QODER_PATH` | Custom path to the `qodercli` binary |+| `MULTICA_QODER_MODEL` | Override the Qoder model used |++The daemon launches Qoder as `qodercli --yolo --acp`, matching Qoder’s ACP “bypass permissions” mode so tool runs do not block on interactive approval in headless runs.`MULTICA_CLAUDE_ARGS` and `MULTICA_CODEX_ARGS` are parsed with POSIX shellword quoting, so values such as `--model "gpt-5.1 codex" --sandbox read-only` are split like a shell command line. Agent arguments are applied in this order: hardcoded Multica defaults, daemon-wide env defaults, then per-agent `custom_args` from the task.diff --git a/README.md b/README.mdindex d73cda8b61..c26674451c 100644--- a/README.md+++ b/README.md@@ -31,7 +31,7 @@ Turn coding agents into real teammates — assign tasks, track progress, compounMultica turns coding agents into real teammates. Assign issues to an agent like you'd assign to a colleague — they'll pick up the work, write code, report blockers, and update statuses autonomously.-No more copy-pasting prompts. No more babysitting runs. Your agents show up on the board, participate in conversations, and compound reusable skills over time. Think of it as open-source infrastructure for managed agents — vendor-neutral, self-hosted, and designed for human + AI teams. Works with **Claude Code**, **Codex**, **GitHub Copilot CLI**, **OpenClaw**, **OpenCode**, **Hermes**, **Gemini**, **Pi**, **Cursor Agent**, **Kimi**, and **Kiro CLI**.+No more copy-pasting prompts. No more babysitting runs. Your agents show up on the board, participate in conversations, and compound reusable skills over time. Think of it as open-source infrastructure for managed agents — vendor-neutral, self-hosted, and designed for human + AI teams. Works with **Claude Code**, **Codex**, **GitHub Copilot CLI**, **OpenClaw**, **OpenCode**, **Hermes**, **Gemini**, **Pi**, **Cursor Agent**, **Kimi**, **Kiro CLI**, and **Qoder CLI**.For larger teams, Squads add a stable routing layer: assign work to a group led by an agent, and the leader delegates to the right member.@@ -115,7 +115,7 @@ multica setup # Connect to Multica Cloud, log in, start daemonmultica setup # Configure, authenticate, and start the daemon```-The daemon runs in the background and auto-detects agent CLIs (`claude`, `codex`, `copilot`, `openclaw`, `opencode`, `hermes`, `gemini`, `pi`, `cursor-agent`, `kimi`, `kiro-cli`, `agy`) on your PATH.+The daemon runs in the background and auto-detects agent CLIs (`claude`, `codex`, `copilot`, `openclaw`, `opencode`, `hermes`, `gemini`, `pi`, `cursor-agent`, `kimi`, `kiro-cli`, `agy`, `qodercli`) on your PATH.### 2. Verify your runtime@@ -125,7 +125,7 @@ Open your workspace in the Multica web app. Navigate to **Settings → Runtimes*### 3. Create an agent-Go to **Settings → Agents** and click **New Agent**. Pick the runtime you just connected and choose a provider (Claude Code, Codex, GitHub Copilot CLI, OpenClaw, OpenCode, Hermes, Gemini, Pi, Cursor Agent, Kimi, Kiro CLI, or Antigravity). Give your agent a name — this is how it will appear on the board, in comments, and in assignments.+Go to **Settings → Agents** and click **New Agent**. Pick the runtime you just connected and choose a provider (Claude Code, Codex, GitHub Copilot CLI, OpenClaw, OpenCode, Hermes, Gemini, Pi, Cursor Agent, Kimi, Kiro CLI, Antigravity, or Qoder CLI). Give your agent a name — this is how it will appear on the board, in comments, and in assignments.### 4. Assign your first task@@ -166,7 +166,7 @@ See the [CLI and Daemon Guide](CLI_AND_DAEMON.md) for the full command reference│ Agent Daemon │ runs on your machine└──────────────┘ (Claude Code, Codex, GitHub Copilot CLI,OpenCode, OpenClaw, Hermes, Gemini,- Pi, Cursor Agent, Kimi, Kiro CLI)+ Pi, Cursor Agent, Kimi, Kiro CLI, Qoder CLI)```| Layer | Stack |@@ -174,7 +174,7 @@ See the [CLI and Daemon Guide](CLI_AND_DAEMON.md) for the full command reference| Frontend | Next.js 16 (App Router) || Backend | Go (Chi router, sqlc, gorilla/websocket) || Database | PostgreSQL 17 with pgvector |-| Agent Runtime | Local daemon executing Claude Code, Codex, GitHub Copilot CLI, OpenClaw, OpenCode, Hermes, Gemini, Pi, Cursor Agent, Kimi, or Kiro CLI |+| Agent Runtime | Local daemon executing Claude Code, Codex, GitHub Copilot CLI, OpenClaw, OpenCode, Hermes, Gemini, Pi, Cursor Agent, Kimi, Kiro CLI, or Qoder CLI |## Developmentdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex 3f8ccb7e27..a70f496d25 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -31,7 +31,7 @@Multica 将编码 Agent 变成真正的队友。像分配给同事一样分配给 Agent——它们会自主接手工作、编写代码、报告阻塞问题、更新状态。-不再需要复制粘贴 prompt,不再需要盯着运行过程。你的 Agent 出现在看板上、参与对话、随着时间积累可复用的技能。可以理解为开源的 Managed Agents 基础设施——厂商中立、可自部署、专为人类 + AI 团队设计。支持 **Claude Code**、**Codex**、**GitHub Copilot CLI**、**OpenClaw**、**OpenCode**、**Hermes**、**Gemini**、**Pi**、**Cursor Agent**、**Kimi** 和 **Kiro CLI**。+不再需要复制粘贴 prompt,不再需要盯着运行过程。你的 Agent 出现在看板上、参与对话、随着时间积累可复用的技能。可以理解为开源的 Managed Agents 基础设施——厂商中立、可自部署、专为人类 + AI 团队设计。支持 **Claude Code**、**Codex**、**GitHub Copilot CLI**、**OpenClaw**、**OpenCode**、**Hermes**、**Gemini**、**Pi**、**Cursor Agent**、**Kimi**、**Kiro CLI** 与 **Qoder CLI**。面向更大的团队,Squads(小队)提供稳定的路由层:把任务分给由 Agent 带队的小队,由队长判断谁最适合接手。@@ -116,7 +116,7 @@ multica setup # 连接 Multica Cloud,登录,启动 daemonmultica setup # 配置、认证、启动 daemon(一条命令搞定)```-daemon 在后台运行,保持你的机器与 Multica 的连接。它会自动检测 PATH 中可用的 Agent CLI(`claude`、`codex`、`copilot`、`openclaw`、`opencode`、`hermes`、`gemini`、`pi`、`cursor-agent`、`kimi`、`kiro-cli`)。+daemon 在后台运行,保持你的机器与 Multica 的连接。它会自动检测 PATH 中可用的 Agent CLI(`claude`、`codex`、`copilot`、`openclaw`、`opencode`、`hermes`、`gemini`、`pi`、`cursor-agent`、`kimi`、`kiro-cli`、`qodercli`)。### 2. 确认运行时已连接@@ -126,7 +126,7 @@ daemon 在后台运行,保持你的机器与 Multica 的连接。它会自动### 3. 创建 Agent-进入 **设置 → Agents**,点击 **新建 Agent**。选择你刚连接的 Runtime,选择 Provider(Claude Code、Codex、GitHub Copilot CLI、OpenClaw、OpenCode、Hermes、Gemini、Pi、Cursor Agent、Kimi 或 Kiro CLI),并为 Agent 起个名字——它将以这个名字出现在看板、评论和任务分配中。+进入 **设置 → Agents**,点击 **新建 Agent**。选择你刚连接的 Runtime,选择 Provider(Claude Code、Codex、GitHub Copilot CLI、OpenClaw、OpenCode、Hermes、Gemini、Pi、Cursor Agent、Kimi、Kiro CLI 或 Qoder CLI),并为 Agent 起个名字——它将以这个名字出现在看板、评论和任务分配中。### 4. 分配你的第一个任务@@ -148,7 +148,7 @@ daemon 在后台运行,保持你的机器与 Multica 的连接。它会自动│ Agent Daemon │ 运行在你的机器上└──────────────┘ (Claude Code、Codex、GitHub Copilot CLI、OpenCode、OpenClaw、Hermes、Gemini、- Pi、Cursor Agent、Kimi、Kiro CLI)+ Pi、Cursor Agent、Kimi、Kiro CLI、Qoder CLI)```| 层级 | 技术栈 |@@ -156,7 +156,7 @@ daemon 在后台运行,保持你的机器与 Multica 的连接。它会自动| 前端 | Next.js 16 (App Router) || 后端 | Go (Chi router, sqlc, gorilla/websocket) || 数据库 | PostgreSQL 17 with pgvector |-| Agent 运行时 | 本地 daemon 执行 Claude Code、Codex、GitHub Copilot CLI、OpenClaw、OpenCode、Hermes、Gemini、Pi、Cursor Agent、Kimi 或 Kiro CLI |+| Agent 运行时 | 本地 daemon 执行 Claude Code、Codex、GitHub Copilot CLI、OpenClaw、OpenCode、Hermes、Gemini、Pi、Cursor Agent、Kimi、Kiro CLI 或 Qoder CLI |## 开发diff --git a/SELF_HOSTING.md b/SELF_HOSTING.mdindex 8e46b8c9a6..e3eb55e2b3 100644--- a/SELF_HOSTING.md+++ b/SELF_HOSTING.md@@ -101,6 +101,7 @@ You also need at least one AI agent CLI installed:- [Cursor Agent](https://cursor.com/) (`cursor-agent` on PATH)- Kimi (`kimi` on PATH)- Kiro CLI (`kiro-cli` on PATH)+- Qoder CLI (`qodercli` on PATH)### b) One-command setupdiff --git a/docs/product-overview.md b/docs/product-overview.mdindex 8057422c3b..895c519740 100644--- a/docs/product-overview.md+++ b/docs/product-overview.md@@ -82,7 +82,7 @@ Multica 做的事:Multica **不自己训模型**,也不锁定某一家厂商。它是调度器,本地 daemon 会自动探测以下 CLI 工具并接入:-Claude Code · Codex · OpenClaw · OpenCode · Hermes · Gemini · Pi · Cursor Agent · Kimi · Kiro CLI+Claude Code · Codex · OpenClaw · OpenCode · Hermes · Gemini · Pi · Cursor Agent · Kimi · Kiro CLI · Qoder CLI每个 agent 可以配置自己的模型、API Key、环境变量、MCP 服务器。@@ -244,7 +244,7 @@ Project 相比 Issue 是更高层的组织单元。一个 issue 可以不属于#### 配置字段- **基本信息**:名字、描述、头像(自动生成)-- **Provider**:选择底层是 Claude / Codex / OpenClaw / OpenCode / Hermes / Gemini / Pi / Cursor / Kimi / Kiro 中的哪一个+- **Provider**:选择底层是 Claude / Codex / OpenClaw / OpenCode / Hermes / Gemini / Pi / Cursor / Kimi / Kiro / Qoder 中的哪一个- **Runtime**:绑定到哪个运行时(即在哪台机器上跑)- **Instructions 说明书**:agent 的系统提示词("你是一个资深工程师...")- **Custom Env**:要注入到 CLI 进程的环境变量(如 `ANTHROPIC_API_KEY`、`ANTHROPIC_BASE_URL`、`CLAUDE_CODE_USE_BEDROCK`)@@ -291,7 +291,7 @@ Agent 是 Multica 的灵魂。几乎所有功能都围绕"如何让一个 agent`multica` CLI 在用户的机器上启动一个后台进程(macOS launchd / Linux systemd / Windows 服务风格),它:-1. **自动探测** `$PATH` 上安装的 coding CLI(`claude`, `codex`, `opencode`, `openclaw`, `hermes`, `gemini`, `pi`, `cursor-agent`, `kimi`, `kiro-cli`)+1. **自动探测** `$PATH` 上安装的 coding CLI(`claude`, `codex`, `opencode`, `openclaw`, `hermes`, `gemini`, `pi`, `cursor-agent`, `kimi`, `kiro-cli`, `qodercli`)2. 向 server **注册** 为一组 runtime(一个 CLI = 一个 runtime)3. 每 3 秒 **轮询** 一次 server,有任务就认领4. 每 15 秒 **心跳**(keepalive),报告自己还活着diff --git a/packages/views/onboarding/steps/step-welcome.tsx b/packages/views/onboarding/steps/step-welcome.tsxindex b4d5ad80b4..eaf866c8b0 100644--- a/packages/views/onboarding/steps/step-welcome.tsx+++ b/packages/views/onboarding/steps/step-welcome.tsx@@ -281,6 +281,7 @@ type ProviderName =| "hermes"| "kimi"| "kiro"+ | "qoder"| "pi"| "copilot"| "cursor";diff --git a/packages/views/runtimes/components/provider-logo.tsx b/packages/views/runtimes/components/provider-logo.tsxindex 8cfb0f46a6..143b17f7c4 100644--- a/packages/views/runtimes/components/provider-logo.tsx+++ b/packages/views/runtimes/components/provider-logo.tsx@@ -172,6 +172,27 @@ function KimiLogo({ className }: { className: string }) {);}+// Qoder (QoderCLI) — official logo from qoder-color.svg+function QoderLogo({ className }: { className: string }) {+ return (+ <svg+ viewBox="0 0 24 24"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ className={className}+ >+ <path+ d="M23.376 14.458v-4.056c0-2.304-1.003-4.154-2.748-5.075L11.612.574l-.046.086-.045.086c1.68.886 2.644 2.673 2.644 4.902v4.056a7.928 7.928 0 01-.014.454l-.005.061c-.005.081-.01.164-.018.245a4.897 4.897 0 01-.011.1l-.01.076c-.008.068-.015.135-.025.203l-.018.113-.01.058a9.99 9.99 0 01-.098.513l-.007.03a7.209 7.209 0 01-.074.294l-.024.086c-.027.099-.056.197-.087.296l-.027.085a9.592 9.592 0 01-.111.323l-.033.085-.018.046c-.032.082-.064.166-.098.248-.019.048-.04.096-.061.145l-.007.017a6 6 0 01-.084.187c-.024.056-.05.11-.077.165-.03.061-.058.122-.089.182a9.423 9.423 0 01-.176.332c-.03.056-.062.111-.094.167-.031.053-.062.108-.095.16-.033.055-.066.11-.101.164-.033.053-.065.104-.1.155-.034.055-.07.107-.111.169l-.099.144a15.193 15.193 0 01-.34.457c-.04.05-.08.102-.121.151l-.107.128-.007.008a6.987 6.987 0 01-.262.298l-.149.16-.116.12a9.562 9.562 0 01-.204.198l-.03.03-.072.069a9.05 9.05 0 01-.263.235l-.025.022-.029.026-.042.035a11.7 11.7 0 01-.22.18l-.07.055-.018.013a8.904 8.904 0 01-.194.146c-.029.02-.057.042-.086.063a7.7 7.7 0 01-.22.152l-.057.04a8.865 8.865 0 01-.293.185l-.062.037a10.424 10.424 0 01-.307.173l-.037.02-.196.103-.108.052-.012.006a6.196 6.196 0 01-.315.143c-.065.028-.13.054-.196.08l-.035.014-.086.034c-.07.026-.143.05-.215.075l-.039.014-.064.023a8.056 8.056 0 01-.323.097l-.63.173a7.285 7.285 0 01-.33.08l-.07.015c-.053.012-.104.023-.157.032l-.065.011-.085.015a2.332 2.332 0 01-.194.027l-.085.01a4.715 4.715 0 01-.16.018l-.034.003a4.861 4.861 0 01-.246.016h-.033a2.714 2.714 0 01-.155.005h-.106a3.384 3.384 0 01-.225-.007H4.86l-.15-.012-.066-.006a5.586 5.586 0 01-.187-.02l-.04-.005a5.14 5.14 0 01-.219-.035l-.054-.01a6.943 6.943 0 01-.347-.082l-.03-.008-.038-.01a5.034 5.034 0 01-.269-.086l-.063-.023a4.216 4.216 0 01-.188-.073l-.071-.031-.016-.007a4.959 4.959 0 01-.16-.074l-.026-.013a.164.164 0 00-.014-.007l-.671-.351.486.486h.016l8.995 4.742.093.048.03.014.02.01c.056.026.111.052.169.076l.016.008.073.032.195.076.022.008a.718.718 0 01.03.012l.014.004a4.693 4.693 0 00.323.1l.027.007c.073.02.147.038.22.055l.018.004.027.006.066.013.088.016c.075.014.15.026.226.038l.042.004c.064.009.128.016.193.022l.126.012.06.003.05.002.098.005c.046.002.094.002.14.003h.12c.05 0 .1-.002.161-.005h.033l.07-.004a6.17 6.17 0 00.184-.014l.033-.003a.753.753 0 00.058-.005l.108-.012.081-.01.08-.01.129-.021.082-.014.071-.012c.054-.01.107-.021.16-.033l.066-.013.059-.013c.096-.022.192-.046.287-.073l.63-.172a7.354 7.354 0 00.397-.122l.04-.015c.075-.025.149-.051.222-.078.032-.011.062-.024.093-.037l.03-.012c.067-.027.135-.054.2-.082l.128-.056.195-.09.021-.01.102-.05c.068-.034.135-.069.202-.105l.037-.02.073-.038c.08-.044.16-.092.24-.139l.026-.015a8.086 8.086 0 00.322-.2l.065-.045 1.98.902a1.748 1.748 0 002.472-1.59v-7.33l.004.004z"+ fill="#2ADB5C"+ />+ <path+ d="M11.617.576a3.904 3.904 0 00-.093-.047c-.016-.009-.033-.016-.05-.024a5.854 5.854 0 00-.166-.077l-.09-.04a4.094 4.094 0 00-.194-.074c-.017-.006-.035-.015-.053-.02l-.013-.005a5.18 5.18 0 00-.277-.088l-.07-.019a4.034 4.034 0 00-.219-.053c-.015-.003-.03-.008-.044-.012L10.253.1l-.057-.011a5.177 5.177 0 00-.225-.036L9.928.047a5.972 5.972 0 00-.191-.022L9.669.02a1.33 1.33 0 00-.058-.005L9.515.009a4.058 4.058 0 00-.111-.005C9.354 0 9.304 0 9.254 0h-.109c-.052 0-.106.004-.16.004L8.884.01A5.32 5.32 0 008.7.022l-.083.006h-.008c-.05.005-.1.013-.15.019l-.12.014c-.056.008-.112.018-.169.028-.037.006-.074.011-.11.018a7.054 7.054 0 00-.572.133l-.63.172c-.111.031-.22.064-.33.1-.037.011-.072.025-.108.037a12.91 12.91 0 00-.345.126c-.067.027-.133.054-.2.083l-.128.055a11.916 11.916 0 00-.318.15 7.376 7.376 0 00-.311.163c-.082.045-.16.092-.24.14a9.424 9.424 0 00-.35.218l-.016.01-.06.04a9.242 9.242 0 00-.51.37 12.54 12.54 0 00-.315.254l-.043.034-.01.007-.045.041c-.09.078-.18.158-.268.24l-.106.101c-.07.067-.139.135-.207.204l-.056.054-.063.067-.153.164-.12.133-.148.17c-.024.03-.049.057-.073.086l-.043.053a5.96 5.96 0 00-.123.155l-.118.151c-.04.053-.08.106-.118.16l-.075.101-.038.056-.107.155-.11.164a9.91 9.91 0 00-.168.265c-.012.02-.023.043-.037.063a12.43 12.43 0 00-.192.335l-.09.168c-.019.034-.04.07-.057.105-.011.022-.02.043-.032.065l-.092.188-.08.167a19.15 19.15 0 00-.083.192c-.017.038-.035.076-.05.115-.008.016-.014.034-.021.051-.035.083-.067.167-.1.253l-.051.134c-.04.11-.077.22-.113.33l-.02.057c0 .002 0 .005-.002.007l-.008.026c-.032.1-.06.2-.09.301l-.023.089c-.027.1-.052.2-.075.301l-.007.03a7.63 7.63 0 00-.057.267l-.008.048c-.015.074-.026.148-.038.223L.082 8.4c-.011.078-.02.156-.029.234-.006.051-.013.103-.017.154a6.57 6.57 0 00-.02.26c-.003.044-.007.086-.009.13-.004.128-.007.257-.007.386v4.056c0 1.478.42 2.741 1.138 3.692A4.75 4.75 0 002.73 18.67l9.015 4.753c-1.656-.874-2.728-2.685-2.73-5.051v-4.056c0-.13.004-.26.01-.39.002-.043.006-.085.01-.128.005-.088.01-.174.019-.261l.017-.155c.01-.077.018-.155.029-.234l.026-.164c.013-.074.025-.15.039-.223.02-.105.04-.21.064-.313l.008-.031c.023-.1.048-.201.075-.301l.023-.088c.028-.1.058-.202.09-.302l.008-.025.021-.063c.036-.11.073-.22.113-.33l.052-.134c.031-.085.065-.169.1-.253.022-.056.047-.111.07-.166a13.856 13.856 0 01.164-.358c.03-.063.06-.126.092-.188l.088-.172a9.22 9.22 0 01.187-.338l.096-.164c.034-.057.069-.112.104-.168l.1-.159a10.49 10.49 0 01.567-.786l.123-.155.116-.139c.05-.057.098-.115.148-.171a14.092 14.092 0 01.272-.297 9.706 9.706 0 01.432-.425c.088-.083.177-.163.268-.241l.054-.048a10.08 10.08 0 01.553-.435l.092-.068c.075-.053.15-.105.226-.156.019-.013.038-.028.06-.04a9.18 9.18 0 01.362-.227c.08-.047.16-.094.241-.139l.11-.058a7.643 7.643 0 01.521-.256l.126-.056a7.509 7.509 0 01.546-.208l.107-.037c.11-.036.22-.069.33-.1l.63-.172c.095-.026.191-.05.287-.072l.097-.02c.062-.014.125-.029.187-.04l.114-.018c.055-.01.11-.02.166-.028.04-.006.08-.01.12-.014.053-.007.105-.014.157-.019l.083-.006c.061-.005.123-.01.184-.013.034-.003.067-.003.101-.004l.16-.006h.11a3.187 3.187 0 01.261.008l.153.01.067.007c.064.006.128.013.192.022l.043.005a5.232 5.232 0 01.281.047l.141.03c.073.016.146.035.218.053l.07.019c.094.026.187.055.278.087l.067.025a4.326 4.326 0 01.449.19l.143.072L11.617.576z"+ fill="currentColor"+ />+ </svg>+ );+}+// Gemini (Google) — official "Google Gemini" mark from Simple Icons// (simpleicons.org/icons/googlegemini.svg, CC0 1.0). Rendered in the// Simple Icons brand color (#8E75B2), matching the pattern used by the@@ -268,6 +289,8 @@ export function ProviderLogo({return <KimiLogo className={className} />;case "kiro":return <KiroLogo className={className} />;+ case "qoder":+ return <QoderLogo className={className} />;case "gemini":return <GeminiLogo className={className} />;case "antigravity":diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex 0f600513e7..85ee9c82bc 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -80,7 +80,7 @@ type Config struct {CLIVersion string // multica CLI version (e.g. "0.1.13")LaunchedBy string // "desktop" when spawned by the Electron app, empty for standaloneProfile string // profile name (empty = default)- Agents map[string]AgentEntry // keyed by provider: claude, codebuddy, codex, copilot, opencode, openclaw, hermes, gemini, pi, cursor, kimi, kiro, antigravity+ Agents map[string]AgentEntry // keyed by provider: claude, codebuddy, codex, copilot, opencode, openclaw, hermes, gemini, pi, cursor, kimi, kiro, antigravity, qoderWorkspacesRoot string // base path for execution envs (default: ~/multica_workspaces)KeepEnvAfterTask bool // preserve env after task for debuggingHealthPort int // local HTTP port for health checks (default: 19514)@@ -300,8 +300,15 @@ func LoadConfig(overrides Overrides) (Config, error) {if e, ok := probe("MULTICA_ANTIGRAVITY_PATH", "agy", "MULTICA_ANTIGRAVITY_MODEL"); ok {agents["antigravity"] = e}+ qoderPath := envOrDefault("MULTICA_QODER_PATH", "qodercli")+ if _, err := exec.LookPath(qoderPath); err == nil {+ agents["qoder"] = AgentEntry{+ Path: qoderPath,+ Model: strings.TrimSpace(os.Getenv("MULTICA_QODER_MODEL")),+ }+ }if len(agents) == 0 {- return Config{}, fmt.Errorf("no agent CLI found: install claude, codebuddy, codex, copilot, opencode, openclaw, hermes, gemini, pi, cursor-agent, kimi, kiro-cli, or agy and ensure it is on PATH")+ return Config{}, fmt.Errorf("no agent CLI found: install claude, codebuddy, codex, copilot, opencode, openclaw, hermes, gemini, pi, cursor-agent, kimi, kiro-cli, agy, or qodercli and ensure it is on PATH")}claudeArgs, err := shellArgsFromEnv("MULTICA_CLAUDE_ARGS")diff --git a/server/internal/daemon/execenv/context.go b/server/internal/daemon/execenv/context.goindex af9fc6e580..c670b80458 100644--- a/server/internal/daemon/execenv/context.go+++ b/server/internal/daemon/execenv/context.go@@ -24,6 +24,7 @@ import (// Cursor: skills → {workDir}/.cursor/skills/{name}/SKILL.md (native discovery)// Kimi: skills → {workDir}/.kimi/skills/{name}/SKILL.md (native discovery)// Kiro: skills → {workDir}/.kiro/skills/{name}/SKILL.md (native discovery)+// Qoder: skills → {workDir}/.qoder/skills/{name}/SKILL.md (project-level; see docs.qoder.com/cli/Skills.md)// Antigravity: skills → {workDir}/.agents/skills/{name}/SKILL.md (native discovery — see https://antigravity.google/docs/gcli-migration "Workspace skills")// Default: skills → {workDir}/.agent_context/skills/{name}/SKILL.md//@@ -212,6 +213,10 @@ func skillsDirPath(workDir, provider string) string {// Kiro CLI auto-discovers project-level skills from .kiro/skills/// in the workdir.return filepath.Join(workDir, ".kiro", "skills")+ case "qoder":+ // Qoder CLI discovers project-level skills under .qoder/skills/.+ // See https://docs.qoder.com/cli/Skills.md+ return filepath.Join(workDir, ".qoder", "skills")case "antigravity":// Antigravity (`agy`) auto-discovers workspace-level skills from// .agents/skills/ in the workdir. The CLI inherits Gemini CLI'sdiff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.goindex ee586bb278..2ea9dd18d4 100644--- a/server/internal/daemon/execenv/execenv_test.go+++ b/server/internal/daemon/execenv/execenv_test.go@@ -1267,6 +1267,33 @@ func TestWriteContextFilesKiroNativeSkills(t *testing.T) {}}+func TestWriteContextFilesQoderNativeSkills(t *testing.T) {+ t.Parallel()+ dir := t.TempDir()++ ctx := TaskContextForEnv{+ IssueID: "qoder-skill-test",+ AgentSkills: []SkillContextForEnv{+ {Name: "Go Conventions", Content: "Follow Go conventions."},+ },+ }++ if err := writeContextFiles(dir, "qoder", ctx, nil); err != nil {+ t.Fatalf("writeContextFiles failed: %v", err)+ }++ skillMd, err := os.ReadFile(filepath.Join(dir, ".qoder", "skills", "go-conventions", "SKILL.md"))+ if err != nil {+ t.Fatalf("failed to read .qoder/skills/go-conventions/SKILL.md: %v", err)+ }+ if !strings.Contains(string(skillMd), "Follow Go conventions.") {+ t.Error("SKILL.md missing content")+ }+ if _, err := os.Stat(filepath.Join(dir, ".agent_context", "skills")); !os.IsNotExist(err) {+ t.Error("expected .agent_context/skills/ to NOT exist for Qoder provider")+ }+}+func TestInjectRuntimeConfigOpencode(t *testing.T) {t.Parallel()dir := t.TempDir()@@ -1333,6 +1360,36 @@ func TestInjectRuntimeConfigKiro(t *testing.T) {}}+func TestInjectRuntimeConfigQoder(t *testing.T) {+ t.Parallel()+ dir := t.TempDir()++ ctx := TaskContextForEnv{+ IssueID: "test-issue-id",+ AgentSkills: []SkillContextForEnv{{Name: "Coding", Content: "Write good code."}},+ }++ if _, err := InjectRuntimeConfig(dir, "qoder", ctx); err != nil {+ t.Fatalf("InjectRuntimeConfig failed: %v", err)+ }++ content, err := os.ReadFile(filepath.Join(dir, "AGENTS.md"))+ if err != nil {+ t.Fatalf("failed to read AGENTS.md: %v", err)+ }++ s := string(content)+ if !strings.Contains(s, "Multica Agent Runtime") {+ t.Error("AGENTS.md missing meta skill header")+ }+ if !strings.Contains(s, "Coding") {+ t.Error("AGENTS.md missing skill name")+ }+ if !strings.Contains(s, "discovered automatically") {+ t.Error("AGENTS.md missing native skill discovery hint")+ }+}+// TestInjectRuntimeConfigAntigravity pins that AGENTS.md for Antigravity// advertises native skill discovery (rather than the .agent_context fallback)// — the CLI inherits Gemini CLI's workspace skill layout at .agents/skills/.diff --git a/server/internal/daemon/execenv/runtime_config.go b/server/internal/daemon/execenv/runtime_config.goindex b2595bf839..0a4f507ac0 100644--- a/server/internal/daemon/execenv/runtime_config.go+++ b/server/internal/daemon/execenv/runtime_config.go@@ -159,6 +159,7 @@ func formatProjectResource(r ProjectResourceForEnv) string {// For Cursor: writes {workDir}/AGENTS.md (skills discovered natively from .cursor/skills/)// For Kimi: writes {workDir}/AGENTS.md (Kimi Code CLI reads AGENTS.md natively; skills auto-discovered from project skills dirs)// For Kiro: writes {workDir}/AGENTS.md (Kiro CLI reads AGENTS.md natively; skills auto-discovered from project skills dirs)+// For Qoder: writes {workDir}/AGENTS.md (skills discovered from .qoder/skills/, user-level ~/.qoder/skills is unaffected)// For Antigravity: writes {workDir}/AGENTS.md (agy CLI reads AGENTS.md natively; skills discovered natively from .agents/skills/ — see https://antigravity.google/docs/gcli-migration)func InjectRuntimeConfig(workDir, provider string, ctx TaskContextForEnv) (string, error) {content := buildMetaSkillContent(provider, ctx)@@ -179,7 +180,7 @@ func runtimeConfigPath(workDir, provider string) string {switch provider {case "claude", "codebuddy":return filepath.Join(workDir, "CLAUDE.md")- case "codex", "copilot", "opencode", "openclaw", "hermes", "pi", "cursor", "kimi", "kiro", "antigravity":+ case "codex", "copilot", "opencode", "openclaw", "hermes", "pi", "cursor", "kimi", "kiro", "antigravity", "qoder":return filepath.Join(workDir, "AGENTS.md")case "gemini":return filepath.Join(workDir, "GEMINI.md")@@ -713,12 +714,13 @@ func buildMetaSkillContent(provider string, ctx TaskContextForEnv) string {case "claude", "codebuddy":// Claude/CodeBuddy discovers skills natively from .claude/skills/ — just list names.b.WriteString("You have the following skills installed (discovered automatically):\n\n")- case "codex", "copilot", "opencode", "openclaw", "pi", "cursor", "kimi", "kiro", "antigravity":- // Codex, Copilot, OpenCode, OpenClaw, Pi, Cursor, Kimi, Kiro, and- // Antigravity discover skills natively from their respective paths.+ case "codex", "copilot", "opencode", "openclaw", "pi", "cursor", "kimi", "kiro", "qoder", "antigravity":+ // Codex, Copilot, OpenCode, OpenClaw, Pi, Cursor, Kimi, Kiro, Qoder,+ // and Antigravity discover skills natively from their respective paths.// For OpenClaw, the daemon also writes a per-task openclaw-config.json// (exported via OPENCLAW_CONFIG_PATH) that pins agents.defaults.workspace// to the task workdir so the CLI's scanner picks up {workDir}/skills/.+ // Qoder discovers project skills from {workDir}/.qoder/skills/.// Antigravity inherits Gemini CLI's workspace skill layout —// {workDir}/.agents/skills/ — see resolveSkillsDir.b.WriteString("You have the following skills installed (discovered automatically):\n\n")diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex 4ae44692cf..e17a48d52b 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -1,7 +1,7 @@// Package agent provides a unified interface for executing prompts via// coding agents (Claude Code, CodeBuddy, Codex, Copilot, OpenCode, OpenClaw,-// Hermes, Gemini, Pi, Cursor, Kimi, Kiro, Antigravity). It mirrors the happy-cli-// AgentBackend pattern, translated to idiomatic Go.+// Hermes, Gemini, Pi, Cursor, Kimi, Kiro, Antigravity, Qoder). It mirrors the+// happy-cli AgentBackend pattern, translated to idiomatic Go.package agentimport (@@ -127,18 +127,20 @@ type Result struct {// Config configures a Backend instance.type Config struct {- ExecutablePath string // path to CLI binary (claude, codebuddy, codex, copilot, opencode, openclaw, hermes, gemini, pi, cursor, kimi, kiro-cli, agy)+ ExecutablePath string // path to CLI binary (claude, codebuddy, codex, copilot, opencode, openclaw, hermes, gemini, pi, cursor, kimi, kiro-cli, agy, qodercli)Env map[string]string // extra environment variablesLogger *slog.Logger}// New creates a Backend for the given agent type.-// Supported types: "claude", "codebuddy", "codex", "copilot", "opencode", "openclaw", "hermes", "gemini", "pi", "cursor", "kimi", "kiro", "antigravity".+// Supported types: "claude", "codebuddy", "codex", "copilot", "opencode", "openclaw", "hermes", "gemini", "pi", "cursor", "kimi", "kiro", "antigravity", "qoder".//-// SupportedTypes is the canonical whitelist of agent types New can construct.-// It MUST stay in lockstep with the switch in New below and the+// SupportedTypes is the canonical whitelist of agent types eligible to back a+// custom runtime profile. It MUST stay in lockstep with the// runtime_profile.protocol_family CHECK constraint (migration 120): a custom// runtime profile may only be based on a backend Multica officially supports.+// (qoder is a built-in provider New can construct, but it is not offered as a+// custom-profile base, so it is intentionally absent from this list.)var SupportedTypes = []string{"claude","codebuddy",@@ -199,8 +201,10 @@ func New(agentType string, cfg Config) (Backend, error) {return &kiroBackend{cfg: cfg}, nilcase "antigravity":return &antigravityBackend{cfg: cfg}, nil+ case "qoder":+ return &qoderBackend{cfg: cfg}, nildefault:- return nil, fmt.Errorf("unknown agent type: %q (supported: claude, codebuddy, codex, copilot, opencode, openclaw, hermes, gemini, pi, cursor, kimi, kiro, antigravity)", agentType)+ return nil, fmt.Errorf("unknown agent type: %q (supported: claude, codebuddy, codex, copilot, opencode, openclaw, hermes, gemini, pi, cursor, kimi, kiro, antigravity, qoder)", agentType)}}@@ -229,6 +233,7 @@ var launchHeaders = map[string]string{"openclaw": "openclaw agent (json)","opencode": "opencode run (json)","pi": "pi (json mode)",+ "qoder": "qodercli --acp",}// LaunchHeader returns the user-visible launch skeleton for agentType, or andiff --git a/server/pkg/agent/agent_test.go b/server/pkg/agent/agent_test.goindex e6bb8cc800..9c7730006c 100644--- a/server/pkg/agent/agent_test.go+++ b/server/pkg/agent/agent_test.go@@ -50,6 +50,17 @@ func TestNewReturnsCopilotBackend(t *testing.T) {}}+func TestNewReturnsQoderBackend(t *testing.T) {+ t.Parallel()+ b, err := New("qoder", Config{ExecutablePath: "/nonexistent/qodercli"})+ if err != nil {+ t.Fatalf("New(qoder) error: %v", err)+ }+ if _, ok := b.(*qoderBackend); !ok {+ t.Fatalf("expected *qoderBackend, got %T", b)+ }+}+func TestNewReturnsAntigravityBackend(t *testing.T) {t.Parallel()b, err := New("antigravity", Config{ExecutablePath: "/nonexistent/agy"})@@ -95,7 +106,7 @@ func TestLaunchHeaderCoversAllSupportedBackends(t *testing.T) {// entry to launchHeaders in agent.go and extend this list.supported := []string{"antigravity", "claude", "codebuddy", "codex", "copilot", "cursor", "gemini",- "hermes", "kimi", "kiro", "openclaw", "opencode", "pi",+ "hermes", "kimi", "kiro", "openclaw", "opencode", "pi", "qoder",}for _, t_ := range supported {if header := LaunchHeader(t_); header == "" {diff --git a/server/pkg/agent/hermes_test.go b/server/pkg/agent/hermes_test.goindex 4fb5b4e8d1..282f2bfcef 100644--- a/server/pkg/agent/hermes_test.go+++ b/server/pkg/agent/hermes_test.go@@ -2102,7 +2102,7 @@ func TestHermesResumeIncludesMcpServers(t *testing.T) {ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{- Timeout: 5 * time.Second,+ Timeout: 30 * time.Second,ResumeSessionID: "ses_resume",McpConfig: json.RawMessage(`{"mcpServers":{"fetch":{"command":"uvx"}}}`),})@@ -2157,7 +2157,7 @@ func TestHermesDropsRemoteMcpWhenCapabilityNotAdvertised(t *testing.T) {ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{- Timeout: 5 * time.Second,+ Timeout: 30 * time.Second,McpConfig: json.RawMessage(`{"mcpServers":{"local":{"command":"uvx"},"remote-http":{"type":"http","url":"https://x/mcp"},@@ -2209,7 +2209,7 @@ func TestHermesKeepsRemoteMcpWhenCapabilityAdvertised(t *testing.T) {ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{- Timeout: 5 * time.Second,+ Timeout: 30 * time.Second,McpConfig: json.RawMessage(`{"mcpServers":{"local":{"command":"uvx"},"remote-http":{"type":"http","url":"https://x/mcp"},diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.goindex 7c99216df8..17c5bd9657 100644--- a/server/pkg/agent/models.go+++ b/server/pkg/agent/models.go@@ -130,6 +130,10 @@ func ListModels(ctx context.Context, providerType, executablePath string) ([]Modreturn cachedDiscovery(providerType, func() ([]Model, error) {return discoverKiroModels(ctx, executablePath)})+ case "qoder":+ return cachedDiscovery(providerType, func() ([]Model, error) {+ return discoverQoderModels(ctx, executablePath)+ })case "opencode":return cachedDiscovery(discoveryCacheKey(providerType, executablePath), func() ([]Model, error) {return discoverOpenCodeModels(ctx, executablePath)@@ -828,6 +832,16 @@ func discoverCopilotModels(ctx context.Context, executablePath string) ([]Model,return models, nil}+// discoverQoderModels spins up `qodercli --yolo --acp` and parses models from session/new.+func discoverQoderModels(ctx context.Context, executablePath string) ([]Model, error) {+ return discoverACPModels(ctx, executablePath, acpDiscoveryProvider{+ defaultBin: "qodercli",+ clientName: "multica-model-discovery",+ acpArgs: []string{"--yolo", "--acp"},+ tmpdirPrefix: "multica-qoder-discovery-",+ })+}+// acpDiscoveryProvider configures how discoverACPModels launches an// ACP-speaking agent CLI. The shared helper drives every CLI in// the same way (initialize → session/new → parse models block) — the@@ -849,9 +863,8 @@ type acpDiscoveryProvider struct {// discoverACPModels runs the ACP handshake for any agent CLI that// implements the standard `initialize` + `session/new` flow and// advertises its model catalog in the response under-// `models.availableModels` / `models.currentModelId`. This covers-// Hermes and Kimi today; future ACP backends can plug in by adding-// an acpDiscoveryProvider entry instead of duplicating the loop.+// `models.availableModels` / `models.currentModelId`. Provider-specific+// `launchArgs` select ACP mode (e.g. `acp` vs `--acp`).func discoverACPModels(ctx context.Context, executablePath string, p acpDiscoveryProvider) ([]Model, error) {if executablePath == "" {executablePath = p.defaultBindiff --git a/server/pkg/agent/models_test.go b/server/pkg/agent/models_test.goindex db663e0e83..49310d5671 100644--- a/server/pkg/agent/models_test.go+++ b/server/pkg/agent/models_test.go@@ -331,6 +331,21 @@ func TestListModelsKiroWithoutBinary(t *testing.T) {}}+func TestListModelsQoderWithoutBinary(t *testing.T) {+ ctx := context.Background()+ modelCacheMu.Lock()+ delete(modelCache, "qoder")+ modelCacheMu.Unlock()++ got, err := ListModels(ctx, "qoder", "/nonexistent/qodercli")+ if err != nil {+ t.Fatalf("ListModels(qoder) error: %v", err)+ }+ if got == nil {+ t.Error("expected non-nil slice even when binary is missing")+ }+}+func TestListModelsUnknownProvider(t *testing.T) {ctx := context.Background()_, err := ListModels(ctx, "nonexistent", "")diff --git a/server/pkg/agent/qoder.go b/server/pkg/agent/qoder.gonew file mode 100644index 0000000000..6a0a4b5f94--- /dev/null+++ b/server/pkg/agent/qoder.go@@ -0,0 +1,436 @@+package agent++import (+ "bufio"+ "context"+ "fmt"+ "io"+ "os/exec"+ "strings"+ "sync"+ "sync/atomic"+ "time"+)++// qoderBlockedArgs are flags hardcoded by the daemon that must not be+// overridden by user-configured custom_args. Qoder enters ACP mode via the+// global `--acp` flag; letting users strip or duplicate it would break the+// daemon↔Qoder transport contract. `--yolo` is daemon-owned so headless ACP+// always runs in bypass-permissions mode (see Qoder ACP docs). The legacy `acp`+// subcommand style is blocked so custom_args cannot switch the binary mode.+var qoderBlockedArgs = map[string]blockedArgMode{+ "--acp": blockedStandalone,+ "acp": blockedStandalone,+ "--yolo": blockedStandalone,+}++// qoderBackend implements Backend by spawning `qodercli --yolo --acp` and+// communicating via the ACP (Agent Communication Protocol) JSON-RPC 2.0+// transport over stdin/stdout.+//+// Qoder CLI uses global flags (`--yolo`, `--acp`), not an `acp` subcommand. We+// reuse hermesClient like Hermes/Kimi/Kiro and mirror their streaming gate so+// history replay flushed during session/setup does not corrupt the streamed+// output or leave the UI stuck on a stale assistant chunk.+type qoderBackend struct {+ cfg Config+}++var qoderReaderDrainGrace = 2 * time.Second++type qoderMessageStream struct {+ ch chan Message+ mu sync.Mutex+ closed bool+}++func newQoderMessageStream(size int) *qoderMessageStream {+ return &qoderMessageStream{ch: make(chan Message, size)}+}++func (s *qoderMessageStream) send(msg Message) {+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.closed {+ return+ }+ trySend(s.ch, msg)+}++func (s *qoderMessageStream) close() {+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.closed {+ return+ }+ s.closed = true+ close(s.ch)+}++func (b *qoderBackend) Execute(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {+ execPath := b.cfg.ExecutablePath+ if execPath == "" {+ execPath = "qodercli"+ }+ if _, err := exec.LookPath(execPath); err != nil {+ return nil, fmt.Errorf("qoder executable not found at %q: %w", execPath, err)+ }++ // Translate the agent's mcp_config (Claude-style object of objects) into+ // the array shape ACP session/new and session/resume expect. Reuse the+ // shared converter so remote MCP `headers` (e.g. Authorization) survive as+ // [{name, value}] and output is deterministic. Fail closed on malformed+ // JSON so the launch surfaces the real error instead of silently dropping+ // every MCP server.+ mcpServers, err := buildACPMcpServers(opts.McpConfig, b.cfg.Logger)+ if err != nil {+ return nil, fmt.Errorf("qoder: invalid mcp_config: %w", err)+ }++ timeout := opts.Timeout+ runCtx, cancel := runContext(ctx, timeout)++ qoderArgs := append(+ []string{"--yolo", "--acp"},+ filterCustomArgs(opts.CustomArgs, qoderBlockedArgs, b.cfg.Logger)...,+ )+ cmd := exec.CommandContext(runCtx, execPath, qoderArgs...)+ hideAgentWindow(cmd)+ b.cfg.Logger.Info("agent command", "exec", execPath, "args", qoderArgs)+ if opts.Cwd != "" {+ cmd.Dir = opts.Cwd+ }+ cmd.Env = buildEnv(b.cfg.Env)++ stdout, err := cmd.StdoutPipe()+ if err != nil {+ cancel()+ return nil, fmt.Errorf("qoder stdout pipe: %w", err)+ }+ stdin, err := cmd.StdinPipe()+ if err != nil {+ cancel()+ return nil, fmt.Errorf("qoder stdin pipe: %w", err)+ }+ // StderrPipe + an explicit copier give us a join point (`stderrDone`)+ // that fires before the failure-promotion decision; see the matching+ // comment in hermes.go for why the io.MultiWriter form races with+ // stopReason=end_turn under load (a terminal provider error can land+ // after we've already read finalOutput and reported "completed").+ providerErr := newACPProviderErrorSniffer("qoder")+ stderr, err := cmd.StderrPipe()+ if err != nil {+ cancel()+ return nil, fmt.Errorf("qoder stderr pipe: %w", err)+ }++ if err := cmd.Start(); err != nil {+ cancel()+ return nil, fmt.Errorf("start qoder: %w", err)+ }++ stderrSink := io.MultiWriter(newLogWriter(b.cfg.Logger, "[qoder:stderr] "), providerErr)+ stderrDone := make(chan struct{})+ go func() {+ defer close(stderrDone)+ _, _ = io.Copy(stderrSink, stderr)+ }()++ b.cfg.Logger.Info("qoder acp started", "pid", cmd.Process.Pid, "cwd", opts.Cwd)++ msgStream := newQoderMessageStream(256)+ resCh := make(chan Result, 1)++ var outputMu sync.Mutex+ var output strings.Builder+ var streamingCurrentTurn atomic.Bool++ promptDone := make(chan hermesPromptResult, 1)++ c := &hermesClient{+ cfg: b.cfg,+ stdin: stdin,+ pending: make(map[int]*pendingRPC),+ pendingTools: make(map[string]*pendingToolCall),+ acceptNotification: func(string) bool {+ return streamingCurrentTurn.Load()+ },+ onMessage: func(msg Message) {+ if !streamingCurrentTurn.Load() {+ return+ }+ if msg.Type == MessageToolUse {+ msg.Tool = kimiToolNameFromTitle(msg.Tool)+ }+ if msg.Type == MessageText {+ outputMu.Lock()+ output.WriteString(msg.Content)+ outputMu.Unlock()+ }+ msgStream.send(msg)+ },+ onPromptDone: func(result hermesPromptResult) {+ if !streamingCurrentTurn.Load() {+ return+ }+ select {+ case promptDone <- result:+ default:+ }+ },+ }++ readerDone := make(chan struct{})+ go func() {+ defer close(readerDone)+ scanner := bufio.NewScanner(stdout)+ scanner.Buffer(make([]byte, 0, 1024*1024), 10*1024*1024)+ for scanner.Scan() {+ line := strings.TrimSpace(scanner.Text())+ if line == "" {+ continue+ }+ c.handleLine(line)+ }+ c.closeAllPending(fmt.Errorf("qoder process exited"))+ }()++ go func() {+ defer cancel()+ defer msgStream.close()+ defer close(resCh)+ defer func() {+ stdin.Close()+ _ = cmd.Wait()+ }()++ startTime := time.Now()+ finalStatus := "completed"+ var finalError string+ var sessionID string+ effectiveModel := strings.TrimSpace(opts.Model)++ initResult, err := c.request(runCtx, "initialize", map[string]any{+ "protocolVersion": 1,+ "clientInfo": map[string]any{+ "name": "multica-agent-sdk",+ "version": "0.2.0",+ },+ "clientCapabilities": map[string]any{},+ })+ if err != nil {+ finalStatus = "failed"+ finalError = fmt.Sprintf("qoder initialize failed: %v", err)+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}+ return+ }++ // Drop MCP entries whose remote transport the runtime didn't+ // advertise. See the matching comment in hermes.go for why+ // unconditionally sending http/sse to a stdio-only ACP runtime+ // tanks the whole session/new.+ mcpServers = filterACPMcpServersByCapability(mcpServers, extractACPMcpCapabilities(initResult), "qoder", b.cfg.Logger)++ cwd := opts.Cwd+ if cwd == "" {+ cwd = "."+ }++ if opts.ResumeSessionID != "" {+ result, err := c.request(runCtx, "session/resume", map[string]any{+ "cwd": cwd,+ "sessionId": opts.ResumeSessionID,+ "mcpServers": mcpServers,+ })+ if err != nil {+ finalStatus = "failed"+ finalError = fmt.Sprintf("qoder session/resume failed: %v", err)+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}+ return+ }+ var changed bool+ sessionID, changed = resolveResumedSessionID(opts.ResumeSessionID, result)+ if changed {+ b.cfg.Logger.Warn("agent returned a different session id on resume — original was likely lost; continuing with the new id",+ "backend", "qoder",+ "requested", opts.ResumeSessionID,+ "actual", sessionID,+ )+ }+ if effectiveModel == "" {+ effectiveModel = extractACPCurrentModelID(result)+ }+ } else {+ result, err := c.request(runCtx, "session/new", map[string]any{+ "cwd": cwd,+ "mcpServers": mcpServers,+ })+ if err != nil {+ finalStatus = "failed"+ finalError = fmt.Sprintf("qoder session/new failed: %v", err)+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}+ return+ }+ sessionID = extractACPSessionID(result)+ if sessionID == "" {+ finalStatus = "failed"+ finalError = "qoder session/new returned no session ID"+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}+ return+ }+ if effectiveModel == "" {+ effectiveModel = extractACPCurrentModelID(result)+ }+ }++ c.sessionID = sessionID+ b.cfg.Logger.Info("qoder session created", "session_id", sessionID)++ if opts.Model != "" {+ if _, err := c.request(runCtx, "session/set_model", map[string]any{+ "sessionId": sessionID,+ "modelId": opts.Model,+ }); err != nil {+ b.cfg.Logger.Warn("qoder set_session_model failed", "error", err, "requested_model", opts.Model)+ finalStatus = "failed"+ finalError = fmt.Sprintf("qoder could not switch to model %q: %v", opts.Model, err)+ if opts.ResumeSessionID != "" && isACPSessionNotFound(err) {+ // On a resumed session with a model override, the dead+ // session surfaces here instead of at session/prompt.+ // Clear the id so the daemon's resume-failure fallback+ // retries fresh and stores the replacement session.+ b.cfg.Logger.Warn("resumed session not found at set_model time; clearing session id so the daemon retries fresh",+ "backend", "qoder",+ "session_id", sessionID,+ )+ sessionID = ""+ }+ resCh <- Result{+ Status: finalStatus,+ Error: finalError,+ DurationMs: time.Since(startTime).Milliseconds(),+ SessionID: sessionID,+ }+ return+ }+ b.cfg.Logger.Info("qoder session model set", "model", opts.Model)+ }++ userText := prompt+ if opts.SystemPrompt != "" {+ userText = opts.SystemPrompt + "\n\n---\n\n" + prompt+ }++ // Flip just before session/prompt so history replay flushed during setup+ // is dropped; every notification for this turn is processed afterward.+ streamingCurrentTurn.Store(true)+ _, err = c.request(runCtx, "session/prompt", map[string]any{+ "sessionId": sessionID,+ "prompt": []map[string]any{+ {"type": "text", "text": userText},+ },+ })+ if err != nil {+ if runCtx.Err() == context.DeadlineExceeded {+ finalStatus = "timeout"+ finalError = fmt.Sprintf("qoder timed out after %s", timeout)+ } else if runCtx.Err() == context.Canceled {+ finalStatus = "aborted"+ finalError = "execution cancelled"+ } else {+ finalStatus = "failed"+ finalError = fmt.Sprintf("qoder session/prompt failed: %v", err)+ if opts.ResumeSessionID != "" && isACPSessionNotFound(err) {+ // The runtime may echo the requested id from+ // session/resume and only reject it at prompt time.+ // Empty SessionID lets the daemon retry with a fresh+ // session instead of pinning future runs to the stale id.+ b.cfg.Logger.Warn("resumed session not found at prompt time; clearing session id so the daemon retries fresh",+ "backend", "qoder",+ "session_id", sessionID,+ )+ sessionID = ""+ }+ }+ } else {+ select {+ case pr := <-promptDone:+ if pr.stopReason == "cancelled" {+ finalStatus = "aborted"+ finalError = "qoder cancelled the prompt"+ }+ c.usageMu.Lock()+ c.usage.InputTokens += pr.usage.InputTokens+ c.usage.OutputTokens += pr.usage.OutputTokens+ c.usage.CacheReadTokens += pr.usage.CacheReadTokens+ c.usageMu.Unlock()+ default:+ }+ }++ duration := time.Since(startTime)+ b.cfg.Logger.Info("qoder finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())++ stdin.Close()+ cancel()++ // Qoder ACP may keep the process — and the stdout/stderr pipes — open+ // after session/prompt returns (it can leave a child holding the+ // inherited fds). The prompt response is already terminal, so bound the+ // drain: wait for both the stdout reader and the stderr copier, but no+ // longer than the grace window. CommandContext cancellation above is+ // what actually tears the process down. Draining stderr here is what+ // makes the provider-error promotion below see a terminal marker before+ // we decide the final status.+ drainCtx, drainCancel := context.WithTimeout(context.Background(), qoderReaderDrainGrace)+ select {+ case <-readerDone:+ case <-drainCtx.Done():+ }+ select {+ case <-stderrDone:+ case <-drainCtx.Done():+ }+ drainCancel()+ // The stdout reader may still run after the grace window. Flip the+ // stream gate before this goroutine's defer closes msgStream; if a+ // late reader already passed the gate, qoderMessageStream serializes+ // send and close so the late send is dropped instead of panicking.+ streamingCurrentTurn.Store(false)++ outputMu.Lock()+ finalOutput := output.String()+ outputMu.Unlock()++ // Promote completed→failed when stderr or the agent text stream show a+ // terminal upstream-LLM failure (HTTP 4xx / rate-limit / expired token).+ // Mirrors hermes/kimi/kiro; without it a run that exhausts retries still+ // reports "completed" because session/prompt ends with stopReason=end_turn+ // even though qodercli wrote a terminal error to stderr.+ finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, finalOutput, providerErr)++ c.usageMu.Lock()+ u := c.usage+ c.usageMu.Unlock()++ var usageMap map[string]TokenUsage+ if u.InputTokens > 0 || u.OutputTokens > 0 || u.CacheReadTokens > 0 {+ model := effectiveModel+ if model == "" {+ model = "unknown"+ }+ usageMap = map[string]TokenUsage{model: u}+ }++ resCh <- Result{+ Status: finalStatus,+ Output: finalOutput,+ Error: finalError,+ DurationMs: duration.Milliseconds(),+ SessionID: sessionID,+ Usage: usageMap,+ }+ }()++ return &Session{Messages: msgStream.ch, Result: resCh}, nil+}diff --git a/server/pkg/agent/qoder_test.go b/server/pkg/agent/qoder_test.gonew file mode 100644index 0000000000..889ed76f0f--- /dev/null+++ b/server/pkg/agent/qoder_test.go@@ -0,0 +1,793 @@+package agent++import (+ "context"+ "encoding/json"+ "log/slog"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++func fakeQoderACPScript() string {+ return `#!/bin/sh+# Fake qodercli — exercises argv (--yolo --acp), blocked custom_args, set_model failure, and prompt success.+if [ -n "$QODER_ARGS_FILE" ]; then+ for arg in "$@"; do+ printf '%s\n' "$arg" >> "$QODER_ARGS_FILE"+ done+fi+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"+ ;;+ *'"method":"session/new"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_fake"}}\n' "$id"+ ;;+ *'"method":"session/set_model"'*)+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32602,"message":"model not available: bogus-model"}}\n' "$id"+ exit 0+ ;;+ *'"method":"session/prompt"'*)+ printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_fake","update":{"type":"AgentMessageChunk","content":{"type":"text","text":"ok"}}}}\n'+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":1,"outputTokens":2}}}\n' "$id"+ exit 0+ ;;+ esac+done+`+}++func fakeQoderACPStaleResumeScript() string {+ return `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"+ ;;+ *'"method":"session/resume"'*)+ sid=$(printf '%s' "$line" | sed -n 's/.*"sessionId":"\([^"]*\)".*/\1/p')+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"%s"}}\n' "$id" "$sid"+ ;;+ *'"method":"session/prompt"'*)+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"Session not found"}}\n' "$id"+ exit 0+ ;;+ esac+done+`+}++func fakeQoderACPStaleResumeSetModelScript() string {+ return `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"+ ;;+ *'"method":"session/resume"'*)+ sid=$(printf '%s' "$line" | sed -n 's/.*"sessionId":"\([^"]*\)".*/\1/p')+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"%s"}}\n' "$id" "$sid"+ ;;+ *'"method":"session/set_model"'*)+ printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32603,"message":"Session not found"}}\n' "$id"+ exit 0+ ;;+ esac+done+`+}++func fakeQoderACPScriptWithLeakedStdout() string {+ return `#!/bin/sh+# Fake qodercli that returns session/prompt but leaves stdout open via a child+# process, matching qodercli ACP staying alive after the turn completes.+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"+ ;;+ *'"method":"session/new"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_fake"}}\n' "$id"+ ;;+ *'"method":"session/prompt"'*)+ printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_fake","update":{"type":"AgentMessageChunk","content":{"type":"text","text":"ok"}}}}\n'+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":1,"outputTokens":2}}}\n' "$id"+ sleep 30 &+ wait+ ;;+ esac+done+`+}++func fakeQoderACPScriptWithLateStdoutAfterResult() string {+ return `#!/bin/sh+# Fake qodercli that returns session/prompt, then leaves stdout open via a+# child process that writes one more notification after the bounded drain grace.+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"+ ;;+ *'"method":"session/new"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_fake"}}\n' "$id"+ ;;+ *'"method":"session/prompt"'*)+ printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_fake","update":{"type":"AgentMessageChunk","content":{"type":"text","text":"ok"}}}}\n'+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":1,"outputTokens":2}}}\n' "$id"+ ( sleep 0.08; printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_fake","update":{"type":"AgentMessageChunk","content":{"type":"text","text":"late"}}}}\n' ) &+ sleep 30+ ;;+ esac+done+`+}++// fakeQoderACPScriptCapturingRPC records every JSON-RPC line it receives to+// $QODER_RPC_FILE so a test can inspect the session/new mcpServers payload that+// qoder actually sent (e.g. that remote MCP headers survived the conversion).+func fakeQoderACPScriptCapturingRPC() string {+ return `#!/bin/sh+while IFS= read -r line; do+ if [ -n "$QODER_RPC_FILE" ]; then printf '%s\n' "$line" >> "$QODER_RPC_FILE"; fi+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ if [ "$QODER_INIT_MCP_SSE" = "1" ]; then+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{"mcpCapabilities":{"sse":true}}}}\n' "$id"+ else+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"+ fi+ ;;+ *'"method":"session/new"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_fake"}}\n' "$id"+ ;;+ *'"method":"session/prompt"'*)+ printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_fake","update":{"type":"AgentMessageChunk","content":{"type":"text","text":"ok"}}}}\n'+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":1,"outputTokens":2}}}\n' "$id"+ exit 0+ ;;+ esac+done+`+}++// fakeQoderACPScriptTerminalProviderError streams a normal text chunk (so the+// final output is non-empty) but writes a terminal upstream-LLM error to stderr+// before ending the turn with end_turn. This is the case promoteACPResultOnProviderError+// must catch: a successful-looking end_turn with output, masking a real failure.+func fakeQoderACPScriptTerminalProviderError() string {+ return `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"+ ;;+ *'"method":"session/new"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_fake"}}\n' "$id"+ ;;+ *'"method":"session/prompt"'*)+ printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_fake","update":{"type":"AgentMessageChunk","content":{"type":"text","text":"partial answer"}}}}\n'+ printf '%s\n' '[ERROR] API call failed after 3 retries: HTTP 429 RateLimitError' >&2+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":1,"outputTokens":2}}}\n' "$id"+ exit 0+ ;;+ esac+done+ `+}++func fakeQoderACPUsageWithDefaultModelScript() string {+ return `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"+ ;;+ *'"method":"session/new"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_model","models":{"currentModelId":"qoder:auto","availableModels":[{"modelId":"qoder:auto","name":"Qoder Auto"}]}}}\n' "$id"+ ;;+ *'"method":"session/prompt"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":17,"outputTokens":5,"cachedReadTokens":3}}}\n' "$id"+ exit 0+ ;;+ esac+done+`+}++func TestQoderBackendSetModelFailureFailsTask(t *testing.T) {+ t.Parallel()++ fakePath := filepath.Join(t.TempDir(), "qodercli")+ writeTestExecutable(t, fakePath, []byte(fakeQoderACPScript()))++ backend, err := New("qoder", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new qoder backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{+ Model: "bogus-model",+ Timeout: 30 * time.Second,+ })+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ select {+ case result, ok := <-session.Result:+ if !ok {+ t.Fatal("result channel closed without a value")+ }+ if result.Status != "failed" {+ t.Fatalf("expected status=failed, got %q (error=%q)", result.Status, result.Error)+ }+ if !strings.Contains(result.Error, `could not switch to model "bogus-model"`) {+ t.Errorf("expected error to name the requested model, got %q", result.Error)+ }+ if !strings.Contains(result.Error, "model not available") {+ t.Errorf("expected error to surface upstream message, got %q", result.Error)+ }+ if result.SessionID != "ses_fake" {+ t.Errorf("expected session id to be preserved on failure, got %q", result.SessionID)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("timeout waiting for result")+ }+}++func TestQoderBackendInvokesACPFlagAndFiltersBlockedArgs(t *testing.T) {+ t.Parallel()++ tempDir := t.TempDir()+ argsFile := filepath.Join(tempDir, "argv.txt")+ fakePath := filepath.Join(tempDir, "qodercli")+ writeTestExecutable(t, fakePath, []byte(fakeQoderACPScript()))++ backend, err := New("qoder", Config{+ ExecutablePath: fakePath,+ Logger: slog.Default(),+ Env: map[string]string{"QODER_ARGS_FILE": argsFile},+ })+ if err != nil {+ t.Fatalf("new qoder backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{+ Model: "bogus-model",+ Timeout: 30 * time.Second,+ CustomArgs: []string{"--acp", "acp", "--yolo", "--model", "extra"},+ })+ 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)+ }+ lines := strings.Split(strings.TrimSpace(string(raw)), "\n")+ if len(lines) < 2 {+ t.Fatalf("expected at least 2 argv entries, got %d: %q", len(lines), lines)+ }+ if lines[0] != "--yolo" || lines[1] != "--acp" {+ t.Fatalf("arg[0], arg[1] = %q, %q, want --yolo and --acp (full: %q)", lines[0], lines[1], lines)+ }+ for _, blocked := range []string{"acp"} {+ for _, got := range lines[2:] {+ if got == blocked {+ t.Errorf("custom_args must not inject standalone %q after daemon argv: %q", blocked, lines)+ }+ }+ }+ yoloCount := 0+ for _, got := range lines {+ if got == "--yolo" {+ yoloCount+++ }+ }+ if yoloCount != 1 {+ t.Fatalf("expected exactly one daemon --yolo, got count=%d argv=%q", yoloCount, lines)+ }+ want := []string{"--yolo", "--acp", "--model", "extra"}+ if strings.Join(lines, "\n") != strings.Join(want, "\n") {+ t.Errorf("unexpected argv after filtering: %q, want %q", lines, want)+ }+}++func TestQoderBackendHappyPath(t *testing.T) {+ t.Parallel()++ fakePath := filepath.Join(t.TempDir(), "qodercli")+ writeTestExecutable(t, fakePath, []byte(fakeQoderACPScript()))++ backend, err := New("qoder", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new qoder backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ session, err := backend.Execute(ctx, "hi", 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 err=%q", result.Status, result.Error)+ }+ if result.Output != "ok" {+ t.Fatalf("output=%q want ok", result.Output)+ }+ if result.SessionID != "ses_fake" {+ t.Fatalf("session=%q", result.SessionID)+ }+ if u := result.Usage["unknown"]; u.InputTokens != 1 || u.OutputTokens != 2 {+ t.Fatalf("usage=%+v", u)+ }+}++func TestQoderBackendNonPositiveTimeoutDoesNotImposeDeadline(t *testing.T) {+ t.Parallel()++ fakePath := filepath.Join(t.TempDir(), "qodercli")+ writeTestExecutable(t, fakePath, []byte(fakeQoderACPScript()))++ backend, err := New("qoder", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new qoder backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ session, err := backend.Execute(ctx, "hi", ExecOptions{Timeout: -1})+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ select {+ case result := <-session.Result:+ if result.Status != "completed" {+ t.Fatalf("non-positive timeout should not impose a deadline, got status=%q error=%q", result.Status, result.Error)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("timeout waiting for qoder result")+ }+}++func TestQoderBackendDoesNotWaitForeverForReaderAfterPromptDone(t *testing.T) {+ oldGrace := qoderReaderDrainGrace+ qoderReaderDrainGrace = 25 * time.Millisecond+ t.Cleanup(func() { qoderReaderDrainGrace = oldGrace })++ fakePath := filepath.Join(t.TempDir(), "qodercli")+ writeTestExecutable(t, fakePath, []byte(fakeQoderACPScriptWithLeakedStdout()))++ backend, err := New("qoder", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new qoder backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()++ session, err := backend.Execute(ctx, "hi", ExecOptions{Timeout: 30 * time.Second})+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ select {+ case result := <-session.Result:+ if result.Status != "completed" {+ t.Fatalf("status=%q err=%q", result.Status, result.Error)+ }+ if result.Output != "ok" {+ t.Fatalf("output=%q want ok", result.Output)+ }+ case <-time.After(3 * time.Second):+ t.Fatal("qoder result blocked waiting for reader shutdown")+ }+}++func TestQoderMessageStreamDropsSendAfterClose(t *testing.T) {+ stream := newQoderMessageStream(1)+ stream.close()++ defer func() {+ if r := recover(); r != nil {+ t.Fatalf("send after close panicked: %v", r)+ }+ }()+ stream.send(Message{Type: MessageText, Content: "late"})++ if _, ok := <-stream.ch; ok {+ t.Fatal("message channel should be closed")+ }+}++func TestQoderBackendIgnoresLateReaderOutputAfterGrace(t *testing.T) {+ oldGrace := qoderReaderDrainGrace+ qoderReaderDrainGrace = 25 * time.Millisecond+ t.Cleanup(func() { qoderReaderDrainGrace = oldGrace })++ fakePath := filepath.Join(t.TempDir(), "qodercli")+ writeTestExecutable(t, fakePath, []byte(fakeQoderACPScriptWithLateStdoutAfterResult()))++ backend, err := New("qoder", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new qoder backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()++ session, err := backend.Execute(ctx, "hi", ExecOptions{Timeout: 30 * time.Second})+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ select {+ case result := <-session.Result:+ if result.Status != "completed" {+ t.Fatalf("status=%q err=%q", result.Status, result.Error)+ }+ if result.Output != "ok" {+ t.Fatalf("output=%q want ok", result.Output)+ }+ case <-time.After(3 * time.Second):+ t.Fatal("qoder result blocked waiting for reader shutdown")+ }++ time.Sleep(150 * time.Millisecond)+}++// TestQoderForwardsMcpAuthHeaderToSessionNew is the end-to-end guard for the+// header-drop bug: qoder must reuse the shared buildACPMcpServers converter so a+// remote MCP server's Authorization header reaches the session/new payload as+// [{name, value}] instead of being silently stripped. We inspect the exact+// JSON-RPC the backend wrote to the (fake) qodercli stdin.+func TestQoderForwardsMcpAuthHeaderToSessionNew(t *testing.T) {+ t.Parallel()++ tempDir := t.TempDir()+ rpcFile := filepath.Join(tempDir, "rpc.txt")+ fakePath := filepath.Join(tempDir, "qodercli")+ writeTestExecutable(t, fakePath, []byte(fakeQoderACPScriptCapturingRPC()))++ backend, err := New("qoder", Config{+ ExecutablePath: fakePath,+ Logger: slog.Default(),+ Env: map[string]string{+ "QODER_RPC_FILE": rpcFile,+ "QODER_INIT_MCP_SSE": "1",+ },+ })+ if err != nil {+ t.Fatalf("new qoder backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ mcpConfig := json.RawMessage(`{"mcpServers":{"fetch":{"type":"sse","url":"https://example.com/sse","headers":{"Authorization":"Bearer tok"}}}}`)+ session, err := backend.Execute(ctx, "hi", ExecOptions{+ Timeout: 30 * time.Second,+ McpConfig: mcpConfig,+ })+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()+ <-session.Result++ raw, err := os.ReadFile(rpcFile)+ if err != nil {+ t.Fatalf("read rpc file: %v", err)+ }+ var sessionNew string+ for _, line := range strings.Split(string(raw), "\n") {+ if strings.Contains(line, `"method":"session/new"`) {+ sessionNew = line+ break+ }+ }+ if sessionNew == "" {+ t.Fatalf("no session/new request captured; rpc log:\n%s", raw)+ }+ if !strings.Contains(sessionNew, "Authorization") || !strings.Contains(sessionNew, "Bearer tok") {+ t.Fatalf("Authorization header did not survive into session/new mcpServers:\n%s", sessionNew)+ }+ // The shared converter emits headers as {name, value} pairs, not the raw+ // Claude object-map; assert that wire shape too.+ if !strings.Contains(sessionNew, `"name":"Authorization"`) || !strings.Contains(sessionNew, `"value":"Bearer tok"`) {+ t.Fatalf("expected headers as [{name,value}] in session/new payload:\n%s", sessionNew)+ }+}++func TestQoderFiltersRemoteMcpWhenInitializeDoesNotAdvertiseCapability(t *testing.T) {+ t.Parallel()++ tempDir := t.TempDir()+ rpcFile := filepath.Join(tempDir, "rpc.txt")+ fakePath := filepath.Join(tempDir, "qodercli")+ writeTestExecutable(t, fakePath, []byte(fakeQoderACPScriptCapturingRPC()))++ backend, err := New("qoder", Config{+ ExecutablePath: fakePath,+ Logger: slog.Default(),+ Env: map[string]string{"QODER_RPC_FILE": rpcFile},+ })+ if err != nil {+ t.Fatalf("new qoder backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ mcpConfig := json.RawMessage(`{"mcpServers":{"local-stdio":{"command":"uvx","args":["mcp-local"]},"remote-sse":{"type":"sse","url":"https://example.com/sse","headers":{"Authorization":"Bearer tok"}}}}`)+ session, err := backend.Execute(ctx, "hi", ExecOptions{+ Timeout: 30 * time.Second,+ McpConfig: mcpConfig,+ })+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()+ <-session.Result++ raw, err := os.ReadFile(rpcFile)+ if err != nil {+ t.Fatalf("read rpc file: %v", err)+ }+ var sessionNew string+ for _, line := range strings.Split(string(raw), "\n") {+ if strings.Contains(line, `"method":"session/new"`) {+ sessionNew = line+ break+ }+ }+ if sessionNew == "" {+ t.Fatalf("no session/new request captured; rpc log:\n%s", raw)+ }+ if !strings.Contains(sessionNew, `"name":"local-stdio"`) || !strings.Contains(sessionNew, `"command":"uvx"`) {+ t.Fatalf("stdio MCP server should remain in session/new payload:\n%s", sessionNew)+ }+ if strings.Contains(sessionNew, `"name":"remote-sse"`) || strings.Contains(sessionNew, "https://example.com/sse") || strings.Contains(sessionNew, "Bearer tok") {+ t.Fatalf("remote SSE MCP server should be filtered when initialize omits mcpCapabilities.sse:\n%s", sessionNew)+ }+}++// TestQoderPromotesTerminalProviderErrorWithOutput guards the second bug: a turn+// that ends with stopReason=end_turn AND non-empty output must still be reported+// as failed when stderr carried a terminal upstream-LLM error. Without the+// StderrPipe drain + promoteACPResultOnProviderError, this run reports+// "completed" and hides the failure.+func TestQoderPromotesTerminalProviderErrorWithOutput(t *testing.T) {+ t.Parallel()++ fakePath := filepath.Join(t.TempDir(), "qodercli")+ writeTestExecutable(t, fakePath, []byte(fakeQoderACPScriptTerminalProviderError()))++ backend, err := New("qoder", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new qoder backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ session, err := backend.Execute(ctx, "hi", ExecOptions{Timeout: 30 * time.Second})+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ select {+ case result := <-session.Result:+ if result.Status != "failed" {+ t.Fatalf("expected status=failed for a terminal provider error, got %q (output=%q error=%q)", result.Status, result.Output, result.Error)+ }+ if result.Output != "partial answer" {+ t.Errorf("expected the partial output to be preserved, got %q", result.Output)+ }+ if !strings.Contains(result.Error, "provider error") || !strings.Contains(result.Error, "429") {+ t.Errorf("expected error to surface the terminal stderr marker, got %q", result.Error)+ }+ case <-time.After(8 * time.Second):+ t.Fatal("timeout waiting for result")+ }+}++func TestQoderBackendAttributesUsageToACPDefaultModel(t *testing.T) {+ t.Parallel()++ fakePath := filepath.Join(t.TempDir(), "qodercli")+ writeTestExecutable(t, fakePath, []byte(fakeQoderACPUsageWithDefaultModelScript()))++ backend, err := New("qoder", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new qoder backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{+ Timeout: 30 * time.Second,+ })+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ select {+ case result, ok := <-session.Result:+ if !ok {+ t.Fatal("result channel closed without a value")+ }+ if result.Status != "completed" {+ t.Fatalf("expected completed result, got %q: %s", result.Status, result.Error)+ }+ if _, ok := result.Usage["unknown"]; ok {+ t.Fatalf("usage should not be attributed to unknown: %+v", result.Usage)+ }+ usage, ok := result.Usage["qoder:auto"]+ if !ok {+ t.Fatalf("expected usage under Qoder current model, got %+v", result.Usage)+ }+ if usage.InputTokens != 17 || usage.OutputTokens != 5 || usage.CacheReadTokens != 3 {+ t.Fatalf("usage = %+v, want input=17 output=5 cache_read=3", usage)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("timeout waiting for result")+ }+}++func TestQoderBackendClearsSessionIDWhenResumedSessionNotFoundAtPrompt(t *testing.T) {+ t.Parallel()++ fakePath := filepath.Join(t.TempDir(), "qodercli")+ writeTestExecutable(t, fakePath, []byte(fakeQoderACPStaleResumeScript()))++ backend, err := New("qoder", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new qoder backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{+ Timeout: 30 * time.Second,+ ResumeSessionID: "ses_stale",+ })+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ select {+ case result, ok := <-session.Result:+ if !ok {+ t.Fatal("result channel closed without a value")+ }+ if result.Status != "failed" {+ t.Fatalf("expected status=failed, got %q (error=%q)", result.Status, result.Error)+ }+ if !strings.Contains(result.Error, "Session not found") {+ t.Errorf("expected error to surface the session-not-found message, got %q", result.Error)+ }+ if result.SessionID != "" {+ t.Errorf("expected empty session id so the daemon's fresh-session retry fires, got %q", result.SessionID)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("timeout waiting for result")+ }+}++func TestQoderBackendClearsSessionIDWhenResumedSessionNotFoundAtSetModel(t *testing.T) {+ t.Parallel()++ fakePath := filepath.Join(t.TempDir(), "qodercli")+ writeTestExecutable(t, fakePath, []byte(fakeQoderACPStaleResumeSetModelScript()))++ backend, err := New("qoder", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new qoder backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{+ Timeout: 30 * time.Second,+ ResumeSessionID: "ses_stale",+ Model: "some-model",+ })+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ select {+ case result, ok := <-session.Result:+ if !ok {+ t.Fatal("result channel closed without a value")+ }+ if result.Status != "failed" {+ t.Fatalf("expected status=failed, got %q (error=%q)", result.Status, result.Error)+ }+ if !strings.Contains(result.Error, `could not switch to model "some-model"`) {+ t.Errorf("expected error to name the requested model, got %q", result.Error)+ }+ if result.SessionID != "" {+ t.Errorf("expected empty session id so the daemon's fresh-session retry fires, got %q", result.SessionID)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("timeout waiting for result")+ }+}