Skip to content

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

Go

MUL-8045: feat(runtimes): Qoder Cloud Agent as a managed cloud runtime (#9402)

Jiayuan Zhang0fe2ebf02e90
diff --git a/.env.example b/.env.example
index dfe90dd74e..078267fd00 100644
--- a/.env.example
+++ b/.env.example
@@ -715,3 +715,7 @@ POSTHOG_HOST=https://us.i.posthog.com
ANALYTICS_ENVIRONMENT=
# Force the no-op client even when POSTHOG_API_KEY is set (CI / opt-out).
ANALYTICS_DISABLED=
+
+# Server-managed QCA (Qoder Cloud Agent) runtimes are available whenever
+# MULTICA_VCS_SECRET_KEY is set: it encrypts the saved Qoder and GitHub tokens
+# and the run journal in the database. Keep it stable across restarts.
diff --git a/apps/desktop/src/renderer/src/components/desktop-choose-runtime-page.tsx b/apps/desktop/src/renderer/src/components/desktop-choose-runtime-page.tsx
new file mode 100644
index 0000000000..a78ac138ab
--- /dev/null
+++ b/apps/desktop/src/renderer/src/components/desktop-choose-runtime-page.tsx
@@ -0,0 +1,18 @@
+import { ChooseRuntimePage } from "@multica/views/agents";
+import { useDesktopRuntimeContext } from "./use-desktop-runtime-context";
+
+/**
+ * Desktop wrapper around step 1 of agent creation: only the desktop app knows
+ * which daemon is "this device", which the "this device" section is built from.
+ */
+export function DesktopChooseRuntimePage() {
+ const context = useDesktopRuntimeContext();
+ return (
+ <ChooseRuntimePage
+ localDaemonId={context.localDaemonId}
+ localMachineName={context.localMachineName}
+ hasLocalMachine
+ bootstrapping={context.bootstrapping}
+ />
+ );
+}
diff --git a/apps/desktop/src/renderer/src/pages/agent-created-page.tsx b/apps/desktop/src/renderer/src/pages/agent-created-page.tsx
new file mode 100644
index 0000000000..2f62c2930a
--- /dev/null
+++ b/apps/desktop/src/renderer/src/pages/agent-created-page.tsx
@@ -0,0 +1,8 @@
+import { useParams } from "react-router-dom";
+import { AgentCreatedPage as SharedAgentCreatedPage } from "@multica/views/agents";
+
+export function AgentCreatedPage() {
+ const { agentId } = useParams<{ agentId: string }>();
+ if (!agentId) return null;
+ return <SharedAgentCreatedPage agentId={agentId} />;
+}
diff --git a/apps/desktop/src/renderer/src/routes.tsx b/apps/desktop/src/renderer/src/routes.tsx
index 37d3ade427..39350edc40 100644
--- a/apps/desktop/src/renderer/src/routes.tsx
+++ b/apps/desktop/src/renderer/src/routes.tsx
@@ -23,9 +23,10 @@ import { DesktopRuntimesPage } from "./components/desktop-runtimes-page";
import { DesktopAgentsPage } from "./components/desktop-agents-page";
import {
AiCreateAgentPage,
- ChooseCreateMethodPage,
ManualCreateAgentPage,
} from "@multica/views/agents";
+import { DesktopChooseRuntimePage } from "./components/desktop-choose-runtime-page";
+import { AgentCreatedPage } from "./pages/agent-created-page";
import { SquadsPage, SquadDetailPage as SquadDetailPageView } from "@multica/views/squads/components";
import { InboxPage } from "@multica/views/inbox";
import { ChatPage } from "@multica/views/chat";
@@ -186,7 +187,12 @@ export const appRoutes: RouteObject[] = [
{ path: "agents", element: <DesktopAgentsPage />, handle: { title: "Agents" } },
{
path: "agents/new",
- element: <ChooseCreateMethodPage />,
+ element: <DesktopChooseRuntimePage />,
+ handle: { title: "Create Agent" },
+ },
+ {
+ path: "agents/new/done/:agentId",
+ element: <AgentCreatedPage />,
handle: { title: "Create Agent" },
},
{
diff --git a/apps/docs/content/docs/daemon-runtimes.ja.mdx b/apps/docs/content/docs/daemon-runtimes.ja.mdx
index c0c3e8d210..660c453745 100644
--- a/apps/docs/content/docs/daemon-runtimes.ja.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.ja.mdx
@@ -7,6 +7,17 @@ import { Callout } from "fumadocs-ui/components/callout";
Multica は作業の記録と調整を担い、接続されたコンピュータが実行を担います。コンピュータ上の**デーモン**(daemon)が実行を取得し、そのマシンにインストールされた AI コーディングツールを呼び出します。
+## Qoder Cloud Agent リモートランタイム
+
+Qoder Cloud Agent は割り当てられたタスクをリモートセッションで実行します。Multica サーバーが既存のデーモンプロトコルを使うブリッジを管理するため、ユーザーがローカルデーモンを起動する必要はありません。
+
+セルフホスト環境では `MULTICA_VCS_SECRET_KEY` を設定してください。ランタイム画面で Qoder Cloud Agent を追加し、QCA PAT を設定すると、利用可能な環境が読み込まれます。接続を保存して起動した後、既存の QCA Agent に紐づく Multica エージェントを追加します。認証情報は暗号化され、ワークスペース内で共有されます。GitHub 認証情報はリポジトリごとに設定し、QCA のセッション作成時に送信されます。
+
+各接続はデフォルトで最大 3 件のタスクを同時に実行します(1〜10 の範囲で変更でき、実行ごとのタイムアウトも設定できます)。それ以上はキューで待機します。同じタスクの後続の実行は、前回のセッションがアイドルであればその Qoder セッションを引き継ぎます。エージェントにはデフォルトのリポジトリを設定でき、タスクのプロジェクトにリポジトリがない場合に使われます。エージェントにはタスク ID を含むブランチ名と、タスク ID で始まる PR タイトルを使うよう指示するため、PR はタスクに自動で紐づきます。
+
+初期版はタスク実行、進捗同期、キャンセル、永続化された実行記録からの復旧に対応します。チャット、ローカルディレクトリ、添付ファイル、リモート QCA Agent の新規作成は未対応です。詳細は [README](https://github.com/multica-ai/multica/blob/main/server/cmd/qoder-runtime/README.md) を参照してください。
+
+
## デーモンとランタイムの違い
- **デーモン**は、1 台のコンピュータで動く Multica のバックグラウンドプロセスです。サーバーへの接続、ローカルツールの検出、実行の取得、結果の報告を担当します。
diff --git a/apps/docs/content/docs/daemon-runtimes.ko.mdx b/apps/docs/content/docs/daemon-runtimes.ko.mdx
index 1a082692ff..40ef2cabb3 100644
--- a/apps/docs/content/docs/daemon-runtimes.ko.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.ko.mdx
@@ -7,6 +7,17 @@ import { Callout } from "fumadocs-ui/components/callout";
Multica는 실행을 기록하고 조율하며 연결된 컴퓨터가 실행을 담당합니다. 컴퓨터의 **데몬**(daemon)이 실행을 가져간 뒤 로컬에 설치된 AI 코딩 도구를 호출합니다.
+## Qoder Cloud Agent 원격 런타임
+
+Qoder Cloud Agent는 할당된 태스크를 원격 세션으로 실행합니다. Multica 서버가 기존 데몬 프로토콜을 사용하는 브리지를 관리하므로 사용자가 로컬 데몬을 실행할 필요가 없습니다.
+
+셀프 호스팅에서는 `MULTICA_VCS_SECRET_KEY`를 설정하세요. 런타임 화면에서 Qoder Cloud Agent를 추가하고 QCA PAT를 입력하면 사용 가능한 환경을 불러옵니다. 연결을 저장하고 시작한 뒤 기존 QCA Agent에 연결된 Multica 에이전트를 추가하세요. 자격 증명은 암호화되어 워크스페이스 내에서 공유됩니다. GitHub 자격 증명은 저장소별로 설정하며 QCA 세션 생성 시 전달됩니다.
+
+각 연결은 기본적으로 최대 3개의 태스크를 동시에 실행합니다(1~10 범위에서 변경 가능하며 실행별 제한 시간도 설정할 수 있습니다). 나머지는 대기열에서 기다립니다. 같은 태스크의 후속 실행은 이전 세션이 유휴 상태이면 해당 Qoder 세션을 이어서 사용합니다. 에이전트에 기본 저장소를 설정할 수 있으며, 태스크의 프로젝트에 저장소가 없을 때 사용됩니다. 에이전트는 태스크 식별자가 포함된 브랜치 이름과 식별자로 시작하는 PR 제목을 사용하도록 안내받으므로 PR이 태스크에 자동으로 연결됩니다.
+
+초기 버전은 태스크 실행, 진행 상황 동기화, 취소, 영구 실행 기록을 통한 복구를 지원합니다. 채팅, 로컬 디렉터리, 첨부 파일, 원격 QCA Agent 생성은 지원하지 않습니다. 자세한 내용은 [README](https://github.com/multica-ai/multica/blob/main/server/cmd/qoder-runtime/README.md)를 참고하세요.
+
+
## 개념 구분
- **데몬**은 한 컴퓨터에서 실행되는 Multica 백그라운드 프로그램입니다. 서버 연결, 로컬 도구 검색, 실행 수령, 결과 반환을 담당합니다.
diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdx
index 05225b7e2d..acf106d784 100644
--- a/apps/docs/content/docs/daemon-runtimes.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.mdx
@@ -7,6 +7,21 @@ import { Callout } from "fumadocs-ui/components/callout";
Multica records and coordinates the work; connected computers execute it. The **daemon** on a computer claims runs and invokes the AI coding tools installed on that machine.
+## Qoder Cloud Agent remote runtime
+
+Qoder Cloud Agent runs assigned issues through remote QCA sessions. The Multica server supervises a bridge that uses the existing daemon task protocol; no user-operated local daemon is needed for this runtime.
+
+For self-hosted installations, set `MULTICA_VCS_SECRET_KEY` on the server. In **Runtimes → Add remote runtime**, choose Qoder Cloud Agent and configure a QCA PAT. Available environments are loaded from Qoder; a single environment is selected automatically. Save and start the connection, then add a Multica agent linked to an existing QCA Agent.
+
+Connection credentials are encrypted and shared within the workspace. Administrators manage the connection; members can select accessible QCA agents. GitHub credentials are bound to repository URLs, while projects choose the repository and starting branch. Repository credentials are passed to QCA when creating a coding session. PAT values are never returned to the browser after saving.
+
+Each connection runs up to three issues at once by default (configurable from 1 to 10, with a per-run timeout); further runs wait in the queue. A follow-up on the same issue continues the agent's previous Qoder session when it is idle. An agent can set a default repository, used when the issue's project has none. The agent is asked to push a branch named after the issue identifier and to prefix the pull request title with it, so the pull request is linked to the issue.
+
+This first version supports issue runs, progress reporting, cancellation, and recovery from a persisted run journal. Configure models, tools, and skills in Qoder. Interactive chat, local directories, attachments, and creating remote QCA agents from Multica are not supported. The Runtimes page separates remote runtimes from connected computers.
+
+For standalone bridge setup and operational limitations, see the [Qoder runtime README](https://github.com/multica-ai/multica/blob/main/server/cmd/qoder-runtime/README.md).
+
+
## Daemon vs runtime
- The **daemon** is the Multica background process running on one computer. It connects to the server, discovers local tools, claims runs, and reports results back.
diff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdx
index 99d5c26a85..3a0c8da47c 100644
--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx
@@ -7,6 +7,21 @@ import { Callout } from "fumadocs-ui/components/callout";
Multica 负责记录和协调工作,连接的电脑负责执行。电脑上的**守护进程**(daemon)领取运行,再调用本机安装的 AI 编程工具。
+## Qoder Cloud Agent 远端运行时
+
+Qoder Cloud Agent 通过远端会话执行分配的任务。Multica 服务端管理桥接进程,复用现有守护进程任务协议,无需用户启动本地守护进程。
+
+自托管部署需在服务端设置 `MULTICA_VCS_SECRET_KEY`。进入**运行时 → 添加远端运行时**,选择 Qoder Cloud Agent 并配置 QCA PAT。页面自动加载可用环境,只有一个时默认选中。保存并启动后,添加关联已有 QCA Agent 的 Multica 智能体。
+
+连接凭证加密保存,在工作区内共享。管理员管理连接,成员可以选择可访问的 QCA 智能体。GitHub 凭证按仓库 URL 绑定,项目选择仓库和起始分支;创建编码会话时,仓库凭证会传给 QCA。保存后的 PAT 不会返回浏览器。
+
+每个连接默认最多同时运行 3 个任务(可在 1 到 10 之间调整,并可设置单次运行超时),其余任务排队等待。同一任务的后续运行会在上一会话空闲时继续使用该 Qoder 会话。智能体可以设置默认仓库,在任务所属项目未绑定仓库时使用。智能体会被要求以任务标识命名分支,并在 PR 标题前加上任务标识,以便 PR 自动关联到任务。
+
+首版支持任务运行、进度同步、取消和基于持久化记录的恢复。模型、工具和 skill 在 Qoder 中配置;暂不支持交互聊天、本地目录、附件,也不支持从 Multica 创建远端 QCA 智能体。运行时页面分别展示远端运行时和电脑。
+
+独立桥接进程的配置与限制见 [Qoder runtime README](https://github.com/multica-ai/multica/blob/main/server/cmd/qoder-runtime/README.md)。
+
+
## 概念区分
- **守护进程**是运行在一台电脑上的 Multica 后台程序。它负责连接服务器、发现本机工具、领取运行和回传结果。
diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/done/[agentId]/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/done/[agentId]/page.tsx
new file mode 100644
index 0000000000..3c7692fcc4
--- /dev/null
+++ b/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/done/[agentId]/page.tsx
@@ -0,0 +1,13 @@
+"use client";
+
+import { use } from "react";
+import { AgentCreatedPage } from "@multica/views/agents/agent-created-page";
+
+export default function NewAgentDoneRoute({
+ params,
+}: {
+ params: Promise<{ agentId: string }>;
+}) {
+ const { agentId } = use(params);
+ return <AgentCreatedPage agentId={agentId} />;
+}
diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/page.tsx
index 7912d16ac5..431790d8fd 100644
--- a/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/page.tsx
+++ b/apps/web/app/[workspaceSlug]/(dashboard)/agents/new/page.tsx
@@ -1,5 +1,5 @@
-import { ChooseCreateMethodPage } from "@multica/views/agents/choose-create-method-page";
+import { ChooseRuntimePage } from "@multica/views/agents/choose-runtime-page";
export default function NewAgentRoute() {
- return <ChooseCreateMethodPage />;
+ return <ChooseRuntimePage />;
}
diff --git a/apps/web/features/landing/i18n/en.ts b/apps/web/features/landing/i18n/en.ts
index aab8eea312..44d9aa2f4b 100644
--- a/apps/web/features/landing/i18n/en.ts
+++ b/apps/web/features/landing/i18n/en.ts
@@ -196,7 +196,7 @@ export function createEnDict(
{
question: "What coding agents does Multica support?",
answer:
- "Multica supports 27 coding tools out of the box: Antigravity, Claude Code, CodeBuddy, CodeArts, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Dim, Grok, Hermes, Kimi, Kiro CLI, MiniMax Code, Muse Code, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, Trae CLI, and ZeroClaw. The daemon auto-detects whichever CLIs you already have installed and registers a runtime for each one. Since the source code is public, you can also add your own backends.",
+ "Multica supports 27 coding tools out of the box: Antigravity, Claude Code, CodeBuddy, CodeArts, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Dim, Grok, Hermes, Kimi, Kiro CLI, MiniMax Code, Muse Code, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, Trae CLI, and ZeroClaw. The daemon auto-detects whichever CLIs you already have installed and registers a runtime for each one. Since the source code is public, you can also add your own backends. Self-hosted deployments can also configure Qoder Cloud Agent as a managed remote runtime for issue runs, using a QCA PAT and an existing QCA agent.",
},
{
question: "Do I need to self-host, or is there a cloud version?",
diff --git a/apps/web/features/landing/i18n/ja.ts b/apps/web/features/landing/i18n/ja.ts
index c6fb5b2f1b..4f2a94a4d7 100644
--- a/apps/web/features/landing/i18n/ja.ts
+++ b/apps/web/features/landing/i18n/ja.ts
@@ -197,7 +197,7 @@ export function createJaDict(
{
question: "Multica はどのコーディングエージェントに対応していますか?",
answer:
- "Multica は、Antigravity、Claude Code、CodeBuddy、CodeArts、Codex、Copilot、Cursor、DeepSeek Harness、DevEco Code、Dim、Grok、Hermes、Kimi、Kiro CLI、MiniMax Code、Muse Code、Oh-My-Pi、OpenClaw、OpenCode、Pi、Qoder、Qoder CN、Qwen Code、QwenPaw、Reasonix、Trae CLI、ZeroClaw の27種類のコーディングツールに標準対応しています。デーモンが、すでにインストール済みの CLI を自動検出し、それぞれをランタイムとして登録します。ソースコードが公開されているので、独自のバックエンドを追加することもできます。",
+ "Multica は、Antigravity、Claude Code、CodeBuddy、CodeArts、Codex、Copilot、Cursor、DeepSeek Harness、DevEco Code、Dim、Grok、Hermes、Kimi、Kiro CLI、MiniMax Code、Muse Code、Oh-My-Pi、OpenClaw、OpenCode、Pi、Qoder、Qoder CN、Qwen Code、QwenPaw、Reasonix、Trae CLI、ZeroClaw の27種類のコーディングツールに標準対応しています。デーモンが、すでにインストール済みの CLI を自動検出し、それぞれをランタイムとして登録します。ソースコードが公開されているので、独自のバックエンドを追加することもできます。 セルフホストでは、QCA PAT と既存の QCA エージェントを使い、タスク実行用のマネージドリモートランタイムとして Qoder Cloud Agent を設定できます。",
},
{
question: "セルフホストが必須ですか、それともクラウド版もありますか?",
diff --git a/apps/web/features/landing/i18n/ko.ts b/apps/web/features/landing/i18n/ko.ts
index afe601e163..c633d396ce 100644
--- a/apps/web/features/landing/i18n/ko.ts
+++ b/apps/web/features/landing/i18n/ko.ts
@@ -197,7 +197,7 @@ export function createKoDict(
{
question: "Multica는 어떤 코딩 에이전트를 지원하나요?",
answer:
- "Multica는 Antigravity, Claude Code, CodeBuddy, CodeArts, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Dim, Grok, Hermes, Kimi, Kiro CLI, MiniMax Code, Muse Code, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, Trae CLI, ZeroClaw 등 27개 코딩 도구를 기본 지원합니다. 데몬이 이미 설치된 CLI를 자동으로 찾아 각각 런타임으로 등록합니다. 소스 코드가 공개되어 있으므로 직접 백엔드를 추가할 수도 있습니다.",
+ "Multica는 Antigravity, Claude Code, CodeBuddy, CodeArts, Codex, Copilot, Cursor, DeepSeek Harness, DevEco Code, Dim, Grok, Hermes, Kimi, Kiro CLI, MiniMax Code, Muse Code, Oh-My-Pi, OpenClaw, OpenCode, Pi, Qoder, Qoder CN, Qwen Code, QwenPaw, Reasonix, Trae CLI, ZeroClaw 등 27개 코딩 도구를 기본 지원합니다. 데몬이 이미 설치된 CLI를 자동으로 찾아 각각 런타임으로 등록합니다. 소스 코드가 공개되어 있으므로 직접 백엔드를 추가할 수도 있습니다. 셀프 호스팅에서는 QCA PAT와 기존 QCA 에이전트를 사용하여 태스크 실행용 관리형 원격 런타임으로 Qoder Cloud Agent를 설정할 수 있습니다.",
},
{
question: "셀프 호스팅만 가능한가요, 클라우드 버전도 있나요?",
diff --git a/apps/web/features/landing/i18n/zh.ts b/apps/web/features/landing/i18n/zh.ts
index 00886314d2..fd16346e99 100644
--- a/apps/web/features/landing/i18n/zh.ts
+++ b/apps/web/features/landing/i18n/zh.ts
@@ -196,7 +196,7 @@ export function createZhDict(
{
question: "Multica \u652f\u6301\u54ea\u4e9b\u7f16\u7801 智能体\uff1f",
answer:
- "Multica \u5f00\u7bb1\u5373\u7528\u652f\u6301 27 \u6b3e AI \u7f16\u7a0b\u5de5\u5177\uff1aAntigravity\u3001Claude Code\u3001CodeBuddy\u3001CodeArts\u3001Codex\u3001Copilot\u3001Cursor\u3001DeepSeek Harness\u3001DevEco Code\u3001Dim\u3001Grok\u3001Hermes\u3001Kimi\u3001Kiro CLI\u3001MiniMax Code\u3001Muse Code\u3001Oh-My-Pi\u3001OpenClaw\u3001OpenCode\u3001Pi\u3001Qoder\u3001Qoder CN\u3001Qwen Code\u3001QwenPaw\u3001Reasonix\u3001Trae CLI\u3001ZeroClaw\u3002\u5b88\u62a4\u8fdb\u7a0b\u4f1a\u81ea\u52a8\u68c0\u6d4b\u672c\u673a\u5df2\u5b89\u88c5\u7684 CLI \u5e76\u4e3a\u6bcf\u6b3e\u6ce8\u518c\u4e00\u4e2a\u8fd0\u884c\u65f6\u3002因为源码公开,你也可以自己添加后端。",
+ "Multica \u5f00\u7bb1\u5373\u7528\u652f\u6301 27 \u6b3e AI \u7f16\u7a0b\u5de5\u5177\uff1aAntigravity\u3001Claude Code\u3001CodeBuddy\u3001CodeArts\u3001Codex\u3001Copilot\u3001Cursor\u3001DeepSeek Harness\u3001DevEco Code\u3001Dim\u3001Grok\u3001Hermes\u3001Kimi\u3001Kiro CLI\u3001MiniMax Code\u3001Muse Code\u3001Oh-My-Pi\u3001OpenClaw\u3001OpenCode\u3001Pi\u3001Qoder\u3001Qoder CN\u3001Qwen Code\u3001QwenPaw\u3001Reasonix\u3001Trae CLI\u3001ZeroClaw\u3002\u5b88\u62a4\u8fdb\u7a0b\u4f1a\u81ea\u52a8\u68c0\u6d4b\u672c\u673a\u5df2\u5b89\u88c5\u7684 CLI \u5e76\u4e3a\u6bcf\u6b3e\u6ce8\u518c\u4e00\u4e2a\u8fd0\u884c\u65f6\u3002因为源码公开,你也可以自己添加后端。 自托管部署还可以使用 QCA PAT 和已有 QCA 智能体,将 Qoder Cloud Agent 配置为执行任务的托管远端运行时。",
},
{
question: "\u9700\u8981\u81ea\u6258\u7ba1\u5417\uff0c\u8fd8\u662f\u6709\u4e91\u7248\u672c\uff1f",
diff --git a/packages/core/agents/builder-protocol.test.ts b/packages/core/agents/builder-protocol.test.ts
index a95c5c5005..3e438b4e47 100644
--- a/packages/core/agents/builder-protocol.test.ts
+++ b/packages/core/agents/builder-protocol.test.ts
@@ -12,6 +12,7 @@ import {
import type { AgentDraft } from "./draft";
const draft = (): AgentDraft => ({
+ qoderAgentId: "",
name: "Old name",
description: "Old description",
instructions: "Old instructions",
diff --git a/packages/core/agents/draft.test.ts b/packages/core/agents/draft.test.ts
index 721bc5b684..85d35d9cde 100644
--- a/packages/core/agents/draft.test.ts
+++ b/packages/core/agents/draft.test.ts
@@ -12,6 +12,7 @@ import {
} from "./draft";
const draft = (): AgentDraft => ({
+ qoderAgentId: "",
name: "Old name",
description: "Old description",
instructions: "Old instructions",
@@ -314,3 +315,35 @@ describe("agent draft execution overrides", () => {
expect(isDraftDescriptionWithinLimit("汉".repeat(256))).toBe(false);
});
});
+
+it("persists a per-agent QCA binding and clears it on runtime change", () => {
+ const current = { ...draft(), qoderAgentId: "agent_qca" };
+ expect(buildCreateAgentRequest({ draft: current, runtimeId: current.runtimeId }).runtime_config).toEqual({ qoder_agent_id: "agent_qca" });
+ expect(applyDraftRuntimeChange(current, "another-runtime").qoderAgentId).toBe("");
+});
+
+it("drops settings a Qoder runtime cannot run from a draft started elsewhere", () => {
+ const current: AgentDraft = {
+ ...draft(),
+ qoderAgentId: "agent_qca",
+ thinkingLevel: "high",
+ serviceTier: "priority",
+ conversationStarters: [{ label: "Plan", prompt: "Plan it" }],
+ };
+ const request = buildCreateAgentRequest({
+ draft: current,
+ runtimeId: "rt-qoder",
+ runtimeProvider: "qoder_cloud",
+ duplicateSource: sourceAgent(),
+ });
+ expect(request).toMatchObject({ runtime_config: { qoder_agent_id: "agent_qca" }, skill_ids: [] });
+ expect(request.model).toBeUndefined();
+ expect(request.thinking_level).toBeUndefined();
+ expect(request.service_tier).toBeUndefined();
+ expect(request).not.toHaveProperty("conversation_starters");
+ expect(request).not.toHaveProperty("custom_args");
+
+ const local = buildCreateAgentRequest({ draft: current, runtimeId: "runtime-1", runtimeProvider: "codex" });
+ expect(local).not.toHaveProperty("runtime_config");
+ expect(local.skill_ids).toEqual(["skill-1"]);
+});
diff --git a/packages/core/agents/draft.ts b/packages/core/agents/draft.ts
index 6214d9f947..dcf0118ae4 100644
--- a/packages/core/agents/draft.ts
+++ b/packages/core/agents/draft.ts
@@ -1,3 +1,4 @@
+import { qoderAgentId } from "./qoder-runtime-config";
import { isRuntimeUsableForUser } from "../runtimes/access";
import type {
Agent,
@@ -17,6 +18,8 @@ import {
// without types/ having to import from agents/.
export type { AgentPermissionScope };
+const QODER_PROVIDER = "qoder_cloud";
+
/**
* The in-progress configuration of an agent being created. Shared by every
* creation surface (manual, duplicate, AI builder) so the same field set is
@@ -29,6 +32,7 @@ export interface AgentDraft {
conversationStarters: AgentConversationStarter[];
avatarUrl: string | null;
runtimeId: string;
+ qoderAgentId: string;
model: string;
/** Runtime-native reasoning/effort token, scoped to `model`. */
thinkingLevel: string;
@@ -48,6 +52,7 @@ export const EMPTY_AGENT_DRAFT: AgentDraft = {
conversationStarters: [],
avatarUrl: null,
runtimeId: "",
+ qoderAgentId: "",
model: "",
thinkingLevel: "",
serviceTier: "",
@@ -73,6 +78,7 @@ export function applyDraftRuntimeChange(
return {
...draft,
runtimeId,
+ qoderAgentId: "",
model: "",
thinkingLevel: "",
serviceTier: "",
@@ -194,6 +200,7 @@ export function buildDuplicateDraft(
runtimeId: keepsRuntime
? (source.runtime_id as string)
: options.fallbackRuntimeId,
+ qoderAgentId: keepsRuntime ? qoderAgentId(source.runtime_config) : "",
model: keepsRuntime ? source.model ?? "" : "",
thinkingLevel: keepsRuntime ? source.thinking_level ?? "" : "",
serviceTier: keepsRuntime ? source.service_tier ?? "" : "",
@@ -211,11 +218,28 @@ export function buildDuplicateDraft(
export function buildCreateAgentRequest(options: {
draft: AgentDraft;
runtimeId: string;
+ /** Provider of `runtimeId`; drafts outlive runtime switches, so fields the target runtime cannot run are dropped here. */
+ runtimeProvider?: string;
/** Creation-source attribution for the `agent_created` analytics event. */
template?: string;
duplicateSource?: Agent | null;
}): CreateAgentRequest {
- const { draft, runtimeId, template, duplicateSource } = options;
+ const { runtimeId, runtimeProvider, template, duplicateSource } = options;
+ const qoder = runtimeProvider === QODER_PROVIDER;
+ // The Qoder bridge refuses skills and execution overrides, and the form
+ // hides them (plus conversation starters) once Qoder is chosen.
+ const draft: AgentDraft = qoder
+ ? {
+ ...options.draft,
+ conversationStarters: [],
+ model: "",
+ thinkingLevel: "",
+ serviceTier: "",
+ skillIds: new Set(),
+ }
+ : runtimeProvider
+ ? { ...options.draft, qoderAgentId: "" }
+ : options.draft;
const request: CreateAgentRequest = {
name: draft.name.trim(),
description: draft.description.trim(),
@@ -230,6 +254,7 @@ export function buildCreateAgentRequest(options: {
: {}),
avatar_url: draft.avatarUrl ?? undefined,
runtime_id: runtimeId,
+ ...(draft.qoderAgentId ? { runtime_config: { qoder_agent_id: draft.qoderAgentId } } : {}),
model: draft.model.trim() || undefined,
thinking_level: draft.thinkingLevel.trim() || undefined,
service_tier: draft.serviceTier.trim() || undefined,
@@ -240,7 +265,7 @@ export function buildCreateAgentRequest(options: {
template,
};
if (duplicateSource) {
- if (duplicateSource.custom_args.length > 0) {
+ if (!qoder && duplicateSource.custom_args.length > 0) {
request.custom_args = duplicateSource.custom_args;
}
const sourceConcurrency = duplicateSource.max_concurrent_tasks;
diff --git a/packages/core/agents/index.ts b/packages/core/agents/index.ts
index 002b447ad6..1377511ccc 100644
--- a/packages/core/agents/index.ts
+++ b/packages/core/agents/index.ts
@@ -19,3 +19,5 @@ export * from "./use-workspace-agent-availability";
export * from "./mcp-support";
export * from "./openclaw-runtime-config";
export * from "./runtime-binding";
+
+export * from "./qoder-runtime-config";
diff --git a/packages/core/agents/qoder-runtime-config.ts b/packages/core/agents/qoder-runtime-config.ts
new file mode 100644
index 0000000000..46cf2917e2
--- /dev/null
+++ b/packages/core/agents/qoder-runtime-config.ts
@@ -0,0 +1,20 @@
+export function qoderAgentId(config: unknown): string {
+ if (!config || typeof config !== "object" || !("qoder_agent_id" in config))
+ return "";
+ return typeof config.qoder_agent_id === "string" ? config.qoder_agent_id : "";
+}
+
+export type QoderRepository = { url: string; ref: string };
+
+// The repository mounted when the issue's project binds none.
+export function qoderDefaultRepository(config: unknown): QoderRepository {
+ const empty = { url: "", ref: "" };
+ if (!config || typeof config !== "object" || !("repository" in config))
+ return empty;
+ const repo = config.repository;
+ if (!repo || typeof repo !== "object") return empty;
+ return {
+ url: "url" in repo && typeof repo.url === "string" ? repo.url : "",
+ ref: "ref" in repo && typeof repo.ref === "string" ? repo.ref : "",
+ };
+}
diff --git a/packages/core/agents/stored-draft.test.ts b/packages/core/agents/stored-draft.test.ts
index a560e54d7c..aa2472a16a 100644
--- a/packages/core/agents/stored-draft.test.ts
+++ b/packages/core/agents/stored-draft.test.ts
@@ -10,6 +10,7 @@ import {
} from "./stored-draft";
const draft = (): AgentDraft => ({
+ qoderAgentId: "agent_qca",
name: "Release manager",
description: "Ships carefully",
instructions: "# Role\nShip.",
diff --git a/packages/core/agents/stored-draft.ts b/packages/core/agents/stored-draft.ts
index 827b880855..7bea07020d 100644
--- a/packages/core/agents/stored-draft.ts
+++ b/packages/core/agents/stored-draft.ts
@@ -15,6 +15,7 @@ export function toStoredAgentDraft(
conversation_starters: draft.conversationStarters,
avatar_url: draft.avatarUrl,
model: draft.model,
+ qoder_agent_id: draft.qoderAgentId,
thinking_level: draft.thinkingLevel,
service_tier: draft.serviceTier,
skill_ids: [...draft.skillIds],
@@ -43,6 +44,7 @@ export function fromStoredAgentDraft(
avatarUrl: stored.avatar_url,
runtimeId,
model: stored.model,
+ qoderAgentId: stored.qoder_agent_id ?? "",
thinkingLevel: stored.thinking_level,
serviceTier: stored.service_tier,
skillIds: new Set(stored.skill_ids),
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 5aca8cf550..116e07d286 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -4,6 +4,7 @@ import type { WorkspaceWakeupPage, WorkspaceWakeupFilters } from "../types/issue
import { WorkspaceWakeupPageSchema, IssueWakeupSchema, IssueWakeupSummaryRowSchema, PausedWakeupSchema, SystemWakeupSchema, WakeupRunSchema, WorkspaceSystemWakeupSchema } from "./schemas";
import type { ArchivedInboxFilters } from "../inbox/filter-store";
import type { ArchivedInboxPage, ArchivedInboxFacets } from "../types/inbox";
+import { parseQoderConnection, parseQoderCatalog, type QoderInput } from "../runtimes/qoder-schema";
import { configStore } from "../config";
import type {
Issue,
@@ -2016,6 +2017,34 @@ export class ApiClient {
return this.fetch(`/api/agents/${id}/cancel-tasks`, { method: "POST" });
}
+ async listQoderEnvironments(wsId: string, token: string, baseUrl: string, signal?: AbortSignal) {
+ return parseQoderCatalog(await this.fetch(`/api/workspaces/${wsId}/qoder/environments`, { method: "POST", body: JSON.stringify({ qoder_token: token, base_url: baseUrl }), signal }));
+ }
+ async listQoderAgents(wsId: string) {
+ return parseQoderCatalog(await this.fetch(`/api/workspaces/${wsId}/qoder/agents`));
+ }
+ async stopQoderConnection(wsId: string) {
+ return parseQoderConnection(await this.fetch(`/api/workspaces/${wsId}/qoder/stop`, { method: "POST" }));
+ }
+ // Refuses with 409 `runtime_delete_plan_changed` and the current
+ // `active_agents` when the confirmed list no longer matches.
+ async disconnectQoderConnection(wsId: string, expectedActiveAgentIds: string[]) {
+ return parseQoderConnection(await this.fetch(`/api/workspaces/${wsId}/qoder`, { method: "DELETE", body: JSON.stringify({ expected_active_agent_ids: expectedActiveAgentIds }) }));
+ }
+ async getQoderConnection(wsId: string) {
+ return parseQoderConnection(await this.fetch(`/api/workspaces/${wsId}/qoder`));
+ }
+ // Saving keeps a paused connection paused; use resumeQoderConnection to run again.
+ async saveQoderConnection(wsId: string, input: QoderInput) {
+ return parseQoderConnection(await this.fetch(`/api/workspaces/${wsId}/qoder`, { method: "PUT", body: JSON.stringify({ name: input.name, base_url: input.baseUrl, environment_id: input.environmentId, qoder_token: input.qoderToken, github_tokens: input.githubTokens, max_concurrency: input.maxConcurrency, run_timeout_minutes: input.runTimeoutMinutes }) }));
+ }
+ async resumeQoderConnection(wsId: string, input: QoderInput) {
+ return parseQoderConnection(await this.fetch(`/api/workspaces/${wsId}/qoder/resume`, { method: "POST", body: JSON.stringify({ name: input.name, base_url: input.baseUrl, environment_id: input.environmentId, qoder_token: input.qoderToken, github_tokens: input.githubTokens, max_concurrency: input.maxConcurrency, run_timeout_minutes: input.runTimeoutMinutes }) }));
+ }
+ async checkQoderConnection(wsId: string, input: QoderInput): Promise<void> {
+ await this.fetch(`/api/workspaces/${wsId}/qoder/check`, { method: "POST", body: JSON.stringify({ name: input.name, base_url: input.baseUrl, environment_id: input.environmentId, qoder_token: input.qoderToken, github_tokens: input.githubTokens, max_concurrency: input.maxConcurrency, run_timeout_minutes: input.runTimeoutMinutes }) });
+ }
+
async listRuntimes(
params?: { workspace_id?: string; owner?: "me" },
workspaceSlug?: string,
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 321d4a21d9..c783a9b920 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -2324,6 +2324,7 @@ export const StoredAgentDraftSchema = z.object({
.catch("private"),
member_ids: z.array(z.string()).catch([]),
team_ids: z.array(z.string()).catch([]),
+ qoder_agent_id: z.string().catch(""),
applied_message_id: z.string().nullable().catch(null),
dismissed_message_id: z.string().nullish().catch(null),
}).loose();
diff --git a/packages/core/diagnostics/diagnostic-context.ts b/packages/core/diagnostics/diagnostic-context.ts
index 1276cbe3b7..d8e6c4d1ec 100644
--- a/packages/core/diagnostics/diagnostic-context.ts
+++ b/packages/core/diagnostics/diagnostic-context.ts
@@ -64,6 +64,7 @@ const WORKSPACE_ROUTES: readonly RoutePattern[] = [
["agents", "new", "manual"],
["agents", "new", "ai"],
["agents", "new", "ai", ":sessionId"],
+ ["agents", "new", "done", ":agentId"],
["agents", ":id"],
["members", ":id"],
["squads"],
diff --git a/packages/core/package.json b/packages/core/package.json
index 63a4dac901..736e4d5e09 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -168,7 +168,8 @@
"./skills/frontmatter": "./skills/frontmatter.ts",
"./skills/pack-archive": "./skills/pack-archive.ts",
"./skills/stores": "./skills/stores/index.ts",
- "./autopilots/stores": "./autopilots/stores/index.ts"
+ "./autopilots/stores": "./autopilots/stores/index.ts",
+ "./runtimes/qoder": "./runtimes/qoder.ts"
},
"dependencies": {
"@formatjs/intl-localematcher": "catalog:",
diff --git a/packages/core/paths/paths.test.ts b/packages/core/paths/paths.test.ts
index 419cdd17c2..e277c304b4 100644
--- a/packages/core/paths/paths.test.ts
+++ b/packages/core/paths/paths.test.ts
@@ -16,6 +16,7 @@ describe("paths.workspace(slug)", () => {
expect(ws.newAgent()).toBe("/acme/agents/new");
expect(ws.newAgentAi()).toBe("/acme/agents/new/ai");
expect(ws.newAgentAiSession("sess_1")).toBe("/acme/agents/new/ai/sess_1");
+ expect(ws.newAgentDone("agent_1")).toBe("/acme/agents/new/done/agent_1");
expect(ws.memberDetail("u1")).toBe("/acme/members/u1");
expect(ws.inbox()).toBe("/acme/inbox");
expect(ws.chatWithAgent("agent one")).toBe(
diff --git a/packages/core/paths/paths.ts b/packages/core/paths/paths.ts
index ba44c09714..e62e24f10c 100644
--- a/packages/core/paths/paths.ts
+++ b/packages/core/paths/paths.ts
@@ -34,10 +34,14 @@ function workspaceScoped(slug: string) {
autopilots: () => `${ws}/autopilots`,
autopilotDetail: (id: string) => `${ws}/autopilots/${encode(id)}`,
agents: () => `${ws}/agents`,
+ // Step 1 of agent creation: choose where the agent runs.
newAgent: () => `${ws}/agents/new`,
- // The two creation methods behind the chooser. Each is a real route so a
+ // Step 2: configure the agent on the chosen runtime. A real route so a
// half-filled form survives a refresh and can be linked to directly.
newAgentManual: () => `${ws}/agents/new/manual`,
+ // Step 3: the agent exists; offer its first uses.
+ newAgentDone: (agentId: string) =>
+ `${ws}/agents/new/done/${encode(agentId)}`,
newAgentAi: () => `${ws}/agents/new/ai`,
// One creation conversation. It is a durable object, not a step of the
// route above: it survives leaving the studio and is resumed later, so it
diff --git a/packages/core/runtimes/display.ts b/packages/core/runtimes/display.ts
index f6b4234b47..d4b30bc391 100644
--- a/packages/core/runtimes/display.ts
+++ b/packages/core/runtimes/display.ts
@@ -44,6 +44,7 @@ const PROVIDER_DISPLAY_NAMES: Record<string, string> = {
codearts: "CodeArts",
dsh: "DeepSeek Harness",
qoderclicn: "Qoder CN",
+ qoder_cloud: "Qoder Cloud Agent",
traecli: "Trae",
qwen: "Qwen Code",
qwenpaw: "QwenPaw",
diff --git a/packages/core/runtimes/qoder-schema.test.ts b/packages/core/runtimes/qoder-schema.test.ts
new file mode 100644
index 0000000000..6e103154af
--- /dev/null
+++ b/packages/core/runtimes/qoder-schema.test.ts
@@ -0,0 +1,76 @@
+// @vitest-environment node
+import { describe, it, expect } from "vitest";
+import { parseQoderConnection, parseQoderCatalog } from "./qoder-schema";
+describe("QCA response boundary", () => {
+ it("disables configuration for malformed responses", () => {
+ for (const input of [
+ null,
+ {},
+ { available: "true" },
+ { repositories: "bad" },
+ ]) {
+ expect(parseQoderConnection(input).available).toBe(false);
+ }
+ });
+ it("preserves capability and valid fields when optional fields are missing", () => {
+ expect(parseQoderConnection({ available: true, configured: true, name: "QCA", repositories: null })).toMatchObject({ available: true, configured: true, name: "QCA", repositories: [], enabled: false });
+ });
+ it("maps fields and drops unexpected secrets", () => {
+ const result = parseQoderConnection({
+ configured: true,
+ available: true,
+ name: "QCA",
+ base_url: "https://api.qoder.com/api/v1/cloud",
+ agent_id: "agent_a",
+ environment_id: "env_a",
+ has_token: true,
+ repositories: ["https://github.com/a/b"],
+ enabled: true,
+ status: "online",
+ last_error: "",
+ qoder_token: "must-not-surface",
+ });
+ expect(result.environmentId).toBe("env_a");
+ expect(result).not.toHaveProperty("agentId");
+ expect(result.hasToken).toBe(true);
+ expect(JSON.stringify(result)).not.toContain("must-not-surface");
+ });
+ it("maps execution limits and usage, defaulting malformed values", () => {
+ expect(
+ parseQoderConnection({
+ available: true,
+ max_concurrency: 5,
+ run_timeout_minutes: 90,
+ active_runs: 2,
+ queued_runs: 1,
+ }),
+ ).toMatchObject({
+ maxConcurrency: 5,
+ runTimeoutMinutes: 90,
+ activeRuns: 2,
+ queuedRuns: 1,
+ });
+ expect(
+ parseQoderConnection({
+ available: true,
+ max_concurrency: 0,
+ run_timeout_minutes: "60",
+ active_runs: -1,
+ }),
+ ).toMatchObject({
+ available: true,
+ maxConcurrency: 3,
+ runTimeoutMinutes: 60,
+ activeRuns: 0,
+ queuedRuns: 0,
+ });
+ });
+});
+
+
+it("validates catalogs and strips provider secrets", () => {
+ expect(parseQoderCatalog({ items: [{ id: "env_a", name: "Web", config: { token: "secret" } }] })).toEqual([{ id: "env_a", name: "Web" }]);
+ for (const malformed of [null, {}, { items: "bad" }, { items: [{ id: 1, name: "bad" }] }]) {
+ expect(parseQoderCatalog(malformed)).toEqual([]);
+ }
+});
diff --git a/packages/core/runtimes/qoder-schema.ts b/packages/core/runtimes/qoder-schema.ts
new file mode 100644
index 0000000000..5e471f0171
--- /dev/null
+++ b/packages/core/runtimes/qoder-schema.ts
@@ -0,0 +1,97 @@
+import { z } from "zod";
+import { parseWithFallback } from "../api/schema";
+
+// Mirrors the server defaults and bounds in handler/qoder_connection.go.
+export const DEFAULT_CONCURRENCY = 3;
+export const MAX_CONCURRENCY = 10;
+export const DEFAULT_RUN_TIMEOUT = 60;
+export const MIN_RUN_TIMEOUT = 5;
+export const MAX_RUN_TIMEOUT = 240;
+// A PAT only works against the region that issued it.
+export const QODER_REGIONS = {
+ global: "https://api.qoder.com/api/v1/cloud",
+ cn: "https://api.qoder.com.cn/api/v1/cloud",
+} as const;
+export type QoderRegion = keyof typeof QODER_REGIONS;
+
+const schema = z
+ .object({
+ configured: z.boolean().catch(false),
+ available: z.boolean().catch(false),
+ name: z.string().catch(""),
+ base_url: z.string().catch(""),
+ environment_id: z.string().catch(""),
+ has_token: z.boolean().catch(false),
+ repositories: z.array(z.string()).catch([]),
+ enabled: z.boolean().catch(false),
+ status: z.string().catch(""),
+ last_error: z.string().catch(""),
+ max_concurrency: z.number().int().positive().catch(DEFAULT_CONCURRENCY),
+ run_timeout_minutes: z.number().int().positive().catch(DEFAULT_RUN_TIMEOUT),
+ active_runs: z.number().int().nonnegative().catch(0),
+ queued_runs: z.number().int().nonnegative().catch(0),
+ })
+ .transform((v) => ({
+ configured: v.configured,
+ available: v.available,
+ name: v.name,
+ baseUrl: v.base_url,
+ environmentId: v.environment_id,
+ hasToken: v.has_token,
+ repositories: v.repositories,
+ enabled: v.enabled,
+ status: v.status,
+ lastError: v.last_error,
+ maxConcurrency: v.max_concurrency,
+ runTimeoutMinutes: v.run_timeout_minutes,
+ activeRuns: v.active_runs,
+ queuedRuns: v.queued_runs,
+ }));
+export type QoderConnection = z.output<typeof schema>;
+export type QoderInput = {
+ name: string;
+ baseUrl: string;
+ environmentId: string;
+ qoderToken: string;
+ // Omitted keeps the stored repository bindings, as an empty qoderToken
+ // keeps the stored token.
+ githubTokens?: Record<string, string>;
+ maxConcurrency: number;
+ runTimeoutMinutes: number;
+};
+export function parseQoderConnection(data: unknown): QoderConnection {
+ return parseWithFallback(
+ data,
+ schema,
+ {
+ configured: false,
+ available: false,
+ name: "",
+ baseUrl: "",
+ environmentId: "",
+ hasToken: false,
+ repositories: [],
+ enabled: false,
+ status: "",
+ lastError: "",
+ maxConcurrency: DEFAULT_CONCURRENCY,
+ runTimeoutMinutes: DEFAULT_RUN_TIMEOUT,
+ activeRuns: 0,
+ queuedRuns: 0,
+ },
+ { endpoint: "qoder" },
+ );
+}
+
+const catalogSchema = z.object({
+ items: z.array(z.object({ id: z.string().min(1), name: z.string() })),
+});
+export type QoderCatalogItem = z.output<typeof catalogSchema>["items"][number];
+export function parseQoderCatalog(data: unknown): QoderCatalogItem[] {
+ return parseWithFallback(
+ data,
+ catalogSchema,
+ { items: [] },
+ { endpoint: "qoder/catalog" },
+ ).items;
+}
diff --git a/packages/core/runtimes/qoder.ts b/packages/core/runtimes/qoder.ts
new file mode 100644
index 0000000000..613eebfeb7
--- /dev/null
+++ b/packages/core/runtimes/qoder.ts
@@ -0,0 +1,104 @@
+import {
+ queryOptions,
+ useMutation,
+ useQueryClient,
+} from "@tanstack/react-query";
+import { api } from "../api";
+import { runtimeKeys } from "./queries";
+import { workspaceKeys } from "../workspace/queries";
+import { agentTaskSnapshotKeys } from "../agents/queries";
+import type { QoderInput } from "./qoder-schema";
+export type { QoderInput, QoderConnection, QoderRegion } from "./qoder-schema";
+export {
+ QODER_REGIONS,
+ DEFAULT_CONCURRENCY,
+ MAX_CONCURRENCY,
+ DEFAULT_RUN_TIMEOUT,
+ MIN_RUN_TIMEOUT,
+ MAX_RUN_TIMEOUT,
+} from "./qoder-schema";
+export const qoderKey = (wsId: string) => ["qoder", wsId] as const;
+export const qoderOptions = (wsId: string) =>
+ queryOptions({
+ queryKey: qoderKey(wsId),
+ queryFn: () => api.getQoderConnection(wsId),
+ refetchInterval: 5000,
+ });
+export function useSaveQoder(wsId: string) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (input: QoderInput) => api.saveQoderConnection(wsId, input),
+ onSuccess: (data) => {
+ qc.setQueryData(qoderKey(wsId), data);
+ void qc.invalidateQueries({ queryKey: ["qoder", wsId, "agents"] });
+ void qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });
+ },
+ });
+}
+export function useResumeQoder(wsId: string) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (input: QoderInput) => api.resumeQoderConnection(wsId, input),
+ onSuccess: (data) => {
+ qc.setQueryData(qoderKey(wsId), data);
+ void qc.invalidateQueries({ queryKey: ["qoder", wsId, "agents"] });
+ void qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });
+ },
+ });
+}
+export function useCheckQoder(wsId: string) {
+ return useMutation({
+ mutationFn: (input: QoderInput) => api.checkQoderConnection(wsId, input),
+ });
+}
+
+export function useStopQoder(wsId: string) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: () => api.stopQoderConnection(wsId),
+ onSuccess: (data) => {
+ qc.setQueryData(qoderKey(wsId), data);
+ void qc.invalidateQueries({ queryKey: ["qoder", wsId, "agents"] });
+ void qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });
+ },
+ });
+}
+
+export function useDisconnectQoder(wsId: string) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (expectedActiveAgentIds: string[]) =>
+ api.disconnectQoderConnection(wsId, expectedActiveAgentIds),
+ onSuccess: (data) => {
+ qc.setQueryData(qoderKey(wsId), data);
+ },
+ onSettled: () => {
+ void qc.invalidateQueries({ queryKey: qoderKey(wsId) });
+ void qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });
+ void qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
+ void qc.invalidateQueries({ queryKey: agentTaskSnapshotKeys.all(wsId) });
+ },
+ });
+}
+
+export const qoderAgentsOptions = (wsId: string) =>
+ queryOptions({
+ queryKey: ["qoder", wsId, "agents"],
+ queryFn: () => api.listQoderAgents(wsId),
+ staleTime: 30_000,
+ });
+
+export function useQoderEnvironments(wsId: string) {
+ return useMutation({
+ mutationFn: ({
+ token,
+ baseUrl,
+ signal,
+ }: {
+ token: string;
+ baseUrl: string;
+ signal?: AbortSignal;
+ }) => api.listQoderEnvironments(wsId, token, baseUrl, signal),
+ gcTime: 0,
+ });
+}
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.ts
index 52f28360f7..621078cc0c 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -715,6 +715,7 @@ export type AgentPermissionScope = "private" | "workspace" | "members";
* over edits the user made after it.
*/
export interface StoredAgentDraft {
+ qoder_agent_id?: string;
name: string;
description: string;
instructions: string;
diff --git a/packages/views/agents/components/agent-detail-inspector.qoder.test.tsx b/packages/views/agents/components/agent-detail-inspector.qoder.test.tsx
new file mode 100644
index 0000000000..18740f36e8
--- /dev/null
+++ b/packages/views/agents/components/agent-detail-inspector.qoder.test.tsx
@@ -0,0 +1,106 @@
+// @vitest-environment jsdom
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { cleanup, screen } from "@testing-library/react";
+import type { Agent, AgentRuntime } from "@multica/core/types";
+import { renderWithI18n } from "../../test/i18n";
+
+const picker = vi.hoisted(() => ({
+ props: null as null | { runtimes: AgentRuntime[]; canEdit?: boolean },
+}));
+const mockInitiateListModels = vi.hoisted(() => vi.fn());
+
+vi.mock("@multica/core/api", () => ({
+ api: {
+ initiateListModels: (...args: unknown[]) => mockInitiateListModels(...args),
+ getListModelsResult: vi.fn(),
+ },
+}));
+vi.mock("../../common/avatar-upload-control", () => ({
+ AvatarUploadControl: () => <div data-testid="avatar-upload" />,
+}));
+vi.mock("./inspector/runtime-picker", () => ({
+ RuntimePicker: (props: { runtimes: AgentRuntime[]; canEdit?: boolean }) => {
+ picker.props = props;
+ return <div data-testid="runtime-picker" />;
+ },
+}));
+
+import { AgentDetailInspector } from "./agent-detail-inspector";
+
+function runtime(id: string, provider: string): AgentRuntime {
+ return {
+ id,
+ workspace_id: "workspace-1",
+ daemon_id: null,
+ name: id,
+ runtime_mode: provider === "qoder_cloud" ? "cloud" : "local",
+ provider,
+ launch_header: "",
+ status: "online",
+ device_info: "",
+ metadata: {},
+ owner_id: "user-1",
+ visibility: "public",
+ last_seen_at: null,
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ };
+}
+
+const claude = runtime("rt-claude", "claude");
+const qoder = runtime("rt-qoder", "qoder_cloud");
+
+function renderInspector(bound: AgentRuntime) {
+ const agent = {
+ id: "agent-1",
+ workspace_id: "workspace-1",
+ name: "Lambda",
+ description: "",
+ runtime_id: bound.id,
+ model: "",
+ max_concurrent_tasks: 6,
+ } as Agent;
+ renderWithI18n(
+ <QueryClientProvider
+ client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}
+ >
+ <AgentDetailInspector
+ agent={agent}
+ runtime={bound}
+ runtimes={[claude, qoder]}
+ members={[]}
+ currentUserId="user-1"
+ canEdit
+ onUpdate={vi.fn(async () => {})}
+ />
+ </QueryClientProvider>,
+ );
+}
+
+describe("AgentDetailInspector and the Qoder runtime", () => {
+ beforeEach(() => {
+ picker.props = null;
+ mockInitiateListModels.mockReset();
+ });
+ afterEach(cleanup);
+
+ it("locks the runtime and drops model overrides for a Qoder agent", () => {
+ renderInspector(qoder);
+ expect(picker.props?.canEdit).toBe(false);
+ expect(screen.queryByText("Model")).toBeNull();
+ expect(
+ screen.getByText("Model, tools and skills are set on the QCA agent in Qoder."),
+ ).toBeInTheDocument();
+ expect(screen.getByLabelText("Concurrency")).toHaveValue(6);
+ expect(mockInitiateListModels).not.toHaveBeenCalled();
+ });
+
+ it("does not offer the Qoder runtime to other agents", () => {
+ renderInspector(claude);
+ expect(picker.props?.canEdit).toBe(true);
+ expect(picker.props?.runtimes.map((r) => r.id)).toEqual(["rt-claude"]);
+ expect(screen.getByText("Model")).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/agents/components/agent-detail-inspector.tsx b/packages/views/agents/components/agent-detail-inspector.tsx
index f2a1fae0ac..e5659686c5 100644
--- a/packages/views/agents/components/agent-detail-inspector.tsx
+++ b/packages/views/agents/components/agent-detail-inspector.tsx
@@ -117,11 +117,23 @@ export function AgentDetailInspector({
isEqual: profileDraftsEqual,
});
+ // A Qoder agent is bound to a QCA agent, and the model lives there. Moving
+ // between Qoder and any other runtime would need a different configuration
+ // the server either rejects or the bridge refuses, so neither direction is
+ // offered here.
+ const qoderRuntime = runtime?.provider === "qoder_cloud";
const isOnline = runtime?.status === "online";
const canReadRuntime =
runtime != null && isRuntimeUsableForUser(runtime, currentUserId);
- const canDiscoverRuntimeModels = isOnline && canReadRuntime;
+ const canDiscoverRuntimeModels = isOnline && canReadRuntime && !qoderRuntime;
const nameInvalid = name.trim().length === 0;
+ const runtimeOptions = useMemo(
+ () =>
+ qoderRuntime
+ ? runtimes
+ : runtimes.filter((r) => r.provider !== "qoder_cloud"),
+ [qoderRuntime, runtimes],
+ );
// Same query the Thinking / Speed fields already use, so switching model
// costs no extra request. `null` = not authoritative (offline runtime, still
@@ -237,6 +249,9 @@ export function AgentDetailInspector({
<SettingsSection
title={t(($) => $.inspector.section_execution)}
+ description={
+ qoderRuntime ? t(($) => $.inspector.qoder_execution_note) : undefined
+ }
>
<SettingsCard>
<SettingsRow
@@ -247,10 +262,10 @@ export function AgentDetailInspector({
variant="field"
showLabel={false}
value={agent.runtime_id}
- runtimes={runtimes}
+ runtimes={runtimeOptions}
members={members}
currentUserId={currentUserId}
- canEdit={canEdit}
+ canEdit={canEdit && !qoderRuntime}
// Model, thinking level, and service tier are runtime/model
// native. Clear them together so the new runtime resolves its
// own defaults instead of inheriting incompatible tokens.
@@ -264,42 +279,48 @@ export function AgentDetailInspector({
}
/>
</SettingsRow>
- <SettingsRow
- label={t(($) => $.inspector.prop_model)}
- size="select-wide"
- >
- <ModelPicker
- variant="field"
- showLabel={false}
- runtimeId={agent.runtime_id}
- runtimeOnline={canDiscoverRuntimeModels}
- value={agent.model ?? ""}
- canEdit={canEdit}
- onChange={handleModelChange}
- />
- </SettingsRow>
- <ThinkingSettingField
- label={t(($) => $.inspector.prop_thinking)}
- runtimeId={agent.runtime_id}
- runtimeOnline={canDiscoverRuntimeModels}
- provider={runtime?.provider ?? ""}
- model={agent.model ?? ""}
- value={agent.thinking_level ?? ""}
- canEdit={canEdit}
- onChange={(thinkingLevel) =>
- update({ thinking_level: thinkingLevel })
- }
- />
- <ServiceTierSettingField
- label={t(($) => $.inspector.prop_speed)}
- runtimeId={agent.runtime_id}
- runtimeOnline={canDiscoverRuntimeModels}
- provider={runtime?.provider ?? ""}
- model={agent.model ?? ""}
- value={agent.service_tier ?? ""}
- canEdit={canEdit}
- onChange={(serviceTier) => update({ service_tier: serviceTier })}
- />
+ {qoderRuntime ? null : (
+ <>
+ <SettingsRow
+ label={t(($) => $.inspector.prop_model)}
+ size="select-wide"
+ >
+ <ModelPicker
+ variant="field"
+ showLabel={false}
+ runtimeId={agent.runtime_id}
+ runtimeOnline={canDiscoverRuntimeModels}
+ value={agent.model ?? ""}
+ canEdit={canEdit}
+ onChange={handleModelChange}
+ />
+ </SettingsRow>
+ <ThinkingSettingField
+ label={t(($) => $.inspector.prop_thinking)}
+ runtimeId={agent.runtime_id}
+ runtimeOnline={canDiscoverRuntimeModels}
+ provider={runtime?.provider ?? ""}
+ model={agent.model ?? ""}
+ value={agent.thinking_level ?? ""}
+ canEdit={canEdit}
+ onChange={(thinkingLevel) =>
+ update({ thinking_level: thinkingLevel })
+ }
+ />
+ <ServiceTierSettingField
+ label={t(($) => $.inspector.prop_speed)}
+ runtimeId={agent.runtime_id}
+ runtimeOnline={canDiscoverRuntimeModels}
+ provider={runtime?.provider ?? ""}
+ model={agent.model ?? ""}
+ value={agent.service_tier ?? ""}
+ canEdit={canEdit}
+ onChange={(serviceTier) =>
+ update({ service_tier: serviceTier })
+ }
+ />
+ </>
+ )}
<SettingsRow
label={t(($) => $.inspector.prop_concurrency)}
size="select-wide"
diff --git a/packages/views/agents/components/agent-detail-page.tsx b/packages/views/agents/components/agent-detail-page.tsx
index 523f3482cc..a6891dc365 100644
--- a/packages/views/agents/components/agent-detail-page.tsx
+++ b/packages/views/agents/components/agent-detail-page.tsx
@@ -542,10 +542,12 @@ function DetailHeader({
t(($) => $.inspector.no_description_placeholder)}
</ExpandableDescription>
<div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-2 text-caption text-muted-foreground">
- <span className="inline-flex min-w-0 items-center gap-1.5">
- <Bot className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />
- <span className="truncate">{agent.model || t(($) => $.pickers.model_default)}</span>
- </span>
+ {runtime?.provider === "qoder_cloud" ? null : (
+ <span className="inline-flex min-w-0 items-center gap-1.5">
+ <Bot className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />
+ <span className="truncate">{agent.model || t(($) => $.pickers.model_default)}</span>
+ </span>
+ )}
<span className="inline-flex min-w-0 items-center gap-1.5">
<Server className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />
<span className="truncate">
diff --git a/packages/views/agents/components/agent-overview-pane.test.tsx b/packages/views/agents/components/agent-overview-pane.test.tsx
index 4e7a1c125f..83e3a5f7ba 100644
--- a/packages/views/agents/components/agent-overview-pane.test.tsx
+++ b/packages/views/agents/components/agent-overview-pane.test.tsx
@@ -287,6 +287,38 @@ describe("AgentOverviewPane Environment tab visibility", () => {
});
});
+describe("AgentOverviewPane on a Qoder Cloud Agent runtime", () => {
+ const tabNames = () =>
+ screen
+ .getAllByRole("tab")
+ .filter((tab) => tab.closest("aside"))
+ .map((tab) => tab.textContent);
+
+ it("offers only Instructions under Capabilities", () => {
+ larkListingRef.current = { installations: [], configured: true };
+ renderPane([makeRuntime("qoder_cloud")]);
+ openCapabilities();
+ expect(tabNames()).toEqual(["Instructions"]);
+ });
+
+ it("drops Environment and Custom Args and names the QCA agent tab", () => {
+ renderPane([makeRuntime("qoder_cloud")]);
+ openSettings();
+ expect(tabNames()).toEqual(["General", "Access", "QCA Agent"]);
+ });
+
+ it("keeps Routing off for other runtimes", () => {
+ renderPane([makeRuntime("claude")]);
+ openSettings();
+ expect(tabNames()).toEqual([
+ "General",
+ "Access",
+ "Environment",
+ "Custom Args",
+ ]);
+ });
+});
+
// MUL-7107: the header, the tab bar and every panel share one leading edge.
// The regression these guard against is a centred width cap: `mx-auto` plus a
// `max-w-*` moves an element's edge as the viewport grows, so chrome on a
diff --git a/packages/views/agents/components/agent-overview-pane.tsx b/packages/views/agents/components/agent-overview-pane.tsx
index 5443c44e77..594eb591a0 100644
--- a/packages/views/agents/components/agent-overview-pane.tsx
+++ b/packages/views/agents/components/agent-overview-pane.tsx
@@ -2,11 +2,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
-import type {
- Agent,
- AgentRuntime,
- MemberWithUser,
-} from "@multica/core/types";
+import type { Agent, AgentRuntime, MemberWithUser } from "@multica/core/types";
import { providerSupportsMcpConfig } from "@multica/core/agents";
import { useFeatureEnabled } from "@multica/core/config";
import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";
@@ -36,6 +32,7 @@ import { CustomArgsTab } from "./tabs/custom-args-tab";
import { McpConfigTab } from "./tabs/mcp-config-tab";
import { AgentMcpTab } from "./tabs/agent-mcp-tab";
import { IntegrationsTab } from "./tabs/integrations-tab";
+import { QoderAgentTab } from "./tabs/qoder-agent-tab";
import { RuntimeConfigTab } from "./tabs/runtime-config-tab";
import { AgentDetailInspector } from "./agent-detail-inspector";
import { AgentAccessSettings } from "./agent-access-settings";
@@ -72,7 +69,8 @@ type SecondaryTab = {
| "access"
| "environment"
| "custom_args"
- | "runtime_config";
+ | "runtime_config"
+ | "qoder_agent";
};
const CAPABILITY_TABS: SecondaryTab[] = [
@@ -98,9 +96,7 @@ const TOP_TABS: { id: DetailSection; labelKey: DetailSection }[] = [
{ id: "settings", labelKey: "settings" },
];
-const CAPABILITY_IDS = new Set<DetailTab>(
- CAPABILITY_TABS.map((tab) => tab.id),
-);
+const CAPABILITY_IDS = new Set<DetailTab>(CAPABILITY_TABS.map((tab) => tab.id));
const SETTINGS_IDS = new Set<DetailTab>(SETTINGS_TABS.map((tab) => tab.id));
const DETAIL_VIEWS = new Set<DetailTab>([
"overview",
@@ -194,7 +190,15 @@ export function AgentOverviewPane({
wecomListing?.configured === true ||
telegramListing?.configured === true;
+ // The Qoder bridge fails every task carrying skills, MCP, connected apps,
+ // env, args or a model override, and runs issues only (no chat). Those
+ // editors are not offered; the QCA agent in Qoder owns that configuration.
+ const qoderRuntime = runtime?.provider === "qoder_cloud";
+
const visibleCapabilityTabs = useMemo(() => {
+ if (qoderRuntime) {
+ return CAPABILITY_TABS.filter((tab) => tab.id === "instructions");
+ }
const showMcp = runtime
? providerSupportsMcpConfig(runtime.provider)
: true;
@@ -215,12 +219,14 @@ export function AgentOverviewPane({
composioMCPAppsEnabled,
currentUserId,
integrationsConfigured,
+ qoderRuntime,
runtime,
]);
const visibleSettingsTabs = useMemo(
() =>
SETTINGS_TABS.filter((tab) => {
+ if (qoderRuntime) return tab.id !== "env" && tab.id !== "custom_args";
// Env is the only settings tab backed by a secret-bearing endpoint.
// GET/PUT /api/agents/{id}/env admits the agent owner or a workspace
// owner/admin (MUL-5438) — the same rule `canEdit` encodes — so
@@ -229,8 +235,12 @@ export function AgentOverviewPane({
if (tab.id === "env") return canEdit;
if (tab.id === "runtime_config") return runtime?.provider === "openclaw";
return true;
- }),
- [canEdit, runtime?.provider],
+ }).map((tab) =>
+ qoderRuntime && tab.id === "runtime_config"
+ ? { ...tab, labelKey: "qoder_agent" as const }
+ : tab,
+ ),
+ [canEdit, qoderRuntime, runtime?.provider],
);
const visibleViews = useMemo(
@@ -323,7 +333,8 @@ export function AgentOverviewPane({
const activeSecondaryTab = secondaryTabs.find(
(tab) => tab.id === effectiveView,
);
- const isSecondaryLayout = secondaryTabs.length > 0 && activeSecondaryTab != null;
+ const isSecondaryLayout =
+ secondaryTabs.length > 0 && activeSecondaryTab != null;
return (
<div className="flex min-h-0 flex-1 flex-col bg-background">
@@ -453,6 +464,7 @@ export function AgentOverviewPane({
agent={agent}
onSave={(updates) => onUpdate(agent.id, updates)}
onDirtyChange={setActiveDirty}
+ showConversationStarters={!qoderRuntime}
/>
)}
{effectiveView === "skills" && (
@@ -510,13 +522,22 @@ export function AgentOverviewPane({
onDirtyChange={setActiveDirty}
/>
)}
- {effectiveView === "runtime_config" && (
- <RuntimeConfigTab
- agent={agent}
- onSave={(updates) => onUpdate(agent.id, updates)}
- onDirtyChange={setActiveDirty}
- />
- )}
+ {effectiveView === "runtime_config" &&
+ (qoderRuntime ? (
+ <QoderAgentTab
+ canEdit={canEdit}
+ key={agent.id}
+ agent={agent}
+ onSave={(updates) => onUpdate(agent.id, updates)}
+ onDirtyChange={setActiveDirty}
+ />
+ ) : (
+ <RuntimeConfigTab
+ agent={agent}
+ onSave={(updates) => onUpdate(agent.id, updates)}
+ onDirtyChange={setActiveDirty}
+ />
+ ))}
</div>
</div>
</section>
diff --git a/packages/views/agents/components/agent-overview-summary.tsx b/packages/views/agents/components/agent-overview-summary.tsx
index c174ee6d6e..76d235ba12 100644
--- a/packages/views/agents/components/agent-overview-summary.tsx
+++ b/packages/views/agents/components/agent-overview-summary.tsx
@@ -6,6 +6,7 @@ import type {
AgentRuntime,
MemberWithUser,
} from "@multica/core/types";
+import { qoderAgentId } from "@multica/core/agents";
import { runtimeDisplayLabel } from "@multica/core/runtimes";
import { ActorAvatar } from "../../common/actor-avatar";
import { useT } from "../../i18n";
@@ -29,7 +30,9 @@ export function AgentOverviewSummary({
owner,
}: AgentOverviewSummaryProps) {
const { t } = useT("agents");
+ const { t: tr } = useT("runtimes");
const runtimeOnline = runtime?.status === "online";
+ const qoderRuntime = runtime?.provider === "qoder_cloud";
return (
<aside className="self-start rounded-xl border border-surface-border bg-surface p-5 shadow-[var(--surface-shadow)] xl:sticky xl:top-6">
@@ -69,14 +72,22 @@ export function AgentOverviewSummary({
</span>
</span>
</SummaryRow>
- <SummaryRow label={t(($) => $.inspector.prop_model)}>
- <span className="flex min-w-0 items-center gap-1.5 text-foreground">
- <Bot className="h-3 w-3 shrink-0 text-muted-foreground" aria-hidden="true" />
- <span className="truncate">
- {agent.model || t(($) => $.pickers.model_default)}
+ {qoderRuntime ? (
+ <SummaryRow label={tr(($) => $.qoder.agent)}>
+ <span className="block truncate font-mono text-foreground">
+ {qoderAgentId(agent.runtime_config) || "—"}
</span>
- </span>
- </SummaryRow>
+ </SummaryRow>
+ ) : (
+ <SummaryRow label={t(($) => $.inspector.prop_model)}>
+ <span className="flex min-w-0 items-center gap-1.5 text-foreground">
+ <Bot className="h-3 w-3 shrink-0 text-muted-foreground" aria-hidden="true" />
+ <span className="truncate">
+ {agent.model || t(($) => $.pickers.model_default)}
+ </span>
+ </span>
+ </SummaryRow>
+ )}
<SummaryRow label={t(($) => $.inspector.prop_concurrency)}>
<span className="font-mono tabular-nums text-foreground">
{agent.max_concurrent_tasks}
@@ -85,6 +96,7 @@ export function AgentOverviewSummary({
</dl>
</section>
+ {qoderRuntime ? null : (
<section className="mt-5 border-t pt-5">
<div className="flex items-center justify-between gap-3">
<h2 className="text-body font-medium">
@@ -111,6 +123,7 @@ export function AgentOverviewSummary({
</p>
)}
</section>
+ )}
<AgentPerformanceSummary agent={agent} />
</aside>
diff --git a/packages/views/agents/components/qoder-agent-select.tsx b/packages/views/agents/components/qoder-agent-select.tsx
new file mode 100644
index 0000000000..0babece30b
--- /dev/null
+++ b/packages/views/agents/components/qoder-agent-select.tsx
@@ -0,0 +1,89 @@
+"use client";
+
+import { useId } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { qoderAgentsOptions } from "@multica/core/runtimes/qoder";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ Select,
+ SelectTrigger,
+ SelectValue,
+ SelectContent,
+ SelectItem,
+} from "@multica/ui/components/ui/select";
+import { useT } from "../../i18n";
+
+export function QoderAgentSelect({
+ value,
+ onChange,
+ disabled = false,
+}: {
+ value: string;
+ onChange: (value: string) => void;
+ disabled?: boolean;
+}) {
+ const wsId = useWorkspaceId();
+ const { t } = useT("runtimes");
+ const labelId = useId();
+ const query = useQuery(qoderAgentsOptions(wsId));
+ const items = query.data ?? [];
+ const missing =
+ !!value && query.isSuccess && !items.some((item) => item.id === value);
+ return (
+ <div className="space-y-2">
+ <p id={labelId} className="text-caption font-medium">
+ {t(($) => $.qoder.agent)}
+ </p>
+ <Select
+ items={items.map((item) => ({ value: item.id, label: item.name }))}
+ value={value || null}
+ onValueChange={(next) => onChange(next ?? "")}
+ disabled={disabled || query.isPending || !items.length}
+ >
+ <SelectTrigger className="w-full" aria-labelledby={labelId}>
+ <SelectValue placeholder={t(($) => $.qoder.select_agent)} />
+ </SelectTrigger>
+ <SelectContent alignItemWithTrigger={false}>
+ {items.map((item) => (
+ <SelectItem key={item.id} value={item.id}>
+ {item.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.qoder.agent_hint)}
+ </p>
+ {query.isPending && (
+ <p role="status" className="text-caption text-muted-foreground">
+ {t(($) => $.qoder.loading)}
+ </p>
+ )}
+ {query.isError && (
+ <p role="alert" className="text-caption text-destructive">
+ {query.error.message}
+ </p>
+ )}
+ {query.isSuccess && !items.length && (
+ <p role="status" className="text-caption text-muted-foreground">
+ {t(($) => $.qoder.no_agents)}
+ </p>
+ )}
+ {missing && (
+ <p role="alert" className="text-caption text-destructive">
+ {t(($) => $.qoder.agent_unavailable)}
+ </p>
+ )}
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ disabled={disabled || query.isFetching}
+ onClick={() => void query.refetch()}
+ >
+ {t(($) => $.qoder.refresh_catalog)}
+ </Button>
+ </div>
+ );
+}
diff --git a/packages/views/agents/components/runtime-machine-filter-dropdown.test.tsx b/packages/views/agents/components/runtime-machine-filter-dropdown.test.tsx
index ef1ddb7a96..7cf0377ecd 100644
--- a/packages/views/agents/components/runtime-machine-filter-dropdown.test.tsx
+++ b/packages/views/agents/components/runtime-machine-filter-dropdown.test.tsx
@@ -19,6 +19,7 @@ function makeMachine(
daemonId: "daemon-1",
title: "dev.local",
subtitle: "x86_64 macOS",
+ deviceSummary: "x86_64 macOS",
deviceInfo: "dev.local · x86_64 macOS",
cliVersion: "1.0.0",
launchedBy: null,
diff --git a/packages/views/agents/components/tabs/instructions-tab.test.tsx b/packages/views/agents/components/tabs/instructions-tab.test.tsx
index 2507f607df..af9e35e848 100644
--- a/packages/views/agents/components/tabs/instructions-tab.test.tsx
+++ b/packages/views/agents/components/tabs/instructions-tab.test.tsx
@@ -175,6 +175,30 @@ describe("InstructionsTab persisted-state synchronization", () => {
instructions: "Updated instructions.",
});
});
+
+ it("leaves starters out for a runtime that never opens a chat", async () => {
+ const onSave = vi.fn().mockResolvedValue(undefined);
+ const user = userEvent.setup();
+ render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <InstructionsTab
+ agent={baseAgent}
+ onSave={onSave}
+ showConversationStarters={false}
+ />
+ </I18nProvider>,
+ );
+
+ expect(screen.queryByLabelText("Suggestion 1 label")).toBeNull();
+ const instructions = screen.getByLabelText("System prompt");
+ await user.clear(instructions);
+ await user.type(instructions, "Updated instructions.");
+ await user.click(screen.getByRole("button", { name: "Save" }));
+
+ expect(onSave).toHaveBeenCalledWith({
+ instructions: "Updated instructions.",
+ });
+ });
});
// The "customize" link in a chat's empty state lands here with ?focus=. The
diff --git a/packages/views/agents/components/tabs/instructions-tab.tsx b/packages/views/agents/components/tabs/instructions-tab.tsx
index 5c8b44c0cf..868f751b3c 100644
--- a/packages/views/agents/components/tabs/instructions-tab.tsx
+++ b/packages/views/agents/components/tabs/instructions-tab.tsx
@@ -20,6 +20,7 @@ export function InstructionsTab({
agent,
onSave,
onDirtyChange,
+ showConversationStarters = true,
}: {
agent: Agent;
onSave: (updates: {
@@ -27,15 +28,19 @@ export function InstructionsTab({
conversation_starters?: AgentConversationStarter[];
}) => Promise<void>;
onDirtyChange?: (dirty: boolean) => void;
+ /** False for runtimes that never open a chat, where starters do nothing. */
+ showConversationStarters?: boolean;
}) {
const { t } = useT("agents");
// Optional read: this tab is a leaf that tests mount in isolation, and its
// only navigation-dependent behaviour (the deep-link focus below) degrades
// to "no highlight" when there is no adapter.
const navigation = useOptionalNavigation();
- const conversationStartersSupported = useConfigStore(
+ const conversationStartersEnabled = useConfigStore(
(state) => state.agentConversationStartersSupported,
);
+ const conversationStartersSupported =
+ conversationStartersEnabled && showConversationStarters;
const [value, setValue] = useState(agent.instructions ?? "");
const [conversationStarters, setConversationStarters] = useState<AgentConversationStarter[]>(
agent.conversation_starters ?? [],
diff --git a/packages/views/agents/components/tabs/qoder-agent-tab.test.tsx b/packages/views/agents/components/tabs/qoder-agent-tab.test.tsx
new file mode 100644
index 0000000000..d775b1e493
--- /dev/null
+++ b/packages/views/agents/components/tabs/qoder-agent-tab.test.tsx
@@ -0,0 +1,64 @@
+import { vi, it, expect, afterEach } from "vitest";
+import { render, screen, fireEvent, cleanup, waitFor } from "@testing-library/react";
+import { I18nProvider } from "@multica/core/i18n/react";
+import type { Agent } from "@multica/core/types";
+import enRuntimes from "../../../locales/en/runtimes.json";
+import { QoderAgentTab } from "./qoder-agent-tab";
+
+vi.mock("../qoder-agent-select", () => ({
+ QoderAgentSelect: ({ value }: { value: string }) => <span>{value}</span>,
+}));
+vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+
+afterEach(cleanup);
+
+function mount(runtimeConfig: Record<string, unknown>) {
+ const onSave = vi.fn().mockResolvedValue(undefined);
+ render(
+ <I18nProvider locale="en" resources={{ en: { runtimes: enRuntimes } }}>
+ <QoderAgentTab
+ agent={{ runtime_config: runtimeConfig } as unknown as Agent}
+ onSave={onSave}
+ />
+ </I18nProvider>,
+ );
+ return onSave;
+}
+
+it("saves a default repository alongside the QCA Agent binding", async () => {
+ const onSave = mount({ qoder_agent_id: "agent_a", keep: true });
+ const save = screen.getByRole("button", { name: "Save association" });
+ expect(save).toBeDisabled();
+ fireEvent.change(screen.getByLabelText("GitHub URL"), {
+ target: { value: " https://github.com/acme/app " },
+ });
+ fireEvent.change(screen.getByLabelText("Branch"), {
+ target: { value: "main" },
+ });
+ fireEvent.click(save);
+ await waitFor(() =>
+ expect(onSave).toHaveBeenCalledWith({
+ runtime_config: {
+ keep: true,
+ qoder_agent_id: "agent_a",
+ repository: { url: "https://github.com/acme/app", ref: "main" },
+ },
+ }),
+ );
+});
+
+it("removes the default repository when the URL is cleared", async () => {
+ const onSave = mount({
+ qoder_agent_id: "agent_a",
+ repository: { url: "https://github.com/acme/app", ref: "" },
+ });
+ fireEvent.change(screen.getByLabelText("GitHub URL"), {
+ target: { value: "" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Save association" }));
+ await waitFor(() =>
+ expect(onSave).toHaveBeenCalledWith({
+ runtime_config: { qoder_agent_id: "agent_a" },
+ }),
+ );
+});
diff --git a/packages/views/agents/components/tabs/qoder-agent-tab.tsx b/packages/views/agents/components/tabs/qoder-agent-tab.tsx
new file mode 100644
index 0000000000..006e38a132
--- /dev/null
+++ b/packages/views/agents/components/tabs/qoder-agent-tab.tsx
@@ -0,0 +1,110 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { toast } from "sonner";
+import type { Agent } from "@multica/core/types";
+import { qoderAgentId, qoderDefaultRepository } from "@multica/core/agents";
+import { Button } from "@multica/ui/components/ui/button";
+import { Input } from "@multica/ui/components/ui/input";
+import { QoderAgentSelect } from "../qoder-agent-select";
+import { useT } from "../../../i18n";
+
+export function QoderAgentTab({
+ agent,
+ onSave,
+ onDirtyChange,
+ canEdit = true,
+}: {
+ agent: Agent;
+ canEdit?: boolean;
+ onSave: (updates: {
+ runtime_config: Record<string, unknown>;
+ }) => Promise<void>;
+ onDirtyChange?: (dirty: boolean) => void;
+}) {
+ const { t } = useT("runtimes");
+ const savedAgentId = qoderAgentId(agent.runtime_config);
+ const savedRepo = qoderDefaultRepository(agent.runtime_config);
+ const [draft, setDraft] = useState<string | null>(null);
+ const [repoUrl, setRepoUrl] = useState<string | null>(null);
+ const [repoRef, setRepoRef] = useState<string | null>(null);
+ const [saving, setSaving] = useState(false);
+ const value = draft ?? savedAgentId;
+ const url = repoUrl ?? savedRepo.url;
+ const ref = repoRef ?? savedRepo.ref;
+ const dirty =
+ value !== savedAgentId ||
+ url.trim() !== savedRepo.url ||
+ ref.trim() !== savedRepo.ref;
+ useEffect(() => {
+ onDirtyChange?.(dirty);
+ }, [dirty, onDirtyChange]);
+ const disabled = saving || !canEdit;
+ return (
+ <form
+ className="space-y-5"
+ onSubmit={async (event) => {
+ event.preventDefault();
+ if (!dirty || !value || disabled) return;
+ setSaving(true);
+ try {
+ const { repository: _previous, ...rest } = agent.runtime_config;
+ await onSave({
+ runtime_config: {
+ ...rest,
+ qoder_agent_id: value,
+ ...(url.trim()
+ ? { repository: { url: url.trim(), ref: ref.trim() } }
+ : {}),
+ },
+ });
+ setDraft(null);
+ setRepoUrl(null);
+ setRepoRef(null);
+ toast.success(t(($) => $.qoder.agent_saved));
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t(($) => $.qoder.agent_save_failed),
+ );
+ } finally {
+ setSaving(false);
+ }
+ }}
+ >
+ <QoderAgentSelect value={value} onChange={setDraft} disabled={disabled} />
+ <fieldset className="space-y-3">
+ <legend className="text-caption font-medium">
+ {t(($) => $.qoder.default_repository)}
+ </legend>
+ <div className="grid gap-3 sm:grid-cols-[1fr_10rem]">
+ <Input
+ type="url"
+ aria-label={t(($) => $.qoder.github_url)}
+ placeholder="https://github.com/owner/repo"
+ value={url}
+ disabled={disabled}
+ autoComplete="off"
+ onChange={(event) => setRepoUrl(event.target.value)}
+ />
+ <Input
+ aria-label={t(($) => $.qoder.default_branch)}
+ placeholder={t(($) => $.qoder.default_branch_placeholder)}
+ value={ref}
+ disabled={disabled || !url.trim()}
+ autoComplete="off"
+ spellCheck={false}
+ onChange={(event) => setRepoRef(event.target.value)}
+ />
+ </div>
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.qoder.default_repository_hint)}
+ </p>
+ </fieldset>
+ <Button type="submit" disabled={!dirty || !value || disabled}>
+ {saving ? t(($) => $.qoder.working) : t(($) => $.qoder.save_agent)}
+ </Button>
+ </form>
+ );
+}
diff --git a/packages/views/agents/create/agent-configuration-panel.tsx b/packages/views/agents/create/agent-configuration-panel.tsx
index 315d89ae20..bfe636e4d7 100644
--- a/packages/views/agents/create/agent-configuration-panel.tsx
+++ b/packages/views/agents/create/agent-configuration-panel.tsx
@@ -25,6 +25,7 @@ import { CharCounter } from "../components/char-counter";
import { ServiceTierSettingField } from "../components/inspector/service-tier-setting-field";
import { ThinkingSettingField } from "../components/inspector/thinking-prop-row";
import { ModelDropdown } from "../components/model-dropdown";
+import { QoderAgentSelect } from "../components/qoder-agent-select";
import { RuntimePicker } from "../components/runtime-picker";
import { SkillMultiSelect } from "../components/skill-multi-select";
import { ConversationStartersEditor } from "../components/conversation-starters-editor";
@@ -49,6 +50,7 @@ export function AgentConfigurationPanel({
onRuntimeSelect,
runtimeSwitchPending = false,
runtimeSwitchInFlight = false,
+ runtimeSummary,
}: {
draft: AgentDraft;
onChange: (draft: AgentDraft) => void;
@@ -69,6 +71,9 @@ export function AgentConfigurationPanel({
runtimeSwitchPending?: boolean;
/** A rebind request is in flight. */
runtimeSwitchInFlight?: boolean;
+ /** Replaces the runtime picker when the runtime was chosen in an earlier
+ * step and changing it means going back there. */
+ runtimeSummary?: ReactNode;
}) {
const { t } = useT("agents");
const conversationStartersSupported = useConfigStore(
@@ -82,6 +87,9 @@ export function AgentConfigurationPanel({
(member) => member.user_id !== currentUserId,
);
const runtimeLocked = runtimeSwitchPending || runtimeSwitchInFlight;
+ // The Qoder bridge refuses tasks from agents with skills or per-agent
+ // config, so the fields that would produce them are not offered.
+ const qoderRuntime = selectedRuntime?.provider === "qoder_cloud";
const handleRuntimeSelect = (id: string) => {
if (id === draft.runtimeId) return;
if (onRuntimeSelect) {
@@ -176,7 +184,7 @@ export function AgentConfigurationPanel({
className="min-h-44 resize-y font-mono text-label leading-6"
/>
</DraftFieldRow>
- {conversationStartersSupported ? (
+ {conversationStartersSupported && !qoderRuntime ? (
<div className="px-4 py-4">
<ConversationStartersEditor
value={draft.conversationStarters}
@@ -184,12 +192,18 @@ export function AgentConfigurationPanel({
/>
</div>
) : null}
- <div className="px-4 py-4">
- <SkillMultiSelect
- selectedIds={draft.skillIds}
- onChange={(ids) => set("skillIds", ids)}
- />
- </div>
+ {qoderRuntime ? (
+ <p className="px-4 py-3 text-caption text-muted-foreground">
+ {t(($) => $.creation_studio.cloud_fields_note)}
+ </p>
+ ) : (
+ <div className="px-4 py-4">
+ <SkillMultiSelect
+ selectedIds={draft.skillIds}
+ onChange={(ids) => set("skillIds", ids)}
+ />
+ </div>
+ )}
</SettingsCard>
</SettingsSection>
@@ -202,6 +216,7 @@ export function AgentConfigurationPanel({
className={cn("grid gap-4 px-4 py-4", !compact && "sm:grid-cols-2")}
>
<div className="min-w-0">
+ {runtimeSummary ?? (
<RuntimePicker
runtimes={runtimes}
runtimesLoading={runtimesLoading}
@@ -212,6 +227,7 @@ export function AgentConfigurationPanel({
disabled={runtimeLocked}
autoSelect={!onRuntimeSelect}
/>
+ )}
{/* A silently greyed-out picker is the worst version of this: the
user reaches for it exactly when the current runtime has gone
wrong, so say what unblocks it instead of just refusing. */}
@@ -221,18 +237,28 @@ export function AgentConfigurationPanel({
</p>
)}
</div>
- <ModelDropdown
- runtimeId={selectedRuntime?.id ?? null}
- runtimeOnline={selectedRuntime?.status === "online"}
- value={draft.model}
- onChange={(value) => onChange(applyDraftModelChange(draft, value))}
- onAutomaticChange={(value) =>
- onAutomaticChange(applyDraftModelChange(draft, value))
- }
- // A successful switch clears the model, so an edit made while the
- // rebind is in flight would be silently discarded.
- disabled={!selectedRuntime || runtimeSwitchInFlight}
- />
+ {qoderRuntime ? (
+ <QoderAgentSelect
+ value={draft.qoderAgentId}
+ onChange={(value) => set("qoderAgentId", value)}
+ disabled={runtimeLocked}
+ />
+ ) : (
+ <ModelDropdown
+ runtimeId={selectedRuntime?.id ?? null}
+ runtimeOnline={selectedRuntime?.status === "online"}
+ value={draft.model}
+ onChange={(value) =>
+ onChange(applyDraftModelChange(draft, value))
+ }
+ onAutomaticChange={(value) =>
+ onAutomaticChange(applyDraftModelChange(draft, value))
+ }
+ // A successful switch clears the model, so an edit made while the
+ // rebind is in flight would be silently discarded.
+ disabled={!selectedRuntime || runtimeSwitchInFlight}
+ />
+ )}
</div>
{/* Both fields fail closed: they render only when the exact selected
model's live catalog advertises the capability (or a value is
diff --git a/packages/views/agents/create/agent-created-page.tsx b/packages/views/agents/create/agent-created-page.tsx
new file mode 100644
index 0000000000..a0712425b3
--- /dev/null
+++ b/packages/views/agents/create/agent-created-page.tsx
@@ -0,0 +1,202 @@
+"use client";
+
+import type { ReactNode } from "react";
+import { ArrowRight, AtSign, CircleCheck, ListPlus, Users } from "lucide-react";
+import { useQuery } from "@tanstack/react-query";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useModalStore } from "@multica/core/modals";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { runtimeDisplayLabel } from "@multica/core/runtimes";
+import { runtimeListOptions } from "@multica/core/runtimes/queries";
+import {
+ agentDetailOptions,
+ squadListOptions,
+} from "@multica/core/workspace/queries";
+import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import { cn } from "@multica/ui/lib/utils";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { AppLink, useNavigation } from "../../navigation";
+import { useT } from "../../i18n";
+import { AgentCreateShell } from "./create-shell";
+
+/**
+ * Step 3 of agent creation. The agent exists; this screen only points at its
+ * first uses, so leaving it at any point loses nothing.
+ */
+export function AgentCreatedPage({ agentId }: { agentId: string }) {
+ const { t } = useT("agents");
+ const wsId = useWorkspaceId();
+ const paths = useWorkspacePaths();
+ const navigation = useNavigation();
+ const squadId = navigation.searchParams.get("squad");
+
+ const { data: agent, isLoading } = useQuery(agentDetailOptions(wsId, agentId));
+ const { data: runtimes = [] } = useQuery(runtimeListOptions(wsId));
+ const { data: squads = [] } = useQuery(squadListOptions(wsId));
+ const runtime = runtimes.find((item) => item.id === agent?.runtime_id) ?? null;
+ const squad = squadId ? squads.find((item) => item.id === squadId) ?? null : null;
+ const name = agent?.name ?? "";
+
+ return (
+ <AgentCreateShell
+ title={t(($) => $.creation_studio.title)}
+ step={t(($) => $.creation_studio.steps.done)}
+ stepIndex={3}
+ closeIcon
+ onBack={() => navigation.replace(paths.agentDetail(agentId))}
+ >
+ <main className="flex min-h-0 flex-1 flex-col overflow-y-auto px-5 py-12">
+ <div className="m-auto w-full max-w-xl">
+ <div className="flex flex-col items-center text-center">
+ {isLoading || !agent ? (
+ <Skeleton className="size-14 rounded-full" />
+ ) : (
+ <span className="relative">
+ <ActorAvatar
+ actorType="agent"
+ actorId={agent.id}
+ name={agent.name}
+ avatarUrl={agent.avatar_url}
+ size="2xl"
+ />
+ <CircleCheck
+ aria-hidden="true"
+ className="absolute -bottom-1 -right-1 size-5 rounded-full bg-background text-success"
+ />
+ </span>
+ )}
+ <h2 className="mt-5 text-balance text-title font-semibold tracking-tight">
+ {isLoading
+ ? t(($) => $.creation_studio.done.loading)
+ : t(($) => $.creation_studio.done.title, { name })}
+ </h2>
+ {runtime ? (
+ <p className="mt-1.5 text-body text-muted-foreground">
+ {t(($) => $.creation_studio.done.runs_on, {
+ runtime: runtimeDisplayLabel(runtime),
+ })}
+ </p>
+ ) : null}
+ {squad ? (
+ <p className="mt-3 rounded-full bg-success/10 px-2.5 py-1 text-caption text-success">
+ {t(($) => $.creation_studio.done.joined_squad, { squad: squad.name })}
+ </p>
+ ) : null}
+ </div>
+
+ <p className="mt-10 text-label font-medium text-muted-foreground">
+ {t(($) => $.creation_studio.done.next)}
+ </p>
+ <div className="mt-2 space-y-2">
+ <DoneAction
+ icon={ListPlus}
+ title={t(($) => $.creation_studio.done.assign_title)}
+ description={t(($) => $.creation_studio.done.assign_description)}
+ primary
+ disabled={!agent}
+ onClick={() =>
+ useModalStore.getState().open("create-issue", {
+ assignee_type: "agent",
+ assignee_id: agentId,
+ })
+ }
+ />
+ <DoneAction
+ icon={AtSign}
+ title={t(($) => $.creation_studio.done.mention_title)}
+ description={t(($) => $.creation_studio.done.mention_description, { name })}
+ href={paths.issues()}
+ />
+ <DoneAction
+ icon={Users}
+ title={
+ squad
+ ? t(($) => $.creation_studio.done.open_squad_title, { squad: squad.name })
+ : t(($) => $.creation_studio.done.squad_title)
+ }
+ description={
+ squad
+ ? t(($) => $.creation_studio.done.open_squad_description)
+ : t(($) => $.creation_studio.done.squad_description)
+ }
+ href={squad ? paths.squadDetail(squad.id) : paths.squads()}
+ />
+ </div>
+
+ <div className="mt-8 flex items-center justify-center gap-4 text-label">
+ <AppLink
+ href={paths.agentDetail(agentId)}
+ className="font-medium text-foreground underline-offset-4 hover:underline"
+ >
+ {t(($) => $.creation_studio.done.open_agent)}
+ </AppLink>
+ <span aria-hidden="true" className="text-muted-foreground">·</span>
+ <AppLink
+ href={paths.agents()}
+ className="text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"
+ >
+ {t(($) => $.creation_studio.done.back_to_list)}
+ </AppLink>
+ </div>
+ </div>
+ </main>
+ </AgentCreateShell>
+ );
+}
+
+function DoneAction({
+ icon: Icon,
+ title,
+ description,
+ primary = false,
+ disabled = false,
+ href,
+ onClick,
+}: {
+ icon: typeof ListPlus;
+ title: string;
+ description: string;
+ primary?: boolean;
+ disabled?: boolean;
+ href?: string;
+ onClick?: () => void;
+}) {
+ const className = cn(
+ "group flex w-full items-center gap-3 rounded-lg border bg-card px-4 py-3 text-left",
+ "transition-colors hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ "disabled:pointer-events-none disabled:opacity-50",
+ primary && "border-primary/30 bg-primary/[0.03]",
+ );
+ const body: ReactNode = (
+ <>
+ <span
+ className={cn(
+ "flex size-9 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground",
+ primary && "bg-primary/10 text-primary",
+ )}
+ >
+ <Icon aria-hidden="true" className="size-4" />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block text-body font-medium">{title}</span>
+ <span className="block text-caption text-muted-foreground">{description}</span>
+ </span>
+ <ArrowRight
+ aria-hidden="true"
+ className="size-4 shrink-0 text-muted-foreground transition-transform group-hover:translate-x-0.5"
+ />
+ </>
+ );
+ if (href) {
+ return (
+ <AppLink href={href} className={className}>
+ {body}
+ </AppLink>
+ );
+ }
+ return (
+ <button type="button" className={className} disabled={disabled} onClick={onClick}>
+ {body}
+ </button>
+ );
+}
diff --git a/packages/views/agents/create/agent-execution-overrides.test.tsx b/packages/views/agents/create/agent-execution-overrides.test.tsx
index 530e0f8f1c..3633ce79a2 100644
--- a/packages/views/agents/create/agent-execution-overrides.test.tsx
+++ b/packages/views/agents/create/agent-execution-overrides.test.tsx
@@ -68,6 +68,7 @@ function listResult(models: RuntimeModel[]): RuntimeModelListRequest {
}
const baseDraft: AgentDraft = {
+ qoderAgentId: "",
name: "Fast Codex",
description: "",
instructions: "",
diff --git a/packages/views/agents/create/ai-builder-session-page.tsx b/packages/views/agents/create/ai-builder-session-page.tsx
index 09e5a96e98..6860b5389d 100644
--- a/packages/views/agents/create/ai-builder-session-page.tsx
+++ b/packages/views/agents/create/ai-builder-session-page.tsx
@@ -44,7 +44,7 @@ export function AiBuilderSessionPage({ sessionId }: { sessionId: string }) {
// link that outlived it. Replace rather than push: the address no longer
// resolves, so it must not stay on the stack for a back to land on.
const leave = useCallback(
- () => navigation.replace(withSquadParam(paths.newAgentAi(), squadId)),
+ () => navigation.replace(withSquadParam(paths.newAgent(), squadId)),
[navigation, paths, squadId],
);
diff --git a/packages/views/agents/create/builder-workspace.tsx b/packages/views/agents/create/builder-workspace.tsx
index 166fde35c4..e516aeb1d1 100644
--- a/packages/views/agents/create/builder-workspace.tsx
+++ b/packages/views/agents/create/builder-workspace.tsx
@@ -166,6 +166,7 @@ export function BuilderWorkspace({
const submit = useCreateAgentSubmit({
draft,
runtimeId: selectedRuntime?.id ?? null,
+ runtimeProvider: selectedRuntime?.provider,
squadId,
template: "agent_builder",
// The agent is already committed here, so builder cleanup must never turn
diff --git a/packages/views/agents/create/choose-create-method-page.tsx b/packages/views/agents/create/choose-create-method-page.tsx
deleted file mode 100644
index 875f3bb708..0000000000
--- a/packages/views/agents/create/choose-create-method-page.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-"use client";
-
-import { ChevronRight, FileText, MessageSquare } from "lucide-react";
-import { useWorkspacePaths } from "@multica/core/paths";
-import { cn } from "@multica/ui/lib/utils";
-import { AppLink, useBackOrReplace, useNavigation } from "../../navigation";
-import { useT } from "../../i18n";
-import { AgentCreateShell } from "./create-shell";
-import { withSquadParam } from "./squad-param";
-
-/**
- * Entry route of agent creation: pick a method, then hand off to that method's
- * own route. Holds no draft — nothing typed here survives to the next screen
- * because nothing is typed here.
- */
-export function ChooseCreateMethodPage() {
- const { t } = useT("agents");
- const paths = useWorkspacePaths();
- const navigation = useNavigation();
- const backOrReplace = useBackOrReplace();
- const squadId = navigation.searchParams.get("squad");
-
- return (
- <AgentCreateShell
- title={
- squadId
- ? t(($) => $.creation_studio.squad_title)
- : t(($) => $.creation_studio.title)
- }
- step={t(($) => $.creation_studio.step_choose)}
- onBack={() => backOrReplace(paths.agents())}
- >
- <main className="flex min-h-0 flex-1 flex-col overflow-y-auto px-5 py-10">
- <CreateMethodChooser
- blankHref={withSquadParam(paths.newAgentManual(), squadId)}
- aiHref={withSquadParam(paths.newAgentAi(), squadId)}
- />
- </main>
- </AgentCreateShell>
- );
-}
-
-export function CreateMethodChooser({
- blankHref,
- aiHref,
-}: {
- blankHref: string;
- aiHref: string;
-}) {
- const { t } = useT("agents");
- const modes = [
- {
- icon: FileText,
- title: t(($) => $.creation_studio.modes.blank.title),
- description: t(($) => $.creation_studio.modes.blank.description),
- href: blankHref,
- },
- {
- icon: MessageSquare,
- title: t(($) => $.creation_studio.modes.ai.title),
- description: t(($) => $.creation_studio.modes.ai.description),
- href: aiHref,
- recommended: true,
- },
- ];
- return (
- <div className="m-auto w-full max-w-5xl">
- <div className="mx-auto max-w-2xl text-center">
- <div className="text-caption font-medium uppercase tracking-wider text-muted-foreground">
- {t(($) => $.creation_studio.eyebrow)}
- </div>
- <h2 className="mt-2 text-balance text-display-sm font-semibold tracking-tight sm:text-display">
- {t(($) => $.creation_studio.choose_title)}
- </h2>
- </div>
- <div className="mx-auto mt-9 grid max-w-3xl gap-4 md:grid-cols-2">
- {modes.map(
- ({ icon: Icon, title, description, href, recommended }) => (
- <AppLink
- key={title}
- href={href}
- className={cn(
- "group relative flex min-h-56 flex-col items-start rounded-xl border bg-card p-5 text-left",
- "transition-[border-color,background-color,transform] hover:-translate-y-0.5 hover:border-primary/40 hover:bg-accent/30",
- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
- recommended && "border-primary/30 bg-primary/[0.025]",
- )}
- >
- {recommended && (
- <span className="absolute right-4 top-4 rounded-full bg-primary/10 px-2 py-1 text-micro font-medium text-primary">
- {t(($) => $.creation_studio.recommended)}
- </span>
- )}
- <span className="flex size-11 items-center justify-center rounded-lg bg-muted text-muted-foreground group-hover:text-foreground">
- <Icon className="size-5" aria-hidden="true" />
- </span>
- <span className="mt-7 text-title-sm font-semibold">{title}</span>
- <span className="mt-2 text-body leading-6 text-muted-foreground">
- {description}
- </span>
- <span className="mt-auto flex items-center gap-1 pt-5 text-caption font-medium text-foreground">
- {t(($) => $.creation_studio.continue)}
- <ChevronRight
- className="size-3.5 transition-transform group-hover:translate-x-0.5"
- aria-hidden="true"
- />
- </span>
- </AppLink>
- ),
- )}
- </div>
- </div>
- );
-}
diff --git a/packages/views/agents/create/choose-runtime-page.tsx b/packages/views/agents/create/choose-runtime-page.tsx
new file mode 100644
index 0000000000..c5ee6305cd
--- /dev/null
+++ b/packages/views/agents/create/choose-runtime-page.tsx
@@ -0,0 +1,306 @@
+"use client";
+
+import { useEffect, useMemo, useRef, useState } from "react";
+import { ArrowRight, Search } from "lucide-react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { agentBuilderSessionListOptions } from "@multica/core/agents";
+import { useAuthStore } from "@multica/core/auth";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { qoderOptions } from "@multica/core/runtimes/qoder";
+import { runtimeKeys, runtimeListOptions } from "@multica/core/runtimes/queries";
+import { useWSEvent } from "@multica/core/realtime";
+import { memberListOptions } from "@multica/core/workspace/queries";
+import { Button } from "@multica/ui/components/ui/button";
+import { Input } from "@multica/ui/components/ui/input";
+import { useBackOrReplace, useNavigation } from "../../navigation";
+import { useT } from "../../i18n";
+import { ConnectRemoteDialog } from "../../runtimes/components/connect-remote-dialog";
+import { RemoteRuntimeDialog } from "../../runtimes/components/remote-runtime-dialog";
+import { QODER_RUNTIME_LOCATOR } from "../../runtimes/components/qoder-detail-page";
+import { buildRuntimeMachines } from "../../runtimes/components/runtime-machines";
+import { AgentCreateShell } from "./create-shell";
+import { buildRuntimeChoiceGroups, type HarnessOption } from "./runtime-choice";
+import { RuntimeChoiceList, qoderChoiceState } from "./runtime-choice-list";
+import { createPathWithParams } from "./squad-param";
+import { UnfinishedDraftsBanner } from "./unfinished-drafts";
+
+type Selection = { kind: "runtime"; runtimeId: string } | { kind: "qoder" } | null;
+
+/** How often a starting Qoder runtime is re-fetched while this screen shows it. */
+const QODER_REGISTER_POLL_MS = 3_000;
+
+export interface ChooseRuntimePageProps {
+ /** Desktop-only: the daemon running on this device. */
+ localDaemonId?: string | null;
+ localMachineName?: string | null;
+ /** Desktop-only: this device can run harnesses, even before any registered. */
+ hasLocalMachine?: boolean;
+ /** The bundled daemon is starting and has not registered yet. */
+ bootstrapping?: boolean;
+}
+
+/**
+ * Step 1 of agent creation: where the agent runs. Everything after this step
+ * depends on the answer (which models exist, whether skills apply), so the
+ * runtime is chosen before anything is typed.
+ */
+export function ChooseRuntimePage({
+ localDaemonId = null,
+ localMachineName = null,
+ hasLocalMachine = false,
+ bootstrapping = false,
+}: ChooseRuntimePageProps = {}) {
+ const { t } = useT("agents");
+ const wsId = useWorkspaceId();
+ const qc = useQueryClient();
+ const paths = useWorkspacePaths();
+ const navigation = useNavigation();
+ const backOrReplace = useBackOrReplace();
+ const squadId = navigation.searchParams.get("squad");
+ const runtimeParam = navigation.searchParams.get("runtime");
+ const currentUserId = useAuthStore((state) => state.user?.id ?? null);
+
+ const { data: runtimes = [], isLoading: runtimesLoading } = useQuery(
+ runtimeListOptions(wsId),
+ );
+ const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const { data: qoderConnection } = useQuery(qoderOptions(wsId));
+ const { data: sessions = [] } = useQuery(agentBuilderSessionListOptions(wsId));
+
+ useWSEvent("daemon:register", () => {
+ void qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });
+ });
+
+ const groups = useMemo(() => {
+ const machines = buildRuntimeMachines(runtimes, {
+ now: Date.now(),
+ localDaemonId,
+ localMachineName,
+ currentUserId,
+ ensureLocalMachine: hasLocalMachine,
+ });
+ return buildRuntimeChoiceGroups(machines, currentUserId);
+ }, [runtimes, localDaemonId, localMachineName, currentUserId, hasLocalMachine]);
+
+ const member = members.find((m) => m.user_id === currentUserId);
+ const canManage = member?.role === "owner" || member?.role === "admin";
+ const ownerName = (ownerId: string | null) =>
+ members.find((m) => m.user_id === ownerId)?.name ?? null;
+
+ const qoder = qoderConnection?.available ? qoderConnection : null;
+ const qoderRuntime = groups.qoderRuntime;
+ const qoderState = qoder
+ ? qoderChoiceState(qoder, qoderRuntime?.status === "online")
+ : null;
+
+ const [selection, setSelection] = useState<Selection>(null);
+ const [query, setQuery] = useState("");
+ const [showConnectRemote, setShowConnectRemote] = useState(false);
+ const [qoderDialogOpen, setQoderDialogOpen] = useState(false);
+ const [selectQoderWhenReady, setSelectQoderWhenReady] = useState(false);
+ const searchRef = useRef<HTMLInputElement>(null);
+
+ const options = useMemo(() => {
+ const byId = new Map<string, { option: HarnessOption; where: string }>();
+ for (const device of [...(groups.local ? [groups.local] : []), ...groups.remotes]) {
+ for (const option of device.harnesses) {
+ byId.set(option.runtime.id, { option, where: device.machine.title });
+ }
+ }
+ const cloudTitle = t(($) => $.creation_studio.runtime_step.groups.cloud);
+ for (const option of groups.cloud) {
+ byId.set(option.runtime.id, { option, where: cloudTitle });
+ }
+ return byId;
+ }, [groups, t]);
+
+ // `?runtime=` comes back from step 2's "change runtime" and from the Qoder
+ // card on the runtimes page; it preselects once the list can resolve it.
+ const seeded = useRef(false);
+ useEffect(() => {
+ if (seeded.current || runtimesLoading) return;
+ seeded.current = true;
+ if (!runtimeParam) return;
+ if (qoderRuntime?.id === runtimeParam) setSelection({ kind: "qoder" });
+ else if (options.has(runtimeParam)) {
+ setSelection({ kind: "runtime", runtimeId: runtimeParam });
+ }
+ }, [runtimeParam, runtimesLoading, options, qoderRuntime]);
+
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== "/" || event.metaKey || event.ctrlKey || event.altKey) return;
+ const target = event.target as HTMLElement | null;
+ if (target?.closest("input, textarea, [contenteditable='true']")) return;
+ event.preventDefault();
+ searchRef.current?.focus();
+ };
+ window.addEventListener("keydown", onKeyDown);
+ return () => window.removeEventListener("keydown", onKeyDown);
+ }, []);
+
+ // A fresh connection registers its runtime asynchronously; keep the list
+ // current while Qoder starts, and select it once it can take tasks.
+ useEffect(() => {
+ if (qoderState !== "starting") return;
+ const timer = setInterval(() => {
+ void qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });
+ }, QODER_REGISTER_POLL_MS);
+ return () => clearInterval(timer);
+ }, [qoderState, qc, wsId]);
+
+ useEffect(() => {
+ if (!selectQoderWhenReady) return;
+ if (qoderState === "ready") {
+ setSelectQoderWhenReady(false);
+ setSelection({ kind: "qoder" });
+ } else if (qoderState === "error" || qoderState === "stopped") {
+ setSelectQoderWhenReady(false);
+ }
+ }, [selectQoderWhenReady, qoderState]);
+
+ const selected =
+ selection?.kind === "runtime" ? options.get(selection.runtimeId) ?? null : null;
+ const nextRuntimeId =
+ selection?.kind === "qoder"
+ ? qoderState === "ready"
+ ? qoderRuntime?.id ?? null
+ : null
+ : selected && selected.option.runtime.status === "online"
+ ? selected.option.runtime.id
+ : null;
+
+ const goNext = (runtimeId: string) =>
+ navigation.push(
+ createPathWithParams(paths.newAgentManual(), {
+ squad: squadId,
+ runtime: runtimeId,
+ }),
+ );
+
+ const resumeSession = (sessionId: string) =>
+ navigation.push(
+ createPathWithParams(paths.newAgentAiSession(sessionId), { squad: squadId }),
+ );
+
+ const summary =
+ selection?.kind === "qoder"
+ ? "Qoder Cloud Agent"
+ : selected
+ ? `${selected.option.label} · ${selected.where}`
+ : null;
+
+ return (
+ <AgentCreateShell
+ title={
+ squadId
+ ? t(($) => $.creation_studio.squad_title)
+ : t(($) => $.creation_studio.title)
+ }
+ step={t(($) => $.creation_studio.steps.runtime)}
+ stepIndex={1}
+ onBack={() => backOrReplace(paths.agents())}
+ closeIcon
+ >
+ <main className="min-h-0 flex-1 overflow-y-auto">
+ <div className="mx-auto w-full max-w-3xl px-5 py-8 sm:px-8">
+ <div className="flex flex-wrap items-center justify-between gap-4">
+ <h2 className="min-w-0 text-balance text-title font-semibold tracking-tight">
+ {t(($) => $.creation_studio.runtime_step.title)}
+ </h2>
+ <div className="relative w-full sm:w-60">
+ <Search
+ aria-hidden="true"
+ className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground"
+ />
+ <Input
+ ref={searchRef}
+ type="search"
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Escape") setQuery("");
+ }}
+ placeholder={t(($) => $.creation_studio.runtime_step.search_placeholder)}
+ aria-label={t(($) => $.creation_studio.runtime_step.search_placeholder)}
+ className="h-8 pl-8 pr-8"
+ />
+ <kbd className="pointer-events-none absolute right-2 top-1/2 -translate-y-1/2 rounded-xs border bg-muted px-1 text-micro text-muted-foreground">
+ /
+ </kbd>
+ </div>
+ </div>
+
+ {sessions.length > 0 ? (
+ <div className="mt-6">
+ <UnfinishedDraftsBanner sessions={sessions} onResume={resumeSession} />
+ </div>
+ ) : null}
+
+ <div className="mt-5">
+ <RuntimeChoiceList
+ local={groups.local}
+ localAvailable={hasLocalMachine}
+ localStarting={bootstrapping}
+ remotes={groups.remotes}
+ hiddenRemoteCount={groups.hiddenRemoteCount}
+ cloud={groups.cloud}
+ qoder={qoder}
+ qoderState={qoderState}
+ qoderSelected={selection?.kind === "qoder"}
+ selectedRuntimeId={selection?.kind === "runtime" ? selection.runtimeId : null}
+ query={query}
+ currentUserId={currentUserId}
+ canManage={canManage}
+ ownerName={ownerName}
+ onSelect={(runtimeId) =>
+ setSelection((current) =>
+ current?.kind === "runtime" && current.runtimeId === runtimeId
+ ? null
+ : { kind: "runtime", runtimeId },
+ )
+ }
+ onSelectQoder={() =>
+ setSelection((current) => (current?.kind === "qoder" ? null : { kind: "qoder" }))
+ }
+ onConnectQoder={() => setQoderDialogOpen(true)}
+ onManageQoder={() =>
+ navigation.push(paths.runtimeDetail(QODER_RUNTIME_LOCATOR))
+ }
+ onAddRemote={() => setShowConnectRemote(true)}
+ />
+ </div>
+ </div>
+ </main>
+ <footer className="flex shrink-0 items-center gap-3 border-t bg-background px-5 py-3">
+ <p className="min-w-0 flex-1 truncate text-label text-muted-foreground">
+ {summary ? (
+ <>
+ {t(($) => $.creation_studio.runtime_step.footer_selected)}{" "}
+ <span className="font-medium text-foreground">{summary}</span>
+ </>
+ ) : (
+ t(($) => $.creation_studio.runtime_step.footer_hint)
+ )}
+ </p>
+ <Button variant="ghost" onClick={() => backOrReplace(paths.agents())}>
+ {t(($) => $.creation_studio.runtime_step.cancel)}
+ </Button>
+ <Button disabled={!nextRuntimeId} onClick={() => nextRuntimeId && goNext(nextRuntimeId)}>
+ {t(($) => $.creation_studio.runtime_step.next)}
+ <ArrowRight aria-hidden="true" className="size-3.5" />
+ </Button>
+ </footer>
+ {showConnectRemote ? (
+ <ConnectRemoteDialog onClose={() => setShowConnectRemote(false)} />
+ ) : null}
+ {qoderDialogOpen ? (
+ <RemoteRuntimeDialog
+ onConnected={() => setSelectQoderWhenReady(true)}
+ onClose={() => setQoderDialogOpen(false)}
+ />
+ ) : null}
+ </AgentCreateShell>
+ );
+}
diff --git a/packages/views/agents/create/create-agent-footer.tsx b/packages/views/agents/create/create-agent-footer.tsx
index a9e2aceb30..95c96c4740 100644
--- a/packages/views/agents/create/create-agent-footer.tsx
+++ b/packages/views/agents/create/create-agent-footer.tsx
@@ -65,7 +65,7 @@ export function CreateAgentFooter({
? t(($) => $.creation_studio.creating)
: squad
? t(($) => $.creation_studio.create_and_add)
- : t(($) => $.creation_studio.create_and_open)}
+ : t(($) => $.creation_studio.create_agent)}
</Button>
</div>
);
diff --git a/packages/views/agents/create/create-agent-ui.test.ts b/packages/views/agents/create/create-agent-ui.test.ts
index 9f6ddc992c..97af143881 100644
--- a/packages/views/agents/create/create-agent-ui.test.ts
+++ b/packages/views/agents/create/create-agent-ui.test.ts
@@ -18,16 +18,7 @@ vi.mock("../../i18n", () => ({
t: (
selector: (translations: {
creation_studio: {
- eyebrow: string;
- choose_title: string;
- choose_description: string;
- recommended: string;
- continue: string;
- modes: {
- blank: { title: string; description: string };
- ai: { title: string; description: string };
- };
- create_and_open: string;
+ create_agent: string;
create_and_add: string;
creating: string;
name_conflict: string;
@@ -40,22 +31,7 @@ vi.mock("../../i18n", () => ({
) =>
selector({
creation_studio: {
- eyebrow: "Agent creation",
- choose_title: "How would you like to start?",
- choose_description: "Choose a creation mode.",
- recommended: "Recommended",
- continue: "Continue",
- modes: {
- blank: {
- title: "Start blank",
- description: "Configure every field yourself.",
- },
- ai: {
- title: "Build with AI",
- description: "Describe the outcome you want.",
- },
- },
- create_and_open: "Create and open",
+ create_agent: "Create agent",
create_and_add: "Create and add",
creating: "Creating…",
name_conflict: "An agent with this name already exists.",
@@ -157,7 +133,7 @@ describe("Agent creation errors", () => {
);
const error = screen.getByRole("alert");
- const button = screen.getByRole("button", { name: "Create and open" });
+ const button = screen.getByRole("button", { name: "Create agent" });
expect(error.parentElement).toBe(button.parentElement);
expect(
error.compareDocumentPosition(button) & Node.DOCUMENT_POSITION_FOLLOWING,
diff --git a/packages/views/agents/create/create-shell.tsx b/packages/views/agents/create/create-shell.tsx
index b8d5106407..d7591288ea 100644
--- a/packages/views/agents/create/create-shell.tsx
+++ b/packages/views/agents/create/create-shell.tsx
@@ -1,28 +1,36 @@
"use client";
-import type { ReactNode } from "react";
-import { ArrowLeft } from "lucide-react";
+import { Fragment, type ReactNode } from "react";
+import { ArrowLeft, Check, X } from "lucide-react";
import { IconButton } from "@multica/ui/components/common/icon-button";
+import { cn } from "@multica/ui/lib/utils";
import { useT } from "../../i18n";
+export type AgentCreateStep = 1 | 2 | 3;
+
/**
* Chrome shared by every agent-creation route: the back control, the flow
- * title, and the current step. Each route owns what "back" means — the chooser
- * leaves the flow, the two method routes return to the chooser — so the shell
+ * title, and the current step. Each route owns what "back" means, so the shell
* takes a handler rather than deriving it.
*/
export function AgentCreateShell({
title,
step,
+ stepIndex,
onBack,
backDisabled = false,
+ closeIcon = false,
chips,
children,
}: {
title: string;
step: string;
+ /** Position in runtime → configure → done. Omitted by off-path routes. */
+ stepIndex?: AgentCreateStep;
onBack: () => void;
backDisabled?: boolean;
+ /** The flow is finished, so the control leaves it instead of going back. */
+ closeIcon?: boolean;
/** Right-aligned context badges (method, runtime). Hidden on small screens. */
chips?: ReactNode;
children: ReactNode;
@@ -37,18 +45,27 @@ export function AgentCreateShell({
size="icon"
onClick={onBack}
disabled={backDisabled}
- label={t(($) => $.creation_studio.back)}
+ label={
+ closeIcon
+ ? t(($) => $.creation_studio.close)
+ : t(($) => $.creation_studio.back)
+ }
tooltipSide="bottom"
>
- <ArrowLeft className="size-4" aria-hidden="true" />
+ {closeIcon ? (
+ <X className="size-4" aria-hidden="true" />
+ ) : (
+ <ArrowLeft className="size-4" aria-hidden="true" />
+ )}
</IconButton>
<div className="min-w-0">
<h1 className="truncate text-body font-semibold">{title}</h1>
<p className="truncate text-caption text-muted-foreground">{step}</p>
</div>
- {chips ? (
- <div className="ml-auto hidden items-center gap-2 text-caption text-muted-foreground sm:flex">
- {chips}
+ {chips || stepIndex ? (
+ <div className="ml-auto hidden items-center gap-4 text-caption text-muted-foreground sm:flex">
+ {chips ? <div className="flex items-center gap-2">{chips}</div> : null}
+ {stepIndex ? <CreateStepper active={stepIndex} /> : null}
</div>
) : null}
</header>
@@ -58,5 +75,55 @@ export function AgentCreateShell({
}
export function AgentCreateChip({ children }: { children: ReactNode }) {
- return <span className="rounded-full bg-muted px-2 py-1">{children}</span>;
+ return (
+ <span className="flex max-w-64 items-center gap-1.5 truncate rounded-full bg-muted px-2 py-1">
+ {children}
+ </span>
+ );
+}
+
+function CreateStepper({ active }: { active: AgentCreateStep }) {
+ const { t } = useT("agents");
+ const labels = [
+ t(($) => $.creation_studio.steps.runtime),
+ t(($) => $.creation_studio.steps.configure),
+ t(($) => $.creation_studio.steps.done),
+ ];
+ return (
+ <ol
+ className="hidden items-center gap-2 lg:flex"
+ aria-label={t(($) => $.creation_studio.steps.aria)}
+ >
+ {labels.map((label, index) => {
+ const number = index + 1;
+ const done = number < active;
+ const current = number === active;
+ return (
+ <Fragment key={label}>
+ {index > 0 ? (
+ <li aria-hidden="true" className="h-px w-5 bg-border" />
+ ) : null}
+ <li
+ aria-current={current ? "step" : undefined}
+ className={cn(
+ "flex items-center gap-1.5",
+ current && "font-medium text-foreground",
+ )}
+ >
+ <span
+ className={cn(
+ "flex size-[18px] items-center justify-center rounded-full border text-micro tabular-nums",
+ current && "border-primary bg-primary text-primary-foreground",
+ done && "border-success/30 bg-success/10 text-success",
+ )}
+ >
+ {done ? <Check className="size-3" aria-hidden="true" /> : number}
+ </span>
+ {label}
+ </li>
+ </Fragment>
+ );
+ })}
+ </ol>
+ );
}
diff --git a/packages/views/agents/create/index.ts b/packages/views/agents/create/index.ts
index 153061d5f4..60412ca892 100644
--- a/packages/views/agents/create/index.ts
+++ b/packages/views/agents/create/index.ts
@@ -1,7 +1,8 @@
// The route entry points. Everything else in this folder is internal to the
// flow and already imported by path — re-exporting it here only created a
// second name for the same thing and a list to keep in sync.
-export { ChooseCreateMethodPage } from "./choose-create-method-page";
+export { ChooseRuntimePage } from "./choose-runtime-page";
+export { AgentCreatedPage } from "./agent-created-page";
export { ManualCreateAgentPage } from "./manual-create-agent-page";
export { AiCreateAgentPage } from "./ai-create-agent-page";
export { AiBuilderSessionPage } from "./ai-builder-session-page";
diff --git a/packages/views/agents/create/manual-create-agent-page.test.tsx b/packages/views/agents/create/manual-create-agent-page.test.tsx
new file mode 100644
index 0000000000..811b0c5e2b
--- /dev/null
+++ b/packages/views/agents/create/manual-create-agent-page.test.tsx
@@ -0,0 +1,108 @@
+// @vitest-environment jsdom
+
+import type { ReactNode } from "react";
+import { cleanup } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { EMPTY_AGENT_DRAFT } from "@multica/core/agents";
+import { renderWithI18n } from "../../test/i18n";
+import { ManualCreateAgentPage } from "./manual-create-agent-page";
+
+const nav = vi.hoisted(() => ({
+ pathname: "/acme/agents/new/manual",
+ searchParams: new URLSearchParams(),
+ push: vi.fn(),
+ replace: vi.fn(),
+}));
+
+vi.mock("@multica/core/api", () => ({ api: {} }));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-test" }));
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({
+ newAgent: () => "/acme/agents/new",
+ newAgentManual: () => "/acme/agents/new/manual",
+ }),
+}));
+vi.mock("@multica/core/workspace/queries", () => ({
+ agentListOptions: () => ({ queryKey: ["agents"], queryFn: () => [] }),
+}));
+vi.mock("../../navigation", () => ({
+ useNavigation: () => nav,
+ useBackOrReplace: () => vi.fn(),
+}));
+vi.mock("./use-create-agent-form", () => ({
+ useCreateAgentForm: () => ({
+ draft: { ...EMPTY_AGENT_DRAFT, runtimeId: "rt-1" },
+ setDraft: vi.fn(),
+ runtimes: [],
+ runtimesLoading: false,
+ runtimesSettled: true,
+ usableRuntimes: [],
+ selectedRuntime: null,
+ members: [],
+ currentUserId: "user-1",
+ draftReady: true,
+ }),
+}));
+vi.mock("./use-create-agent-submit", () => ({
+ useCreateAgentSubmit: () => ({
+ creating: false,
+ nameError: null,
+ formError: null,
+ clearNameError: vi.fn(),
+ create: vi.fn(),
+ }),
+}));
+vi.mock("./use-duplicate-draft-seed", () => ({ useDuplicateDraftSeed: () => {} }));
+vi.mock("./use-manual-draft-sync", () => ({
+ useManualDraftSync: () => {},
+ clearManualDraftForOwner: vi.fn(),
+}));
+vi.mock("./agent-configuration-panel", () => ({ AgentConfigurationPanel: () => null }));
+vi.mock("./create-agent-footer", () => ({ CreateAgentFooter: () => null }));
+vi.mock("./create-shell", () => ({
+ AgentCreateShell: ({ children }: { children: ReactNode }) => <>{children}</>,
+ AgentCreateChip: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+function mount() {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const page = () => (
+ <QueryClientProvider client={qc}>
+ <ManualCreateAgentPage />
+ </QueryClientProvider>
+ );
+ const view = renderWithI18n(page());
+ return { refresh: () => view.rerender(page()) };
+}
+
+describe("ManualCreateAgentPage runtime guard", () => {
+ beforeEach(() => {
+ nav.pathname = "/acme/agents/new/manual";
+ nav.searchParams = new URLSearchParams();
+ nav.replace.mockClear();
+ });
+ afterEach(cleanup);
+
+ it("sends a visit without a runtime back to step 1", () => {
+ mount();
+ expect(nav.replace).toHaveBeenCalledWith("/acme/agents/new");
+ });
+
+ it("stays put when a runtime is chosen", () => {
+ nav.searchParams = new URLSearchParams("runtime=rt-1");
+ mount();
+ expect(nav.replace).not.toHaveBeenCalled();
+ });
+
+ // Desktop: creating replaces the tab URL with the done page while this
+ // route is still rendered.
+ it("does not redirect once the location has moved to the done page", () => {
+ nav.searchParams = new URLSearchParams("runtime=rt-1");
+ const view = mount();
+ nav.pathname = "/acme/agents/new/done/agent-1";
+ nav.searchParams = new URLSearchParams();
+ view.refresh();
+ expect(nav.replace).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/agents/create/manual-create-agent-page.tsx b/packages/views/agents/create/manual-create-agent-page.tsx
index 37067ecf0c..629730c769 100644
--- a/packages/views/agents/create/manual-create-agent-page.tsx
+++ b/packages/views/agents/create/manual-create-agent-page.tsx
@@ -1,16 +1,28 @@
"use client";
-import { useState } from "react";
-import { useQuery } from "@tanstack/react-query";
+import { useEffect, useState } from "react";
+import { Loader2, Sparkles } from "lucide-react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { api } from "@multica/core/api";
+import {
+ agentBuilderSessionKeys,
+ toStoredAgentDraft,
+} from "@multica/core/agents";
import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
import { runtimeDisplayLabel } from "@multica/core/runtimes";
+import type { RuntimeDevice } from "@multica/core/types";
import { agentListOptions } from "@multica/core/workspace/queries";
+import { Button } from "@multica/ui/components/ui/button";
+import { cn } from "@multica/ui/lib/utils";
import { useBackOrReplace, useNavigation } from "../../navigation";
import { useT } from "../../i18n";
+import { ProviderLogo } from "../../runtimes/components/provider-logo";
+import { splitRuntimeName } from "../../runtimes/components/runtime-machines";
import { AgentConfigurationPanel } from "./agent-configuration-panel";
import { CreateAgentFooter } from "./create-agent-footer";
import { AgentCreateChip, AgentCreateShell } from "./create-shell";
+import { createPathWithParams } from "./squad-param";
import { useCreateAgentForm } from "./use-create-agent-form";
import { useCreateAgentSubmit } from "./use-create-agent-submit";
import { useDuplicateDraftSeed } from "./use-duplicate-draft-seed";
@@ -20,22 +32,39 @@ import {
} from "./use-manual-draft-sync";
/**
- * Manual agent creation: every field filled in by hand.
+ * Step 2 of agent creation: configure an agent on the runtime chosen in step 1
+ * (`?runtime=`).
*
* `?duplicate=<id>` seeds the same form from an existing agent instead of
* starting empty — the two share one route because after seeding they are the
- * same screen with the same submit path.
+ * same screen with the same submit path. A duplicate skips step 1 and keeps the
+ * inline runtime picker, since its runtime comes from the source agent.
*/
export function ManualCreateAgentPage() {
const { t } = useT("agents");
const wsId = useWorkspaceId();
+ const qc = useQueryClient();
const paths = useWorkspacePaths();
const navigation = useNavigation();
const backOrReplace = useBackOrReplace();
const duplicateId = navigation.searchParams.get("duplicate");
const squadId = navigation.searchParams.get("squad");
+ const runtimeParam = duplicateId ? null : navigation.searchParams.get("runtime");
+ // On desktop the location is the tab's URL, and it moves to the done page
+ // while this route is still mounted. Its missing `?runtime=` is not a
+ // skipped step 1; redirecting on it threw the user back there.
+ const onThisRoute = navigation.pathname === paths.newAgentManual();
+ const needsRuntime = onThisRoute && !duplicateId && !runtimeParam;
+
+ useEffect(() => {
+ if (needsRuntime) {
+ navigation.replace(createPathWithParams(paths.newAgent(), { squad: squadId }));
+ }
+ }, [needsRuntime, navigation, paths, squadId]);
- const form = useCreateAgentForm();
+ const form = useCreateAgentForm({
+ runtimeSeed: { ready: !needsRuntime, runtimeId: runtimeParam ?? "" },
+ });
const { data: agents = [] } = useQuery(agentListOptions(wsId));
const duplicateAgent = duplicateId
? agents.find((agent) => agent.id === duplicateId) ?? null
@@ -76,11 +105,13 @@ export function ManualCreateAgentPage() {
draft: form.draft,
setDraft: form.setDraft,
ready: !duplicateId || duplicateSeeded,
+ runtimeId: runtimeParam,
});
const submit = useCreateAgentSubmit({
draft: form.draft,
runtimeId: form.selectedRuntime?.id ?? null,
+ runtimeProvider: form.selectedRuntime?.provider,
squadId,
duplicateSource: duplicateAgent,
// The work is committed; leaving it stored would hand the finished agent's
@@ -89,9 +120,58 @@ export function ManualCreateAgentPage() {
onCreated: () => clearManualDraftForOwner(duplicateId),
});
+ const changeRuntime = () =>
+ navigation.replace(
+ createPathWithParams(paths.newAgent(), {
+ squad: squadId,
+ runtime: form.draft.runtimeId || runtimeParam,
+ }),
+ );
+
+ // Hands the current draft to a builder conversation on the same runtime.
+ const [startingAi, setStartingAi] = useState(false);
+ const [aiError, setAiError] = useState<string | null>(null);
+ const runtime = form.selectedRuntime;
+ const canAskAi =
+ !!runtime && runtime.runtime_mode !== "cloud" && runtime.status === "online";
+ const askAi = async () => {
+ if (!runtime) return;
+ setStartingAi(true);
+ setAiError(null);
+ try {
+ const session = await api.createAgentBuilderSession({
+ runtime_id: runtime.id,
+ model: form.draft.model.trim() || undefined,
+ });
+ if (!session.session_id) {
+ throw new Error(t(($) => $.creation_studio.builder.start_failed));
+ }
+ await api.saveAgentBuilderDraft(
+ session.session_id,
+ toStoredAgentDraft(form.draft, null, null),
+ );
+ void qc.invalidateQueries({ queryKey: agentBuilderSessionKeys.list(wsId) });
+ navigation.replace(
+ createPathWithParams(paths.newAgentAiSession(session.session_id), {
+ squad: squadId,
+ runtime: runtime.id,
+ }),
+ );
+ } catch (err) {
+ setAiError(
+ err instanceof Error
+ ? err.message
+ : t(($) => $.creation_studio.builder.start_failed),
+ );
+ setStartingAi(false);
+ }
+ };
+
const canCreate =
form.draft.name.trim().length > 0 && form.draftReady && !submit.creating;
+ if (needsRuntime) return null;
+
return (
<AgentCreateShell
title={
@@ -103,23 +183,19 @@ export function ManualCreateAgentPage() {
? t(($) => $.creation_studio.squad_title)
: t(($) => $.creation_studio.title)
}
- step={t(($) => $.creation_studio.step_configure)}
- // A duplicate arrives from the agents list, not from the chooser, so it
- // returns to where it came from instead of offering a method to pick.
+ step={t(($) => $.creation_studio.steps.configure)}
+ stepIndex={duplicateId ? undefined : 2}
+ // A duplicate arrives from the agents list, not from step 1, so it
+ // returns to where it came from instead of offering a runtime to pick.
onBack={() =>
- backOrReplace(duplicateId ? paths.agents() : paths.newAgent())
+ duplicateId ? backOrReplace(paths.agents()) : changeRuntime()
}
chips={
- <>
+ duplicateId && form.selectedRuntime ? (
<AgentCreateChip>
- {t(($) => $.creation_studio.modes.blank.title)}
+ {runtimeDisplayLabel(form.selectedRuntime)}
</AgentCreateChip>
- {form.selectedRuntime && (
- <AgentCreateChip>
- {runtimeDisplayLabel(form.selectedRuntime)}
- </AgentCreateChip>
- )}
- </>
+ ) : undefined
}
>
<div className="min-h-0 flex-1 overflow-y-auto">
@@ -134,6 +210,39 @@ export function ManualCreateAgentPage() {
{t(($) => $.creation_studio.duplicate_runtime_reset_notice)}
</div>
)}
+ {!duplicateId ? (
+ <div className="mb-6 flex flex-wrap items-center justify-between gap-3">
+ <div className="min-w-0">
+ <h2 className="text-title font-semibold tracking-tight">
+ {t(($) => $.creation_studio.configure_title)}
+ </h2>
+ <p className="mt-1 text-body text-muted-foreground">
+ {t(($) => $.creation_studio.configure_description)}
+ </p>
+ </div>
+ {canAskAi ? (
+ <div className="flex flex-col items-end gap-1">
+ <Button
+ variant="outline"
+ disabled={startingAi}
+ onClick={() => void askAi()}
+ >
+ {startingAi ? (
+ <Loader2 aria-hidden="true" className="size-3.5 animate-spin" />
+ ) : (
+ <Sparkles aria-hidden="true" className="size-3.5" />
+ )}
+ {t(($) => $.creation_studio.ask_ai)}
+ </Button>
+ {aiError ? (
+ <p role="alert" className="text-caption text-destructive">
+ {aiError}
+ </p>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ ) : null}
<AgentConfigurationPanel
draft={form.draft}
onChange={form.setDraft}
@@ -146,6 +255,15 @@ export function ManualCreateAgentPage() {
submit.clearNameError();
form.setDraft((current) => ({ ...current, name }));
}}
+ runtimeSummary={
+ duplicateId ? undefined : (
+ <RuntimeSummaryCard
+ runtime={runtime}
+ loading={form.runtimesLoading}
+ onChange={changeRuntime}
+ />
+ )
+ }
/>
</div>
<CreateAgentFooter
@@ -159,3 +277,59 @@ export function ManualCreateAgentPage() {
</AgentCreateShell>
);
}
+
+function RuntimeSummaryCard({
+ runtime,
+ loading,
+ onChange,
+}: {
+ runtime: RuntimeDevice | null;
+ loading: boolean;
+ onChange: () => void;
+}) {
+ const { t } = useT("agents");
+ const online = runtime?.status === "online";
+ const where = !runtime
+ ? ""
+ : runtime.runtime_mode === "cloud"
+ ? t(($) => $.creation_studio.runtime_step.groups.cloud)
+ : splitRuntimeName(runtime.name).hostname ?? runtime.device_info;
+ return (
+ <div>
+ <p className="mb-1.5 text-label font-medium">
+ {t(($) => $.creation_studio.runtime_label)}
+ </p>
+ <div className="flex min-h-10 items-center gap-2.5 rounded-lg border bg-muted/30 px-3 py-2">
+ {runtime ? (
+ <>
+ <ProviderLogo provider={runtime.provider} className="size-4 shrink-0" />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-label font-medium">
+ {runtimeDisplayLabel(runtime)}
+ </span>
+ <span className="flex items-center gap-1.5 truncate text-caption text-muted-foreground">
+ <span
+ aria-hidden="true"
+ className={cn(
+ "size-1.5 shrink-0 rounded-full",
+ online ? "bg-success" : "bg-muted-foreground/40",
+ )}
+ />
+ {where}
+ </span>
+ </span>
+ </>
+ ) : (
+ <span className="flex-1 text-label text-muted-foreground">
+ {loading
+ ? t(($) => $.creation_studio.runtime_loading)
+ : t(($) => $.creation_studio.runtime_missing)}
+ </span>
+ )}
+ <Button variant="ghost" size="sm" onClick={onChange}>
+ {t(($) => $.creation_studio.change_runtime)}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/agents/create/runtime-choice-list.test.tsx b/packages/views/agents/create/runtime-choice-list.test.tsx
new file mode 100644
index 0000000000..5a93ccb4c8
--- /dev/null
+++ b/packages/views/agents/create/runtime-choice-list.test.tsx
@@ -0,0 +1,176 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { I18nProvider } from "@multica/core/i18n/react";
+import type { QoderConnection } from "@multica/core/runtimes/qoder";
+import type { AgentRuntime } from "@multica/core/types";
+import enAgents from "../../locales/en/agents.json";
+import enRuntimes from "../../locales/en/runtimes.json";
+import { buildRuntimeMachines } from "../../runtimes/components/runtime-machines";
+import { buildRuntimeChoiceGroups } from "./runtime-choice";
+import {
+ RuntimeChoiceList,
+ qoderChoiceState,
+ type RuntimeChoiceListProps,
+} from "./runtime-choice-list";
+
+const NOW = Date.now();
+
+function makeRuntime(overrides: Partial<AgentRuntime> = {}): AgentRuntime {
+ return {
+ id: "runtime-1",
+ workspace_id: "ws-1",
+ daemon_id: "daemon-local",
+ name: "Claude (my-mac)",
+ runtime_mode: "local",
+ provider: "claude",
+ launch_header: "",
+ status: "online",
+ device_info: "my-mac",
+ metadata: {},
+ owner_id: "me",
+ visibility: "private",
+ last_seen_at: new Date(NOW - 10_000).toISOString(),
+ created_at: "2026-10-18T11:00:00Z",
+ updated_at: "2026-10-18T11:00:00Z",
+ ...overrides,
+ };
+}
+
+const LOCAL_PROVIDERS = [
+ "claude",
+ "codex",
+ "cursor",
+ "gemini",
+ "kimi",
+ "opencode",
+ "openclaw",
+ "qwen",
+ "kiro",
+];
+
+const runtimes = [
+ ...LOCAL_PROVIDERS.map((provider) =>
+ makeRuntime({ id: `local-${provider}`, provider, name: `${provider} (my-mac)` }),
+ ),
+ makeRuntime({
+ id: "server-claude",
+ daemon_id: "daemon-server",
+ name: "Claude (build-01)",
+ device_info: "build-01",
+ owner_id: "teammate",
+ visibility: "public",
+ }),
+];
+
+const groups = buildRuntimeChoiceGroups(
+ buildRuntimeMachines(runtimes, {
+ now: NOW,
+ localDaemonId: "daemon-local",
+ currentUserId: "me",
+ }),
+ "me",
+);
+
+const unconnectedQoder: QoderConnection = {
+ available: true,
+ configured: false,
+ name: "",
+ baseUrl: "https://api.qoder.com/api/v1/cloud",
+ environmentId: "",
+ hasToken: false,
+ repositories: [],
+ enabled: false,
+ status: "stopped",
+ lastError: "",
+ maxConcurrency: 3,
+ runTimeoutMinutes: 60,
+ activeRuns: 0,
+ queuedRuns: 0,
+};
+
+function mount(overrides: Partial<RuntimeChoiceListProps> = {}) {
+ const props: RuntimeChoiceListProps = {
+ local: groups.local,
+ localAvailable: true,
+ localStarting: false,
+ remotes: groups.remotes,
+ hiddenRemoteCount: 0,
+ cloud: [],
+ qoder: unconnectedQoder,
+ qoderState: qoderChoiceState(unconnectedQoder, false),
+ qoderSelected: false,
+ selectedRuntimeId: null,
+ query: "",
+ currentUserId: "me",
+ canManage: true,
+ ownerName: (id) => (id === "teammate" ? "Bohan" : null),
+ onSelect: vi.fn(),
+ onSelectQoder: vi.fn(),
+ onConnectQoder: vi.fn(),
+ onManageQoder: vi.fn(),
+ onAddRemote: vi.fn(),
+ ...overrides,
+ };
+ render(
+ <I18nProvider
+ locale="en"
+ resources={{ en: { agents: enAgents, runtimes: enRuntimes } }}
+ >
+ <RuntimeChoiceList {...props} />
+ </I18nProvider>,
+ );
+ return props;
+}
+
+afterEach(() => {
+ cleanup();
+});
+
+describe("RuntimeChoiceList", () => {
+ it("opens this machine, folds harnesses past six, and keeps other machines closed", () => {
+ const props = mount();
+
+ expect(screen.getByRole("button", { name: /my-mac/ })).toHaveAttribute(
+ "aria-expanded",
+ "true",
+ );
+ expect(screen.getByRole("button", { name: /^3 more:/ })).toBeInTheDocument();
+ const server = screen.getByRole("button", { name: /build-01/ });
+ expect(server).toHaveAttribute("aria-expanded", "false");
+
+ fireEvent.click(screen.getByRole("button", { name: /^3 more:/ }));
+ expect(screen.queryByRole("button", { name: /^3 more:/ })).not.toBeInTheDocument();
+
+ fireEvent.click(server);
+ expect(server).toHaveAttribute("aria-expanded", "true");
+ fireEvent.click(screen.getByRole("button", { name: "Claude" }));
+ expect(props.onSelect).toHaveBeenCalledWith("server-claude");
+ });
+
+ it("opens the machine holding the selection and warns about a teammate's account", () => {
+ mount({ selectedRuntimeId: "server-claude" });
+
+ expect(screen.getByRole("button", { name: /build-01/ })).toHaveAttribute(
+ "aria-expanded",
+ "true",
+ );
+ expect(screen.getByText(/Tasks run on Bohan's machine/)).toBeInTheDocument();
+ });
+
+ it("lets an admin connect Qoder in place, and tells a member to ask an admin", () => {
+ const props = mount();
+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));
+ expect(props.onConnectQoder).toHaveBeenCalledTimes(1);
+ expect(screen.queryByRole("button", { name: /Qoder Cloud Agent/ })).toBeNull();
+
+ cleanup();
+ mount({ canManage: false });
+ expect(screen.queryByRole("button", { name: "Connect" })).toBeNull();
+ expect(screen.getByText("Ask an admin to connect")).toBeInTheDocument();
+ });
+
+ it("says so when nothing matches the search", () => {
+ mount({ query: "zzz" });
+ expect(screen.getByText("Nothing matches “zzz”")).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/agents/create/runtime-choice-list.tsx b/packages/views/agents/create/runtime-choice-list.tsx
new file mode 100644
index 0000000000..ea0c76eb38
--- /dev/null
+++ b/packages/views/agents/create/runtime-choice-list.tsx
@@ -0,0 +1,736 @@
+"use client";
+
+import { useState, type ReactNode } from "react";
+import {
+ ChevronDown,
+ ChevronRight,
+ Cloud,
+ Download,
+ Laptop,
+ Loader2,
+ Lock,
+ Monitor,
+ Plus,
+ SquareTerminal,
+ TriangleAlert,
+} from "lucide-react";
+import type { QoderConnection } from "@multica/core/runtimes/qoder";
+import { Button, buttonVariants } from "@multica/ui/components/ui/button";
+import { cn } from "@multica/ui/lib/utils";
+import { useT } from "../../i18n";
+import { ProviderLogo } from "../../runtimes/components/provider-logo";
+import { HealthDot, useHealthLabel } from "../../runtimes/components/shared";
+import {
+ filterDevice,
+ harnessMatches,
+ HARNESS_PREVIEW_COUNT,
+ LOGO_STACK_LIMIT,
+ previewOptions,
+ type DeviceOption,
+ type HarnessOption,
+} from "./runtime-choice";
+
+export type QoderChoiceState =
+ | "not_configured"
+ | "starting"
+ | "ready"
+ | "error"
+ | "stopped";
+
+export function qoderChoiceState(
+ connection: QoderConnection,
+ runtimeOnline: boolean,
+): QoderChoiceState {
+ if (!connection.configured) return "not_configured";
+ if (!connection.enabled) return "stopped";
+ if (connection.status === "error") return "error";
+ return runtimeOnline && connection.status === "online" ? "ready" : "starting";
+}
+
+const QODER_NAME = "Qoder Cloud Agent";
+
+const COMING_SOON = [
+ { provider: "cursor", name: "Cursor Cloud Agents", vendor: "Cursor" },
+ { provider: "claude", name: "Claude Managed Agents", vendor: "Anthropic" },
+];
+
+const ROW = "flex w-full min-w-0 items-center gap-3 px-4 text-left";
+const INTERACTIVE =
+ "transition-colors hover:bg-accent/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring";
+const SELECTED = "bg-brand/5 shadow-[inset_2px_0_0_var(--brand)] hover:bg-brand/5";
+/** Lines child rows up under their machine's tile, past the chevron. */
+const CHILD_INDENT = "pl-11";
+
+function Highlight({ text, query }: { text: string; query: string }) {
+ const q = query.trim().toLowerCase();
+ const index = q ? text.toLowerCase().indexOf(q) : -1;
+ if (index < 0) return <>{text}</>;
+ return (
+ <>
+ {text.slice(0, index)}
+ <mark className="rounded-xs bg-warning/25 text-inherit">
+ {text.slice(index, index + q.length)}
+ </mark>
+ {text.slice(index + q.length)}
+ </>
+ );
+}
+
+function Radio({ checked, disabled }: { checked: boolean; disabled?: boolean }) {
+ return (
+ <span
+ aria-hidden="true"
+ className={cn(
+ "flex size-4 shrink-0 items-center justify-center rounded-full border-[1.5px] border-input",
+ checked && "border-brand",
+ disabled && "opacity-50",
+ )}
+ >
+ {checked ? <span className="size-2 rounded-full bg-brand" /> : null}
+ </span>
+ );
+}
+
+function Tile({ children, dot }: { children: ReactNode; dot?: ReactNode }) {
+ return (
+ <span className="relative flex size-7 shrink-0 items-center justify-center rounded-md border bg-background">
+ {children}
+ {dot}
+ </span>
+ );
+}
+
+const TILE_DOT = "absolute -bottom-0.5 -right-0.5 ring-2 ring-card";
+
+function GroupHeader({
+ icon: Icon,
+ title,
+ count,
+}: {
+ icon: typeof Monitor;
+ title: string;
+ count: number;
+}) {
+ return (
+ <div className="flex h-9 items-center gap-2 bg-muted/40 px-4 text-caption">
+ <Icon aria-hidden="true" className="size-3.5 text-muted-foreground" />
+ <h3 className="font-semibold">{title}</h3>
+ <span className="font-mono tabular-nums text-muted-foreground">{count}</span>
+ </div>
+ );
+}
+
+function Badge({
+ tone = "muted",
+ children,
+}: {
+ tone?: "muted" | "success" | "warning" | "destructive";
+ children: ReactNode;
+}) {
+ return (
+ <span
+ className={cn(
+ "inline-flex shrink-0 items-center gap-1 rounded-xs px-1.5 py-0.5 text-micro font-medium",
+ tone === "muted" && "bg-muted text-muted-foreground",
+ tone === "success" && "bg-success/10 text-success",
+ tone === "warning" && "bg-warning/10 text-warning",
+ tone === "destructive" && "bg-destructive/10 text-destructive",
+ )}
+ >
+ {children}
+ </span>
+ );
+}
+
+function HarnessRow({
+ option,
+ query,
+ selected,
+ indent,
+ onSelect,
+}: {
+ option: HarnessOption;
+ query: string;
+ selected: boolean;
+ indent: boolean;
+ onSelect: () => void;
+}) {
+ const { t } = useT("agents");
+ const online = option.runtime.status === "online";
+ return (
+ <button
+ type="button"
+ aria-pressed={selected}
+ disabled={!online}
+ onClick={onSelect}
+ className={cn(
+ ROW,
+ INTERACTIVE,
+ "min-h-11",
+ indent && CHILD_INDENT,
+ "disabled:cursor-not-allowed disabled:text-muted-foreground disabled:hover:bg-transparent",
+ selected && SELECTED,
+ )}
+ >
+ <Radio checked={selected} disabled={!online} />
+ <Tile>
+ <ProviderLogo
+ provider={option.runtime.provider}
+ className={cn("size-4", !online && "opacity-50")}
+ />
+ </Tile>
+ <span className={cn("min-w-0 truncate text-body", selected && "font-medium")}>
+ <Highlight text={option.label} query={query} />
+ </span>
+ {option.custom ? (
+ <Badge>{t(($) => $.creation_studio.runtime_step.custom_badge)}</Badge>
+ ) : null}
+ {option.version ? (
+ <span className="shrink-0 font-mono text-caption text-faint-foreground">
+ {option.version}
+ </span>
+ ) : null}
+ </button>
+ );
+}
+
+function LogoStack({ options }: { options: HarnessOption[] }) {
+ const shown = options.slice(0, LOGO_STACK_LIMIT);
+ const extra = options.length - shown.length;
+ return (
+ <span aria-hidden="true" className="hidden items-center pr-1 sm:flex">
+ {shown.map((option) => (
+ <span
+ key={option.runtime.id}
+ className="-mr-1 flex size-5 items-center justify-center rounded-sm bg-background ring-1 ring-border"
+ >
+ <ProviderLogo provider={option.runtime.provider} className="size-3" />
+ </span>
+ ))}
+ {extra > 0 ? (
+ <span className="ml-2 font-mono text-micro text-muted-foreground">+{extra}</span>
+ ) : null}
+ </span>
+ );
+}
+
+function MachineBlock({
+ device,
+ open,
+ onToggle,
+ showAll,
+ onShowAll,
+ starting,
+ query,
+ owner,
+ selectedRuntimeId,
+ selectedNotice,
+ onSelect,
+}: {
+ device: DeviceOption;
+ open: boolean;
+ onToggle: () => void;
+ showAll: boolean;
+ onShowAll: () => void;
+ starting: boolean;
+ query: string;
+ owner: string | null;
+ selectedRuntimeId: string | null;
+ selectedNotice: string | null;
+ onSelect: (runtimeId: string) => void;
+}) {
+ const { t } = useT("agents");
+ const healthLabel = useHealthLabel();
+ const { machine, harnesses } = device;
+ const searching = query.trim().length > 0;
+ const offline = machine.health !== "online";
+ const Icon = machine.isCurrent ? Laptop : Monitor;
+ const subtitle = [owner, machine.deviceSummary].filter(Boolean).join(" · ");
+ const { shown, hiddenCount } =
+ searching || showAll
+ ? { shown: harnesses, hiddenCount: 0 }
+ : previewOptions(harnesses, selectedRuntimeId, HARNESS_PREVIEW_COUNT);
+ const hiddenNames = harnesses
+ .filter((option) => !shown.includes(option))
+ .map((option) => option.label)
+ .join(", ");
+
+ return (
+ <>
+ <button
+ type="button"
+ aria-expanded={open}
+ onClick={onToggle}
+ className={cn(ROW, INTERACTIVE, "min-h-11", open && "bg-muted/20")}
+ >
+ <ChevronRight
+ aria-hidden="true"
+ className={cn(
+ "size-3.5 shrink-0 text-muted-foreground transition-transform",
+ open && "rotate-90",
+ )}
+ />
+ <Tile dot={<HealthDot health={machine.health} className={TILE_DOT} />}>
+ <Icon aria-hidden="true" className="size-3.5 text-muted-foreground" />
+ </Tile>
+ <span
+ className={cn(
+ "max-w-64 shrink-0 truncate text-body font-medium",
+ offline && "text-muted-foreground",
+ )}
+ >
+ <Highlight text={machine.title} query={query} />
+ </span>
+ {machine.isCurrent ? (
+ <Badge>{t(($) => $.creation_studio.runtime_step.this_machine)}</Badge>
+ ) : subtitle ? (
+ <span className="min-w-0 truncate text-caption text-muted-foreground">
+ {subtitle}
+ </span>
+ ) : null}
+ <span className="ml-auto flex shrink-0 items-center gap-4 text-caption text-muted-foreground">
+ {!open && harnesses.length > 0 ? <LogoStack options={harnesses} /> : null}
+ <span className="hidden tabular-nums sm:inline">
+ {t(($) => $.creation_studio.runtime_step.harness_count, {
+ count: harnesses.length,
+ })}
+ </span>
+ <span className="flex min-w-12 items-center justify-end gap-1.5 whitespace-nowrap">
+ <HealthDot health={machine.health} />
+ {healthLabel(machine.health)}
+ </span>
+ </span>
+ </button>
+ {open && harnesses.length === 0 ? (
+ <div className={cn(ROW, CHILD_INDENT, "gap-2.5 py-3")}>
+ {starting ? (
+ <Loader2
+ aria-hidden="true"
+ className="size-4 shrink-0 animate-spin text-muted-foreground"
+ />
+ ) : (
+ <SquareTerminal
+ aria-hidden="true"
+ className="size-4 shrink-0 text-muted-foreground"
+ />
+ )}
+ <span className="min-w-0">
+ <span className="block text-label font-medium">
+ {starting
+ ? t(($) => $.creation_studio.runtime_step.local_starting)
+ : t(($) => $.creation_studio.runtime_step.local_empty_title)}
+ </span>
+ <span className="block text-caption text-muted-foreground">
+ {t(($) => $.creation_studio.runtime_step.local_empty_hint)}
+ </span>
+ </span>
+ </div>
+ ) : null}
+ {open
+ ? shown.map((option) => {
+ const selected = option.runtime.id === selectedRuntimeId;
+ return (
+ <div key={option.runtime.id}>
+ <HarnessRow
+ option={option}
+ query={query}
+ selected={selected}
+ indent
+ onSelect={() => onSelect(option.runtime.id)}
+ />
+ {selected && selectedNotice ? (
+ <p
+ className={cn(
+ ROW,
+ CHILD_INDENT,
+ SELECTED,
+ "items-start gap-2 pb-2.5 text-caption text-muted-foreground",
+ )}
+ >
+ <TriangleAlert
+ aria-hidden="true"
+ className="mt-0.5 size-3.5 shrink-0 text-warning"
+ />
+ {selectedNotice}
+ </p>
+ ) : null}
+ </div>
+ );
+ })
+ : null}
+ {open && hiddenCount > 0 ? (
+ <button
+ type="button"
+ onClick={onShowAll}
+ className={cn(
+ ROW,
+ INTERACTIVE,
+ CHILD_INDENT,
+ "h-9 gap-1.5 text-caption text-muted-foreground hover:text-foreground",
+ )}
+ >
+ <ChevronDown aria-hidden="true" className="size-3.5 shrink-0" />
+ <span className="truncate">
+ {t(($) => $.creation_studio.runtime_step.more_harnesses, {
+ count: hiddenCount,
+ names: hiddenNames,
+ })}
+ </span>
+ </button>
+ ) : null}
+ </>
+ );
+}
+
+function QoderRow({
+ connection,
+ state,
+ selected,
+ canManage,
+ query,
+ onSelect,
+ onConnect,
+ onManage,
+}: {
+ connection: QoderConnection;
+ state: QoderChoiceState;
+ selected: boolean;
+ canManage: boolean;
+ query: string;
+ onSelect: () => void;
+ onConnect: () => void;
+ onManage: () => void;
+}) {
+ const { t } = useT("agents");
+ const ready = state === "ready";
+ const dot = {
+ ready: "bg-success",
+ starting: "bg-warning",
+ not_configured: "bg-warning",
+ error: "bg-destructive",
+ stopped: "bg-muted-foreground/40",
+ }[state];
+ const errorText = state === "error" ? connection.lastError : null;
+ const status = (
+ <Badge
+ tone={
+ ready
+ ? "success"
+ : state === "error"
+ ? "destructive"
+ : state === "stopped"
+ ? "muted"
+ : "warning"
+ }
+ >
+ {state === "starting" ? (
+ <Loader2 aria-hidden="true" className="size-3 animate-spin" />
+ ) : null}
+ {t(($) => $.creation_studio.runtime_step.qoder_status[state])}
+ </Badge>
+ );
+
+ let trailing: ReactNode = status;
+ if (state === "not_configured" || state === "error" || state === "stopped") {
+ const unconfigured = state === "not_configured";
+ trailing = canManage ? (
+ <>
+ {unconfigured ? null : status}
+ <Button size="sm" variant="outline" onClick={unconfigured ? onConnect : onManage}>
+ {unconfigured
+ ? t(($) => $.creation_studio.runtime_step.connect)
+ : t(($) => $.creation_studio.runtime_step.settings)}
+ </Button>
+ </>
+ ) : (
+ <>
+ {status}
+ <span className="text-caption text-muted-foreground">
+ {unconfigured
+ ? t(($) => $.creation_studio.runtime_step.member_connect)
+ : t(($) => $.creation_studio.runtime_step.member_fix)}
+ </span>
+ </>
+ );
+ }
+
+ const body = (
+ <>
+ <Radio checked={selected} disabled={!ready} />
+ <Tile dot={<span className={cn("size-2 rounded-full", TILE_DOT, dot)} />}>
+ <ProviderLogo provider="qoder_cloud" className="size-4" />
+ </Tile>
+ <span className="min-w-0 flex-1">
+ <span className={cn("block truncate text-body", selected && "font-medium")}>
+ <Highlight text={QODER_NAME} query={query} />
+ </span>
+ <span
+ className={cn(
+ "block truncate text-caption",
+ errorText ? "text-destructive" : "text-muted-foreground",
+ )}
+ >
+ {errorText ||
+ t(($) => $.creation_studio.runtime_step.hosted_by, { vendor: "Qoder" })}
+ </span>
+ </span>
+ </>
+ );
+
+ if (ready) {
+ return (
+ <button
+ type="button"
+ aria-pressed={selected}
+ onClick={onSelect}
+ className={cn(ROW, INTERACTIVE, "min-h-13 py-2", selected && SELECTED)}
+ >
+ {body}
+ {trailing}
+ </button>
+ );
+ }
+ return (
+ <div className={cn(ROW, "min-h-13 py-2")}>
+ {body}
+ <span className="flex shrink-0 items-center gap-2">{trailing}</span>
+ </div>
+ );
+}
+
+export interface RuntimeChoiceListProps {
+ local: DeviceOption | null;
+ /** False on web, where no harness can run on the device in use. */
+ localAvailable: boolean;
+ localStarting: boolean;
+ remotes: DeviceOption[];
+ hiddenRemoteCount: number;
+ cloud: HarnessOption[];
+ qoder: QoderConnection | null;
+ qoderState: QoderChoiceState | null;
+ qoderSelected: boolean;
+ selectedRuntimeId: string | null;
+ query: string;
+ currentUserId: string | null;
+ canManage: boolean;
+ ownerName: (ownerId: string | null) => string | null;
+ onSelect: (runtimeId: string) => void;
+ onSelectQoder: () => void;
+ onConnectQoder: () => void;
+ onManageQoder: () => void;
+ onAddRemote: () => void;
+}
+
+/**
+ * Every place an agent can run, as one list: machines (this one first, open)
+ * and cloud services. A machine folds to a single row until opened.
+ */
+export function RuntimeChoiceList({
+ local,
+ localAvailable,
+ localStarting,
+ remotes,
+ hiddenRemoteCount,
+ cloud,
+ qoder,
+ qoderState,
+ qoderSelected,
+ selectedRuntimeId,
+ query,
+ currentUserId,
+ canManage,
+ ownerName,
+ onSelect,
+ onSelectQoder,
+ onConnectQoder,
+ onManageQoder,
+ onAddRemote,
+}: RuntimeChoiceListProps) {
+ const { t } = useT("agents");
+ const [openOverrides, setOpenOverrides] = useState<ReadonlyMap<string, boolean>>(
+ () => new Map(),
+ );
+ const [showAllIds, setShowAllIds] = useState<ReadonlySet<string>>(() => new Set());
+ const searching = query.trim().length > 0;
+ const q = query.trim().toLowerCase();
+
+ const devices = [...(local ? [local] : []), ...remotes];
+ const matchedDevices = searching
+ ? devices
+ .map((device) => filterDevice(device, query))
+ .filter((device): device is DeviceOption => device !== null)
+ : devices;
+ const showWebRow = !localAvailable && !searching;
+
+ const showQoder = !!qoder && !!qoderState && (!q || QODER_NAME.toLowerCase().includes(q));
+ const matchedCloud = cloud.filter((option) => harnessMatches(option, "", query));
+ const soon = COMING_SOON.filter((item) => !q || item.name.toLowerCase().includes(q));
+
+ const showMachines = matchedDevices.length > 0 || showWebRow || !searching;
+ const showCloud = showQoder || matchedCloud.length > 0 || soon.length > 0;
+
+ if (!showMachines && !showCloud) {
+ return (
+ <div className="rounded-lg border border-dashed px-4 py-6 text-center text-label text-muted-foreground">
+ {t(($) => $.creation_studio.runtime_step.no_match, { query })}
+ </div>
+ );
+ }
+
+ const isOpen = (device: DeviceOption) =>
+ searching ||
+ (openOverrides.get(device.machine.id) ??
+ (device.machine.isCurrent ||
+ device.harnesses.some((option) => option.runtime.id === selectedRuntimeId)));
+
+ const noticeFor = (device: DeviceOption) => {
+ if (device.machine.isCurrent) return null;
+ const selected = device.harnesses.find(
+ (option) => option.runtime.id === selectedRuntimeId,
+ );
+ const ownerId = selected?.runtime.owner_id ?? null;
+ if (!selected || !ownerId || ownerId === currentUserId) return null;
+ const owner = ownerName(ownerId);
+ return owner
+ ? t(($) => $.creation_studio.runtime_step.remote_warning, { owner })
+ : null;
+ };
+
+ return (
+ <div className="divide-y overflow-hidden rounded-lg border bg-card">
+ {showMachines ? (
+ <>
+ <GroupHeader
+ icon={Monitor}
+ title={t(($) => $.creation_studio.runtime_step.groups.machines)}
+ count={matchedDevices.length}
+ />
+ {showWebRow ? (
+ <div className={cn(ROW, "min-h-12 py-2")}>
+ <Tile>
+ <Laptop aria-hidden="true" className="size-3.5 text-muted-foreground" />
+ </Tile>
+ <span className="min-w-0 flex-1 text-label text-muted-foreground">
+ {t(($) => $.creation_studio.runtime_step.web_local_title)}
+ </span>
+ <a
+ href="/download"
+ target="_blank"
+ rel="noreferrer"
+ className={buttonVariants({ size: "sm", variant: "outline" })}
+ >
+ <Download aria-hidden="true" className="size-3.5" />
+ {t(($) => $.creation_studio.runtime_step.download_desktop)}
+ </a>
+ </div>
+ ) : null}
+ {matchedDevices.map((device) => {
+ const id = device.machine.id;
+ const ownerId = device.harnesses[0]?.runtime.owner_id ?? null;
+ const owner = device.machine.isCurrent
+ ? null
+ : ownerId && ownerId === currentUserId
+ ? t(($) => $.creation_studio.runtime_step.owner_you)
+ : ownerName(ownerId);
+ return (
+ <MachineBlock
+ key={id}
+ device={device}
+ open={isOpen(device)}
+ onToggle={() =>
+ setOpenOverrides((current) =>
+ new Map(current).set(id, !isOpen(device)),
+ )
+ }
+ showAll={showAllIds.has(id)}
+ onShowAll={() => setShowAllIds((current) => new Set(current).add(id))}
+ starting={device.machine.isCurrent && localStarting}
+ query={query}
+ owner={owner}
+ selectedRuntimeId={selectedRuntimeId}
+ selectedNotice={noticeFor(device)}
+ onSelect={onSelect}
+ />
+ );
+ })}
+ {!searching ? (
+ <div className={cn(ROW, "h-10 text-caption text-muted-foreground")}>
+ {hiddenRemoteCount > 0 ? (
+ <span className="flex min-w-0 items-center gap-1.5">
+ <Lock aria-hidden="true" className="size-3 shrink-0" />
+ <span className="truncate">
+ {t(($) => $.creation_studio.runtime_step.hidden_remote, {
+ count: hiddenRemoteCount,
+ })}
+ </span>
+ </span>
+ ) : null}
+ <button
+ type="button"
+ onClick={onAddRemote}
+ className="ml-auto inline-flex shrink-0 items-center gap-1 rounded-sm font-medium text-brand hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <Plus aria-hidden="true" className="size-3.5" />
+ {t(($) => $.creation_studio.runtime_step.add_remote)}
+ </button>
+ </div>
+ ) : null}
+ </>
+ ) : null}
+ {showCloud ? (
+ <>
+ <GroupHeader
+ icon={Cloud}
+ title={t(($) => $.creation_studio.runtime_step.groups.cloud)}
+ count={(showQoder ? 1 : 0) + matchedCloud.length}
+ />
+ {showQoder && qoder && qoderState ? (
+ <QoderRow
+ connection={qoder}
+ state={qoderState}
+ selected={qoderSelected}
+ canManage={canManage}
+ query={query}
+ onSelect={onSelectQoder}
+ onConnect={onConnectQoder}
+ onManage={onManageQoder}
+ />
+ ) : null}
+ {matchedCloud.map((option) => (
+ <HarnessRow
+ key={option.runtime.id}
+ option={option}
+ query={query}
+ selected={option.runtime.id === selectedRuntimeId}
+ indent={false}
+ onSelect={() => onSelect(option.runtime.id)}
+ />
+ ))}
+ {soon.map((item) => (
+ <div
+ key={item.provider}
+ aria-disabled="true"
+ className={cn(ROW, "min-h-13 py-2 text-muted-foreground")}
+ >
+ <Radio checked={false} disabled />
+ <Tile>
+ <ProviderLogo provider={item.provider} className="size-4 opacity-50 grayscale" />
+ </Tile>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-body">
+ <Highlight text={item.name} query={query} />
+ </span>
+ <span className="block truncate text-caption text-faint-foreground">
+ {t(($) => $.creation_studio.runtime_step.hosted_by, {
+ vendor: item.vendor,
+ })}
+ </span>
+ </span>
+ <Badge>{t(($) => $.creation_studio.runtime_step.coming_soon)}</Badge>
+ </div>
+ ))}
+ </>
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/views/agents/create/runtime-choice.test.ts b/packages/views/agents/create/runtime-choice.test.ts
new file mode 100644
index 0000000000..59ec9d0a73
--- /dev/null
+++ b/packages/views/agents/create/runtime-choice.test.ts
@@ -0,0 +1,148 @@
+// @vitest-environment node
+
+import { describe, expect, it } from "vitest";
+import type { AgentRuntime } from "@multica/core/types";
+import { buildRuntimeMachines } from "../../runtimes/components/runtime-machines";
+import {
+ buildRuntimeChoiceGroups,
+ filterDevice,
+ harnessOption,
+ previewOptions,
+ shortVersion,
+} from "./runtime-choice";
+
+const NOW = new Date("2026-10-18T12:00:00Z").getTime();
+
+function makeRuntime(overrides: Partial<AgentRuntime> = {}): AgentRuntime {
+ return {
+ id: "runtime-1",
+ workspace_id: "ws-1",
+ daemon_id: "daemon-local",
+ name: "Claude (my-mac)",
+ runtime_mode: "local",
+ provider: "claude",
+ launch_header: "",
+ status: "online",
+ device_info: "my-mac",
+ metadata: {},
+ owner_id: "me",
+ visibility: "private",
+ last_seen_at: new Date(NOW - 10_000).toISOString(),
+ created_at: "2026-10-18T11:00:00Z",
+ updated_at: "2026-10-18T11:00:00Z",
+ ...overrides,
+ };
+}
+
+function groups(runtimes: AgentRuntime[]) {
+ const machines = buildRuntimeMachines(runtimes, {
+ now: NOW,
+ localDaemonId: "daemon-local",
+ currentUserId: "me",
+ });
+ return buildRuntimeChoiceGroups(machines, "me");
+}
+
+describe("buildRuntimeChoiceGroups", () => {
+ it("splits runtimes into this device, remote devices and cloud", () => {
+ const result = groups([
+ makeRuntime({ id: "local-codex", provider: "codex", name: "Codex (my-mac)" }),
+ makeRuntime({ id: "local-claude" }),
+ makeRuntime({
+ id: "server-claude",
+ daemon_id: "daemon-server",
+ name: "Claude (build-01)",
+ owner_id: "teammate",
+ visibility: "public",
+ }),
+ makeRuntime({
+ id: "qoder",
+ daemon_id: null,
+ name: "Qoder Cloud Agent",
+ runtime_mode: "cloud",
+ provider: "qoder_cloud",
+ owner_id: "admin",
+ visibility: "public",
+ }),
+ ]);
+
+ expect(result.local?.harnesses.map((h) => h.runtime.id)).toEqual([
+ "local-claude",
+ "local-codex",
+ ]);
+ expect(result.remotes.map((d) => d.harnesses[0]?.runtime.id)).toEqual([
+ "server-claude",
+ ]);
+ expect(result.qoderRuntime?.id).toBe("qoder");
+ expect(result.cloud).toEqual([]);
+ });
+
+ it("counts remote devices with nothing this member may use instead of listing them", () => {
+ const result = groups([
+ makeRuntime({
+ id: "private-elsewhere",
+ daemon_id: "daemon-other",
+ name: "Claude (their-mac)",
+ owner_id: "teammate",
+ visibility: "private",
+ }),
+ ]);
+ expect(result.remotes).toEqual([]);
+ expect(result.hiddenRemoteCount).toBe(1);
+ });
+
+ it("prefers the online Qoder runtime over a stale one", () => {
+ const cloud = {
+ runtime_mode: "cloud" as const,
+ provider: "qoder_cloud",
+ owner_id: "admin",
+ visibility: "public" as const,
+ };
+ const result = groups([
+ makeRuntime({ ...cloud, id: "qoder-old", daemon_id: "qoder", status: "offline" }),
+ makeRuntime({ ...cloud, id: "qoder-new", daemon_id: "qoder" }),
+ ]);
+ expect(result.qoderRuntime?.id).toBe("qoder-new");
+ });
+});
+
+describe("harness helpers", () => {
+ const options = Array.from({ length: 10 }, (_, index) =>
+ harnessOption(
+ makeRuntime({ id: `rt-${index}`, name: `Harness ${index} (my-mac)` }),
+ "my-mac",
+ ),
+ );
+
+ it("keeps the selected harness visible in a collapsed preview", () => {
+ const { shown, hiddenCount } = previewOptions(options, "rt-9", 7);
+ expect(shown).toHaveLength(7);
+ expect(shown.at(-1)?.runtime.id).toBe("rt-9");
+ expect(hiddenCount).toBe(3);
+ });
+
+ it("reduces CLI version output to the version number", () => {
+ expect(shortVersion("codex-cli 0.161.0")).toBe("0.161.0");
+ expect(shortVersion("kimi, version 1.37.0")).toBe("1.37.0");
+ expect(shortVersion("2.1.300 (Claude Code)")).toBe("2.1.300");
+ expect(shortVersion("grok 1.0.52 (0920c8169e27)")).toBe("1.0.52");
+ expect(shortVersion("2026.10.19-6bbf2c4")).toBe("2026.10.19-6bbf2c4");
+ expect(shortVersion("0.1.0-rc.6")).toBe("0.1.0-rc.6");
+ expect(shortVersion("nightly")).toBe("nightly");
+ });
+
+ it("shows a single leftover harness instead of folding it", () => {
+ const { shown, hiddenCount } = previewOptions(options.slice(0, 7), null, 6);
+ expect(shown).toHaveLength(7);
+ expect(hiddenCount).toBe(0);
+ });
+
+ it("matches a device by its name or by any of its harnesses", () => {
+ const device = {
+ machine: buildRuntimeMachines([options[0]!.runtime], { now: NOW })[0]!,
+ harnesses: options.slice(0, 3),
+ };
+ expect(filterDevice(device, "harness 2")?.harnesses).toHaveLength(1);
+ expect(filterDevice(device, "nothing-like-this")).toBeNull();
+ });
+});
diff --git a/packages/views/agents/create/runtime-choice.ts b/packages/views/agents/create/runtime-choice.ts
new file mode 100644
index 0000000000..9ceb7c5c80
--- /dev/null
+++ b/packages/views/agents/create/runtime-choice.ts
@@ -0,0 +1,168 @@
+import {
+ isRuntimeUsableForUser,
+ providerDisplayName,
+} from "@multica/core/runtimes";
+import type { RuntimeDevice } from "@multica/core/types";
+import {
+ runtimeRowLabel,
+ type RuntimeMachine,
+} from "../../runtimes/components/runtime-machines";
+
+export const QODER_PROVIDER = "qoder_cloud";
+
+/** Harness rows shown under an open machine before the rest fold into one row. */
+export const HARNESS_PREVIEW_COUNT = 6;
+/** Provider logos on a closed machine row before "+N". */
+export const LOGO_STACK_LIMIT = 4;
+
+export interface HarnessOption {
+ runtime: RuntimeDevice;
+ label: string;
+ version: string | null;
+ custom: boolean;
+}
+
+export interface DeviceOption {
+ machine: RuntimeMachine;
+ harnesses: HarnessOption[];
+}
+
+export interface RuntimeChoiceGroups {
+ /** This device, or null when the client cannot run harnesses (web). */
+ local: DeviceOption | null;
+ remotes: DeviceOption[];
+ /** Remote devices with no harness this member may use. */
+ hiddenRemoteCount: number;
+ /** Managed cloud runtimes other than Qoder, which has its own tile. */
+ cloud: HarnessOption[];
+ qoderRuntime: RuntimeDevice | null;
+}
+
+/**
+ * The version number out of a CLI's `--version` output, which comes in many
+ * shapes ("codex-cli 0.161.0", "kimi, version 1.37.0", "2.1.300 (Claude Code)").
+ */
+export function shortVersion(raw: string): string {
+ return raw.match(/\d+(?:\.\d+)+(?:-[\w.]+)?/)?.[0] ?? raw;
+}
+
+export function harnessOption(
+ runtime: RuntimeDevice,
+ machineTitle: string,
+): HarnessOption {
+ const version =
+ typeof runtime.metadata?.version === "string" && runtime.metadata.version
+ ? shortVersion(runtime.metadata.version)
+ : null;
+ return {
+ runtime,
+ label:
+ runtime.runtime_mode === "cloud"
+ ? providerDisplayName(runtime.provider)
+ : runtimeRowLabel(runtime, machineTitle),
+ version,
+ custom: !!runtime.profile_id,
+ };
+}
+
+function byLabel(a: HarnessOption, b: HarnessOption): number {
+ return a.label.localeCompare(b.label);
+}
+
+export function buildRuntimeChoiceGroups(
+ machines: RuntimeMachine[],
+ currentUserId: string | null,
+): RuntimeChoiceGroups {
+ let local: DeviceOption | null = null;
+ const remotes: DeviceOption[] = [];
+ let hiddenRemoteCount = 0;
+ const cloud: HarnessOption[] = [];
+ let qoderRuntime: RuntimeDevice | null = null;
+
+ for (const machine of machines) {
+ const usable = machine.runtimes.filter((runtime) =>
+ isRuntimeUsableForUser(runtime, currentUserId),
+ );
+ if (machine.section === "local") {
+ local = {
+ machine,
+ harnesses: usable
+ .map((runtime) => harnessOption(runtime, machine.title))
+ .sort(byLabel),
+ };
+ continue;
+ }
+ if (machine.section === "cloud") {
+ for (const runtime of usable) {
+ if (runtime.provider === QODER_PROVIDER) {
+ if (!qoderRuntime || runtime.status === "online") qoderRuntime = runtime;
+ continue;
+ }
+ cloud.push(harnessOption(runtime, machine.title));
+ }
+ continue;
+ }
+ if (usable.length === 0) {
+ hiddenRemoteCount += 1;
+ continue;
+ }
+ remotes.push({
+ machine,
+ harnesses: usable
+ .map((runtime) => harnessOption(runtime, machine.title))
+ .sort(byLabel),
+ });
+ }
+
+ return { local, remotes, hiddenRemoteCount, cloud: cloud.sort(byLabel), qoderRuntime };
+}
+
+export function normalizeQuery(query: string): string {
+ return query.trim().toLowerCase();
+}
+
+/** A harness matches by its own name or provider, or by its device's name. */
+export function harnessMatches(
+ option: HarnessOption,
+ deviceTitle: string,
+ query: string,
+): boolean {
+ const q = normalizeQuery(query);
+ if (!q) return true;
+ return [option.label, option.runtime.provider, providerDisplayName(option.runtime.provider), deviceTitle]
+ .join(" ")
+ .toLowerCase()
+ .includes(q);
+}
+
+export function filterDevice(
+ device: DeviceOption,
+ query: string,
+): DeviceOption | null {
+ const harnesses = device.harnesses.filter((option) =>
+ harnessMatches(option, device.machine.title, query),
+ );
+ return harnesses.length > 0 ? { ...device, harnesses } : null;
+}
+
+/**
+ * The first `limit` options, with the selected one swapped into the last slot
+ * when it would otherwise be hidden — a collapsed list must never hide what is
+ * selected. A single leftover is shown rather than folded, since the fold row
+ * would take the same space.
+ */
+export function previewOptions(
+ options: HarnessOption[],
+ selectedRuntimeId: string | null,
+ limit: number,
+): { shown: HarnessOption[]; hiddenCount: number } {
+ if (options.length <= limit + 1) return { shown: options, hiddenCount: 0 };
+ const shown = options.slice(0, limit);
+ const selected = selectedRuntimeId
+ ? options.find((option) => option.runtime.id === selectedRuntimeId)
+ : undefined;
+ if (selected && !shown.includes(selected)) {
+ shown[shown.length - 1] = selected;
+ }
+ return { shown, hiddenCount: options.length - shown.length };
+}
diff --git a/packages/views/agents/create/use-create-agent-form.ts b/packages/views/agents/create/use-create-agent-form.ts
index 3fcc2dc934..b08e5d5f4f 100644
--- a/packages/views/agents/create/use-create-agent-form.ts
+++ b/packages/views/agents/create/use-create-agent-form.ts
@@ -151,6 +151,7 @@ export function useCreateAgentForm(options?: {
draftReady:
selectedRuntime != null &&
isRuntimeUsableForUser(selectedRuntime, currentUserId) &&
+ (selectedRuntime.provider !== "qoder_cloud" || !!draft.qoderAgentId) &&
isDraftDescriptionWithinLimit(draft.description) &&
!accessInvalid &&
!conversationStartersInvalid,
diff --git a/packages/views/agents/create/use-create-agent-submit.test.tsx b/packages/views/agents/create/use-create-agent-submit.test.tsx
index e1c7e9ddaa..abb16ad144 100644
--- a/packages/views/agents/create/use-create-agent-submit.test.tsx
+++ b/packages/views/agents/create/use-create-agent-submit.test.tsx
@@ -11,7 +11,7 @@ import { workspaceKeys } from "@multica/core/workspace/queries";
import enAgents from "../../locales/en/agents.json";
const mockCreateAgent = vi.hoisted(() => vi.fn());
-const mockPush = vi.hoisted(() => vi.fn());
+const mockReplace = vi.hoisted(() => vi.fn());
vi.mock("@multica/core/hooks", () => ({
useWorkspaceId: () => "ws-1",
@@ -21,11 +21,12 @@ vi.mock("@multica/core/paths", () => ({
useWorkspacePaths: () => ({
agentDetail: (agentId: string) => `/acme/agents/${agentId}`,
squadDetail: (squadId: string) => `/acme/squads/${squadId}`,
+ newAgentDone: (agentId: string) => `/acme/agents/new/done/${agentId}`,
}),
}));
vi.mock("../../navigation", () => ({
- useNavigation: () => ({ push: mockPush }),
+ useNavigation: () => ({ replace: mockReplace }),
}));
vi.mock("@multica/core/api", () => {
@@ -107,7 +108,7 @@ describe("useCreateAgentSubmit cache handoff", () => {
let navigationSnapshot:
| { path: string; list: Agent[] | undefined; detail: Agent | undefined }
| undefined;
- mockPush.mockImplementation((path: string) => {
+ mockReplace.mockImplementation((path: string) => {
navigationSnapshot = {
path,
list: queryClient.getQueryData<Agent[]>(
@@ -138,7 +139,7 @@ describe("useCreateAgentSubmit cache handoff", () => {
});
expect(navigationSnapshot).toEqual({
- path: "/acme/agents/agent-new",
+ path: "/acme/agents/new/done/agent-new",
list: [CREATED_AGENT],
detail: CREATED_AGENT,
});
diff --git a/packages/views/agents/create/use-create-agent-submit.ts b/packages/views/agents/create/use-create-agent-submit.ts
index 2120a9dfe3..e57b5117d5 100644
--- a/packages/views/agents/create/use-create-agent-submit.ts
+++ b/packages/views/agents/create/use-create-agent-submit.ts
@@ -13,6 +13,7 @@ import {
workspaceKeys,
} from "@multica/core/workspace/queries";
import { useNavigation } from "../../navigation";
+import { withSquadParam } from "./squad-param";
import { useT } from "../../i18n";
interface AgentCreateErrors {
@@ -43,6 +44,8 @@ export function classifyAgentCreateError(
export function useCreateAgentSubmit(options: {
draft: AgentDraft;
runtimeId: string | null;
+ /** Provider of `runtimeId`, so settings it cannot run are not submitted. */
+ runtimeProvider?: string;
squadId: string | null;
/** Creation-source attribution for the `agent_created` analytics event. */
template?: string;
@@ -60,8 +63,15 @@ export function useCreateAgentSubmit(options: {
const [nameError, setNameError] = useState<string | null>(null);
const [formError, setFormError] = useState<string | null>(null);
- const { draft, runtimeId, squadId, template, duplicateSource, onCreated } =
- options;
+ const {
+ draft,
+ runtimeId,
+ runtimeProvider,
+ squadId,
+ template,
+ duplicateSource,
+ onCreated,
+ } = options;
const create = async () => {
if (!runtimeId || creating) return;
@@ -73,6 +83,7 @@ export function useCreateAgentSubmit(options: {
buildCreateAgentRequest({
draft,
runtimeId,
+ runtimeProvider,
template,
duplicateSource,
}),
@@ -109,14 +120,9 @@ export function useCreateAgentSubmit(options: {
// Reconcile other list projections in the background instead of making
// navigation wait on a second network request.
void qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
- toast.success(
- t(($) => $.creation_studio.created, {
- name: agent.name || draft.name.trim(),
- }),
- );
- navigation.push(
- squadId ? paths.squadDetail(squadId) : paths.agentDetail(agent.id),
- );
+ // Replace, not push: back from the done step must not reopen a form
+ // whose agent already exists.
+ navigation.replace(withSquadParam(paths.newAgentDone(agent.id), squadId));
} catch (error) {
const nextErrors = classifyAgentCreateError(
error,
diff --git a/packages/views/agents/create/use-manual-draft-sync.ts b/packages/views/agents/create/use-manual-draft-sync.ts
index 55211a1361..7471f4ad24 100644
--- a/packages/views/agents/create/use-manual-draft-sync.ts
+++ b/packages/views/agents/create/use-manual-draft-sync.ts
@@ -7,6 +7,7 @@ import {
type SetStateAction,
} from "react";
import {
+ applyDraftRuntimeChange,
fromStoredAgentDraft,
manualDraftOwner,
setManualDraftEntry,
@@ -39,8 +40,11 @@ export function useManualDraftSync(options: {
/** False until a duplicate has finished seeding; saving before then would
* persist the empty form the seed is about to replace. */
ready: boolean;
+ /** The runtime chosen in step 1. It outranks the stored draft's, whose
+ * per-runtime fields are dropped when the two differ. */
+ runtimeId?: string | null;
}): void {
- const { duplicateId, draft, setDraft, ready } = options;
+ const { duplicateId, draft, setDraft, ready, runtimeId } = options;
const owner = manualDraftOwner(duplicateId);
const setStored = useManualAgentDraftStore((state) => state.setDraft);
@@ -52,10 +56,15 @@ export function useManualDraftSync(options: {
// subscription would re-fire it on every keystroke's own write.
const persisted = useManualAgentDraftStore.getState().draft.byOwner[owner];
if (persisted) {
- setDraft(fromStoredAgentDraft(persisted.draft, persisted.runtimeId));
+ const stored = fromStoredAgentDraft(persisted.draft, persisted.runtimeId);
+ setDraft(
+ runtimeId && runtimeId !== stored.runtimeId
+ ? applyDraftRuntimeChange(stored, runtimeId)
+ : stored,
+ );
}
setRestored(true);
- }, [owner, ready, restored, setDraft]);
+ }, [owner, ready, restored, runtimeId, setDraft]);
useEffect(() => {
if (!restored) return;
diff --git a/packages/views/agents/index.ts b/packages/views/agents/index.ts
index e431d0107e..2d58cc8cdd 100644
--- a/packages/views/agents/index.ts
+++ b/packages/views/agents/index.ts
@@ -1,6 +1,7 @@
export { AgentsPage, AgentDetailPage } from "./components";
export {
- ChooseCreateMethodPage,
+ ChooseRuntimePage,
+ AgentCreatedPage,
ManualCreateAgentPage,
AiCreateAgentPage,
AiBuilderSessionPage,
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index 26d7f480d5..e6c7072093 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -171,6 +171,7 @@
"inspector": {
"section_profile": "Profile",
"section_execution": "Execution",
+ "qoder_execution_note": "Model, tools and skills are set on the QCA agent in Qoder.",
"section_access": "Access",
"section_properties": "Properties",
"section_details": "Details",
@@ -279,6 +280,7 @@
"composio_mcp": "MCP Apps",
"integrations": "Integrations",
"runtime_config": "Routing",
+ "qoder_agent": "QCA Agent",
"discard_dialog_title": "Discard unsaved changes?",
"discard_dialog_description": "You have unsaved changes in this tab. Leaving now will discard them.",
"discard_keep": "Keep editing",
@@ -289,18 +291,8 @@
"squad_title": "Create an agent for this squad",
"duplicate_title": "Duplicate {{name}}",
"back": "Go back",
- "eyebrow": "Agent creation",
- "choose_title": "How would you like to start?",
- "recommended": "Recommended",
- "continue": "Continue",
- "step_choose": "Choose a starting point",
- "step_configure": "Review and configure",
"step_ai": "Build through conversation",
"modes": {
- "blank": {
- "title": "Start blank",
- "description": "Set the name, instructions, and runtime yourself."
- },
"template": {
"title": "Use a template",
"description": "Start from curated instructions and skills, then adapt every detail to your workspace."
@@ -362,12 +354,11 @@
"live_draft_hint": "You can edit the draft directly.",
"duplicate_env_notice": "Instructions, skills and command arguments are copied. Environment variables, MCP servers and machine-local runtime config are not.",
"duplicate_runtime_reset_notice": "The original runtime is unavailable, so this copy runs on another one. Model, thinking level and speed were cleared because they only apply to the runtime they were chosen on.",
- "create_and_open": "Create & open agent",
+ "create_agent": "Create agent",
"create_and_add": "Create & add to squad",
"creating": "Creating agent…",
"create_failed": "Could not create the agent.",
"name_conflict": "An agent with this name already exists.",
- "created": "{{name}} was created",
"drafts": {
"title": "Drafts",
"untitled": "Untitled draft",
@@ -377,6 +368,80 @@
"discard_cancel": "Keep editing",
"banner": "You have {{count}} unfinished draft(s)",
"pick_hint": "Pick one to continue."
+ },
+ "close": "Close",
+ "steps": {
+ "runtime": "Choose runtime",
+ "configure": "Configure",
+ "done": "Done",
+ "aria": "Agent creation steps"
+ },
+ "configure_title": "Configure the agent",
+ "configure_description": "Give it a name and instructions. Everything can be changed later.",
+ "ask_ai": "Let AI write it",
+ "change_runtime": "Change",
+ "runtime_label": "Runtime",
+ "runtime_loading": "Loading runtime…",
+ "runtime_missing": "This runtime is no longer available.",
+ "cloud_fields_note": "Skills, MCP and conversation starters are only available on local and remote runtimes.",
+ "done": {
+ "loading": "Finishing up…",
+ "title": "{{name}} is ready",
+ "runs_on": "Runs on {{runtime}}",
+ "joined_squad": "Added to squad {{squad}}",
+ "next": "What next",
+ "assign_title": "Assign its first task",
+ "assign_description": "Create an issue with this agent as the assignee.",
+ "mention_title": "Mention it in an issue",
+ "mention_description": "@{{name}} in any issue comment and it picks the work up.",
+ "squad_title": "Add it to a squad",
+ "squad_description": "Work alongside other agents, dispatched by the squad leader.",
+ "open_squad_title": "Open {{squad}}",
+ "open_squad_description": "See the squad this agent just joined.",
+ "open_agent": "Open agent",
+ "back_to_list": "Back to agents"
+ },
+ "runtime_step": {
+ "title": "Where should this agent run?",
+ "search_placeholder": "Search harnesses or machines",
+ "groups": {
+ "machines": "Machines",
+ "cloud": "Cloud services"
+ },
+ "this_machine": "This machine",
+ "owner_you": "You",
+ "custom_badge": "Custom",
+ "web_local_title": "Use this computer's harnesses with the desktop app",
+ "download_desktop": "Download desktop app",
+ "harness_count_one": "{{count}} harness",
+ "harness_count_other": "{{count}} harnesses",
+ "local_starting": "Starting the local daemon…",
+ "local_empty_title": "No harness found on this machine",
+ "local_empty_hint": "Install a CLI such as Claude Code or Codex, and it will show up here.",
+ "more_harnesses_one": "{{count}} more: {{names}}",
+ "more_harnesses_other": "{{count}} more: {{names}}",
+ "add_remote": "Connect a machine",
+ "hidden_remote_one": "{{count}} more machine is only usable by its owner",
+ "hidden_remote_other": "{{count}} more machines are only usable by their owners",
+ "remote_warning": "Tasks run on {{owner}}'s machine, read and write files there, and count against {{owner}}'s account.",
+ "no_match": "Nothing matches “{{query}}”",
+ "hosted_by": "By {{vendor}}",
+ "coming_soon": "Coming soon",
+ "qoder_status": {
+ "not_configured": "Not connected",
+ "starting": "Starting",
+ "ready": "Connected",
+ "error": "Error",
+ "stopped": "Paused"
+ },
+ "connect": "Connect",
+ "settings": "Settings",
+ "member_connect": "Ask an admin to connect",
+ "member_fix": "Ask an admin to fix it",
+ "footer_selected": "Selected:",
+ "footer_hint": "Pick a runtime to continue",
+ "cancel": "Cancel",
+ "next": "Next"
}
},
"create_dialog": {
diff --git a/packages/views/locales/en/runtimes.json b/packages/views/locales/en/runtimes.json
index f45d81cf7d..5ebb8fb3f3 100644
--- a/packages/views/locales/en/runtimes.json
+++ b/packages/views/locales/en/runtimes.json
@@ -1,10 +1,10 @@
{
"page": {
"title": "Runtimes",
- "tagline": "Machines and cloud workers running CLI sessions for your agents.",
+ "tagline": "Machines and cloud services your agents run tasks on.",
"learn_more": "Learn more →",
- "connect_remote": "Add a computer",
- "search_placeholder": "Search runtimes…",
+ "connect_remote": "Add a machine",
+ "search_placeholder": "Search…",
"scope_mine": "Mine",
"scope_all": "All",
"live": "Live",
@@ -13,7 +13,7 @@
"filter_all_description": "All runtimes in this view",
"empty": {
"title": "No runtimes yet",
- "hint": "Desktop detects this computer automatically. Connect other computers here."
+ "hint": "Desktop detects this computer automatically. Add other machines here."
},
"no_matches": {
"title": "No matches",
@@ -25,6 +25,52 @@
"bootstrapping": {
"title": "Starting local runtime…",
"hint": "Connecting to the workspace..."
+ },
+ "add": "Add",
+ "add_menu": {
+ "machines": "Machines",
+ "this_computer": "This computer",
+ "this_computer_connected": "Connected · {{name}}",
+ "this_computer_download": "Download the desktop app to connect it",
+ "other_machine": "Other machine or server",
+ "other_machine_hint": "Run two commands on that machine",
+ "cloud_services": "Cloud services",
+ "qoder_manage_hint": "Connected · manage connection",
+ "cloud_runtime_hint": "Provision a Multica-hosted cloud node"
+ },
+ "columns": {
+ "name": "Name",
+ "harness": "Harness",
+ "agents": "Agents",
+ "workload": "Workload",
+ "status": "Status"
+ },
+ "groups": {
+ "machines": {
+ "title": "Machines"
+ },
+ "cloud": {
+ "title": "Cloud services",
+ "coming_soon": "Coming soon"
+ }
+ },
+ "rows": {
+ "this_computer_title": "Run on this computer",
+ "this_computer_hint": "Download the desktop app and sign in; Claude Code, Codex and other CLIs on this computer show up here automatically",
+ "download_desktop": "Download desktop",
+ "add_machine_title": "Add another machine or server",
+ "add_machine_hint": "Run two commands on that machine so agents can use the CLIs installed there",
+ "view_commands": "View commands",
+ "owner_you": "You",
+ "connect": "Connect",
+ "not_connected": "Not connected",
+ "provided_by": "By {{vendor}}",
+ "no_matches": "No machines or cloud services match"
+ },
+ "filters": {
+ "all": "All",
+ "online": "Online",
+ "offline": "Offline"
}
},
"mika_setup": {
@@ -79,7 +125,7 @@
"rename": "Rename machine",
"rename_dialog": {
"title": "Rename machine",
- "description": "Used for this computer and all its runtimes.",
+ "description": "Used for this machine and all its runtimes.",
"placeholder": "e.g. Bohan's MacBook",
"hint": "Leave empty to use the device's default name.",
"cancel": "Cancel",
@@ -211,16 +257,16 @@
"queued_one": "{{count}} queued",
"queued_other": "{{count}} queued",
"connect": {
- "title": "Add a computer",
- "description": "Run these two commands on the computer you want to add. We'll detect it the moment the daemon comes online.",
+ "title": "Add a machine",
+ "description": "Run these two commands on the machine you want to add. We'll detect it the moment the daemon comes online.",
"step1_label": "Install the Multica CLI",
"platform_group": "Choose your platform",
"platform_macos_linux": "macOS / Linux",
"platform_windows": "Windows",
"step2_label": "Start the daemon",
"step2_hint": "Opens a browser to sign in, then keeps the daemon running in the background.",
- "live_listening": "Waiting for your computer",
- "troubleshooting": "Can't open a browser on that computer?",
+ "live_listening": "Waiting for your machine",
+ "troubleshooting": "Can't open a browser on that machine?",
"trouble_intro": "Use a token instead of the browser sign-in. This replaces step 2 and works anywhere you have a terminal.",
"trouble_token_hint_prefix": "Create a token in ",
"trouble_token_hint_destination": "Settings → Tokens",
@@ -229,8 +275,8 @@
"trouble_view_logs": "View logs",
"copy_aria": "Copy",
"cancel": "Cancel",
- "success_title": "Computer connected",
- "success_description": "Computer connected. You can now create an agent.",
+ "success_title": "Machine connected",
+ "success_description": "Machine connected. You can now create an agent.",
"view_runtime": "View runtime",
"create_agent": "Create an agent"
},
@@ -477,5 +523,144 @@
"table_cache_r": "Cache R",
"table_cache_w": "Cache W",
"no_data": "No usage data yet"
+ },
+ "qoder": {
+ "title": "QCA runtime",
+ "description": "Connect Qoder Cloud Agent. Multica manages execution and stores credentials encrypted. Workspace administrators can change this configuration.",
+ "loading": "Loading…",
+ "unavailable": "Server setup is required: configure MULTICA_VCS_SECRET_KEY.",
+ "online": "Online",
+ "error": "Connection error",
+ "starting": "Starting",
+ "not_configured": "Not configured",
+ "name": "Runtime name",
+ "region": "Region",
+ "region_global": "Global (qoder.com)",
+ "region_cn": "China (qoder.com.cn)",
+ "region_hint": "Use the site where you created the PAT; a PAT only works in its own region.",
+ "keep_secret": "Leave blank to keep the saved token",
+ "repositories": "GitHub authorization",
+ "repositories_hint": "Bind a token to each repository. Select the repository and starting branch in your project. Tokens are never returned by the server.",
+ "remove": "Remove",
+ "add_repository": "Add repository",
+ "saved": "Saved. The server will start the runtime automatically.",
+ "check": "Test connection",
+ "working": "Working…",
+ "stop": "Pause",
+ "stopped": "Paused",
+ "offline": "Offline; reconnecting",
+ "checking": "Testing connection...",
+ "check_passed": "Connection successful",
+ "check_failed": "Connection failed",
+ "environment": "Environment",
+ "select_environment": "Select an environment",
+ "no_environments": "No available environments. Create one in Qoder, then refresh.",
+ "refresh_catalog": "Refresh list",
+ "agent": "QCA Agent",
+ "select_agent": "Select a QCA Agent",
+ "agent_hint": "Use the PAT saved in the remote runtime to link a QCA Agent. Manage its model, tools and skills in Qoder.",
+ "no_agents": "No available QCA Agents. Create one in Qoder, then refresh.",
+ "agent_unavailable": "The linked QCA Agent is unavailable. Select another agent.",
+ "save_agent": "Save association",
+ "agent_saved": "QCA Agent association saved",
+ "agent_save_failed": "Could not save QCA Agent association",
+ "cloud_title": "Qoder Cloud Agent",
+ "managed": "Managed service",
+ "cloud_description": "Run agents in Qoder Cloud using a shared connection, without maintaining a local host.",
+ "configure_credentials": "Configure credentials",
+ "add_agent": "Add agent",
+ "add_agent_description": "Create a Multica agent linked to an existing QCA Agent. It will use the environment and credentials configured for Qoder Cloud.",
+ "agent_name": "Agent name",
+ "cancel": "Cancel",
+ "shared_credentials_hint": "Credentials are shared within this workspace. PATs are encrypted and never displayed after saving.",
+ "agent_count_one": "{{count}} agent",
+ "agent_count_other": "{{count}} agents",
+ "github_url": "GitHub URL",
+ "github_token": "GitHub token",
+ "execution": "Execution",
+ "concurrency": "Concurrent runs",
+ "concurrency_hint": "Runs beyond this limit wait in the queue.",
+ "run_timeout": "Run timeout (minutes)",
+ "run_timeout_hint": "A run still going after this long is cancelled and marked failed.",
+ "data_disclosure_title": "What Multica sends to Qoder",
+ "data_disclosure": "The issue title and description, relevant comments, project context and the agent's instructions. GitHub tokens are only used to mount the repository for a run.",
+ "usage": "{{active}} of {{limit}} running · {{queued}} queued",
+ "open_settings": "Open settings",
+ "default_repository": "Default repository",
+ "default_repository_hint": "Mounted when the issue's project has no repository. The connection needs a GitHub token for it.",
+ "default_branch": "Branch",
+ "default_branch_placeholder": "Default branch",
+ "create_agent": "Create an agent with it",
+ "connect": {
+ "submit": "Connect",
+ "connected": "Qoder connected. It will be ready in a few seconds.",
+ "token": "Personal access token",
+ "token_rejected": "{{region}} does not accept this token. A token only works on the site that created it.",
+ "retry_cn": "Retry on China site",
+ "retry_global": "Retry on Global site",
+ "verifying": "Verifying token…",
+ "verified": "Token verified",
+ "environment_waiting": "Environments load once the token is verified",
+ "repo_count_one": "{{count}} repository",
+ "repo_count_other": "{{count}} repositories",
+ "optional": "Optional",
+ "execution_summary": "Up to {{concurrency}} at once · {{timeout}} min timeout"
+ },
+ "stop_confirm": {
+ "title": "Pause Qoder Cloud Agent?",
+ "description": "New tasks will not be sent to Qoder until it is resumed.",
+ "cancel": "Cancel",
+ "description_agents_one": "This agent keeps its instructions and history but cannot take new tasks until Qoder is resumed or it moves to another runtime.",
+ "description_agents_other": "These {{count}} agents keep their instructions and history but cannot take new tasks until Qoder is resumed or they move to another runtime."
+ },
+ "connect_title": "Connect Qoder Cloud Agent",
+ "connect_description": "Connect once with a Qoder PAT. Multica runs tasks in Qoder's sandboxes and stores credentials encrypted.",
+ "page": {
+ "configuration": "Configuration",
+ "agents_title": "Agents",
+ "pause_title": "Pause Qoder",
+ "pause_hint": "Stop sending new tasks to Qoder. Credentials and agents stay, and you can resume anytime.",
+ "resume_title": "Resume Qoder",
+ "resume_hint": "Start taking tasks again with the saved configuration.",
+ "resume": "Resume",
+ "resumed": "Qoder is starting.",
+ "disconnect_title": "Disconnect Qoder",
+ "disconnect_hint": "Delete the saved PAT and repository tokens and remove this runtime. Agents using it are unbound and keep their history.",
+ "disconnect": "Disconnect",
+ "not_connected_title": "Qoder isn't connected",
+ "not_connected_hint": "Ask a workspace admin to connect Qoder Cloud Agent.",
+ "workload_idle": "Idle",
+ "connection_title": "Connection",
+ "edit": "Edit",
+ "edit_connection_title": "Edit connection",
+ "edit_connection_hint": "The connection is tested before it's saved.",
+ "test_and_save": "Test and save",
+ "save": "Save",
+ "token_saved": "Saved",
+ "repositories_hint": "Agents can only clone the repositories authorized here.",
+ "repo_token_saved": "Token saved",
+ "repo_actions": "Actions for {{repo}}",
+ "replace_token": "Replace token",
+ "replace_token_title": "Replace the token for {{repo}}",
+ "open_on_github": "Open on GitHub",
+ "remove_repository_title": "Remove {{repo}}?",
+ "remove_repository_description": "Its token is deleted and agents can no longer clone it.",
+ "edit_limits": "Edit execution settings",
+ "run_timeout": "Run timeout",
+ "manage_title": "Manage",
+ "minutes_one": "{{count}} minute",
+ "minutes_other": "{{count}} minutes"
+ },
+ "disconnect_confirm": {
+ "title": "Disconnect Qoder Cloud Agent?",
+ "description": "The saved PAT and repository tokens are deleted and the Qoder runtime is removed. To use Qoder again, connect it from scratch.",
+ "description_agents_one": "This agent will be unbound. It keeps its instructions and history and can move to another runtime.",
+ "description_agents_other": "These {{count}} agents will be unbound. They keep their instructions and history and can move to another runtime.",
+ "plan_changed": "The agents on Qoder changed. Review the list and confirm again.",
+ "confirm": "Disconnect",
+ "working": "Disconnecting…",
+ "cancel": "Cancel",
+ "done": "Qoder disconnected"
+ }
}
}
diff --git a/packages/views/locales/fr/agents.json b/packages/views/locales/fr/agents.json
index cf2579bf7e..4b97dac166 100644
--- a/packages/views/locales/fr/agents.json
+++ b/packages/views/locales/fr/agents.json
@@ -171,6 +171,7 @@
"inspector": {
"section_profile": "Profil",
"section_execution": "Exécution",
+ "qoder_execution_note": "Le modèle, les outils et les Skills se configurent sur l’agent QCA dans Qoder.",
"section_access": "Accès",
"section_properties": "Propriétés",
"section_details": "Détails",
@@ -279,6 +280,7 @@
"composio_mcp": "Applications MCP",
"integrations": "Intégrations",
"runtime_config": "Routage",
+ "qoder_agent": "Agent QCA",
"discard_dialog_title": "Abandonner les modifications non enregistrées ?",
"discard_dialog_description": "Cet onglet contient des modifications non enregistrées. Les quitter maintenant les abandonnera.",
"discard_keep": "Continuer à modifier",
@@ -289,18 +291,8 @@
"squad_title": "Créer un agent pour ce squad",
"duplicate_title": "Dupliquer {{name}}",
"back": "Revenir en arrière",
- "eyebrow": "Création d'agent",
- "choose_title": "Comment souhaitez-vous commencer ?",
- "recommended": "Recommandé",
- "continue": "Continuer",
- "step_choose": "Choisir un point de départ",
- "step_configure": "Vérifier et configurer",
"step_ai": "Construire par la conversation",
"modes": {
- "blank": {
- "title": "Partir de zéro",
- "description": "Définissez vous-même le nom, les instructions et le runtime."
- },
"template": {
"title": "Partir d'un modèle",
"description": "Partez d'instructions et de skills sélectionnés, puis adaptez chaque détail à votre espace de travail."
@@ -362,12 +354,11 @@
"live_draft_hint": "Vous pouvez modifier le brouillon directement.",
"duplicate_env_notice": "Les instructions, les skills et les arguments de commande sont copiés. Les variables d'environnement, les serveurs MCP et la configuration de runtime locale à la machine ne le sont pas.",
"duplicate_runtime_reset_notice": "Le runtime d'origine est indisponible : cette copie s'exécute donc sur un autre. Le modèle, le niveau de réflexion et la vitesse ont été effacés car ils ne valent que pour le runtime sur lequel ils ont été choisis.",
- "create_and_open": "Créer et ouvrir l'agent",
+ "create_agent": "Créer l'agent",
"create_and_add": "Créer et ajouter au squad",
"creating": "Création de l'agent…",
"create_failed": "Impossible de créer l'agent.",
"name_conflict": "Un agent portant ce nom existe déjà.",
- "created": "{{name}} a été créé",
"drafts": {
"title": "Brouillons",
"untitled": "Brouillon sans titre",
@@ -377,6 +368,80 @@
"discard_cancel": "Continuer à modifier",
"banner": "Vous avez {{count}} brouillon(s) inachevé(s)",
"pick_hint": "Choisissez-en un pour continuer."
+ },
+ "close": "Fermer",
+ "steps": {
+ "runtime": "Choisir le runtime",
+ "configure": "Configurer",
+ "done": "Terminé",
+ "aria": "Étapes de création de l'agent"
+ },
+ "configure_title": "Configurer l'agent",
+ "configure_description": "Donnez-lui un nom et des instructions. Tout reste modifiable ensuite.",
+ "ask_ai": "Laisser l'IA rédiger",
+ "change_runtime": "Changer",
+ "runtime_label": "Runtime",
+ "runtime_loading": "Chargement du runtime…",
+ "runtime_missing": "Ce runtime n'est plus disponible.",
+ "cloud_fields_note": "Les Skills, le MCP et les amorces de conversation ne sont disponibles que sur les runtimes locaux et distants.",
+ "done": {
+ "loading": "Finalisation…",
+ "title": "{{name}} est prêt",
+ "runs_on": "S'exécute sur {{runtime}}",
+ "joined_squad": "Ajouté à l'escouade {{squad}}",
+ "next": "Et ensuite",
+ "assign_title": "Lui confier une première tâche",
+ "assign_description": "Créez un ticket assigné à cet agent.",
+ "mention_title": "Le mentionner dans un ticket",
+ "mention_description": "Mentionnez @{{name}} dans un commentaire de ticket et il prend le travail en charge.",
+ "squad_title": "L'ajouter à une escouade",
+ "squad_description": "Travailler avec d'autres agents, sous la répartition du chef d'escouade.",
+ "open_squad_title": "Ouvrir {{squad}}",
+ "open_squad_description": "Voir l'escouade que cet agent vient de rejoindre.",
+ "open_agent": "Ouvrir l'agent",
+ "back_to_list": "Retour aux agents"
+ },
+ "runtime_step": {
+ "title": "Où cet agent doit-il s'exécuter ?",
+ "search_placeholder": "Rechercher un harness ou une machine",
+ "groups": {
+ "machines": "Machines",
+ "cloud": "Services cloud"
+ },
+ "this_machine": "Cette machine",
+ "owner_you": "Vous",
+ "custom_badge": "Personnalisé",
+ "web_local_title": "Utilisez les harness de cet ordinateur avec l'application de bureau",
+ "download_desktop": "Télécharger l'application de bureau",
+ "harness_count_one": "{{count}} harness",
+ "harness_count_other": "{{count}} harness",
+ "local_starting": "Démarrage du démon local…",
+ "local_empty_title": "Aucun harness trouvé sur cette machine",
+ "local_empty_hint": "Installez une CLI comme Claude Code ou Codex et elle apparaîtra ici.",
+ "more_harnesses_one": "{{count}} de plus : {{names}}",
+ "more_harnesses_other": "{{count}} de plus : {{names}}",
+ "add_remote": "Connecter une machine",
+ "hidden_remote_one": "{{count}} autre machine n'est utilisable que par son propriétaire",
+ "hidden_remote_other": "{{count}} autres machines ne sont utilisables que par leur propriétaire",
+ "remote_warning": "Les tâches s'exécutent sur la machine de {{owner}}, y lisent et écrivent des fichiers, et l'usage est imputé au compte de {{owner}}.",
+ "no_match": "Aucun résultat pour « {{query}} »",
+ "hosted_by": "Par {{vendor}}",
+ "coming_soon": "Bientôt disponible",
+ "qoder_status": {
+ "not_configured": "Non connecté",
+ "starting": "Démarrage",
+ "ready": "Connecté",
+ "error": "Erreur",
+ "stopped": "En pause"
+ },
+ "connect": "Connecter",
+ "settings": "Paramètres",
+ "member_connect": "Demandez à un admin de le connecter",
+ "member_fix": "Demandez à un admin de corriger",
+ "footer_selected": "Sélection :",
+ "footer_hint": "Choisissez un runtime pour continuer",
+ "cancel": "Annuler",
+ "next": "Suivant"
}
},
"create_dialog": {
diff --git a/packages/views/locales/fr/runtimes.json b/packages/views/locales/fr/runtimes.json
index 6978aebdf9..06dca437aa 100644
--- a/packages/views/locales/fr/runtimes.json
+++ b/packages/views/locales/fr/runtimes.json
@@ -1,10 +1,10 @@
{
"page": {
"title": "Runtimes",
- "tagline": "Machines et workers cloud qui exécutent des sessions CLI pour vos agents.",
+ "tagline": "Les machines et services cloud sur lesquels vos agents exécutent leurs tâches.",
"learn_more": "En savoir plus →",
- "connect_remote": "Ajouter un ordinateur",
- "search_placeholder": "Rechercher des runtimes…",
+ "connect_remote": "Ajouter une machine",
+ "search_placeholder": "Rechercher…",
"scope_mine": "Les miens",
"scope_all": "Tous",
"live": "En direct",
@@ -13,7 +13,7 @@
"filter_all_description": "Tous les runtimes de cette vue",
"empty": {
"title": "Aucun runtime pour l'instant",
- "hint": "Desktop détecte cet ordinateur automatiquement. Connectez d’autres ordinateurs ici."
+ "hint": "Desktop détecte cet ordinateur automatiquement. Ajoutez d’autres machines ici."
},
"no_matches": {
"title": "Aucune correspondance",
@@ -25,6 +25,52 @@
"bootstrapping": {
"title": "Démarrage du runtime local…",
"hint": "Connexion à l’espace de travail..."
+ },
+ "add": "Ajouter",
+ "add_menu": {
+ "machines": "Machines",
+ "this_computer": "Cet ordinateur",
+ "this_computer_connected": "Connecté · {{name}}",
+ "this_computer_download": "Téléchargez l’app de bureau pour le connecter",
+ "other_machine": "Autre machine ou serveur",
+ "other_machine_hint": "Exécutez deux commandes sur cette machine",
+ "cloud_services": "Services cloud",
+ "qoder_manage_hint": "Connecté · gérer la connexion",
+ "cloud_runtime_hint": "Créer un nœud cloud hébergé par Multica"
+ },
+ "columns": {
+ "name": "Nom",
+ "harness": "Harness",
+ "agents": "Agents",
+ "workload": "Charge",
+ "status": "Statut"
+ },
+ "groups": {
+ "machines": {
+ "title": "Machines"
+ },
+ "cloud": {
+ "title": "Services cloud",
+ "coming_soon": "Bientôt disponible"
+ }
+ },
+ "rows": {
+ "this_computer_title": "Exécuter sur cet ordinateur",
+ "this_computer_hint": "Téléchargez l’app de bureau et connectez-vous : Claude Code, Codex et les autres CLI de cet ordinateur apparaîtront ici",
+ "download_desktop": "Télécharger l’app",
+ "add_machine_title": "Ajouter une autre machine ou un serveur",
+ "add_machine_hint": "Exécutez deux commandes sur cette machine pour que les agents utilisent ses CLI",
+ "view_commands": "Voir les commandes",
+ "owner_you": "Vous",
+ "connect": "Connecter",
+ "not_connected": "Non connecté",
+ "provided_by": "Par {{vendor}}",
+ "no_matches": "Aucune machine ni aucun service cloud ne correspond"
+ },
+ "filters": {
+ "all": "Tous",
+ "online": "En ligne",
+ "offline": "Hors ligne"
}
},
"mika_setup": {
@@ -79,7 +125,7 @@
"rename": "Renommer la machine",
"rename_dialog": {
"title": "Renommer la machine",
- "description": "Utilisé pour cet ordinateur et tous ses runtimes.",
+ "description": "Utilisé pour cette machine et tous ses runtimes.",
"placeholder": "ex. MacBook de Bohan",
"hint": "Laissez vide pour utiliser le nom par défaut de l'appareil.",
"cancel": "Annuler",
@@ -211,16 +257,16 @@
"queued_one": "{{count}} en attente",
"queued_other": "{{count}} en attente",
"connect": {
- "title": "Ajouter un ordinateur",
- "description": "Exécutez ces deux commandes sur l'ordinateur à ajouter. Nous le détecterons dès que le daemon sera en ligne.",
+ "title": "Ajouter une machine",
+ "description": "Exécutez ces deux commandes sur la machine à ajouter. Nous la détecterons dès que le daemon sera en ligne.",
"step1_label": "Installer le CLI Multica",
"platform_group": "Choisissez votre système",
"platform_macos_linux": "macOS / Linux",
"platform_windows": "Windows",
"step2_label": "Démarrer le daemon",
"step2_hint": "Ouvre un navigateur pour la connexion, puis laisse le daemon tourner en arrière-plan.",
- "live_listening": "En attente de votre ordinateur",
- "troubleshooting": "Impossible d'ouvrir un navigateur sur cet ordinateur ?",
+ "live_listening": "En attente de votre machine",
+ "troubleshooting": "Impossible d'ouvrir un navigateur sur cette machine ?",
"trouble_intro": "Utilisez un jeton plutôt que la connexion par navigateur. Cela remplace l'étape 2 et fonctionne partout où vous disposez d'un terminal.",
"trouble_token_hint_prefix": "Créez un jeton dans ",
"trouble_token_hint_destination": "Paramètres → Jetons",
@@ -229,8 +275,8 @@
"trouble_view_logs": "Voir les journaux",
"copy_aria": "Copier",
"cancel": "Annuler",
- "success_title": "Ordinateur connecté",
- "success_description": "Ordinateur connecté. Vous pouvez maintenant créer un agent.",
+ "success_title": "Machine connectée",
+ "success_description": "Machine connectée. Vous pouvez maintenant créer un agent.",
"view_runtime": "Voir le runtime",
"create_agent": "Créer un agent"
},
@@ -477,5 +523,144 @@
"table_cache_r": "Cache L",
"table_cache_w": "Cache É",
"no_data": "Aucune donnée de consommation pour l'instant"
+ },
+ "qoder": {
+ "title": "Environnement QCA",
+ "description": "Connectez Qoder Cloud Agent. Multica gère l’exécution et chiffre les identifiants. Les administrateurs de l’espace de travail peuvent modifier cette configuration.",
+ "loading": "Chargement…",
+ "unavailable": "Configuration serveur requise : définissez MULTICA_VCS_SECRET_KEY.",
+ "online": "En ligne",
+ "error": "Erreur de connexion",
+ "starting": "Démarrage",
+ "not_configured": "Non configuré",
+ "name": "Nom de l’environnement d’exécution",
+ "region": "Région",
+ "region_global": "International (qoder.com)",
+ "region_cn": "Chine (qoder.com.cn)",
+ "region_hint": "Choisissez le site où vous avez créé le PAT ; un PAT ne fonctionne que dans sa région.",
+ "keep_secret": "Laissez vide pour conserver le jeton enregistré",
+ "repositories": "Autorisation GitHub",
+ "repositories_hint": "Associez un jeton à chaque dépôt. Choisissez le dépôt et la branche de départ dans votre projet. Le serveur ne renvoie jamais les jetons.",
+ "remove": "Supprimer",
+ "add_repository": "Ajouter un dépôt",
+ "saved": "Enregistré. Le serveur démarrera automatiquement l’environnement d’exécution.",
+ "check": "Tester la connexion",
+ "working": "En cours…",
+ "stop": "Mettre en pause",
+ "stopped": "En pause",
+ "offline": "Hors ligne ; reconnexion en cours",
+ "checking": "Test de connexion...",
+ "check_passed": "Connexion réussie",
+ "check_failed": "Échec de la connexion",
+ "environment": "Environnement",
+ "select_environment": "Choisir un environnement",
+ "no_environments": "Aucun environnement disponible. Créez-en un dans Qoder, puis actualisez.",
+ "refresh_catalog": "Actualiser la liste",
+ "agent": "Agent QCA",
+ "select_agent": "Choisir un agent QCA",
+ "agent_hint": "Utilisez le PAT enregistré dans l’environnement distant pour associer un agent QCA. Gérez son modèle, ses outils et ses skills dans Qoder.",
+ "no_agents": "Aucun agent QCA disponible. Créez-en un dans Qoder, puis actualisez.",
+ "agent_unavailable": "L’agent QCA associé n’est pas disponible. Choisissez-en un autre.",
+ "save_agent": "Enregistrer l’association",
+ "agent_saved": "Association de l’agent QCA enregistrée",
+ "agent_save_failed": "Impossible d’enregistrer l’association de l’agent QCA",
+ "cloud_title": "Qoder Cloud Agent",
+ "managed": "Service géré",
+ "cloud_description": "Exécutez des agents dans Qoder Cloud avec une connexion partagée, sans maintenir d’hôte local.",
+ "configure_credentials": "Configurer les identifiants",
+ "add_agent": "Ajouter un agent",
+ "add_agent_description": "Créez un agent Multica associé à un agent QCA existant. Il utilisera l’environnement et les identifiants configurés pour Qoder Cloud.",
+ "agent_name": "Nom de l’agent",
+ "cancel": "Annuler",
+ "shared_credentials_hint": "Les identifiants sont partagés dans cet espace de travail. Les PAT sont chiffrés et ne sont plus affichés après l’enregistrement.",
+ "agent_count_one": "{{count}} agent",
+ "agent_count_other": "{{count}} agents",
+ "github_url": "URL GitHub",
+ "github_token": "Jeton GitHub",
+ "execution": "Exécution",
+ "concurrency": "Exécutions simultanées",
+ "concurrency_hint": "Au-delà de cette limite, les tâches attendent dans la file.",
+ "run_timeout": "Délai d'exécution (minutes)",
+ "run_timeout_hint": "Une exécution encore en cours après ce délai est annulée et marquée en échec.",
+ "data_disclosure_title": "Ce que Multica envoie à Qoder",
+ "data_disclosure": "Le titre et la description du ticket, les commentaires pertinents, le contexte du projet et les instructions de l'agent. Les jetons GitHub servent uniquement à monter le dépôt pendant une exécution.",
+ "usage": "{{active}} sur {{limit}} en cours · {{queued}} en attente",
+ "open_settings": "Ouvrir les paramètres",
+ "default_repository": "Dépôt par défaut",
+ "default_repository_hint": "Monté quand le projet du ticket n'a pas de dépôt. La connexion doit avoir un jeton GitHub pour ce dépôt.",
+ "default_branch": "Branche",
+ "default_branch_placeholder": "Branche par défaut",
+ "create_agent": "Créer un agent avec",
+ "connect": {
+ "submit": "Connecter",
+ "connected": "Qoder est connecté. Il sera prêt dans quelques secondes.",
+ "token": "Jeton d'accès personnel",
+ "token_rejected": "{{region}} n'accepte pas ce jeton. Un jeton ne fonctionne que sur le site qui l'a créé.",
+ "retry_cn": "Réessayer sur le site Chine",
+ "retry_global": "Réessayer sur le site international",
+ "verifying": "Vérification du jeton…",
+ "verified": "Jeton vérifié",
+ "environment_waiting": "Les environnements se chargent une fois le jeton vérifié",
+ "repo_count_one": "{{count}} dépôt",
+ "repo_count_other": "{{count}} dépôts",
+ "optional": "Facultatif",
+ "execution_summary": "Jusqu'à {{concurrency}} à la fois · délai de {{timeout}} min"
+ },
+ "stop_confirm": {
+ "title": "Mettre Qoder Cloud Agent en pause ?",
+ "description": "Aucune nouvelle tâche ne sera envoyée à Qoder tant qu'il n'est pas relancé.",
+ "cancel": "Annuler",
+ "description_agents_one": "Cet agent garde ses instructions et son historique, mais ne peut plus prendre de tâches tant que Qoder n'est pas relancé ou qu'il n'est pas déplacé vers un autre environnement.",
+ "description_agents_other": "Ces {{count}} agents gardent leurs instructions et leur historique, mais ne peuvent plus prendre de tâches tant que Qoder n'est pas relancé ou qu'ils ne sont pas déplacés vers un autre environnement."
+ },
+ "connect_title": "Connecter Qoder Cloud Agent",
+ "connect_description": "Connectez-vous une fois avec un PAT Qoder. Multica exécute les tâches dans les sandboxes Qoder et chiffre les identifiants.",
+ "page": {
+ "configuration": "Configuration",
+ "agents_title": "Agents",
+ "pause_title": "Mettre Qoder en pause",
+ "pause_hint": "Plus aucune nouvelle tâche n'est envoyée à Qoder. Les identifiants et les agents sont conservés, et vous pouvez relancer à tout moment.",
+ "resume_title": "Relancer Qoder",
+ "resume_hint": "Reprendre les tâches avec la configuration enregistrée.",
+ "resume": "Relancer",
+ "resumed": "Qoder démarre.",
+ "disconnect_title": "Déconnecter Qoder",
+ "disconnect_hint": "Supprime le PAT et les jetons de dépôt enregistrés, et retire cet environnement. Les agents qui l'utilisent sont détachés et gardent leur historique.",
+ "disconnect": "Déconnecter",
+ "not_connected_title": "Qoder n'est pas connecté",
+ "not_connected_hint": "Demandez à un administrateur de l'espace de travail de connecter Qoder Cloud Agent.",
+ "workload_idle": "Inactif",
+ "connection_title": "Connexion",
+ "edit": "Modifier",
+ "edit_connection_title": "Modifier la connexion",
+ "edit_connection_hint": "La connexion est testée avant d'être enregistrée.",
+ "test_and_save": "Tester et enregistrer",
+ "save": "Enregistrer",
+ "token_saved": "Enregistré",
+ "repositories_hint": "Les agents ne peuvent cloner que les dépôts autorisés ici.",
+ "repo_token_saved": "Jeton enregistré",
+ "repo_actions": "Actions pour {{repo}}",
+ "replace_token": "Remplacer le jeton",
+ "replace_token_title": "Remplacer le jeton de {{repo}}",
+ "open_on_github": "Ouvrir sur GitHub",
+ "remove_repository_title": "Retirer {{repo}} ?",
+ "remove_repository_description": "Son jeton est supprimé et les agents ne peuvent plus le cloner.",
+ "edit_limits": "Modifier les paramètres d'exécution",
+ "run_timeout": "Délai d'exécution",
+ "manage_title": "Gérer",
+ "minutes_one": "{{count}} minute",
+ "minutes_other": "{{count}} minutes"
+ },
+ "disconnect_confirm": {
+ "title": "Déconnecter Qoder Cloud Agent ?",
+ "description": "Le PAT et les jetons de dépôt enregistrés sont supprimés et l'environnement Qoder est retiré. Pour réutiliser Qoder, il faudra le reconnecter depuis le début.",
+ "description_agents_one": "Cet agent sera détaché. Il garde ses instructions et son historique et peut passer à un autre environnement.",
+ "description_agents_other": "Ces {{count}} agents seront détachés. Ils gardent leurs instructions et leur historique et peuvent passer à un autre environnement.",
+ "plan_changed": "Les agents sur Qoder ont changé. Vérifiez la liste et confirmez à nouveau.",
+ "confirm": "Déconnecter",
+ "working": "Déconnexion…",
+ "cancel": "Annuler",
+ "done": "Qoder déconnecté"
+ }
}
}
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index 626eeb179c..7e3c78c6eb 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -154,6 +154,7 @@
"inspector": {
"section_profile": "プロフィール",
"section_execution": "実行設定",
+ "qoder_execution_note": "モデル、ツール、Skills は Qoder の QCA エージェントで設定します。",
"section_access": "アクセス",
"section_properties": "プロパティ",
"section_details": "詳細",
@@ -261,6 +262,7 @@
"composio_mcp": "MCP アプリ",
"integrations": "連携",
"runtime_config": "ルーティング",
+ "qoder_agent": "QCA エージェント",
"discard_dialog_title": "保存していない変更を破棄しますか?",
"discard_dialog_description": "このタブに保存していない変更があります。今移動すると変更は破棄されます。",
"discard_keep": "編集を続ける",
@@ -871,18 +873,8 @@
"squad_title": "このスクワッド用のエージェントを作成",
"duplicate_title": "{{name}} を複製",
"back": "戻る",
- "eyebrow": "エージェント作成",
- "choose_title": "どの方法で始めますか?",
- "recommended": "おすすめ",
- "continue": "続ける",
- "step_choose": "開始方法を選択",
- "step_configure": "確認して設定",
"step_ai": "会話で作成",
"modes": {
- "blank": {
- "title": "空白から始める",
- "description": "名前、指示、ランタイムを自分で設定します。"
- },
"template": {
"title": "テンプレートを使用",
"description": "整理された指示とスキルを基に、ワークスペースに合わせて詳細を調整します。"
@@ -944,12 +936,11 @@
"live_draft_hint": "下書きは直接編集できます。",
"duplicate_env_notice": "指示、スキル、コマンド引数がコピーされます。環境変数、MCP サーバー、マシンローカルのランタイム設定はコピーされません。",
"duplicate_runtime_reset_notice": "元のランタイムが利用できないため、このコピーは別のランタイムで実行されます。モデル・思考レベル・速度は選択したランタイムでのみ有効なため、クリアされました。",
- "create_and_open": "作成して開く",
+ "create_agent": "エージェントを作成",
"create_and_add": "作成してスクワッドに追加",
"creating": "エージェントを作成中…",
"create_failed": "エージェントを作成できませんでした。",
"name_conflict": "同じ名前のエージェントがすでに存在します。",
- "created": "{{name}} を作成しました",
"drafts": {
"title": "下書き",
"untitled": "無題の下書き",
@@ -959,6 +950,77 @@
"discard_cancel": "編集を続ける",
"banner": "未完了の下書きが {{count}} 件あります",
"pick_hint": "続きを選んでください。"
+ },
+ "close": "閉じる",
+ "steps": {
+ "runtime": "ランタイムを選択",
+ "configure": "設定",
+ "done": "完了",
+ "aria": "エージェント作成の手順"
+ },
+ "configure_title": "エージェントを設定",
+ "configure_description": "名前と指示を入力します。あとからいつでも変更できます。",
+ "ask_ai": "AI に書いてもらう",
+ "change_runtime": "変更",
+ "runtime_label": "ランタイム",
+ "runtime_loading": "ランタイムを読み込み中…",
+ "runtime_missing": "このランタイムは利用できなくなりました。",
+ "cloud_fields_note": "Skills、MCP、会話のきっかけはローカルとリモートのランタイムでのみ利用できます。",
+ "done": {
+ "loading": "仕上げています…",
+ "title": "{{name}} の準備ができました",
+ "runs_on": "{{runtime}} で実行",
+ "joined_squad": "スクワッド {{squad}} に追加しました",
+ "next": "次にすること",
+ "assign_title": "最初のタスクを割り当てる",
+ "assign_description": "このエージェントを担当者にしてイシューを作成します。",
+ "mention_title": "イシューでメンションする",
+ "mention_description": "イシューのコメントで @{{name}} とメンションすると、作業を引き受けます。",
+ "squad_title": "スクワッドに追加",
+ "squad_description": "スクワッドリーダーの割り振りで、他のエージェントと一緒に働きます。",
+ "open_squad_title": "{{squad}} を開く",
+ "open_squad_description": "このエージェントが加わったスクワッドを表示します。",
+ "open_agent": "エージェントを開く",
+ "back_to_list": "エージェント一覧に戻る"
+ },
+ "runtime_step": {
+ "title": "このエージェントをどこで実行しますか?",
+ "search_placeholder": "ハーネスまたはマシンを検索",
+ "groups": {
+ "machines": "マシン",
+ "cloud": "クラウドサービス"
+ },
+ "this_machine": "このマシン",
+ "owner_you": "あなた",
+ "custom_badge": "カスタム",
+ "web_local_title": "このコンピューターのハーネスはデスクトップアプリで使えます",
+ "download_desktop": "デスクトップアプリをダウンロード",
+ "harness_count_other": "{{count}} 個のハーネス",
+ "local_starting": "ローカルデーモンを起動中…",
+ "local_empty_title": "このマシンにハーネスが見つかりません",
+ "local_empty_hint": "Claude Code や Codex などの CLI をインストールすると、ここに表示されます。",
+ "more_harnesses_other": "ほか {{count}} 件:{{names}}",
+ "add_remote": "マシンを接続",
+ "hidden_remote_other": "ほかに所有者のみ利用できるマシンが {{count}} 台あります",
+ "remote_warning": "タスクは {{owner}} のマシンで実行され、そのマシンのファイルを読み書きし、使用量は {{owner}} のアカウントに計上されます。",
+ "no_match": "「{{query}}」に一致する項目はありません",
+ "hosted_by": "提供:{{vendor}}",
+ "coming_soon": "近日公開",
+ "qoder_status": {
+ "not_configured": "未接続",
+ "starting": "起動中",
+ "ready": "接続済み",
+ "error": "エラー",
+ "stopped": "一時停止中"
+ },
+ "connect": "接続",
+ "settings": "設定",
+ "member_connect": "管理者に接続を依頼してください",
+ "member_fix": "管理者に対応を依頼してください",
+ "footer_selected": "選択中:",
+ "footer_hint": "続行するにはランタイムを選択してください",
+ "cancel": "キャンセル",
+ "next": "次へ"
}
},
"actions": {
diff --git a/packages/views/locales/ja/runtimes.json b/packages/views/locales/ja/runtimes.json
index e9ff895cb5..7076917bdf 100644
--- a/packages/views/locales/ja/runtimes.json
+++ b/packages/views/locales/ja/runtimes.json
@@ -1,10 +1,10 @@
{
"page": {
"title": "ランタイム",
- "tagline": "エージェントの CLI セッションを実行するマシンとクラウドワーカーです。",
+ "tagline": "エージェントがタスクを実行するマシンとクラウドサービス。",
"learn_more": "詳しく見る →",
- "connect_remote": "コンピュータを追加",
- "search_placeholder": "ランタイムを検索…",
+ "connect_remote": "マシンを追加",
+ "search_placeholder": "検索…",
"scope_mine": "自分のもの",
"scope_all": "すべて",
"live": "ライブ",
@@ -13,7 +13,7 @@
"filter_all_description": "このビューのすべてのランタイム",
"empty": {
"title": "まだランタイムがありません",
- "hint": "デスクトップ版はこのコンピュータを自動検出します。他のコンピュータはここで接続できます。"
+ "hint": "デスクトップ版はこのコンピューターを自動検出します。他のマシンはここで追加できます。"
},
"no_matches": {
"title": "一致する結果なし",
@@ -25,6 +25,52 @@
"bootstrapping": {
"title": "ローカルランタイムを起動中…",
"hint": "ワークスペースに接続中..."
+ },
+ "add": "追加",
+ "add_menu": {
+ "machines": "マシン",
+ "this_computer": "このコンピューター",
+ "this_computer_connected": "接続済み · {{name}}",
+ "this_computer_download": "デスクトップアプリをダウンロードして接続",
+ "other_machine": "他のマシンまたはサーバー",
+ "other_machine_hint": "そのマシンで 2 つのコマンドを実行",
+ "cloud_services": "クラウドサービス",
+ "qoder_manage_hint": "接続済み · 接続を管理",
+ "cloud_runtime_hint": "Multica がホストするクラウドノードを作成"
+ },
+ "columns": {
+ "name": "名前",
+ "harness": "Harness",
+ "agents": "エージェント",
+ "workload": "負荷",
+ "status": "ステータス"
+ },
+ "groups": {
+ "machines": {
+ "title": "マシン"
+ },
+ "cloud": {
+ "title": "クラウドサービス",
+ "coming_soon": "近日公開"
+ }
+ },
+ "rows": {
+ "this_computer_title": "このコンピューターで実行",
+ "this_computer_hint": "デスクトップアプリをダウンロードしてサインインすると、このコンピューターの Claude Code や Codex などが自動的に表示されます",
+ "download_desktop": "デスクトップ版をダウンロード",
+ "add_machine_title": "他のマシンやサーバーを追加",
+ "add_machine_hint": "そのマシンで 2 つのコマンドを実行すると、エージェントがそこにインストールされた CLI を使えます",
+ "view_commands": "コマンドを表示",
+ "owner_you": "あなた",
+ "connect": "接続",
+ "not_connected": "未接続",
+ "provided_by": "{{vendor}} 提供",
+ "no_matches": "一致するマシンやクラウドサービスはありません"
+ },
+ "filters": {
+ "all": "すべて",
+ "online": "オンライン",
+ "offline": "オフライン"
}
},
"mika_setup": {
@@ -75,7 +121,7 @@
"rename": "マシンの名前を変更",
"rename_dialog": {
"title": "マシンの名前を変更",
- "description": "このコンピュータと、そのすべてのランタイムに使われます。",
+ "description": "このマシンと、そのすべてのランタイムに使われます。",
"placeholder": "例:私の MacBook",
"hint": "空欄にするとデバイスのデフォルト名を使用します。",
"cancel": "キャンセル",
@@ -199,16 +245,16 @@
"running_other": "実行中 {{count}} 件",
"queued_other": "キュー待ち {{count}} 件",
"connect": {
- "title": "コンピュータを追加",
- "description": "追加したいコンピュータで、この 2 つのコマンドを実行してください。デーモンがオンラインになった瞬間に検出します。",
+ "title": "マシンを追加",
+ "description": "追加したいマシンで、この 2 つのコマンドを実行してください。デーモンがオンラインになった瞬間に検出します。",
"step1_label": "Multica CLI をインストール",
"platform_group": "プラットフォームを選択",
"platform_macos_linux": "macOS / Linux",
"platform_windows": "Windows",
"step2_label": "デーモンを起動",
"step2_hint": "サインインのためにブラウザを開き、その後デーモンをバックグラウンドで実行し続けます。",
- "live_listening": "あなたのコンピュータを待っています",
- "troubleshooting": "そのコンピュータでブラウザを開けませんか?",
+ "live_listening": "マシンを待っています",
+ "troubleshooting": "そのマシンでブラウザを開けませんか?",
"trouble_intro": "ブラウザでのサインインの代わりにトークンを使ってください。手順 2 を置き換え、ターミナルがある場所ならどこでも動作します。",
"trouble_token_hint_prefix": "トークンは ",
"trouble_token_hint_destination": "設定 → トークン",
@@ -217,8 +263,8 @@
"trouble_view_logs": "ログを表示",
"copy_aria": "コピー",
"cancel": "キャンセル",
- "success_title": "コンピュータを接続しました",
- "success_description": "コンピュータに接続しました。エージェントを作成できます。",
+ "success_title": "マシンを接続しました",
+ "success_description": "マシンに接続しました。エージェントを作成できます。",
"view_runtime": "ランタイムを表示",
"create_agent": "エージェントを作成"
},
@@ -461,5 +507,139 @@
"table_cache_r": "キャッシュ R",
"table_cache_w": "キャッシュ W",
"no_data": "まだ使用量データがありません"
+ },
+ "qoder": {
+ "title": "QCA runtime",
+ "description": "Connect Qoder Cloud Agent. Multica manages execution and stores credentials encrypted. Workspace administrators can change this configuration.",
+ "loading": "Loading…",
+ "unavailable": "サーバーの設定が必要です:MULTICA_VCS_SECRET_KEY を設定してください。",
+ "online": "Online",
+ "error": "Connection error",
+ "starting": "Starting",
+ "not_configured": "Not configured",
+ "name": "Runtime name",
+ "region": "リージョン",
+ "region_global": "グローバル(qoder.com)",
+ "region_cn": "中国(qoder.com.cn)",
+ "region_hint": "PAT を作成したサイトを選択してください。PAT はそのリージョンでのみ使用できます。",
+ "keep_secret": "Leave blank to keep the saved token",
+ "repositories": "GitHub authorization",
+ "repositories_hint": "Bind a token to each repository. Select the repository and starting branch in your project. Tokens are never returned by the server.",
+ "remove": "Remove",
+ "add_repository": "Add repository",
+ "saved": "Saved. The server will start the runtime automatically.",
+ "check": "Test connection",
+ "working": "Working…",
+ "stop": "一時停止",
+ "stopped": "一時停止中",
+ "offline": "Offline; reconnecting",
+ "checking": "接続をテスト中...",
+ "check_passed": "接続に成功しました",
+ "check_failed": "接続に失敗しました",
+ "environment": "実行環境",
+ "select_environment": "実行環境を選択",
+ "no_environments": "利用可能な環境がありません。Qoder で作成して一覧を更新してください。",
+ "refresh_catalog": "一覧を更新",
+ "agent": "QCA エージェント",
+ "select_agent": "QCA エージェントを選択",
+ "agent_hint": "リモートランタイムに保存された PAT で QCA エージェントを関連付けます。モデル、ツール、スキルは Qoder で管理します。",
+ "no_agents": "利用可能な QCA エージェントがありません。Qoder で作成して一覧を更新してください。",
+ "agent_unavailable": "関連付けた QCA エージェントは利用できません。別のエージェントを選択してください。",
+ "save_agent": "関連付けを保存",
+ "agent_saved": "QCA エージェントの関連付けを保存しました",
+ "agent_save_failed": "QCA エージェントの関連付けを保存できませんでした",
+ "cloud_title": "Qoder Cloud Agent",
+ "managed": "マネージドサービス",
+ "cloud_description": "共有接続を使って Qoder クラウドでエージェントを実行します。ローカルホストの管理は不要です。",
+ "configure_credentials": "認証情報を設定",
+ "add_agent": "エージェントを追加",
+ "add_agent_description": "既存の QCA エージェントに関連付ける Multica エージェントを作成します。Qoder クラウドに設定した環境と認証情報を使用します。",
+ "agent_name": "エージェント名",
+ "cancel": "キャンセル",
+ "shared_credentials_hint": "認証情報はこのワークスペース内で共有します。PAT は暗号化して保存し、再表示しません。",
+ "agent_count_other": "エージェント {{count}} 件",
+ "github_url": "GitHub URL",
+ "github_token": "GitHub トークン",
+ "execution": "実行設定",
+ "concurrency": "同時実行数",
+ "concurrency_hint": "上限を超えたタスクはキューで待機します。",
+ "run_timeout": "実行タイムアウト(分)",
+ "run_timeout_hint": "この時間を過ぎても終わらない実行はキャンセルされ、失敗として記録されます。",
+ "data_disclosure_title": "Multica が Qoder に送信する内容",
+ "data_disclosure": "Issue のタイトルと説明、関連コメント、プロジェクトのコンテキスト、エージェントの指示。GitHub トークンは実行時のリポジトリのマウントにのみ使われます。",
+ "usage": "実行中 {{active}}/{{limit}} · 待機 {{queued}}",
+ "open_settings": "設定を開く",
+ "default_repository": "デフォルトのリポジトリ",
+ "default_repository_hint": "Issue のプロジェクトにリポジトリがない場合にマウントされます。接続にこのリポジトリの GitHub トークンが必要です。",
+ "default_branch": "ブランチ",
+ "default_branch_placeholder": "デフォルトブランチ",
+ "create_agent": "これでエージェントを作成",
+ "connect": {
+ "submit": "接続",
+ "connected": "Qoder に接続しました。数秒で利用できるようになります。",
+ "token": "個人アクセストークン",
+ "token_rejected": "{{region}}ではこのトークンを使えません。トークンは作成したサイトでのみ有効です。",
+ "retry_cn": "中国サイトで再試行",
+ "retry_global": "グローバルサイトで再試行",
+ "verifying": "トークンを確認中…",
+ "verified": "トークンを確認しました",
+ "environment_waiting": "トークンの確認後に読み込まれます",
+ "repo_count_other": "{{count}} 件のリポジトリ",
+ "optional": "任意",
+ "execution_summary": "同時に最大 {{concurrency}} 件 · タイムアウト {{timeout}} 分"
+ },
+ "stop_confirm": {
+ "title": "Qoder Cloud Agent を一時停止しますか?",
+ "description": "再開するまで、新しいタスクは Qoder に送られません。",
+ "cancel": "キャンセル",
+ "description_agents_other": "次の {{count}} 件のエージェントは指示と履歴を保持しますが、Qoder を再開するか別のランタイムに移すまで新しいタスクを受けられません。"
+ },
+ "connect_title": "Qoder Cloud Agent を接続",
+ "connect_description": "Qoder の PAT で一度接続します。Multica は Qoder のサンドボックスでタスクを実行し、認証情報は暗号化して保存します。",
+ "page": {
+ "configuration": "設定",
+ "agents_title": "エージェント",
+ "pause_title": "Qoder を一時停止",
+ "pause_hint": "Qoder への新しいタスクの送信を止めます。認証情報とエージェントは残り、いつでも再開できます。",
+ "resume_title": "Qoder を再開",
+ "resume_hint": "保存済みの設定でタスクの受け付けを再開します。",
+ "resume": "再開",
+ "resumed": "Qoder を起動しています。",
+ "disconnect_title": "Qoder の接続を解除",
+ "disconnect_hint": "保存済みの PAT とリポジトリトークンを削除し、このランタイムを取り除きます。使用中のエージェントは割り当てが解除され、履歴は残ります。",
+ "disconnect": "接続を解除",
+ "not_connected_title": "Qoder は未接続です",
+ "not_connected_hint": "ワークスペース管理者に Qoder Cloud Agent の接続を依頼してください。",
+ "workload_idle": "待機中",
+ "connection_title": "接続",
+ "edit": "編集",
+ "edit_connection_title": "接続を編集",
+ "edit_connection_hint": "保存する前に接続をテストします。",
+ "test_and_save": "テストして保存",
+ "save": "保存",
+ "token_saved": "保存済み",
+ "repositories_hint": "エージェントがクローンできるのは、ここで許可したリポジトリだけです。",
+ "repo_token_saved": "トークン保存済み",
+ "repo_actions": "{{repo}} の操作",
+ "replace_token": "トークンを差し替え",
+ "replace_token_title": "{{repo}} のトークンを差し替え",
+ "open_on_github": "GitHub で開く",
+ "remove_repository_title": "{{repo}} を削除しますか?",
+ "remove_repository_description": "このリポジトリのトークンは削除され、エージェントはクローンできなくなります。",
+ "edit_limits": "実行設定を編集",
+ "run_timeout": "実行タイムアウト",
+ "manage_title": "管理",
+ "minutes_other": "{{count}} 分"
+ },
+ "disconnect_confirm": {
+ "title": "Qoder Cloud Agent の接続を解除しますか?",
+ "description": "保存済みの PAT とリポジトリトークンは削除され、Qoder ランタイムは取り除かれます。再び使うには最初から接続し直す必要があります。",
+ "description_agents_other": "次の {{count}} 件のエージェントの割り当てが解除されます。指示と履歴は残り、別のランタイムに移せます。",
+ "plan_changed": "Qoder 上のエージェントが変わりました。最新の一覧を確認してから、もう一度実行してください。",
+ "confirm": "接続を解除",
+ "working": "解除しています…",
+ "cancel": "キャンセル",
+ "done": "Qoder の接続を解除しました"
+ }
}
}
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 8c38196863..be79ac1442 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -162,6 +162,7 @@
"inspector": {
"section_profile": "프로필",
"section_execution": "실행 설정",
+ "qoder_execution_note": "모델, 도구, Skills는 Qoder의 QCA 에이전트에서 설정합니다.",
"section_access": "접근 권한",
"section_properties": "속성",
"section_details": "세부 정보",
@@ -269,6 +270,7 @@
"composio_mcp": "MCP 앱",
"integrations": "연동",
"runtime_config": "라우팅",
+ "qoder_agent": "QCA 에이전트",
"discard_dialog_title": "저장하지 않은 변경사항을 버릴까요?",
"discard_dialog_description": "이 탭에 저장하지 않은 변경사항이 있습니다. 지금 나가면 변경사항이 사라집니다.",
"discard_keep": "계속 편집",
@@ -871,18 +873,8 @@
"squad_title": "이 스쿼드용 에이전트 만들기",
"duplicate_title": "{{name}} 복제",
"back": "뒤로",
- "eyebrow": "에이전트 만들기",
- "choose_title": "어떻게 시작하시겠어요?",
- "recommended": "추천",
- "continue": "계속",
- "step_choose": "시작 방법 선택",
- "step_configure": "검토 및 설정",
"step_ai": "대화로 만들기",
"modes": {
- "blank": {
- "title": "빈 상태로 시작",
- "description": "이름, 지침, 런타임을 직접 설정합니다."
- },
"template": {
"title": "템플릿 사용",
"description": "정리된 지침과 스킬을 바탕으로 워크스페이스에 맞게 세부 항목을 조정합니다."
@@ -944,12 +936,11 @@
"live_draft_hint": "초안을 직접 수정할 수 있습니다.",
"duplicate_env_notice": "지침, 스킬, 명령 인수는 복사됩니다. 환경 변수, MCP 서버, 머신 로컬 런타임 설정은 복사되지 않습니다.",
"duplicate_runtime_reset_notice": "원래 런타임을 사용할 수 없어 이 복사본은 다른 런타임에서 실행됩니다. 모델, 추론 수준, 속도는 선택한 런타임에서만 유효하므로 초기화되었습니다.",
- "create_and_open": "만들고 열기",
+ "create_agent": "에이전트 만들기",
"create_and_add": "만들고 스쿼드에 추가",
"creating": "에이전트 만드는 중…",
"create_failed": "에이전트를 만들지 못했습니다.",
"name_conflict": "같은 이름의 에이전트가 이미 있습니다.",
- "created": "{{name}}을(를) 만들었습니다",
"drafts": {
"title": "초안",
"untitled": "제목 없는 초안",
@@ -959,6 +950,77 @@
"discard_cancel": "계속 편집",
"banner": "미완료 초안이 {{count}}개 있습니다",
"pick_hint": "이어서 진행할 항목을 선택하세요."
+ },
+ "close": "닫기",
+ "steps": {
+ "runtime": "런타임 선택",
+ "configure": "구성",
+ "done": "완료",
+ "aria": "에이전트 생성 단계"
+ },
+ "configure_title": "에이전트 구성",
+ "configure_description": "이름과 지침을 입력하세요. 나중에 언제든지 바꿀 수 있습니다.",
+ "ask_ai": "AI에게 작성 맡기기",
+ "change_runtime": "변경",
+ "runtime_label": "런타임",
+ "runtime_loading": "런타임을 불러오는 중…",
+ "runtime_missing": "이 런타임은 더 이상 사용할 수 없습니다.",
+ "cloud_fields_note": "Skills, MCP, 대화 시작 문구는 로컬 및 원격 런타임에서만 사용할 수 있습니다.",
+ "done": {
+ "loading": "마무리하는 중…",
+ "title": "{{name}} 준비 완료",
+ "runs_on": "{{runtime}}에서 실행",
+ "joined_squad": "스쿼드 {{squad}}에 추가됨",
+ "next": "다음 단계",
+ "assign_title": "첫 작업 할당하기",
+ "assign_description": "이 에이전트를 담당자로 하는 이슈를 만듭니다.",
+ "mention_title": "이슈에서 멘션하기",
+ "mention_description": "이슈 댓글에서 @{{name}}을(를) 멘션하면 작업을 맡습니다.",
+ "squad_title": "스쿼드에 추가",
+ "squad_description": "스쿼드 리더의 배분에 따라 다른 에이전트와 함께 일합니다.",
+ "open_squad_title": "{{squad}} 열기",
+ "open_squad_description": "이 에이전트가 방금 합류한 스쿼드를 봅니다.",
+ "open_agent": "에이전트 열기",
+ "back_to_list": "에이전트 목록으로"
+ },
+ "runtime_step": {
+ "title": "이 에이전트를 어디서 실행할까요?",
+ "search_placeholder": "하네스 또는 머신 검색",
+ "groups": {
+ "machines": "머신",
+ "cloud": "클라우드 서비스"
+ },
+ "this_machine": "이 머신",
+ "owner_you": "나",
+ "custom_badge": "사용자 지정",
+ "web_local_title": "데스크톱 앱에서 이 컴퓨터의 하네스를 사용할 수 있습니다",
+ "download_desktop": "데스크톱 앱 다운로드",
+ "harness_count_other": "하네스 {{count}}개",
+ "local_starting": "로컬 데몬을 시작하는 중…",
+ "local_empty_title": "이 머신에서 하네스를 찾지 못했습니다",
+ "local_empty_hint": "Claude Code나 Codex 같은 CLI를 설치하면 여기에 표시됩니다.",
+ "more_harnesses_other": "{{count}}개 더: {{names}}",
+ "add_remote": "머신 연결",
+ "hidden_remote_other": "소유자만 사용할 수 있는 머신 {{count}}대는 표시하지 않습니다",
+ "remote_warning": "작업은 {{owner}}의 머신에서 실행되고, 그 머신의 파일을 읽고 쓰며, 사용량은 {{owner}}의 계정에 집계됩니다.",
+ "no_match": "“{{query}}”와 일치하는 항목이 없습니다",
+ "hosted_by": "제공: {{vendor}}",
+ "coming_soon": "출시 예정",
+ "qoder_status": {
+ "not_configured": "연결 안 됨",
+ "starting": "시작 중",
+ "ready": "연결됨",
+ "error": "오류",
+ "stopped": "일시 중지됨"
+ },
+ "connect": "연결",
+ "settings": "설정",
+ "member_connect": "관리자에게 연결을 요청하세요",
+ "member_fix": "관리자에게 해결을 요청하세요",
+ "footer_selected": "선택됨:",
+ "footer_hint": "계속하려면 런타임을 선택하세요",
+ "cancel": "취소",
+ "next": "다음"
}
},
"actions": {
diff --git a/packages/views/locales/ko/runtimes.json b/packages/views/locales/ko/runtimes.json
index 9d4580faa5..6896a5aa46 100644
--- a/packages/views/locales/ko/runtimes.json
+++ b/packages/views/locales/ko/runtimes.json
@@ -1,10 +1,10 @@
{
"page": {
"title": "런타임",
- "tagline": "에이전트의 CLI 세션을 실행하는 기기와 클라우드 워커입니다.",
+ "tagline": "에이전트가 작업을 실행하는 머신과 클라우드 서비스입니다.",
"learn_more": "자세히 보기 →",
- "connect_remote": "컴퓨터 추가",
- "search_placeholder": "런타임 검색...",
+ "connect_remote": "머신 추가",
+ "search_placeholder": "검색…",
"scope_mine": "내 것",
"scope_all": "전체",
"live": "실시간",
@@ -13,7 +13,7 @@
"filter_all_description": "이 보기의 모든 런타임",
"empty": {
"title": "아직 런타임이 없습니다",
- "hint": "데스크톱 앱은 이 컴퓨터를 자동 감지합니다. 다른 컴퓨터는 여기서 연결하세요."
+ "hint": "데스크톱 앱은 이 컴퓨터를 자동 감지합니다. 다른 머신은 여기서 추가하세요."
},
"no_matches": {
"title": "일치하는 결과 없음",
@@ -25,6 +25,52 @@
"bootstrapping": {
"title": "로컬 런타임 시작 중...",
"hint": "워크스페이스에 연결 중..."
+ },
+ "add": "추가",
+ "add_menu": {
+ "machines": "머신",
+ "this_computer": "이 컴퓨터",
+ "this_computer_connected": "연결됨 · {{name}}",
+ "this_computer_download": "데스크톱 앱을 내려받아 연결",
+ "other_machine": "다른 머신 또는 서버",
+ "other_machine_hint": "해당 머신에서 명령 두 개 실행",
+ "cloud_services": "클라우드 서비스",
+ "qoder_manage_hint": "연결됨 · 연결 관리",
+ "cloud_runtime_hint": "Multica가 호스팅하는 클라우드 노드 생성"
+ },
+ "columns": {
+ "name": "이름",
+ "harness": "Harness",
+ "agents": "에이전트",
+ "workload": "작업량",
+ "status": "상태"
+ },
+ "groups": {
+ "machines": {
+ "title": "머신"
+ },
+ "cloud": {
+ "title": "클라우드 서비스",
+ "coming_soon": "출시 예정"
+ }
+ },
+ "rows": {
+ "this_computer_title": "이 컴퓨터에서 실행",
+ "this_computer_hint": "데스크톱 앱을 내려받아 로그인하면 이 컴퓨터의 Claude Code, Codex 등이 자동으로 표시됩니다",
+ "download_desktop": "데스크톱 앱 다운로드",
+ "add_machine_title": "다른 머신 또는 서버 추가",
+ "add_machine_hint": "해당 머신에서 명령 두 개를 실행하면 에이전트가 그 머신의 CLI를 사용할 수 있습니다",
+ "view_commands": "명령 보기",
+ "owner_you": "나",
+ "connect": "연결",
+ "not_connected": "연결 안 됨",
+ "provided_by": "{{vendor}} 제공",
+ "no_matches": "일치하는 머신 또는 클라우드 서비스가 없습니다"
+ },
+ "filters": {
+ "all": "전체",
+ "online": "온라인",
+ "offline": "오프라인"
}
},
"mika_setup": {
@@ -75,7 +121,7 @@
"rename": "기기 이름 변경",
"rename_dialog": {
"title": "기기 이름 변경",
- "description": "이 컴퓨터와 모든 런타임에 사용됩니다.",
+ "description": "이 머신과 모든 런타임에 사용됩니다.",
"placeholder": "예: 내 MacBook",
"hint": "비워 두면 기기의 기본 이름을 사용합니다.",
"cancel": "취소",
@@ -199,16 +245,16 @@
"running_other": "실행 중 {{count}}개",
"queued_other": "대기 중 {{count}}개",
"connect": {
- "title": "컴퓨터 추가",
- "description": "추가하려는 컴퓨터에서 아래 두 명령을 실행하세요. 데몬이 온라인이 되는 순간 감지합니다.",
+ "title": "머신 추가",
+ "description": "추가하려는 머신에서 아래 두 명령을 실행하세요. 데몬이 온라인이 되는 순간 감지합니다.",
"step1_label": "Multica CLI 설치",
"platform_group": "플랫폼 선택",
"platform_macos_linux": "macOS / Linux",
"platform_windows": "Windows",
"step2_label": "데몬 시작",
"step2_hint": "로그인을 위해 브라우저를 열고, 이후 데몬을 백그라운드에서 계속 실행합니다.",
- "live_listening": "컴퓨터를 기다리는 중",
- "troubleshooting": "해당 컴퓨터에서 브라우저를 열 수 없나요?",
+ "live_listening": "머신을 기다리는 중",
+ "troubleshooting": "해당 머신에서 브라우저를 열 수 없나요?",
"trouble_intro": "브라우저 로그인 대신 토큰을 사용하세요. 2단계를 대체하며 터미널이 있는 곳이면 어디서든 작동합니다.",
"trouble_token_hint_prefix": "토큰은 ",
"trouble_token_hint_destination": "설정 → 토큰",
@@ -217,8 +263,8 @@
"trouble_view_logs": "로그 보기",
"copy_aria": "복사",
"cancel": "취소",
- "success_title": "컴퓨터 연결됨",
- "success_description": "컴퓨터가 연결되었습니다. 에이전트를 만들 수 있습니다.",
+ "success_title": "머신 연결됨",
+ "success_description": "머신이 연결되었습니다. 에이전트를 만들 수 있습니다.",
"view_runtime": "런타임 보기",
"create_agent": "에이전트 만들기"
},
@@ -461,5 +507,139 @@
"table_cache_r": "캐시 R",
"table_cache_w": "캐시 W",
"no_data": "아직 사용량 데이터가 없습니다"
+ },
+ "qoder": {
+ "title": "QCA runtime",
+ "description": "Connect Qoder Cloud Agent. Multica manages execution and stores credentials encrypted. Workspace administrators can change this configuration.",
+ "loading": "Loading…",
+ "unavailable": "서버 설정이 필요합니다: MULTICA_VCS_SECRET_KEY를 설정하세요.",
+ "online": "Online",
+ "error": "Connection error",
+ "starting": "Starting",
+ "not_configured": "Not configured",
+ "name": "Runtime name",
+ "region": "리전",
+ "region_global": "글로벌(qoder.com)",
+ "region_cn": "중국(qoder.com.cn)",
+ "region_hint": "PAT를 만든 사이트를 선택하세요. PAT는 해당 리전에서만 사용할 수 있습니다.",
+ "keep_secret": "Leave blank to keep the saved token",
+ "repositories": "GitHub authorization",
+ "repositories_hint": "Bind a token to each repository. Select the repository and starting branch in your project. Tokens are never returned by the server.",
+ "remove": "Remove",
+ "add_repository": "Add repository",
+ "saved": "Saved. The server will start the runtime automatically.",
+ "check": "Test connection",
+ "working": "Working…",
+ "stop": "일시 중지",
+ "stopped": "일시 중지됨",
+ "offline": "Offline; reconnecting",
+ "checking": "연결 테스트 중...",
+ "check_passed": "연결 성공",
+ "check_failed": "연결 실패",
+ "environment": "실행 환경",
+ "select_environment": "실행 환경 선택",
+ "no_environments": "사용 가능한 환경이 없습니다. Qoder에서 생성한 후 새로고침하세요.",
+ "refresh_catalog": "목록 새로고침",
+ "agent": "QCA 에이전트",
+ "select_agent": "QCA 에이전트 선택",
+ "agent_hint": "원격 런타임에 저장된 PAT로 QCA 에이전트를 연결합니다. 모델, 도구, 스킬은 Qoder에서 관리합니다.",
+ "no_agents": "사용 가능한 QCA 에이전트가 없습니다. Qoder에서 생성한 후 새로고침하세요.",
+ "agent_unavailable": "연결된 QCA 에이전트를 사용할 수 없습니다. 다른 에이전트를 선택하세요.",
+ "save_agent": "연결 저장",
+ "agent_saved": "QCA 에이전트 연결을 저장했습니다",
+ "agent_save_failed": "QCA 에이전트 연결을 저장할 수 없습니다",
+ "cloud_title": "Qoder Cloud Agent",
+ "managed": "관리형 서비스",
+ "cloud_description": "공유 연결로 Qoder 클라우드에서 에이전트를 실행합니다. 로컬 호스트를 관리할 필요가 없습니다.",
+ "configure_credentials": "인증 정보 설정",
+ "add_agent": "에이전트 추가",
+ "add_agent_description": "기존 QCA 에이전트에 연결할 Multica 에이전트를 생성합니다. Qoder 클라우드에 설정된 환경과 인증 정보를 사용합니다.",
+ "agent_name": "에이전트 이름",
+ "cancel": "취소",
+ "shared_credentials_hint": "인증 정보는 현재 워크스페이스 내에서 공유됩니다. PAT는 암호화하여 저장되며 다시 표시되지 않습니다.",
+ "agent_count_other": "에이전트 {{count}}개",
+ "github_url": "GitHub URL",
+ "github_token": "GitHub 토큰",
+ "execution": "실행 설정",
+ "concurrency": "동시 실행 수",
+ "concurrency_hint": "한도를 넘는 작업은 대기열에서 기다립니다.",
+ "run_timeout": "실행 제한 시간(분)",
+ "run_timeout_hint": "이 시간이 지나도 끝나지 않은 실행은 취소되고 실패로 기록됩니다.",
+ "data_disclosure_title": "Multica가 Qoder로 보내는 내용",
+ "data_disclosure": "이슈 제목과 설명, 관련 댓글, 프로젝트 컨텍스트, 에이전트 지침. GitHub 토큰은 실행 시 저장소를 마운트하는 데만 사용됩니다.",
+ "usage": "실행 중 {{active}}/{{limit}} · 대기 {{queued}}",
+ "open_settings": "설정 열기",
+ "default_repository": "기본 저장소",
+ "default_repository_hint": "이슈의 프로젝트에 저장소가 없을 때 마운트됩니다. 연결에 이 저장소의 GitHub 토큰이 필요합니다.",
+ "default_branch": "브랜치",
+ "default_branch_placeholder": "기본 브랜치",
+ "create_agent": "이것으로 에이전트 만들기",
+ "connect": {
+ "submit": "연결",
+ "connected": "Qoder가 연결되었습니다. 몇 초 후 사용할 수 있습니다.",
+ "token": "개인 액세스 토큰",
+ "token_rejected": "{{region}}에서는 이 토큰을 사용할 수 없습니다. 토큰은 생성한 사이트에서만 유효합니다.",
+ "retry_cn": "중국 사이트로 다시 시도",
+ "retry_global": "글로벌 사이트로 다시 시도",
+ "verifying": "토큰 확인 중…",
+ "verified": "토큰 확인됨",
+ "environment_waiting": "토큰을 확인하면 불러옵니다",
+ "repo_count_other": "저장소 {{count}}개",
+ "optional": "선택 사항",
+ "execution_summary": "동시에 최대 {{concurrency}}개 · 제한 시간 {{timeout}}분"
+ },
+ "stop_confirm": {
+ "title": "Qoder Cloud Agent를 일시 중지할까요?",
+ "description": "다시 시작하기 전까지 새 작업은 Qoder로 보내지지 않습니다.",
+ "cancel": "취소",
+ "description_agents_other": "다음 {{count}}개 에이전트는 지침과 기록을 유지하지만 Qoder를 다시 시작하거나 다른 런타임으로 옮기기 전까지 새 작업을 받을 수 없습니다."
+ },
+ "connect_title": "Qoder Cloud Agent 연결",
+ "connect_description": "Qoder PAT로 한 번 연결하세요. Multica는 Qoder 샌드박스에서 작업을 실행하고 자격 증명을 암호화해 저장합니다.",
+ "page": {
+ "configuration": "구성",
+ "agents_title": "에이전트",
+ "pause_title": "Qoder 일시 중지",
+ "pause_hint": "Qoder로 새 작업을 보내지 않습니다. 자격 증명과 에이전트는 유지되며 언제든 다시 시작할 수 있습니다.",
+ "resume_title": "Qoder 다시 시작",
+ "resume_hint": "저장된 구성으로 작업을 다시 받습니다.",
+ "resume": "다시 시작",
+ "resumed": "Qoder를 시작하는 중입니다.",
+ "disconnect_title": "Qoder 연결 해제",
+ "disconnect_hint": "저장된 PAT와 저장소 토큰을 삭제하고 이 런타임을 제거합니다. 이를 사용하는 에이전트는 연결이 해제되며 기록은 유지됩니다.",
+ "disconnect": "연결 해제",
+ "not_connected_title": "Qoder가 연결되지 않았습니다",
+ "not_connected_hint": "워크스페이스 관리자에게 Qoder Cloud Agent 연결을 요청하세요.",
+ "workload_idle": "유휴",
+ "connection_title": "연결",
+ "edit": "편집",
+ "edit_connection_title": "연결 편집",
+ "edit_connection_hint": "저장하기 전에 연결을 테스트합니다.",
+ "test_and_save": "테스트 후 저장",
+ "save": "저장",
+ "token_saved": "저장됨",
+ "repositories_hint": "에이전트는 여기서 승인한 저장소만 복제할 수 있습니다.",
+ "repo_token_saved": "토큰 저장됨",
+ "repo_actions": "{{repo}} 작업",
+ "replace_token": "토큰 교체",
+ "replace_token_title": "{{repo}} 토큰 교체",
+ "open_on_github": "GitHub에서 열기",
+ "remove_repository_title": "{{repo}}을(를) 제거할까요?",
+ "remove_repository_description": "이 저장소의 토큰이 삭제되며 에이전트가 더 이상 복제할 수 없습니다.",
+ "edit_limits": "실행 설정 편집",
+ "run_timeout": "실행 제한 시간",
+ "manage_title": "관리",
+ "minutes_other": "{{count}}분"
+ },
+ "disconnect_confirm": {
+ "title": "Qoder Cloud Agent 연결을 해제할까요?",
+ "description": "저장된 PAT와 저장소 토큰이 삭제되고 Qoder 런타임이 제거됩니다. 다시 사용하려면 처음부터 연결해야 합니다.",
+ "description_agents_other": "다음 {{count}}개 에이전트는 연결이 해제됩니다. 지침과 기록은 유지되며 다른 런타임으로 옮길 수 있습니다.",
+ "plan_changed": "Qoder의 에이전트가 변경되었습니다. 최신 목록을 확인한 뒤 다시 확인하세요.",
+ "confirm": "연결 해제",
+ "working": "연결 해제 중…",
+ "cancel": "취소",
+ "done": "Qoder 연결을 해제했습니다"
+ }
}
}
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index adc367cc19..cacbcc9d01 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -162,6 +162,7 @@
"inspector": {
"section_profile": "资料",
"section_execution": "执行配置",
+ "qoder_execution_note": "模型、工具和 skill 在 Qoder 的 QCA 智能体上设置。",
"section_access": "访问权限",
"section_properties": "属性",
"section_details": "详情",
@@ -269,6 +270,7 @@
"composio_mcp": "MCP 应用",
"integrations": "集成",
"runtime_config": "路由",
+ "qoder_agent": "QCA 智能体",
"discard_dialog_title": "放弃未保存的修改?",
"discard_dialog_description": "当前 tab 有未保存的修改,离开会丢弃这些修改。",
"discard_keep": "继续编辑",
@@ -279,18 +281,8 @@
"squad_title": "为小队创建智能体",
"duplicate_title": "复制 {{name}}",
"back": "返回",
- "eyebrow": "创建智能体",
- "choose_title": "你想从哪里开始?",
- "recommended": "推荐",
- "continue": "继续",
- "step_choose": "选择起点",
- "step_configure": "检查并配置",
"step_ai": "通过对话创建",
"modes": {
- "blank": {
- "title": "从空白开始",
- "description": "手动填写名称、指令和运行时。"
- },
"template": {
"title": "使用模板",
"description": "从整理好的指令和 skill 开始,再根据工作区需要修改每个细节。"
@@ -352,12 +344,11 @@
"live_draft_hint": "可直接修改草稿。",
"duplicate_env_notice": "指令、skill 和命令行参数会被复制。环境变量、MCP 服务器和本机运行时配置不会复制。",
"duplicate_runtime_reset_notice": "原运行时当前不可用,副本已改用其他运行时。模型、思考等级和速度只在所选运行时上有效,因此已被清空。",
- "create_and_open": "创建并打开",
+ "create_agent": "创建智能体",
"create_and_add": "创建并加入小队",
"creating": "正在创建…",
"create_failed": "无法创建智能体。",
"name_conflict": "工作区中已存在同名智能体。",
- "created": "已创建 {{name}}",
"drafts": {
"title": "创建草稿",
"untitled": "未命名草稿",
@@ -367,6 +358,77 @@
"discard_cancel": "继续编辑",
"banner": "您有 {{count}} 条未完成的创建",
"pick_hint": "选一条继续。"
+ },
+ "close": "关闭",
+ "steps": {
+ "runtime": "选择运行时",
+ "configure": "配置",
+ "done": "完成",
+ "aria": "创建智能体步骤"
+ },
+ "configure_title": "配置智能体",
+ "configure_description": "给它起个名字,写下指令。之后都可以再改。",
+ "ask_ai": "让 AI 帮我写",
+ "change_runtime": "更换",
+ "runtime_label": "运行时",
+ "runtime_loading": "正在加载运行时…",
+ "runtime_missing": "这个运行时已不可用。",
+ "cloud_fields_note": "Skills、MCP 和聊天开场白只在本机和远端运行时可用,这里不显示。",
+ "done": {
+ "loading": "正在完成…",
+ "title": "{{name}} 已就绪",
+ "runs_on": "运行在 {{runtime}}",
+ "joined_squad": "已加入小队:{{squad}}",
+ "next": "接下来",
+ "assign_title": "指派第一个任务",
+ "assign_description": "新建一个任务,负责人设为这个智能体。",
+ "mention_title": "在任务里 @ 它",
+ "mention_description": "在任何任务的评论里 @{{name}},它会接手处理。",
+ "squad_title": "加入小队",
+ "squad_description": "和其他智能体一起,由小队负责人分派。",
+ "open_squad_title": "打开 {{squad}}",
+ "open_squad_description": "查看它刚加入的小队。",
+ "open_agent": "打开智能体",
+ "back_to_list": "返回智能体列表"
+ },
+ "runtime_step": {
+ "title": "这个智能体在哪里运行?",
+ "search_placeholder": "搜索 harness 或机器",
+ "groups": {
+ "machines": "机器",
+ "cloud": "云服务"
+ },
+ "this_machine": "本机",
+ "owner_you": "你",
+ "custom_badge": "自定义",
+ "web_local_title": "在桌面端可以使用这台电脑上的 harness",
+ "download_desktop": "下载桌面端",
+ "harness_count_other": "{{count}} 个 harness",
+ "local_starting": "正在启动本机守护进程…",
+ "local_empty_title": "这台机器上没有找到 harness",
+ "local_empty_hint": "安装 Claude Code、Codex 等 CLI 后,会出现在这里。",
+ "more_harnesses_other": "其余 {{count}} 个:{{names}}",
+ "add_remote": "连接机器",
+ "hidden_remote_other": "另有 {{count}} 台机器仅所有者可用,不在这里显示",
+ "remote_warning": "任务会在 {{owner}} 的机器上执行,读写那台机器上的文件,用量计入 {{owner}} 的账号。",
+ "no_match": "没有与「{{query}}」匹配的结果",
+ "hosted_by": "由 {{vendor}} 提供",
+ "coming_soon": "即将推出",
+ "qoder_status": {
+ "not_configured": "未连接",
+ "starting": "启动中",
+ "ready": "已连接",
+ "error": "出错",
+ "stopped": "已暂停"
+ },
+ "connect": "连接",
+ "settings": "设置",
+ "member_connect": "需要管理员连接",
+ "member_fix": "需要管理员处理",
+ "footer_selected": "已选:",
+ "footer_hint": "选择一个运行时以继续",
+ "cancel": "取消",
+ "next": "下一步"
}
},
"create_dialog": {
diff --git a/packages/views/locales/zh-Hans/runtimes.json b/packages/views/locales/zh-Hans/runtimes.json
index 75dfbd1a3d..b56700ee2c 100644
--- a/packages/views/locales/zh-Hans/runtimes.json
+++ b/packages/views/locales/zh-Hans/runtimes.json
@@ -1,10 +1,10 @@
{
"page": {
"title": "运行时",
- "tagline": "为智能体跑 CLI 会话的机器和云端 worker。",
+ "tagline": "智能体在这些机器和云服务上执行任务。",
"learn_more": "了解更多 →",
- "connect_remote": "添加电脑",
- "search_placeholder": "搜索运行时...",
+ "connect_remote": "添加机器",
+ "search_placeholder": "搜索...",
"scope_mine": "我的",
"scope_all": "全部",
"live": "实时",
@@ -13,7 +13,7 @@
"filter_all_description": "当前视图下的所有运行时",
"empty": {
"title": "还没有运行时",
- "hint": "桌面端自动检测本机;可在此连接其他电脑。"
+ "hint": "桌面端会自动识别这台电脑;其他机器可以在这里添加。"
},
"no_matches": {
"title": "无匹配",
@@ -25,6 +25,52 @@
"bootstrapping": {
"title": "正在启动本地运行时...",
"hint": "正在连接工作区..."
+ },
+ "add": "添加",
+ "add_menu": {
+ "machines": "机器",
+ "this_computer": "这台电脑",
+ "this_computer_connected": "已连接 · {{name}}",
+ "this_computer_download": "下载桌面端即可连接",
+ "other_machine": "其他机器或服务器",
+ "other_machine_hint": "在那台机器上运行两条命令",
+ "cloud_services": "云服务",
+ "qoder_manage_hint": "已连接 · 管理连接",
+ "cloud_runtime_hint": "创建一台 Multica 托管的云节点"
+ },
+ "columns": {
+ "name": "名称",
+ "harness": "Harness",
+ "agents": "智能体",
+ "workload": "负载",
+ "status": "状态"
+ },
+ "groups": {
+ "machines": {
+ "title": "机器"
+ },
+ "cloud": {
+ "title": "云服务",
+ "coming_soon": "即将推出"
+ }
+ },
+ "rows": {
+ "this_computer_title": "在这台电脑上运行",
+ "this_computer_hint": "下载桌面端并登录,这台电脑上的 Claude Code、Codex 等会自动出现在这里",
+ "download_desktop": "下载桌面端",
+ "add_machine_title": "添加其他机器或服务器",
+ "add_machine_hint": "在那台机器上运行两条命令,智能体就能用它上面装好的 CLI 执行任务",
+ "view_commands": "查看命令",
+ "owner_you": "你",
+ "connect": "连接",
+ "not_connected": "未连接",
+ "provided_by": "由 {{vendor}} 提供",
+ "no_matches": "没有匹配的机器或云服务"
+ },
+ "filters": {
+ "all": "全部",
+ "online": "在线",
+ "offline": "离线"
}
},
"mika_setup": {
@@ -32,7 +78,7 @@
"description": "让 Mika 帮你安排任务和协调智能体。",
"action": "和 Mika 开始",
"failed": "无法启动 Mika",
- "dialog_title": "让 Mika 在哪台电脑上运行?",
+ "dialog_title": "让 Mika 在哪台机器上运行?",
"cancel": "取消"
},
"machine": {
@@ -199,16 +245,16 @@
"running_other": "{{count}} 个运行中",
"queued_other": "{{count}} 个排队中",
"connect": {
- "title": "添加电脑",
- "description": "在要添加的电脑上运行这两条命令。守护进程一上线,这里就会自动识别。",
+ "title": "添加机器",
+ "description": "在要添加的机器上运行这两条命令。守护进程一上线,这里就会自动识别。",
"step1_label": "安装 Multica CLI",
"platform_group": "选择你的系统",
"platform_macos_linux": "macOS / Linux",
"platform_windows": "Windows",
"step2_label": "启动守护进程",
"step2_hint": "会打开浏览器登录,然后在后台保持守护进程运行。",
- "live_listening": "等待你的电脑上线",
- "troubleshooting": "那台电脑打不开浏览器?",
+ "live_listening": "等待你的机器上线",
+ "troubleshooting": "那台机器打不开浏览器?",
"trouble_intro": "改用 token 登录替代第 2 步,适用于任何有终端的环境。",
"trouble_token_hint_prefix": "在 ",
"trouble_token_hint_destination": "设置 → Tokens",
@@ -217,8 +263,8 @@
"trouble_view_logs": "查看日志",
"copy_aria": "复制",
"cancel": "取消",
- "success_title": "电脑已连接",
- "success_description": "电脑已连接,可以创建智能体。",
+ "success_title": "机器已连接",
+ "success_description": "机器已连接,可以创建智能体。",
"view_runtime": "查看运行时",
"create_agent": "创建智能体"
},
@@ -461,5 +507,139 @@
"table_cache_r": "缓存读",
"table_cache_w": "缓存写",
"no_data": "还没有使用数据"
+ },
+ "qoder": {
+ "title": "QCA 运行时",
+ "description": "连接 Qoder Cloud Agent,由 Multica 管理执行并加密保存凭证。工作区管理员可修改配置。",
+ "loading": "加载中...",
+ "unavailable": "请先在服务端配置 MULTICA_VCS_SECRET_KEY。",
+ "online": "在线",
+ "error": "连接异常",
+ "starting": "启动中",
+ "not_configured": "尚未配置",
+ "name": "运行时名称",
+ "region": "服务区域",
+ "region_global": "国际站(qoder.com)",
+ "region_cn": "中国站(qoder.com.cn)",
+ "region_hint": "选择创建 PAT 的站点,PAT 只能在对应区域使用。",
+ "keep_secret": "留空保留已保存的凭证",
+ "repositories": "GitHub 仓库授权",
+ "repositories_hint": "为每个仓库绑定凭证,在项目中选择仓库和起始分支。服务端不会返回凭证明文。",
+ "remove": "移除",
+ "add_repository": "添加仓库",
+ "saved": "已保存,服务端将自动启动运行时。",
+ "check": "测试连接",
+ "working": "处理中...",
+ "stop": "暂停",
+ "stopped": "已暂停",
+ "offline": "离线,正在重连",
+ "checking": "正在测试连接...",
+ "check_passed": "连接成功",
+ "check_failed": "连接失败",
+ "environment": "运行环境",
+ "select_environment": "选择运行环境",
+ "no_environments": "没有可用环境,请在 Qoder 中创建后刷新。",
+ "refresh_catalog": "刷新列表",
+ "agent": "QCA 智能体",
+ "select_agent": "选择 QCA 智能体",
+ "agent_hint": "使用远端运行时保存的 PAT 关联 QCA 智能体。模型、工具和 skill 在 Qoder 中管理。",
+ "no_agents": "没有可用的 QCA 智能体,请在 Qoder 中创建后刷新。",
+ "agent_unavailable": "关联的 QCA 智能体不可用,请重新选择。",
+ "save_agent": "保存关联",
+ "agent_saved": "已保存 QCA 智能体关联",
+ "agent_save_failed": "无法保存 QCA 智能体关联",
+ "cloud_title": "Qoder Cloud Agent",
+ "managed": "托管服务",
+ "cloud_description": "使用共享连接在 Qoder 云端运行智能体,无需维护本地主机。",
+ "configure_credentials": "配置凭证",
+ "add_agent": "添加智能体",
+ "add_agent_description": "创建 Multica 智能体并关联已有的 QCA 智能体,使用 Qoder 云端已配置的环境和凭证。",
+ "agent_name": "智能体名称",
+ "cancel": "取消",
+ "shared_credentials_hint": "凭证在当前工作区内共享,PAT 加密保存后不再显示。",
+ "agent_count_other": "{{count}} 个智能体",
+ "github_url": "GitHub URL",
+ "github_token": "GitHub 访问凭证",
+ "execution": "执行设置",
+ "concurrency": "并发运行数",
+ "concurrency_hint": "超过上限的任务会排队等待。",
+ "run_timeout": "单次运行超时(分钟)",
+ "run_timeout_hint": "超过该时长仍未结束的运行会被取消并标记为失败。",
+ "data_disclosure_title": "Multica 会发送给 Qoder 的内容",
+ "data_disclosure": "任务标题与描述、相关评论、项目上下文和智能体指令。GitHub 凭证仅用于在运行时挂载仓库。",
+ "usage": "运行中 {{active}}/{{limit}} · 排队 {{queued}}",
+ "open_settings": "查看设置",
+ "default_repository": "默认仓库",
+ "default_repository_hint": "任务所属项目未绑定仓库时挂载。连接中需要为该仓库配置 GitHub 凭证。",
+ "default_branch": "分支",
+ "default_branch_placeholder": "默认分支",
+ "create_agent": "用它创建智能体",
+ "connect": {
+ "submit": "连接",
+ "connected": "Qoder 已连接,几秒后即可使用。",
+ "token": "个人访问令牌",
+ "token_rejected": "{{region}}不认这个令牌。令牌只能在创建它的站点使用。",
+ "retry_cn": "切换到中国站重试",
+ "retry_global": "切换到国际站重试",
+ "verifying": "正在验证令牌…",
+ "verified": "令牌已验证",
+ "environment_waiting": "令牌验证后自动加载",
+ "repo_count_other": "{{count}} 个仓库",
+ "optional": "可选",
+ "execution_summary": "最多同时 {{concurrency}} 个 · 单次超时 {{timeout}} 分钟"
+ },
+ "stop_confirm": {
+ "title": "暂停 Qoder Cloud Agent?",
+ "description": "恢复之前,新任务不会再发给 Qoder。",
+ "cancel": "取消",
+ "description_agents_other": "下面 {{count}} 个智能体会保留指令和历史,但在恢复 Qoder 或更换运行时之前无法接新任务。"
+ },
+ "connect_title": "连接 Qoder Cloud Agent",
+ "connect_description": "用 Qoder PAT 连接一次。Multica 会在 Qoder 的沙箱里执行任务,凭证加密保存。",
+ "page": {
+ "configuration": "配置",
+ "agents_title": "智能体",
+ "pause_title": "暂停 Qoder",
+ "pause_hint": "不再向 Qoder 派发新任务。凭证和智能体都会保留,可以随时恢复。",
+ "resume_title": "恢复 Qoder",
+ "resume_hint": "使用已保存的配置重新开始接任务。",
+ "resume": "恢复",
+ "resumed": "Qoder 正在启动。",
+ "disconnect_title": "断开 Qoder",
+ "disconnect_hint": "删除已保存的 PAT 和仓库令牌,并移除这个运行时。使用它的智能体会被解绑,历史保留。",
+ "disconnect": "断开连接",
+ "not_connected_title": "Qoder 尚未连接",
+ "not_connected_hint": "请工作区管理员连接 Qoder Cloud Agent。",
+ "workload_idle": "空闲",
+ "connection_title": "连接",
+ "edit": "编辑",
+ "edit_connection_title": "编辑连接",
+ "edit_connection_hint": "保存前会先测试连接。",
+ "test_and_save": "测试并保存",
+ "save": "保存",
+ "token_saved": "已保存",
+ "repositories_hint": "智能体只能克隆这里授权的仓库。",
+ "repo_token_saved": "令牌已保存",
+ "repo_actions": "{{repo}} 的操作",
+ "replace_token": "更换令牌",
+ "replace_token_title": "更换 {{repo}} 的令牌",
+ "open_on_github": "在 GitHub 打开",
+ "remove_repository_title": "移除 {{repo}}?",
+ "remove_repository_description": "这个仓库的令牌会被删除,智能体之后无法再克隆它。",
+ "edit_limits": "编辑执行设置",
+ "run_timeout": "单次超时",
+ "manage_title": "管理",
+ "minutes_other": "{{count}} 分钟"
+ },
+ "disconnect_confirm": {
+ "title": "断开 Qoder Cloud Agent?",
+ "description": "已保存的 PAT 和仓库令牌会被删除,Qoder 运行时会被移除。之后要再用 Qoder,需要重新连接。",
+ "description_agents_other": "下面 {{count}} 个智能体会被解绑,保留指令和历史,之后可以换到其他运行时。",
+ "plan_changed": "Qoder 上的智能体有变化,请确认最新列表后再操作。",
+ "confirm": "断开连接",
+ "working": "正在断开…",
+ "cancel": "取消",
+ "done": "已断开 Qoder"
+ }
}
}
diff --git a/packages/views/modals/quick-create-issue.test.tsx b/packages/views/modals/quick-create-issue.test.tsx
index 13943fd7a5..f8e27d8b97 100644
--- a/packages/views/modals/quick-create-issue.test.tsx
+++ b/packages/views/modals/quick-create-issue.test.tsx
@@ -133,7 +133,7 @@ const mockSquadsData = vi.hoisted(
// version" (#7633). Tests flip this to drop the row and prove the panel no
// longer blocks on it.
const mockRuntimesData = vi.hoisted(
- () => ({ list: [{ id: "runtime-1", metadata: { cli_version: "1.2.3" } }] as Array<{ id: string; metadata: Record<string, unknown> }> }),
+ () => ({ list: [{ id: "runtime-1", metadata: { cli_version: "1.2.3" } }] as Array<{ id: string; provider?: string; metadata: Record<string, unknown> }> }),
);
// The real handle mints an id when it inserts the placeholder and hands it to
@@ -500,6 +500,18 @@ function renderPanel(props: React.ComponentProps<typeof AgentCreatePanel>) {
}
describe("AgentCreatePanel", () => {
+ it("does not select Qoder agents or their squads for issue creation", () => {
+ mockRuntimesData.list = [{ id: "runtime-1", provider: "qoder_cloud", metadata: {} }];
+ mockQuickCreateStore.lastActorType = "agent";
+ mockQuickCreateStore.lastActorId = "agent-1";
+ mockSquadsData.list = [{ id: "squad-1", name: "Cloud Squad", leader_id: "agent-1", archived_at: null }];
+ renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });
+ expect(screen.getByRole("button", { name: /^Create$/i })).toBeDisabled();
+ expect(screen.queryByText(/daemon.*version/i)).not.toBeInTheDocument();
+ expect(screen.queryByText("Bohan")).not.toBeInTheDocument();
+ expect(screen.queryByText("Cloud Squad")).not.toBeInTheDocument();
+ });
+
beforeEach(() => {
vi.clearAllMocks();
mockQuickCreateStore.lastActorType = null;
diff --git a/packages/views/modals/quick-create-issue.tsx b/packages/views/modals/quick-create-issue.tsx
index 4a3040b295..904ead1f6f 100644
--- a/packages/views/modals/quick-create-issue.tsx
+++ b/packages/views/modals/quick-create-issue.tsx
@@ -143,6 +143,7 @@ export function AgentCreatePanel({
const userId = useAuthStore((s) => s.user?.id);
const { data: members = [] } = useQuery(memberListOptions(wsId));
const { data: agents = [] } = useQuery(agentListOptions(wsId));
+ const { data: runtimes = [] } = useQuery(runtimeListOptions(wsId));
const { data: squads = [] } = useQuery(squadListOptions(wsId));
// Pull `isSuccess` so the stale-id sweep below can distinguish "still
// loading" from "loaded as empty". Reading length alone treats both as
@@ -166,9 +167,10 @@ export function AgentCreatePanel({
(a) =>
!a.archived_at &&
isAgentRuntimeBound(a) &&
+ !runtimes.some((r) => r.id === a.runtime_id && r.provider === "qoder_cloud") &&
canAssignAgent(a, userId, memberRole),
),
- [agents, userId, memberRole],
+ [agents, runtimes, userId, memberRole],
);
const visibleAgentIds = useMemo(
() => new Set(visibleAgents.map((a) => a.id)),
@@ -333,7 +335,6 @@ export function AgentCreatePanel({
// (git-describe shape) are exempted inside checkQuickCreateCliVersion
// — frontend and server share the same signal there, so they agree by
// construction across web/desktop/staging without comparing env flags.
- const { data: runtimes = [] } = useQuery(runtimeListOptions(wsId));
const selectedRuntime = useMemo(
() =>
selectedAgent?.runtime_id
diff --git a/packages/views/package.json b/packages/views/package.json
index 69c9fc0887..a67f3bb728 100644
--- a/packages/views/package.json
+++ b/packages/views/package.json
@@ -30,7 +30,8 @@
"./agents/agents-page": "./agents/components/agents-page.tsx",
"./agents/ai-builder-session-page": "./agents/create/ai-builder-session-page.tsx",
"./agents/ai-create-agent-page": "./agents/create/ai-create-agent-page.tsx",
- "./agents/choose-create-method-page": "./agents/create/choose-create-method-page.tsx",
+ "./agents/agent-created-page": "./agents/create/agent-created-page.tsx",
+ "./agents/choose-runtime-page": "./agents/create/choose-runtime-page.tsx",
"./agents/manual-create-agent-page": "./agents/create/manual-create-agent-page.tsx",
"./members": "./members/index.ts",
"./inbox": "./inbox/index.ts",
diff --git a/packages/views/runtimes/components/connect-remote-dialog.test.tsx b/packages/views/runtimes/components/connect-remote-dialog.test.tsx
index 56ddcadd6d..abebc7f089 100644
--- a/packages/views/runtimes/components/connect-remote-dialog.test.tsx
+++ b/packages/views/runtimes/components/connect-remote-dialog.test.tsx
@@ -142,7 +142,7 @@ describe("ConnectRemoteDialog", () => {
});
await waitFor(() => {
- expect(screen.getByText("Computer connected")).toBeInTheDocument();
+ expect(screen.getByText("Machine connected")).toBeInTheDocument();
expect(
screen.getByRole("button", { name: "Create an agent" }),
).toBeInTheDocument();
diff --git a/packages/views/runtimes/components/delete-runtime-dialog.tsx b/packages/views/runtimes/components/delete-runtime-dialog.tsx
index 065fb85ffb..f69f82b20c 100644
--- a/packages/views/runtimes/components/delete-runtime-dialog.tsx
+++ b/packages/views/runtimes/components/delete-runtime-dialog.tsx
@@ -587,7 +587,7 @@ function VisibilityCell({ visibility }: { visibility: string }) {
// Server response parsing
-interface ActiveAgentsConflict {
+export interface ActiveAgentsConflict {
code: "runtime_has_active_agents" | "runtime_delete_plan_changed";
activeAgents: Agent[];
}
@@ -595,7 +595,9 @@ interface ActiveAgentsConflict {
// parseActiveAgentsConflict pulls the structured 409 fields off an ApiError.
// Non-409s, non-active-agents codes, and missing bodies all collapse to
// `null` so callers can fall through to the generic error toast.
-function parseActiveAgentsConflict(err: unknown): ActiveAgentsConflict | null {
+export function parseActiveAgentsConflict(
+ err: unknown,
+): ActiveAgentsConflict | null {
if (!(err instanceof ApiError)) return null;
if (err.status !== 409) return null;
const body = err.body;
diff --git a/packages/views/runtimes/components/machine-cli-section.test.tsx b/packages/views/runtimes/components/machine-cli-section.test.tsx
index 85316523a5..01d8ad4f10 100644
--- a/packages/views/runtimes/components/machine-cli-section.test.tsx
+++ b/packages/views/runtimes/components/machine-cli-section.test.tsx
@@ -52,6 +52,7 @@ function machine(runtimes: AgentRuntime[]): RuntimeMachine {
daemonId: "daemon-1",
title: "dev.local",
subtitle: null,
+ deviceSummary: null,
deviceInfo: "dev.local",
cliVersion: "0.3.17",
launchedBy: launchedBy ?? null,
diff --git a/packages/views/runtimes/components/provider-logo.tsx b/packages/views/runtimes/components/provider-logo.tsx
index 3bfacf0c0e..28a7b7ebb0 100644
--- a/packages/views/runtimes/components/provider-logo.tsx
+++ b/packages/views/runtimes/components/provider-logo.tsx
@@ -426,6 +426,7 @@ export function ProviderLogo({
return <KiroLogo className={className} />;
case "qoder":
case "qoderclicn":
+ case "qoder_cloud":
return <QoderLogo className={className} />;
case "antigravity":
return <AntigravityLogo className={className} />;
diff --git a/packages/views/runtimes/components/qoder-configuration.test.tsx b/packages/views/runtimes/components/qoder-configuration.test.tsx
new file mode 100644
index 0000000000..2da91f2671
--- /dev/null
+++ b/packages/views/runtimes/components/qoder-configuration.test.tsx
@@ -0,0 +1,120 @@
+import { vi, it, expect, beforeEach, afterEach } from "vitest";
+import {
+ render,
+ screen,
+ fireEvent,
+ waitFor,
+ cleanup,
+} from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enRuntimes from "../../locales/en/runtimes.json";
+import { QoderConfiguration } from "./qoder-configuration";
+
+const mocks = vi.hoisted(() => ({
+ getQoderConnection: vi.fn(),
+ listMembers: vi.fn(),
+ listQoderEnvironments: vi.fn(),
+ checkQoderConnection: vi.fn(),
+ saveQoderConnection: vi.fn(),
+}));
+vi.mock("@multica/core/api", () => ({ api: mocks }));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-test" }));
+vi.mock("@multica/core/auth", () => {
+ const state = { user: { id: "owner" } };
+ return {
+ useAuthStore: Object.assign(
+ (selector: (s: typeof state) => unknown) => selector(state),
+ { getState: () => state },
+ ),
+ };
+});
+vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+
+beforeEach(() => {
+ mocks.getQoderConnection.mockResolvedValue({
+ available: true,
+ configured: true,
+ name: "QCA",
+ baseUrl: "https://api.qoder.com/api/v1/cloud",
+ environmentId: "",
+ hasToken: true,
+ repositories: [],
+ enabled: true,
+ status: "online",
+ lastError: "",
+ maxConcurrency: 3,
+ runTimeoutMinutes: 60,
+ activeRuns: 0,
+ queuedRuns: 0,
+ });
+ mocks.listMembers.mockResolvedValue([{ user_id: "owner", role: "owner" }]);
+ mocks.checkQoderConnection.mockResolvedValue(undefined);
+});
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+function mount(onConnected?: () => void) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ render(
+ <I18nProvider locale="en" resources={{ en: { runtimes: enRuntimes } }}>
+ <QueryClientProvider client={client}>
+ <QoderConfiguration onConnected={onConnected} />
+ </QueryClientProvider>
+ </I18nProvider>,
+ );
+ return client;
+}
+it("points an existing connection to its runtime page", async () => {
+ const client = mount();
+ expect(
+ await screen.findByText("Qoder connected. It will be ready in a few seconds."),
+ ).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Connect" })).not.toBeInTheDocument();
+ expect(mocks.listQoderEnvironments).not.toHaveBeenCalled();
+ client.clear();
+});
+it("connects a first-time workspace with the short form", async () => {
+ mocks.getQoderConnection.mockResolvedValue({
+ ...(await mocks.getQoderConnection()),
+ configured: false,
+ hasToken: false,
+ enabled: false,
+ status: "offline",
+ });
+ mocks.listQoderEnvironments.mockResolvedValue([]);
+ const client = mount();
+ expect(await screen.findByRole("button", { name: "Connect" })).toBeDisabled();
+ expect(screen.queryByRole("button", { name: "Test connection" })).not.toBeInTheDocument();
+ client.clear();
+});
+it("reports a first-time connection so the caller can close", async () => {
+ mocks.getQoderConnection.mockResolvedValue({
+ ...(await mocks.getQoderConnection()),
+ configured: false,
+ hasToken: false,
+ enabled: false,
+ status: "offline",
+ });
+ mocks.listQoderEnvironments.mockResolvedValue([
+ { id: "env_one", name: "Web environment" },
+ ]);
+ mocks.saveQoderConnection.mockResolvedValue(undefined);
+ const onConnected = vi.fn();
+ const client = mount(onConnected);
+ fireEvent.change(await screen.findByPlaceholderText("pt-…"), {
+ target: { value: "pt-test" },
+ });
+ const connect = screen.getByRole("button", { name: "Connect" });
+ await waitFor(() => expect(connect).toBeEnabled(), { timeout: 3000 });
+ fireEvent.click(connect);
+ await waitFor(() => expect(onConnected).toHaveBeenCalledTimes(1));
+ expect(mocks.saveQoderConnection).toHaveBeenCalledWith(
+ "ws-test",
+ expect.objectContaining({ environmentId: "env_one", qoderToken: "pt-test" }),
+ );
+ client.clear();
+});
diff --git a/packages/views/runtimes/components/qoder-configuration.tsx b/packages/views/runtimes/components/qoder-configuration.tsx
new file mode 100644
index 0000000000..43bda56da9
--- /dev/null
+++ b/packages/views/runtimes/components/qoder-configuration.tsx
@@ -0,0 +1,52 @@
+"use client";
+
+import { toast } from "sonner";
+import { useQuery } from "@tanstack/react-query";
+import { useAuthStore } from "@multica/core/auth";
+import { memberListOptions } from "@multica/core/workspace/queries";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { qoderOptions } from "@multica/core/runtimes/qoder";
+import { QoderConnectForm } from "./qoder-connect-form";
+import { useT } from "../../i18n";
+
+/**
+ * Connects the workspace to Qoder. An existing connection is managed section
+ * by section on the Qoder runtime page.
+ */
+export function QoderConfiguration({
+ onConnected,
+}: {
+ /** Called after a first-time connection succeeds. */
+ onConnected?: () => void;
+} = {}) {
+ const wsId = useWorkspaceId();
+ const query = useQuery(qoderOptions(wsId));
+ const { t } = useT("runtimes");
+ const user = useAuthStore((s) => s.user);
+ const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const member = members.find((m) => m.user_id === user?.id);
+ const canManage = member?.role === "owner" || member?.role === "admin";
+ if (query.isPending) return <p role="status">{t(($) => $.qoder.loading)}</p>;
+ if (query.isError) return <p role="alert">{query.error.message}</p>;
+ if (query.data?.available !== true)
+ return <p>{t(($) => $.qoder.unavailable)}</p>;
+ if (query.data.configured)
+ return <p role="status">{t(($) => $.qoder.connect.connected)}</p>;
+ if (!canManage)
+ return (
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.qoder.page.not_connected_hint)}
+ </p>
+ );
+ return (
+ <QoderConnectForm
+ wsId={wsId}
+ connection={query.data}
+ submitLabel={t(($) => $.qoder.connect.submit)}
+ onConnected={() => {
+ toast.success(t(($) => $.qoder.connect.connected));
+ onConnected?.();
+ }}
+ />
+ );
+}
diff --git a/packages/views/runtimes/components/qoder-connect-form.tsx b/packages/views/runtimes/components/qoder-connect-form.tsx
new file mode 100644
index 0000000000..ca5df0af47
--- /dev/null
+++ b/packages/views/runtimes/components/qoder-connect-form.tsx
@@ -0,0 +1,488 @@
+"use client";
+
+import { useEffect, useState, type ReactNode } from "react";
+import {
+ CheckCircle2,
+ ChevronRight,
+ CircleAlert,
+ FolderGit2,
+ Loader2,
+ Plug,
+ Settings2,
+ ShieldCheck,
+} from "lucide-react";
+import {
+ MAX_CONCURRENCY,
+ MAX_RUN_TIMEOUT,
+ MIN_RUN_TIMEOUT,
+ QODER_REGIONS,
+ useQoderEnvironments,
+ useSaveQoder,
+ type QoderConnection,
+ type QoderRegion,
+} from "@multica/core/runtimes/qoder";
+import { Button } from "@multica/ui/components/ui/button";
+import { Input } from "@multica/ui/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@multica/ui/components/ui/select";
+import { cn } from "@multica/ui/lib/utils";
+import { useT } from "../../i18n";
+
+const DEFAULT_NAME = "Qoder Cloud Agent";
+
+export function regionOf(baseUrl: string): QoderRegion {
+ return (
+ (Object.keys(QODER_REGIONS) as QoderRegion[]).find(
+ (key) => QODER_REGIONS[key] === baseUrl,
+ ) ?? "global"
+ );
+}
+
+export function RegionToggle({
+ value,
+ onChange,
+ disabled,
+ labelledBy,
+}: {
+ value: QoderRegion;
+ onChange: (region: QoderRegion) => void;
+ disabled?: boolean;
+ labelledBy: string;
+}) {
+ const { t } = useT("runtimes");
+ return (
+ <div
+ role="radiogroup"
+ aria-labelledby={labelledBy}
+ className="grid grid-cols-2 gap-0.5 rounded-lg bg-muted p-0.5"
+ >
+ {(["global", "cn"] as const).map((region) => (
+ <button
+ key={region}
+ type="button"
+ role="radio"
+ aria-checked={value === region}
+ disabled={disabled}
+ onClick={() => onChange(region)}
+ className={cn(
+ "truncate rounded-md px-2 py-1.5 text-caption text-muted-foreground transition-colors",
+ "hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ value === region && "bg-background font-medium text-foreground shadow-sm",
+ )}
+ >
+ {region === "global"
+ ? t(($) => $.qoder.region_global)
+ : t(($) => $.qoder.region_cn)}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+/**
+ * First-time Qoder connection: region, PAT and environment up front, the
+ * optional GitHub and execution settings folded away. Saving starts the
+ * managed runtime; editing an existing connection stays in
+ * QoderConfiguration.
+ */
+export function QoderConnectForm({
+ wsId,
+ connection,
+ submitLabel,
+ onConnected,
+}: {
+ wsId: string;
+ connection: QoderConnection;
+ submitLabel: string;
+ onConnected?: () => void;
+}) {
+ const { t } = useT("runtimes");
+ const save = useSaveQoder(wsId);
+ const environments = useQoderEnvironments(wsId);
+ const { mutate: loadEnvironments, reset: resetEnvironments } = environments;
+
+ const [region, setRegion] = useState<QoderRegion>(() =>
+ regionOf(connection.baseUrl),
+ );
+ const [token, setToken] = useState("");
+ const [environmentId, setEnvironmentId] = useState("");
+ const [showRepos, setShowRepos] = useState(false);
+ const [repos, setRepos] = useState<{ url: string; token: string }[]>([]);
+ const [showExecution, setShowExecution] = useState(false);
+ const [maxConcurrency, setMaxConcurrency] = useState(
+ connection.maxConcurrency,
+ );
+ const [runTimeoutMinutes, setRunTimeoutMinutes] = useState(
+ connection.runTimeoutMinutes,
+ );
+
+ const baseUrl = QODER_REGIONS[region];
+ const trimmedToken = token.trim();
+
+ useEffect(() => {
+ resetEnvironments();
+ setEnvironmentId("");
+ if (!trimmedToken) return;
+ const controller = new AbortController();
+ const timer = setTimeout(() => {
+ loadEnvironments(
+ { token: trimmedToken, baseUrl, signal: controller.signal },
+ {
+ onSuccess: (items) => {
+ if (controller.signal.aborted) return;
+ if (items.length === 1) setEnvironmentId(items[0]!.id);
+ },
+ },
+ );
+ }, 600);
+ return () => {
+ clearTimeout(timer);
+ controller.abort();
+ };
+ }, [trimmedToken, baseUrl, loadEnvironments, resetEnvironments]);
+
+ const environmentValid =
+ !!environmentId &&
+ environments.data?.some((item) => item.id === environmentId) === true;
+ const reposValid = repos.every(
+ (row) => row.url.trim().length > 0 && row.token.trim().length > 0,
+ );
+ const limitsValid =
+ maxConcurrency >= 1 &&
+ maxConcurrency <= MAX_CONCURRENCY &&
+ runTimeoutMinutes >= MIN_RUN_TIMEOUT &&
+ runTimeoutMinutes <= MAX_RUN_TIMEOUT;
+ const canSubmit =
+ environmentValid && reposValid && limitsValid && !save.isPending;
+ const otherRegion: QoderRegion = region === "cn" ? "global" : "cn";
+
+ const submit = async () => {
+ if (!canSubmit) return;
+ try {
+ await save.mutateAsync({
+ name: connection.name || DEFAULT_NAME,
+ baseUrl,
+ environmentId,
+ qoderToken: trimmedToken,
+ githubTokens: Object.fromEntries(
+ repos.map((row) => [row.url.trim(), row.token.trim()]),
+ ),
+ maxConcurrency,
+ runTimeoutMinutes,
+ });
+ setToken("");
+ onConnected?.();
+ } catch {
+ /* Mutation error is rendered below. */
+ }
+ };
+
+ return (
+ <form
+ className="flex min-h-0 flex-1 flex-col gap-5"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void submit();
+ }}
+ >
+ <div className="space-y-2">
+ <p id="qoder-connect-region" className="text-caption font-medium">
+ {t(($) => $.qoder.region)}
+ </p>
+ <RegionToggle
+ value={region}
+ onChange={setRegion}
+ disabled={save.isPending}
+ labelledBy="qoder-connect-region"
+ />
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.qoder.region_hint)}
+ </p>
+ </div>
+
+ <label className="block space-y-2">
+ <span className="block text-caption font-medium">
+ {t(($) => $.qoder.connect.token)}
+ </span>
+ <Input
+ type="password"
+ autoComplete="new-password"
+ value={token}
+ // eslint-disable-next-line no-restricted-syntax -- Qoder token prefix
+ placeholder="pt-…"
+ aria-invalid={environments.isError}
+ disabled={save.isPending}
+ className="font-mono"
+ onChange={(event) => setToken(event.target.value)}
+ />
+ </label>
+ {environments.isError ? (
+ <div className="-mt-3 space-y-2">
+ <p
+ role="alert"
+ className="flex items-start gap-1.5 text-caption text-destructive"
+ >
+ <CircleAlert aria-hidden="true" className="mt-0.5 size-3.5 shrink-0" />
+ <span className="min-w-0 break-words">
+ {t(($) => $.qoder.connect.token_rejected, {
+ region:
+ region === "global"
+ ? t(($) => $.qoder.region_global)
+ : t(($) => $.qoder.region_cn),
+ })}
+ </span>
+ </p>
+ <Button
+ type="button"
+ size="xs"
+ variant="outline"
+ onClick={() => setRegion(otherRegion)}
+ >
+ {otherRegion === "cn"
+ ? t(($) => $.qoder.connect.retry_cn)
+ : t(($) => $.qoder.connect.retry_global)}
+ </Button>
+ </div>
+ ) : null}
+
+ <div className="space-y-2">
+ <p id="qoder-connect-environment" className="text-caption font-medium">
+ {t(($) => $.qoder.environment)}
+ </p>
+ {environments.isPending ? (
+ <div
+ role="status"
+ className="flex h-9 items-center gap-2 rounded-lg border bg-muted/30 px-3 text-caption text-muted-foreground"
+ >
+ <Loader2 aria-hidden="true" className="size-3.5 animate-spin" />
+ {t(($) => $.qoder.connect.verifying)}
+ </div>
+ ) : environments.isSuccess && environments.data.length > 1 ? (
+ <Select
+ items={environments.data.map((item) => ({
+ value: item.id,
+ label: item.name,
+ }))}
+ value={environmentId || null}
+ onValueChange={(value) => setEnvironmentId(value ?? "")}
+ disabled={save.isPending}
+ >
+ <SelectTrigger
+ className="w-full"
+ aria-labelledby="qoder-connect-environment"
+ >
+ <SelectValue placeholder={t(($) => $.qoder.select_environment)} />
+ </SelectTrigger>
+ <SelectContent alignItemWithTrigger={false}>
+ {environments.data.map((item) => (
+ <SelectItem key={item.id} value={item.id}>
+ {item.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : environments.isSuccess && environments.data.length === 1 ? (
+ <div className="flex h-9 items-center gap-2 rounded-lg border px-3 text-body">
+ <span className="min-w-0 flex-1 truncate">
+ {environments.data[0]!.name}
+ </span>
+ <span className="inline-flex shrink-0 items-center gap-1 text-caption text-success">
+ <CheckCircle2 aria-hidden="true" className="size-3.5" />
+ {t(($) => $.qoder.connect.verified)}
+ </span>
+ </div>
+ ) : (
+ <div className="flex h-9 items-center rounded-lg border bg-muted/30 px-3 text-caption text-muted-foreground">
+ {environments.isSuccess
+ ? t(($) => $.qoder.no_environments)
+ : t(($) => $.qoder.connect.environment_waiting)}
+ </div>
+ )}
+ </div>
+
+ <div className="divide-y rounded-lg border">
+ <Disclosure
+ icon={FolderGit2}
+ title={t(($) => $.qoder.repositories)}
+ summary={
+ repos.length > 0
+ ? t(($) => $.qoder.connect.repo_count, { count: repos.length })
+ : t(($) => $.qoder.connect.optional)
+ }
+ open={showRepos}
+ onToggle={() => setShowRepos((open) => !open)}
+ >
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.qoder.repositories_hint)}
+ </p>
+ {repos.map((row, index) => (
+ <div key={index} className="space-y-2 rounded-md bg-muted/40 p-2.5">
+ <Input
+ type="url"
+ value={row.url}
+ aria-label={t(($) => $.qoder.github_url)}
+ placeholder="https://github.com/org/repo"
+ disabled={save.isPending}
+ onChange={(event) =>
+ setRepos((old) =>
+ old.map((r, i) =>
+ i === index ? { ...r, url: event.target.value } : r,
+ ),
+ )
+ }
+ />
+ <Input
+ type="password"
+ autoComplete="new-password"
+ value={row.token}
+ aria-label={t(($) => $.qoder.github_token)}
+ placeholder={t(($) => $.qoder.github_token)}
+ disabled={save.isPending}
+ onChange={(event) =>
+ setRepos((old) =>
+ old.map((r, i) =>
+ i === index ? { ...r, token: event.target.value } : r,
+ ),
+ )
+ }
+ />
+ <Button
+ type="button"
+ size="xs"
+ variant="ghost"
+ disabled={save.isPending}
+ onClick={() =>
+ setRepos((old) => old.filter((_, i) => i !== index))
+ }
+ >
+ {t(($) => $.qoder.remove)}
+ </Button>
+ </div>
+ ))}
+ <Button
+ type="button"
+ size="xs"
+ variant="outline"
+ disabled={save.isPending}
+ onClick={() => setRepos((old) => [...old, { url: "", token: "" }])}
+ >
+ {t(($) => $.qoder.add_repository)}
+ </Button>
+ </Disclosure>
+ <Disclosure
+ icon={Settings2}
+ title={t(($) => $.qoder.execution)}
+ summary={t(($) => $.qoder.connect.execution_summary, {
+ concurrency: maxConcurrency,
+ timeout: runTimeoutMinutes,
+ })}
+ open={showExecution}
+ onToggle={() => setShowExecution((open) => !open)}
+ >
+ <div className="grid grid-cols-2 gap-3">
+ <label className="block space-y-1 text-caption">
+ {t(($) => $.qoder.concurrency)}
+ <Input
+ type="number"
+ inputMode="numeric"
+ min={1}
+ max={MAX_CONCURRENCY}
+ value={maxConcurrency}
+ disabled={save.isPending}
+ onChange={(event) =>
+ setMaxConcurrency(event.target.valueAsNumber || 0)
+ }
+ />
+ </label>
+ <label className="block space-y-1 text-caption">
+ {t(($) => $.qoder.run_timeout)}
+ <Input
+ type="number"
+ inputMode="numeric"
+ min={MIN_RUN_TIMEOUT}
+ max={MAX_RUN_TIMEOUT}
+ step={5}
+ value={runTimeoutMinutes}
+ disabled={save.isPending}
+ onChange={(event) =>
+ setRunTimeoutMinutes(event.target.valueAsNumber || 0)
+ }
+ />
+ </label>
+ </div>
+ </Disclosure>
+ </div>
+
+ <div className="flex items-start gap-2 rounded-lg bg-muted/50 p-3 text-caption text-muted-foreground">
+ <ShieldCheck aria-hidden="true" className="mt-0.5 size-3.5 shrink-0" />
+ <p className="leading-relaxed">
+ {t(($) => $.qoder.data_disclosure)}{" "}
+ {t(($) => $.qoder.shared_credentials_hint)}
+ </p>
+ </div>
+
+ {save.error ? (
+ <p role="alert" className="text-caption text-destructive">
+ {save.error.message}
+ </p>
+ ) : null}
+
+ <div className="mt-auto space-y-2">
+ <Button type="submit" className="w-full" disabled={!canSubmit}>
+ {save.isPending ? (
+ <Loader2 aria-hidden="true" className="size-4 animate-spin" />
+ ) : (
+ <Plug aria-hidden="true" className="size-4" />
+ )}
+ {save.isPending ? t(($) => $.qoder.working) : submitLabel}
+ </Button>
+ </div>
+ </form>
+ );
+}
+
+function Disclosure({
+ icon: Icon,
+ title,
+ summary,
+ open,
+ onToggle,
+ children,
+}: {
+ icon: typeof Settings2;
+ title: string;
+ summary: string;
+ open: boolean;
+ onToggle: () => void;
+ children: ReactNode;
+}) {
+ return (
+ <div>
+ <button
+ type="button"
+ aria-expanded={open}
+ onClick={onToggle}
+ className="flex w-full items-center gap-2 px-3 py-2.5 text-left transition-colors hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
+ >
+ <Icon aria-hidden="true" className="size-3.5 text-muted-foreground" />
+ <span className="flex-1 text-label font-medium">{title}</span>
+ <span className="truncate text-caption tabular-nums text-muted-foreground">
+ {summary}
+ </span>
+ <ChevronRight
+ aria-hidden="true"
+ className={cn(
+ "size-3.5 shrink-0 text-muted-foreground transition-transform",
+ open && "rotate-90",
+ )}
+ />
+ </button>
+ {open ? <div className="space-y-3 px-3 pb-3">{children}</div> : null}
+ </div>
+ );
+}
diff --git a/packages/views/runtimes/components/qoder-connection-cards.tsx b/packages/views/runtimes/components/qoder-connection-cards.tsx
new file mode 100644
index 0000000000..778159abd4
--- /dev/null
+++ b/packages/views/runtimes/components/qoder-connection-cards.tsx
@@ -0,0 +1,1028 @@
+"use client";
+
+import { useCallback, useEffect, useState, type ReactNode } from "react";
+import {
+ ExternalLink,
+ FolderGit2,
+ KeyRound,
+ Loader2,
+ MoreHorizontal,
+ Pencil,
+ Plus,
+ RefreshCw,
+ ShieldCheck,
+ Trash2,
+} from "lucide-react";
+import { toast } from "sonner";
+import {
+ MAX_CONCURRENCY,
+ MAX_RUN_TIMEOUT,
+ MIN_RUN_TIMEOUT,
+ QODER_REGIONS,
+ useCheckQoder,
+ useQoderEnvironments,
+ useSaveQoder,
+ type QoderConnection,
+ type QoderInput,
+} from "@multica/core/runtimes/qoder";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import { DeferredTooltip } from "@multica/ui/components/common/deferred-tooltip";
+import { IconButton } from "@multica/ui/components/common/icon-button";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { Input } from "@multica/ui/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@multica/ui/components/ui/popover";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@multica/ui/components/ui/select";
+import { cn } from "@multica/ui/lib/utils";
+import { openExternal } from "../../platform";
+import { useT } from "../../i18n";
+import { regionOf, RegionToggle } from "./qoder-connect-form";
+
+/**
+ * The saved connection as a save payload. A blank token and omitted
+ * repositories keep what the server already stores.
+ */
+export function savedQoderInput(
+ data: QoderConnection,
+ fallbackName: string,
+): QoderInput {
+ return {
+ name: data.name || fallbackName,
+ baseUrl: data.baseUrl || QODER_REGIONS.global,
+ environmentId: data.environmentId,
+ qoderToken: "",
+ maxConcurrency: data.maxConcurrency,
+ runTimeoutMinutes: data.runTimeoutMinutes,
+ };
+}
+
+/** Keeps every saved repository token except the ones in `change`. */
+function repositoryTokens(
+ repositories: string[],
+ change: Record<string, string | null>,
+): Record<string, string> {
+ const tokens: Record<string, string> = {};
+ for (const url of repositories) tokens[url] = "";
+ for (const [url, token] of Object.entries(change)) {
+ if (token === null) delete tokens[url];
+ else tokens[url] = token;
+ }
+ return tokens;
+}
+
+/** Matches the server's repository key, so a re-added repository replaces its token. */
+function repositoryKey(url: string): string {
+ return url
+ .trim()
+ .replace(/\/+$/, "")
+ .replace(/\.git$/, "")
+ .toLowerCase();
+}
+
+function repositoryLabel(url: string): string {
+ return url.replace(/^https:\/\/github\.com\//, "");
+}
+
+export function QoderSection({
+ title,
+ count,
+ actions,
+ footer,
+ className,
+ titleClassName,
+ children,
+}: {
+ title: string;
+ count?: number;
+ actions?: ReactNode;
+ footer?: ReactNode;
+ className?: string;
+ titleClassName?: string;
+ children: ReactNode;
+}) {
+ return (
+ <section className={cn("rounded-lg border bg-card", className)}>
+ <div className="flex min-h-10 items-center gap-2 border-b py-1.5 pl-4 pr-2">
+ <h2 className={cn("text-caption font-semibold", titleClassName)}>
+ {title}
+ </h2>
+ {count !== undefined && (
+ <span className="text-caption tabular-nums text-muted-foreground">
+ {count}
+ </span>
+ )}
+ {actions && (
+ <div className="ml-auto flex items-center gap-1.5">{actions}</div>
+ )}
+ </div>
+ {children}
+ {footer && (
+ <div className="border-t px-4 py-2.5 text-caption text-muted-foreground">
+ {footer}
+ </div>
+ )}
+ </section>
+ );
+}
+
+function Fact({ label, children }: { label: string; children: ReactNode }) {
+ return (
+ <div className="min-w-0 px-4 py-3">
+ <dt className="text-micro uppercase tracking-wider text-muted-foreground">
+ {label}
+ </dt>
+ <dd className="mt-1 truncate text-body">{children}</dd>
+ </div>
+ );
+}
+
+export function QoderConnectionCard({
+ wsId,
+ data,
+ canManage,
+}: {
+ wsId: string;
+ data: QoderConnection;
+ canManage: boolean;
+}) {
+ const { t } = useT("runtimes");
+ const check = useCheckQoder(wsId);
+ const environments = useQoderEnvironments(wsId);
+ const { mutate: loadEnvironments } = environments;
+ const [editing, setEditing] = useState(false);
+
+ // Names come from Qoder with the saved token, which only admins may use.
+ useEffect(() => {
+ if (!canManage || !data.hasToken) return;
+ const controller = new AbortController();
+ loadEnvironments({
+ token: "",
+ baseUrl: data.baseUrl,
+ signal: controller.signal,
+ });
+ return () => controller.abort();
+ }, [canManage, data.hasToken, data.baseUrl, data.environmentId, loadEnvironments]);
+
+ const environmentName =
+ environments.data?.find((item) => item.id === data.environmentId)?.name ??
+ data.environmentId;
+ const region =
+ regionOf(data.baseUrl) === "cn"
+ ? t(($) => $.qoder.region_cn)
+ : t(($) => $.qoder.region_global);
+
+ const test = () =>
+ check.mutate(savedQoderInput(data, t(($) => $.qoder.cloud_title)), {
+ onSuccess: () => toast.success(t(($) => $.qoder.check_passed)),
+ onError: (err) =>
+ toast.error(t(($) => $.qoder.check_failed), {
+ description: err.message,
+ }),
+ });
+
+ return (
+ <QoderSection
+ title={t(($) => $.qoder.page.connection_title)}
+ actions={
+ canManage ? (
+ <>
+ <Button
+ size="xs"
+ variant="outline"
+ disabled={check.isPending}
+ aria-busy={check.isPending}
+ onClick={test}
+ >
+ {check.isPending && (
+ <Loader2 aria-hidden="true" className="animate-spin" />
+ )}
+ {t(($) => $.qoder.check)}
+ </Button>
+ <Button size="xs" variant="outline" onClick={() => setEditing(true)}>
+ <Pencil aria-hidden="true" />
+ {t(($) => $.qoder.page.edit)}
+ </Button>
+ </>
+ ) : null
+ }
+ footer={<DataDisclosure />}
+ >
+ <dl className="grid grid-cols-1 divide-y sm:grid-cols-3 sm:divide-x sm:divide-y-0">
+ <Fact label={t(($) => $.qoder.region)}>{region}</Fact>
+ <Fact label={t(($) => $.qoder.environment)}>{environmentName}</Fact>
+ <Fact label={t(($) => $.qoder.connect.token)}>
+ <span className="inline-flex items-center gap-1.5">
+ <KeyRound
+ aria-hidden="true"
+ className="size-3.5 text-muted-foreground"
+ />
+ {data.hasToken ? t(($) => $.qoder.page.token_saved) : "—"}
+ </span>
+ </Fact>
+ </dl>
+ {editing && (
+ <EditConnectionDialog
+ wsId={wsId}
+ data={data}
+ onClose={() => setEditing(false)}
+ />
+ )}
+ </QoderSection>
+ );
+}
+
+function DataDisclosure() {
+ const { t } = useT("runtimes");
+ return (
+ <Popover>
+ <PopoverTrigger
+ render={
+ <button
+ type="button"
+ className="inline-flex items-center gap-1.5 rounded-sm transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ />
+ }
+ >
+ <ShieldCheck aria-hidden="true" className="size-3.5" />
+ {t(($) => $.qoder.data_disclosure_title)}
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-80 text-caption leading-relaxed">
+ {t(($) => $.qoder.data_disclosure)}
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+function EditConnectionDialog({
+ wsId,
+ data,
+ onClose,
+}: {
+ wsId: string;
+ data: QoderConnection;
+ onClose: () => void;
+}) {
+ const { t } = useT("runtimes");
+ const save = useSaveQoder(wsId);
+ const check = useCheckQoder(wsId);
+ const environments = useQoderEnvironments(wsId);
+ const { mutate: loadEnvironments, reset: resetEnvironments } = environments;
+ const savedRegion = regionOf(data.baseUrl);
+ const [name, setName] = useState(
+ data.name || t(($) => $.qoder.cloud_title),
+ );
+ const [region, setRegion] = useState(savedRegion);
+ const [token, setToken] = useState("");
+ const [environmentId, setEnvironmentId] = useState(data.environmentId);
+
+ const baseUrl = QODER_REGIONS[region];
+ const trimmedToken = token.trim();
+ // A token only works on the site that issued it.
+ const needsToken = region !== savedRegion || !data.hasToken;
+ const canLoad = !!trimmedToken || !needsToken;
+ const busy = save.isPending || check.isPending;
+
+ const load = useCallback(
+ (signal?: AbortSignal) =>
+ loadEnvironments(
+ { token: trimmedToken, baseUrl, signal },
+ {
+ onSuccess: (items) => {
+ if (signal?.aborted) return;
+ setEnvironmentId((current) =>
+ items.some((item) => item.id === current)
+ ? current
+ : items.length === 1
+ ? items[0]!.id
+ : "",
+ );
+ },
+ },
+ ),
+ [loadEnvironments, trimmedToken, baseUrl],
+ );
+
+ useEffect(() => {
+ resetEnvironments();
+ if (!canLoad) return;
+ const controller = new AbortController();
+ const timer = setTimeout(
+ () => load(controller.signal),
+ trimmedToken ? 600 : 0,
+ );
+ return () => {
+ clearTimeout(timer);
+ controller.abort();
+ };
+ }, [canLoad, load, resetEnvironments, trimmedToken]);
+
+ const environmentValid =
+ environments.data?.some((item) => item.id === environmentId) === true;
+ const canSubmit =
+ environmentValid && !!name.trim() && canLoad && !busy;
+
+ const submit = async () => {
+ if (!canSubmit) return;
+ const input: QoderInput = {
+ ...savedQoderInput(data, name.trim()),
+ name: name.trim(),
+ baseUrl,
+ environmentId,
+ qoderToken: trimmedToken,
+ };
+ try {
+ await check.mutateAsync(input);
+ await save.mutateAsync(input);
+ toast.success(t(($) => $.qoder.saved));
+ onClose();
+ } catch {
+ /* The error is rendered in the dialog. */
+ }
+ };
+
+ const error = check.error ?? save.error;
+
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open && !busy) onClose();
+ }}
+ >
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>{t(($) => $.qoder.page.edit_connection_title)}</DialogTitle>
+ <DialogDescription>
+ {t(($) => $.qoder.page.edit_connection_hint)}
+ </DialogDescription>
+ </DialogHeader>
+ <form
+ className="space-y-4"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void submit();
+ }}
+ >
+ <label className="block space-y-1.5">
+ <span className="block text-caption font-medium">
+ {t(($) => $.qoder.name)}
+ </span>
+ <Input
+ value={name}
+ required
+ disabled={busy}
+ onChange={(event) => setName(event.target.value)}
+ />
+ </label>
+ <div className="space-y-1.5">
+ <p id="qoder-edit-region" className="text-caption font-medium">
+ {t(($) => $.qoder.region)}
+ </p>
+ <RegionToggle
+ value={region}
+ onChange={(next) => {
+ setRegion(next);
+ check.reset();
+ save.reset();
+ }}
+ disabled={busy}
+ labelledBy="qoder-edit-region"
+ />
+ </div>
+ <label className="block space-y-1.5">
+ <span className="block text-caption font-medium">
+ {t(($) => $.qoder.connect.token)}
+ </span>
+ <Input
+ type="password"
+ autoComplete="new-password"
+ value={token}
+ required={needsToken}
+ placeholder={
+ needsToken ? "pt-…" : t(($) => $.qoder.keep_secret)
+ }
+ disabled={busy}
+ className="font-mono"
+ onChange={(event) => {
+ setToken(event.target.value);
+ check.reset();
+ save.reset();
+ }}
+ />
+ {region !== savedRegion && (
+ <span className="block text-caption text-muted-foreground">
+ {t(($) => $.qoder.region_hint)}
+ </span>
+ )}
+ </label>
+ <div className="space-y-1.5">
+ <p id="qoder-edit-environment" className="text-caption font-medium">
+ {t(($) => $.qoder.environment)}
+ </p>
+ <div className="flex items-center gap-2">
+ <Select
+ items={
+ environments.data?.map((item) => ({
+ value: item.id,
+ label: item.name,
+ })) ?? []
+ }
+ value={environmentId || null}
+ onValueChange={(value) => {
+ setEnvironmentId(value ?? "");
+ check.reset();
+ save.reset();
+ }}
+ disabled={busy || !environments.data?.length}
+ >
+ <SelectTrigger
+ className="min-w-0 flex-1"
+ aria-labelledby="qoder-edit-environment"
+ >
+ <SelectValue
+ placeholder={t(($) => $.qoder.select_environment)}
+ />
+ </SelectTrigger>
+ <SelectContent alignItemWithTrigger={false}>
+ {environments.data?.map((item) => (
+ <SelectItem key={item.id} value={item.id}>
+ {item.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <IconButton
+ type="button"
+ size="icon"
+ variant="outline"
+ label={t(($) => $.qoder.refresh_catalog)}
+ disabled={busy || !canLoad || environments.isPending}
+ onClick={() => load()}
+ >
+ <RefreshCw
+ aria-hidden="true"
+ className={cn(environments.isPending && "animate-spin")}
+ />
+ </IconButton>
+ </div>
+ {!canLoad ? (
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.qoder.connect.environment_waiting)}
+ </p>
+ ) : environments.isError ? (
+ <p role="alert" className="text-caption text-destructive">
+ {environments.error.message}
+ </p>
+ ) : environments.isSuccess && !environments.data.length ? (
+ <p role="status" className="text-caption text-muted-foreground">
+ {t(($) => $.qoder.no_environments)}
+ </p>
+ ) : null}
+ </div>
+ {error && (
+ <p role="alert" className="text-caption text-destructive">
+ {error.message}
+ </p>
+ )}
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ disabled={busy}
+ onClick={onClose}
+ >
+ {t(($) => $.qoder.cancel)}
+ </Button>
+ <Button type="submit" disabled={!canSubmit} aria-busy={busy}>
+ {busy && <Loader2 aria-hidden="true" className="animate-spin" />}
+ {busy
+ ? t(($) => $.qoder.checking)
+ : t(($) => $.qoder.page.test_and_save)}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+export function QoderRepositoriesCard({
+ wsId,
+ data,
+ canManage,
+}: {
+ wsId: string;
+ data: QoderConnection;
+ canManage: boolean;
+}) {
+ const { t } = useT("runtimes");
+ const [editing, setEditing] = useState<{ url: string | null } | null>(null);
+ const [removing, setRemoving] = useState<string | null>(null);
+ const repositories = data.repositories;
+
+ return (
+ <QoderSection
+ title={t(($) => $.qoder.repositories)}
+ count={repositories.length || undefined}
+ actions={
+ canManage ? (
+ <Button
+ size="xs"
+ variant="outline"
+ onClick={() => setEditing({ url: null })}
+ >
+ <Plus aria-hidden="true" />
+ {t(($) => $.qoder.add_repository)}
+ </Button>
+ ) : null
+ }
+ footer={
+ repositories.length > 0
+ ? t(($) => $.qoder.page.repositories_hint)
+ : undefined
+ }
+ >
+ {repositories.length === 0 ? (
+ <p className="px-4 py-6 text-center text-caption text-muted-foreground">
+ {t(($) => $.qoder.page.repositories_hint)}
+ </p>
+ ) : (
+ <ul className="divide-y">
+ {repositories.map((url) => (
+ <li key={url} className="flex items-center gap-3 py-2 pl-4 pr-2">
+ <span className="flex size-7 shrink-0 items-center justify-center rounded-md border bg-background text-muted-foreground">
+ <FolderGit2 aria-hidden="true" className="size-3.5" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-label font-medium">
+ {repositoryLabel(url)}
+ </p>
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.qoder.page.repo_token_saved)}
+ </p>
+ </div>
+ {canManage && (
+ <DropdownMenu>
+ <DeferredTooltip
+ content={t(($) => $.qoder.page.repo_actions, {
+ repo: repositoryLabel(url),
+ })}
+ trigger={
+ <DropdownMenuTrigger
+ render={
+ <Button
+ size="icon-sm"
+ variant="ghost"
+ aria-label={t(($) => $.qoder.page.repo_actions, {
+ repo: repositoryLabel(url),
+ })}
+ className="text-muted-foreground"
+ >
+ <MoreHorizontal aria-hidden="true" />
+ </Button>
+ }
+ />
+ }
+ />
+ <DropdownMenuContent align="end" className="w-44">
+ <DropdownMenuItem onClick={() => setEditing({ url })}>
+ <KeyRound aria-hidden="true" className="size-3.5" />
+ {t(($) => $.qoder.page.replace_token)}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => openExternal(url)}>
+ <ExternalLink aria-hidden="true" className="size-3.5" />
+ {t(($) => $.qoder.page.open_on_github)}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => setRemoving(url)}
+ >
+ <Trash2 aria-hidden="true" className="size-3.5" />
+ {t(($) => $.qoder.remove)}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </li>
+ ))}
+ </ul>
+ )}
+ {editing && (
+ <RepositoryDialog
+ wsId={wsId}
+ data={data}
+ url={editing.url}
+ onClose={() => setEditing(null)}
+ />
+ )}
+ {removing && (
+ <RemoveRepositoryDialog
+ wsId={wsId}
+ data={data}
+ url={removing}
+ onClose={() => setRemoving(null)}
+ />
+ )}
+ </QoderSection>
+ );
+}
+
+/** Adds a repository, or replaces the token of `url` when given. */
+function RepositoryDialog({
+ wsId,
+ data,
+ url: fixedUrl,
+ onClose,
+}: {
+ wsId: string;
+ data: QoderConnection;
+ url: string | null;
+ onClose: () => void;
+}) {
+ const { t } = useT("runtimes");
+ const save = useSaveQoder(wsId);
+ const [url, setUrl] = useState(fixedUrl ?? "");
+ const [token, setToken] = useState("");
+ const canSubmit = !!url.trim() && !!token.trim() && !save.isPending;
+
+ const submit = async () => {
+ if (!canSubmit) return;
+ const key =
+ data.repositories.find((saved) => saved === repositoryKey(url)) ??
+ url.trim();
+ try {
+ await save.mutateAsync({
+ ...savedQoderInput(data, t(($) => $.qoder.cloud_title)),
+ githubTokens: repositoryTokens(data.repositories, {
+ [key]: token.trim(),
+ }),
+ });
+ onClose();
+ } catch {
+ /* The error is rendered in the dialog. */
+ }
+ };
+
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open && !save.isPending) onClose();
+ }}
+ >
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>
+ {fixedUrl
+ ? t(($) => $.qoder.page.replace_token_title, {
+ repo: repositoryLabel(fixedUrl),
+ })
+ : t(($) => $.qoder.add_repository)}
+ </DialogTitle>
+ <DialogDescription>
+ {t(($) => $.qoder.page.repositories_hint)}
+ </DialogDescription>
+ </DialogHeader>
+ <form
+ className="space-y-4"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void submit();
+ }}
+ >
+ {!fixedUrl && (
+ <label className="block space-y-1.5">
+ <span className="block text-caption font-medium">
+ {t(($) => $.qoder.github_url)}
+ </span>
+ <Input
+ type="url"
+ required
+ value={url}
+ placeholder="https://github.com/org/repo"
+ disabled={save.isPending}
+ onChange={(event) => {
+ setUrl(event.target.value);
+ save.reset();
+ }}
+ />
+ </label>
+ )}
+ <label className="block space-y-1.5">
+ <span className="block text-caption font-medium">
+ {t(($) => $.qoder.github_token)}
+ </span>
+ <Input
+ type="password"
+ autoComplete="new-password"
+ required
+ value={token}
+ disabled={save.isPending}
+ className="font-mono"
+ onChange={(event) => {
+ setToken(event.target.value);
+ save.reset();
+ }}
+ />
+ </label>
+ {save.error && (
+ <p role="alert" className="text-caption text-destructive">
+ {save.error.message}
+ </p>
+ )}
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ disabled={save.isPending}
+ onClick={onClose}
+ >
+ {t(($) => $.qoder.cancel)}
+ </Button>
+ <Button
+ type="submit"
+ disabled={!canSubmit}
+ aria-busy={save.isPending}
+ >
+ {save.isPending && (
+ <Loader2 aria-hidden="true" className="animate-spin" />
+ )}
+ {t(($) => $.qoder.page.save)}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function RemoveRepositoryDialog({
+ wsId,
+ data,
+ url,
+ onClose,
+}: {
+ wsId: string;
+ data: QoderConnection;
+ url: string;
+ onClose: () => void;
+}) {
+ const { t } = useT("runtimes");
+ const save = useSaveQoder(wsId);
+ return (
+ <AlertDialog
+ open
+ onOpenChange={(open) => {
+ if (!open && !save.isPending) onClose();
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $.qoder.page.remove_repository_title, {
+ repo: repositoryLabel(url),
+ })}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $.qoder.page.remove_repository_description)}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={save.isPending}>
+ {t(($) => $.qoder.cancel)}
+ </AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ disabled={save.isPending}
+ aria-busy={save.isPending}
+ onClick={() =>
+ save.mutate(
+ {
+ ...savedQoderInput(data, t(($) => $.qoder.cloud_title)),
+ githubTokens: repositoryTokens(data.repositories, {
+ [url]: null,
+ }),
+ },
+ {
+ onSuccess: onClose,
+ onError: (err) => toast.error(err.message),
+ },
+ )
+ }
+ >
+ {t(($) => $.qoder.remove)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
+
+export function QoderLimitsCard({
+ wsId,
+ data,
+ canManage,
+}: {
+ wsId: string;
+ data: QoderConnection;
+ canManage: boolean;
+}) {
+ const { t } = useT("runtimes");
+ const [editing, setEditing] = useState(false);
+ return (
+ <QoderSection
+ title={t(($) => $.qoder.execution)}
+ actions={
+ canManage ? (
+ <IconButton
+ label={t(($) => $.qoder.page.edit_limits)}
+ className="text-muted-foreground"
+ onClick={() => setEditing(true)}
+ >
+ <Pencil aria-hidden="true" />
+ </IconButton>
+ ) : null
+ }
+ >
+ <dl className="divide-y text-body">
+ <div className="flex items-center gap-3 px-4 py-2.5">
+ <dt className="flex-1 text-muted-foreground">
+ {t(($) => $.qoder.concurrency)}
+ </dt>
+ <dd className="tabular-nums">{data.maxConcurrency}</dd>
+ </div>
+ <div className="flex items-center gap-3 px-4 py-2.5">
+ <dt className="flex-1 text-muted-foreground">
+ {t(($) => $.qoder.page.run_timeout)}
+ </dt>
+ <dd className="tabular-nums">
+ {t(($) => $.qoder.page.minutes, { count: data.runTimeoutMinutes })}
+ </dd>
+ </div>
+ </dl>
+ {editing && (
+ <LimitsDialog wsId={wsId} data={data} onClose={() => setEditing(false)} />
+ )}
+ </QoderSection>
+ );
+}
+
+function LimitsDialog({
+ wsId,
+ data,
+ onClose,
+}: {
+ wsId: string;
+ data: QoderConnection;
+ onClose: () => void;
+}) {
+ const { t } = useT("runtimes");
+ const save = useSaveQoder(wsId);
+ const [maxConcurrency, setMaxConcurrency] = useState(data.maxConcurrency);
+ const [runTimeoutMinutes, setRunTimeoutMinutes] = useState(
+ data.runTimeoutMinutes,
+ );
+ const valid =
+ maxConcurrency >= 1 &&
+ maxConcurrency <= MAX_CONCURRENCY &&
+ runTimeoutMinutes >= MIN_RUN_TIMEOUT &&
+ runTimeoutMinutes <= MAX_RUN_TIMEOUT;
+
+ const submit = async () => {
+ if (!valid || save.isPending) return;
+ try {
+ await save.mutateAsync({
+ ...savedQoderInput(data, t(($) => $.qoder.cloud_title)),
+ maxConcurrency,
+ runTimeoutMinutes,
+ });
+ onClose();
+ } catch {
+ /* The error is rendered in the dialog. */
+ }
+ };
+
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open && !save.isPending) onClose();
+ }}
+ >
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>{t(($) => $.qoder.page.edit_limits)}</DialogTitle>
+ </DialogHeader>
+ <form
+ className="space-y-4"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void submit();
+ }}
+ >
+ <label className="block space-y-1.5">
+ <span className="block text-caption font-medium">
+ {t(($) => $.qoder.concurrency)}
+ </span>
+ <Input
+ type="number"
+ inputMode="numeric"
+ min={1}
+ max={MAX_CONCURRENCY}
+ step={1}
+ required
+ value={maxConcurrency}
+ disabled={save.isPending}
+ onChange={(event) =>
+ setMaxConcurrency(event.target.valueAsNumber || 0)
+ }
+ />
+ <span className="block text-caption text-muted-foreground">
+ {t(($) => $.qoder.concurrency_hint)}
+ </span>
+ </label>
+ <label className="block space-y-1.5">
+ <span className="block text-caption font-medium">
+ {t(($) => $.qoder.run_timeout)}
+ </span>
+ <Input
+ type="number"
+ inputMode="numeric"
+ min={MIN_RUN_TIMEOUT}
+ max={MAX_RUN_TIMEOUT}
+ step={5}
+ required
+ value={runTimeoutMinutes}
+ disabled={save.isPending}
+ onChange={(event) =>
+ setRunTimeoutMinutes(event.target.valueAsNumber || 0)
+ }
+ />
+ <span className="block text-caption text-muted-foreground">
+ {t(($) => $.qoder.run_timeout_hint)}
+ </span>
+ </label>
+ {save.error && (
+ <p role="alert" className="text-caption text-destructive">
+ {save.error.message}
+ </p>
+ )}
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ disabled={save.isPending}
+ onClick={onClose}
+ >
+ {t(($) => $.qoder.cancel)}
+ </Button>
+ <Button
+ type="submit"
+ disabled={!valid || save.isPending}
+ aria-busy={save.isPending}
+ >
+ {save.isPending && (
+ <Loader2 aria-hidden="true" className="animate-spin" />
+ )}
+ {t(($) => $.qoder.page.save)}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/views/runtimes/components/qoder-detail-page.test.tsx b/packages/views/runtimes/components/qoder-detail-page.test.tsx
new file mode 100644
index 0000000000..4656b98f06
--- /dev/null
+++ b/packages/views/runtimes/components/qoder-detail-page.test.tsx
@@ -0,0 +1,402 @@
+import { vi, it, expect, beforeEach, afterEach, describe } from "vitest";
+import {
+ render,
+ screen,
+ fireEvent,
+ waitFor,
+ cleanup,
+ within,
+} from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { I18nProvider } from "@multica/core/i18n/react";
+import type { AgentRuntime } from "@multica/core/types";
+import enRuntimes from "../../locales/en/runtimes.json";
+import { isQoderLocator, QoderDetailPage } from "./qoder-detail-page";
+
+const { ApiError, mocks, nav } = vi.hoisted(() => {
+ class ApiError extends Error {
+ status: number;
+ body: unknown;
+ constructor(message: string, status: number, body: unknown) {
+ super(message);
+ this.status = status;
+ this.body = body;
+ }
+ }
+ return {
+ ApiError,
+ mocks: {
+ getQoderConnection: vi.fn(),
+ listMembers: vi.fn(),
+ listRuntimes: vi.fn(),
+ listAgents: vi.fn(),
+ stopQoderConnection: vi.fn(),
+ saveQoderConnection: vi.fn(),
+ resumeQoderConnection: vi.fn(),
+ disconnectQoderConnection: vi.fn(),
+ listQoderEnvironments: vi.fn(),
+ checkQoderConnection: vi.fn(),
+ },
+ nav: { push: vi.fn(), replace: vi.fn() },
+ };
+});
+vi.mock("@multica/core/api", () => ({ api: mocks, ApiError }));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-test" }));
+vi.mock("@multica/core/auth", () => {
+ const state = { user: { id: "owner" } };
+ return {
+ useAuthStore: Object.assign(
+ (selector: (s: typeof state) => unknown) => selector(state),
+ { getState: () => state },
+ ),
+ };
+});
+vi.mock("@multica/core/agents", () => ({
+ useWorkspacePresenceMap: () => ({ byAgent: new Map() }),
+}));
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({
+ runtimes: () => "/acme/runtimes",
+ newAgentManual: () => "/acme/agents/new/manual",
+ agentDetail: (id: string) => `/acme/agents/${id}`,
+ }),
+}));
+vi.mock("../../navigation", () => ({
+ useNavigation: () => nav,
+ AppLink: ({ href, children }: { href: string; children: React.ReactNode }) => (
+ <a href={href}>{children}</a>
+ ),
+}));
+vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+vi.mock("../../platform", () => ({ openExternal: vi.fn() }));
+vi.mock("./qoder-configuration", () => ({
+ QoderConfiguration: () => <div>configuration form</div>,
+}));
+vi.mock("./usage-section", () => ({ UsageSection: () => null }));
+vi.mock("./runtime-detail", () => ({
+ ServingAgentsCard: ({ agents }: { agents: { id: string; name: string }[] }) => (
+ <ul aria-label="serving agents">
+ {agents.map((agent) => (
+ <li key={agent.id}>{agent.name}</li>
+ ))}
+ </ul>
+ ),
+}));
+
+const connection = {
+ available: true,
+ configured: true,
+ name: "QCA",
+ baseUrl: "https://api.qoder.com/api/v1/cloud",
+ environmentId: "env_one",
+ hasToken: true,
+ repositories: ["https://github.com/acme/web"],
+ enabled: true,
+ status: "online",
+ lastError: "",
+ maxConcurrency: 3,
+ runTimeoutMinutes: 60,
+ activeRuns: 1,
+ queuedRuns: 0,
+};
+
+beforeEach(() => {
+ mocks.getQoderConnection.mockResolvedValue(connection);
+ mocks.listMembers.mockResolvedValue([{ user_id: "owner", role: "owner" }]);
+ mocks.listRuntimes.mockResolvedValue([
+ { id: "rt_qoder", provider: "qoder_cloud", status: "online", visibility: "public" },
+ ]);
+ mocks.listAgents.mockResolvedValue([
+ { id: "a1", name: "Reviewer", runtime_id: "rt_qoder", archived_at: null },
+ { id: "a2", name: "Local helper", runtime_id: "rt_local", archived_at: null },
+ ]);
+ mocks.listQoderEnvironments.mockResolvedValue([
+ { id: "env_one", name: "Web environment" },
+ { id: "env_two", name: "Build environment" },
+ ]);
+ mocks.checkQoderConnection.mockResolvedValue(undefined);
+ mocks.saveQoderConnection.mockResolvedValue(connection);
+});
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+function mount() {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ render(
+ <I18nProvider locale="en" resources={{ en: { runtimes: enRuntimes } }}>
+ <QueryClientProvider client={client}>
+ <QoderDetailPage />
+ </QueryClientProvider>
+ </I18nProvider>,
+ );
+ return client;
+}
+
+describe("isQoderLocator", () => {
+ const runtimes = [
+ { id: "rt_qoder", provider: "qoder_cloud" },
+ { id: "rt_local", provider: "claude" },
+ ] as AgentRuntime[];
+ it("accepts the page locator, the managed machine id and a Qoder runtime id", () => {
+ expect(isQoderLocator("qoder", runtimes)).toBe(true);
+ expect(isQoderLocator("cloud:qoder-managed-ws-test", runtimes)).toBe(true);
+ expect(isQoderLocator("rt_qoder", runtimes)).toBe(true);
+ expect(isQoderLocator("rt_local", runtimes)).toBe(false);
+ expect(isQoderLocator("local:daemon-1", runtimes)).toBe(false);
+ });
+});
+
+it("shows the connection with its agents and no machine-level controls", async () => {
+ const client = mount();
+ expect(
+ await screen.findByRole("heading", { name: "Qoder Cloud Agent" }),
+ ).toBeInTheDocument();
+ expect(await screen.findByText("Web environment")).toBeInTheDocument();
+ expect(screen.getByText("acme/web")).toBeInTheDocument();
+ expect(screen.queryByText("configuration form")).not.toBeInTheDocument();
+ const serving = await screen.findByRole("list", { name: "serving agents" });
+ expect(within(serving).getByText("Reviewer")).toBeInTheDocument();
+ expect(within(serving).queryByText("Local helper")).not.toBeInTheDocument();
+ expect(screen.getByText("1 of 3 running · 0 queued")).toBeInTheDocument();
+ expect(screen.queryByText("Visibility")).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Delete runtime" }),
+ ).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Create an agent with it" }));
+ expect(nav.push).toHaveBeenCalledWith(
+ "/acme/agents/new/manual?runtime=rt_qoder",
+ );
+ client.clear();
+});
+
+it("asks before pausing and names the agents it strands", async () => {
+ mocks.stopQoderConnection.mockResolvedValue({ ...connection, enabled: false });
+ const client = mount();
+ fireEvent.click(await screen.findByRole("button", { name: "Pause" }));
+ const dialog = await screen.findByRole("alertdialog");
+ expect(within(dialog).getByText("Pause Qoder Cloud Agent?")).toBeInTheDocument();
+ expect(within(dialog).getByText("Reviewer")).toBeInTheDocument();
+ expect(mocks.stopQoderConnection).not.toHaveBeenCalled();
+ fireEvent.click(within(dialog).getByRole("button", { name: "Pause" }));
+ await waitFor(() => expect(mocks.stopQoderConnection).toHaveBeenCalledWith("ws-test"));
+ client.clear();
+});
+
+it("resumes with the saved token and repository bindings", async () => {
+ mocks.getQoderConnection.mockResolvedValue({
+ ...connection,
+ enabled: false,
+ status: "offline",
+ });
+ mocks.resumeQoderConnection.mockResolvedValue(connection);
+ const client = mount();
+ fireEvent.click(await screen.findByRole("button", { name: "Resume" }));
+ await waitFor(() => expect(mocks.resumeQoderConnection).toHaveBeenCalledTimes(1));
+ expect(mocks.saveQoderConnection).not.toHaveBeenCalled();
+ const input = mocks.resumeQoderConnection.mock.calls[0]![1];
+ expect(input).toMatchObject({
+ environmentId: "env_one",
+ qoderToken: "",
+ maxConcurrency: 3,
+ runTimeoutMinutes: 60,
+ });
+ expect(input).not.toHaveProperty("githubTokens");
+ client.clear();
+});
+
+it("disconnects after confirming the latest agents to unbind", async () => {
+ mocks.disconnectQoderConnection
+ .mockRejectedValueOnce(
+ new ApiError("plan changed", 409, {
+ code: "runtime_delete_plan_changed",
+ active_agents: [
+ { id: "a1", name: "Reviewer" },
+ { id: "a3", name: "Triage" },
+ ],
+ }),
+ )
+ .mockResolvedValueOnce({ ...connection, configured: false });
+ const client = mount();
+ fireEvent.click(await screen.findByRole("button", { name: "Disconnect" }));
+ const dialog = await screen.findByRole("alertdialog");
+ expect(within(dialog).getByText("Reviewer")).toBeInTheDocument();
+
+ fireEvent.click(within(dialog).getByRole("button", { name: "Disconnect" }));
+ expect(
+ await within(dialog).findByText(
+ "The agents on Qoder changed. Review the list and confirm again.",
+ ),
+ ).toBeInTheDocument();
+ expect(within(dialog).getByText("Triage")).toBeInTheDocument();
+ expect(mocks.disconnectQoderConnection).toHaveBeenLastCalledWith("ws-test", ["a1"]);
+ expect(nav.replace).not.toHaveBeenCalled();
+
+ fireEvent.click(within(dialog).getByRole("button", { name: "Disconnect" }));
+ await waitFor(() =>
+ expect(mocks.disconnectQoderConnection).toHaveBeenLastCalledWith("ws-test", [
+ "a1",
+ "a3",
+ ]),
+ );
+ await waitFor(() => expect(nav.replace).toHaveBeenCalledWith("/acme/runtimes"));
+ client.clear();
+});
+
+it("shows members the connection read-only", async () => {
+ mocks.listMembers.mockResolvedValue([{ user_id: "owner", role: "member" }]);
+ const client = mount();
+ expect(await screen.findByText("acme/web")).toBeInTheDocument();
+ await waitFor(() => expect(mocks.listMembers).toHaveBeenCalled());
+ expect(screen.getByText("env_one")).toBeInTheDocument();
+ expect(mocks.listQoderEnvironments).not.toHaveBeenCalled();
+ for (const name of ["Disconnect", "Pause", "Edit", "Test connection", "Add repository"]) {
+ expect(screen.queryByRole("button", { name })).not.toBeInTheDocument();
+ }
+ expect(
+ screen.queryByRole("button", { name: "Actions for acme/web" }),
+ ).not.toBeInTheDocument();
+ client.clear();
+});
+
+it("connects through the form while Qoder is not configured", async () => {
+ mocks.getQoderConnection.mockResolvedValue({
+ ...connection,
+ configured: false,
+ hasToken: false,
+ repositories: [],
+ });
+ const client = mount();
+ expect(await screen.findByText("configuration form")).toBeInTheDocument();
+ expect(screen.queryByText("Connection")).not.toBeInTheDocument();
+ client.clear();
+});
+
+it("tests the saved connection without sending secrets", async () => {
+ const client = mount();
+ fireEvent.click(await screen.findByRole("button", { name: "Test connection" }));
+ await waitFor(() => expect(mocks.checkQoderConnection).toHaveBeenCalledTimes(1));
+ const input = mocks.checkQoderConnection.mock.calls[0]![1];
+ expect(input).toMatchObject({ environmentId: "env_one", qoderToken: "" });
+ expect(input).not.toHaveProperty("githubTokens");
+ client.clear();
+});
+
+it("tests an edited connection before saving it", async () => {
+ const client = mount();
+ fireEvent.click(await screen.findByRole("button", { name: "Edit" }));
+ const dialog = await screen.findByRole("dialog");
+ const environment = within(dialog).getByRole("combobox", { name: "Environment" });
+ await waitFor(() => expect(environment).toHaveTextContent("Web environment"));
+ fireEvent.click(within(dialog).getByRole("button", { name: "Test and save" }));
+ await waitFor(() => expect(mocks.saveQoderConnection).toHaveBeenCalledTimes(1));
+ expect(mocks.checkQoderConnection).toHaveBeenCalledTimes(1);
+ const input = mocks.saveQoderConnection.mock.calls[0]![1];
+ expect(input).toMatchObject({
+ name: "QCA",
+ baseUrl: "https://api.qoder.com/api/v1/cloud",
+ environmentId: "env_one",
+ qoderToken: "",
+ });
+ expect(input).not.toHaveProperty("githubTokens");
+ await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
+ client.clear();
+});
+
+it("asks for a new token when the region changes", async () => {
+ const client = mount();
+ fireEvent.click(await screen.findByRole("button", { name: "Edit" }));
+ const dialog = await screen.findByRole("dialog");
+ await waitFor(() =>
+ expect(
+ within(dialog).getByRole("combobox", { name: "Environment" }),
+ ).toHaveTextContent("Web environment"),
+ );
+ fireEvent.click(within(dialog).getByRole("radio", { name: "China (qoder.com.cn)" }));
+ expect(
+ within(dialog).getByText("Environments load once the token is verified"),
+ ).toBeInTheDocument();
+ expect(within(dialog).getByRole("button", { name: "Test and save" })).toBeDisabled();
+ client.clear();
+});
+
+it("adds a repository and keeps the saved tokens", async () => {
+ const client = mount();
+ fireEvent.click(await screen.findByRole("button", { name: "Add repository" }));
+ const dialog = await screen.findByRole("dialog");
+ fireEvent.change(within(dialog).getByLabelText("GitHub URL"), {
+ target: { value: "https://github.com/acme/api" },
+ });
+ fireEvent.change(within(dialog).getByLabelText("GitHub token"), {
+ target: { value: "ghp_new" },
+ });
+ fireEvent.click(within(dialog).getByRole("button", { name: "Save" }));
+ await waitFor(() => expect(mocks.saveQoderConnection).toHaveBeenCalledTimes(1));
+ expect(mocks.saveQoderConnection.mock.calls[0]![1]).toMatchObject({
+ qoderToken: "",
+ githubTokens: {
+ "https://github.com/acme/web": "",
+ "https://github.com/acme/api": "ghp_new",
+ },
+ });
+ client.clear();
+});
+
+it("replaces the token of a saved repository", async () => {
+ const client = mount();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Actions for acme/web" }),
+ );
+ fireEvent.click(await screen.findByText("Replace token"));
+ const dialog = await screen.findByRole("dialog");
+ expect(within(dialog).queryByLabelText("GitHub URL")).not.toBeInTheDocument();
+ fireEvent.change(within(dialog).getByLabelText("GitHub token"), {
+ target: { value: "ghp_rotated" },
+ });
+ fireEvent.click(within(dialog).getByRole("button", { name: "Save" }));
+ await waitFor(() => expect(mocks.saveQoderConnection).toHaveBeenCalledTimes(1));
+ expect(mocks.saveQoderConnection.mock.calls[0]![1].githubTokens).toEqual({
+ "https://github.com/acme/web": "ghp_rotated",
+ });
+ client.clear();
+});
+
+it("removes a repository after confirming", async () => {
+ mocks.getQoderConnection.mockResolvedValue({
+ ...connection,
+ repositories: ["https://github.com/acme/api", "https://github.com/acme/web"],
+ });
+ const client = mount();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Actions for acme/web" }),
+ );
+ fireEvent.click(await screen.findByText("Remove"));
+ const dialog = await screen.findByRole("alertdialog");
+ expect(within(dialog).getByText("Remove acme/web?")).toBeInTheDocument();
+ fireEvent.click(within(dialog).getByRole("button", { name: "Remove" }));
+ await waitFor(() => expect(mocks.saveQoderConnection).toHaveBeenCalledTimes(1));
+ expect(mocks.saveQoderConnection.mock.calls[0]![1].githubTokens).toEqual({
+ "https://github.com/acme/api": "",
+ });
+ client.clear();
+});
+
+it("edits the execution limits", async () => {
+ const client = mount();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Edit execution settings" }),
+ );
+ const dialog = await screen.findByRole("dialog");
+ fireEvent.change(within(dialog).getByLabelText(/Concurrent runs/), {
+ target: { value: "5" },
+ });
+ fireEvent.click(within(dialog).getByRole("button", { name: "Save" }));
+ await waitFor(() => expect(mocks.saveQoderConnection).toHaveBeenCalledTimes(1));
+ const input = mocks.saveQoderConnection.mock.calls[0]![1];
+ expect(input).toMatchObject({ maxConcurrency: 5, runTimeoutMinutes: 60, qoderToken: "" });
+ expect(input).not.toHaveProperty("githubTokens");
+ client.clear();
+});
diff --git a/packages/views/runtimes/components/qoder-detail-page.tsx b/packages/views/runtimes/components/qoder-detail-page.tsx
new file mode 100644
index 0000000000..9e838a1ac1
--- /dev/null
+++ b/packages/views/runtimes/components/qoder-detail-page.tsx
@@ -0,0 +1,580 @@
+"use client";
+
+import { useState } from "react";
+import { AlertCircle, Plus } from "lucide-react";
+import { toast } from "sonner";
+import { useQuery } from "@tanstack/react-query";
+import type { Agent, AgentRuntime } from "@multica/core/types";
+import { useAuthStore } from "@multica/core/auth";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { useWorkspacePresenceMap } from "@multica/core/agents";
+import { isRuntimeUsableForUser } from "@multica/core/runtimes";
+import { runtimeListOptions } from "@multica/core/runtimes/queries";
+import {
+ QODER_REGIONS,
+ qoderOptions,
+ useDisconnectQoder,
+ useResumeQoder,
+ useStopQoder,
+ type QoderConnection,
+} from "@multica/core/runtimes/qoder";
+import {
+ agentListOptions,
+ memberListOptions,
+} from "@multica/core/workspace/queries";
+import { Button } from "@multica/ui/components/ui/button";
+import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import { cn } from "@multica/ui/lib/utils";
+import { PAGE_GUTTER, PAGE_RAIL } from "../../layout/page-header";
+import { AppLink, useNavigation } from "../../navigation";
+import { createPathWithParams } from "../../agents/create/squad-param";
+import { useT } from "../../i18n";
+import { ProviderLogo } from "./provider-logo";
+import { QoderConfiguration } from "./qoder-configuration";
+import {
+ QoderConnectionCard,
+ QoderLimitsCard,
+ QoderRepositoriesCard,
+ QoderSection,
+ savedQoderInput,
+} from "./qoder-connection-cards";
+import { QoderStatusBadge } from "./qoder-status-badge";
+import { ServingAgentsCard } from "./runtime-detail";
+import { UsageSection } from "./usage-section";
+import { parseActiveAgentsConflict } from "./delete-runtime-dialog";
+
+/** Route locator of the workspace's Qoder Cloud Agent page. */
+export const QODER_RUNTIME_LOCATOR = "qoder";
+
+/**
+ * Whether a runtimes route locator names Qoder: its own locator, the machine
+ * id its runtime registers under, or the id of a Qoder runtime.
+ */
+export function isQoderLocator(
+ locator: string,
+ runtimes: AgentRuntime[],
+): boolean {
+ return (
+ locator === QODER_RUNTIME_LOCATOR ||
+ locator.startsWith("cloud:qoder-managed-") ||
+ runtimes.some(
+ (runtime) => runtime.id === locator && runtime.provider === "qoder_cloud",
+ )
+ );
+}
+
+/**
+ * The workspace's Qoder Cloud Agent: one shared connection, so the page
+ * manages the connection directly instead of listing harnesses on a machine.
+ */
+export function QoderDetailPage() {
+ const { t } = useT("runtimes");
+ const wsId = useWorkspaceId();
+ const paths = useWorkspacePaths();
+ const navigation = useNavigation();
+ const userId = useAuthStore((state) => state.user?.id ?? null);
+ const connection = useQuery(qoderOptions(wsId));
+ const { data: runtimes = [], isLoading: runtimesLoading } = useQuery(
+ runtimeListOptions(wsId),
+ );
+ const { data: agents = [] } = useQuery(agentListOptions(wsId));
+ const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const { byAgent: presenceMap } = useWorkspacePresenceMap(wsId);
+
+ if (connection.isPending || runtimesLoading) return <QoderPageSkeleton />;
+ const data = connection.data;
+ if (connection.isError || data?.available !== true) {
+ return (
+ <div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 py-16 text-center">
+ <AlertCircle aria-hidden="true" className="size-8 text-destructive" />
+ <p className="max-w-md text-body">
+ {connection.isError
+ ? connection.error.message
+ : t(($) => $.qoder.unavailable)}
+ </p>
+ <Button
+ size="sm"
+ render={<AppLink href={paths.runtimes()} />}
+ nativeButton={false}
+ >
+ {t(($) => $.detail.all_runtimes)}
+ </Button>
+ </div>
+ );
+ }
+
+ const member = members.find((m) => m.user_id === userId);
+ const isAdmin = member?.role === "owner" || member?.role === "admin";
+ const qoderRuntimes = runtimes.filter(
+ (runtime) => runtime.provider === "qoder_cloud",
+ );
+ const runtime =
+ qoderRuntimes.find((item) => item.status === "online") ??
+ qoderRuntimes[0] ??
+ null;
+ const boundAgents = agents.filter(
+ (agent) =>
+ !agent.archived_at &&
+ qoderRuntimes.some((item) => item.id === agent.runtime_id),
+ );
+ const ready =
+ data.configured &&
+ data.enabled &&
+ data.status === "online" &&
+ runtime?.status === "online";
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <QoderHeader
+ data={data}
+ agentCount={boundAgents.length}
+ action={
+ ready && runtime ? (
+ <Button
+ size="sm"
+ onClick={() =>
+ navigation.push(
+ createPathWithParams(paths.newAgentManual(), {
+ runtime: runtime.id,
+ }),
+ )
+ }
+ >
+ <Plus aria-hidden="true" className="size-3.5" />
+ {t(($) => $.qoder.create_agent)}
+ </Button>
+ ) : null
+ }
+ />
+ <div className="min-h-0 flex-1 overflow-y-auto bg-background">
+ <div
+ className={cn(
+ PAGE_RAIL,
+ PAGE_GUTTER,
+ "grid grid-cols-1 gap-4 py-4 sm:py-6 lg:grid-cols-[minmax(0,1fr)_320px]",
+ )}
+ >
+ <div className="min-w-0 space-y-4">
+ {data.configured ? (
+ <>
+ <QoderConnectionCard wsId={wsId} data={data} canManage={isAdmin} />
+ <QoderRepositoriesCard
+ wsId={wsId}
+ data={data}
+ canManage={isAdmin}
+ />
+ </>
+ ) : (
+ <QoderSection title={t(($) => $.qoder.page.configuration)}>
+ <div className="p-4">
+ {isAdmin ? (
+ <QoderConfiguration />
+ ) : (
+ <div className="py-6 text-center">
+ <p className="text-body font-medium">
+ {t(($) => $.qoder.page.not_connected_title)}
+ </p>
+ <p className="mt-1 text-caption text-muted-foreground">
+ {t(($) => $.qoder.page.not_connected_hint)}
+ </p>
+ </div>
+ )}
+ </div>
+ </QoderSection>
+ )}
+ {runtime && isRuntimeUsableForUser(runtime, userId) && (
+ <UsageSection runtime={runtime} />
+ )}
+ </div>
+ <div className="space-y-4">
+ <ServingAgentsCard
+ agents={boundAgents}
+ presenceMap={presenceMap}
+ agentHref={(id) => paths.agentDetail(id)}
+ />
+ {data.configured && (
+ <QoderLimitsCard wsId={wsId} data={data} canManage={isAdmin} />
+ )}
+ {isAdmin && data.configured && (
+ <ManageCard
+ wsId={wsId}
+ data={data}
+ boundAgents={boundAgents}
+ onDisconnected={() => {
+ navigation.replace(paths.runtimes());
+ toast.success(t(($) => $.qoder.disconnect_confirm.done));
+ }}
+ />
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function QoderHeader({
+ data,
+ agentCount,
+ action,
+}: {
+ data: QoderConnection;
+ agentCount: number;
+ action: React.ReactNode;
+}) {
+ const { t } = useT("runtimes");
+ const paths = useWorkspacePaths();
+ const title = t(($) => $.qoder.cloud_title);
+ const region =
+ data.baseUrl === QODER_REGIONS.cn
+ ? t(($) => $.qoder.region_cn)
+ : t(($) => $.qoder.region_global);
+ const failing = data.enabled && data.status === "error" && !!data.lastError;
+ return (
+ <header className="shrink-0 border-b bg-background pb-5 pt-3">
+ <div className={cn(PAGE_RAIL, PAGE_GUTTER)}>
+ <div className="flex min-w-0 items-center gap-1.5 text-caption text-muted-foreground">
+ <AppLink
+ href={paths.runtimes()}
+ className="rounded-sm transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {t(($) => $.page.title)}
+ </AppLink>
+ <span aria-hidden="true">/</span>
+ <span className="truncate text-foreground">{title}</span>
+ </div>
+ <div className="mt-4 flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
+ <div className="flex min-w-0 items-start gap-4">
+ <div className="flex size-12 shrink-0 items-center justify-center rounded-xl border bg-card sm:size-14">
+ <ProviderLogo provider="qoder_cloud" className="size-6" />
+ </div>
+ <div className="min-w-0 pt-0.5">
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
+ <h1 className="min-w-0 text-balance text-title-lg font-semibold tracking-tight sm:text-display-sm">
+ {title}
+ </h1>
+ <QoderStatusBadge connection={data} />
+ </div>
+ {failing && (
+ <p role="alert" className="mt-1 text-body text-destructive">
+ {data.lastError}
+ </p>
+ )}
+ {data.configured ? (
+ <div className="mt-1.5 flex flex-wrap items-center gap-x-1.5 gap-y-1 text-caption text-muted-foreground">
+ <span>{region}</span>
+ <span aria-hidden="true">·</span>
+ <span>
+ {t(($) => $.qoder.agent_count, { count: agentCount })}
+ </span>
+ <span aria-hidden="true">·</span>
+ <span className="tabular-nums">
+ {data.enabled && data.status === "online"
+ ? t(($) => $.qoder.usage, {
+ active: data.activeRuns,
+ limit: data.maxConcurrency,
+ queued: data.queuedRuns,
+ })
+ : t(($) => $.qoder.page.workload_idle)}
+ </span>
+ </div>
+ ) : null}
+ </div>
+ </div>
+ {action && (
+ <div className="flex shrink-0 items-center gap-2 self-end lg:self-start">
+ {action}
+ </div>
+ )}
+ </div>
+ </div>
+ </header>
+ );
+}
+
+function ManageCard({
+ wsId,
+ data,
+ boundAgents,
+ onDisconnected,
+}: {
+ wsId: string;
+ data: QoderConnection;
+ boundAgents: Agent[];
+ onDisconnected: () => void;
+}) {
+ const { t } = useT("runtimes");
+ const stop = useStopQoder(wsId);
+ const resumeConnection = useResumeQoder(wsId);
+ const [pauseOpen, setPauseOpen] = useState(false);
+ const [disconnectOpen, setDisconnectOpen] = useState(false);
+ const busy = stop.isPending || resumeConnection.isPending;
+
+ const resume = () =>
+ resumeConnection.mutate(savedQoderInput(data, t(($) => $.qoder.cloud_title)), {
+ onSuccess: () => toast.success(t(($) => $.qoder.page.resumed)),
+ onError: (err) => toast.error(err.message),
+ });
+
+ return (
+ <QoderSection title={t(($) => $.qoder.page.manage_title)}>
+ <div className="divide-y">
+ {data.enabled ? (
+ <ManageRow
+ title={t(($) => $.qoder.page.pause_title)}
+ hint={t(($) => $.qoder.page.pause_hint)}
+ >
+ <Button
+ variant="outline"
+ size="xs"
+ disabled={busy}
+ onClick={() => setPauseOpen(true)}
+ >
+ {t(($) => $.qoder.stop)}
+ </Button>
+ </ManageRow>
+ ) : (
+ <ManageRow
+ title={t(($) => $.qoder.page.resume_title)}
+ hint={t(($) => $.qoder.page.resume_hint)}
+ >
+ <Button
+ variant="outline"
+ size="xs"
+ disabled={busy}
+ aria-busy={resumeConnection.isPending}
+ onClick={resume}
+ >
+ {t(($) => $.qoder.page.resume)}
+ </Button>
+ </ManageRow>
+ )}
+ <ManageRow
+ title={t(($) => $.qoder.page.disconnect_title)}
+ hint={t(($) => $.qoder.page.disconnect_hint)}
+ destructive
+ >
+ <Button
+ variant="destructive"
+ size="xs"
+ disabled={busy}
+ onClick={() => setDisconnectOpen(true)}
+ >
+ {t(($) => $.qoder.page.disconnect)}
+ </Button>
+ </ManageRow>
+ </div>
+
+ <AlertDialog
+ open={pauseOpen}
+ onOpenChange={(open) => {
+ if (!open && !stop.isPending) setPauseOpen(false);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $.qoder.stop_confirm.title)}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {boundAgents.length > 0
+ ? t(($) => $.qoder.stop_confirm.description_agents, {
+ count: boundAgents.length,
+ })
+ : t(($) => $.qoder.stop_confirm.description)}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AgentNames agents={boundAgents} />
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={stop.isPending}>
+ {t(($) => $.qoder.stop_confirm.cancel)}
+ </AlertDialogCancel>
+ <AlertDialogAction
+ disabled={stop.isPending}
+ onClick={() =>
+ stop.mutate(undefined, {
+ onError: (err) => toast.error(err.message),
+ onSettled: () => setPauseOpen(false),
+ })
+ }
+ >
+ {t(($) => $.qoder.stop)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ {disconnectOpen && (
+ <DisconnectQoderDialog
+ wsId={wsId}
+ agents={boundAgents}
+ onClose={() => setDisconnectOpen(false)}
+ onDisconnected={onDisconnected}
+ />
+ )}
+ </QoderSection>
+ );
+}
+
+function ManageRow({
+ title,
+ hint,
+ destructive,
+ children,
+}: {
+ title: string;
+ hint: string;
+ destructive?: boolean;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="space-y-1 px-4 py-3">
+ <div className="flex items-center justify-between gap-3">
+ <p
+ className={cn(
+ "min-w-0 text-body font-medium",
+ destructive && "text-destructive",
+ )}
+ >
+ {title}
+ </p>
+ <div className="shrink-0">{children}</div>
+ </div>
+ <p className="text-pretty text-caption text-muted-foreground">{hint}</p>
+ </div>
+ );
+}
+
+function AgentNames({ agents }: { agents: Agent[] }) {
+ if (agents.length === 0) return null;
+ return (
+ <ul className="max-h-40 space-y-1 overflow-y-auto rounded-md bg-muted/60 px-3 py-2 text-caption">
+ {agents.map((agent) => (
+ <li key={agent.id} className="truncate">
+ {agent.name}
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+/**
+ * Confirms the agents that lose their runtime. The server refuses when that
+ * set changed since the dialog opened; the dialog then shows the new set and
+ * asks again.
+ */
+export function DisconnectQoderDialog({
+ wsId,
+ agents,
+ onClose,
+ onDisconnected,
+}: {
+ wsId: string;
+ agents: Agent[];
+ onClose: () => void;
+ onDisconnected: () => void;
+}) {
+ const { t } = useT("runtimes");
+ const disconnect = useDisconnectQoder(wsId);
+ const [planAgents, setPlanAgents] = useState(agents);
+ const [notice, setNotice] = useState<string | null>(null);
+
+ const confirm = () =>
+ disconnect.mutate(
+ planAgents.map((agent) => agent.id),
+ {
+ onSuccess: onDisconnected,
+ onError: (err) => {
+ const conflict = parseActiveAgentsConflict(err);
+ if (conflict?.code === "runtime_delete_plan_changed") {
+ setPlanAgents(conflict.activeAgents);
+ setNotice(t(($) => $.qoder.disconnect_confirm.plan_changed));
+ return;
+ }
+ toast.error(err.message);
+ },
+ },
+ );
+
+ return (
+ <AlertDialog
+ open
+ onOpenChange={(open) => {
+ if (!open && !disconnect.isPending) onClose();
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $.qoder.disconnect_confirm.title)}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $.qoder.disconnect_confirm.description)}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ {planAgents.length > 0 && (
+ <div className="space-y-2">
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.qoder.disconnect_confirm.description_agents, {
+ count: planAgents.length,
+ })}
+ </p>
+ <AgentNames agents={planAgents} />
+ </div>
+ )}
+ {notice && (
+ <p role="alert" className="text-caption text-warning">
+ {notice}
+ </p>
+ )}
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={disconnect.isPending}>
+ {t(($) => $.qoder.disconnect_confirm.cancel)}
+ </AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ disabled={disconnect.isPending}
+ aria-busy={disconnect.isPending}
+ onClick={confirm}
+ >
+ {disconnect.isPending
+ ? t(($) => $.qoder.disconnect_confirm.working)
+ : t(($) => $.qoder.disconnect_confirm.confirm)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
+
+function QoderPageSkeleton() {
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div className="border-b pb-5 pt-3">
+ <div className={cn(PAGE_RAIL, PAGE_GUTTER)}>
+ <Skeleton className="h-3 w-36" />
+ <div className="mt-4 flex items-start gap-4">
+ <Skeleton className="size-14 rounded-xl" />
+ <div className="flex-1">
+ <Skeleton className="h-7 w-64" />
+ <Skeleton className="mt-2 h-4 w-40" />
+ </div>
+ </div>
+ </div>
+ </div>
+ <div className={cn(PAGE_RAIL, PAGE_GUTTER, "py-6")}>
+ <Skeleton className="h-64 w-full rounded-lg" />
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/runtimes/components/qoder-status-badge.tsx b/packages/views/runtimes/components/qoder-status-badge.tsx
new file mode 100644
index 0000000000..63849f291d
--- /dev/null
+++ b/packages/views/runtimes/components/qoder-status-badge.tsx
@@ -0,0 +1,36 @@
+import type { QoderConnection } from "@multica/core/runtimes/qoder";
+import { Badge } from "@multica/ui/components/ui/badge";
+import { useT } from "../../i18n";
+
+export function QoderStatusBadge({
+ connection,
+}: {
+ connection: QoderConnection;
+}) {
+ const { t } = useT("runtimes");
+ const status = !connection.configured
+ ? "not_configured"
+ : !connection.enabled
+ ? "stopped"
+ : connection.status === "online"
+ ? "online"
+ : connection.status === "error"
+ ? "error"
+ : connection.status === "offline"
+ ? "offline"
+ : "starting";
+ const tone =
+ status === "online"
+ ? "bg-success/10 text-success"
+ : status === "error"
+ ? "bg-destructive/10 text-destructive"
+ : status === "starting"
+ ? "bg-warning/10 text-warning"
+ : "bg-muted text-muted-foreground";
+ return (
+ <Badge variant="secondary" className={tone}>
+ <span aria-hidden="true" className="size-1.5 rounded-full bg-current" />
+ {t(($) => $.qoder[status])}
+ </Badge>
+ );
+}
diff --git a/packages/views/runtimes/components/remote-runtime-dialog.tsx b/packages/views/runtimes/components/remote-runtime-dialog.tsx
new file mode 100644
index 0000000000..50d03eb260
--- /dev/null
+++ b/packages/views/runtimes/components/remote-runtime-dialog.tsx
@@ -0,0 +1,49 @@
+"use client";
+
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogDescription,
+} from "@multica/ui/components/ui/dialog";
+import { useT } from "../../i18n";
+import { QoderConfiguration } from "./qoder-configuration";
+
+/**
+ * Connects the workspace's Qoder Cloud Agent. An existing connection is
+ * managed on its runtime page instead.
+ */
+export function RemoteRuntimeDialog({
+ onClose,
+ onConnected,
+}: {
+ onClose: () => void;
+ /** Called after a first-time connection succeeds, before the dialog closes. */
+ onConnected?: () => void;
+}) {
+ const { t } = useT("runtimes");
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-2xl">
+ <DialogHeader>
+ <DialogTitle>{t(($) => $.qoder.connect_title)}</DialogTitle>
+ <DialogDescription>
+ {t(($) => $.qoder.connect_description)}
+ </DialogDescription>
+ </DialogHeader>
+ <QoderConfiguration
+ onConnected={() => {
+ onConnected?.();
+ onClose();
+ }}
+ />
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/views/runtimes/components/runtime-detail-page.tsx b/packages/views/runtimes/components/runtime-detail-page.tsx
index 93f24ea735..14bfcebc25 100644
--- a/packages/views/runtimes/components/runtime-detail-page.tsx
+++ b/packages/views/runtimes/components/runtime-detail-page.tsx
@@ -28,6 +28,7 @@ import { RenameMachineDialog } from "./rename-machine-dialog";
import { RuntimeProfilesDialog } from "./runtime-profiles-dialog";
import { pendingRuntimesForProfiles } from "./pending-runtime";
import { MachineCliSection } from "./machine-cli-section";
+import { isQoderLocator, QoderDetailPage } from "./qoder-detail-page";
import { HealthIcon, useHealthLabel } from "./shared";
import { useT, useTimeAgo } from "../../i18n";
@@ -177,6 +178,13 @@ export function RuntimeDetailPage({
};
}, [machine, isAdmin, currentUserId]);
+ if (
+ isQoderLocator(machineLocator, runtimes) ||
+ (machine?.runtimes.length &&
+ machine.runtimes.every((runtime) => runtime.provider === "qoder_cloud"))
+ ) {
+ return <QoderDetailPage />;
+ }
if (isLoading) return <MachineDetailSkeleton />;
if (!machine) {
diff --git a/packages/views/runtimes/components/runtime-detail.tsx b/packages/views/runtimes/components/runtime-detail.tsx
index 524168266b..1da58a3ead 100644
--- a/packages/views/runtimes/components/runtime-detail.tsx
+++ b/packages/views/runtimes/components/runtime-detail.tsx
@@ -399,7 +399,7 @@ function Fact({
);
}
-function ServingAgentsCard({
+export function ServingAgentsCard({
agents,
presenceMap,
agentHref,
diff --git a/packages/views/runtimes/components/runtime-machines.ts b/packages/views/runtimes/components/runtime-machines.ts
index 30da26f8cf..9c20430375 100644
--- a/packages/views/runtimes/components/runtime-machines.ts
+++ b/packages/views/runtimes/components/runtime-machines.ts
@@ -15,6 +15,8 @@ export interface RuntimeMachine {
daemonId: string | null;
title: string;
subtitle: string | null;
+ /** Compact OS/arch summary without the daemon-id fallback of `subtitle`. */
+ deviceSummary: string | null;
deviceInfo: string | null;
cliVersion: string | null;
launchedBy: string | null;
@@ -132,6 +134,7 @@ function placeholderLocalMachine(
daemonId,
title: options.localMachineName ?? "This machine",
subtitle: null,
+ deviceSummary: null,
deviceInfo: null,
cliVersion: null,
launchedBy: null,
@@ -253,6 +256,7 @@ function finalizeRuntimeMachine(
daemonId: draft.daemonId,
title,
subtitle,
+ deviceSummary: compactDeviceInfo(deviceInfo, title),
deviceInfo,
cliVersion: currentMachineMetadata(runtimes, "cli_version"),
launchedBy: currentMachineMetadata(runtimes, "launched_by"),
diff --git a/packages/views/runtimes/components/runtime-settings-page.tsx b/packages/views/runtimes/components/runtime-settings-page.tsx
index 9fe45117ae..e4877b0870 100644
--- a/packages/views/runtimes/components/runtime-settings-page.tsx
+++ b/packages/views/runtimes/components/runtime-settings-page.tsx
@@ -9,6 +9,7 @@ import { runtimeListOptions } from "@multica/core/runtimes/queries";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
import { RuntimeDetail } from "./runtime-detail";
import { buildRuntimeMachines } from "./runtime-machines";
+import { QoderDetailPage } from "./qoder-detail-page";
import { useT } from "../../i18n";
export function RuntimeSettingsPage({
@@ -59,6 +60,7 @@ export function RuntimeSettingsPage({
);
}
const { machine, runtime } = target;
+ if (runtime.provider === "qoder_cloud") return <QoderDetailPage />;
return (
<RuntimeDetail
diff --git a/packages/views/runtimes/components/runtimes-page.test.tsx b/packages/views/runtimes/components/runtimes-page.test.tsx
new file mode 100644
index 0000000000..a3ab6e1cd5
--- /dev/null
+++ b/packages/views/runtimes/components/runtimes-page.test.tsx
@@ -0,0 +1,226 @@
+import type { ReactNode } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { render, screen, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { describe, expect, it, vi } from "vitest";
+import { I18nProvider } from "@multica/core/i18n/react";
+import { agentTaskSnapshotOptions } from "@multica/core/agents";
+import { chatSessionsOptions } from "@multica/core/chat/queries";
+import { runtimeProfileListOptions } from "@multica/core/runtimes";
+import { qoderOptions, type QoderConnection } from "@multica/core/runtimes/qoder";
+import { runtimeListOptions } from "@multica/core/runtimes/queries";
+import type { AgentRuntime } from "@multica/core/types";
+import {
+ agentListOptions,
+ memberListOptions,
+} from "@multica/core/workspace/queries";
+import enCommon from "../../locales/en/common.json";
+import enRuntimes from "../../locales/en/runtimes.json";
+import { RuntimesPage } from "./runtimes-page";
+
+const TEST_RESOURCES = { en: { common: enCommon, runtimes: enRuntimes } };
+const WS = "ws-test";
+
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-test" }));
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: (select: (state: unknown) => unknown) =>
+ select({ isLoading: false, user: { id: "user-1" } }),
+}));
+vi.mock("@multica/core/paths", () => ({
+ useWorkspacePaths: () => ({
+ runtimeDetail: (id: string) => `/runtimes/${id}`,
+ }),
+ useRequiredWorkspaceSlug: () => "workspace-test",
+}));
+vi.mock("@multica/core/realtime", () => ({ useWSEvent: () => {} }));
+vi.mock("@multica/core/onboarding", () => ({
+ memberNeedsMikaSetup: () => false,
+ useBootstrapMika: () => ({ isPending: false, mutateAsync: vi.fn() }),
+}));
+vi.mock("../../navigation", () => ({
+ AppLink: ({ href, children, ...props }: { href: string; children: ReactNode }) => (
+ <a href={href} {...props}>
+ {children}
+ </a>
+ ),
+ rowLinkInteractiveProps: {},
+ useNavigation: () => ({ push: vi.fn() }),
+ useRowLink: () => () => ({}),
+}));
+
+const NOW = Date.now();
+
+function makeRuntime(overrides: Partial<AgentRuntime> = {}): AgentRuntime {
+ return {
+ id: "rt-claude",
+ workspace_id: WS,
+ daemon_id: "daemon-1",
+ name: "Claude (dev-machine.local)",
+ runtime_mode: "local",
+ provider: "claude",
+ launch_header: "",
+ status: "online",
+ device_info: "dev-machine.local · claude 1.0.0",
+ metadata: {},
+ owner_id: "user-1",
+ visibility: "private",
+ last_seen_at: new Date(NOW - 5_000).toISOString(),
+ created_at: new Date(NOW - 60_000).toISOString(),
+ updated_at: new Date(NOW - 60_000).toISOString(),
+ ...overrides,
+ };
+}
+
+function qoder(overrides: Partial<QoderConnection> = {}): QoderConnection {
+ return {
+ configured: false,
+ available: true,
+ name: "",
+ baseUrl: "",
+ environmentId: "",
+ hasToken: false,
+ repositories: [],
+ enabled: false,
+ status: "",
+ lastError: "",
+ maxConcurrency: 3,
+ runTimeoutMinutes: 60,
+ activeRuns: 0,
+ queuedRuns: 0,
+ ...overrides,
+ };
+}
+
+function renderPage({
+ runtimes = [makeRuntime()],
+ connection = qoder(),
+ desktop = false,
+}: {
+ runtimes?: AgentRuntime[];
+ connection?: QoderConnection;
+ desktop?: boolean;
+} = {}) {
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },
+ });
+ qc.setQueryData(runtimeListOptions(WS).queryKey, runtimes);
+ qc.setQueryData(runtimeProfileListOptions(WS).queryKey, []);
+ qc.setQueryData(agentListOptions(WS).queryKey, []);
+ qc.setQueryData(memberListOptions(WS).queryKey, []);
+ qc.setQueryData(agentTaskSnapshotOptions(WS).queryKey, []);
+ qc.setQueryData(chatSessionsOptions(WS).queryKey, []);
+ qc.setQueryData(qoderOptions(WS).queryKey, connection);
+ return render(
+ <QueryClientProvider client={qc}>
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <RuntimesPage
+ {...(desktop
+ ? {
+ localDaemonId: "daemon-1",
+ localMachineName: "Jiayuan's MacBook",
+ hasLocalMachine: true,
+ }
+ : {})}
+ />
+ </I18nProvider>
+ </QueryClientProvider>,
+ );
+}
+
+describe("RuntimesPage", () => {
+ it("lists machines and cloud services in one table", () => {
+ renderPage();
+
+ expect(screen.getByText("Machines")).toBeInTheDocument();
+ expect(screen.getByText("Cloud services")).toBeInTheDocument();
+ expect(screen.getByText("dev-machine.local")).toBeInTheDocument();
+ expect(screen.getByText("Not connected")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Connect" })).toBeInTheDocument();
+ expect(screen.getByText("Cursor Cloud Agents")).toBeInTheDocument();
+ expect(screen.getByText("Claude Managed Agents")).toBeInTheDocument();
+ });
+
+ it("offers the desktop download on web when no machine is connected", () => {
+ renderPage({ runtimes: [] });
+
+ expect(screen.getByText("Run on this computer")).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: /Download desktop/ })).toHaveAttribute(
+ "href",
+ "/download",
+ );
+ expect(screen.getByText("Add another machine or server")).toBeInTheDocument();
+ });
+
+ it("pins this device on desktop and marks it connected in the add menu", async () => {
+ const user = userEvent.setup();
+ renderPage({ desktop: true });
+
+ expect(screen.getByText("This device")).toBeInTheDocument();
+ expect(screen.queryByText("Run on this computer")).not.toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: /^Add/ }));
+ const menu = await screen.findByRole("menu");
+ expect(within(menu).getByText("Connected · Jiayuan's MacBook")).toBeInTheDocument();
+ expect(within(menu).getByText("Other machine or server")).toBeInTheDocument();
+ expect(within(menu).getByText("Qoder Cloud Agent")).toBeInTheDocument();
+ expect(within(menu).getByText("By Qoder")).toBeInTheDocument();
+ });
+
+ it("filters rows by search and status", async () => {
+ const user = userEvent.setup();
+ renderPage({
+ runtimes: [
+ makeRuntime(),
+ makeRuntime({
+ id: "rt-codex",
+ daemon_id: "daemon-2",
+ name: "Codex (build-server)",
+ provider: "codex",
+ device_info: "build-server · codex 0.5.0",
+ status: "offline",
+ last_seen_at: new Date(NOW - 3 * 60 * 60_000).toISOString(),
+ }),
+ ],
+ connection: qoder({ configured: true, enabled: true, status: "online" }),
+ });
+
+ await user.click(screen.getByRole("button", { name: /^Offline/ }));
+ expect(screen.getByText("build-server")).toBeInTheDocument();
+ expect(screen.queryByText("dev-machine.local")).not.toBeInTheDocument();
+ expect(screen.queryByText("Qoder Cloud Agent")).not.toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: /^All/ }));
+ await user.type(screen.getByRole("textbox"), "zzz");
+ expect(
+ screen.getByText("No machines or cloud services match"),
+ ).toBeInTheDocument();
+ });
+
+ it("never lists the Qoder runtime as a machine", () => {
+ const qoderRuntime = makeRuntime({
+ id: "rt-qoder",
+ daemon_id: "qoder-managed-ws-test",
+ name: "Qoder Cloud Agent",
+ provider: "qoder_cloud",
+ runtime_mode: "cloud",
+ device_info: "",
+ });
+ for (const connection of [
+ qoder({ configured: true, enabled: true, status: "online" }),
+ qoder({ available: false }),
+ ]) {
+ const { unmount } = renderPage({
+ runtimes: [makeRuntime(), qoderRuntime],
+ connection,
+ });
+ expect(screen.getByText("dev-machine.local")).toBeInTheDocument();
+ expect(screen.queryAllByText("Qoder Cloud Agent")).toHaveLength(
+ connection.available ? 1 : 0,
+ );
+ expect(screen.getByRole("button", { name: /^All/ })).toHaveTextContent(
+ connection.available ? "2" : "1",
+ );
+ unmount();
+ }
+ });
+});
diff --git a/packages/views/runtimes/components/runtimes-page.tsx b/packages/views/runtimes/components/runtimes-page.tsx
index 8bd3102a6e..f613adcb4c 100644
--- a/packages/views/runtimes/components/runtimes-page.tsx
+++ b/packages/views/runtimes/components/runtimes-page.tsx
@@ -1,29 +1,50 @@
"use client";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
import {
+ Check,
+ ChevronDown,
ChevronRight,
Cloud,
+ Download,
+ Laptop,
Loader2,
Monitor,
Plus,
+ Search,
Server,
+ SquareTerminal,
} from "lucide-react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { useAuthStore } from "@multica/core/auth";
import { useWorkspaceId } from "@multica/core/hooks";
-import { memberNeedsMikaSetup, useBootstrapMika } from "@multica/core/onboarding";
+import {
+ memberNeedsMikaSetup,
+ useBootstrapMika,
+} from "@multica/core/onboarding";
import { MIKA_PLACEHOLDER_EMOJI } from "../../onboarding/components/mika-intro";
-import { useRequiredWorkspaceSlug, useWorkspacePaths } from "@multica/core/paths";
+import {
+ useRequiredWorkspaceSlug,
+ useWorkspacePaths,
+} from "@multica/core/paths";
import { agentTaskSnapshotOptions } from "@multica/core/agents";
import { chatSessionsOptions } from "@multica/core/chat/queries";
import { runtimeProfileListOptions } from "@multica/core/runtimes";
-import { runtimeListOptions, runtimeKeys } from "@multica/core/runtimes/queries";
+import {
+ runtimeListOptions,
+ runtimeKeys,
+} from "@multica/core/runtimes/queries";
import { useWSEvent } from "@multica/core/realtime";
-import { agentListOptions } from "@multica/core/workspace/queries";
-import type { AgentRuntime } from "@multica/core/types";
-import { Button } from "@multica/ui/components/ui/button";
+import {
+ agentListOptions,
+ memberListOptions,
+} from "@multica/core/workspace/queries";
+import type { AgentRuntime, MemberWithUser } from "@multica/core/types";
+import type { QoderConnection } from "@multica/core/runtimes/qoder";
+import { Badge } from "@multica/ui/components/ui/badge";
+import { Button, buttonVariants } from "@multica/ui/components/ui/button";
+import { Input } from "@multica/ui/components/ui/input";
import {
Dialog,
DialogContent,
@@ -31,27 +52,44 @@ import {
DialogHeader,
DialogTitle,
} from "@multica/ui/components/ui/dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import {
+ ListGrid,
+ ListGridCell,
+ ListGridHeader,
+ ListGridHeaderCell,
+ ListGridRow,
+} from "@multica/ui/components/ui/list-grid";
import {
MikaRuntimeChoice,
type MikaRuntimeSelection,
} from "./mika-runtime-choice";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
-import {
- CollectionPageHeader,
- CollectionPageHeaderAction,
- CollectionPageState,
-} from "../../layout/collection-page";
+import { CollectionPageHeader } from "../../layout/collection-page";
import { PAGE_GUTTER, PAGE_RAIL, PageHeader } from "../../layout/page-header";
import { cn } from "@multica/ui/lib/utils";
-import { AppLink, useNavigation } from "../../navigation";
import {
- getMikaOnboarding,
- pickContentLang,
-} from "../../onboarding/templates";
+ AppLink,
+ rowLinkInteractiveProps,
+ useNavigation,
+ useRowLink,
+} from "../../navigation";
+import { getMikaOnboarding, pickContentLang } from "../../onboarding/templates";
+import { qoderOptions } from "@multica/core/runtimes/qoder";
+import { QODER_RUNTIME_LOCATOR } from "./qoder-detail-page";
+import { RemoteRuntimeDialog } from "./remote-runtime-dialog";
import { ConnectRemoteDialog } from "./connect-remote-dialog";
import { CloudRuntimeDialog } from "./cloud-runtime-dialog";
import { ProviderLogo } from "./provider-logo";
-import { buildWorkloadIndex, RuntimeList } from "./runtime-list";
+import { RuntimeList, buildWorkloadIndex } from "./runtime-list";
import { pendingRuntimeFromProfile } from "./pending-runtime";
import { buildRuntimeMachines, type RuntimeMachine } from "./runtime-machines";
import { HealthDot, HealthIcon, useHealthLabel } from "./shared";
@@ -71,6 +109,24 @@ export interface RuntimesPageProps {
cloudRuntimeEnabled?: boolean;
}
+type StatusFilter = "all" | "online" | "offline";
+const STATUS_FILTERS: StatusFilter[] = ["all", "online", "offline"];
+
+const COMING_SOON_SERVICES = [
+ { provider: "cursor", name: "Cursor Cloud Agents", vendor: "Cursor" },
+ { provider: "claude", name: "Claude Managed Agents", vendor: "Anthropic" },
+];
+
+// Track order: edge, name, harness, agents, workload, status, actions, edge.
+// Below @2xl only name, status and actions keep a track; the other cells are
+// `hidden @2xl:flex` and drop out of subgrid placement. MUST stay a literal
+// string so Tailwind sees the arbitrary template.
+const GRID_COLS =
+ "grid-cols-[0.5rem_minmax(160px,1fr)_112px_5.5rem_0.5rem] " +
+ "@2xl:grid-cols-[0.5rem_minmax(120px,1fr)_128px_64px_112px_136px_5.5rem_0.5rem]";
+
+const OPTIONAL_CELL = "hidden @2xl:flex";
+
function useNowTick(intervalMs = 30_000): number {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
@@ -80,6 +136,14 @@ function useNowTick(intervalMs = 30_000): number {
return now;
}
+function qoderIsOnline(connection: QoderConnection): boolean {
+ return (
+ connection.configured &&
+ connection.enabled &&
+ connection.status === "online"
+ );
+}
+
export function RuntimesPage({
localDaemonId,
localMachineName,
@@ -87,12 +151,19 @@ export function RuntimesPage({
bootstrapping,
cloudRuntimeEnabled = false,
}: RuntimesPageProps = {}) {
+ const { t, i18n } = useT("runtimes");
const isAuthLoading = useAuthStore((state) => state.isLoading);
const currentUserId = useAuthStore((state) => state.user?.id);
const wsId = useWorkspaceId();
const qc = useQueryClient();
+ const paths = useWorkspacePaths();
+ const { data: qoderConnection } = useQuery(qoderOptions(wsId));
+ const navigation = useNavigation();
+ const [qoderDialogOpen, setQoderDialogOpen] = useState(false);
const [showConnectDialog, setShowConnectDialog] = useState(false);
const [showCloudRuntimeDialog, setShowCloudRuntimeDialog] = useState(false);
+ const [query, setQuery] = useState("");
+ const [statusFilter, setStatusFilter] = useState<StatusFilter>("all");
const { data: runtimes = [], isLoading: runtimesLoading } = useQuery(
runtimeListOptions(wsId),
@@ -103,6 +174,7 @@ export function RuntimesPage({
const { data: agents = [], isLoading: agentsLoading } = useQuery(
agentListOptions(wsId),
);
+ const { data: members = [] } = useQuery(memberListOptions(wsId));
const { data: snapshot = [] } = useQuery(agentTaskSnapshotOptions(wsId));
// The Mika entrypoint is per member, not per workspace: the agent alone does
// not say whether *this* member's conversation was ever opened and kicked
@@ -120,6 +192,14 @@ export function RuntimesPage({
() => buildWorkloadIndex(agents, snapshot),
[agents, snapshot],
);
+ const agentCountByRuntime = useMemo(() => {
+ const counts = new Map<string, number>();
+ for (const agent of agents) {
+ if (!agent.runtime_id) continue;
+ counts.set(agent.runtime_id, (counts.get(agent.runtime_id) ?? 0) + 1);
+ }
+ return counts;
+ }, [agents]);
const now = useNowTick();
const machines = useMemo(
() =>
@@ -157,56 +237,233 @@ export function RuntimesPage({
return <RuntimesPageSkeleton />;
}
- const showEmpty =
- machines.length === 0 &&
- orphanProfileRuntimes.length === 0 &&
- !bootstrapping &&
- hasLocalMachine !== true;
+ const isDesktop = hasLocalMachine === true;
+ const qoder = qoderConnection?.available === true ? qoderConnection : null;
+ const qoderHref = paths.runtimeDetail(QODER_RUNTIME_LOCATOR);
+ // Qoder's runtime registers like a machine, but it is listed once, as a
+ // cloud service — never as a machine, even when this server cannot run
+ // Qoder and the cloud row is hidden.
+ const machineList = machines.filter(
+ (machine) =>
+ !(
+ machine.runtimes.length > 0 &&
+ machine.runtimes.every((runtime) => runtime.provider === "qoder_cloud")
+ ),
+ );
+ const qoderAgentCount = agents.filter((agent) =>
+ runtimes.some(
+ (runtime) =>
+ runtime.id === agent.runtime_id && runtime.provider === "qoder_cloud",
+ ),
+ ).length;
+ const localMachine = machineList.find((machine) => machine.isCurrent);
+
+ const needle = query.trim().toLowerCase();
+ const filtering = needle.length > 0 || statusFilter !== "all";
+ const matchesQuery = (...fields: (string | null | undefined)[]) =>
+ !needle || fields.some((field) => field?.toLowerCase().includes(needle));
+ const matchesStatus = (online: boolean) =>
+ statusFilter === "all" || (statusFilter === "online") === online;
+
+ const visibleMachines = machineList.filter(
+ (machine) =>
+ matchesStatus(machine.health === "online") &&
+ matchesQuery(machine.title, machine.subtitle, ...machine.providerNames),
+ );
+ const qoderConfigured = qoder?.configured === true;
+ const showQoderRow =
+ qoder !== null &&
+ matchesQuery(t(($) => $.qoder.cloud_title), "qoder") &&
+ (statusFilter === "all" ||
+ (qoderConfigured && matchesStatus(qoderIsOnline(qoder))));
+ const visibleComingSoon =
+ statusFilter === "all"
+ ? COMING_SOON_SERVICES.filter((service) =>
+ matchesQuery(service.name, service.vendor),
+ )
+ : [];
+ const showThisComputerRow =
+ !filtering && !isDesktop && machineList.length === 0;
+ const showAddMachineRow = !filtering && machineList.length === 0;
+ const nothingMatches =
+ filtering &&
+ visibleMachines.length === 0 &&
+ !showQoderRow &&
+ visibleComingSoon.length === 0;
+
+ const configuredCloudCount = qoderConfigured ? 1 : 0;
+ const totalCount = machineList.length + configuredCloudCount;
+ const onlineCount =
+ machineList.filter((machine) => machine.health === "online").length +
+ (qoder && qoderIsOnline(qoder) ? 1 : 0);
+ const statusCounts: Record<StatusFilter, number> = {
+ all: totalCount,
+ online: onlineCount,
+ offline: totalCount - onlineCount,
+ };
+
+ const openQoder = () =>
+ qoderConfigured ? navigation.push(qoderHref) : setQoderDialogOpen(true);
return (
<div className="flex min-h-0 flex-1 flex-col">
- <PageHeaderBar
- totalCount={machines.length}
- onConnectRemote={() => setShowConnectDialog(true)}
- cloudRuntimeEnabled={cloudRuntimeEnabled}
- onOpenCloudRuntime={() => setShowCloudRuntimeDialog(true)}
+ <CollectionPageHeader
+ icon={Server}
+ title={t(($) => $.page.title)}
+ count={totalCount}
+ description={t(($) => $.page.tagline)}
+ learnMore={{
+ href: daemonRuntimesDocsHref(i18n.language),
+ label: t(($) => $.page.learn_more),
+ }}
+ actions={
+ <AddRuntimeMenu
+ isDesktop={isDesktop}
+ localMachineName={localMachineName ?? localMachine?.title ?? null}
+ qoder={qoder}
+ cloudRuntimeEnabled={cloudRuntimeEnabled}
+ onAddMachine={() => setShowConnectDialog(true)}
+ onQoder={openQoder}
+ onCloudRuntime={() => setShowCloudRuntimeDialog(true)}
+ />
+ }
/>
- {showEmpty ? (
- <div className="flex flex-1 items-center justify-center p-6">
- <EmptyState onConnectRemote={() => setShowConnectDialog(true)} />
- </div>
- ) : (
- <div className="min-h-0 flex-1 overflow-y-auto">
- <div className={cn(PAGE_RAIL, PAGE_GUTTER, "flex flex-col py-4 sm:py-6")}>
- {!agentsLoading &&
- !chatSessionsLoading &&
- memberNeedsMikaSetup(agents, chatSessions) &&
- runtimes.length > 0 && (
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <div className={cn(PAGE_RAIL, PAGE_GUTTER, "flex flex-col gap-3 py-4 sm:py-6")}>
+ <RuntimesToolbar
+ query={query}
+ onQueryChange={setQuery}
+ statusFilter={statusFilter}
+ onStatusFilterChange={setStatusFilter}
+ counts={statusCounts}
+ />
+
+ <div className="@container overflow-hidden rounded-lg border bg-card">
+ <ListGrid className={cn(GRID_COLS, "[&>[role=row]:last-child]:border-b-0")}>
+ <ListGridHeader className="static border-b bg-card after:hidden">
+ <ListGridHeaderCell>{t(($) => $.page.columns.name)}</ListGridHeaderCell>
+ <ListGridHeaderCell className={OPTIONAL_CELL}>
+ {t(($) => $.page.columns.harness)}
+ </ListGridHeaderCell>
+ <ListGridHeaderCell className={OPTIONAL_CELL}>
+ {t(($) => $.page.columns.agents)}
+ </ListGridHeaderCell>
+ <ListGridHeaderCell className={OPTIONAL_CELL}>
+ {t(($) => $.page.columns.workload)}
+ </ListGridHeaderCell>
+ <ListGridHeaderCell>{t(($) => $.page.columns.status)}</ListGridHeaderCell>
+ <ListGridHeaderCell aria-hidden="true" />
+ </ListGridHeader>
+
+ {nothingMatches ? (
+ <div
+ role="row"
+ className="col-span-full px-4 py-10 text-center text-caption text-muted-foreground"
+ >
+ {t(($) => $.page.rows.no_matches)}
+ </div>
+ ) : (
+ <>
+ <GroupHeader
+ title={t(($) => $.page.groups.machines.title)}
+ count={machineList.length}
+ />
+ {visibleMachines.map((machine) => (
+ <MachineRow
+ key={machine.id}
+ machine={machine}
+ bootstrapping={bootstrapping}
+ currentUserId={currentUserId ?? null}
+ members={members}
+ agentCount={machine.runtimes.reduce(
+ (sum, runtime) =>
+ sum + (agentCountByRuntime.get(runtime.id) ?? 0),
+ 0,
+ )}
+ />
+ ))}
+ {showThisComputerRow && (
+ <ActionRow
+ icon={Laptop}
+ title={t(($) => $.page.rows.this_computer_title)}
+ description={t(($) => $.page.rows.this_computer_hint)}
+ action={
+ <a
+ href="/download"
+ target="_blank"
+ rel="noreferrer"
+ className={buttonVariants({ variant: "outline", size: "sm" })}
+ >
+ <Download aria-hidden="true" className="size-3.5" />
+ {t(($) => $.page.rows.download_desktop)}
+ </a>
+ }
+ />
+ )}
+ {showAddMachineRow && (
+ <ActionRow
+ icon={SquareTerminal}
+ title={t(($) => $.page.rows.add_machine_title)}
+ description={t(($) => $.page.rows.add_machine_hint)}
+ action={
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setShowConnectDialog(true)}
+ >
+ {t(($) => $.page.rows.view_commands)}
+ </Button>
+ }
+ />
+ )}
+
+ <GroupHeader
+ title={t(($) => $.page.groups.cloud.title)}
+ count={configuredCloudCount}
+ />
+ {showQoderRow && qoder && (
+ <QoderRow
+ connection={qoder}
+ agentCount={qoderAgentCount}
+ detailHref={qoderHref}
+ onConnect={() => setQoderDialogOpen(true)}
+ />
+ )}
+ {visibleComingSoon.map((service) => (
+ <ComingSoonRow key={service.provider} {...service} />
+ ))}
+ </>
+ )}
+ </ListGrid>
+ </div>
+
+ {!agentsLoading &&
+ !chatSessionsLoading &&
+ memberNeedsMikaSetup(agents, chatSessions) &&
+ runtimes.some((runtime) => runtime.provider !== "qoder_cloud") && (
<MikaSetupCard
workspaceId={wsId}
- runtimes={runtimes}
+ runtimes={runtimes.filter(
+ (runtime) => runtime.provider !== "qoder_cloud",
+ )}
runtimesLoading={runtimesLoading}
currentUserId={currentUserId ?? null}
/>
)}
- {(machines.length > 0 || bootstrapping) && (
- <MachineList
- machines={machines}
- bootstrapping={bootstrapping}
- />
- )}
- {orphanProfileRuntimes.length > 0 && (
- <OrphanRuntimeProfiles
- runtimes={orphanProfileRuntimes}
- now={now}
- hasMachines={machines.length > 0}
- />
- )}
- </div>
+ {orphanProfileRuntimes.length > 0 && (
+ <OrphanRuntimeProfiles
+ runtimes={orphanProfileRuntimes}
+ now={now}
+ hasMachines={machines.length > 0}
+ />
+ )}
</div>
- )}
+ </div>
+ {qoderDialogOpen && (
+ <RemoteRuntimeDialog onClose={() => setQoderDialogOpen(false)} />
+ )}
{showConnectDialog && (
<ConnectRemoteDialog onClose={() => setShowConnectDialog(false)} />
)}
@@ -217,6 +474,617 @@ export function RuntimesPage({
);
}
+function AddRuntimeMenu({
+ isDesktop,
+ localMachineName,
+ qoder,
+ cloudRuntimeEnabled,
+ onAddMachine,
+ onQoder,
+ onCloudRuntime,
+}: {
+ isDesktop: boolean;
+ localMachineName: string | null;
+ qoder: QoderConnection | null;
+ cloudRuntimeEnabled: boolean;
+ onAddMachine: () => void;
+ onQoder: () => void;
+ onCloudRuntime: () => void;
+}) {
+ const { t } = useT("runtimes");
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button size="sm" className="gap-1">
+ <Plus aria-hidden="true" className="size-3.5" />
+ {t(($) => $.page.add)}
+ <ChevronDown aria-hidden="true" className="size-3.5 opacity-70" />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end" className="w-80">
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{t(($) => $.page.add_menu.machines)}</DropdownMenuLabel>
+ {isDesktop ? (
+ <AddMenuItem
+ icon={<Laptop className="size-4 text-muted-foreground" />}
+ title={t(($) => $.page.add_menu.this_computer)}
+ description={
+ localMachineName
+ ? t(($) => $.page.add_menu.this_computer_connected, {
+ name: localMachineName,
+ })
+ : undefined
+ }
+ trailing={<Check className="size-4 text-muted-foreground" />}
+ disabled
+ />
+ ) : (
+ <AddMenuItem
+ icon={<Laptop className="size-4 text-muted-foreground" />}
+ title={t(($) => $.page.add_menu.this_computer)}
+ description={t(($) => $.page.add_menu.this_computer_download)}
+ render={<a href="/download" target="_blank" rel="noreferrer" />}
+ />
+ )}
+ <AddMenuItem
+ icon={<SquareTerminal className="size-4 text-muted-foreground" />}
+ title={t(($) => $.page.add_menu.other_machine)}
+ description={t(($) => $.page.add_menu.other_machine_hint)}
+ onClick={onAddMachine}
+ />
+ </DropdownMenuGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{t(($) => $.page.add_menu.cloud_services)}</DropdownMenuLabel>
+ {qoder && (
+ <AddMenuItem
+ icon={<ProviderLogo provider="qoder_cloud" className="size-4" />}
+ title={t(($) => $.qoder.cloud_title)}
+ description={
+ qoder.configured
+ ? t(($) => $.page.add_menu.qoder_manage_hint)
+ : t(($) => $.page.rows.provided_by, { vendor: "Qoder" })
+ }
+ trailing={
+ qoder.configured ? (
+ <Check className="size-4 text-muted-foreground" />
+ ) : undefined
+ }
+ onClick={onQoder}
+ />
+ )}
+ {cloudRuntimeEnabled && (
+ <AddMenuItem
+ icon={<Cloud className="size-4 text-muted-foreground" />}
+ title={t(($) => $.cloud_runtime.action)}
+ description={t(($) => $.page.add_menu.cloud_runtime_hint)}
+ onClick={onCloudRuntime}
+ />
+ )}
+ {COMING_SOON_SERVICES.map((service) => (
+ <AddMenuItem
+ key={service.provider}
+ icon={<ProviderLogo provider={service.provider} className="size-4" />}
+ title={service.name}
+ description={t(($) => $.page.rows.provided_by, {
+ vendor: service.vendor,
+ })}
+ trailing={
+ <Badge variant="secondary" className="shrink-0">
+ {t(($) => $.page.groups.cloud.coming_soon)}
+ </Badge>
+ }
+ disabled
+ />
+ ))}
+ </DropdownMenuGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+function AddMenuItem({
+ icon,
+ title,
+ description,
+ trailing,
+ ...props
+}: {
+ icon: ReactNode;
+ title: string;
+ description?: string;
+ trailing?: ReactNode;
+} & Omit<React.ComponentProps<typeof DropdownMenuItem>, "children" | "title">) {
+ return (
+ <DropdownMenuItem className="gap-2.5 px-2 py-1.5" {...props}>
+ <span className="flex size-7 shrink-0 items-center justify-center rounded-md border bg-background">
+ {icon}
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate text-body font-medium">{title}</span>
+ {description && (
+ <span className="truncate text-caption text-muted-foreground">
+ {description}
+ </span>
+ )}
+ </span>
+ {trailing}
+ </DropdownMenuItem>
+ );
+}
+
+function RuntimesToolbar({
+ query,
+ onQueryChange,
+ statusFilter,
+ onStatusFilterChange,
+ counts,
+}: {
+ query: string;
+ onQueryChange: (query: string) => void;
+ statusFilter: StatusFilter;
+ onStatusFilterChange: (filter: StatusFilter) => void;
+ counts: Record<StatusFilter, number>;
+}) {
+ const { t } = useT("runtimes");
+ const labels: Record<StatusFilter, string> = {
+ all: t(($) => $.page.filters.all),
+ online: t(($) => $.page.filters.online),
+ offline: t(($) => $.page.filters.offline),
+ };
+ return (
+ <div className="flex min-w-0 items-center gap-2">
+ <div className="relative min-w-0 flex-1 sm:flex-none">
+ <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ value={query}
+ onChange={(e) => onQueryChange(e.target.value)}
+ aria-label={t(($) => $.page.search_placeholder)}
+ placeholder={t(($) => $.page.search_placeholder)}
+ className="h-8 w-full pl-8 text-body sm:w-64"
+ />
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ {STATUS_FILTERS.map((filter) => (
+ <Button
+ key={filter}
+ variant="outline"
+ size="sm"
+ aria-pressed={statusFilter === filter}
+ className={
+ statusFilter === filter
+ ? "gap-1.5 bg-accent text-accent-foreground hover:bg-accent/80"
+ : "gap-1.5 text-muted-foreground"
+ }
+ onClick={() => onStatusFilterChange(filter)}
+ >
+ {labels[filter]}
+ <span className="tabular-nums text-caption text-muted-foreground">
+ {counts[filter]}
+ </span>
+ </Button>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function GroupHeader({ title, count }: { title: string; count: number }) {
+ return (
+ <div
+ role="row"
+ className="col-span-full flex h-9 min-w-0 items-center gap-2 border-b bg-muted/40 px-4 text-caption"
+ >
+ <span className="font-semibold text-foreground">{title}</span>
+ <span className="font-mono tabular-nums text-muted-foreground">{count}</span>
+ </div>
+ );
+}
+
+function ActionRow({
+ icon: Icon,
+ title,
+ description,
+ action,
+}: {
+ icon: typeof Server;
+ title: string;
+ description: string;
+ action: ReactNode;
+}) {
+ return (
+ <div
+ role="row"
+ className="col-span-full flex min-h-14 items-center gap-3 border-b px-4 py-2.5"
+ >
+ <span className="flex size-8 shrink-0 items-center justify-center rounded-lg border border-dashed text-muted-foreground">
+ <Icon aria-hidden="true" className="size-4" />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-body font-medium">{title}</span>
+ <span className="block truncate text-caption text-muted-foreground">
+ {description}
+ </span>
+ </span>
+ <span className="shrink-0">{action}</span>
+ </div>
+ );
+}
+
+function RowTile({
+ children,
+ dot,
+}: {
+ children: ReactNode;
+ dot?: ReactNode;
+}) {
+ return (
+ <span className="relative flex size-8 shrink-0 items-center justify-center rounded-lg border bg-background">
+ {children}
+ {dot}
+ </span>
+ );
+}
+
+function NameCell({
+ tile,
+ title,
+ href,
+ badge,
+ subtitle,
+ muted,
+}: {
+ tile: ReactNode;
+ title: string;
+ href?: string;
+ badge?: ReactNode;
+ subtitle: string;
+ muted?: boolean;
+}) {
+ return (
+ <ListGridCell className="gap-3 py-2.5">
+ {tile}
+ <span className="min-w-0 flex-1">
+ <span className="flex min-w-0 items-center gap-2">
+ {href ? (
+ <AppLink
+ href={href}
+ className="truncate text-body font-medium focus-visible:outline-none focus-visible:underline"
+ {...rowLinkInteractiveProps}
+ >
+ {title}
+ </AppLink>
+ ) : (
+ <span
+ className={cn(
+ "truncate text-body font-medium",
+ muted && "text-muted-foreground",
+ )}
+ >
+ {title}
+ </span>
+ )}
+ {badge}
+ </span>
+ <span className="block truncate text-caption text-muted-foreground">
+ {subtitle}
+ </span>
+ </span>
+ </ListGridCell>
+ );
+}
+
+function EmptyCell({ optional = true }: { optional?: boolean }) {
+ return (
+ <ListGridCell className={cn(optional && OPTIONAL_CELL, "text-caption text-faint-foreground")}>
+ —
+ </ListGridCell>
+ );
+}
+
+function RowChevron() {
+ return (
+ <ListGridCell className="justify-end">
+ <ChevronRight
+ aria-hidden="true"
+ className="size-4 text-faint-foreground transition-transform group-hover/row:translate-x-0.5 group-hover/row:text-muted-foreground"
+ />
+ </ListGridCell>
+ );
+}
+
+function WorkloadText({
+ running,
+ queued,
+}: {
+ running: number;
+ queued: number;
+}) {
+ const { t } = useT("runtimes");
+ if (running + queued === 0) {
+ return (
+ <span className="text-caption text-muted-foreground">
+ {t(($) => $.machine.metrics.workload_idle)}
+ </span>
+ );
+ }
+ return (
+ <span className="truncate text-caption tabular-nums">
+ {t(($) => $.machine.metrics.workload_hint, { running, queued })}
+ </span>
+ );
+}
+
+function MachineRow({
+ machine,
+ bootstrapping,
+ currentUserId,
+ members,
+ agentCount,
+}: {
+ machine: RuntimeMachine;
+ bootstrapping?: boolean;
+ currentUserId: string | null;
+ members: MemberWithUser[];
+ agentCount: number;
+}) {
+ const { t } = useT("runtimes");
+ const healthLabel = useHealthLabel();
+ const timeAgo = useTimeAgo();
+ const paths = useWorkspacePaths();
+ const rowLink = useRowLink();
+ const href = paths.runtimeDetail(machine.id);
+ const Icon = machine.isCurrent
+ ? Laptop
+ : machine.section === "cloud"
+ ? Cloud
+ : Monitor;
+ const ownerId = machine.runtimes[0]?.owner_id ?? null;
+ const owner =
+ ownerId && ownerId === currentUserId
+ ? t(($) => $.page.rows.owner_you)
+ : (members.find((member) => member.user_id === ownerId)?.name ?? null);
+ const subtitle =
+ [machine.deviceSummary, owner].filter(Boolean).join(" · ") ||
+ (machine.section === "cloud"
+ ? t(($) => $.machine.metrics.cloud_worker)
+ : t(($) => $.machine.metrics.local_daemon));
+ const starting =
+ machine.isCurrent && bootstrapping && machine.runtimes.length === 0;
+ const online = machine.health === "online";
+
+ return (
+ <ListGridRow
+ className="h-auto min-h-14 cursor-pointer border-b"
+ {...rowLink(href, machine.title)}
+ >
+ <NameCell
+ tile={
+ <RowTile
+ dot={
+ <HealthDot
+ health={machine.health}
+ className="absolute -bottom-0.5 -right-0.5 ring-2 ring-card"
+ />
+ }
+ >
+ <Icon aria-hidden="true" className="size-4 text-muted-foreground" />
+ </RowTile>
+ }
+ title={machine.title}
+ href={href}
+ badge={
+ machine.isCurrent ? (
+ <Badge variant="secondary" className="shrink-0">
+ {t(($) => $.machine.this_machine)}
+ </Badge>
+ ) : undefined
+ }
+ subtitle={subtitle}
+ />
+ <ListGridCell className={OPTIONAL_CELL}>
+ <ProviderIconStack providers={machine.providerNames} />
+ </ListGridCell>
+ <ListGridCell className={cn(OPTIONAL_CELL, "text-body tabular-nums")}>
+ {agentCount}
+ </ListGridCell>
+ {online ? (
+ <ListGridCell className={OPTIONAL_CELL}>
+ <WorkloadText
+ running={machine.runningCount}
+ queued={machine.queuedCount}
+ />
+ </ListGridCell>
+ ) : (
+ <EmptyCell />
+ )}
+ <ListGridCell className="gap-1.5 text-caption">
+ {starting ? (
+ <>
+ <Loader2 aria-hidden="true" className="size-3 animate-spin text-muted-foreground" />
+ <span className="truncate text-muted-foreground">
+ {t(($) => $.page.bootstrapping.title)}
+ </span>
+ </>
+ ) : (
+ <>
+ <HealthIcon health={machine.health} />
+ <span className={cn("truncate", !online && "text-muted-foreground")}>
+ {healthLabel(machine.health)}
+ {!online && machine.lastSeenAt
+ ? ` · ${timeAgo(machine.lastSeenAt)}`
+ : ""}
+ </span>
+ </>
+ )}
+ </ListGridCell>
+ <RowChevron />
+ </ListGridRow>
+ );
+}
+
+function QoderRow({
+ connection,
+ agentCount,
+ detailHref,
+ onConnect,
+}: {
+ connection: QoderConnection;
+ agentCount: number;
+ detailHref: string;
+ onConnect: () => void;
+}) {
+ const { t } = useT("runtimes");
+ const rowLink = useRowLink();
+ const title = t(($) => $.qoder.cloud_title);
+ const logo = <ProviderLogo provider="qoder_cloud" className="size-4" />;
+ const byQoder = t(($) => $.page.rows.provided_by, { vendor: "Qoder" });
+
+ if (!connection.configured) {
+ return (
+ <ListGridRow className="h-auto min-h-14 border-b">
+ <NameCell
+ tile={
+ <RowTile
+ dot={
+ <span className="absolute -bottom-0.5 -right-0.5 size-2 rounded-full bg-warning ring-2 ring-card" />
+ }
+ >
+ {logo}
+ </RowTile>
+ }
+ title={title}
+ subtitle={byQoder}
+ />
+ <EmptyCell />
+ <EmptyCell />
+ <EmptyCell />
+ <ListGridCell>
+ <Badge variant="secondary" className="bg-warning/10 text-warning">
+ {t(($) => $.page.rows.not_connected)}
+ </Badge>
+ </ListGridCell>
+ <ListGridCell className="justify-end">
+ <Button variant="outline" size="sm" onClick={onConnect}>
+ {t(($) => $.page.rows.connect)}
+ </Button>
+ </ListGridCell>
+ </ListGridRow>
+ );
+ }
+
+ const status = !connection.enabled
+ ? "stopped"
+ : connection.status === "online"
+ ? "online"
+ : connection.status === "error"
+ ? "error"
+ : connection.status === "offline"
+ ? "offline"
+ : "starting";
+ const dotTone =
+ status === "online"
+ ? "bg-success"
+ : status === "error"
+ ? "bg-destructive"
+ : status === "starting"
+ ? "bg-warning"
+ : "bg-muted-foreground/40";
+ const subtitle =
+ status === "error" && connection.lastError ? connection.lastError : byQoder;
+
+ return (
+ <ListGridRow
+ className="h-auto min-h-14 cursor-pointer border-b"
+ {...rowLink(detailHref, title)}
+ >
+ <NameCell
+ tile={
+ <RowTile
+ dot={
+ <span
+ className={cn(
+ "absolute -bottom-0.5 -right-0.5 size-2 rounded-full ring-2 ring-card",
+ dotTone,
+ )}
+ />
+ }
+ >
+ {logo}
+ </RowTile>
+ }
+ title={title}
+ href={detailHref}
+ subtitle={subtitle}
+ />
+ <EmptyCell />
+ <ListGridCell className={cn(OPTIONAL_CELL, "text-body tabular-nums")}>
+ {agentCount}
+ </ListGridCell>
+ {status === "online" ? (
+ <ListGridCell className={OPTIONAL_CELL}>
+ <WorkloadText
+ running={connection.activeRuns}
+ queued={connection.queuedRuns}
+ />
+ </ListGridCell>
+ ) : (
+ <EmptyCell />
+ )}
+ <ListGridCell className="gap-1.5 text-caption">
+ <span aria-hidden="true" className={cn("size-1.5 rounded-full", dotTone)} />
+ <span
+ className={cn(
+ "truncate",
+ status === "error" && "text-destructive",
+ status !== "online" && status !== "error" && "text-muted-foreground",
+ )}
+ >
+ {t(($) => $.qoder[status])}
+ </span>
+ </ListGridCell>
+ <RowChevron />
+ </ListGridRow>
+ );
+}
+
+function ComingSoonRow({
+ provider,
+ name,
+ vendor,
+}: {
+ provider: string;
+ name: string;
+ vendor: string;
+}) {
+ const { t } = useT("runtimes");
+ return (
+ <ListGridRow className="h-auto min-h-14 border-b hover:bg-transparent">
+ <NameCell
+ tile={
+ <RowTile>
+ <span className="opacity-60">
+ <ProviderLogo provider={provider} className="size-4" />
+ </span>
+ </RowTile>
+ }
+ title={name}
+ subtitle={t(($) => $.page.rows.provided_by, { vendor })}
+ muted
+ />
+ <EmptyCell />
+ <EmptyCell />
+ <EmptyCell />
+ <ListGridCell>
+ <Badge variant="secondary">{t(($) => $.page.groups.cloud.coming_soon)}</Badge>
+ </ListGridCell>
+ <ListGridCell aria-hidden="true" />
+ </ListGridRow>
+ );
+}
+
/**
* Entry point for creating Mika once a runtime exists.
*
@@ -282,7 +1150,7 @@ function MikaSetupCard({
return (
<>
- <div className="mb-6 flex flex-col gap-4 rounded-xl border bg-card p-5 sm:flex-row sm:items-center">
+ <div className="flex flex-col gap-4 rounded-xl border bg-card p-5 sm:flex-row sm:items-center">
<span
role="img"
aria-label={t(($) => $.mika_setup.title)}
@@ -369,163 +1237,6 @@ function OrphanRuntimeProfiles({
);
}
-function PageHeaderBar({
- totalCount,
- onConnectRemote,
- cloudRuntimeEnabled,
- onOpenCloudRuntime,
-}: {
- totalCount: number;
- onConnectRemote: () => void;
- cloudRuntimeEnabled: boolean;
- onOpenCloudRuntime: () => void;
-}) {
- const { t, i18n } = useT("runtimes");
- return (
- <CollectionPageHeader
- icon={Server}
- title={t(($) => $.page.title)}
- count={totalCount}
- description={t(($) => $.page.tagline)}
- learnMore={{
- href: daemonRuntimesDocsHref(i18n.language),
- label: t(($) => $.page.learn_more),
- }}
- actions={
- <>
- {cloudRuntimeEnabled && (
- <CollectionPageHeaderAction
- icon={Cloud}
- label={t(($) => $.cloud_runtime.action)}
- onClick={onOpenCloudRuntime}
- />
- )}
- <CollectionPageHeaderAction
- icon={Plus}
- label={t(($) => $.page.connect_remote)}
- onClick={onConnectRemote}
- />
- </>
- }
- />
- );
-}
-
-function MachineList({
- machines,
- bootstrapping,
-}: {
- machines: RuntimeMachine[];
- bootstrapping?: boolean;
-}) {
- const { t } = useT("runtimes");
- if (machines.length === 0) {
- return (
- <CollectionPageState
- icon={Server}
- title={
- bootstrapping
- ? t(($) => $.page.bootstrapping.title)
- : t(($) => $.page.empty.title)
- }
- description={
- bootstrapping
- ? t(($) => $.page.bootstrapping.hint)
- : t(($) => $.page.empty.hint)
- }
- />
- );
- }
-
- return (
- <div className="overflow-hidden rounded-lg border bg-card">
- <div className="divide-y">
- {machines.map((machine) => (
- <MachineRow key={machine.id} machine={machine} />
- ))}
- </div>
- </div>
- );
-}
-
-function MachineRow({ machine }: { machine: RuntimeMachine }) {
- const { t } = useT("runtimes");
- const healthLabel = useHealthLabel();
- const timeAgo = useTimeAgo();
- const paths = useWorkspacePaths();
- const Icon = machine.section === "cloud" ? Cloud : Monitor;
- const locator = machine.id;
- const busyCount = machine.runningCount + machine.queuedCount;
- const body = (
- <>
- <span className="relative flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border bg-background">
- <Icon aria-hidden="true" className="h-4 w-4 text-muted-foreground" />
- <HealthDot
- health={machine.health}
- className="absolute -bottom-0.5 -right-0.5 ring-2 ring-background"
- />
- </span>
- <span className="min-w-0 flex-1">
- <span className="block truncate text-body font-medium">
- {machine.title}
- </span>
- <span className="mt-1 flex min-w-0 items-center gap-2 text-caption text-muted-foreground">
- <span className="truncate">
- {machine.subtitle ??
- (machine.section === "cloud"
- ? t(($) => $.machine.metrics.cloud_worker)
- : t(($) => $.machine.metrics.local_daemon))}
- </span>
- {machine.isCurrent && (
- <span className="shrink-0 rounded-xs bg-muted px-1.5 py-0.5 text-micro font-medium text-muted-foreground">
- {t(($) => $.machine.this_machine)}
- </span>
- )}
- </span>
- </span>
-
- <span className="hidden w-36 shrink-0 items-center gap-1.5 text-caption md:flex">
- <HealthIcon health={machine.health} />
- <span>{healthLabel(machine.health)}</span>
- </span>
- <span className="hidden w-40 shrink-0 flex-col gap-1 lg:flex">
- <span className="text-caption text-muted-foreground">
- {t(($) => $.machine.runtime_count, {
- count: machine.runtimes.length,
- })}
- </span>
- <ProviderIconStack providers={machine.providerNames} />
- </span>
- <span className="hidden w-36 shrink-0 text-caption text-muted-foreground xl:block">
- {busyCount > 0
- ? t(($) => $.machine.metrics.workload_hint, {
- running: machine.runningCount,
- queued: machine.queuedCount,
- })
- : t(($) => $.machine.metrics.workload_idle)}
- </span>
- <span className="hidden w-28 shrink-0 text-right text-caption text-muted-foreground lg:block">
- {machine.lastSeenAt ? timeAgo(machine.lastSeenAt) : "—"}
- </span>
- {locator && (
- <ChevronRight
- aria-hidden="true"
- className="h-4 w-4 shrink-0 text-faint-foreground transition-transform group-hover:translate-x-0.5 group-hover:text-muted-foreground"
- />
- )}
- </>
- );
-
- return (
- <AppLink
- href={paths.runtimeDetail(locator)}
- className="group flex min-w-0 items-center gap-3 px-4 py-3.5 transition-colors hover:bg-accent/40 focus-visible:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
- >
- {body}
- </AppLink>
- );
-}
-
function ProviderIconStack({ providers }: { providers: string[] }) {
const visible = providers.slice(0, 4);
const extra = providers.length - visible.length;
@@ -549,23 +1260,6 @@ function ProviderIconStack({ providers }: { providers: string[] }) {
);
}
-function EmptyState({ onConnectRemote }: { onConnectRemote: () => void }) {
- const { t } = useT("runtimes");
- return (
- <CollectionPageState
- icon={Server}
- title={t(($) => $.page.empty.title)}
- description={t(($) => $.page.empty.hint)}
- actions={
- <Button type="button" size="sm" onClick={onConnectRemote}>
- <Plus aria-hidden="true" className="size-3" />
- {t(($) => $.page.connect_remote)}
- </Button>
- }
- />
- );
-}
-
function RuntimesPageSkeleton() {
return (
<div className="flex min-h-0 flex-1 flex-col">
@@ -575,7 +1269,10 @@ function RuntimesPageSkeleton() {
<div className={cn(PAGE_RAIL, PAGE_GUTTER, "py-6")}>
<div className="overflow-hidden rounded-lg border">
{Array.from({ length: 5 }).map((_, index) => (
- <div key={index} className="flex h-[76px] items-center gap-3 border-b px-4 last:border-b-0">
+ <div
+ key={index}
+ className="flex h-[76px] items-center gap-3 border-b px-4 last:border-b-0"
+ >
<Skeleton className="h-10 w-10 rounded-lg" />
<div className="flex-1">
<Skeleton className="h-4 w-44" />
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index cece0fdddb..48d20158a2 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -187,6 +187,7 @@ var concurrentIndexCleanups = map[string]string{
"486_maintenance_job_id_index": "idx_maintenance_job_id",
"487_maintenance_job_idempotency_index": "idx_maintenance_job_idempotency",
"488_maintenance_job_active_index": "idx_maintenance_job_active",
+ "587_cloud_agent_connection_provider_index": "cloud_agent_connection_provider_index",
"035_task_queue_issue_id_index": "idx_agent_task_queue_issue_id",
"067_task_queue_claim_candidate_index": "idx_agent_task_queue_claim_candidates",
"074_task_usage_updated_at_index": "idx_task_usage_updated_at",
diff --git a/server/cmd/qoder-runtime/README.md b/server/cmd/qoder-runtime/README.md
new file mode 100644
index 0000000000..8a14ce90f8
--- /dev/null
+++ b/server/cmd/qoder-runtime/README.md
@@ -0,0 +1,283 @@
+# Qoder Cloud Agent runtime bridge (PoC)
+
+This standalone service registers a `qoder_cloud` runtime in one Multica
+workspace. Bind a Multica agent to that runtime and assign it an issue. The
+bridge reads issue context using the claim's task-scoped token, creates a
+managed Qoder session, sends the work, and reports messages and the final result.
+No local coding-agent CLI, repository checkout, or shell execution is performed
+by the bridge. Run it on a server that can reach both APIs.
+
+## Issue status
+
+For issues still assigned to the executing Qoder agent, the server moves
+`todo` or `backlog` to `in_progress` when execution starts. A successful run
+moves that issue to `in_review`, never directly to `done`, only if its revision
+is unchanged and no newer task has been created for it. Any intervening issue
+edit or reassignment prevents the completion transition. Custom status columns,
+triage, and issues already in progress, review, or a terminal state are left
+unchanged. Failed and cancelled runs do not advance the issue to review.
+
+These transitions and their activity entries commit with the task transition;
+connected clients receive status and activity updates. Existing runs started
+before this support was deployed have no revision marker and are not advanced
+automatically.
+
+## Build and configure
+
+From `server/`:
+
+```sh
+go build -o qoder-runtime ./cmd/qoder-runtime
+```
+
+Provide these environment variables through your service manager or secret
+store. Do not commit tokens to source control.
+
+| Variable | Value |
+| --- | --- |
+| `MULTICA_SERVER_URL` | Multica server origin, without `/api` |
+| `MULTICA_TOKEN` | Multica workspace administrator PAT (standalone mode only) |
+| `MULTICA_WORKSPACE_ID` | Workspace UUID |
+| `QODER_CLOUD_BASE_URL` | Qoder managed API base, including its gateway prefix (for example `https://api.qoder.com/api/v1/cloud`) |
+| `QODER_CLOUD_TOKEN` | Qoder PAT with access to the configured agent/environment |
+| `QODER_CLOUD_ENVIRONMENT_ID` | Existing managed Qoder Environment ID |
+| `QODER_BRIDGE_STATE_DIR` | Dedicated persistent directory, writable by the service user |
+| `QODER_BRIDGE_NAME` | Optional display name; defaults to `Qoder Cloud Agent` |
+
+Alternatively, copy `config.example.json` to a private location, set its fields,
+and restrict it with `chmod 600`. File fields override the environment; missing
+fields inherit environment values. Unknown keys are rejected to catch typos.
+
+```sh
+./qoder-runtime --config /private/path/config.json --check
+./qoder-runtime --config /private/path/config.json
+```
+
+`--check` only reads the Multica workspace and Qoder environment. It does
+not register a runtime, claim a task or start execution.
+
+Start `./qoder-runtime`. Startup checks access to the Multica workspace and Qoder environment
+before registering. Copy the `runtime_id` from its registration log and bind
+an existing Multica agent:
+
+```sh
+multica agent update <agent-id> --runtime-id <runtime-id>
+```
+
+Configure the model, tools and skills on the Qoder Agent. GitHub resources require
+an explicit `authorization_token` when creating a Qoder session, including public
+repositories. Configure repository-scoped token files in the bridge JSON:
+
+```json
+"github_token_files": {
+ "https://github.com/OWNER/REPO": "/path/to/private/github-token"
+}
+```
+
+Each file must be a private regular file (0600) containing only the GitHub token.
+Keep it outside the repository and grant only the repository permissions needed
+for the task. The bridge reads it immediately before session creation and injects
+it into an ephemeral request copy. Neither the token nor its file path enters the
+run journal or prompt. Restart/resume reads the current file, allowing rotation.
+Missing credentials fail the task without creating a Qoder session. No workspace
+wide fallback credential is used. This is bridge-hosted configuration; Multica's
+web UI does not yet manage GitHub credentials for this runtime.
+
+A project may bind one HTTPS GitHub repository and an optional branch ref.
+Without one, the agent's default repository (`runtime_config.repository`) is
+mounted, and failing that the workspace's only repository when a credential is
+configured for it. Other workspace repositories are context only.
+
+The prompt asks the agent to push a branch named `multica/<identifier>-<slug>`
+and to prefix the pull request title with the issue identifier, so Multica's
+GitHub integration links the pull request back to the issue.
+
+
+## Execution and recovery
+
+- Up to `max_concurrency` runs (default 1 for this binary, 3 for managed
+ connections, at most 10) execute at once per bridge; further tasks stay
+ queued in Multica. Deploy one instance per configuration with its dedicated
+ persistent state volume; this is not an HA service.
+- A follow-up run on the same issue continues the agent's previous Qoder session
+ when that session is idle, uses the same Qoder agent and environment, and no
+ other run is using it. Otherwise a fresh session starts with the current issue
+ and triggering/coalesced comment context. Do not send additional messages
+ directly to a bridge-owned session while its run is active.
+- Progress uses cursor-paginated persisted events, polled every three seconds.
+ Event IDs and opaque page cursors are tracked separately. A turn is successful
+ only after its user message and `session.status_idle` with `end_turn`, without
+ an unrecovered error. Thread-level idle does not complete the run.
+- Cancelling/deleting a Multica run requests Qoder cancellation and waits for
+ the session to become idle or terminated. Losing runtime access also requests
+ cancellation. The session cancellation response alone is not proof of a stop.
+- Shutdown leaves remote execution running. Restart with the same directory
+ to resume reconciliation; do not delete the journal while work is active.
+- State is written atomically with private file permissions. It includes task
+ content, session ID, event cursor and pending outcome, but no API credentials.
+ An OS file lock prevents concurrent use of the same directory.
+- Submission intent is persisted before sending the user message. If the HTTP
+ result is ambiguous, the bridge searches event history for that exact message
+ and never automatically sends it twice. If no matching event appears, inspect
+ the remote session before deliberately retrying. Unconfirmed submissions expire
+ after two minutes; all runs have a one-hour deadline. Cancellation is attempted
+ before failure is reported. Failed cancellation remains in a durable cleanup
+ queue, independently of the next task. Do not manually resend pending work.
+- A lost **session creation** response can leave an unused idle session; retry
+ does not automatically create a second session. The run fails with an explicit
+ unconfirmed-creation error. An unused session whose ID was never received needs
+ manual provider-side inspection; no task message is sent to it.
+- Final callbacks retry through reconciliation. Transcript messages carry a
+ task-scoped `idempotency_key` derived from the Qoder event ID. The server derives
+ a stable message UUID and inserts once; accepted replays do not create another
+ row or broadcast another event. Deploy the server changes in this branch with
+ the bridge: older servers ignore that key and may duplicate transcript messages.
+
+## Current boundaries
+
+This is an issue-execution PoC. Chat, squad coordination, local directories,
+attachments, arbitrary Git hosts, tag/commit checkout, full comment-history
+hydration, interactive tool approval, custom client-side tools, terminal access,
+file transfer and billing/usage conversion are not implemented. Set up a Qoder
+Agent that can execute autonomously with its configured tools. `requires_action`
+ends the Multica run as failed with the stop reason; approvals are not granted
+implicitly.
+
+Multica custom skills and execution overrides are rejected; built-in Multica
+CLI skills are omitted because their local tools are unavailable. Qoder sessions
+keep any artifacts they produce; textual result and PR/MR links are returned in
+the final summary, without parsing them into structured Multica branch fields.
+
+The bridge uses the existing daemon registration protocol with
+`runtime_mode=cloud` and provider `qoder_cloud`. Existing daemons that omit the
+mode still register as local. No cloud-node lifecycle or update API is advertised.
+
+## Verification
+
+```sh
+go test -race ./internal/qoderruntime ./cmd/qoder-runtime
+go vet ./internal/qoderruntime ./cmd/qoder-runtime
+```
+
+Tests use local HTTP fixtures and never access real accounts or execute an
+installed coding-agent CLI. Live integration still requires a configured Multica
+workspace and Qoder environment; it is not covered by these tests.
+
+To exercise a running **local** Multica server with a simulated Qoder API:
+
+```sh
+MULTICA_QODER_INTEGRATION_CONFIG=/private/path/config.json \
+ go test -race -tags=integration ./internal/qoderruntime -run '^TestLocalMultica$' -count=1 -v
+```
+
+This test requires a loopback Multica URL and a test workspace. It creates an
+isolated runtime, agent and issue through the real authenticated API, simulates
+a lost transcript response, verifies one persisted output, then cleans up the
+issue/runtime and archives the fixture agent. Qoder credentials in the file are
+not used; Qoder is an in-process HTTP fixture.
+
+## Managed configuration in the web and desktop apps
+
+The runtime page presents a **Qoder Cloud** card with live status, associated
+agent count, **Configure credentials**, and **Add agent**. Credentials are grouped
+into QCA connection and GitHub repository sections; saved PATs remain hidden until
+the administrator chooses **Update credentials**. The quick-add dialog creates a
+Multica agent linked to an existing QCA Agent and uses the configured environment.
+
+
+Workspace administrators can open **Runtimes → Add remote runtime → Qoder Cloud Agent** to configure one
+managed QCA connection per workspace, load environments from the PAT and check environment access, bind GitHub
+repository tokens, save/start, or stop an idle runtime. The existing project
+resource picker selects the repository and starting branch. The managed form
+offers Qoder's official regions, `https://api.qoder.com/api/v1/cloud` (Global) and
+`https://api.qoder.com.cn/api/v1/cloud` (China); a PAT works only in the region
+that issued it. Custom endpoints remain available to the standalone bridge only.
+
+Server setup requires `MULTICA_VCS_SECRET_KEY` (a base64-encoded 32-byte encryption
+key). Keep the key stable across restarts. Credentials and the run journal are
+encrypted in `cloud_agent_connection`, so no local state directory is needed, and API
+responses return only presence flags and repository names. Empty password fields
+keep saved credentials; removing a repository removes its credential. Saving
+creates an encrypted workspace/daemon-scoped credential with a one-hour lifetime.
+The supervisor renews it only while the connection is enabled and its owner is an
+administrator. Save and Stop revoke the old credential and invalidate its cache.
+Membership/role checks also gate managed daemon requests. Removing or demoting
+that administrator retires the bridge and schedules remote cancellation.
+
+The API process supervises execution, restarts failed bridges, and resumes their
+journals. One PostgreSQL advisory lock elects the active supervisor. Managed
+journals are encrypted in PostgreSQL, including pending cancellations; API
+instances do not need shared local disks. Standalone journals remain local.
+Remote calls run outside database transactions under a bounded step lease;
+Save/Stop may return a retryable conflict while a step is synchronizing.
+Stop and configuration changes refuse active tasks; finish or cancel the tasks
+first. Stopping keeps QCA/repository credentials for a later Save and start, but revokes the internal daemon token. Do not run a
+standalone bridge for the same connection alongside the managed service. When
+migrating, stop the standalone bridge at idle before saving the managed config.
+
+This does not add chat support, session continuation, or delivery validation:
+QCA's end-of-turn remains execution completion, not proof that a PR was created.
+
+
+### Agent associations
+
+A runtime holds the QCA connection and environment, not a fixed QCA Agent.
+After entering a PAT in the Web/Desktop runtime dialog, available environments
+load automatically; one available environment is selected automatically.
+Names are displayed instead of requiring copied IDs. Archived resources are excluded.
+
+In the Multica agent creation form, select the QCA Agent under execution settings.
+For existing agents, use the runtime configuration tab. The association is stored
+in `agent.runtime_config.qoder_agent_id` and copied into each run journal before
+session creation. Several Multica agents can share a runtime with different QCA
+Agents. Configure QCA models, tools and skills in Qoder; the Multica page links
+existing QCA Agents rather than creating or editing those remote resources.
+
+The API exposes `POST /api/workspaces/{id}/qoder/environments` (admin-only,
+`{"qoder_token":"..."}`, blank reuses the saved PAT), and
+`GET /api/workspaces/{id}/qoder/agents` (workspace members, saved PAT).
+Only IDs and names are returned; provider configuration and credentials stay
+server-side. Listing follows pagination and excludes archived resources.
+
+When upgrading an earlier PoC configuration, stop idle bridges first, copy the
+old fixed Agent ID to every associated Multica agent's runtime configuration,
+and remove `agent_id` from standalone config files. Runtime identity and the
+journal directory now depend on connection/environment, not the fixed Agent ID;
+migrate an idle journal and daemon identity together to preserve existing runtime
+bindings. Never move a journal with an active run.
+
+### Updating an early development database
+
+The QCA migrations now use `573_qoder_connection` and
+`574_qoder_connection_workspace_index` after rebasing onto upstream main.
+If you ran an earlier draft with `564_qoder_connection` and
+`565_qoder_connection_workspace_index`, with `509_qoder_connection` and
+`510_qoder_connection_workspace_index`, with `479_qoder_connection` and
+`480_qoder_connection_workspace_index`, or with `451_qoder_connection` and
+`452_qoder_connection_workspace_index`, verify that the QCA table and its valid
+unique index already exist, then rename only those two exact entries in
+`schema_migrations` to the new names before running migrations. Preserve the
+existing table, encrypted credentials, and journal. Do not mark upstream's
+`451_agent_task_comment_thread` or `452_agent_task_pending_thread_unique` as
+applied; the normal migration runner must still execute them.
+
+Migration 575 revokes the early PoC's user-wide internal PATs and pauses existing
+connections. Before upgrading, let old executions finish or cancel them while the
+old bridge is still running. After migration, save the connection once to issue a
+scoped daemon credential; QCA and repository secrets are preserved. The managed
+daemon identity changes once during this upgrade; select the new managed runtime
+for agents previously bound to the old PoC runtime. Old local
+managed journals are not imported: archive/remove their private directories only
+after confirming no old remote work remains. Keep the encryption key stable.
+
+Workspace deletion first pauses its connection and cancels remote work. If a
+step or provider cancellation is still pending, deletion returns a conflict and
+must be retried; the encrypted recovery record is retained. Retired connections
+are retried by the supervisor, and task prompts are removed after cleanup.
+Catalog requests are limited to six per workspace per minute and ten pages per
+request. A failed bridge restarts with bounded exponential backoff.
+
+If lifecycle migration `566_qoder_lifecycle` was already applied, rename that
+exact ledger entry to `575_qoder_lifecycle` as well; do not re-run its credential
+revocation and connection pause. Do not rename upstream migrations sharing the
+old numeric prefixes.
diff --git a/server/cmd/qoder-runtime/config.example.json b/server/cmd/qoder-runtime/config.example.json
new file mode 100644
index 0000000000..375b366a13
--- /dev/null
+++ b/server/cmd/qoder-runtime/config.example.json
@@ -0,0 +1,13 @@
+{
+ "multica_url": "http://localhost:8080",
+ "multica_token": "",
+ "workspace_id": "",
+ "qoder_url": "",
+ "qoder_token": "",
+ "environment_id": "",
+ "state_dir": "/var/lib/multica-qoder",
+ "name": "Qoder Cloud Agent",
+ "github_token_files": {
+ "https://github.com/OWNER/REPO": "/path/to/private/github-token"
+ }
+}
diff --git a/server/cmd/qoder-runtime/main.go b/server/cmd/qoder-runtime/main.go
new file mode 100644
index 0000000000..28499fc5a6
--- /dev/null
+++ b/server/cmd/qoder-runtime/main.go
@@ -0,0 +1,82 @@
+// qoder-runtime runs a server-hosted Multica to Qoder Cloud Agent bridge.
+package main
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "flag"
+ "fmt"
+ "io"
+ "log/slog"
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/multica-ai/multica/server/internal/qoderruntime"
+)
+
+func main() {
+ log := slog.New(slog.NewJSONHandler(os.Stderr, nil))
+ configPath := flag.String("config", "", "JSON configuration file; supplied fields override environment variables")
+ checkOnly := flag.Bool("check", false, "Verify API access without registering a runtime or running tasks")
+ flag.Parse()
+ cfg, err := loadConfig(*configPath, os.Getenv)
+ if err != nil {
+ log.Error("read bridge configuration", "error", err)
+ os.Exit(1)
+ }
+ b, err := qoderruntime.New(cfg, log)
+ if err != nil {
+ log.Error("invalid bridge configuration", "error", err)
+ os.Exit(1)
+ }
+ ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer cancel()
+ if *checkOnly {
+ if err := b.Check(ctx); err != nil {
+ log.ErrorContext(ctx, "bridge check failed", "error", err)
+ os.Exit(1)
+ }
+ log.InfoContext(ctx, "bridge API access verified")
+ return
+ }
+ if err := b.Run(ctx); err != nil {
+ log.ErrorContext(ctx, "Qoder bridge stopped", "error", err)
+ os.Exit(1)
+ }
+}
+
+func loadConfig(path string, getenv func(string) string) (qoderruntime.Config, error) {
+ cfg := qoderruntime.Config{
+ MulticaURL: getenv("MULTICA_SERVER_URL"), MulticaToken: getenv("MULTICA_TOKEN"), WorkspaceID: getenv("MULTICA_WORKSPACE_ID"),
+ QoderURL: getenv("QODER_CLOUD_BASE_URL"), QoderToken: getenv("QODER_CLOUD_TOKEN"), EnvironmentID: getenv("QODER_CLOUD_ENVIRONMENT_ID"),
+ StateDir: getenv("QODER_BRIDGE_STATE_DIR"), Name: getenv("QODER_BRIDGE_NAME"),
+ }
+ if path == "" {
+ return cfg, nil
+ }
+ f, err := os.Open(path)
+ if err != nil {
+ return cfg, fmt.Errorf("cannot open configuration file")
+ }
+ defer f.Close()
+ raw, err := io.ReadAll(io.LimitReader(f, (1<<20)+1))
+ if err != nil || len(raw) > 1<<20 {
+ return cfg, fmt.Errorf("cannot read configuration or file exceeds 1 MiB")
+ }
+ raw = bytes.TrimSpace(raw)
+ if len(raw) == 0 || raw[0] != '{' {
+ return cfg, fmt.Errorf("configuration must be a JSON object")
+ }
+ decoder := json.NewDecoder(bytes.NewReader(raw))
+ decoder.DisallowUnknownFields()
+ if err := decoder.Decode(&cfg); err != nil {
+ return cfg, fmt.Errorf("invalid configuration JSON or unknown field")
+ }
+ var extra any
+ if err := decoder.Decode(&extra); err != io.EOF {
+ return cfg, fmt.Errorf("configuration must contain one JSON object")
+ }
+ return cfg, nil
+}
diff --git a/server/cmd/qoder-runtime/main_test.go b/server/cmd/qoder-runtime/main_test.go
new file mode 100644
index 0000000000..b5d7d0cc49
--- /dev/null
+++ b/server/cmd/qoder-runtime/main_test.go
@@ -0,0 +1,40 @@
+package main
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestLoadConfigPrecedenceAndValidation(t *testing.T) {
+ env := func(key string) string {
+ if key == "MULTICA_TOKEN" {
+ return "private-env-token"
+ }
+ if key == "QODER_CLOUD_ENVIRONMENT_ID" {
+ return "env_environment"
+ }
+ return ""
+ }
+ path := filepath.Join(t.TempDir(), "config.json")
+ if err := os.WriteFile(path, []byte(`{"environment_id":"env_file","workspace_id":"workspace"}`), 0600); err != nil {
+ t.Fatal(err)
+ }
+ cfg, err := loadConfig(path, env)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if cfg.EnvironmentID != "env_file" || cfg.MulticaToken != "private-env-token" {
+ t.Fatal("configuration precedence changed")
+ }
+ for _, body := range []string{`{"misspelled_secret":"sensitive"}`, `{"qoder_token":`, `{} {}`, `null`, `[]`} {
+ if err := os.WriteFile(path, []byte(body), 0600); err != nil {
+ t.Fatal(err)
+ }
+ _, err := loadConfig(path, env)
+ if err == nil || strings.Contains(err.Error(), "sensitive") {
+ t.Fatalf("unsafe or missing validation: %v", err)
+ }
+ }
+}
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index a2432fe75d..677246b150 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -748,6 +748,7 @@ func main() {
// Queued work now expires on the same runtime-liveness signal as in-flight
// work, so there is no separate queue TTL to tune: a busy runtime keeps its
// backlog, and a departed one retires everything it owned at once.
+ go h.RunQoderConnections(sweepCtx, pool, "http://localhost:"+port)
go runRuntimeSweeper(sweepCtx, queries, liveness, taskSvc, bus, runtimeReconnectGrace)
if telemetryWorker != nil {
go telemetryWorker.Run(sweepCtx)
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 4296b94b52..d28ec1e56c 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -516,6 +516,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
h.LocalSkillListStore = handler.NewRedisLocalSkillListStore(rdb)
h.LocalSkillImportStore = handler.NewRedisLocalSkillImportStore(rdb)
h.LivenessStore = handler.NewRedisLivenessStore(rdb)
+ h.QoderRateLimiter = handler.NewRedisWebhookRateLimiter(rdb, handler.WebhookRateLimit{Limit: 6, Window: time.Minute})
h.WebhookRateLimiter = handler.NewRedisWebhookRateLimiter(rdb, handler.DefaultWebhookRateLimit())
h.WebhookIPRateLimiter = handler.NewRedisWebhookIPRateLimiter(rdb, handler.DefaultWebhookIPRateLimit())
h.WebhookAbsoluteIPRateLimiter = handler.NewRedisWebhookAbsoluteIPRateLimiter(rdb, handler.DefaultWebhookAbsoluteIPRateLimit())
@@ -1713,6 +1714,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// for the same reason as GitHub installations; connect /
// disconnect are admin-gated in the group below.
r.Get("/vcs/connections", h.ListVCSConnections)
+ r.Get("/qoder", h.GetQoderConnection)
+ r.Get("/qoder/agents", h.ListQoderAgents)
// Custom runtime profiles — listing/reading is member-visible
// (the Runtime page renders for everyone; create/edit/delete
// are admin-gated below).
@@ -1798,6 +1801,12 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Delete("/github/installations/{installationId}", h.DeleteGitHubInstallation)
// VCS connect / disconnect / webhook regeneration (admin-only).
r.Post("/vcs/connections", h.ConnectVCS)
+ r.Put("/qoder", h.SaveQoderConnection)
+ r.Post("/qoder/check", h.CheckQoderConnection)
+ r.Post("/qoder/environments", h.ListQoderEnvironments)
+ r.Post("/qoder/stop", h.StopQoderConnection)
+ r.Post("/qoder/resume", h.ResumeQoderConnection)
+ r.Delete("/qoder", h.DisconnectQoderConnection)
r.Post("/vcs/connections/{connectionId}/rotate-webhook", h.RotateVCSConnectionWebhook)
r.Delete("/vcs/connections/{connectionId}", h.DeleteVCSConnection)
})
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index d021502a7c..269a6459b5 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -1471,6 +1471,18 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {
return
}
+ if runtime.Provider == "qoder_cloud" {
+ raw, _ := json.Marshal(req.RuntimeConfig)
+ if err := validateQoderAgentConfig(raw); err != nil {
+ writeError(w, 400, err.Error())
+ return
+ }
+ overrides := qoderOverrides{skills: len(req.SkillIDs), customEnv: len(req.CustomEnv), customArgs: len(req.CustomArgs), mcpConfig: req.McpConfig, model: req.Model, thinkingLevel: req.ThinkingLevel, serviceTier: req.ServiceTier}
+ if err := overrides.validate(); err != nil {
+ writeError(w, 400, err.Error())
+ return
+ }
+ }
// thinking_level validation: fixed-enum providers reject unknown literals;
// dynamic-catalog providers (Codex/OpenCode) reject malformed tokens here.
// Pi has a fixed token universe and a daemon-discovered per-model subset.
@@ -2036,6 +2048,61 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {
targetRuntimeID = runtime.ID
targetProvider = runtime.Provider
}
+ // Validate the settings the agent will have after this update, not only the
+ // fields in the request: a Qoder agent must never be left with settings the
+ // bridge refuses at run time.
+ runtimeChange := req.RuntimeConfig != nil || req.RuntimeID != nil
+ if runtimeChange || req.CustomArgs != nil || req.McpConfig != nil || req.Model != nil || req.ThinkingLevel != nil || req.ServiceTier != nil {
+ provider := targetProvider
+ if provider == "" {
+ var ok bool
+ provider, ok = h.resolveAgentProvider(r, existing.WorkspaceID, targetRuntimeID)
+ if !ok {
+ writeError(w, 400, "cannot resolve agent runtime")
+ return
+ }
+ }
+ if provider == "qoder_cloud" {
+ if runtimeChange {
+ raw := existing.RuntimeConfig
+ if req.RuntimeConfig != nil {
+ raw, _ = json.Marshal(req.RuntimeConfig)
+ }
+ if err := validateQoderAgentConfig(raw); err != nil {
+ writeError(w, 400, err.Error())
+ return
+ }
+ }
+ overrides := storedQoderOverrides(existing)
+ if req.RuntimeID != nil {
+ skills, err := h.Queries.ListAgentSkills(r.Context(), existing.ID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load agent skills")
+ return
+ }
+ overrides.skills = len(skills)
+ }
+ if req.CustomArgs != nil {
+ overrides.customArgs = len(*req.CustomArgs)
+ }
+ if req.McpConfig != nil {
+ overrides.mcpConfig = *req.McpConfig
+ }
+ if req.Model != nil {
+ overrides.model = *req.Model
+ }
+ if req.ThinkingLevel != nil {
+ overrides.thinkingLevel = *req.ThinkingLevel
+ }
+ if req.ServiceTier != nil {
+ overrides.serviceTier = *req.ServiceTier
+ }
+ if err := overrides.validate(); err != nil {
+ writeError(w, 400, err.Error())
+ return
+ }
+ }
+ }
// Invocation permission (MUL-3963). OWNER-ONLY write: access is the one
// agent property a workspace admin may NOT change (only the owner decides
// who can run their agent — the overlay uses the owner's own Composio
diff --git a/server/internal/handler/agent_env.go b/server/internal/handler/agent_env.go
index 440ce73172..6661ace927 100644
--- a/server/internal/handler/agent_env.go
+++ b/server/internal/handler/agent_env.go
@@ -204,6 +204,9 @@ func (h *Handler) UpdateAgentEnv(w http.ResponseWriter, r *http.Request) {
existing := unmarshalCustomEnv(agent)
merged, audit := mergeAgentEnv(existing, req.CustomEnv)
+ if len(merged) > 0 && h.rejectQoderOverrides(w, r, agent, qoderOverrides{customEnv: len(merged)}) {
+ return
+ }
envBytes, err := json.Marshal(merged)
if err != nil {
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 66f013335b..2234e216f7 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -64,6 +64,17 @@ func (h *Handler) requireDaemonWorkspaceAccess(w http.ResponseWriter, r *http.Re
writeError(w, http.StatusNotFound, "not found")
return false
}
+ if strings.HasPrefix(middleware.DaemonIDFromContext(r.Context()), "qoder-managed-") {
+ allowed, err := h.qoderCredentialAllowed(r, workspaceID, middleware.DaemonIDFromContext(r.Context()))
+ if err != nil {
+ writeError(w, http.StatusServiceUnavailable, "runtime authorization unavailable")
+ return false
+ }
+ if !allowed {
+ writeError(w, http.StatusForbidden, "runtime access revoked")
+ return false
+ }
+ }
return true
}
@@ -202,10 +213,11 @@ type DaemonRegisterRequest struct {
CLIVersion string `json:"cli_version"` // multica CLI version
LaunchedBy string `json:"launched_by"` // "desktop" when spawned by the Electron app
Runtimes []struct {
- Name string `json:"name"`
- Type string `json:"type"`
- Version string `json:"version"` // agent CLI version (claude/codex)
- Status string `json:"status"`
+ Name string `json:"name"`
+ RuntimeMode string `json:"runtime_mode,omitempty"`
+ Type string `json:"type"`
+ Version string `json:"version"` // agent CLI version (claude/codex)
+ Status string `json:"status"`
// ProfileID, when non-empty, marks this as an instance of a custom
// runtime_profile (MUL-3284). Empty = built-in runtime (legacy path).
// Type carries the protocol family for both built-in and custom rows
@@ -426,11 +438,48 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "at least one runtime or failed profile is required")
return
}
+ // Validate all entries before writing any registration. Custom profiles
+ // launch a local command and cannot declare managed cloud execution.
+ for i := range req.Runtimes {
+ rt := &req.Runtimes[i]
+ if rt.RuntimeMode == "" {
+ rt.RuntimeMode = "local"
+ }
+ if (rt.RuntimeMode != "local" && rt.RuntimeMode != "cloud") || (rt.ProfileID != "" && rt.RuntimeMode != "local") {
+ writeError(w, http.StatusBadRequest, "invalid runtime_mode for registration")
+ return
+ }
+ }
wsUUID, ok := parseUUIDOrBadRequest(w, req.WorkspaceID, "workspace_id")
if !ok {
return
}
req.WorkspaceID = uuidToString(wsUUID)
+ if id := middleware.DaemonIDFromContext(r.Context()); id != "" && id != req.DaemonID {
+ writeError(w, http.StatusForbidden, "daemon identity mismatch")
+ return
+ }
+ for _, rt := range req.Runtimes {
+ if normalizeProvider(rt.Type) != "qoder_cloud" {
+ continue
+ }
+ if middleware.DaemonIDFromContext(r.Context()) != "" {
+ allowed, err := h.qoderCredentialAllowed(r, req.WorkspaceID, req.DaemonID)
+ if err != nil || !allowed {
+ writeError(w, http.StatusForbidden, "managed runtime credential required")
+ return
+ }
+ } else {
+ member, ok := h.requireWorkspaceMember(w, r, req.WorkspaceID, "workspace not found")
+ if !ok {
+ return
+ }
+ if !roleAllowed(member.Role, "owner", "admin") {
+ writeError(w, http.StatusForbidden, "workspace administrator required")
+ return
+ }
+ }
+ }
// Verify workspace access and resolve owner.
// Daemon tokens (mdt_) prove workspace access directly; OwnerID will be zero
@@ -570,7 +619,7 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
WorkspaceID: wsUUID,
DaemonID: strToText(req.DaemonID),
Name: name,
- RuntimeMode: "local",
+ RuntimeMode: runtime.RuntimeMode,
Provider: provider,
Status: status,
DeviceInfo: deviceInfo,
@@ -5135,6 +5184,8 @@ type TaskMessageRequest struct {
// never as false. Recording an unmeasured output as complete is the one
// claim this data is not entitled to make.
OutputTruncated *bool `json:"output_truncated,omitempty"`
+ // IdempotencyKey scopes provider event replays to this task.
+ IdempotencyKey string `json:"idempotency_key,omitempty"`
}
type TaskMessageBatchRequest struct {
@@ -5183,7 +5234,7 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {
// string means SQL NULL, applied by the query's NULLIF.
n := len(req.Messages)
params := db.CreateTaskMessagesParams{
- TaskID: parseUUID(taskID),
+ TaskID: task.ID,
Ids: make([]pgtype.UUID, 0, n),
Seqs: make([]int32, 0, n),
Types: make([]string, 0, n),
@@ -5202,12 +5253,22 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {
}
createdAts := taskMessageCreatedAts(req.Messages, time.Now().UTC())
for i, msg := range req.Messages {
- id, err := uuid.NewV7()
- if err != nil {
- slog.Error("failed to generate task message id", "task_id", taskID, "error", err)
- writeError(w, http.StatusInternalServerError, "failed to persist task message")
+ if len(msg.IdempotencyKey) > 512 {
+ writeError(w, http.StatusBadRequest, "message idempotency_key exceeds 512 bytes")
return
}
+ var id uuid.UUID
+ if msg.IdempotencyKey != "" {
+ id = uuid.NewSHA1(uuid.UUID(task.ID.Bytes), []byte(msg.IdempotencyKey))
+ } else {
+ var err error
+ id, err = uuid.NewV7()
+ if err != nil {
+ slog.Error("failed to generate task message id", "task_id", taskID, "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to persist task message")
+ return
+ }
+ }
// Redact sensitive information before persisting or broadcasting.
msg.Content = redact.Text(msg.Content)
diff --git a/server/internal/handler/daemon_remote_runtime_test.go b/server/internal/handler/daemon_remote_runtime_test.go
new file mode 100644
index 0000000000..2c6b7a249c
--- /dev/null
+++ b/server/internal/handler/daemon_remote_runtime_test.go
@@ -0,0 +1,48 @@
+package handler
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func TestDaemonRegisterExecutionMode(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ for _, tc := range []struct {
+ name, mode, want string
+ status int
+ }{
+ {"legacy", "", "local", http.StatusOK},
+ {"remote", "cloud", "local", http.StatusForbidden},
+ {"invalid", "unknown", "local", http.StatusBadRequest},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ daemonID := uuid.NewString()
+ id := dbfx.Runtime(t, "mode fixture", testutil.Cols{"daemon_id": daemonID, "provider": func() string {
+ if tc.name == "legacy" {
+ return "claude"
+ }
+ return "qoder_cloud"
+ }(), "runtime_mode": "local"})
+ req := newDaemonTokenRequest("POST", "/api/daemon/register", map[string]any{
+ "workspace_id": testWorkspaceID, "daemon_id": daemonID,
+ "runtimes": []map[string]any{{"name": "Qoder Cloud Agent", "type": func() string {
+ if tc.name == "legacy" {
+ return "claude"
+ }
+ return "qoder_cloud"
+ }(), "runtime_mode": tc.mode, "status": "online"}},
+ }, testWorkspaceID, daemonID)
+ testutil.Call(t, testHandler.DaemonRegister, req).Want(tc.status)
+ var mode string
+ dbfx.QueryRow(t, `SELECT runtime_mode FROM agent_runtime WHERE id=$1`, id).Scan(&mode)
+ if mode != tc.want {
+ t.Fatalf("runtime_mode=%q, want %q", mode, tc.want)
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index db9e9b6e79..1987866ad9 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -264,6 +264,7 @@ type Handler struct {
PATCache *auth.PATCache
DaemonTokenCache *auth.DaemonTokenCache
MembershipCache *auth.MembershipCache
+ QoderRateLimiter WebhookRateLimiter
WebhookRateLimiter WebhookRateLimiter
WebhookIPRateLimiter WebhookRateLimiter
WebhookAbsoluteIPRateLimiter WebhookRateLimiter
@@ -513,6 +514,7 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *event
Storage: store,
CFSigner: cfSigner,
Analytics: analyticsClient,
+ QoderRateLimiter: NewMemoryWebhookRateLimiter(WebhookRateLimit{Limit: 6, Window: time.Minute}),
WebhookRateLimiter: NewMemoryWebhookRateLimiter(DefaultWebhookRateLimit()),
WebhookIPRateLimiter: NewMemoryWebhookIPRateLimiter(DefaultWebhookIPRateLimit()),
WebhookAbsoluteIPRateLimiter: NewMemoryWebhookAbsoluteIPRateLimiter(DefaultWebhookAbsoluteIPRateLimit()),
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index c5fd276acd..41670e523d 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -28,6 +28,7 @@ import (
"github.com/multica-ai/multica/server/internal/logger"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
+ "github.com/multica-ai/multica/server/internal/qoderruntime"
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
agentpkg "github.com/multica-ai/multica/server/pkg/agent"
@@ -2986,6 +2987,12 @@ func (h *Handler) checkQuickCreateDaemonVersionAtLeast(ctx context.Context, sour
"reason": "agent's runtime is no longer registered",
}
}
+ if rt.Provider == qoderruntime.Provider {
+ return http.StatusUnprocessableEntity, map[string]any{
+ "code": "agent_unavailable",
+ "reason": "Qoder Cloud Agent supports existing issue runs only; create the issue manually and assign it to this agent",
+ }
+ }
current := readRuntimeCLIVersion(rt.Metadata)
switch err := agentpkg.CheckMinCLIVersionFor(current, minimum); {
case err == nil:
diff --git a/server/internal/handler/qoder_agent_settings_test.go b/server/internal/handler/qoder_agent_settings_test.go
new file mode 100644
index 0000000000..e5e732cdf1
--- /dev/null
+++ b/server/internal/handler/qoder_agent_settings_test.go
@@ -0,0 +1,47 @@
+package handler
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func TestQoderAgentWritesValidateEffectiveSettings(t *testing.T) {
+ if testPool == nil {
+ t.Skip("database not available")
+ }
+ qoderRuntime := dbfx.Runtime(t, "qoder settings runtime", testutil.Cols{"provider": "qoder_cloud"})
+ localRuntime := dbfx.Runtime(t, "local settings runtime")
+ qoderAgent := dbfx.Agent(t, "qoder settings agent", qoderRuntime)
+ modelAgent := dbfx.Agent(t, "local model agent", localRuntime, testutil.Cols{"model": "gpt-5"})
+ var skillID string
+ dbfx.QueryRow(t, `
+ INSERT INTO skill (workspace_id, name, description, content, config, created_by)
+ VALUES ($1, 'Qoder settings skill', '', '# Skill', '{}'::jsonb, $2)
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&skillID)
+ dbfx.Cleanup(t, `DELETE FROM skill WHERE id = $1`, skillID)
+
+ put := func(handler http.HandlerFunc, agentID, path string, body map[string]any) *testutil.Response {
+ return testutil.Call(t, handler, withURLParam(newRequest(http.MethodPut, "/api/agents/"+agentID+path, body), "id", agentID))
+ }
+
+ for name, body := range map[string]map[string]any{
+ "model": {"model": "gpt-5"},
+ "custom args": {"custom_args": []string{"--verbose"}},
+ "mcp config": {"mcp_config": map[string]any{"mcpServers": map[string]any{"x": map[string]any{"command": "x"}}}},
+ } {
+ t.Run(name, func(t *testing.T) {
+ put(testHandler.UpdateAgent, qoderAgent, "", body).Want(http.StatusBadRequest)
+ })
+ }
+ put(testHandler.UpdateAgent, qoderAgent, "", map[string]any{"description": "still fine"}).Want(http.StatusOK)
+ put(testHandler.UpdateAgent, qoderAgent, "", map[string]any{"model": ""}).Want(http.StatusOK)
+
+ put(testHandler.UpdateAgent, modelAgent, "", map[string]any{"runtime_id": qoderRuntime, "runtime_config": map[string]any{"qoder_agent_id": "agent_1"}}).Want(http.StatusBadRequest)
+
+ put(testHandler.UpdateAgentEnv, qoderAgent, "/env", map[string]any{"custom_env": map[string]string{"API_KEY": "x"}}).Want(http.StatusBadRequest)
+ put(testHandler.SetAgentSkills, qoderAgent, "/skills", map[string]any{"skill_ids": []string{skillID}}).Want(http.StatusBadRequest)
+ put(testHandler.SetAgentSkills, qoderAgent, "/skills", map[string]any{"skill_ids": []string{}}).Want(http.StatusOK)
+}
diff --git a/server/internal/handler/qoder_catalog.go b/server/internal/handler/qoder_catalog.go
new file mode 100644
index 0000000000..f18c68b9d9
--- /dev/null
+++ b/server/internal/handler/qoder_catalog.go
@@ -0,0 +1,253 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
+ "github.com/multica-ai/multica/server/internal/qoderruntime"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+const qoderAPIURL = "https://api.qoder.com/api/v1/cloud"
+
+// Managed connections may only reach Qoder's public regional APIs, preventing SSRF.
+var qoderAPIURLs = map[string]bool{
+ qoderAPIURL: true,
+ "https://api.qoder.com.cn/api/v1/cloud": true,
+}
+
+func qoderBaseURL(raw string) (string, bool) {
+ base := strings.TrimRight(strings.TrimSpace(raw), "/")
+ if base == "" {
+ return qoderAPIURL, true
+ }
+ return base, qoderAPIURLs[base]
+}
+
+type qoderCatalogItem struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+}
+
+// Only names and identifiers leave the server. Provider configurations may contain secrets.
+func fetchQoderCatalog(ctx context.Context, baseURL, token, kind string) ([]qoderCatalogItem, error) {
+ client := &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
+ items := []qoderCatalogItem{}
+ cursor := ""
+ seen := map[string]bool{}
+ ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
+ defer cancel()
+ for page := 0; page < 10; page++ {
+ query := url.Values{"limit": {"100"}}
+ if cursor != "" {
+ query.Set("after_id", cursor)
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/"+kind+"?"+query.Encode(), nil)
+ if err != nil {
+ return nil, fmt.Errorf("invalid QCA catalog request")
+ }
+ req.Header.Set("Authorization", "Bearer "+token)
+ res, err := client.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("QCA connection failed")
+ }
+ if res.StatusCode != http.StatusOK {
+ res.Body.Close()
+ return nil, fmt.Errorf("QCA catalog returned HTTP %d", res.StatusCode)
+ }
+ var result struct {
+ Data []struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ ArchivedAt *string `json:"archived_at"`
+ } `json:"data"`
+ HasMore bool `json:"has_more"`
+ LastID string `json:"last_id"`
+ }
+ raw, err := io.ReadAll(io.LimitReader(res.Body, (2<<20)+1))
+ res.Body.Close()
+ if err != nil || len(raw) > 2<<20 || json.Unmarshal(raw, &result) != nil || result.Data == nil {
+ return nil, fmt.Errorf("invalid QCA catalog response")
+ }
+ for _, item := range result.Data {
+ prefix := "env_"
+ if kind == "agents" {
+ prefix = "agent_"
+ }
+ if !strings.HasPrefix(item.ID, prefix) {
+ return nil, fmt.Errorf("invalid QCA catalog identity")
+ }
+ if item.ArchivedAt != nil || seen[item.ID] {
+ continue
+ }
+ seen[item.ID] = true
+ name := strings.TrimSpace(item.Name)
+ if name == "" {
+ name = item.ID
+ }
+ items = append(items, qoderCatalogItem{ID: item.ID, Name: name})
+ }
+ if !result.HasMore {
+ return items, nil
+ }
+ if result.LastID == "" || result.LastID == cursor || len(result.Data) == 0 {
+ return nil, fmt.Errorf("invalid QCA pagination")
+ }
+ cursor = result.LastID
+ }
+ return nil, fmt.Errorf("QCA catalog exceeds pagination limit")
+}
+
+func (h *Handler) ListQoderAgents(w http.ResponseWriter, r *http.Request) {
+ ws, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace_id")
+ if !ok {
+ return
+ }
+ if h.QoderRateLimiter != nil && !h.QoderRateLimiter.Allow(r.Context(), "qoder-catalog:"+uuidToString(ws)) {
+ w.Header().Set("Retry-After", "60")
+ writeError(w, http.StatusTooManyRequests, "QCA catalog request limit reached")
+ return
+ }
+
+ cfg, _, _, _, err := h.readQoderSettings(r.Context(), uuidToString(ws))
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, 409, "configure a QCA connection first")
+ return
+ }
+ if err != nil {
+ writeError(w, 500, "cannot read QCA configuration")
+ return
+ }
+ base, ok := qoderBaseURL(cfg.BaseURL)
+ if !ok {
+ writeError(w, 409, "unsupported QCA API URL")
+ return
+ }
+ items, err := fetchQoderCatalog(r.Context(), base, cfg.QoderToken, "agents")
+ if err != nil {
+ writeError(w, 502, err.Error())
+ return
+ }
+ writeJSON(w, 200, map[string]any{"items": items})
+}
+
+func (h *Handler) ListQoderEnvironments(w http.ResponseWriter, r *http.Request) {
+ ws, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace_id")
+ if !ok {
+ return
+ }
+ if h.QoderRateLimiter != nil && !h.QoderRateLimiter.Allow(r.Context(), "qoder-catalog:"+uuidToString(ws)) {
+ w.Header().Set("Retry-After", "60")
+ writeError(w, http.StatusTooManyRequests, "QCA catalog request limit reached")
+ return
+ }
+
+ var input struct {
+ Token string `json:"qoder_token"`
+ BaseURL string `json:"base_url"`
+ }
+ dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10))
+ dec.DisallowUnknownFields()
+ if dec.Decode(&input) != nil {
+ writeError(w, 400, "invalid QCA token request")
+ return
+ }
+ var extra any
+ if dec.Decode(&extra) != io.EOF {
+ writeError(w, 400, "request must contain one JSON object")
+ return
+ }
+ cfg, _, _, _, err := h.readQoderSettings(r.Context(), uuidToString(ws))
+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, 500, "cannot read QCA configuration")
+ return
+ }
+ requested := input.BaseURL
+ if strings.TrimSpace(requested) == "" {
+ requested = cfg.BaseURL
+ }
+ base, ok := qoderBaseURL(requested)
+ if !ok {
+ writeError(w, 400, "unsupported QCA API URL")
+ return
+ }
+ token := strings.TrimSpace(input.Token)
+ if token == "" {
+ token = cfg.QoderToken
+ }
+ if token == "" || strings.ContainsAny(token, "\r\n\t ") {
+ writeError(w, 400, "QCA token is required")
+ return
+ }
+ items, err := fetchQoderCatalog(r.Context(), base, token, "environments")
+ if err != nil {
+ writeError(w, 502, err.Error())
+ return
+ }
+ writeJSON(w, 200, map[string]any{"items": items})
+}
+
+// qoderOverrides lists per-agent execution settings the Qoder bridge refuses
+// at run time (see qoderruntime.prepare); saving them would create an agent
+// that fails every task.
+type qoderOverrides struct {
+ skills, customEnv, customArgs int
+ mcpConfig json.RawMessage
+ model, thinkingLevel, serviceTier string
+}
+
+func (o qoderOverrides) validate() error {
+ mcp := strings.TrimSpace(string(o.mcpConfig))
+ if o.skills > 0 || o.customEnv > 0 || o.customArgs > 0 || (mcp != "" && mcp != "null" && mcp != "{}") || o.model != "" || o.thinkingLevel != "" || o.serviceTier != "" {
+ return fmt.Errorf("Qoder agents take skills, tools, credentials and model from the Qoder Agent; remove them from this agent")
+ }
+ return nil
+}
+
+// storedQoderOverrides reads an agent's saved execution settings. Skills live
+// in their own table and are counted by the caller when they matter.
+func storedQoderOverrides(agent db.Agent) qoderOverrides {
+ var args []string
+ _ = json.Unmarshal(agent.CustomArgs, &args)
+ return qoderOverrides{
+ customEnv: len(unmarshalCustomEnv(agent)),
+ customArgs: len(args),
+ mcpConfig: agent.McpConfig,
+ model: agent.Model.String,
+ thinkingLevel: agent.ThinkingLevel.String,
+ serviceTier: agent.ServiceTier.String,
+ }
+}
+
+// rejectQoderOverrides writes a 400 and reports true when the agent runs on
+// Qoder and o would leave it with settings the bridge refuses at run time.
+func (h *Handler) rejectQoderOverrides(w http.ResponseWriter, r *http.Request, agent db.Agent, o qoderOverrides) bool {
+ provider, ok := h.resolveAgentProvider(r, agent.WorkspaceID, agent.RuntimeID)
+ if !ok || provider != "qoder_cloud" {
+ return false
+ }
+ if err := o.validate(); err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return true
+ }
+ return false
+}
+
+func validateQoderAgentConfig(raw []byte) error {
+ if _, err := qoderruntime.ParseAgentConfig(raw); err != nil {
+ if strings.HasPrefix(err.Error(), "default repository") {
+ return err
+ }
+ return fmt.Errorf("select a QCA Agent in the agent runtime configuration")
+ }
+ return nil
+}
diff --git a/server/internal/handler/qoder_catalog_test.go b/server/internal/handler/qoder_catalog_test.go
new file mode 100644
index 0000000000..f9c3376969
--- /dev/null
+++ b/server/internal/handler/qoder_catalog_test.go
@@ -0,0 +1,75 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestQoderCatalogPaginationAndRedaction(t *testing.T) {
+ requests := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests++
+ if r.Header.Get("Authorization") != "Bearer private-token" {
+ t.Error("missing credential")
+ }
+ w.Header().Set("Content-Type", "application/json")
+ if requests == 1 {
+ _, _ = w.Write([]byte(`{"data":[{"id":"env_first","name":"Web","config":{"secret":"do-not-expose"}},{"id":"env_archived","name":"Archived","archived_at":"2026-01-01"}],"has_more":true,"last_id":"env_archived"}`))
+ } else {
+ if r.URL.Query().Get("after_id") != "env_archived" {
+ t.Error("missing pagination cursor")
+ }
+ _, _ = w.Write([]byte(`{"data":[{"id":"env_second","name":"Build"}],"has_more":false}`))
+ }
+ }))
+ defer server.Close()
+ items, err := fetchQoderCatalog(context.Background(), server.URL, "private-token", "environments")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if requests != 2 || len(items) != 2 || items[1].ID != "env_second" {
+ t.Fatalf("unexpected catalog: %+v", items)
+ }
+ raw, _ := json.Marshal(items)
+ if strings.Contains(string(raw), "secret") || strings.Contains(string(raw), "config") {
+ t.Fatal("provider configuration leaked")
+ }
+}
+func TestQoderCatalogRejectsMalformedAndRedactsErrors(t *testing.T) {
+ for _, body := range []string{`{}`, `{"data":null}`, `{"data":[{"id":"wrong"}]}`, `{"data":[],"has_more":true}`} {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(body)) }))
+ if _, err := fetchQoderCatalog(context.Background(), server.URL, "private-token", "environments"); err == nil {
+ t.Errorf("accepted %s", body)
+ }
+ server.Close()
+ }
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "private-token", 401) }))
+ defer server.Close()
+ _, err := fetchQoderCatalog(context.Background(), server.URL, "private-token", "agents")
+ if err == nil || strings.Contains(err.Error(), "private-token") {
+ t.Fatal("provider error was not redacted")
+ }
+}
+
+func TestQoderOverridesRejectedAtSave(t *testing.T) {
+ if err := (qoderOverrides{mcpConfig: json.RawMessage(`{}`)}).validate(); err != nil {
+ t.Fatalf("empty overrides rejected: %v", err)
+ }
+ for name, o := range map[string]qoderOverrides{
+ "skills": {skills: 1},
+ "custom env": {customEnv: 1},
+ "custom args": {customArgs: 1},
+ "mcp config": {mcpConfig: json.RawMessage(`{"mcpServers":{}}`)},
+ "model": {model: "gpt"},
+ "thinking level": {thinkingLevel: "high"},
+ "service tier": {serviceTier: "priority"},
+ } {
+ if err := o.validate(); err == nil {
+ t.Errorf("%s accepted for a Qoder agent", name)
+ }
+ }
+}
diff --git a/server/internal/handler/qoder_cleanup.go b/server/internal/handler/qoder_cleanup.go
new file mode 100644
index 0000000000..80fc5da57b
--- /dev/null
+++ b/server/internal/handler/qoder_cleanup.go
@@ -0,0 +1,116 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+
+ "github.com/multica-ai/multica/server/internal/qoderruntime"
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+// Retired connections keep their encrypted journal until remote cancellation
+// succeeds. Cleanup is independent of the former owner's access token.
+func (h *Handler) cleanupInactiveQoder(ctx context.Context) {
+ rows, err := h.DB.Query(ctx, `SELECT c.workspace_id::text FROM cloud_agent_connection c WHERE c.provider='qoder_cloud' AND c.journal_encrypted<>'' AND (NOT c.enabled OR NOT EXISTS(SELECT 1 FROM member m WHERE m.workspace_id=c.workspace_id AND m.user_id=c.owner_id AND m.role IN ('owner','admin')))`)
+ if err != nil {
+ return
+ }
+ var workspaces []string
+ for rows.Next() {
+ var ws string
+ if rows.Scan(&ws) == nil {
+ workspaces = append(workspaces, ws)
+ }
+ }
+ rows.Close()
+ for _, ws := range workspaces {
+ cleanupCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ _ = h.cleanupQoderJournal(cleanupCtx, ws)
+ cancel()
+ }
+}
+
+func (h *Handler) cleanupQoderJournal(ctx context.Context, ws string) error {
+ cfg, _, _, _, err := h.readQoderSettings(ctx, ws)
+ if err != nil {
+ return err
+ }
+ var encrypted string
+ if err = h.DB.QueryRow(ctx, `SELECT journal_encrypted FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1`, ws).Scan(&encrypted); err != nil {
+ return err
+ }
+ if encrypted == "" {
+ return nil
+ }
+ raw, err := h.openVCSSecret(encrypted)
+ if err != nil {
+ return err
+ }
+ type journalRun struct {
+ TaskID string `json:"task_id"`
+ SessionID string `json:"session_id"`
+ }
+ var state struct {
+ Run *journalRun `json:"run"`
+ Runs []journalRun `json:"runs"`
+ Cleanup []string `json:"cleanup"`
+ }
+ if err = json.Unmarshal([]byte(raw), &state); err != nil {
+ return err
+ }
+ if state.Run != nil {
+ state.Runs = append(state.Runs, *state.Run)
+ }
+ sessions := state.Cleanup
+ for _, run := range state.Runs {
+ if run.SessionID != "" {
+ sessions = append(sessions, run.SessionID)
+ }
+ id, err := util.ParseUUID(run.TaskID)
+ if err != nil {
+ return err
+ }
+ // The task transition is idempotent and does not require the removed owner.
+ if _, err = h.TaskService.FailTask(ctx, id, "Qoder connection stopped", run.SessionID, "", "", "qoder_cloud_execution", false, "", ""); err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ return err
+ }
+ }
+ for _, id := range sessions {
+ if err = qoderruntime.CancelRemoteSession(ctx, cfg.BaseURL, cfg.QoderToken, id); err != nil {
+ return fmt.Errorf("remote cleanup pending: %w", err)
+ }
+ }
+ _, err = h.DB.Exec(ctx, `UPDATE cloud_agent_connection SET journal_encrypted='' WHERE provider='qoder_cloud' AND workspace_id=$1`, ws)
+ return err
+}
+
+func (h *Handler) prepareQoderWorkspaceDeletion(ctx context.Context, ws string) error {
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback(ctx)
+ if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,19))`, ws); err != nil {
+ return err
+ }
+ var busy bool
+ err = tx.QueryRow(ctx, `UPDATE cloud_agent_connection SET enabled=false,status='stopped' WHERE provider='qoder_cloud' AND workspace_id=$1 RETURNING COALESCE(busy_until>now(),false)`, ws).Scan(&busy)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ if err = tx.Commit(ctx); err != nil {
+ return err
+ }
+ if busy {
+ return fmt.Errorf("remote step still active")
+ }
+ return h.cleanupQoderJournal(ctx, ws)
+}
diff --git a/server/internal/handler/qoder_connection.go b/server/internal/handler/qoder_connection.go
new file mode 100644
index 0000000000..d915fa5eb5
--- /dev/null
+++ b/server/internal/handler/qoder_connection.go
@@ -0,0 +1,627 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/url"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/auth"
+ "github.com/multica-ai/multica/server/internal/qoderruntime"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+type qoderSettings struct {
+ Name string `json:"name"`
+ BaseURL string `json:"base_url"`
+ EnvironmentID string `json:"environment_id"`
+ QoderToken string `json:"qoder_token,omitempty"`
+ GitHubTokens map[string]string `json:"github_tokens,omitempty"`
+ MulticaToken string `json:"multica_token,omitempty"`
+ MaxConcurrency int `json:"max_concurrency,omitempty"`
+ RunTimeoutMinutes int `json:"run_timeout_minutes,omitempty"`
+}
+
+const (
+ defaultQoderConcurrency = 3
+ defaultQoderRunTimeout = 60
+ maxQoderRunTimeout = 240
+)
+
+// withDefaults fills limits for connections saved before they were configurable.
+func (s qoderSettings) withDefaults() qoderSettings {
+ if s.MaxConcurrency == 0 {
+ s.MaxConcurrency = defaultQoderConcurrency
+ }
+ if s.RunTimeoutMinutes == 0 {
+ s.RunTimeoutMinutes = defaultQoderRunTimeout
+ }
+ return s
+}
+
+type qoderSettingsView struct {
+ Configured bool `json:"configured"`
+ Available bool `json:"available"`
+ Name string `json:"name"`
+ BaseURL string `json:"base_url"`
+ EnvironmentID string `json:"environment_id"`
+ HasToken bool `json:"has_token"`
+ Repositories []string `json:"repositories"`
+ Enabled bool `json:"enabled"`
+ Status string `json:"status"`
+ LastError string `json:"last_error"`
+ MaxConcurrency int `json:"max_concurrency"`
+ RunTimeoutMinutes int `json:"run_timeout_minutes"`
+ ActiveRuns int `json:"active_runs"`
+ QueuedRuns int `json:"queued_runs"`
+}
+
+func (h *Handler) readQoderSettings(ctx context.Context, ws string) (qoderSettings, bool, string, string, error) {
+ var encrypted, status, lastError string
+ var enabled bool
+ err := h.DB.QueryRow(ctx, `SELECT config_encrypted, enabled, status, last_error FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1`, ws).Scan(&encrypted, &enabled, &status, &lastError)
+ if err != nil {
+ return qoderSettings{}, false, "", "", err
+ }
+ raw, err := h.openVCSSecret(encrypted)
+ if err != nil {
+ return qoderSettings{}, false, "", "", fmt.Errorf("cannot decrypt QCA configuration")
+ }
+ var cfg qoderSettings
+ err = json.Unmarshal([]byte(raw), &cfg)
+ return cfg.withDefaults(), enabled, status, lastError, err
+}
+
+func (h *Handler) GetQoderConnection(w http.ResponseWriter, r *http.Request) {
+ ws, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace_id")
+ if !ok {
+ return
+ }
+ view := qoderSettingsView{Available: h.VCSSecretBox != nil, Repositories: []string{}}
+ if !view.Available {
+ writeJSON(w, 200, view)
+ return
+ }
+ cfg, enabled, status, lastError, err := h.readQoderSettings(r.Context(), uuidToString(ws))
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeJSON(w, 200, view)
+ return
+ }
+ if err != nil {
+ writeError(w, 500, "cannot read QCA configuration")
+ return
+ }
+ var online bool
+ _ = h.DB.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM agent_runtime WHERE workspace_id=$1 AND provider='qoder_cloud' AND last_seen_at>now()-interval '45 seconds' AND status='online')`, ws).Scan(&online)
+ if status == "online" && enabled && !online {
+ status = "offline"
+ }
+ view.Configured = true
+ view.Name = cfg.Name
+ view.BaseURL = cfg.BaseURL
+ view.EnvironmentID = cfg.EnvironmentID
+ view.HasToken = cfg.QoderToken != ""
+ view.Enabled = enabled
+ view.Status = status
+ view.LastError = lastError
+ view.MaxConcurrency = cfg.MaxConcurrency
+ view.RunTimeoutMinutes = cfg.RunTimeoutMinutes
+ _ = h.DB.QueryRow(r.Context(), `SELECT count(*) FILTER (WHERE t.status IN ('dispatched','running')), count(*) FILTER (WHERE t.status='queued') FROM agent_task_queue t JOIN agent_runtime rt ON rt.id=t.runtime_id WHERE rt.workspace_id=$1 AND rt.provider='qoder_cloud' AND t.status IN ('queued','dispatched','running')`, ws).Scan(&view.ActiveRuns, &view.QueuedRuns)
+ for repo := range cfg.GitHubTokens {
+ view.Repositories = append(view.Repositories, repo)
+ }
+ sort.Strings(view.Repositories)
+ writeJSON(w, 200, view)
+}
+
+func (h *Handler) qoderInput(w http.ResponseWriter, r *http.Request, ws string) (qoderSettings, bool) {
+ var cfg qoderSettings
+ if h.VCSSecretBox == nil {
+ writeError(w, 503, "QCA requires MULTICA_VCS_SECRET_KEY on the server")
+ return cfg, false
+ }
+ var req struct {
+ Name string `json:"name"`
+ BaseURL string `json:"base_url"`
+ EnvironmentID string `json:"environment_id"`
+ QoderToken string `json:"qoder_token"`
+ GitHubTokens map[string]string `json:"github_tokens"`
+ MaxConcurrency int `json:"max_concurrency"`
+ RunTimeoutMinutes int `json:"run_timeout_minutes"`
+ }
+ decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10))
+ decoder.DisallowUnknownFields()
+ if err := decoder.Decode(&req); err != nil {
+ writeError(w, 400, "invalid QCA configuration")
+ return cfg, false
+ }
+ var extra any
+ if decoder.Decode(&extra) != io.EOF {
+ writeError(w, 400, "configuration must contain one JSON object")
+ return cfg, false
+ }
+ cfg, _, _, _, err := h.readQoderSettings(r.Context(), ws)
+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, 500, "cannot read QCA configuration")
+ return cfg, false
+ }
+ cfg.Name = strings.TrimSpace(req.Name)
+ cfg.BaseURL = strings.TrimRight(strings.TrimSpace(req.BaseURL), "/")
+ cfg.EnvironmentID = strings.TrimSpace(req.EnvironmentID)
+ if !qoderAPIURLs[cfg.BaseURL] || cfg.EnvironmentID == "" || cfg.Name == "" {
+ writeError(w, 400, "name, environment and official API URL are required")
+ return cfg, false
+ }
+ if req.MaxConcurrency != 0 {
+ cfg.MaxConcurrency = req.MaxConcurrency
+ }
+ if req.RunTimeoutMinutes != 0 {
+ cfg.RunTimeoutMinutes = req.RunTimeoutMinutes
+ }
+ cfg = cfg.withDefaults()
+ if cfg.MaxConcurrency < 1 || cfg.MaxConcurrency > qoderruntime.MaxConcurrencyLimit {
+ writeError(w, 400, fmt.Sprintf("concurrency must be between 1 and %d", qoderruntime.MaxConcurrencyLimit))
+ return cfg, false
+ }
+ if cfg.RunTimeoutMinutes < 5 || cfg.RunTimeoutMinutes > maxQoderRunTimeout {
+ writeError(w, 400, fmt.Sprintf("run timeout must be between 5 and %d minutes", maxQoderRunTimeout))
+ return cfg, false
+ }
+ if req.QoderToken != "" {
+ cfg.QoderToken = strings.TrimSpace(req.QoderToken)
+ }
+ if cfg.QoderToken == "" || strings.ContainsAny(cfg.QoderToken, "\r\n\t ") {
+ writeError(w, 400, "QCA token is required")
+ return cfg, false
+ }
+ if req.GitHubTokens != nil {
+ next := map[string]string{}
+ for raw, token := range req.GitHubTokens {
+ key, err := qoderruntime.RepositoryKey(raw)
+ if err != nil {
+ writeError(w, 400, "invalid GitHub repository URL")
+ return cfg, false
+ }
+ if _, exists := next[key]; exists {
+ writeError(w, 400, "duplicate repository binding")
+ return cfg, false
+ }
+ if token == "" {
+ token = cfg.GitHubTokens[key]
+ }
+ if strings.TrimSpace(token) == "" || strings.ContainsAny(strings.TrimSpace(token), "\r\n\t ") {
+ writeError(w, 400, "GitHub token is required for each repository")
+ return cfg, false
+ }
+ next[key] = strings.TrimSpace(token)
+ }
+ cfg.GitHubTokens = next
+ }
+ return cfg, true
+}
+
+func (h *Handler) CheckQoderConnection(w http.ResponseWriter, r *http.Request) {
+ ws, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace_id")
+ if !ok {
+ return
+ }
+ cfg, ok := h.qoderInput(w, r, uuidToString(ws))
+ if !ok {
+ return
+ }
+ client := &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
+ for path, expectedID := range map[string]string{"/environments/" + url.PathEscape(cfg.EnvironmentID): cfg.EnvironmentID} {
+ req, err := http.NewRequestWithContext(r.Context(), "GET", cfg.BaseURL+path, nil)
+ if err != nil {
+ writeError(w, 400, "invalid QCA resource")
+ return
+ }
+ req.Header.Set("Authorization", "Bearer "+cfg.QoderToken)
+ res, err := client.Do(req)
+ if err != nil {
+ writeError(w, 502, "QCA connection failed")
+ return
+ }
+ if res.StatusCode != 200 {
+ res.Body.Close()
+ writeError(w, 400, fmt.Sprintf("QCA access check returned HTTP %d", res.StatusCode))
+ return
+ }
+ var resource struct {
+ ID string `json:"id"`
+ }
+ err = json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&resource)
+ res.Body.Close()
+ if err != nil || resource.ID != expectedID {
+ writeError(w, 502, "invalid QCA resource response")
+ return
+ }
+ }
+ writeJSON(w, 200, map[string]bool{"ok": true})
+}
+
+// SaveQoderConnection keeps a paused connection paused; only
+// ResumeQoderConnection (or the first connect) enables execution.
+func (h *Handler) SaveQoderConnection(w http.ResponseWriter, r *http.Request) {
+ h.saveQoderConnection(w, r, false)
+}
+
+func (h *Handler) ResumeQoderConnection(w http.ResponseWriter, r *http.Request) {
+ h.saveQoderConnection(w, r, true)
+}
+
+func (h *Handler) saveQoderConnection(w http.ResponseWriter, r *http.Request, resume bool) {
+ ws, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace_id")
+ if !ok {
+ return
+ }
+ user, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ cfg, ok := h.qoderInput(w, r, uuidToString(ws))
+ if !ok {
+ return
+ }
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, 500, "cannot save QCA configuration")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ // Serialize writes even before a connection exists.
+ if _, err = tx.Exec(r.Context(), `SELECT pg_advisory_xact_lock(hashtextextended($1, 19))`, uuidToString(ws)); err != nil {
+ writeError(w, 500, "cannot lock QCA configuration")
+ return
+ }
+ var busy bool
+ if err := tx.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1 AND busy_until>now())`, ws).Scan(&busy); err != nil {
+ writeError(w, 500, "cannot check QCA connection")
+ return
+ }
+ if busy {
+ writeError(w, 409, "QCA is synchronizing; retry shortly")
+ return
+ }
+
+ var journal string
+ if err := tx.QueryRow(r.Context(), `SELECT journal_encrypted FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1`, ws).Scan(&journal); err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, 500, "cannot read execution state")
+ return
+ }
+ if journal != "" {
+ raw, err := h.openVCSSecret(journal)
+ if err != nil {
+ writeError(w, 500, "cannot read execution state")
+ return
+ }
+ var state struct {
+ Run json.RawMessage `json:"run"`
+ Runs []json.RawMessage `json:"runs"`
+ Cleanup []string `json:"cleanup"`
+ }
+ if json.Unmarshal([]byte(raw), &state) != nil {
+ writeError(w, 500, "cannot read execution state")
+ return
+ }
+ if len(state.Cleanup) > 0 || len(state.Runs) > 0 || (len(state.Run) > 0 && string(state.Run) != "null") {
+ writeError(w, 409, "wait for QCA execution cleanup before changing configuration")
+ return
+ }
+ }
+ var revokedHash string
+ _ = tx.QueryRow(r.Context(), `SELECT d.token_hash FROM daemon_token d JOIN cloud_agent_connection c ON c.token_id=d.id AND c.provider='qoder_cloud' WHERE c.workspace_id=$1`, ws).Scan(&revokedHash)
+ var active bool
+ err = tx.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM agent_task_queue t JOIN agent_runtime rt ON rt.id=t.runtime_id WHERE rt.workspace_id=$1 AND rt.provider='qoder_cloud' AND t.status IN ('running','dispatched'))`, ws).Scan(&active)
+ if err != nil {
+ writeError(w, 500, "cannot check active QCA tasks")
+ return
+ }
+ if active {
+ writeError(w, 409, "wait for active QCA tasks to finish before changing configuration")
+ return
+ }
+ rawToken, err := auth.GenerateDaemonToken()
+ if err != nil {
+ writeError(w, 500, "cannot generate service credential")
+ return
+ }
+ q := h.Queries.WithTx(tx)
+ pat, err := q.CreateDaemonToken(r.Context(), db.CreateDaemonTokenParams{WorkspaceID: ws, DaemonID: "qoder-managed-" + uuidToString(ws), TokenHash: auth.HashToken(rawToken), ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(time.Hour), Valid: true}})
+ if err != nil {
+ writeError(w, 500, "cannot create service credential")
+ return
+ }
+ cfg.MulticaToken = rawToken
+ raw, _ := json.Marshal(cfg)
+ encrypted, err := h.sealVCSSecret(string(raw))
+ if err != nil {
+ writeError(w, 500, "cannot encrypt QCA configuration")
+ return
+ }
+ _, err = tx.Exec(r.Context(), `DELETE FROM daemon_token WHERE id IN (SELECT token_id FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1)`, ws)
+ if err == nil {
+ _, err = tx.Exec(r.Context(), `INSERT INTO cloud_agent_connection(workspace_id,provider,owner_id,token_id,config_encrypted) VALUES($1,'qoder_cloud',$2,$3,$4) ON CONFLICT(workspace_id,provider) DO UPDATE SET owner_id=excluded.owner_id,token_id=excluded.token_id,config_encrypted=excluded.config_encrypted,enabled=($5 OR cloud_agent_connection.enabled),journal_encrypted='',revision=cloud_agent_connection.revision+1,status=CASE WHEN $5 OR cloud_agent_connection.enabled THEN 'starting' ELSE cloud_agent_connection.status END,last_error='',updated_at=now()`, ws, parseUUID(user), pat.ID, encrypted, resume)
+ }
+ if err != nil || tx.Commit(r.Context()) != nil {
+ writeError(w, 500, "cannot save QCA configuration")
+ return
+ }
+ h.DaemonTokenCache.Invalidate(r.Context(), revokedHash)
+ h.GetQoderConnection(w, r)
+}
+
+// RunQoderConnections owns managed bridges for this server. A database advisory
+// lock elects one supervisor, and each bridge journal lives encrypted in
+// cloud_agent_connection, so a restart or another replica resumes it.
+func (h *Handler) RunQoderConnections(ctx context.Context, pool *pgxpool.Pool, serverURL string) {
+ if h.VCSSecretBox == nil {
+ return
+ }
+ for ctx.Err() == nil {
+ conn, err := pool.Acquire(ctx)
+ if err != nil {
+ if ctx.Err() != nil {
+ return
+ }
+ slog.WarnContext(ctx, "Qoder supervisor database connection unavailable", "error", err)
+ select {
+ case <-ctx.Done():
+ return
+ case <-time.After(5 * time.Second):
+ continue
+ }
+ }
+ var locked bool
+ err = conn.QueryRow(ctx, `SELECT pg_try_advisory_lock(71243, 8191)`).Scan(&locked)
+ if err == nil && locked {
+ h.runQoderSupervisor(ctx, conn, serverURL)
+ }
+ if locked {
+ _, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock(71243,8191)`)
+ }
+ conn.Release()
+ select {
+ case <-ctx.Done():
+ return
+ case <-time.After(5 * time.Second):
+ }
+ }
+}
+
+type managedQoderRun struct {
+ revision int64
+ cancel context.CancelFunc
+ done chan error
+}
+
+func (h *Handler) runQoderSupervisor(ctx context.Context, conn *pgxpool.Conn, serverURL string) {
+ runs := map[string]managedQoderRun{}
+ retryAt := map[string]time.Time{}
+ failures := map[string]int{}
+ defer func() {
+ for _, run := range runs {
+ run.cancel()
+ <-run.done
+ }
+ }()
+ for ctx.Err() == nil {
+ _, _ = conn.Exec(ctx, `UPDATE daemon_token d SET expires_at=now()+interval '1 hour' FROM cloud_agent_connection c JOIN member m ON m.workspace_id=c.workspace_id AND m.user_id=c.owner_id WHERE c.provider='qoder_cloud' AND d.id=c.token_id AND c.enabled=true AND m.role IN ('owner','admin') AND d.expires_at<now()+interval '30 minutes'`)
+ revoked, revokeErr := conn.Query(ctx, `DELETE FROM daemon_token d USING cloud_agent_connection c WHERE c.provider='qoder_cloud' AND d.id=c.token_id AND (NOT c.enabled OR NOT EXISTS(SELECT 1 FROM member m WHERE m.workspace_id=c.workspace_id AND m.user_id=c.owner_id AND m.role IN ('owner','admin'))) RETURNING d.token_hash`)
+ if revokeErr != nil {
+ return
+ }
+ for revoked.Next() {
+ var hash string
+ if revoked.Scan(&hash) == nil {
+ h.DaemonTokenCache.Invalidate(ctx, hash)
+ }
+ }
+ revoked.Close()
+ rows, err := conn.Query(ctx, `SELECT c.workspace_id::text,c.revision FROM cloud_agent_connection c JOIN workspace w ON w.id=c.workspace_id JOIN member m ON m.workspace_id=c.workspace_id AND m.user_id=c.owner_id WHERE c.provider='qoder_cloud' AND c.enabled=true AND m.role IN ('owner','admin')`)
+ if err != nil {
+ return
+ }
+ desired := map[string]int64{}
+ for rows.Next() {
+ var ws string
+ var rev int64
+ if rows.Scan(&ws, &rev) != nil {
+ rows.Close()
+ return
+ }
+ desired[ws] = rev
+ }
+ err = rows.Err()
+ rows.Close()
+ if err != nil {
+ return
+ }
+ retryLater := map[string]bool{}
+ for ws, run := range runs {
+ if desired[ws] != run.revision {
+ run.cancel()
+ <-run.done
+ delete(runs, ws)
+ continue
+ }
+ select {
+ case err := <-run.done:
+ message := "execution service stopped; retrying"
+ if err != nil {
+ slog.WarnContext(ctx, "Qoder bridge stopped", "workspace_id", ws, "error", err)
+ message = "remote execution unavailable; retrying"
+ }
+ _, _ = conn.Exec(ctx, `UPDATE cloud_agent_connection SET status='error',last_error=$2 WHERE provider='qoder_cloud' AND workspace_id=$1`, ws, message)
+ delete(runs, ws)
+ retryLater[ws] = true
+ failures[ws]++
+ delay := 10 * time.Second << min(failures[ws]-1, 5)
+ retryAt[ws] = time.Now().Add(delay)
+ default:
+ }
+ }
+ h.cleanupInactiveQoder(ctx)
+ for ws, rev := range desired {
+ if retryLater[ws] || time.Now().Before(retryAt[ws]) {
+ continue
+ }
+ if _, ok := runs[ws]; ok {
+ continue
+ }
+ cfg, _, _, _, err := h.readQoderSettings(ctx, ws)
+ if err != nil {
+ continue
+ }
+ bridge, err := qoderruntime.New(qoderruntime.Config{DaemonID: "qoder-managed-" + ws, MulticaURL: serverURL, MulticaToken: cfg.MulticaToken, WorkspaceID: ws, QoderURL: cfg.BaseURL, QoderToken: cfg.QoderToken, EnvironmentID: cfg.EnvironmentID, Name: cfg.Name, MaxConcurrency: cfg.MaxConcurrency, RunTimeout: time.Duration(cfg.RunTimeoutMinutes) * time.Minute, GitHubTokens: cfg.GitHubTokens,
+ LoadState: func(loadCtx context.Context) ([]byte, error) {
+ var encrypted string
+ if err := h.DB.QueryRow(loadCtx, `SELECT journal_encrypted FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1`, ws).Scan(&encrypted); err != nil {
+ return nil, err
+ }
+ if encrypted == "" {
+ return nil, nil
+ }
+ raw, err := h.openVCSSecret(encrypted)
+ return []byte(raw), err
+ },
+ SaveState: func(saveCtx context.Context, raw []byte) error {
+ encrypted, err := h.sealVCSSecret(string(raw))
+ if err != nil {
+ return err
+ }
+ _, err = h.DB.Exec(saveCtx, `UPDATE cloud_agent_connection SET journal_encrypted=$2 WHERE provider='qoder_cloud' AND workspace_id=$1`, ws, encrypted)
+ return err
+ },
+ OnReady: func(readyCtx context.Context, runtimeID string) error {
+ return h.qoderReady(readyCtx, ws, rev, runtimeID)
+ },
+ BeforeStep: func(stepCtx context.Context) (func(), error) {
+ return h.acquireQoderStep(stepCtx, ws, rev)
+ }}, nil)
+ if err != nil {
+ _, _ = conn.Exec(ctx, `UPDATE cloud_agent_connection SET status='error',last_error='invalid execution configuration' WHERE provider='qoder_cloud' AND workspace_id=$1`, ws)
+ continue
+ }
+ runCtx, cancel := context.WithCancel(ctx)
+ done := make(chan error, 1)
+ runs[ws] = managedQoderRun{rev, cancel, done}
+ _, _ = conn.Exec(ctx, `UPDATE cloud_agent_connection SET status='starting',last_error='' WHERE provider='qoder_cloud' AND workspace_id=$1`, ws)
+ go func() { done <- bridge.Run(runCtx) }()
+ }
+ select {
+ case <-ctx.Done():
+ return
+ case <-time.After(5 * time.Second):
+ }
+ }
+}
+
+// StopQoderConnection pauses an idle connection without discarding its secrets.
+// Active work must be cancelled through the task API before stopping service.
+func (h *Handler) StopQoderConnection(w http.ResponseWriter, r *http.Request) {
+ ws, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace_id")
+ if !ok {
+ return
+ }
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, 500, "cannot stop QCA runtime")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ _, err = tx.Exec(r.Context(), `SELECT pg_advisory_xact_lock(hashtextextended($1,19))`, uuidToString(ws))
+ if err != nil {
+ writeError(w, 500, "cannot lock QCA configuration")
+ return
+ }
+ var busy bool
+ if err := tx.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1 AND busy_until>now())`, ws).Scan(&busy); err != nil {
+ writeError(w, 500, "cannot check QCA connection")
+ return
+ }
+ if busy {
+ writeError(w, 409, "QCA is synchronizing; retry shortly")
+ return
+ }
+ var revokedHash string
+ _ = tx.QueryRow(r.Context(), `SELECT d.token_hash FROM daemon_token d JOIN cloud_agent_connection c ON c.token_id=d.id AND c.provider='qoder_cloud' WHERE c.workspace_id=$1`, ws).Scan(&revokedHash)
+ var active bool
+ err = tx.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM agent_task_queue t JOIN agent_runtime rt ON rt.id=t.runtime_id WHERE rt.workspace_id=$1 AND rt.provider='qoder_cloud' AND t.status IN ('running','dispatched'))`, ws).Scan(&active)
+ if err != nil {
+ writeError(w, 500, "cannot check active QCA tasks")
+ return
+ }
+ if active {
+ writeError(w, 409, "wait for or cancel active QCA tasks before stopping")
+ return
+ }
+ _, err = tx.Exec(r.Context(), `DELETE FROM daemon_token WHERE id IN (SELECT token_id FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1)`, ws)
+ if err != nil {
+ writeError(w, 500, "cannot revoke runtime credential")
+ return
+ }
+ _, err = tx.Exec(r.Context(), `UPDATE cloud_agent_connection SET enabled=false,revision=revision+1,status='stopped',last_error='' WHERE provider='qoder_cloud' AND workspace_id=$1`, ws)
+ if err != nil || tx.Commit(r.Context()) != nil {
+ writeError(w, 500, "cannot stop QCA runtime")
+ return
+ }
+ h.DaemonTokenCache.Invalidate(r.Context(), revokedHash)
+ h.GetQoderConnection(w, r)
+}
+
+func (h *Handler) qoderReady(ctx context.Context, ws string, revision int64, runtimeID string) error {
+ if _, err := h.DB.Exec(ctx, `UPDATE agent_runtime SET visibility='public',owner_id=(SELECT owner_id FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$2) WHERE id=$1 AND workspace_id=$2`, runtimeID, ws); err != nil {
+ return fmt.Errorf("cannot publish managed runtime")
+ }
+ _, err := h.DB.Exec(ctx, `UPDATE cloud_agent_connection SET status='online',last_error='' WHERE provider='qoder_cloud' AND workspace_id=$1 AND revision=$2`, ws, revision)
+ return err
+}
+
+func (h *Handler) qoderCredentialAllowed(r *http.Request, ws, daemonID string) (bool, error) {
+ var allowed bool
+ err := h.DB.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM cloud_agent_connection c JOIN daemon_token d ON d.id=c.token_id JOIN member m ON m.workspace_id=c.workspace_id AND m.user_id=c.owner_id WHERE c.provider='qoder_cloud' AND c.workspace_id=$1 AND c.enabled AND d.daemon_id=$2 AND d.token_hash=$3 AND d.expires_at>now() AND m.role IN ('owner','admin'))`, ws, daemonID, auth.HashToken(strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))).Scan(&allowed)
+ return allowed, err
+}
+
+func (h *Handler) acquireQoderStep(stepCtx context.Context, ws string, rev int64) (func(), error) {
+ tx, err := h.TxStarter.Begin(stepCtx)
+ if err != nil {
+ return nil, err
+ }
+ defer tx.Rollback(stepCtx)
+ release := func() {
+ releaseCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ _, _ = h.DB.Exec(releaseCtx, `UPDATE cloud_agent_connection SET busy_until=NULL WHERE provider='qoder_cloud' AND workspace_id=$1 AND revision=$2`, ws, rev)
+ }
+ if _, err = tx.Exec(stepCtx, `SELECT pg_advisory_xact_lock(hashtextextended($1,19))`, ws); err != nil {
+ return nil, err
+ }
+ var valid bool
+ err = tx.QueryRow(stepCtx, `SELECT EXISTS(SELECT 1 FROM cloud_agent_connection c JOIN member m ON m.workspace_id=c.workspace_id AND m.user_id=c.owner_id WHERE c.provider='qoder_cloud' AND c.workspace_id=$1 AND c.revision=$2 AND c.enabled=true AND m.role IN ('owner','admin') AND (c.busy_until IS NULL OR c.busy_until<now()))`, ws, rev).Scan(&valid)
+ if err != nil {
+ return nil, err
+ }
+ if !valid {
+ return nil, context.Canceled
+ }
+ if _, err := tx.Exec(stepCtx, `UPDATE cloud_agent_connection SET busy_until=now()+interval '45 seconds' WHERE provider='qoder_cloud' AND workspace_id=$1 AND revision=$2`, ws, rev); err != nil {
+ return nil, err
+ }
+ if err := tx.Commit(stepCtx); err != nil {
+ return nil, err
+ }
+ return release, nil
+}
diff --git a/server/internal/handler/qoder_connection_test.go b/server/internal/handler/qoder_connection_test.go
new file mode 100644
index 0000000000..8afb186255
--- /dev/null
+++ b/server/internal/handler/qoder_connection_test.go
@@ -0,0 +1,301 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/auth"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func TestQoderConnectionSecrets(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ withVCSBox(t)
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM daemon_token WHERE id IN (SELECT token_id FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1)`, testWorkspaceID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1`, testWorkspaceID)
+ })
+ body := map[string]any{"name": "Managed QCA", "base_url": "https://api.qoder.com/api/v1/cloud", "environment_id": "env_test", "qoder_token": "qca-test-secret", "github_tokens": map[string]string{"https://github.com/owner/repo": "github-test-secret"}}
+ var view qoderSettingsView
+ testutil.Call(t, testHandler.SaveQoderConnection, vcsHandlerRequest("PUT", "/qoder", body, "")).Want(200).JSON(&view)
+ if !view.Configured || !view.HasToken || len(view.Repositories) != 1 {
+ t.Fatalf("unexpected view: %+v", view)
+ }
+ var encrypted string
+ dbfx.QueryRow(t, `SELECT config_encrypted FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1`, testWorkspaceID).Scan(&encrypted)
+ raw, _ := json.Marshal(view)
+ for _, secret := range []string{"qca-test-secret", "github-test-secret"} {
+ if strings.Contains(encrypted, secret) || strings.Contains(string(raw), secret) {
+ t.Fatal("plaintext credential exposed")
+ }
+ }
+ body["qoder_token"] = ""
+ body["github_tokens"] = map[string]string{"https://github.com/owner/repo": ""}
+ testutil.Call(t, testHandler.SaveQoderConnection, vcsHandlerRequest("PUT", "/qoder", body, "")).Want(200)
+ cfg, _, _, _, err := testHandler.readQoderSettings(context.Background(), testWorkspaceID)
+ if err != nil || cfg.QoderToken != "qca-test-secret" || cfg.GitHubTokens["https://github.com/owner/repo"] != "github-test-secret" {
+ t.Fatal("blank field did not retain credentials")
+ }
+ if !strings.HasPrefix(cfg.MulticaToken, "mdt_") {
+ t.Fatal("managed bridge must use a daemon credential")
+ }
+ var credentialWorkspace, daemonID string
+ var expiring bool
+ dbfx.QueryRow(t, `SELECT workspace_id::text,daemon_id,expires_at>now() AND expires_at<now()+interval '2 hours' FROM daemon_token WHERE token_hash=$1`, auth.HashToken(cfg.MulticaToken)).Scan(&credentialWorkspace, &daemonID, &expiring)
+ if credentialWorkspace != testWorkspaceID || daemonID != "qoder-managed-"+testWorkspaceID || !expiring {
+ t.Fatal("unscoped or non-expiring service credential")
+ }
+ body["github_tokens"] = map[string]string{}
+ testutil.Call(t, testHandler.SaveQoderConnection, vcsHandlerRequest("PUT", "/qoder", body, "")).Want(200)
+ cfg, _, _, _, err = testHandler.readQoderSettings(context.Background(), testWorkspaceID)
+ if err != nil || len(cfg.GitHubTokens) != 0 {
+ t.Fatal("removed repository retained credential")
+ }
+ testutil.Call(t, testHandler.StopQoderConnection, vcsHandlerRequest("POST", "/qoder/stop", nil, "")).Want(200).JSON(&view)
+ var tokenCount int
+ dbfx.QueryRow(t, `SELECT count(*) FROM daemon_token d JOIN cloud_agent_connection c ON c.token_id=d.id AND c.provider='qoder_cloud' WHERE c.workspace_id=$1`, testWorkspaceID).Scan(&tokenCount)
+ if tokenCount != 0 {
+ t.Fatal("stopped credential still exists")
+ }
+ if view.Enabled {
+ t.Fatal("connection did not stop")
+ }
+ runtimeID := dbfx.Runtime(t, "active QCA", testutil.Cols{"provider": "qoder_cloud", "runtime_mode": "cloud"})
+ var revision int64
+ dbfx.QueryRow(t, `SELECT revision FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1`, testWorkspaceID).Scan(&revision)
+ if err := testHandler.qoderReady(context.Background(), testWorkspaceID, revision, runtimeID); err != nil {
+ t.Fatal(err)
+ }
+ var visibility string
+ dbfx.QueryRow(t, `SELECT visibility FROM agent_runtime WHERE id=$1`, runtimeID).Scan(&visibility)
+ if visibility != "public" {
+ t.Fatal("managed runtime is not available to workspace members")
+ }
+ agentID := dbfx.Agent(t, "active QCA agent", runtimeID)
+ dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "status": "running"})
+ testutil.Call(t, testHandler.SaveQoderConnection, vcsHandlerRequest("PUT", "/qoder", body, "")).Want(409)
+ testutil.Call(t, testHandler.StopQoderConnection, vcsHandlerRequest("POST", "/qoder/stop", nil, "")).Want(409)
+
+ body["base_url"] = "http://127.0.0.1:1"
+ testutil.Call(t, testHandler.SaveQoderConnection, vcsHandlerRequest("PUT", "/qoder", body, "")).Want(400)
+ body["base_url"] = "https://api.qoder.com/api/v1/cloud"
+ body["multica_token"] = "injected"
+ testutil.Call(t, testHandler.SaveQoderConnection, vcsHandlerRequest("PUT", "/qoder", body, "")).Want(400)
+}
+
+func TestQoderBaseURL(t *testing.T) {
+ for raw, want := range map[string]string{
+ "": qoderAPIURL,
+ "https://api.qoder.com/api/v1/cloud/": qoderAPIURL,
+ " https://api.qoder.com.cn/api/v1/cloud": "https://api.qoder.com.cn/api/v1/cloud",
+ } {
+ if got, ok := qoderBaseURL(raw); !ok || got != want {
+ t.Fatalf("qoderBaseURL(%q) = %q, %v", raw, got, ok)
+ }
+ }
+ for _, raw := range []string{"https://api.qoder.com.cn.evil.test/api/v1/cloud", "http://api.qoder.com/api/v1/cloud", "https://api.qoder.com.cn/api/v1"} {
+ if _, ok := qoderBaseURL(raw); ok {
+ t.Fatalf("qoderBaseURL(%q) accepted", raw)
+ }
+ }
+}
+
+func TestQoderConnectionLimits(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ withVCSBox(t)
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM daemon_token WHERE id IN (SELECT token_id FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1)`, testWorkspaceID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1`, testWorkspaceID)
+ })
+ body := map[string]any{"name": "Managed QCA", "base_url": "https://api.qoder.com/api/v1/cloud", "environment_id": "env_test", "qoder_token": "qca-test-secret"}
+ var view qoderSettingsView
+ testutil.Call(t, testHandler.SaveQoderConnection, vcsHandlerRequest("PUT", "/qoder", body, "")).Want(200).JSON(&view)
+ if view.MaxConcurrency != defaultQoderConcurrency || view.RunTimeoutMinutes != defaultQoderRunTimeout {
+ t.Fatalf("defaults not applied: %+v", view)
+ }
+ for _, invalid := range []map[string]any{{"max_concurrency": 11}, {"max_concurrency": -1}, {"run_timeout_minutes": 4}, {"run_timeout_minutes": 241}} {
+ req := map[string]any{}
+ for k, v := range body {
+ req[k] = v
+ }
+ for k, v := range invalid {
+ req[k] = v
+ }
+ testutil.Call(t, testHandler.SaveQoderConnection, vcsHandlerRequest("PUT", "/qoder", req, "")).Want(400)
+ }
+ body["base_url"] = "https://api.qoder.com.cn/api/v1/cloud/"
+ testutil.Call(t, testHandler.SaveQoderConnection, vcsHandlerRequest("PUT", "/qoder", body, "")).Want(200).JSON(&view)
+ if view.BaseURL != "https://api.qoder.com.cn/api/v1/cloud" {
+ t.Fatalf("China region not saved: %+v", view)
+ }
+ body["max_concurrency"] = 5
+ body["run_timeout_minutes"] = 90
+ testutil.Call(t, testHandler.SaveQoderConnection, vcsHandlerRequest("PUT", "/qoder", body, "")).Want(200).JSON(&view)
+ if view.MaxConcurrency != 5 || view.RunTimeoutMinutes != 90 {
+ t.Fatalf("limits not saved: %+v", view)
+ }
+ // Omitted limits keep the saved values rather than resetting to defaults.
+ delete(body, "max_concurrency")
+ delete(body, "run_timeout_minutes")
+ testutil.Call(t, testHandler.SaveQoderConnection, vcsHandlerRequest("PUT", "/qoder", body, "")).Want(200).JSON(&view)
+ if view.MaxConcurrency != 5 || view.RunTimeoutMinutes != 90 {
+ t.Fatalf("limits reset on save: %+v", view)
+ }
+ // A journal holding concurrent runs blocks configuration changes.
+ journal, err := testHandler.sealVCSSecret(`{"binding":"b","runs":[{"task_id":"t","phase":"prepared"}]}`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := testPool.Exec(context.Background(), `UPDATE cloud_agent_connection SET journal_encrypted=$2 WHERE provider='qoder_cloud' AND workspace_id=$1`, testWorkspaceID, journal); err != nil {
+ t.Fatal(err)
+ }
+ testutil.Call(t, testHandler.SaveQoderConnection, vcsHandlerRequest("PUT", "/qoder", body, "")).Want(409)
+}
+
+func TestQoderSaveKeepsPausedConnectionPaused(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ withVCSBox(t)
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM daemon_token WHERE id IN (SELECT token_id FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1)`, testWorkspaceID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1`, testWorkspaceID)
+ })
+ body := map[string]any{"name": "QCA", "base_url": qoderAPIURL, "environment_id": "env_test", "qoder_token": "fixture-token"}
+ var view qoderSettingsView
+ testutil.Call(t, testHandler.SaveQoderConnection, vcsHandlerRequest("PUT", "/qoder", body, "")).Want(200).JSON(&view)
+ if !view.Enabled {
+ t.Fatal("first connect must enable execution")
+ }
+ testutil.Call(t, testHandler.StopQoderConnection, vcsHandlerRequest("POST", "/qoder/stop", nil, "")).Want(200)
+
+ body["max_concurrency"] = 3
+ body["github_tokens"] = map[string]string{"https://github.com/owner/repo": "github-test-secret"}
+ testutil.Call(t, testHandler.SaveQoderConnection, vcsHandlerRequest("PUT", "/qoder", body, "")).Want(200).JSON(&view)
+ var status string
+ dbfx.QueryRow(t, `SELECT status FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1`, testWorkspaceID).Scan(&status)
+ if view.Enabled || status != "stopped" || view.MaxConcurrency != 3 {
+ t.Fatalf("saving a paused connection resumed it: enabled=%v status=%s view=%+v", view.Enabled, status, view)
+ }
+
+ testutil.Call(t, testHandler.ResumeQoderConnection, vcsHandlerRequest("POST", "/qoder/resume", body, "")).Want(200).JSON(&view)
+ dbfx.QueryRow(t, `SELECT status FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1`, testWorkspaceID).Scan(&status)
+ if !view.Enabled || status != "starting" {
+ t.Fatalf("resume did not enable execution: enabled=%v status=%s", view.Enabled, status)
+ }
+}
+
+func TestQoderManagedRegistrationAndRevocation(t *testing.T) {
+ withVCSBox(t)
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM daemon_token WHERE id IN (SELECT token_id FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1)`, testWorkspaceID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1`, testWorkspaceID)
+ })
+ input := map[string]any{"name": "QCA", "base_url": qoderAPIURL, "environment_id": "env_test", "qoder_token": "fixture-token"}
+ testutil.Call(t, testHandler.SaveQoderConnection, vcsHandlerRequest("PUT", "/qoder", input, "")).Want(200)
+ cfg, _, _, _, err := testHandler.readQoderSettings(context.Background(), testWorkspaceID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ daemonID := "qoder-managed-" + testWorkspaceID
+ req := newDaemonTokenRequest("POST", "/api/daemon/register", map[string]any{"workspace_id": testWorkspaceID, "daemon_id": daemonID, "runtimes": []map[string]any{{"name": "QCA", "type": "qoder_cloud", "runtime_mode": "cloud", "status": "online"}}}, testWorkspaceID, daemonID)
+ req.Header.Set("Authorization", "Bearer "+cfg.MulticaToken)
+ testutil.Call(t, testHandler.DaemonRegister, req).Want(200)
+ testutil.Call(t, testHandler.StopQoderConnection, vcsHandlerRequest("POST", "/qoder/stop", nil, "")).Want(200)
+ allowed, err := testHandler.qoderCredentialAllowed(req, testWorkspaceID, daemonID)
+ if err != nil || allowed {
+ t.Fatalf("stopped credential accepted: %v %v", allowed, err)
+ }
+}
+
+func TestQoderRetirementCancelsRemoteAndClearsPrompt(t *testing.T) {
+ withVCSBox(t)
+ ctx := context.Background()
+ cancelled := 0
+ remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == "POST" {
+ cancelled++
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"status":"idle"}`))
+ }))
+ defer remote.Close()
+ runtimeID := dbfx.Runtime(t, "retired QCA", testutil.Cols{"provider": "qoder_cloud", "runtime_mode": "cloud"})
+ agentID := dbfx.Agent(t, "retired agent", runtimeID)
+ taskID := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "status": "running"})
+ cfg, _ := json.Marshal(qoderSettings{BaseURL: remote.URL, QoderToken: "fixture-secret"})
+ encrypted, err := testHandler.sealVCSSecret(string(cfg))
+ if err != nil {
+ t.Fatal(err)
+ }
+ state, _ := json.Marshal(map[string]any{"run": map[string]any{"task_id": taskID, "session_id": "sess_fixture", "prompt": "private issue content"}})
+ journal, err := testHandler.sealVCSSecret(string(state))
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = testPool.Exec(ctx, `INSERT INTO cloud_agent_connection(workspace_id,provider,owner_id,token_id,config_encrypted,enabled,journal_encrypted) VALUES($1,'qoder_cloud',$2,$2,$3,false,$4)`, testWorkspaceID, testUserID, encrypted, journal)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(ctx, `DELETE FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1`, testWorkspaceID)
+ })
+ if err = testHandler.cleanupQoderJournal(ctx, testWorkspaceID); err != nil {
+ t.Fatal(err)
+ }
+ var remaining, status string
+ dbfx.QueryRow(t, `SELECT journal_encrypted FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1`, testWorkspaceID).Scan(&remaining)
+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id=$1`, taskID).Scan(&status)
+ if cancelled != 1 || remaining != "" || status != "failed" {
+ t.Fatalf("retirement: cancels=%d journal cleared=%v status=%s", cancelled, remaining == "", status)
+ }
+}
+
+func TestQoderStepLeaseReleasesDatabaseConnection(t *testing.T) {
+ withVCSBox(t)
+ ctx := context.Background()
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(ctx, `DELETE FROM daemon_token WHERE id IN (SELECT token_id FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1)`, testWorkspaceID)
+ _, _ = testPool.Exec(ctx, `DELETE FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1`, testWorkspaceID)
+ })
+ input := map[string]any{"name": "QCA", "base_url": qoderAPIURL, "environment_id": "env_test", "qoder_token": "fixture-token"}
+ testutil.Call(t, testHandler.SaveQoderConnection, vcsHandlerRequest("PUT", "/qoder", input, "")).Want(200)
+ var revision int64
+ dbfx.QueryRow(t, `SELECT revision FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1`, testWorkspaceID).Scan(&revision)
+ baseline := testPool.Stat().AcquiredConns()
+ release, err := testHandler.acquireQoderStep(ctx, testWorkspaceID, revision)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer release()
+ if testPool.Stat().AcquiredConns() != baseline {
+ t.Fatal("step retained a database connection")
+ }
+ testutil.Call(t, testHandler.StopQoderConnection, vcsHandlerRequest("POST", "/qoder/stop", nil, "")).Want(409)
+ release()
+ testutil.Call(t, testHandler.StopQoderConnection, vcsHandlerRequest("POST", "/qoder/stop", nil, "")).Want(200)
+}
+
+func TestQoderQuickCreateUnsupported(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ for _, metadata := range []string{`{}`, `{"cli_version":"99.0.0"}`} {
+ runtimeID := dbfx.Runtime(t, "Qoder issue-only runtime", testutil.Cols{"provider": "qoder_cloud", "runtime_mode": "cloud", "metadata": metadata})
+ status, payload := testHandler.checkQuickCreateDaemonVersion(context.Background(), "issue", parseUUID(runtimeID))
+ if status != http.StatusUnprocessableEntity || payload["code"] != "agent_unavailable" {
+ t.Fatalf("Qoder quick-create should be unavailable, got %d: %v", status, payload)
+ }
+ if !strings.Contains(payload["reason"].(string), "create the issue manually") {
+ t.Fatalf("missing actionable issue-only explanation: %v", payload)
+ }
+ }
+}
diff --git a/server/internal/handler/qoder_disconnect.go b/server/internal/handler/qoder_disconnect.go
new file mode 100644
index 0000000000..81c1a6f7cc
--- /dev/null
+++ b/server/internal/handler/qoder_disconnect.go
@@ -0,0 +1,240 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "log/slog"
+ "net/http"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/service"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// disconnectQoderRequest carries the active agents the admin was shown as
+// losing their runtime. A different live set refuses with the latest list.
+type disconnectQoderRequest struct {
+ ExpectedActiveAgentIDs []string `json:"expected_active_agent_ids"`
+}
+
+// DisconnectQoderConnection removes the workspace's Qoder connection for good:
+// the encrypted credentials and the managed runtime go, and agents on that
+// runtime are unbound (kept, with their history). Unlike stop, nothing is left
+// to resume from.
+//
+// The bridge is stopped first so no step or dispatch can start, then remote
+// sessions are cancelled while the credentials still exist, and only then is
+// the connection deleted. A refusal after the stop leaves the connection
+// stopped, which is where the admin was headed anyway.
+func (h *Handler) DisconnectQoderConnection(w http.ResponseWriter, r *http.Request) {
+ ws, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace_id")
+ if !ok {
+ return
+ }
+ user, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ var req disconnectQoderRequest
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)).Decode(&req); err != nil && !errors.Is(err, io.EOF) {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ expected, ok := parseExpectedActiveAgentIDs(req.ExpectedActiveAgentIDs)
+ if !ok {
+ writeError(w, http.StatusBadRequest, "expected_active_agent_ids must be a list of valid UUIDs")
+ return
+ }
+ wsID := uuidToString(ws)
+
+ if !h.stopQoderForDisconnect(w, r, ws, expected) {
+ return
+ }
+ if err := h.cleanupQoderJournal(r.Context(), wsID); err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ slog.Warn("qoder disconnect waiting on remote cleanup", "workspace_id", wsID, "error", err)
+ writeError(w, http.StatusConflict, "Qoder is stopped and still cancelling remote sessions; retry shortly")
+ return
+ }
+
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "cannot disconnect Qoder")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ if _, err = tx.Exec(r.Context(), `SELECT pg_advisory_xact_lock(hashtextextended($1,19))`, wsID); err != nil {
+ writeError(w, http.StatusInternalServerError, "cannot lock QCA configuration")
+ return
+ }
+ qtx := h.Queries.WithTx(tx)
+ runtimeIDs, refused := h.checkQoderDisconnectPlan(w, r.Context(), tx, qtx, ws, expected)
+ if refused {
+ return
+ }
+ teardowns := make([]service.RuntimeTeardownResult, 0, len(runtimeIDs))
+ for _, runtimeID := range runtimeIDs {
+ teardown, err := service.TeardownRuntime(r.Context(), qtx, runtimeID, service.RuntimeTeardownOptions{CancelNonTerminalTasks: true})
+ if err != nil {
+ if errors.Is(err, service.ErrRuntimeNotDrained) {
+ writeError(w, http.StatusConflict, "Qoder still has tasks in flight; retry in a moment")
+ return
+ }
+ slog.Error("qoder disconnect teardown failed", "runtime_id", uuidToString(runtimeID), "error", err)
+ writeError(w, http.StatusInternalServerError, "cannot disconnect Qoder")
+ return
+ }
+ if err := qtx.DeleteAgentRuntime(r.Context(), runtimeID); err != nil {
+ writeError(w, http.StatusInternalServerError, "cannot disconnect Qoder")
+ return
+ }
+ teardowns = append(teardowns, teardown)
+ }
+ tag, err := tx.Exec(r.Context(), `DELETE FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1 AND journal_encrypted=''`, ws)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "cannot disconnect Qoder")
+ return
+ }
+ if tag.RowsAffected() == 0 {
+ writeError(w, http.StatusConflict, "Qoder is stopped and still cancelling remote sessions; retry shortly")
+ return
+ }
+ if err := tx.Commit(r.Context()); err != nil {
+ writeError(w, http.StatusInternalServerError, "cannot disconnect Qoder")
+ return
+ }
+
+ userID := user
+ for i, runtimeID := range runtimeIDs {
+ h.NotifyRuntimeGone(uuidToString(runtimeID))
+ h.publishRuntimeTeardown(r.Context(), teardowns[i], wsID, userID)
+ }
+ slog.Info("qoder disconnected", "workspace_id", wsID, "disconnected_by", userID, "runtimes_removed", len(runtimeIDs))
+ h.GetQoderConnection(w, r)
+}
+
+// stopQoderForDisconnect disables the connection and revokes the bridge's
+// credential, after the same checks as stop plus the confirmed agent plan.
+// It reports whether the caller may continue; on false a response was written.
+func (h *Handler) stopQoderForDisconnect(w http.ResponseWriter, r *http.Request, ws pgtype.UUID, expected map[string]struct{}) bool {
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "cannot disconnect Qoder")
+ return false
+ }
+ defer tx.Rollback(r.Context())
+ if _, err = tx.Exec(r.Context(), `SELECT pg_advisory_xact_lock(hashtextextended($1,19))`, uuidToString(ws)); err != nil {
+ writeError(w, http.StatusInternalServerError, "cannot lock QCA configuration")
+ return false
+ }
+ var exists, busy bool
+ if err := tx.QueryRow(r.Context(), `SELECT true, COALESCE(busy_until>now(),false) FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1`, ws).Scan(&exists, &busy); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "Qoder is not connected")
+ return false
+ }
+ writeError(w, http.StatusInternalServerError, "cannot check QCA connection")
+ return false
+ }
+ if busy {
+ writeError(w, http.StatusConflict, "QCA is synchronizing; retry shortly")
+ return false
+ }
+ if _, refused := h.checkQoderDisconnectPlan(w, r.Context(), tx, h.Queries.WithTx(tx), ws, expected); refused {
+ return false
+ }
+ var revokedHash string
+ _ = tx.QueryRow(r.Context(), `SELECT d.token_hash FROM daemon_token d JOIN cloud_agent_connection c ON c.token_id=d.id AND c.provider='qoder_cloud' WHERE c.workspace_id=$1`, ws).Scan(&revokedHash)
+ if _, err = tx.Exec(r.Context(), `DELETE FROM daemon_token WHERE id IN (SELECT token_id FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1)`, ws); err != nil {
+ writeError(w, http.StatusInternalServerError, "cannot revoke runtime credential")
+ return false
+ }
+ if _, err = tx.Exec(r.Context(), `UPDATE cloud_agent_connection SET enabled=false,revision=revision+1,status='stopped',last_error='' WHERE provider='qoder_cloud' AND workspace_id=$1`, ws); err != nil {
+ writeError(w, http.StatusInternalServerError, "cannot stop QCA runtime")
+ return false
+ }
+ if err := tx.Commit(r.Context()); err != nil {
+ writeError(w, http.StatusInternalServerError, "cannot stop QCA runtime")
+ return false
+ }
+ if revokedHash != "" {
+ h.DaemonTokenCache.Invalidate(r.Context(), revokedHash)
+ }
+ return true
+}
+
+// checkQoderDisconnectPlan locks the workspace's Qoder runtimes and refuses
+// while tasks run on them or when their active agents differ from the
+// confirmed set. It returns the runtimes to remove.
+func (h *Handler) checkQoderDisconnectPlan(w http.ResponseWriter, ctx context.Context, tx pgx.Tx, qtx *db.Queries, ws pgtype.UUID, expected map[string]struct{}) ([]pgtype.UUID, bool) {
+ rows, err := tx.Query(ctx, `SELECT id FROM agent_runtime WHERE workspace_id=$1 AND provider='qoder_cloud' ORDER BY id FOR UPDATE`, ws)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "cannot load Qoder runtime")
+ return nil, true
+ }
+ runtimeIDs, err := pgx.CollectRows(rows, pgx.RowTo[pgtype.UUID])
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "cannot load Qoder runtime")
+ return nil, true
+ }
+ var active bool
+ if err := tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM agent_task_queue t JOIN agent_runtime rt ON rt.id=t.runtime_id WHERE rt.workspace_id=$1 AND rt.provider='qoder_cloud' AND t.status IN ('running','dispatched'))`, ws).Scan(&active); err != nil {
+ writeError(w, http.StatusInternalServerError, "cannot check active QCA tasks")
+ return nil, true
+ }
+ if active {
+ writeError(w, http.StatusConflict, "wait for or cancel active QCA tasks before disconnecting")
+ return nil, true
+ }
+ var agents []db.Agent
+ for _, runtimeID := range runtimeIDs {
+ bound, err := qtx.ListActiveAgentsByRuntimeForUpdate(ctx, runtimeID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "cannot check Qoder agents")
+ return nil, true
+ }
+ agents = append(agents, bound...)
+ }
+ if !activeAgentSetMatches(agents, expected) {
+ body := h.runtimeHasActiveAgentsResponse(agents)
+ body["code"] = "runtime_delete_plan_changed"
+ body["error"] = "the agents on Qoder changed; please review and confirm again."
+ writeJSON(w, http.StatusConflict, body)
+ return nil, true
+ }
+ return runtimeIDs, false
+}
+
+// qoderManagesRuntime reports whether a runtime belongs to a live Qoder
+// connection, whose lifecycle is owned by connect and disconnect rather than
+// the generic runtime endpoints.
+func (h *Handler) qoderManagesRuntime(ctx context.Context, rt db.AgentRuntime) (bool, error) {
+ if rt.Provider != "qoder_cloud" {
+ return false, nil
+ }
+ var managed bool
+ err := h.DB.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1)`, rt.WorkspaceID).Scan(&managed)
+ return managed, err
+}
+
+// refuseQoderManagedRuntime writes the refusal for generic runtime mutations
+// on a Qoder-managed runtime and reports whether it did.
+func (h *Handler) refuseQoderManagedRuntime(w http.ResponseWriter, ctx context.Context, rt db.AgentRuntime, message string) bool {
+ managed, err := h.qoderManagesRuntime(ctx, rt)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to check runtime connection")
+ return true
+ }
+ if !managed {
+ return false
+ }
+ writeJSON(w, http.StatusConflict, map[string]any{
+ "error": message,
+ "code": "runtime_managed_by_connection",
+ })
+ return true
+}
diff --git a/server/internal/handler/qoder_disconnect_test.go b/server/internal/handler/qoder_disconnect_test.go
new file mode 100644
index 0000000000..5742e80c8a
--- /dev/null
+++ b/server/internal/handler/qoder_disconnect_test.go
@@ -0,0 +1,52 @@
+package handler
+
+import (
+ "context"
+ "testing"
+
+ "github.com/go-chi/chi/v5"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func TestQoderDisconnectRemovesConnectionAndUnbindsAgents(t *testing.T) {
+ withVCSBox(t)
+ ctx := context.Background()
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(ctx, `DELETE FROM daemon_token WHERE id IN (SELECT token_id FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1)`, testWorkspaceID)
+ _, _ = testPool.Exec(ctx, `DELETE FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1`, testWorkspaceID)
+ })
+ input := map[string]any{"name": "QCA", "base_url": qoderAPIURL, "environment_id": "env_test", "qoder_token": "fixture-token"}
+ testutil.Call(t, testHandler.SaveQoderConnection, vcsHandlerRequest("PUT", "/qoder", input, "")).Want(200)
+ runtimeID := dbfx.Runtime(t, "QCA", testutil.Cols{"provider": "qoder_cloud", "runtime_mode": "cloud"})
+ agentID := dbfx.Agent(t, "QCA agent", runtimeID)
+
+ deleteReq := newRequest("DELETE", "/api/runtimes/"+runtimeID, nil)
+ rctx := chi.NewRouteContext()
+ rctx.URLParams.Add("runtimeId", runtimeID)
+ deleteReq = deleteReq.WithContext(context.WithValue(deleteReq.Context(), chi.RouteCtxKey, rctx))
+ var managed map[string]any
+ testutil.Call(t, testHandler.DeleteAgentRuntime, deleteReq).Want(409).JSON(&managed)
+ if managed["code"] != "runtime_managed_by_connection" {
+ t.Fatalf("generic delete of a Qoder runtime: %v", managed)
+ }
+
+ var changed map[string]any
+ testutil.Call(t, testHandler.DisconnectQoderConnection, vcsHandlerRequest("DELETE", "/qoder", map[string]any{"expected_active_agent_ids": []string{}}, "")).Want(409).JSON(&changed)
+ if changed["code"] != "runtime_delete_plan_changed" {
+ t.Fatalf("unconfirmed agents should refuse with the latest plan: %v", changed)
+ }
+
+ body := map[string]any{"expected_active_agent_ids": []string{agentID}}
+ testutil.Call(t, testHandler.DisconnectQoderConnection, vcsHandlerRequest("DELETE", "/qoder", body, "")).Want(200)
+
+ var connections, runtimes, agents int
+ var bound bool
+ dbfx.QueryRow(t, `SELECT count(*) FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1`, testWorkspaceID).Scan(&connections)
+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_runtime WHERE id=$1`, runtimeID).Scan(&runtimes)
+ dbfx.QueryRow(t, `SELECT count(*), bool_or(runtime_id IS NOT NULL) FROM agent WHERE id=$1`, agentID).Scan(&agents, &bound)
+ if connections != 0 || runtimes != 0 || agents != 1 || bound {
+ t.Fatalf("disconnect: connections=%d runtimes=%d agents=%d bound=%v", connections, runtimes, agents, bound)
+ }
+ testutil.Call(t, testHandler.DisconnectQoderConnection, vcsHandlerRequest("DELETE", "/qoder", body, "")).Want(404)
+}
diff --git a/server/internal/handler/qoder_issue_lifecycle_test.go b/server/internal/handler/qoder_issue_lifecycle_test.go
new file mode 100644
index 0000000000..eb6c9fde62
--- /dev/null
+++ b/server/internal/handler/qoder_issue_lifecycle_test.go
@@ -0,0 +1,106 @@
+package handler
+
+import (
+ "context"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func TestQoderIssueLifecycle(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ for _, scenario := range []string{"success", "claim replay", "edit", "status roundtrip", "reassign", "newer task", "already reviewing", "custom status", "local runtime", "failed", "cancelled"} {
+ t.Run(scenario, func(t *testing.T) {
+ provider := "qoder_cloud"
+ initial := "todo"
+ if scenario == "local runtime" {
+ provider = "claude"
+ }
+ if scenario == "already reviewing" {
+ initial = "in_review"
+ }
+ if scenario == "custom status" {
+ initial = createTestCustomStatus(t, "qoder_custom_active", "started").Key
+ }
+ runtimeID := dbfx.Runtime(t, "lifecycle runtime", testutil.Cols{"provider": provider})
+ agentID := dbfx.Agent(t, "lifecycle agent", runtimeID)
+ issueID := dbfx.Issue(t, "Qoder lifecycle", testutil.Cols{"status": initial, "assignee_type": "agent", "assignee_id": agentID})
+ taskID := dbfx.Task(t, agentID, testutil.Cols{"issue_id": issueID, "runtime_id": runtimeID, "status": "dispatched", "dispatched_at": time.Now().UTC()})
+ if scenario == "claim replay" {
+ task, err := testHandler.Queries.GetAgentTask(ctx, parseUUID(taskID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for range 2 {
+ if _, err := testHandler.TaskService.StartTaskForClaim(ctx, db.LockAgentTaskStartClaimParams{ID: task.ID, RuntimeID: task.RuntimeID, DispatchedAt: task.DispatchedAt}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ } else if _, err := testHandler.TaskService.StartTask(ctx, parseUUID(taskID)); err != nil {
+ t.Fatal(err)
+ }
+ issue, err := testHandler.Queries.GetIssue(ctx, parseUUID(issueID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := "in_progress"
+ if scenario == "local runtime" || scenario == "already reviewing" || scenario == "custom status" {
+ want = initial
+ }
+ if issue.Status != want {
+ t.Fatalf("start status = %s, want %s", issue.Status, want)
+ }
+ switch scenario {
+ case "edit":
+ dbfx.Exec(t, `UPDATE issue SET title='Human edit', revision=revision+1 WHERE id=$1`, issueID)
+ case "status roundtrip":
+ dbfx.Exec(t, `UPDATE issue SET status='blocked', revision=revision+1 WHERE id=$1`, issueID)
+ dbfx.Exec(t, `UPDATE issue SET status='in_progress', revision=revision+1 WHERE id=$1`, issueID)
+ case "reassign":
+ dbfx.Exec(t, `UPDATE issue SET assignee_type='member', assignee_id=$2, revision=revision+1 WHERE id=$1`, issueID, testUserID)
+ case "newer task":
+ dbfx.Task(t, agentID, testutil.Cols{"issue_id": issueID, "runtime_id": runtimeID})
+ case "failed":
+ if _, err := testHandler.TaskService.FailTask(ctx, parseUUID(taskID), "Qoder failed", "", "", "", "qoder_cloud_execution", false, "", ""); err != nil {
+ t.Fatal(err)
+ }
+ case "cancelled":
+ if _, err := testHandler.TaskService.CancelTask(ctx, parseUUID(taskID)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for range 2 {
+ if _, _, err := testHandler.TaskService.CompleteTaskWithTransition(ctx, parseUUID(taskID), []byte(`{"output":"Ready for review"}`), "", "", "", false, "", ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ issue, err = testHandler.Queries.GetIssue(ctx, parseUUID(issueID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if scenario == "success" || scenario == "claim replay" {
+ want = "in_review"
+ }
+ if issue.Status != want {
+ t.Fatalf("completion status = %s, want %s", issue.Status, want)
+ }
+ var changes int
+ dbfx.QueryRow(t, `SELECT count(*) FROM activity_log WHERE issue_id=$1 AND action='status_changed' AND details->>'source'='qoder_cloud'`, issueID).Scan(&changes)
+ expected := 1
+ if scenario == "success" || scenario == "claim replay" {
+ expected = 2
+ }
+ if scenario == "local runtime" || scenario == "already reviewing" || scenario == "custom status" {
+ expected = 0
+ }
+ if changes != expected {
+ t.Fatalf("activity count = %d, want %d", changes, expected)
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.go
index 02524cc24d..7bcb9a3b81 100644
--- a/server/internal/handler/runtime.go
+++ b/server/internal/handler/runtime.go
@@ -536,6 +536,9 @@ func (h *Handler) UpdateAgentRuntime(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusForbidden, "only the runtime owner can change its visibility")
return
}
+ if h.refuseQoderManagedRuntime(w, r.Context(), rt, "the Qoder runtime is always shared with the workspace") {
+ return
+ }
newVisibility = v
needVisibility = true
}
@@ -1337,6 +1340,9 @@ func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusForbidden, "you can only delete your own runtimes")
return
}
+ if h.refuseQoderManagedRuntime(w, r.Context(), rt, "disconnect Qoder to remove its runtime") {
+ return
+ }
userID := uuidToString(member.UserID)
profile, hasLiveProfile, err := h.runtimeLiveProfile(r.Context(), rt)
@@ -1555,6 +1561,9 @@ func (h *Handler) UnbindAgentsAndDeleteRuntime(w http.ResponseWriter, r *http.Re
writeError(w, http.StatusForbidden, "you can only delete your own runtimes")
return
}
+ if h.refuseQoderManagedRuntime(w, r.Context(), rt, "disconnect Qoder to remove its runtime") {
+ return
+ }
userID := uuidToString(member.UserID)
profile, hasLiveProfile, err := h.runtimeLiveProfile(r.Context(), rt)
diff --git a/server/internal/handler/skill.go b/server/internal/handler/skill.go
index 36c2b040f4..63360b5d8b 100644
--- a/server/internal/handler/skill.go
+++ b/server/internal/handler/skill.go
@@ -2640,6 +2640,9 @@ func (h *Handler) SetAgentSkills(w http.ResponseWriter, r *http.Request) {
if !h.validateAgentSkillIDsInWorkspace(w, r, agent, skillUUIDs) {
return
}
+ if len(skillUUIDs) > 0 && h.rejectQoderOverrides(w, r, agent, qoderOverrides{skills: len(skillUUIDs)}) {
+ return
+ }
tx, err := h.TxStarter.Begin(r.Context())
if err != nil {
@@ -2696,6 +2699,9 @@ func (h *Handler) AddAgentSkills(w http.ResponseWriter, r *http.Request) {
if !h.validateAgentSkillIDsInWorkspace(w, r, agent, skillUUIDs) {
return
}
+ if len(skillUUIDs) > 0 && h.rejectQoderOverrides(w, r, agent, qoderOverrides{skills: len(skillUUIDs)}) {
+ return
+ }
tx, err := h.TxStarter.Begin(r.Context())
if err != nil {
diff --git a/server/internal/handler/task_message_batch_test.go b/server/internal/handler/task_message_batch_test.go
index 9f09bc8aea..32aced2fc7 100644
--- a/server/internal/handler/task_message_batch_test.go
+++ b/server/internal/handler/task_message_batch_test.go
@@ -4,6 +4,7 @@ import (
"context"
"net/http"
"slices"
+ "strings"
"sync"
"testing"
"time"
@@ -251,7 +252,7 @@ func TestCreateTaskMessagesBatchIsAtomic(t *testing.T) {
ctx := context.Background()
taskID := seedBatchTask(t, "batch-atomic")
- // The colliding row is built as a fixture, not through the query under
+ // The existing row is built as a fixture, not through the query under
// test: test setup that shares code with the code being exercised can pass
// for the wrong reason.
const dupID = "018f0000-0000-7000-8000-000000000001"
@@ -265,18 +266,18 @@ func TestCreateTaskMessagesBatchIsAtomic(t *testing.T) {
_, err := testHandler.Queries.CreateTaskMessages(ctx, db.CreateTaskMessagesParams{
TaskID: util.MustParseUUID(taskID),
- Ids: []pgtype.UUID{util.MustParseUUID("018f0000-0000-7000-8000-000000000002"), util.MustParseUUID(dupID)},
+ Ids: []pgtype.UUID{util.MustParseUUID("018f0000-0000-7000-8000-000000000002"), util.MustParseUUID("018f0000-0000-7000-8000-000000000003")},
Seqs: []int32{2, 3},
Types: []string{"text", "text"},
Tools: []string{"", ""},
- Contents: []string{"ok", "collides"},
- Inputs: []string{"", ""},
+ Contents: []string{"ok", "invalid input"},
+ Inputs: []string{"", "not-json"},
Outputs: []string{"", ""},
CreatedAts: []string{"", ""},
OutputTruncations: []string{"", ""},
})
if err == nil {
- t.Fatal("CreateTaskMessages accepted a batch with a duplicate primary key")
+ t.Fatal("CreateTaskMessages accepted a batch with invalid JSON input")
}
count := dbfx.Count(t, `SELECT COUNT(*) FROM task_message WHERE task_id = $1`, taskID)
@@ -342,3 +343,65 @@ func TestTaskMessageCreatedAtsFallsBackWholeBatch(t *testing.T) {
t.Fatalf("taskMessageCreatedAts() = %q, want %q", got, want)
}
}
+
+func TestReportTaskMessagesIdempotencyIsTaskScoped(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ first := seedBatchTask(t, "idempotent-first")
+ second := seedBatchTask(t, "idempotent-second")
+ sharedBus := testHandler.Bus
+ testHandler.Bus = events.New()
+ t.Cleanup(func() { testHandler.Bus = sharedBus })
+ var mu sync.Mutex
+ published := 0
+ testHandler.Bus.Subscribe(protocol.EventTaskMessage, func(e events.Event) {
+ if e.TaskID == first || e.TaskID == second {
+ mu.Lock()
+ published++
+ mu.Unlock()
+ }
+ })
+ eventTime := time.Now().UTC().Truncate(time.Microsecond)
+ message := map[string]any{"seq": 1, "type": "text", "content": "original", "idempotency_key": "qoder:evt_1", "call_id": "call_original", "created_at": eventTime, "output_truncated": true}
+ for _, taskID := range []string{first, first, second} {
+ testutil.Call(t, testHandler.ReportTaskMessages, batchMessagesRequest(t, taskID, []any{message})).Want(http.StatusOK)
+ }
+ // Replaying the key with a changed payload must not overwrite the first report.
+ message["content"] = "changed"
+ message["call_id"] = "call_changed"
+ message["created_at"] = eventTime.Add(time.Second)
+ message["output_truncated"] = false
+ testutil.Call(t, testHandler.ReportTaskMessages, batchMessagesRequest(t, first, []any{message})).Want(http.StatusOK)
+ for _, taskID := range []string{first, second} {
+ rows, err := testHandler.Queries.ListTaskMessages(context.Background(), util.MustParseUUID(taskID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(rows) != 1 || rows[0].Content.String != "original" {
+ t.Fatalf("task %s replay changed persisted messages: %+v", taskID, rows)
+ }
+ if rows[0].CallID.String != "call_original" || !rows[0].CreatedAt.Time.Equal(eventTime) || !rows[0].OutputTruncated.Valid || !rows[0].OutputTruncated.Bool {
+ t.Fatalf("task %s replay changed event metadata: %+v", taskID, rows[0])
+ }
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if published != 2 {
+ t.Fatalf("published %d events, want one per task", published)
+ }
+}
+
+func TestReportTaskMessagesRejectsOversizedIdempotencyKeyAtomically(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ taskID := seedBatchTask(t, "idempotency-key-limit")
+ testutil.Call(t, testHandler.ReportTaskMessages, batchMessagesRequest(t, taskID, []any{
+ map[string]any{"seq": 1, "type": "text", "content": "valid"},
+ map[string]any{"seq": 2, "type": "text", "idempotency_key": strings.Repeat("x", 513)},
+ })).Want(http.StatusBadRequest)
+ if n := dbfx.Count(t, `SELECT COUNT(*) FROM task_message WHERE task_id=$1`, taskID); n != 0 {
+ t.Fatalf("persisted %d rows before validation failed", n)
+ }
+}
diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.go
index 232c2fa338..ff5db1cdf8 100644
--- a/server/internal/handler/workspace.go
+++ b/server/internal/handler/workspace.go
@@ -1088,6 +1088,13 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {
return
}
+ // Stop remote work before deleting the only durable session journal.
+ // A pending step/cancellation leaves the workspace intact for a safe retry.
+ if err := h.prepareQoderWorkspaceDeletion(r.Context(), uuidToString(requester.WorkspaceID)); err != nil {
+ writeError(w, http.StatusConflict, "Qoder cleanup is pending; retry workspace deletion shortly")
+ return
+ }
+
// Invalidate membership cache for all workspace members before deletion.
// After CASCADE deletes the member rows, cache entries become harmless
// orphans (downstream lookups for the deleted workspace will fail), but
@@ -1228,6 +1235,16 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {
name: "delete tasks",
run: func() error { return deleteWorkspaceTasks(ctx, qtx, requester.WorkspaceID) },
},
+ {
+ name: "delete QCA connection",
+ run: func() error {
+ if _, err := tx.Exec(ctx, `DELETE FROM daemon_token WHERE id IN (SELECT token_id FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1)`, requester.WorkspaceID); err != nil {
+ return err
+ }
+ _, err := tx.Exec(ctx, `DELETE FROM cloud_agent_connection WHERE provider='qoder_cloud' AND workspace_id=$1`, requester.WorkspaceID)
+ return err
+ },
+ },
{
name: "delete leaf data",
run: func() error { return qtx.DeleteWorkspaceLeafData(ctx, requester.WorkspaceID) },
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index 357a68902d..53f8c28dbd 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -19,6 +19,7 @@ const (
// teardown. Adding a table requires an explicit ownership decision here; the
// handler deletion graph must then implement that decision before CI passes.
var workspaceDeletionManifest = map[string]workspaceDeleteAction{
+ "cloud_agent_connection": workspaceDelete,
"activity_log": workspaceDelete,
"agent": workspaceDelete,
"agent_builder_draft": workspaceDelete,
diff --git a/server/internal/qoderruntime/bridge.go b/server/internal/qoderruntime/bridge.go
new file mode 100644
index 0000000000..54add304c8
--- /dev/null
+++ b/server/internal/qoderruntime/bridge.go
@@ -0,0 +1,691 @@
+package qoderruntime
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+const Provider = "qoder_cloud"
+
+type Config struct {
+ DaemonID string `json:"daemon_id,omitempty"`
+ LoadState func(context.Context) ([]byte, error) `json:"-"`
+ SaveState func(context.Context, []byte) error `json:"-"`
+ BeforeStep func(context.Context) (func(), error) `json:"-"`
+ OnReady func(context.Context, string) error `json:"-"`
+ GitHubTokens map[string]string `json:"-"`
+ GitHubTokenFiles map[string]string `json:"github_token_files,omitempty"`
+ MulticaURL string `json:"multica_url"`
+ MulticaToken string `json:"multica_token"`
+ WorkspaceID string `json:"workspace_id"`
+ QoderURL string `json:"qoder_url"`
+ QoderToken string `json:"qoder_token"`
+ EnvironmentID string `json:"environment_id"`
+ StateDir string `json:"state_dir"`
+ Name string `json:"name,omitempty"`
+ RunTimeout time.Duration `json:"-"`
+ SubmissionTimeout time.Duration `json:"-"`
+ PollInterval time.Duration `json:"-"`
+ // MaxConcurrency bounds simultaneous remote sessions; extra tasks stay queued in Multica.
+ MaxConcurrency int `json:"max_concurrency,omitempty"`
+}
+
+// MaxConcurrencyLimit caps how many sessions one connection may run at once.
+const MaxConcurrencyLimit = 10
+
+type Bridge struct {
+ cfg Config
+ multica, qoder *api
+ state *journal
+ path string
+ log *slog.Logger
+ turn int
+}
+
+func New(cfg Config, log *slog.Logger) (*Bridge, error) {
+ workspace, err := uuid.Parse(cfg.WorkspaceID)
+ if err != nil {
+ return nil, fmt.Errorf("workspace ID must be a UUID")
+ }
+ cfg.WorkspaceID = workspace.String()
+ if cfg.EnvironmentID == "" {
+ return nil, fmt.Errorf("environment ID is required")
+ }
+ if (cfg.LoadState == nil) != (cfg.SaveState == nil) {
+ return nil, fmt.Errorf("journal load and save must be configured together")
+ }
+ if cfg.LoadState == nil && cfg.StateDir == "" {
+ return nil, fmt.Errorf("state directory is required when the journal is stored on disk")
+ }
+ if cfg.PollInterval == 0 {
+ cfg.PollInterval = 3 * time.Second
+ }
+ if cfg.PollInterval < time.Millisecond {
+ return nil, fmt.Errorf("poll interval must be positive")
+ }
+ if cfg.RunTimeout == 0 {
+ cfg.RunTimeout = time.Hour
+ }
+ if cfg.SubmissionTimeout == 0 {
+ cfg.SubmissionTimeout = 2 * time.Minute
+ }
+ if cfg.RunTimeout < time.Second || cfg.SubmissionTimeout < time.Second {
+ return nil, fmt.Errorf("timeouts must be positive")
+ }
+ if cfg.MaxConcurrency == 0 {
+ cfg.MaxConcurrency = 1
+ }
+ if cfg.MaxConcurrency < 1 || cfg.MaxConcurrency > MaxConcurrencyLimit {
+ return nil, fmt.Errorf("max concurrency must be between 1 and %d", MaxConcurrencyLimit)
+ }
+ if cfg.Name == "" {
+ cfg.Name = "Qoder Cloud Agent"
+ }
+ m, err := newAPI(cfg.MulticaURL, cfg.MulticaToken, cfg.WorkspaceID)
+ if err != nil {
+ return nil, fmt.Errorf("Multica: %w", err)
+ }
+ q, err := newAPI(cfg.QoderURL, cfg.QoderToken, "")
+ if err != nil {
+ return nil, fmt.Errorf("Qoder: %w", err)
+ }
+ if log == nil {
+ log = slog.Default()
+ }
+ return &Bridge{cfg: cfg, multica: m, qoder: q, path: filepath.Join(cfg.StateDir, "state.json"), log: log}, nil
+}
+
+// Run is single-instance per journal and processes up to MaxConcurrency runs.
+// Restart resumes the journal instead of declaring remote work orphaned. An
+// on-disk journal is guarded by a file lock; an external journal's owner
+// (the server's Qoder supervisor) must guarantee a single bridge itself.
+func (b *Bridge) Run(ctx context.Context) error {
+ var err error
+ if b.cfg.LoadState == nil {
+ if err = os.MkdirAll(b.cfg.StateDir, 0700); err != nil {
+ return err
+ }
+ lock, err := lockState(filepath.Join(b.cfg.StateDir, "bridge.lock"))
+ if err != nil {
+ return err
+ }
+ defer lock.Close()
+ }
+ binding := Binding(b.multica.base, b.cfg.WorkspaceID, b.qoder.base, b.cfg.EnvironmentID)
+ if b.cfg.SaveState != nil {
+ binding = Binding("", b.cfg.WorkspaceID, b.qoder.base, b.cfg.EnvironmentID)
+ }
+ if b.cfg.LoadState != nil {
+ var raw []byte
+ raw, err = b.cfg.LoadState(ctx)
+ if err == nil {
+ b.state, err = decodeJournal(raw, binding)
+ }
+ } else {
+ b.state, err = readJournal(b.path, binding)
+ }
+ if err != nil {
+ return err
+ }
+ // Validate remote access before accepting work. Existing runs still reconcile
+ // even if the live agent/environment was removed after the session snapshot.
+ if len(b.state.Runs) == 0 {
+ if err := b.Check(ctx); err != nil {
+ return err
+ }
+ }
+
+ // A stable daemon identity reconnects to the same runtime registration.
+ if err = b.register(ctx, binding); err != nil {
+ return err
+ }
+ if err = b.persist(); err != nil {
+ return err
+ }
+ b.log.InfoContext(ctx, "Qoder runtime registered", "runtime_id", b.state.RuntimeID)
+ if b.cfg.OnReady != nil {
+ if err := b.cfg.OnReady(ctx, b.state.RuntimeID); err != nil {
+ return err
+ }
+ }
+ ticker := time.NewTicker(b.cfg.PollInterval)
+ defer ticker.Stop()
+ for {
+ if err := ctx.Err(); err != nil {
+ return nil
+ }
+ b.cleanup(ctx)
+ // Heartbeats run even while event delivery or submission reconciliation is failing.
+ if err := b.multica.call(ctx, http.MethodPost, "/api/daemon/heartbeat", map[string]any{"runtime_id": b.state.RuntimeID}, nil); err != nil {
+ b.log.WarnContext(ctx, "runtime heartbeat failed", "error", err)
+ var denied *apiError
+ if errors.As(err, &denied) && (denied.Status == 401 || denied.Status == 403 || denied.Status == 404) {
+ if cancelErr := b.cancelActive(ctx); cancelErr != nil {
+ b.log.WarnContext(ctx, "waiting to stop remote work after runtime access was lost", "error", cancelErr)
+ select {
+ case <-ctx.Done():
+ return nil
+ case <-ticker.C:
+ continue
+ }
+ }
+ return fmt.Errorf("runtime access lost: %w", err)
+ }
+ } else if err := b.guardedStep(ctx); err != nil {
+ if errors.Is(err, context.Canceled) {
+ return nil
+ }
+ var diskErr *persistenceError
+ if errors.As(err, &diskErr) {
+ return err
+ }
+ b.log.WarnContext(ctx, "Qoder bridge will retry reconciliation", "error", err)
+ }
+ select {
+ case <-ctx.Done():
+ return nil
+ case <-ticker.C:
+ }
+ }
+}
+func (b *Bridge) register(ctx context.Context, binding string) error {
+ daemonID := b.cfg.DaemonID
+ if daemonID == "" {
+ daemonID = "qoder-cloud-" + binding[:24]
+ }
+ var response struct {
+ Runtimes []struct {
+ ID string `json:"id"`
+ Provider string `json:"provider"`
+ } `json:"runtimes"`
+ }
+ err := b.multica.call(ctx, http.MethodPost, "/api/daemon/register", map[string]any{
+ "workspace_id": b.cfg.WorkspaceID, "daemon_id": daemonID, "device_name": b.cfg.Name,
+ "runtimes": []map[string]string{{"name": b.cfg.Name, "type": Provider, "status": "online", "runtime_mode": "cloud"}},
+ }, &response)
+ if err != nil {
+ return err
+ }
+ if len(response.Runtimes) != 1 || response.Runtimes[0].ID == "" || response.Runtimes[0].Provider != Provider {
+ return fmt.Errorf("invalid runtime registration response")
+ }
+ if len(b.state.Runs) > 0 && b.state.RuntimeID != "" && b.state.RuntimeID != response.Runtimes[0].ID {
+ return fmt.Errorf("active journal belongs to a deleted runtime; reconcile its remote session before restarting")
+ }
+ b.state.RuntimeID = response.Runtimes[0].ID
+ return nil
+}
+func (b *Bridge) taskCall(ctx context.Context, r *run, suffix string, body, out any) error {
+ return b.multica.call(ctx, http.MethodPost, "/api/daemon/tasks/"+url.PathEscape(r.TaskID)+suffix, body, out)
+}
+
+// step advances every active run, then claims new work while capacity remains.
+// One failing run must not stall the others, so errors are collected and the
+// first is returned after all runs had their turn. Rotating the starting run
+// keeps a slow provider call from starving the same run on every tick.
+func (b *Bridge) step(ctx context.Context) error {
+ var firstErr error
+ keep := func(r *run, err error) error {
+ var diskErr *persistenceError
+ if errors.As(err, &diskErr) {
+ return err
+ }
+ if firstErr == nil {
+ firstErr = fmt.Errorf("run %s: %w", r.TaskID, err)
+ }
+ return nil
+ }
+ runs := append([]*run(nil), b.state.Runs...)
+ for i := range runs {
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ r := runs[(b.turn+i)%len(runs)]
+ if err := b.stepRun(ctx, r); err != nil {
+ if err := keep(r, err); err != nil {
+ return err
+ }
+ }
+ }
+ b.turn++
+ for len(b.state.Runs) < b.cfg.MaxConcurrency && ctx.Err() == nil {
+ r, err := b.claim(ctx)
+ if err != nil {
+ if firstErr == nil {
+ firstErr = err
+ }
+ break
+ }
+ if r == nil {
+ break
+ }
+ if err := b.stepRun(ctx, r); err != nil {
+ if err := keep(r, err); err != nil {
+ return err
+ }
+ }
+ }
+ return firstErr
+}
+
+func (b *Bridge) claim(ctx context.Context) (*run, error) {
+ var response struct {
+ Task *claimedTask `json:"task"`
+ }
+ if err := b.multica.call(ctx, http.MethodPost, "/api/daemon/runtimes/"+url.PathEscape(b.state.RuntimeID)+"/tasks/claim", map[string]any{}, &response); err != nil {
+ return nil, err
+ }
+ if response.Task == nil {
+ return nil, nil
+ }
+ r, err := b.prepare(ctx, response.Task)
+ if err != nil {
+ r = &run{TaskID: response.Task.ID, Phase: "final", Outcome: "failed", Failure: err.Error()}
+ }
+ r.Deadline = time.Now().Add(b.cfg.RunTimeout)
+ b.state.Runs = append(b.state.Runs, r)
+ if err := b.persist(); err != nil {
+ return nil, err
+ }
+ return r, nil
+}
+
+func (b *Bridge) stepRun(ctx context.Context, r *run) error {
+ if r.Phase != "final" {
+ if r.Deadline.IsZero() {
+ r.Deadline = time.Now().Add(b.cfg.RunTimeout)
+ if err := b.persist(); err != nil {
+ return err
+ }
+ }
+ if time.Now().After(r.Deadline) || (!r.SubmissionDeadline.IsZero() && !r.Started && time.Now().After(r.SubmissionDeadline)) {
+ // Persist compensating cancellation separately; a provider outage must
+ // not block the next task or discard the remote session identity.
+ if r.SessionID != "" {
+ b.queueCleanup(r.SessionID)
+ if err := b.persist(); err != nil {
+ return err
+ }
+ b.cleanup(ctx)
+ }
+ return b.reject(ctx, r, "Qoder execution deadline exceeded")
+ }
+ }
+ var status struct {
+ Status string `json:"status"`
+ }
+ err := b.multica.call(ctx, http.MethodGet, "/api/daemon/tasks/"+url.PathEscape(r.TaskID)+"/status", nil, &status)
+ var remoteErr *apiError
+ if err != nil && !(errors.As(err, &remoteErr) && remoteErr.Status == 404) {
+ return err
+ }
+ if err != nil || status.Status == "cancelled" || status.Status == "failed" || status.Status == "completed" {
+ // Do not leave remote work running after deletion, cancellation or server-side timeout.
+ if r.SessionID != "" && r.Phase != "final" {
+ b.queueCleanup(r.SessionID)
+ if err := b.persist(); err != nil {
+ return err
+ }
+ b.cleanup(ctx)
+ }
+ if status.Status == "cancelled" {
+ if err := b.taskCall(ctx, r, "/cancel-ack", map[string]any{}, nil); err != nil {
+ return err
+ }
+ }
+ b.state.remove(r)
+ return b.persist()
+ }
+ if r.Phase == "final" {
+ return b.deliver(ctx, r)
+ }
+ if time.Now().Before(r.RetryAt) {
+ return nil
+ }
+ if r.Phase == "creating" {
+ // The provider may have created a session before the response was lost.
+ // Never create a second session automatically for the same run.
+ return b.reject(ctx, r, "Qoder session creation was not confirmed; inspect remote sessions before retrying")
+ }
+ if status.Status == "dispatched" {
+ if err := b.taskCall(ctx, r, "/start", map[string]any{}, nil); err != nil {
+ return err
+ }
+ } else if status.Status != "running" {
+ return fmt.Errorf("unexpected Multica run status %q", status.Status)
+ }
+ if r.Phase == "prepared" {
+ // Resolve credentials before reusing a session too, so a revoked or
+ // changed repository credential is never carried into a follow-up.
+ resources, err := b.sessionResources(r.Resources)
+ if err != nil {
+ return b.reject(ctx, r, err.Error())
+ }
+ fingerprint := resourceFingerprint(resources)
+ if r.PriorSessionID != "" {
+ continued, err := b.continueSession(ctx, r, fingerprint)
+ if err != nil {
+ return err
+ }
+ if continued {
+ r.SessionID = r.PriorSessionID
+ r.Continued = true
+ r.Phase = "created"
+ if err := b.persist(); err != nil {
+ return err
+ }
+ }
+ }
+ if r.Phase == "prepared" {
+ if err := b.createSession(ctx, r, resources, fingerprint); err != nil || r.Phase != "created" {
+ return err
+ }
+ }
+ }
+ if err := b.taskCall(ctx, r, "/session", map[string]string{"session_id": r.SessionID}, nil); err != nil {
+ return err
+ }
+ if r.Phase == "created" {
+ // Save intent before POST. After an ambiguous response/restart, never resend automatically.
+ r.Phase = "sending"
+ r.SubmissionDeadline = time.Now().Add(b.cfg.SubmissionTimeout)
+ if err := b.persist(); err != nil {
+ return err
+ }
+ if err := b.qoder.call(ctx, http.MethodPost, "/sessions/"+url.PathEscape(r.SessionID)+"/events", map[string]any{"events": []map[string]any{{"type": "user.message", "content": []map[string]string{{"type": "text", "text": r.Prompt}}}}}, nil); err != nil {
+ if rateLimited(err) {
+ r.Phase = "created"
+ r.SubmissionDeadline = time.Time{}
+ r.RetryAt = time.Now().Add(30 * time.Second)
+ return b.persist()
+ }
+ if definitelyRejected(err) && r.Continued {
+ // The earlier session can no longer take messages; a definite
+ // rejection means nothing was delivered, so start a fresh session.
+ r.SessionID, r.PriorSessionID, r.Continued = "", "", false
+ r.Phase = "prepared"
+ r.SubmissionDeadline = time.Time{}
+ return b.persist()
+ }
+ if definitelyRejected(err) {
+ return b.reject(ctx, r, "Qoder rejected the task message: "+err.Error())
+ }
+ return err
+ }
+ r.Phase = "running"
+ if err := b.persist(); err != nil {
+ return err
+ }
+ }
+ return b.events(ctx, r)
+}
+
+// createSession moves the run to "created" on success. A rate-limited request
+// leaves it "prepared" for a later retry; a definite refusal finalizes it.
+func (b *Bridge) createSession(ctx context.Context, r *run, resources []map[string]any, fingerprint string) error {
+ var session struct {
+ ID string `json:"id"`
+ }
+ r.Phase = "creating"
+ if err := b.persist(); err != nil {
+ return err
+ }
+ metadata := map[string]string{"multica_task_id": r.TaskID, "multica_workspace_id": b.cfg.WorkspaceID, resourcesMetadataKey: fingerprint}
+ if err := b.qoder.call(ctx, http.MethodPost, "/sessions", map[string]any{"agent": r.AgentID, "environment_id": b.cfg.EnvironmentID, "title": "Multica run " + r.TaskID, "metadata": metadata, "resources": resources}, &session); err != nil {
+ if rateLimited(err) {
+ r.Phase = "prepared"
+ r.RetryAt = time.Now().Add(30 * time.Second)
+ return b.persist()
+ }
+ if definitelyRejected(err) {
+ return b.reject(ctx, r, "Qoder rejected session creation: "+err.Error())
+ }
+ return err
+ }
+ if session.ID == "" {
+ return fmt.Errorf("Qoder create returned no session ID")
+ }
+ r.SessionID = session.ID
+ r.Phase = "created"
+ return b.persist()
+}
+
+// resourcesMetadataKey stores resourceFingerprint on each session Multica creates.
+const resourcesMetadataKey = "multica_resources"
+
+// resourceFingerprint identifies the repositories, branches and credentials a
+// session was created with. Only this digest leaves the bridge.
+func resourceFingerprint(resources []map[string]any) string {
+ h := sha256.New()
+ h.Write([]byte("multica-qoder-resources-v1\n"))
+ for _, res := range resources {
+ raw, _ := res["url"].(string)
+ key, _ := repositoryKey(raw)
+ token, _ := res["authorization_token"].(string)
+ fmt.Fprintf(h, "%s\x00%s\x00%s\n", key, checkoutBranch(res["checkout"]), token)
+ }
+ return hex.EncodeToString(h.Sum(nil))
+}
+
+// checkoutBranch reads the branch from a freshly built resource
+// (map[string]string) or one restored from the journal (map[string]any).
+func checkoutBranch(checkout any) string {
+ raw, err := json.Marshal(checkout)
+ if err != nil {
+ return ""
+ }
+ var c struct {
+ Name string `json:"name"`
+ }
+ _ = json.Unmarshal(raw, &c)
+ return c.Name
+}
+
+// continueSession reports whether the agent's previous session on this issue
+// can take the follow-up. Only an idle session that no other active run is
+// using, created with the same repositories, branches and credentials,
+// qualifies; anything else (including sessions without a fingerprint) falls
+// back to a new session.
+func (b *Bridge) continueSession(ctx context.Context, r *run, fingerprint string) (bool, error) {
+ for _, other := range b.state.Runs {
+ if other != r && other.SessionID == r.PriorSessionID {
+ return false, nil
+ }
+ }
+ var s struct {
+ Status string `json:"status"`
+ Agent json.RawMessage `json:"agent"`
+ EnvironmentID string `json:"environment_id"`
+ Metadata map[string]string `json:"metadata"`
+ }
+ if err := b.qoder.call(ctx, http.MethodGet, "/sessions/"+url.PathEscape(r.PriorSessionID), nil, &s); err != nil {
+ if definitelyRejected(err) {
+ return false, nil
+ }
+ return false, err
+ }
+ if s.Status != "idle" {
+ return false, nil
+ }
+ if id := sessionAgentID(s.Agent); (id != "" && id != r.AgentID) || (s.EnvironmentID != "" && s.EnvironmentID != b.cfg.EnvironmentID) {
+ return false, nil
+ }
+ return s.Metadata[resourcesMetadataKey] == fingerprint, nil
+}
+
+// sessionAgentID accepts the agent as a bare ID or as an object with an id.
+func sessionAgentID(raw json.RawMessage) string {
+ var id string
+ if json.Unmarshal(raw, &id) == nil {
+ return id
+ }
+ var obj struct {
+ ID string `json:"id"`
+ }
+ _ = json.Unmarshal(raw, &obj)
+ return obj.ID
+}
+
+// cancelActive stops every remote session that is still executing.
+func (b *Bridge) cancelActive(ctx context.Context) error {
+ var firstErr error
+ for _, r := range b.state.Runs {
+ if r.SessionID == "" || r.Phase == "final" {
+ continue
+ }
+ if err := b.cancelSession(ctx, r.SessionID); err != nil && firstErr == nil {
+ firstErr = err
+ }
+ }
+ return firstErr
+}
+func (b *Bridge) cancelSession(ctx context.Context, sessionID string) error {
+ if err := b.qoder.call(ctx, http.MethodPost, "/sessions/"+url.PathEscape(sessionID)+"/cancel", map[string]any{}, nil); err != nil {
+ var ae *apiError
+ if errors.As(err, &ae) && ae.Status == 404 {
+ return nil
+ }
+ return err
+ }
+ var s struct {
+ Status string `json:"status"`
+ }
+ if err := b.qoder.call(ctx, http.MethodGet, "/sessions/"+url.PathEscape(sessionID), nil, &s); err != nil {
+ var ae *apiError
+ if errors.As(err, &ae) && ae.Status == 404 {
+ return nil
+ }
+ return err
+ }
+ if s.Status != "idle" && s.Status != "terminated" {
+ return fmt.Errorf("waiting for Qoder cancellation")
+ }
+ return nil
+}
+func (b *Bridge) deliver(ctx context.Context, r *run) error {
+ body := map[string]any{"session_id": r.SessionID}
+ suffix := "/complete"
+ if r.Outcome == "completed" {
+ body["output"] = r.Output
+ } else {
+ suffix = "/fail"
+ body["error"] = r.Failure
+ body["failure_reason"] = "qoder_cloud_execution"
+ }
+ if err := b.taskCall(ctx, r, suffix, body, nil); err != nil {
+ return err
+ }
+ b.state.remove(r)
+ return b.persist()
+}
+
+func definitelyRejected(err error) bool {
+ var rejected *apiError
+ return errors.As(err, &rejected) && rejected.Status >= 400 && rejected.Status < 500 && rejected.Status != 408 && rejected.Status != 429
+}
+func (b *Bridge) reject(ctx context.Context, r *run, reason string) error {
+ r.Phase = "final"
+ r.Outcome = "failed"
+ r.Failure = reason
+ if err := b.persist(); err != nil {
+ return err
+ }
+ return b.deliver(ctx, r)
+}
+
+// Check validates access without registering a runtime or executing a task.
+func (b *Bridge) Check(ctx context.Context) error {
+ resources := []struct {
+ api *api
+ path, id, name string
+ }{
+ {b.multica, "/api/workspaces/" + url.PathEscape(b.cfg.WorkspaceID), b.cfg.WorkspaceID, "Multica workspace"},
+ {b.qoder, "/environments/" + url.PathEscape(b.cfg.EnvironmentID), b.cfg.EnvironmentID, "Qoder environment"},
+ }
+ for _, resource := range resources {
+ if resource.api == b.multica && strings.HasPrefix(b.cfg.MulticaToken, "mdt_") {
+ continue
+ }
+ var response struct {
+ ID string `json:"id"`
+ }
+ if err := resource.api.call(ctx, http.MethodGet, resource.path, nil, &response); err != nil {
+ return fmt.Errorf("validate %s: %w", resource.name, err)
+ }
+ if response.ID != resource.id {
+ return fmt.Errorf("validate %s: unexpected resource identity", resource.name)
+ }
+ }
+ return nil
+}
+
+func (b *Bridge) guardedStep(ctx context.Context) error {
+ ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
+ defer cancel()
+ if b.cfg.BeforeStep != nil {
+ release, err := b.cfg.BeforeStep(ctx)
+ if err != nil {
+ return err
+ }
+ defer release()
+ }
+ return b.step(ctx)
+}
+
+func rateLimited(err error) bool {
+ var ae *apiError
+ return errors.As(err, &ae) && ae.Status == http.StatusTooManyRequests
+}
+
+func (b *Bridge) queueCleanup(id string) {
+ for _, existing := range b.state.Cleanup {
+ if existing == id {
+ return
+ }
+ }
+ b.state.Cleanup = append(b.state.Cleanup, id)
+}
+func (b *Bridge) cleanup(ctx context.Context) {
+ if len(b.state.Cleanup) == 0 {
+ return
+ }
+ cleanupCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ if err := b.cancelSession(cleanupCtx, b.state.Cleanup[0]); err != nil {
+ return
+ }
+ b.state.Cleanup = b.state.Cleanup[1:]
+ if err := b.persist(); err != nil {
+ b.log.ErrorContext(ctx, "cannot persist remote cleanup", "error", err)
+ }
+}
+
+// Binding identifies one workspace/environment independently of process lifetime.
+func Binding(multicaURL, workspaceID, qoderURL, environmentID string) string {
+ sum := sha256.Sum256([]byte(strings.TrimRight(multicaURL, "/") + "\n" + workspaceID + "\n" + strings.TrimRight(qoderURL, "/") + "\n" + environmentID))
+ return hex.EncodeToString(sum[:])
+}
+
+// CancelRemoteSession is used by the managed supervisor after user access is
+// revoked. It needs only Qoder credentials, never a former owner's Multica PAT.
+func CancelRemoteSession(ctx context.Context, baseURL, token, sessionID string) error {
+ api, err := newAPI(baseURL, token, "")
+ if err != nil {
+ return err
+ }
+ b := &Bridge{qoder: api}
+ return b.cancelSession(ctx, sessionID)
+}
diff --git a/server/internal/qoderruntime/bridge_test.go b/server/internal/qoderruntime/bridge_test.go
new file mode 100644
index 0000000000..161b5bb28f
--- /dev/null
+++ b/server/internal/qoderruntime/bridge_test.go
@@ -0,0 +1,635 @@
+package qoderruntime
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/daemon"
+)
+
+const workspaceID = "11111111-1111-4111-8111-111111111111"
+
+type harness struct {
+ b *Bridge
+ status string
+ task *daemon.Task
+ events []map[string]any
+ creates, sends, cancels int
+ lostSend bool
+ complete, failure map[string]any
+ messages []map[string]any
+ prompt string
+ sessionAgent string
+}
+
+func setup(t *testing.T) *harness {
+ t.Helper()
+ h := &harness{status: "dispatched"}
+ h.task = &daemon.Task{ID: "task-1", RuntimeID: "runtime-1", WorkspaceID: workspaceID, IssueID: "issue-1", AuthToken: "mat_task", Agent: &daemon.AgentData{Instructions: "Run tests", RuntimeConfig: json.RawMessage(`{"qoder_agent_id":"agent_1"}`), Skills: []daemon.SkillData{{Name: "multica-platform"}}}}
+ m := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if r.Header.Get("X-Workspace-ID") != workspaceID {
+ t.Error("missing workspace")
+ }
+ auth := "Bearer multica-secret"
+ if strings.HasPrefix(r.URL.Path, "/api/issues/") {
+ auth = "Bearer mat_task"
+ }
+ if r.Header.Get("Authorization") != auth {
+ t.Error("wrong credential scope")
+ }
+ if r.Header.Get("X-Client-Capabilities") != "" {
+ t.Error("unsupported capabilities advertised")
+ }
+ switch {
+ case strings.HasSuffix(r.URL.Path, "/tasks/claim"):
+ json.NewEncoder(w).Encode(map[string]any{"task": h.task})
+ h.task = nil
+ case strings.HasPrefix(r.URL.Path, "/api/issues/"):
+ io.WriteString(w, `{"title":"Fix bug","description":"Use repository context"}`)
+ case strings.HasSuffix(r.URL.Path, "/status"):
+ json.NewEncoder(w).Encode(map[string]string{"status": h.status})
+ case strings.HasSuffix(r.URL.Path, "/start"):
+ h.status = "running"
+ io.WriteString(w, `{}`)
+ case strings.HasSuffix(r.URL.Path, "/complete"):
+ json.NewDecoder(r.Body).Decode(&h.complete)
+ h.status = "completed"
+ io.WriteString(w, `{}`)
+ case strings.HasSuffix(r.URL.Path, "/fail"):
+ json.NewDecoder(r.Body).Decode(&h.failure)
+ h.status = "failed"
+ io.WriteString(w, `{}`)
+ case strings.HasSuffix(r.URL.Path, "/messages"):
+ var req struct {
+ Messages []map[string]any `json:"messages"`
+ }
+ json.NewDecoder(r.Body).Decode(&req)
+ h.messages = append(h.messages, req.Messages...)
+ io.WriteString(w, `{}`)
+ case strings.HasSuffix(r.URL.Path, "/session"), strings.HasSuffix(r.URL.Path, "/cancel-ack"):
+ io.WriteString(w, `{}`)
+ default:
+ t.Errorf("unexpected Multica request %s", r.URL)
+ http.NotFound(w, r)
+ }
+ }))
+ t.Cleanup(m.Close)
+ q := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if r.Header.Get("Authorization") != "Bearer qoder-secret" {
+ t.Error("wrong Qoder credential")
+ }
+ switch {
+ case r.URL.Path == "/sessions" && r.Method == "POST":
+ h.creates++
+ var input struct {
+ Agent string `json:"agent"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
+ t.Fatal(err)
+ }
+ h.sessionAgent = input.Agent
+ io.WriteString(w, `{"id":"sess_1","status":"idle"}`)
+ case r.URL.Path == "/sessions/sess_1/events" && r.Method == "POST":
+ h.sends++
+ var req struct {
+ Events []event `json:"events"`
+ }
+ json.NewDecoder(r.Body).Decode(&req)
+ h.prompt = req.Events[0].text()
+ h.events = append(h.events, map[string]any{"id": "evt_user", "type": "user.message", "content": []map[string]string{{"type": "text", "text": h.prompt}}})
+ if h.lostSend {
+ http.Error(w, "unknown", 502)
+ return
+ }
+ io.WriteString(w, `{"data":[]}`)
+ case r.URL.Path == "/sessions/sess_1/events" && r.Method == "GET":
+ if r.URL.Query().Get("page") != "" {
+ t.Error("event ID used as page cursor")
+ }
+ events := h.events
+ after := r.URL.Query().Get("after_id")
+ if after != "" {
+ for i, e := range events {
+ if e["id"] == after {
+ events = events[i+1:]
+ break
+ }
+ }
+ }
+ json.NewEncoder(w).Encode(map[string]any{"data": events, "has_more": false})
+ case strings.HasSuffix(r.URL.Path, "/cancel"):
+ h.cancels++
+ io.WriteString(w, `{"status":"canceling"}`)
+ case r.URL.Path == "/sessions/sess_1":
+ io.WriteString(w, `{"status":"idle"}`)
+ default:
+ t.Errorf("unexpected Qoder request %s", r.URL)
+ http.NotFound(w, r)
+ }
+ }))
+ t.Cleanup(q.Close)
+ var err error
+ h.b, err = New(Config{MulticaURL: m.URL, MulticaToken: "multica-secret", WorkspaceID: workspaceID, QoderURL: q.URL, QoderToken: "qoder-secret", EnvironmentID: "env_1", StateDir: t.TempDir()}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ h.b.state = &journal{Binding: "test", RuntimeID: "runtime-1"}
+ return h
+}
+func (h *harness) finish(reason string) {
+ h.events = append(h.events, map[string]any{"id": "evt_reply", "type": "agent.message", "content": []map[string]string{{"type": "text", "text": "Tests passed. PR: https://example.com/pr/1"}}}, map[string]any{"id": "evt_idle", "type": "session.status_idle", "stop_reason": map[string]string{"type": reason}})
+}
+func TestIssueRun(t *testing.T) {
+ h := setup(t)
+ ctx := context.Background()
+ h.events = []map[string]any{{"id": "evt_initial", "type": "session.status_idle", "stop_reason": map[string]string{"type": "end_turn"}}}
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if h.complete != nil {
+ t.Fatal("completed before user turn")
+ }
+ if !strings.Contains(h.prompt, "Fix bug") || strings.Contains(h.prompt, "secret") || strings.Contains(h.prompt, "mat_task") {
+ t.Fatalf("incorrect prompt: %s", h.prompt)
+ }
+ h.finish("end_turn")
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if h.complete["session_id"] != "sess_1" || !strings.Contains(fmt.Sprint(h.complete["output"]), "Tests passed") {
+ t.Fatalf("result: %#v", h.complete)
+ }
+ if h.creates != 1 || h.sends != 1 || len(h.messages) != 1 || h.b.state.first() != nil {
+ t.Fatal("incorrect lifecycle")
+ }
+ data, err := os.ReadFile(h.b.path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(string(data), "secret") {
+ t.Fatal("credential persisted")
+ }
+}
+func TestAmbiguousSubmitReconcilesAfterRestart(t *testing.T) {
+ h := setup(t)
+ h.lostSend = true
+ if err := h.b.step(context.Background()); err == nil {
+ t.Fatal("expected ambiguous failure")
+ }
+ j, err := readJournal(h.b.path, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ h.b.state = j
+ if j.first().Phase != "sending" || j.first().SessionID != "sess_1" {
+ t.Fatal("missing intent")
+ }
+ h.finish("end_turn")
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.sends != 1 || h.creates != 1 || h.complete == nil {
+ t.Fatal("restart duplicated/lost execution")
+ }
+}
+func TestUnconfirmedSubmissionDoesNotResend(t *testing.T) {
+ h := setup(t)
+ h.lostSend = true
+ _ = h.b.step(context.Background())
+ h.events = nil
+ for range 2 {
+ if err := h.b.step(context.Background()); err == nil {
+ t.Fatal("expected reconciliation warning")
+ }
+ }
+ if h.sends != 1 {
+ t.Fatal("duplicated submission")
+ }
+}
+func TestCancelStopsRemote(t *testing.T) {
+ h := setup(t)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ h.status = "cancelled"
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.cancels != 1 || h.b.state.first() != nil || h.complete != nil {
+ t.Fatal("incorrect cancellation")
+ }
+}
+func TestRequiresActionIsNotSuccess(t *testing.T) {
+ h := setup(t)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ h.finish("requires_action")
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.complete != nil || !strings.Contains(fmt.Sprint(h.failure["error"]), "requires_action") {
+ t.Fatalf("unexpected report: %#v", h.failure)
+ }
+}
+func TestLocalDirectoryFailsBeforeExecution(t *testing.T) {
+ h := setup(t)
+ h.task.ProjectResources = []daemon.ProjectResourceData{{ResourceType: "local_directory"}}
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.creates != 0 || h.failure == nil {
+ t.Fatal("local directory ignored")
+ }
+}
+func TestStateLockAndBinding(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "lock")
+ f, err := lockState(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if second, err := lockState(path); err == nil {
+ second.Close()
+ t.Fatal("second process acquired lock")
+ }
+ f.Close()
+ f, err = lockState(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.Close()
+ path = filepath.Join(t.TempDir(), "state.json")
+ if err := save(path, &journal{Binding: "a"}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := readJournal(path, "b"); err == nil {
+ t.Fatal("wrong binding accepted")
+ }
+}
+func TestAPIRejectsRedirectsAndRedactsErrors(t *testing.T) {
+ target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { t.Error("followed redirect") }))
+ defer target.Close()
+ source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Location", target.URL)
+ w.WriteHeader(302)
+ io.WriteString(w, "sensitive-secret")
+ }))
+ defer source.Close()
+ a, err := newAPI(source.URL, "credential", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ err = a.call(context.Background(), http.MethodGet, "/", nil, nil)
+ if err == nil || strings.Contains(err.Error(), "sensitive-secret") {
+ t.Fatalf("unsafe error: %v", err)
+ }
+ if _, err := newAPI("http://remote.example", "token", ""); err == nil {
+ t.Fatal("plaintext remote URL accepted")
+ }
+}
+
+func TestOpaquePaginationWithEmptyProjectedPage(t *testing.T) {
+ h := setup(t)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ requests := 0
+ q := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests++
+ if requests == 1 {
+ if r.URL.Query().Get("after_id") != "evt_user" {
+ t.Error("missing event cursor")
+ }
+ io.WriteString(w, `{"data":[],"has_more":true,"next_page":"opaque-cursor"}`)
+ } else {
+ if r.URL.Query().Get("page") != "opaque-cursor" || r.URL.Query().Get("after_id") != "" {
+ t.Error("incorrect page request")
+ }
+ io.WriteString(w, `{"data":[{"id":"evt_done","type":"session.status_idle","stop_reason":{"type":"end_turn"}}],"has_more":false}`)
+ }
+ }))
+ defer q.Close()
+ h.b.qoder.base = q.URL
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ j, err := readJournal(h.b.path, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ h.b.state = j
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.complete == nil || requests != 2 {
+ t.Fatal("pagination lost terminal event")
+ }
+}
+
+func TestTerminalReportSurvivesRestart(t *testing.T) {
+ h := setup(t)
+ h.b.state.Runs = []*run{&run{TaskID: "task-1", SessionID: "sess_1", Phase: "final", Outcome: "completed", Output: "Recovered result"}}
+ if err := h.b.persist(); err != nil {
+ t.Fatal(err)
+ }
+ j, err := readJournal(h.b.path, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ h.b.state = j
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.complete["output"] != "Recovered result" || h.creates != 0 || h.sends != 0 {
+ t.Fatal("terminal recovery re-executed task")
+ }
+}
+
+func TestRejectedMessageFailsRun(t *testing.T) {
+ h := setup(t)
+ q := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/sessions" {
+ io.WriteString(w, `{"id":"sess_1"}`)
+ return
+ }
+ http.Error(w, "bad message", 400)
+ }))
+ defer q.Close()
+ h.b.qoder.base = q.URL
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.failure == nil || h.b.state.first() != nil {
+ t.Fatal("definite rejection left run pending")
+ }
+}
+
+func TestRegistrationAndShutdown(t *testing.T) {
+ h := setup(t)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ m := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/workspaces/" + workspaceID:
+ json.NewEncoder(w).Encode(map[string]string{"id": workspaceID})
+ case "/api/daemon/register":
+ var req struct {
+ Runtimes []struct {
+ Type string `json:"type"`
+ Mode string `json:"runtime_mode"`
+ } `json:"runtimes"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ t.Error(err)
+ }
+ if len(req.Runtimes) != 1 || req.Runtimes[0].Type != Provider || req.Runtimes[0].Mode != "cloud" {
+ t.Error("wrong registration provider")
+ }
+ io.WriteString(w, `{"runtimes":[{"id":"runtime-1","provider":"qoder_cloud"}]}`)
+ case "/api/daemon/heartbeat":
+ io.WriteString(w, `{}`)
+ cancel()
+ default:
+ t.Errorf("unexpected startup request %s", r.URL)
+ }
+ }))
+ defer m.Close()
+ h.b.multica.base = m.URL
+ q := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/agents/agent_1" && r.URL.Path != "/environments/env_1" {
+ t.Error("unexpected remote validation")
+ }
+ id := strings.TrimPrefix(strings.TrimPrefix(r.URL.Path, "/agents/"), "/environments/")
+ json.NewEncoder(w).Encode(map[string]string{"id": id})
+ }))
+ defer q.Close()
+ h.b.qoder.base = q.URL
+ err := h.b.Run(ctx)
+ if err != nil && ctx.Err() == nil {
+ t.Fatal(err)
+ }
+}
+
+func TestPerAgentSessionBinding(t *testing.T) {
+ for _, id := range []string{"agent_first", "agent_second"} {
+ t.Run(id, func(t *testing.T) {
+ h := setup(t)
+ h.task.Agent.RuntimeConfig = json.RawMessage(fmt.Sprintf(`{"qoder_agent_id":%q}`, id))
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.sessionAgent != id {
+ t.Fatalf("session agent = %q, want %q", h.sessionAgent, id)
+ }
+ restored, err := readJournal(h.b.path, "test")
+ if err != nil || restored.first().AgentID != id {
+ t.Fatal("per-run agent binding not persisted")
+ }
+ })
+ }
+}
+func TestMissingAgentBindingFailsBeforeSession(t *testing.T) {
+ for _, raw := range []string{`{}`, `{"qoder_agent_id":"../agents"}`, `{"qoder_agent_id":1}`} {
+ h := setup(t)
+ h.task.Agent.RuntimeConfig = json.RawMessage(raw)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.creates != 0 || h.status != "failed" {
+ t.Fatal("unbound task created a QCA session")
+ }
+ }
+}
+
+func TestRunDeadlineReleasesQueue(t *testing.T) {
+ h := setup(t)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ h.b.state.first().Deadline = time.Now().Add(-time.Second)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.failure == nil || h.b.state.first() != nil || h.cancels != 1 {
+ t.Fatal("expired run did not cancel and finish")
+ }
+}
+
+func TestAmbiguousCreationIsNotRepeated(t *testing.T) {
+ h := setup(t)
+ h.b.state.Runs = []*run{&run{TaskID: "task-1", Phase: "creating", Deadline: time.Now().Add(time.Hour)}}
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.creates != 0 || h.failure == nil {
+ t.Fatal("ambiguous creation was repeated")
+ }
+}
+
+func TestTimeoutKeepsFailedCancellationForRecovery(t *testing.T) {
+ h := setup(t)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(503) }))
+ defer remote.Close()
+ h.b.qoder.base = remote.URL
+ h.b.state.first().Deadline = time.Now().Add(-time.Second)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.b.state.first() != nil || len(h.b.state.Cleanup) != 1 || h.failure == nil {
+ t.Fatal("failed cancellation blocked queue or lost session")
+ }
+ j, err := readJournal(h.b.path, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(j.Cleanup) != 1 || j.Cleanup[0] != "sess_1" {
+ t.Fatal("cleanup not durable")
+ }
+}
+
+func TestDeletedRemoteSessionFailsRun(t *testing.T) {
+ h := setup(t)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ remote := httptest.NewServer(http.NotFoundHandler())
+ defer remote.Close()
+ h.b.qoder.base = remote.URL
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.failure == nil || h.b.state.first() != nil {
+ t.Fatal("deleted session not terminal")
+ }
+}
+
+func TestRateLimitedCreationRetriesAfterDelay(t *testing.T) {
+ h := setup(t)
+ attempts := 0
+ remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { attempts++; w.WriteHeader(http.StatusTooManyRequests) }))
+ defer remote.Close()
+ h.b.qoder.base = remote.URL
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.b.state.first() == nil || h.b.state.first().Phase != "prepared" || h.failure != nil {
+ t.Fatal("rate limit became permanent failure")
+ }
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if attempts != 1 {
+ t.Fatal("rate limit retry ignored backoff")
+ }
+}
+
+func TestSubmissionDeadlineReleasesUnconfirmedRun(t *testing.T) {
+ h := setup(t)
+ h.lostSend = true
+ if err := h.b.step(context.Background()); err == nil {
+ t.Fatal("expected lost response")
+ }
+ h.events = nil
+ h.b.state.first().SubmissionDeadline = time.Now().Add(-time.Second)
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.failure == nil || h.b.state.first() != nil || h.sends != 1 {
+ t.Fatal("unconfirmed submission blocked queue or resent")
+ }
+}
+
+func TestManagedJournalPersistsWithoutLocalFiles(t *testing.T) {
+ h := setup(t)
+ var saved []byte
+ h.b.cfg.SaveState = func(_ context.Context, raw []byte) error { saved = append([]byte(nil), raw...); return nil }
+ h.b.path = "/not/a/writable/path"
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ restored, err := decodeJournal(saved, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if restored.first() == nil || restored.first().SessionID != "sess_1" || restored.first().Deadline.IsZero() {
+ t.Fatal("managed recovery lost session or deadline")
+ }
+}
+
+func TestToolResultsPreserveCallIdentity(t *testing.T) {
+ for _, prefix := range []string{"agent.", "agent.mcp_"} {
+ t.Run(prefix, func(t *testing.T) {
+ h := setup(t)
+ ctx := context.Background()
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ h.events = append(h.events,
+ map[string]any{"id": "call-a", "type": prefix + "tool_use", "name": "Read"},
+ map[string]any{"id": "call-b", "type": prefix + "tool_use", "name": "Read"},
+ map[string]any{"id": "result-b", "type": prefix + "tool_result", "tool_use_id": "call-b"},
+ map[string]any{"id": "result-a", "type": prefix + "tool_result", "tool_use_id": "call-a"},
+ )
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if len(h.messages) != 4 {
+ t.Fatalf("got %d messages", len(h.messages))
+ }
+ for i, want := range []string{"call-a", "call-b", "call-b", "call-a"} {
+ if h.messages[i]["call_id"] != want {
+ t.Errorf("message %d: call_id = %v, want %s", i, h.messages[i]["call_id"], want)
+ }
+ }
+ })
+ }
+}
+
+// first returns the oldest active run, which single-run tests inspect.
+func (j *journal) first() *run {
+ if len(j.Runs) == 0 {
+ return nil
+ }
+ return j.Runs[0]
+}
+
+func TestJournalStorageConfig(t *testing.T) {
+ base := Config{MulticaURL: "http://127.0.0.1:1", MulticaToken: "m", WorkspaceID: workspaceID, QoderURL: "http://127.0.0.1:2", QoderToken: "q", EnvironmentID: "env_1"}
+ load := func(context.Context) ([]byte, error) { return nil, nil }
+ save := func(context.Context, []byte) error { return nil }
+
+ external := base
+ external.LoadState, external.SaveState = load, save
+ if _, err := New(external, nil); err != nil {
+ t.Fatalf("external journal needs no state directory: %v", err)
+ }
+ onDisk := base
+ onDisk.StateDir = t.TempDir()
+ if _, err := New(onDisk, nil); err != nil {
+ t.Fatalf("on-disk journal rejected: %v", err)
+ }
+ for name, cfg := range map[string]Config{
+ "no journal": base,
+ "load only": func() Config { c := base; c.LoadState = load; c.StateDir = t.TempDir(); return c }(),
+ "save only": func() Config { c := base; c.SaveState = save; c.StateDir = t.TempDir(); return c }(),
+ "no environment": func() Config { c := external; c.EnvironmentID = ""; return c }(),
+ } {
+ if _, err := New(cfg, nil); err == nil {
+ t.Errorf("%s accepted", name)
+ }
+ }
+}
diff --git a/server/internal/qoderruntime/claim.go b/server/internal/qoderruntime/claim.go
new file mode 100644
index 0000000000..ec67c8ad9e
--- /dev/null
+++ b/server/internal/qoderruntime/claim.go
@@ -0,0 +1,59 @@
+package qoderruntime
+
+import "encoding/json"
+
+// Claim payload fields consumed by the remote bridge. Keep this HTTP boundary
+// independent of the local daemon implementation and its CLI dependencies.
+type claimedTask struct {
+ ID string `json:"id"`
+ RuntimeID string `json:"runtime_id"`
+ WorkspaceID string `json:"workspace_id"`
+ IssueID string `json:"issue_id"`
+ ChatSessionID string `json:"chat_session_id,omitempty"`
+ IsLeaderTask bool `json:"is_leader_task,omitempty"`
+ AuthToken string `json:"auth_token,omitempty"`
+ RemoteMCPConnections []json.RawMessage `json:"remote_mcp_connections,omitempty"`
+ ConnectedApps []json.RawMessage `json:"connected_apps,omitempty"`
+ PluginHookTools []json.RawMessage `json:"plugin_hook_tools,omitempty"`
+ Agent *claimedAgent `json:"agent,omitempty"`
+ PriorSessionID string `json:"prior_session_id,omitempty"`
+ IssueIdentifier string `json:"issue_identifier,omitempty"`
+ WorkspaceContext string `json:"workspace_context,omitempty"`
+ ProjectTitle string `json:"project_title,omitempty"`
+ ProjectDescription string `json:"project_description,omitempty"`
+ HandoffNote string `json:"handoff_note,omitempty"`
+ CoalescedComments []claimedComment `json:"coalesced_comments,omitempty"`
+ TriggerCommentContent string `json:"trigger_comment_content,omitempty"`
+ TriggerAuthorName string `json:"trigger_author_name,omitempty"`
+ ProjectResources []claimedResource `json:"project_resources,omitempty"`
+ Repos []claimedRepo `json:"repos,omitempty"`
+}
+
+type claimedAgent struct {
+ Instructions string `json:"instructions"`
+ Skills []claimedSkill `json:"skills,omitempty"`
+ SkillRefs []json.RawMessage `json:"skill_refs,omitempty"`
+ CustomEnv map[string]string `json:"custom_env,omitempty"`
+ CustomArgs []string `json:"custom_args,omitempty"`
+ McpConfig json.RawMessage `json:"mcp_config,omitempty"`
+ Model string `json:"model,omitempty"`
+ ThinkingLevel string `json:"thinking_level,omitempty"`
+ ServiceTier string `json:"service_tier,omitempty"`
+ RuntimeConfig json.RawMessage `json:"runtime_config,omitempty"`
+}
+
+type claimedSkill struct {
+ ID string `json:"id"`
+}
+type claimedComment struct {
+ AuthorName string `json:"author_name"`
+ Content string `json:"content"`
+}
+type claimedResource struct {
+ ResourceType string `json:"resource_type"`
+ ResourceRef json.RawMessage `json:"resource_ref"`
+}
+type claimedRepo struct {
+ URL string `json:"url"`
+ Description string `json:"description"`
+}
diff --git a/server/internal/qoderruntime/concurrency_test.go b/server/internal/qoderruntime/concurrency_test.go
new file mode 100644
index 0000000000..99c59dd2f9
--- /dev/null
+++ b/server/internal/qoderruntime/concurrency_test.go
@@ -0,0 +1,361 @@
+package qoderruntime
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/daemon"
+)
+
+// multiHarness serves several tasks and sessions at once; setup() models one.
+type multiHarness struct {
+ b *Bridge
+ mu sync.Mutex
+ queue []*daemon.Task
+ claims int
+ status map[string]string
+ completed map[string]map[string]any
+ failed map[string]map[string]any
+ sessions map[string][]map[string]any
+ sessionStatus map[string]string
+ creates int
+ sentTo []string
+ prompts map[string]string
+ metadata map[string]map[string]string
+ resources map[string][]map[string]any
+}
+
+func newTask(id, prior string) *daemon.Task {
+ return &daemon.Task{ID: id, RuntimeID: "runtime-1", WorkspaceID: workspaceID, IssueID: "issue-" + id, IssueIdentifier: "MUL-42", AuthToken: "mat_task", PriorSessionID: prior, Agent: &daemon.AgentData{Instructions: "Run tests", RuntimeConfig: json.RawMessage(`{"qoder_agent_id":"agent_1"}`)}}
+}
+
+func setupMulti(t *testing.T, limit int, tasks ...*daemon.Task) *multiHarness {
+ t.Helper()
+ h := &multiHarness{queue: tasks, status: map[string]string{}, completed: map[string]map[string]any{}, failed: map[string]map[string]any{}, sessions: map[string][]map[string]any{}, sessionStatus: map[string]string{}, prompts: map[string]string{}, metadata: map[string]map[string]string{}, resources: map[string][]map[string]any{}}
+ taskID := func(path string) string {
+ rest := strings.TrimPrefix(path, "/api/daemon/tasks/")
+ return rest[:strings.Index(rest, "/")]
+ }
+ m := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ w.Header().Set("Content-Type", "application/json")
+ switch {
+ case strings.HasSuffix(r.URL.Path, "/tasks/claim"):
+ h.claims++
+ var next *daemon.Task
+ if len(h.queue) > 0 {
+ next, h.queue = h.queue[0], h.queue[1:]
+ h.status[next.ID] = "dispatched"
+ }
+ json.NewEncoder(w).Encode(map[string]any{"task": next})
+ case strings.HasPrefix(r.URL.Path, "/api/issues/"):
+ io.WriteString(w, `{"title":"Fix the login bug","description":"Use repository context"}`)
+ case strings.HasSuffix(r.URL.Path, "/status"):
+ json.NewEncoder(w).Encode(map[string]string{"status": h.status[taskID(r.URL.Path)]})
+ case strings.HasSuffix(r.URL.Path, "/start"):
+ h.status[taskID(r.URL.Path)] = "running"
+ io.WriteString(w, `{}`)
+ case strings.HasSuffix(r.URL.Path, "/complete"):
+ var body map[string]any
+ json.NewDecoder(r.Body).Decode(&body)
+ h.completed[taskID(r.URL.Path)] = body
+ h.status[taskID(r.URL.Path)] = "completed"
+ io.WriteString(w, `{}`)
+ case strings.HasSuffix(r.URL.Path, "/fail"):
+ var body map[string]any
+ json.NewDecoder(r.Body).Decode(&body)
+ h.failed[taskID(r.URL.Path)] = body
+ h.status[taskID(r.URL.Path)] = "failed"
+ io.WriteString(w, `{}`)
+ case strings.HasSuffix(r.URL.Path, "/messages"), strings.HasSuffix(r.URL.Path, "/session"), strings.HasSuffix(r.URL.Path, "/cancel-ack"):
+ io.WriteString(w, `{}`)
+ default:
+ t.Errorf("unexpected Multica request %s", r.URL)
+ http.NotFound(w, r)
+ }
+ }))
+ t.Cleanup(m.Close)
+ q := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ w.Header().Set("Content-Type", "application/json")
+ parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
+ switch {
+ case r.URL.Path == "/sessions" && r.Method == http.MethodPost:
+ h.creates++
+ id := fmt.Sprintf("sess_new_%d", h.creates)
+ h.sessionStatus[id] = "idle"
+ var req struct {
+ Metadata map[string]string `json:"metadata"`
+ Resources []map[string]any `json:"resources"`
+ }
+ json.NewDecoder(r.Body).Decode(&req)
+ h.metadata[id] = req.Metadata
+ h.resources[id] = req.Resources
+ fmt.Fprintf(w, `{"id":%q}`, id)
+ case len(parts) == 3 && parts[2] == "events" && r.Method == http.MethodPost:
+ var req struct {
+ Events []event `json:"events"`
+ }
+ json.NewDecoder(r.Body).Decode(&req)
+ h.sentTo = append(h.sentTo, parts[1])
+ h.prompts[parts[1]] = req.Events[0].text()
+ h.sessionStatus[parts[1]] = "running"
+ h.sessions[parts[1]] = append(h.sessions[parts[1]], map[string]any{"id": fmt.Sprintf("evt_%s_%d", parts[1], len(h.sessions[parts[1]])), "type": "user.message", "content": []map[string]string{{"type": "text", "text": req.Events[0].text()}}})
+ io.WriteString(w, `{"data":[]}`)
+ case len(parts) == 3 && parts[2] == "events":
+ events := h.sessions[parts[1]]
+ if after := r.URL.Query().Get("after_id"); after != "" {
+ for i, e := range events {
+ if e["id"] == after {
+ events = events[i+1:]
+ break
+ }
+ }
+ }
+ json.NewEncoder(w).Encode(map[string]any{"data": events, "has_more": false})
+ case len(parts) == 2 && r.Method == http.MethodGet:
+ status, ok := h.sessionStatus[parts[1]]
+ if !ok {
+ http.NotFound(w, r)
+ return
+ }
+ json.NewEncoder(w).Encode(map[string]any{"status": status, "agent": "agent_1", "environment_id": "env_1", "metadata": h.metadata[parts[1]]})
+ default:
+ t.Errorf("unexpected Qoder request %s", r.URL)
+ http.NotFound(w, r)
+ }
+ }))
+ t.Cleanup(q.Close)
+ var err error
+ h.b, err = New(Config{MulticaURL: m.URL, MulticaToken: "multica-secret", WorkspaceID: workspaceID, QoderURL: q.URL, QoderToken: "qoder-secret", EnvironmentID: "env_1", StateDir: t.TempDir(), MaxConcurrency: limit}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ h.b.state = &journal{Binding: "test", RuntimeID: "runtime-1"}
+ return h
+}
+
+func (h *multiHarness) finish(session string) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ n := len(h.sessions[session])
+ h.sessions[session] = append(h.sessions[session],
+ map[string]any{"id": fmt.Sprintf("evt_%s_%d", session, n), "type": "agent.message", "content": []map[string]string{{"type": "text", "text": "done in " + session}}},
+ map[string]any{"id": fmt.Sprintf("evt_%s_%d", session, n+1), "type": "session.status_idle", "stop_reason": map[string]string{"type": "end_turn"}})
+ h.sessionStatus[session] = "idle"
+}
+
+func TestConcurrentRunsRespectLimit(t *testing.T) {
+ h := setupMulti(t, 2, newTask("task-1", ""), newTask("task-2", ""), newTask("task-3", ""))
+ ctx := context.Background()
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if h.creates != 2 || len(h.b.state.Runs) != 2 || h.claims != 2 || len(h.queue) != 1 {
+ t.Fatalf("creates=%d runs=%d claims=%d queued=%d", h.creates, len(h.b.state.Runs), h.claims, len(h.queue))
+ }
+ h.finish("sess_new_1")
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if h.completed["task-1"]["session_id"] != "sess_new_1" {
+ t.Fatalf("task-1 result: %#v", h.completed["task-1"])
+ }
+ if h.completed["task-2"] != nil || h.creates != 3 || len(h.b.state.Runs) != 2 || len(h.queue) != 0 {
+ t.Fatalf("freed slot not reused: creates=%d runs=%d queued=%d", h.creates, len(h.b.state.Runs), len(h.queue))
+ }
+}
+
+func TestFollowUpContinuesIdleSession(t *testing.T) {
+ h := setupMulti(t, 1, newTask("task-1", "sess_prev"))
+ h.sessionStatus["sess_prev"] = "idle"
+ h.metadata["sess_prev"] = map[string]string{resourcesMetadataKey: resourceFingerprint(nil)}
+ h.sessions["sess_prev"] = []map[string]any{
+ {"id": "evt_old_0", "type": "user.message", "content": []map[string]string{{"type": "text", "text": "earlier run"}}},
+ {"id": "evt_old_1", "type": "session.status_idle", "stop_reason": map[string]string{"type": "end_turn"}},
+ }
+ ctx := context.Background()
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if h.creates != 0 || len(h.sentTo) != 1 || h.sentTo[0] != "sess_prev" {
+ t.Fatalf("follow-up did not continue: creates=%d sentTo=%v", h.creates, h.sentTo)
+ }
+ if h.completed["task-1"] != nil {
+ t.Fatal("earlier idle event completed the follow-up")
+ }
+ h.finish("sess_prev")
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if h.completed["task-1"]["session_id"] != "sess_prev" || h.completed["task-1"]["output"] != "done in sess_prev" {
+ t.Fatalf("result: %#v", h.completed["task-1"])
+ }
+}
+
+func TestFollowUpStartsNewSessionWhenPriorIsUnavailable(t *testing.T) {
+ for name, status := range map[string]string{"busy": "running", "deleted": ""} {
+ t.Run(name, func(t *testing.T) {
+ h := setupMulti(t, 1, newTask("task-1", "sess_prev"))
+ if status != "" {
+ h.sessionStatus["sess_prev"] = status
+ }
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.creates != 1 || len(h.sentTo) != 1 || h.sentTo[0] != "sess_new_1" {
+ t.Fatalf("creates=%d sentTo=%v", h.creates, h.sentTo)
+ }
+ })
+ }
+}
+
+func repoTask(id, prior, repo, ref string) *daemon.Task {
+ task := newTask(id, prior)
+ task.Agent.RuntimeConfig = json.RawMessage(fmt.Sprintf(`{"qoder_agent_id":"agent_1","repository":{"url":%q,"ref":%q}}`, repo, ref))
+ return task
+}
+
+func TestFollowUpReusesSessionOnlyForSameRepositoryAndCredential(t *testing.T) {
+ const repoA, repoB = "https://github.com/acme/a", "https://github.com/acme/b"
+ for name, tc := range map[string]struct {
+ followUp *daemon.Task
+ tokens map[string]string
+ reuse bool
+ }{
+ "unchanged": {repoTask("task-2", "sess_new_1", repoA, "main"), map[string]string{repoA: "tok-a"}, true},
+ "other repository": {repoTask("task-2", "sess_new_1", repoB, "main"), map[string]string{repoA: "tok-a", repoB: "tok-b"}, false},
+ "other branch": {repoTask("task-2", "sess_new_1", repoA, "release"), map[string]string{repoA: "tok-a"}, false},
+ "rotated token": {repoTask("task-2", "sess_new_1", repoA, "main"), map[string]string{repoA: "tok-a2"}, false},
+ } {
+ t.Run(name, func(t *testing.T) {
+ h := setupMulti(t, 1, repoTask("task-1", "", repoA, "main"), tc.followUp)
+ h.b.cfg.GitHubTokens = map[string]string{repoA: "tok-a"}
+ ctx := context.Background()
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ h.b.cfg.GitHubTokens = tc.tokens
+ h.finish("sess_new_1")
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if reused := h.creates == 1 && h.sentTo[len(h.sentTo)-1] == "sess_new_1"; reused != tc.reuse {
+ t.Fatalf("reuse=%v, want %v (creates=%d sentTo=%v)", reused, tc.reuse, h.creates, h.sentTo)
+ }
+ if !tc.reuse {
+ got := h.resources["sess_new_2"]
+ if len(got) != 1 || got[0]["authorization_token"] != tc.tokens[got[0]["url"].(string)] {
+ t.Fatalf("new session resources: %v", got)
+ }
+ }
+ })
+ }
+}
+
+func TestFollowUpFailsWhenRepositoryCredentialWasRemoved(t *testing.T) {
+ const repo = "https://github.com/acme/a"
+ h := setupMulti(t, 1, repoTask("task-1", "", repo, ""), repoTask("task-2", "sess_new_1", repo, ""))
+ h.b.cfg.GitHubTokens = map[string]string{repo: "tok-a"}
+ ctx := context.Background()
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ h.b.cfg.GitHubTokens = nil
+ h.finish("sess_new_1")
+ if err := h.b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if len(h.sentTo) != 1 || h.creates != 1 || h.failed["task-2"] == nil {
+ t.Fatalf("follow-up ran without a credential: creates=%d sentTo=%v failed=%v", h.creates, h.sentTo, h.failed["task-2"])
+ }
+}
+
+func TestFollowUpSkipsSessionWithoutFingerprint(t *testing.T) {
+ h := setupMulti(t, 1, newTask("task-1", "sess_prev"))
+ h.sessionStatus["sess_prev"] = "idle"
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if h.creates != 1 || len(h.sentTo) != 1 || h.sentTo[0] != "sess_new_1" {
+ t.Fatalf("legacy session reused: creates=%d sentTo=%v", h.creates, h.sentTo)
+ }
+}
+
+func TestPromptAsksForLinkableBranch(t *testing.T) {
+ h := setupMulti(t, 1, newTask("task-1", ""))
+ if err := h.b.step(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ prompt := h.prompts["sess_new_1"]
+ if !strings.Contains(prompt, "multica/mul-42-fix-the-login-bug") || !strings.Contains(prompt, `"MUL-42: "`) {
+ t.Fatalf("prompt lacks branch convention: %s", prompt)
+ }
+}
+
+func TestLegacySingleRunJournalDecodes(t *testing.T) {
+ j, err := decodeJournal([]byte(`{"binding":"b","runtime_id":"rt","run":{"task_id":"task-1","session_id":"sess_1","phase":"running"}}`), "b")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if j.Run != nil || len(j.Runs) != 1 || j.Runs[0].SessionID != "sess_1" {
+ t.Fatalf("legacy run not folded: %#v", j)
+ }
+ if _, err := decodeJournal([]byte(`{"binding":"b","runs":[{"task_id":"t","phase":"prepared"},{"task_id":"t","phase":"prepared"}]}`), "b"); err == nil {
+ t.Fatal("duplicate task accepted")
+ }
+}
+
+func TestBranchName(t *testing.T) {
+ for _, tc := range []struct{ id, title, want string }{
+ {"MUL-7", "Fix: Login → SSO!", "multica/mul-7-fix-login-sso"},
+ {"MUL-7", "修复登录", "multica/mul-7"},
+ {"MUL-7", strings.Repeat("long title ", 10), "multica/mul-7-long-title-long-title-long-title-long"},
+ } {
+ if got := BranchName(tc.id, tc.title); got != tc.want {
+ t.Errorf("BranchName(%q) = %q, want %q", tc.title, got, tc.want)
+ }
+ }
+}
+
+func TestAgentDefaultRepository(t *testing.T) {
+ if _, err := ParseAgentConfig(json.RawMessage(`{"qoder_agent_id":"agent_1","repository":{"url":"https://github.com/acme/app","ref":"main"}}`)); err != nil {
+ t.Fatal(err)
+ }
+ for _, raw := range []string{
+ `{"qoder_agent_id":"agent_1","repository":{"url":"http://github.com/acme/app"}}`,
+ `{"qoder_agent_id":"agent_1","repository":{"url":"https://github.com/acme/app","ref":"refs/tags/v1"}}`,
+ } {
+ if _, err := ParseAgentConfig(json.RawMessage(raw)); err == nil || !strings.HasPrefix(err.Error(), "default repository") {
+ t.Errorf("accepted %s: %v", raw, err)
+ }
+ }
+}
+
+func TestResourceFingerprintSurvivesJournalRoundTrip(t *testing.T) {
+ release, err := repositoryResource(Repository{URL: "https://github.com/acme/a", Ref: "release"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defaultBranch, _ := repositoryResource(Repository{URL: "https://github.com/acme/a"})
+ raw, _ := json.Marshal(&run{TaskID: "t", Resources: []map[string]any{release}})
+ var restored run
+ if err := json.Unmarshal(raw, &restored); err != nil {
+ t.Fatal(err)
+ }
+ if got, want := resourceFingerprint(restored.Resources), resourceFingerprint([]map[string]any{release}); got != want {
+ t.Fatal("restored resources fingerprint differently")
+ }
+ if resourceFingerprint(restored.Resources) == resourceFingerprint([]map[string]any{defaultBranch}) {
+ t.Fatal("restored branch dropped from fingerprint")
+ }
+}
diff --git a/server/internal/qoderruntime/credentials.go b/server/internal/qoderruntime/credentials.go
new file mode 100644
index 0000000000..ac1a2ebea8
--- /dev/null
+++ b/server/internal/qoderruntime/credentials.go
@@ -0,0 +1,89 @@
+package qoderruntime
+
+import (
+ "fmt"
+ "io"
+ "net/url"
+ "os"
+ "strings"
+)
+
+// repositoryKey binds each credential to an exact GitHub repository.
+func repositoryKey(raw string) (string, error) {
+ u, err := url.Parse(raw)
+ if err != nil || u.Scheme != "https" || u.Host != "github.com" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.RawPath != "" {
+ return "", fmt.Errorf("repository must be an HTTPS github.com URL without credentials")
+ }
+ path := strings.TrimSuffix(strings.TrimSuffix(u.Path, "/"), ".git")
+ parts := strings.Split(strings.TrimPrefix(path, "/"), "/")
+ if len(parts) != 2 || parts[0] == "" || parts[1] == "" || parts[0] == "." || parts[0] == ".." || parts[1] == "." || parts[1] == ".." {
+ return "", fmt.Errorf("repository URL must contain an owner and repository")
+ }
+ return "https://github.com/" + strings.ToLower(strings.Join(parts, "/")), nil
+}
+
+// sessionResources creates an ephemeral request copy; never put secrets in the journal.
+func (b *Bridge) sessionResources(resources []map[string]any) ([]map[string]any, error) {
+ out := make([]map[string]any, 0, len(resources))
+ for _, resource := range resources {
+ raw, _ := resource["url"].(string)
+ key, err := repositoryKey(raw)
+ if err != nil {
+ return nil, err
+ }
+ token := b.cfg.GitHubTokens[key]
+ path := ""
+ for configured, file := range b.cfg.GitHubTokenFiles {
+ candidate, err := repositoryKey(configured)
+ if err != nil {
+ return nil, fmt.Errorf("invalid GitHub credential repository binding")
+ }
+ if candidate == key {
+ if path != "" {
+ return nil, fmt.Errorf("duplicate GitHub credential repository binding")
+ }
+ path = file
+ }
+ }
+ if path == "" && token == "" {
+ return nil, fmt.Errorf("no GitHub credential configured for project repository")
+ }
+ if token == "" {
+ token, err = readRepositoryToken(path)
+ if err != nil {
+ return nil, err
+ }
+ }
+ copy := make(map[string]any, len(resource)+1)
+ for k, v := range resource {
+ copy[k] = v
+ }
+ copy["authorization_token"] = token
+ out = append(out, copy)
+ }
+ return out, nil
+}
+
+func readRepositoryToken(path string) (string, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return "", fmt.Errorf("cannot open GitHub credential file")
+ }
+ defer f.Close()
+ info, err := f.Stat()
+ if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 {
+ return "", fmt.Errorf("GitHub credential file must be a private regular file (0600)")
+ }
+ raw, err := io.ReadAll(io.LimitReader(f, 16385))
+ if err != nil || len(raw) > 16384 {
+ return "", fmt.Errorf("cannot read GitHub credential file or file too large")
+ }
+ token := strings.TrimSpace(string(raw))
+ if token == "" || strings.ContainsAny(token, "\r\n\t ") {
+ return "", fmt.Errorf("GitHub credential file must contain one non-empty token")
+ }
+ return token, nil
+}
+
+// RepositoryKey validates and canonicalizes a repository credential binding.
+func RepositoryKey(raw string) (string, error) { return repositoryKey(raw) }
diff --git a/server/internal/qoderruntime/credentials_test.go b/server/internal/qoderruntime/credentials_test.go
new file mode 100644
index 0000000000..a9fe47436d
--- /dev/null
+++ b/server/internal/qoderruntime/credentials_test.go
@@ -0,0 +1,70 @@
+package qoderruntime
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestRepositoryCredentialRequestOnly(t *testing.T) {
+ dir := t.TempDir()
+ file := filepath.Join(dir, "token")
+ if err := os.WriteFile(file, []byte("test-secret\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ b := &Bridge{cfg: Config{GitHubTokenFiles: map[string]string{"https://github.com/Owner/Repo.git": file}}}
+ r := &run{Resources: []map[string]any{{"type": "github_repository", "url": "https://github.com/owner/repo", "checkout": map[string]string{"type": "branch", "name": "main"}}}}
+ request, err := b.sessionResources(r.Resources)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if request[0]["authorization_token"] != "test-secret" {
+ t.Fatal("missing request credential")
+ }
+ state := filepath.Join(dir, "state.json")
+ if err := save(state, &journal{Runs: []*run{r}}); err != nil {
+ t.Fatal(err)
+ }
+ data, err := os.ReadFile(state)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(string(data), "test-secret") || strings.Contains(string(data), "authorization_token") {
+ t.Fatal("credential persisted")
+ }
+ if err := os.WriteFile(file, []byte("rotated-secret"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ request, err = b.sessionResources(r.Resources)
+ if err != nil || request[0]["authorization_token"] != "rotated-secret" {
+ t.Fatal("credential rotation not picked up")
+ }
+ r.Resources[0]["url"] = "https://github.com/owner/another"
+ if _, err := b.sessionResources(r.Resources); err == nil {
+ t.Fatal("credential crossed repository boundary")
+ }
+}
+
+func TestRepositoryCredentialValidation(t *testing.T) {
+ for _, raw := range []string{"https://github.com/owner", "https://github.com:443/a/b", "https://github.com/a/b?token=x", "https://[email protected]/a/b", "https://github.com/a/b/extra", "https://github.com/a/%62", "https://github.com/a/.."} {
+ if _, err := repositoryKey(raw); err == nil {
+ t.Errorf("accepted %q", raw)
+ }
+ }
+ file := filepath.Join(t.TempDir(), "token")
+ for _, secret := range []string{"", "first\nsecond", strings.Repeat("x", 16385)} {
+ if err := os.WriteFile(file, []byte(secret), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := readRepositoryToken(file); err == nil {
+ t.Fatal("accepted invalid credential")
+ }
+ }
+ if err := os.Chmod(file, 0644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := readRepositoryToken(file); err == nil {
+ t.Fatal("accepted public file")
+ }
+}
diff --git a/server/internal/qoderruntime/events.go b/server/internal/qoderruntime/events.go
new file mode 100644
index 0000000000..e83a61470d
--- /dev/null
+++ b/server/internal/qoderruntime/events.go
@@ -0,0 +1,147 @@
+package qoderruntime
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/url"
+ "strings"
+)
+
+type event struct {
+ ToolUseID string `json:"tool_use_id"`
+ ID string `json:"id"`
+ Type string `json:"type"`
+ Name string `json:"name"`
+ Content []struct {
+ Type string `json:"type"`
+ Text string `json:"text"`
+ } `json:"content"`
+ Input map[string]any `json:"input"`
+ StopReason struct {
+ Type string `json:"type"`
+ } `json:"stop_reason"`
+ Error struct {
+ Message string `json:"message"`
+ RetryStatus struct {
+ Type string `json:"type"`
+ } `json:"retry_status"`
+ } `json:"error"`
+}
+
+func (e event) text() string {
+ var parts []string
+ for _, c := range e.Content {
+ if c.Type == "text" {
+ parts = append(parts, c.Text)
+ }
+ }
+ return strings.Join(parts, "\n")
+}
+func (b *Bridge) events(ctx context.Context, r *run) error {
+ q := url.Values{"limit": {"100"}, "order": {"asc"}}
+ if r.Page != "" {
+ q.Set("page", r.Page)
+ } else if r.Cursor != "" {
+ q.Set("after_id", r.Cursor)
+ }
+ var page struct {
+ Data []event `json:"data"`
+ HasMore bool `json:"has_more"`
+ NextPage string `json:"next_page"`
+ }
+ if err := b.qoder.call(ctx, http.MethodGet, "/sessions/"+url.PathEscape(r.SessionID)+"/events?"+q.Encode(), nil, &page); err != nil {
+ var ae *apiError
+ if errors.As(err, &ae) && ae.Status == http.StatusNotFound {
+ return b.reject(ctx, r, "Qoder session no longer exists")
+ }
+ return err
+ }
+ for _, e := range page.Data {
+ if e.ID == "" {
+ return fmt.Errorf("Qoder event has no ID")
+ }
+ if e.ID == r.Cursor {
+ continue
+ }
+ // A new session can emit an initial idle before the user message. Ignore it.
+ if e.Type == "user.message" && e.text() == r.Prompt {
+ r.Started = true
+ r.Phase = "running"
+ }
+ if !r.Started {
+ r.Cursor = e.ID
+ r.Page = ""
+ continue
+ }
+ msg := map[string]any{}
+ switch e.Type {
+ case "agent.message":
+ msg["type"] = "text"
+ msg["content"] = e.text()
+ r.Output = e.text()
+ case "agent.tool_use", "agent.mcp_tool_use":
+ msg["type"] = "tool_use"
+ msg["call_id"] = e.ID
+ msg["tool"] = e.Name
+ msg["input"] = e.Input
+ case "agent.tool_result", "agent.mcp_tool_result":
+ msg["type"] = "tool_result"
+ if e.ToolUseID != "" {
+ msg["call_id"] = e.ToolUseID
+ }
+ msg["output"] = e.text()
+ case "session.error":
+ msg["type"] = "error"
+ msg["content"] = e.Error.Message
+ if e.Error.RetryStatus.Type != "retrying" {
+ r.Failure = e.Error.Message
+ }
+ case "session.status_idle":
+ r.Phase = "final"
+ if e.StopReason.Type == "end_turn" && r.Failure == "" {
+ r.Outcome = "completed"
+ } else {
+ r.Outcome = "failed"
+ if r.Failure == "" {
+ r.Failure = "Qoder stopped: " + e.StopReason.Type
+ }
+ }
+ case "session.status_terminated", "session.deleted":
+ r.Phase = "final"
+ r.Outcome = "failed"
+ r.Failure = "Qoder session terminated"
+ }
+ if len(msg) > 0 {
+ msg["seq"] = r.Seq + 1
+ msg["idempotency_key"] = "qoder:" + e.ID
+ if err := b.taskCall(ctx, r, "/messages", map[string]any{"messages": []map[string]any{msg}}, nil); err != nil {
+ return err
+ }
+ r.Seq++
+ }
+ r.Cursor = e.ID
+ r.Page = ""
+ if err := b.persist(); err != nil {
+ return err
+ }
+ if r.Phase == "final" {
+ return b.deliver(ctx, r)
+ }
+ }
+ r.Page = ""
+ if page.HasMore {
+ if page.NextPage == "" || page.NextPage == q.Get("page") {
+ return fmt.Errorf("Qoder pagination cursor did not advance")
+ }
+ r.Page = page.NextPage
+ }
+ if err := b.persist(); err != nil {
+ return err
+ }
+ if r.Phase == "sending" {
+ return fmt.Errorf("submission not yet confirmed; inspect Qoder session %s before any manual resubmission", r.SessionID)
+ }
+ return nil
+}
diff --git a/server/internal/qoderruntime/http.go b/server/internal/qoderruntime/http.go
new file mode 100644
index 0000000000..1d87cc98fa
--- /dev/null
+++ b/server/internal/qoderruntime/http.go
@@ -0,0 +1,82 @@
+// Package qoderruntime bridges Multica's daemon task protocol to Qoder's managed sessions API.
+package qoderruntime
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+)
+
+type api struct {
+ base, token, workspace string
+ client *http.Client
+}
+type apiError struct{ Status int }
+
+func (e *apiError) Error() string { return fmt.Sprintf("remote API returned HTTP %d", e.Status) }
+
+func newAPI(base, token, workspace string) (*api, error) {
+ u, err := url.Parse(base)
+ if err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http") || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
+ return nil, fmt.Errorf("invalid API base URL")
+ }
+ if u.Scheme == "http" && u.Hostname() != "localhost" && u.Hostname() != "127.0.0.1" && u.Hostname() != "::1" {
+ return nil, fmt.Errorf("API base URL must use HTTPS except on loopback")
+ }
+ if strings.TrimSpace(token) == "" {
+ return nil, fmt.Errorf("API token is required")
+ }
+ return &api{base: strings.TrimRight(base, "/"), token: token, workspace: workspace, client: &http.Client{Timeout: 30 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil
+}
+
+// Errors deliberately omit remote bodies and URLs, which may echo credentials or task content.
+func (a *api) call(ctx context.Context, method, path string, in, out any) error {
+ var body io.Reader
+ if in != nil {
+ b, err := json.Marshal(in)
+ if err != nil {
+ return err
+ }
+ body = bytes.NewReader(b)
+ }
+ req, err := http.NewRequestWithContext(ctx, method, a.base+path, body)
+ if err != nil {
+ return fmt.Errorf("build API request: %w", err)
+ }
+ req.Header.Set("Authorization", "Bearer "+a.token)
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Accept", "application/json")
+ if a.workspace != "" {
+ req.Header.Set("X-Workspace-ID", a.workspace)
+ }
+ resp, err := a.client.Do(req)
+ if err != nil {
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ return fmt.Errorf("remote API transport failed")
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return &apiError{resp.StatusCode}
+ }
+ b, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20+1))
+ if err != nil {
+ return fmt.Errorf("read API response failed")
+ }
+ if len(b) > 8<<20 {
+ return fmt.Errorf("API response exceeds 8 MiB")
+ }
+ if out != nil {
+ if err := json.Unmarshal(b, out); err != nil {
+ return fmt.Errorf("invalid API JSON response")
+ }
+ }
+ return nil
+}
diff --git a/server/internal/qoderruntime/local_integration_test.go b/server/internal/qoderruntime/local_integration_test.go
new file mode 100644
index 0000000000..15ce83f348
--- /dev/null
+++ b/server/internal/qoderruntime/local_integration_test.go
@@ -0,0 +1,186 @@
+//go:build integration
+
+package qoderruntime
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+// TestLocalMultica exercises the actual authenticated HTTP router and database.
+// Qoder is a local fixture: no remote credentials, agent execution or quota.
+func TestLocalMultica(t *testing.T) {
+ path := os.Getenv("MULTICA_QODER_INTEGRATION_CONFIG")
+ if path == "" {
+ t.Skip("set MULTICA_QODER_INTEGRATION_CONFIG to a local bridge config")
+ }
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var cfg Config
+ if err = json.Unmarshal(raw, &cfg); err != nil {
+ t.Fatal("invalid integration config")
+ }
+ u, err := url.Parse(cfg.MulticaURL)
+ if err != nil || (u.Hostname() != "localhost" && u.Hostname() != "127.0.0.1") {
+ t.Fatal("integration test requires a loopback Multica server")
+ }
+ var mu sync.Mutex
+ var prompt string
+ creates, sends := 0, 0
+ q := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ defer mu.Unlock()
+ switch {
+ case r.URL.Path == "/sessions" && r.Method == http.MethodPost:
+ creates++
+ io.WriteString(w, `{"id":"sess_fixture"}`)
+ case strings.HasSuffix(r.URL.Path, "/events") && r.Method == http.MethodPost:
+ sends++
+ var req struct {
+ Events []event `json:"events"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ t.Error(err)
+ }
+ prompt = req.Events[0].text()
+ io.WriteString(w, `{}`)
+ case strings.HasSuffix(r.URL.Path, "/events"):
+ events := []map[string]any{
+ {"id": "evt_user", "type": "user.message", "content": []map[string]string{{"type": "text", "text": prompt}}},
+ {"id": "evt_result", "type": "agent.message", "content": []map[string]string{{"type": "text", "text": "Local bridge integration passed"}}},
+ {"id": "evt_idle", "type": "session.status_idle", "stop_reason": map[string]string{"type": "end_turn"}},
+ }
+ if r.URL.Query().Get("after_id") == "evt_user" {
+ events = events[1:]
+ }
+ json.NewEncoder(w).Encode(map[string]any{"data": events, "has_more": false})
+ case r.URL.Path == "/agents/agent_fixture":
+ io.WriteString(w, `{"id":"agent_fixture"}`)
+ case r.URL.Path == "/environments/env_fixture":
+ io.WriteString(w, `{"id":"env_fixture"}`)
+ default:
+ io.WriteString(w, `{}`)
+ }
+ }))
+ defer q.Close()
+ cfg.QoderURL = q.URL
+ cfg.QoderToken = "test-only"
+ cfg.EnvironmentID = "env_fixture"
+ cfg.StateDir = t.TempDir()
+ b, err := New(cfg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ b.state = &journal{Binding: "local-integration"}
+ if err = b.Check(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if err = b.register(ctx, strings.ReplaceAll(uuid.NewString(), "-", "")); err != nil {
+ t.Fatal(err)
+ }
+ cleanup := func(method, path string) {
+ t.Cleanup(func() {
+ if err := b.multica.call(context.Background(), method, path, map[string]any{}, nil); err != nil {
+ t.Errorf("cleanup %s failed: %v", path, err)
+ }
+ })
+ }
+ cleanup(http.MethodDelete, "/api/runtimes/"+b.state.RuntimeID)
+ var runtimes []struct {
+ ID string `json:"id"`
+ Mode string `json:"runtime_mode"`
+ }
+ if err = b.multica.call(ctx, http.MethodGet, "/api/runtimes/", nil, &runtimes); err != nil {
+ t.Fatal(err)
+ }
+ mode := ""
+ for _, rt := range runtimes {
+ if rt.ID == b.state.RuntimeID {
+ mode = rt.Mode
+ }
+ }
+ if mode != "cloud" {
+ t.Fatalf("registered runtime_mode=%s", mode)
+ }
+ var agent struct {
+ ID string `json:"id"`
+ }
+ if err = b.multica.call(ctx, http.MethodPost, "/api/agents/", map[string]any{"name": "Qoder fixture " + uuid.NewString(), "runtime_id": b.state.RuntimeID, "runtime_config": map[string]string{"qoder_agent_id": "agent_fixture"}, "instructions": "Return a concise result", "max_concurrent_tasks": 1}, &agent); err != nil {
+ t.Fatal(err)
+ }
+ cleanup(http.MethodPost, "/api/agents/"+agent.ID+"/archive")
+ var issue struct {
+ ID string `json:"id"`
+ }
+ if err = b.multica.call(ctx, http.MethodPost, "/api/issues/", map[string]any{"title": "Qoder bridge fixture " + uuid.NewString(), "description": "Validate remote execution", "status": "todo", "assignee_type": "agent", "assignee_id": agent.ID}, &issue); err != nil {
+ t.Fatal(err)
+ }
+ cleanup(http.MethodDelete, "/api/issues/"+issue.ID)
+ // Lose exactly one successful transcript response after the real server commits.
+ b.multica.client = &http.Client{Timeout: 10 * time.Second, Transport: &loseMessageResponse{base: http.DefaultTransport}}
+ err = b.step(ctx)
+ if err == nil || b.state.first() == nil {
+ t.Fatalf("expected lost message response, got err=%v", err)
+ }
+ taskID := b.state.first().TaskID
+ if err = b.step(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if b.state.first() != nil {
+ t.Fatalf("run did not finish: phase=%s failure=%s", b.state.first().Phase, b.state.first().Failure)
+ }
+ var status struct {
+ Status string `json:"status"`
+ }
+ if err = b.multica.call(ctx, http.MethodGet, "/api/daemon/tasks/"+taskID+"/status", nil, &status); err != nil {
+ t.Fatal(err)
+ }
+ if status.Status != "completed" {
+ t.Fatalf("task ended as %s", status.Status)
+ }
+ var messages []struct {
+ Content string `json:"content"`
+ }
+ if err = b.multica.call(ctx, http.MethodGet, "/api/tasks/"+taskID+"/messages", nil, &messages); err != nil {
+ t.Fatal(err)
+ }
+ if len(messages) != 1 || messages[0].Content != "Local bridge integration passed" {
+ t.Fatalf("transcript replay duplicated or lost output: %+v", messages)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if creates != 1 || sends != 1 {
+ t.Fatalf("remote execution duplicated: creates=%d sends=%d", creates, sends)
+ }
+}
+
+type loseMessageResponse struct {
+ base http.RoundTripper
+ lost bool
+}
+
+func (t *loseMessageResponse) RoundTrip(r *http.Request) (*http.Response, error) {
+ resp, err := t.base.RoundTrip(r)
+ if err == nil && r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/messages") && !t.lost {
+ t.lost = true
+ resp.Body.Close()
+ return nil, fmt.Errorf("injected lost response")
+ }
+ return resp, err
+}
diff --git a/server/internal/qoderruntime/lock_unix.go b/server/internal/qoderruntime/lock_unix.go
new file mode 100644
index 0000000000..216bd78575
--- /dev/null
+++ b/server/internal/qoderruntime/lock_unix.go
@@ -0,0 +1,30 @@
+//go:build !windows
+
+package qoderruntime
+
+import (
+ "fmt"
+ "golang.org/x/sys/unix"
+ "os"
+)
+
+func lockState(path string) (*os.File, error) {
+ f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0600)
+ if err != nil {
+ return nil, err
+ }
+ if err = unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil {
+ f.Close()
+ return nil, fmt.Errorf("bridge state is already locked: %w", err)
+ }
+ return f, nil
+}
+
+func syncStateDir(path string) error {
+ d, err := os.Open(path)
+ if err != nil {
+ return err
+ }
+ defer d.Close()
+ return d.Sync()
+}
diff --git a/server/internal/qoderruntime/lock_windows.go b/server/internal/qoderruntime/lock_windows.go
new file mode 100644
index 0000000000..05b968c0c2
--- /dev/null
+++ b/server/internal/qoderruntime/lock_windows.go
@@ -0,0 +1,22 @@
+package qoderruntime
+
+import (
+ "fmt"
+ "golang.org/x/sys/windows"
+ "os"
+)
+
+func lockState(path string) (*os.File, error) {
+ f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0600)
+ if err != nil {
+ return nil, err
+ }
+ if err = windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &windows.Overlapped{}); err != nil {
+ f.Close()
+ return nil, fmt.Errorf("bridge state is already locked: %w", err)
+ }
+ return f, nil
+}
+
+// Windows does not support fsync on directory handles opened by os.Open.
+func syncStateDir(string) error { return nil }
diff --git a/server/internal/qoderruntime/prompt.go b/server/internal/qoderruntime/prompt.go
new file mode 100644
index 0000000000..c27619d45f
--- /dev/null
+++ b/server/internal/qoderruntime/prompt.go
@@ -0,0 +1,195 @@
+package qoderruntime
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "regexp"
+ "strings"
+)
+
+func (b *Bridge) prepare(ctx context.Context, t *claimedTask) (*run, error) {
+ r := &run{TaskID: t.ID, Phase: "prepared", Resources: []map[string]any{}}
+ if t.RuntimeID != b.state.RuntimeID || t.WorkspaceID != b.cfg.WorkspaceID {
+ return nil, fmt.Errorf("claim identity does not match bridge")
+ }
+ if t.IssueID == "" || t.ChatSessionID != "" || t.IsLeaderTask {
+ return nil, fmt.Errorf("Qoder bridge currently supports issue runs only")
+ }
+ if !strings.HasPrefix(t.AuthToken, "mat_") {
+ return nil, fmt.Errorf("claim is missing a task-scoped credential")
+ }
+ if len(t.RemoteMCPConnections) > 0 || len(t.ConnectedApps) > 0 || len(t.PluginHookTools) > 0 {
+ return nil, fmt.Errorf("Multica connected apps and runtime MCP tools are not supported by the Qoder bridge")
+ }
+ if t.Agent != nil && (hasCustomSkills(t.Agent.Skills) || len(t.Agent.SkillRefs) > 0 || len(t.Agent.CustomEnv) > 0 || len(t.Agent.CustomArgs) > 0 || len(t.Agent.McpConfig) > 0 && string(t.Agent.McpConfig) != "null" && string(t.Agent.McpConfig) != "{}" || t.Agent.Model != "" || t.Agent.ThinkingLevel != "" || t.Agent.ServiceTier != "") {
+ return nil, fmt.Errorf("configure skills, tools, credentials and model on the Qoder Agent; Multica execution overrides are not supported by this bridge")
+ }
+ if t.Agent == nil {
+ return nil, fmt.Errorf("associate a QCA Agent in the Multica agent runtime configuration")
+ }
+ binding, err := ParseAgentConfig(t.Agent.RuntimeConfig)
+ if err != nil {
+ return nil, err
+ }
+ r.AgentID = binding.AgentID
+ taskAPI := *b.multica
+ taskAPI.token = t.AuthToken
+ var issue struct {
+ Title string `json:"title"`
+ Description string `json:"description"`
+ Attachments []json.RawMessage `json:"attachments"`
+ }
+ if err := taskAPI.call(ctx, http.MethodGet, "/api/issues/"+url.PathEscape(t.IssueID), nil, &issue); err != nil {
+ return nil, fmt.Errorf("read issue: %w", err)
+ }
+ if len(issue.Attachments) > 0 {
+ return nil, fmt.Errorf("issue attachments are not supported by the Qoder bridge")
+ }
+ var p strings.Builder
+ p.WriteString("Complete the following Multica issue in your Qoder environment. Return a final summary including code changes, tests and branch/PR/MR links when available. This bridge does not expose a local Multica daemon.\n")
+ if t.PriorSessionID != "" {
+ r.PriorSessionID = t.PriorSessionID
+ p.WriteString("This is a follow-up on the same issue. If the earlier conversation is not in your context, rely on the issue and comments below.\n")
+ }
+ fmt.Fprintf(&p, "\nRun: %s\nIssue: %s\n\n%s\n\n%s\n", t.ID, t.IssueIdentifier, issue.Title, issue.Description)
+ if t.IssueIdentifier != "" {
+ fmt.Fprintf(&p, "\nWhen you change code, push a new branch named %s (never the default branch), open a pull request whose title starts with \"%s: \", and put the pull request link in your final summary. Multica links the pull request to this issue through that identifier.\n", BranchName(t.IssueIdentifier, issue.Title), t.IssueIdentifier)
+ }
+ if t.Agent != nil {
+ fmt.Fprintf(&p, "\nAgent instructions:\n%s\n", t.Agent.Instructions)
+ }
+ fmt.Fprintf(&p, "\nWorkspace context:\n%s\n\nProject:\n%s\n%s\n", t.WorkspaceContext, t.ProjectTitle, t.ProjectDescription)
+ if t.HandoffNote != "" {
+ fmt.Fprintf(&p, "\nHandoff:\n%s\n", t.HandoffNote)
+ }
+ for _, c := range t.CoalescedComments {
+ fmt.Fprintf(&p, "\nComment by %s:\n%s\n", c.AuthorName, c.Content)
+ }
+ if t.TriggerCommentContent != "" {
+ fmt.Fprintf(&p, "\nTriggering comment by %s:\n%s\n", t.TriggerAuthorName, t.TriggerCommentContent)
+ }
+ for _, res := range t.ProjectResources {
+ if res.ResourceType == "local_directory" {
+ return nil, fmt.Errorf("local directory resources cannot be executed by Qoder Cloud Agent")
+ }
+ if res.ResourceType != "github_repo" {
+ continue
+ }
+ var ref Repository
+ if err := json.Unmarshal(res.ResourceRef, &ref); err != nil {
+ return nil, fmt.Errorf("invalid repository resource")
+ }
+ resource, err := repositoryResource(ref)
+ if err != nil {
+ return nil, err
+ }
+ r.Resources = append(r.Resources, resource)
+ if len(r.Resources) > 1 {
+ return nil, fmt.Errorf("Qoder Cloud Agent supports one project repository per run")
+ }
+ }
+ // Project repositories win; otherwise use the agent's default repository,
+ // and finally the workspace's only repository when it has a credential.
+ if len(r.Resources) == 0 && binding.Repository != nil && binding.Repository.URL != "" {
+ resource, err := repositoryResource(*binding.Repository)
+ if err != nil {
+ return nil, err
+ }
+ r.Resources = append(r.Resources, resource)
+ }
+ if len(r.Resources) == 0 && len(t.Repos) == 1 {
+ if resource, err := repositoryResource(Repository{URL: t.Repos[0].URL}); err == nil {
+ if _, err := b.sessionResources([]map[string]any{resource}); err == nil {
+ r.Resources = append(r.Resources, resource)
+ }
+ }
+ }
+ for _, repo := range t.Repos {
+ fmt.Fprintf(&p, "\nAvailable repository: %s (%s)\n", repo.URL, repo.Description)
+ }
+ r.Prompt = p.String()
+ return r, nil
+}
+
+// Repository is a GitHub repository and optional branch mounted into a session.
+type Repository struct {
+ URL string `json:"url"`
+ Ref string `json:"ref,omitempty"`
+}
+
+// AgentConfig is the runtime_config of a Multica agent bound to Qoder.
+type AgentConfig struct {
+ AgentID string `json:"qoder_agent_id"`
+ Repository *Repository `json:"repository,omitempty"`
+}
+
+// ParseAgentConfig validates the Qoder binding stored on a Multica agent.
+func ParseAgentConfig(raw json.RawMessage) (AgentConfig, error) {
+ var cfg AgentConfig
+ if err := json.Unmarshal(raw, &cfg); err != nil || !ValidAgentID(cfg.AgentID) {
+ return cfg, fmt.Errorf("associate a QCA Agent in the Multica agent runtime configuration")
+ }
+ if cfg.Repository != nil && cfg.Repository.URL != "" {
+ if _, err := repositoryResource(*cfg.Repository); err != nil {
+ return cfg, fmt.Errorf("default repository: %w", err)
+ }
+ }
+ return cfg, nil
+}
+
+var commitRef = regexp.MustCompile(`^[a-fA-F0-9]{40}([a-fA-F0-9]{24})?$`)
+
+func repositoryResource(ref Repository) (map[string]any, error) {
+ u, err := url.Parse(ref.URL)
+ if err != nil || u.Scheme != "https" || u.Hostname() != "github.com" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
+ return nil, fmt.Errorf("repositories must use an HTTPS github.com URL without credentials")
+ }
+ resource := map[string]any{"type": "github_repository", "url": ref.URL}
+ if strings.HasPrefix(ref.Ref, "refs/tags/") || commitRef.MatchString(ref.Ref) {
+ return nil, fmt.Errorf("Qoder Cloud Agent supports branch refs only")
+ }
+ if name := strings.TrimPrefix(ref.Ref, "refs/heads/"); name != "" {
+ resource["checkout"] = map[string]string{"type": "branch", "name": name}
+ }
+ return resource, nil
+}
+
+var nonSlug = regexp.MustCompile(`[^a-z0-9]+`)
+
+// BranchName gives remote work a branch Multica's GitHub integration links back
+// to the issue: the identifier must appear in the branch name.
+func BranchName(identifier, title string) string {
+ slug := strings.Trim(nonSlug.ReplaceAllString(strings.ToLower(title), "-"), "-")
+ if len(slug) > 40 {
+ slug = slug[:41]
+ if i := strings.LastIndex(slug, "-"); i > 0 {
+ slug = slug[:i]
+ } else {
+ slug = slug[:40]
+ }
+ }
+ branch := "multica/" + strings.ToLower(identifier)
+ if slug != "" {
+ branch += "-" + slug
+ }
+ return branch
+}
+
+// Built-in platform skills have no ID and assume local CLI tools. Do not inject
+// those tools into a managed Qoder session; custom skills must be configured there.
+func hasCustomSkills(skills []claimedSkill) bool {
+ for _, s := range skills {
+ if s.ID != "" {
+ return true
+ }
+ }
+ return false
+}
+
+// ValidAgentID validates the public QCA identifier without accepting URL fragments.
+func ValidAgentID(id string) bool {
+ return regexp.MustCompile(`^agent_[a-zA-Z0-9_-]{1,128}$`).MatchString(id)
+}
diff --git a/server/internal/qoderruntime/state.go b/server/internal/qoderruntime/state.go
new file mode 100644
index 0000000000..fc4cfb64cc
--- /dev/null
+++ b/server/internal/qoderruntime/state.go
@@ -0,0 +1,151 @@
+package qoderruntime
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "time"
+)
+
+// One journal belongs to exactly one bridge configuration and holds every
+// active run, bounded by the connection's concurrency limit. Credentials are
+// never persisted. Keep this directory on persistent storage.
+type journal struct {
+ Binding string `json:"binding"`
+ RuntimeID string `json:"runtime_id"`
+ Cleanup []string `json:"cleanup,omitempty"`
+ Runs []*run `json:"runs,omitempty"`
+ // Run is the single-run format written before concurrency; decode folds it into Runs.
+ Run *run `json:"run,omitempty"`
+}
+type run struct {
+ // PriorSessionID is the session of this agent's previous run on the issue.
+ // An idle prior session is continued instead of creating a new one.
+ PriorSessionID string `json:"prior_session_id,omitempty"`
+ Continued bool `json:"continued,omitempty"`
+ Deadline time.Time `json:"deadline"`
+ SubmissionDeadline time.Time `json:"submission_deadline,omitempty"`
+ RetryAt time.Time `json:"retry_at,omitempty"`
+ AgentID string `json:"agent_id,omitempty"`
+ Page string `json:"page,omitempty"`
+ TaskID string `json:"task_id"`
+ SessionID string `json:"session_id,omitempty"`
+ Prompt string `json:"prompt,omitempty"`
+ Resources []map[string]any `json:"resources,omitempty"`
+ Phase string `json:"phase"`
+ Cursor string `json:"cursor,omitempty"`
+ Seq int `json:"seq"`
+ Started bool `json:"started"`
+ Output string `json:"output,omitempty"`
+ Failure string `json:"failure,omitempty"`
+ Outcome string `json:"outcome,omitempty"`
+}
+
+func save(path string, j *journal) error {
+ b, err := json.Marshal(j)
+ if err != nil {
+ return err
+ }
+ f, err := os.CreateTemp(filepath.Dir(path), ".qoder-state-*")
+ if err != nil {
+ return err
+ }
+ defer os.Remove(f.Name())
+ if _, err = f.Write(b); err != nil {
+ f.Close()
+ return err
+ }
+ if err = f.Sync(); err != nil {
+ f.Close()
+ return err
+ }
+ if err = f.Close(); err != nil {
+ return err
+ }
+ if err = os.Rename(f.Name(), path); err != nil {
+ return err
+ }
+ return syncStateDir(filepath.Dir(path))
+}
+func readJournal(path, binding string) (*journal, error) {
+ b, err := os.ReadFile(path)
+ if os.IsNotExist(err) {
+ return &journal{Binding: binding}, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return decodeJournal(b, binding)
+}
+func decodeJournal(b []byte, binding string) (*journal, error) {
+ if len(b) == 0 {
+ return &journal{Binding: binding}, nil
+ }
+ var j journal
+ if err := json.Unmarshal(b, &j); err != nil {
+ return nil, fmt.Errorf("invalid bridge journal: %w", err)
+ }
+ if j.Binding != binding {
+ return nil, fmt.Errorf("state directory belongs to a different bridge configuration")
+ }
+ if j.Binding == "" {
+ j.Binding = binding
+ }
+ if j.Run != nil {
+ j.Runs = append(j.Runs, j.Run)
+ j.Run = nil
+ }
+ seen := map[string]bool{}
+ for _, r := range j.Runs {
+ if r == nil || r.TaskID == "" {
+ return nil, fmt.Errorf("bridge journal has no task ID")
+ }
+ if seen[r.TaskID] {
+ return nil, fmt.Errorf("bridge journal has a duplicate task")
+ }
+ seen[r.TaskID] = true
+ switch r.Phase {
+ case "prepared", "creating", "final":
+ case "created", "sending", "running":
+ if r.SessionID == "" {
+ return nil, fmt.Errorf("bridge journal has no session ID")
+ }
+ default:
+ return nil, fmt.Errorf("unknown bridge journal phase")
+ }
+ }
+ return &j, nil
+}
+
+func (j *journal) remove(r *run) {
+ for i, existing := range j.Runs {
+ if existing == r {
+ j.Runs = append(j.Runs[:i], j.Runs[i+1:]...)
+ return
+ }
+ }
+}
+
+type persistenceError struct{ err error }
+
+func (e *persistenceError) Error() string { return "persist bridge journal: " + e.err.Error() }
+func (b *Bridge) persist() error {
+ if b.cfg.SaveState != nil {
+ raw, err := json.Marshal(b.state)
+ if err != nil {
+ return &persistenceError{err}
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ if err := b.cfg.SaveState(ctx, raw); err != nil {
+ return &persistenceError{err}
+ }
+ return nil
+ }
+ if err := save(b.path, b.state); err != nil {
+ return &persistenceError{err}
+ }
+ return nil
+}
diff --git a/server/internal/service/builtin_skills/multica-platform/references/runtimes.md b/server/internal/service/builtin_skills/multica-platform/references/runtimes.md
index dd42ec56e9..3ec4b80f84 100644
--- a/server/internal/service/builtin_skills/multica-platform/references/runtimes.md
+++ b/server/internal/service/builtin_skills/multica-platform/references/runtimes.md
@@ -174,3 +174,60 @@ Workspace repos and project resources are not the same thing:
Do not add a project resource just because `repo checkout` failed. First
determine whether the user asked for durable project context or just a task
checkout.
+
+## Qoder Cloud Agent bridge (PoC)
+
+A server-hosted `qoder-runtime` service can register the `qoder_cloud` provider.
+Bind a Multica agent to the runtime and set its `runtime_config.qoder_agent_id` to the selected QCA Agent ID. The Web/Desktop agent creation form and runtime configuration tab provide a name-based QCA Agent picker.
+The bridge executes issue runs through Qoder's managed session API; it does not
+run a local coding-agent CLI. Model, tools, skills and credentials are configured
+on Qoder. Local-directory resources and Multica execution overrides are rejected.
+
+Each run's session ID is pinned to the Multica run. A follow-up run on the same
+issue continues the agent's previous session when it is idle; otherwise a fresh
+session starts. The prompt asks the agent to push a `multica/<identifier>-<slug>`
+branch and prefix the pull request title with the issue identifier, so the GitHub
+integration links the pull request. The service needs persistent state for
+restart recovery. Cancel from Multica to stop remote
+work; stopping the bridge process alone leaves remote execution running. Do not
+use `runtime update` to upgrade the bridge: deploy its binary through its service
+manager. For setup and recovery, consult the Qoder Cloud Agent section of the
+Multica runtime documentation or ask the deployment administrator.
+
+The bridge registers `runtime_mode=cloud`. Other daemons may omit
+`runtimes[].runtime_mode` to retain local registration; custom CLI profiles
+remain local. `qoder-runtime --config <private-config.json> --check` verifies
+workspace and Qoder resource access without starting execution.
+
+Daemon `/tasks/{taskId}/messages` requests may include an `idempotency_key`
+(maximum 512 bytes) per message. Keys are scoped to a run: repeated keys retain
+the first persisted payload and do not rebroadcast it. Omitted keys preserve
+append-only behavior. The Qoder bridge uses its remote event IDs as these keys.
+
+Qoder Cloud bridge repository runs require `github_token_files` in its private JSON configuration, mapping each GitHub repository URL to a 0600 token file. Credentials are injected only into session creation requests, never into prompts or recovery state. Managed connections also support repository credential configuration in the runtime dialog.
+
+Workspace admins may also configure one managed QCA connection in **Runtimes →
+Add remote runtime → Qoder Cloud Agent** (web and desktop). The server prerequisite is
+`MULTICA_VCS_SECRET_KEY`. The server
+supervises the bridge, encrypts credentials in the database, and supports idle
+stop/restart. Active tasks must finish or be cancelled before configuration
+changes. `GET/PUT /api/workspaces/{id}/qoder`, `POST .../qoder/check`, and
+`POST .../qoder/stop` expose this flow; writes/checks are admin-only and no
+credential plaintext is returned. Blank secrets retain saved values; an empty
+`github_tokens` object removes all repository credentials. `max_concurrency`
+(1–10, default 3) bounds simultaneous runs, with extra tasks queued in Multica;
+`run_timeout_minutes` (5–240, default 60) bounds each run. `GET` also reports
+`active_runs` and `queued_runs`.
+
+
+Managed runtimes store the QCA PAT and selected environment. Entering a PAT loads
+available environments automatically; a single environment is selected by default.
+`POST .../qoder/environments` lists environments using an entered or saved PAT
+(admin-only). `GET .../qoder/agents` lists names and IDs using the saved PAT for
+workspace members. Lists exclude archived resources. Each Multica agent stores its
+own `runtime_config.qoder_agent_id`; each run uses that association and the
+shared runtime's environment. An optional `runtime_config.repository`
+(`{"url": "https://github.com/owner/repo", "ref": "main"}`) is mounted when the
+issue's project binds no repository; the workspace's only repository is the last
+fallback when the connection holds its credential. QCA model/tool/skill
+management remains in Qoder.
diff --git a/server/internal/service/qoder_issue_lifecycle.go b/server/internal/service/qoder_issue_lifecycle.go
new file mode 100644
index 0000000000..d710969b74
--- /dev/null
+++ b/server/internal/service/qoder_issue_lifecycle.go
@@ -0,0 +1,84 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+)
+
+type qoderIssueChange struct {
+ issue db.Issue
+ previous string
+ activity wakeupActivity
+}
+
+// syncQoderIssue runs inside the task transition transaction. Only a status
+// this run took ownership of can advance to review. A revision mismatch also
+// protects edits away and back, reassignment, and concurrent human decisions.
+func syncQoderIssue(ctx context.Context, q *db.Queries, task db.AgentTaskQueue, completing bool) (*qoderIssueChange, error) {
+ if !task.IssueID.Valid || !task.RuntimeID.Valid {
+ return nil, nil
+ }
+ issue, err := q.LockQoderTaskIssue(ctx, task.ID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ target := "in_progress"
+ if completing {
+ var marker struct {
+ Revision int64 `json:"qoder_issue_revision"`
+ }
+ if err := json.Unmarshal(task.Context, &marker); err != nil {
+ return nil, nil
+ }
+ if marker.Revision == 0 || marker.Revision != issue.Revision || issue.Status != "in_progress" {
+ return nil, nil
+ }
+ target = "in_review"
+ } else {
+ // Clear any caller-provided marker before deciding whether to own this run.
+ if err := q.SetQoderIssueRevision(ctx, db.SetQoderIssueRevisionParams{TaskID: task.ID, Revision: 0}); err != nil {
+ return nil, err
+ }
+ // Custom workflow columns, triage, review and terminal issues stay untouched.
+ if issue.TriageState.Valid || (issue.Status != "todo" && issue.Status != "backlog") {
+ return nil, nil
+ }
+ }
+ updated, err := q.UpdateIssueStatus(ctx, db.UpdateIssueStatusParams{
+ ID: issue.ID, WorkspaceID: issue.WorkspaceID, Status: target, SourceTaskID: task.ID,
+ })
+ if err != nil {
+ return nil, err
+ }
+ if !completing {
+ if err := q.SetQoderIssueRevision(ctx, db.SetQoderIssueRevisionParams{TaskID: task.ID, Revision: updated.Revision}); err != nil {
+ return nil, err
+ }
+ }
+ details, _ := json.Marshal(map[string]any{"from": issue.Status, "to": target, "source": "qoder_cloud", "task_id": util.UUIDToString(task.ID)})
+ activity, err := q.CreateActivity(ctx, db.CreateActivityParams{
+ ID: dbid.NewV7(), WorkspaceID: issue.WorkspaceID, IssueID: issue.ID,
+ ActorType: util.StrToText("agent"), ActorID: task.AgentID, Action: "status_changed", Details: details,
+ })
+ if err != nil {
+ return nil, err
+ }
+ return &qoderIssueChange{issue: updated, previous: issue.Status, activity: wakeupActivity{row: activity, actorType: "agent", actorID: util.UUIDToString(task.AgentID), details: details}}, nil
+}
+
+func (s *TaskService) publishQoderIssueChange(ctx context.Context, change *qoderIssueChange) {
+ if change == nil || s.Bus == nil {
+ return
+ }
+ s.broadcastIssueUpdated(ctx, change.issue, change.previous)
+ (&IssueWakeupService{Tasks: s}).publishWakeupActivities(change.activity)
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 1dc8d4184a..e2bf651cad 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -4204,16 +4204,24 @@ func (s *TaskService) maybeLogClaimSlow(agentID pgtype.UUID, outcome string, sta
}
// StartTask transitions a dispatched task to running.
-// Issue status is NOT changed here — the agent manages it via the CLI.
+// Local agents manage issue status via the CLI; Qoder runs use guarded server transitions.
func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID, supplementSupport ...bool) (*db.AgentTaskQueue, error) {
enableTaskSupplement := len(supplementSupport) > 0 && supplementSupport[0]
- task, err := s.Queries.StartAgentTaskWithSupplement(ctx, db.StartAgentTaskWithSupplementParams{
- TaskID: taskID,
- EnableTaskSupplement: enableTaskSupplement,
+ var task db.AgentTaskQueue
+ var change *qoderIssueChange
+ err := s.runInTx(ctx, func(q *db.Queries) error {
+ var err error
+ task, err = q.StartAgentTaskWithSupplement(ctx, db.StartAgentTaskWithSupplementParams{TaskID: taskID, EnableTaskSupplement: enableTaskSupplement})
+ if err != nil {
+ return err
+ }
+ change, err = syncQoderIssue(ctx, q, task, false)
+ return err
})
if err != nil {
return nil, fmt.Errorf("start task: %w", err)
}
+ s.publishQoderIssueChange(ctx, change)
s.taskStarted(ctx, task)
return &task, nil
}
@@ -4235,6 +4243,7 @@ func (s *TaskService) StartTaskForClaim(ctx context.Context, claim db.LockAgentT
if err != nil {
return nil, fmt.Errorf("lock task start claim: %w", err)
}
+ var change *qoderIssueChange
replay := task.Status == "running"
if !replay {
task, err = qtx.StartAgentTaskWithSupplement(ctx, db.StartAgentTaskWithSupplementParams{
@@ -4245,9 +4254,16 @@ func (s *TaskService) StartTaskForClaim(ctx context.Context, claim db.LockAgentT
return nil, fmt.Errorf("start claimed task: %w", err)
}
}
+ if !replay {
+ change, err = syncQoderIssue(ctx, qtx, task, false)
+ if err != nil {
+ return nil, err
+ }
+ }
if err := tx.Commit(ctx); err != nil {
return nil, fmt.Errorf("commit task start: %w", err)
}
+ s.publishQoderIssueChange(ctx, change)
if !replay {
s.taskStarted(ctx, task)
}
@@ -4412,6 +4428,7 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
// terminal task is still an idempotent success but must not emit them again.
func (s *TaskService) CompleteTaskWithTransition(ctx context.Context, taskID pgtype.UUID, result []byte, sessionID, workDir, branchName string, sessionRolloutMissing bool, retiredSessionID, durableWorkDir string) (*db.AgentTaskQueue, bool, error) {
var task db.AgentTaskQueue
+ var change *qoderIssueChange
// chatAssistantMsg is the single assistant outcome row written for a chat
// task inside the completion transaction below. It is broadcast (chat:done)
// only after the transaction commits.
@@ -4434,6 +4451,10 @@ func (s *TaskService) CompleteTaskWithTransition(ctx context.Context, taskID pgt
return err
}
task = t
+ change, err = syncQoderIssue(ctx, qtx, t, true)
+ if err != nil {
+ return err
+ }
// Atomic with the status flip: a crash between the two would leave a
// finished obligation looking pending forever.
@@ -4521,6 +4542,7 @@ func (s *TaskService) CompleteTaskWithTransition(ctx context.Context, taskID pgt
return nil, false, fmt.Errorf("complete task: %w", err)
}
+ s.publishQoderIssueChange(ctx, change)
slog.Info("task completed", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID))
s.captureTaskCompleted(ctx, task)
diff --git a/server/migrations/586_cloud_agent_connection.down.sql b/server/migrations/586_cloud_agent_connection.down.sql
new file mode 100644
index 0000000000..9a88323a02
--- /dev/null
+++ b/server/migrations/586_cloud_agent_connection.down.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS cloud_agent_connection;
diff --git a/server/migrations/586_cloud_agent_connection.up.sql b/server/migrations/586_cloud_agent_connection.up.sql
new file mode 100644
index 0000000000..ee97e6146e
--- /dev/null
+++ b/server/migrations/586_cloud_agent_connection.up.sql
@@ -0,0 +1,16 @@
+-- One managed cloud-agent provider connection per workspace and provider.
+-- Secrets and the run journal are sealed with MULTICA_VCS_SECRET_KEY.
+CREATE TABLE cloud_agent_connection (
+ workspace_id uuid NOT NULL,
+ provider text NOT NULL,
+ owner_id uuid NOT NULL,
+ token_id uuid NOT NULL,
+ config_encrypted text NOT NULL,
+ journal_encrypted text NOT NULL DEFAULT '',
+ enabled boolean NOT NULL DEFAULT true,
+ revision bigint NOT NULL DEFAULT 1,
+ status text NOT NULL DEFAULT 'starting',
+ last_error text NOT NULL DEFAULT '',
+ busy_until timestamptz,
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
diff --git a/server/migrations/587_cloud_agent_connection_provider_index.down.sql b/server/migrations/587_cloud_agent_connection_provider_index.down.sql
new file mode 100644
index 0000000000..9f4839c950
--- /dev/null
+++ b/server/migrations/587_cloud_agent_connection_provider_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS cloud_agent_connection_provider_index;
diff --git a/server/migrations/587_cloud_agent_connection_provider_index.up.sql b/server/migrations/587_cloud_agent_connection_provider_index.up.sql
new file mode 100644
index 0000000000..3a92fe33ee
--- /dev/null
+++ b/server/migrations/587_cloud_agent_connection_provider_index.up.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX CONCURRENTLY cloud_agent_connection_provider_index ON cloud_agent_connection (workspace_id, provider);
diff --git a/server/pkg/agent/hermes_escaped_holder_unix_test.go b/server/pkg/agent/hermes_escaped_holder_unix_test.go
index 597d4c6bfa..c455de3d29 100644
--- a/server/pkg/agent/hermes_escaped_holder_unix_test.go
+++ b/server/pkg/agent/hermes_escaped_holder_unix_test.go
@@ -55,9 +55,15 @@ func TestHermesEscapedPipeHolderHelper(t *testing.T) {
if _, err := syscall.Setsid(); err != nil {
t.Fatalf("setsid: %v", err)
}
- if err := os.WriteFile(statePath, []byte(fmt.Sprintf("%d %d", os.Getpid(), syscall.Getpgrp())), 0o600); err != nil {
+ // Both readers use file existence as the ready signal. Publish only after
+ // the full identity is written, so neither can observe an empty file.
+ pendingPath := statePath + ".pending"
+ if err := os.WriteFile(pendingPath, []byte(fmt.Sprintf("%d %d", os.Getpid(), syscall.Getpgrp())), 0o600); err != nil {
t.Fatalf("record holder identity: %v", err)
}
+ if err := os.Rename(pendingPath, statePath); err != nil {
+ t.Fatalf("publish holder identity: %v", err)
+ }
time.Sleep(hermesEscapedHolderLifetime)
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index acda1380bc..c56adb8151 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -585,6 +585,21 @@ type ClientUsageDaily struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
+type CloudAgentConnection struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Provider string `json:"provider"`
+ OwnerID pgtype.UUID `json:"owner_id"`
+ TokenID pgtype.UUID `json:"token_id"`
+ ConfigEncrypted string `json:"config_encrypted"`
+ JournalEncrypted string `json:"journal_encrypted"`
+ Enabled bool `json:"enabled"`
+ Revision int64 `json:"revision"`
+ Status string `json:"status"`
+ LastError string `json:"last_error"`
+ BusyUntil pgtype.Timestamptz `json:"busy_until"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
type Comment struct {
ID pgtype.UUID `json:"id"`
IssueID pgtype.UUID `json:"issue_id"`
diff --git a/server/pkg/db/generated/qoder_issue_lifecycle.sql.go b/server/pkg/db/generated/qoder_issue_lifecycle.sql.go
new file mode 100644
index 0000000000..329b516d6b
--- /dev/null
+++ b/server/pkg/db/generated/qoder_issue_lifecycle.sql.go
@@ -0,0 +1,80 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: qoder_issue_lifecycle.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const lockQoderTaskIssue = `-- name: LockQoderTaskIssue :one
+SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties, i.revision, i.last_activity_at, i.triage_state, i.duplicate_of_issue_id FROM issue i
+JOIN agent_task_queue t ON t.issue_id = i.id
+JOIN agent_runtime r ON r.id = t.runtime_id AND r.workspace_id = i.workspace_id
+WHERE t.id = $1 AND r.provider = 'qoder_cloud'
+ AND i.assignee_type = 'agent' AND i.assignee_id = t.agent_id
+ AND NOT EXISTS (
+ SELECT 1 FROM agent_task_queue newer
+ WHERE newer.issue_id = i.id AND (newer.created_at, newer.id) > (t.created_at, t.id)
+ )
+FOR UPDATE OF i
+`
+
+// The task row is locked by the lifecycle transition before locking its issue.
+func (q *Queries) LockQoderTaskIssue(ctx context.Context, taskID pgtype.UUID) (Issue, error) {
+ row := q.db.QueryRow(ctx, lockQoderTaskIssue, taskID)
+ var i Issue
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Title,
+ &i.Description,
+ &i.Status,
+ &i.Priority,
+ &i.AssigneeType,
+ &i.AssigneeID,
+ &i.CreatorType,
+ &i.CreatorID,
+ &i.ParentIssueID,
+ &i.AcceptanceCriteria,
+ &i.ContextRefs,
+ &i.Position,
+ &i.DueDate,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Number,
+ &i.ProjectID,
+ &i.OriginType,
+ &i.OriginID,
+ &i.FirstExecutedAt,
+ &i.StartDate,
+ &i.Metadata,
+ &i.Stage,
+ &i.Properties,
+ &i.Revision,
+ &i.LastActivityAt,
+ &i.TriageState,
+ &i.DuplicateOfIssueID,
+ )
+ return i, err
+}
+
+const setQoderIssueRevision = `-- name: SetQoderIssueRevision :exec
+UPDATE agent_task_queue SET context = jsonb_set(
+ COALESCE(context, '{}'::jsonb), '{qoder_issue_revision}', to_jsonb($1::bigint)
+) WHERE id = $2
+`
+
+type SetQoderIssueRevisionParams struct {
+ Revision int64 `json:"revision"`
+ TaskID pgtype.UUID `json:"task_id"`
+}
+
+func (q *Queries) SetQoderIssueRevision(ctx context.Context, arg SetQoderIssueRevisionParams) error {
+ _, err := q.db.Exec(ctx, setQoderIssueRevision, arg.Revision, arg.TaskID)
+ return err
+}
diff --git a/server/pkg/db/generated/task_message.sql.go b/server/pkg/db/generated/task_message.sql.go
index a0c7dac254..76325bdea7 100644
--- a/server/pkg/db/generated/task_message.sql.go
+++ b/server/pkg/db/generated/task_message.sql.go
@@ -93,6 +93,7 @@ WITH incoming AS (
NULLIF(m.output_truncated, '')::bool,
NULLIF(m.call_id, '')
FROM incoming AS m
+ ON CONFLICT (id) DO NOTHING
RETURNING id, task_id, seq, type, tool, content, input, output, created_at, output_truncated, call_id
)
SELECT id, task_id, seq, type, tool, content, input, output, created_at, output_truncated, call_id FROM inserted ORDER BY seq ASC
@@ -160,8 +161,9 @@ type CreateTaskMessagesRow struct {
// loop this replaces could persist part of a batch and then fail, leaving the
// transcript with a prefix of the batch and no way to complete it — the daemon
// does not retry this endpoint. One statement makes the batch all-or-nothing,
-// which buys consistency; a batch that fails is still lost whole, so closing
-// the gap for real needs a retry plus a (task_id, seq) uniqueness rule.
+// which buys consistency. Callers that supply a task-scoped idempotency key
+// derive a stable message UUID; the primary-key conflict below deduplicates
+// retries without changing the append-only behavior of legacy random IDs.
//
// The ORDER BY is a contract, not decoration. A bare `INSERT ... RETURNING`
// has no defined row order, and the caller republishes these rows as realtime
diff --git a/server/pkg/db/queries/qoder_issue_lifecycle.sql b/server/pkg/db/queries/qoder_issue_lifecycle.sql
new file mode 100644
index 0000000000..9d44cef134
--- /dev/null
+++ b/server/pkg/db/queries/qoder_issue_lifecycle.sql
@@ -0,0 +1,17 @@
+-- name: LockQoderTaskIssue :one
+-- The task row is locked by the lifecycle transition before locking its issue.
+SELECT i.* FROM issue i
+JOIN agent_task_queue t ON t.issue_id = i.id
+JOIN agent_runtime r ON r.id = t.runtime_id AND r.workspace_id = i.workspace_id
+WHERE t.id = sqlc.arg('task_id') AND r.provider = 'qoder_cloud'
+ AND i.assignee_type = 'agent' AND i.assignee_id = t.agent_id
+ AND NOT EXISTS (
+ SELECT 1 FROM agent_task_queue newer
+ WHERE newer.issue_id = i.id AND (newer.created_at, newer.id) > (t.created_at, t.id)
+ )
+FOR UPDATE OF i;
+
+-- name: SetQoderIssueRevision :exec
+UPDATE agent_task_queue SET context = jsonb_set(
+ COALESCE(context, '{}'::jsonb), '{qoder_issue_revision}', to_jsonb(sqlc.arg('revision')::bigint)
+) WHERE id = sqlc.arg('task_id');
diff --git a/server/pkg/db/queries/task_message.sql b/server/pkg/db/queries/task_message.sql
index 237c191fff..be4338e760 100644
--- a/server/pkg/db/queries/task_message.sql
+++ b/server/pkg/db/queries/task_message.sql
@@ -38,8 +38,9 @@ RETURNING *;
-- loop this replaces could persist part of a batch and then fail, leaving the
-- transcript with a prefix of the batch and no way to complete it — the daemon
-- does not retry this endpoint. One statement makes the batch all-or-nothing,
--- which buys consistency; a batch that fails is still lost whole, so closing
--- the gap for real needs a retry plus a (task_id, seq) uniqueness rule.
+-- which buys consistency. Callers that supply a task-scoped idempotency key
+-- derive a stable message UUID; the primary-key conflict below deduplicates
+-- retries without changing the append-only behavior of legacy random IDs.
--
-- The ORDER BY is a contract, not decoration. A bare `INSERT ... RETURNING`
-- has no defined row order, and the caller republishes these rows as realtime
@@ -79,6 +80,7 @@ WITH incoming AS (
NULLIF(m.output_truncated, '')::bool,
NULLIF(m.call_id, '')
FROM incoming AS m
+ ON CONFLICT (id) DO NOTHING
RETURNING *
)
SELECT * FROM inserted ORDER BY seq ASC;