Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9142: fix(zcode): run Linux desktop CLI headlessly (#10476)
Bohan Jiangdb3aafc4c4f6
diff --git a/apps/docs/content/docs/install-agent-runtime.fr.mdx b/apps/docs/content/docs/install-agent-runtime.fr.mdxindex f2f9fefe01..7b0e8557de 100644--- a/apps/docs/content/docs/install-agent-runtime.fr.mdx+++ b/apps/docs/content/docs/install-agent-runtime.fr.mdx@@ -216,4 +216,4 @@ Si l'outil apparaît en ligne mais que les exécutions échouent toujours, ouvre- [Daemon et runtimes](/daemon-runtimes) — statut en ligne, parallélisme et runtimes personnalisés.- [Comparatif des outils de codage IA](/providers) — comparer ce que chaque outil peut faire dans Multica.-Sur macOS, ZCode Desktop est détecté depuis son bundle d'application. Installez Node.js et activez une connexion API fonctionnelle dans l'application. Les choix de modèle et de raisonnement viennent de ZCode ; voir [la comparaison des outils](/providers#zcode).+Sur macOS, ZCode Desktop est détecté depuis son bundle d'application et nécessite Node.js. Sur Linux, le daemon détecte ZCode Desktop via `zcode` dans le PATH ou `/opt/ZCode/zcode` et exécute son CLI intégré sans ouvrir de fenêtre. Sur Linux, aucune installation séparée de Node.js ni configuration manuelle de variables d'environnement n'est nécessaire. Activez une connexion API fonctionnelle dans l'application. Les choix de modèle et de raisonnement viennent de ZCode ; voir [la comparaison des outils](/providers#zcode).diff --git a/apps/docs/content/docs/install-agent-runtime.ja.mdx b/apps/docs/content/docs/install-agent-runtime.ja.mdxindex aca16f1eed..1c610b9946 100644--- a/apps/docs/content/docs/install-agent-runtime.ja.mdx+++ b/apps/docs/content/docs/install-agent-runtime.ja.mdx@@ -216,4 +216,4 @@ Multica Desktop を終了して開き直してください。- [デーモンとランタイム](/daemon-runtimes) — オンライン状態、同時実行、カスタムランタイムについて確認する- [AI コーディングツール比較](/providers) — Multica で使える機能をツールごとに比較する-macOS の ZCode Desktop はアプリケーションバンドルから自動検出されます。Node.js をインストールし、デスクトップアプリで利用可能な API 接続を有効にしてください。モデルと推論レベルの選択肢は ZCode が提供します。[ツールの比較](/providers#zcode)を参照してください。+macOS の ZCode Desktop はアプリケーションバンドルから自動検出され、Node.js のインストールが必要です。Linux では、デーモンが PATH 上の `zcode` または `/opt/ZCode/zcode` から ZCode Desktop を自動検出し、デスクトップウィンドウを開かずに同梱 CLI を実行します。Linux では Node.js の追加インストールや環境変数の手動設定は不要です。デスクトップアプリで利用可能な API 接続を有効にしてください。モデルと推論レベルの選択肢は ZCode が提供します。[ツールの比較](/providers#zcode)を参照してください。diff --git a/apps/docs/content/docs/install-agent-runtime.ko.mdx b/apps/docs/content/docs/install-agent-runtime.ko.mdxindex 11c7848d75..88a90046dc 100644--- a/apps/docs/content/docs/install-agent-runtime.ko.mdx+++ b/apps/docs/content/docs/install-agent-runtime.ko.mdx@@ -216,4 +216,4 @@ Multica Desktop을 종료한 뒤 다시 엽니다.- [데몬과 런타임](/daemon-runtimes) — 온라인 상태, 동시 실행, 사용자 지정 런타임을 알아봅니다.- [AI 코딩 도구 비교](/providers) — Multica에서 도구별 기능을 비교합니다.-macOS의 ZCode Desktop은 앱 번들에서 자동으로 감지됩니다. Node.js를 설치하고 데스크톱 앱에서 작동하는 API 연결을 활성화하세요. 모델과 추론 수준 선택지는 ZCode에서 제공합니다. [도구 비교](/providers#zcode)를 참고하세요.+macOS의 ZCode Desktop은 앱 번들에서 자동으로 감지되며 Node.js가 설치되어 있어야 합니다. Linux에서는 데몬이 PATH의 `zcode` 또는 `/opt/ZCode/zcode`를 통해 ZCode Desktop을 자동으로 감지하고 데스크톱 창을 열지 않고 내장 CLI를 실행합니다. Linux에서는 Node.js를 별도로 설치하거나 환경 변수를 직접 설정할 필요가 없습니다. 데스크톱 앱에서 작동하는 API 연결을 활성화하세요. 모델과 추론 수준 선택지는 ZCode에서 제공합니다. [도구 비교](/providers#zcode)를 참고하세요.diff --git a/apps/docs/content/docs/install-agent-runtime.mdx b/apps/docs/content/docs/install-agent-runtime.mdxindex 17a829e830..cad5147309 100644--- a/apps/docs/content/docs/install-agent-runtime.mdx+++ b/apps/docs/content/docs/install-agent-runtime.mdx@@ -236,4 +236,4 @@ If the tool shows as online but runs still fail, open the issue's run record to- [Daemon and runtimes](/daemon-runtimes) — online status, concurrency, and custom runtimes.- [AI coding tools comparison](/providers) — compare what each tool can do in Multica.-ZCode Desktop on macOS is discovered from its application bundle. Install Node.js and enable a working API connection in the desktop app. Model and reasoning choices are supplied by ZCode itself; see [the runtime comparison](/providers#zcode).+ZCode Desktop on macOS is discovered from its application bundle and requires Node.js. On Linux, the daemon discovers ZCode Desktop through `zcode` on PATH or `/opt/ZCode/zcode` and runs its bundled CLI without opening a desktop window. No separate Node.js installation or manual environment configuration is needed on Linux. Enable a working API connection in the desktop app. Model and reasoning choices are supplied by ZCode itself; see [the runtime comparison](/providers#zcode).diff --git a/apps/docs/content/docs/install-agent-runtime.zh-Hant.mdx b/apps/docs/content/docs/install-agent-runtime.zh-Hant.mdxindex d59e25751a..230c644d07 100644--- a/apps/docs/content/docs/install-agent-runtime.zh-Hant.mdx+++ b/apps/docs/content/docs/install-agent-runtime.zh-Hant.mdx@@ -221,4 +221,4 @@ multica daemon restart- [守護程序與執行時](/daemon-runtimes) — 瞭解線上狀態、併發和自定義執行時。- [AI 程式設計工具對照](/providers) — 比較各工具在 Multica 中的能力。-ZCode Desktop 的 macOS 應用程式包可被自動發現;請同時安裝 Node.js,並在桌面端啟用可用的 API 連線。模型與思考強度由 ZCode 原生目錄提供。詳見[執行時對照](/providers#zcode)。+ZCode Desktop 的 macOS 應用程式包可被自動發現,需要同時安裝 Node.js。Linux 下,守護程序透過 PATH 中的 `zcode` 或 `/opt/ZCode/zcode` 自動發現 ZCode Desktop,在背景執行內建 CLI,不開啟桌面視窗,無需額外安裝 Node.js 或手動設定環境變數。請在桌面端啟用可用的 API 連線。模型與思考強度由 ZCode 原生目錄提供。詳見[執行時對照](/providers#zcode)。diff --git a/apps/docs/content/docs/install-agent-runtime.zh.mdx b/apps/docs/content/docs/install-agent-runtime.zh.mdxindex 71417b85da..a5eaedbb66 100644--- a/apps/docs/content/docs/install-agent-runtime.zh.mdx+++ b/apps/docs/content/docs/install-agent-runtime.zh.mdx@@ -231,4 +231,4 @@ multica daemon restart- [守护进程与运行时](/daemon-runtimes) — 了解在线状态、并发和自定义运行时。- [AI 编程工具对照](/providers) — 比较各工具在 Multica 中的能力。-ZCode Desktop 的 macOS 应用包可被自动发现;请同时安装 Node.js,并在桌面端启用可用的 API 连接。模型与思考强度由 ZCode 原生目录提供。详见[运行时对照](/providers#zcode)。+ZCode Desktop 的 macOS 应用包可被自动发现,需要同时安装 Node.js。Linux 下,守护进程通过 PATH 中的 `zcode` 或 `/opt/ZCode/zcode` 自动发现 ZCode Desktop,在后台运行内置 CLI,不打开桌面窗口,无需额外安装 Node.js 或手动配置环境变量。请在桌面端启用可用的 API 连接。模型与思考强度由 ZCode 原生目录提供。详见[运行时对照](/providers#zcode)。diff --git a/apps/docs/content/docs/providers.fr.mdx b/apps/docs/content/docs/providers.fr.mdxindex c446cc0af1..71f81d1d98 100644--- a/apps/docs/content/docs/providers.fr.mdx+++ b/apps/docs/content/docs/providers.fr.mdx@@ -120,4 +120,4 @@ Pour créer et rattacher des skills, consultez [Skills](/skills).ZCode utilise son protocole natif NDJSON `app-server` pour créer, reprendre et annuler les sessions, découvrir les modèles, gérer les niveaux de raisonnement et configurer MCP. Les tâches s'exécutent en mode yolo, sans approbation interactive des outils. Les niveaux de raisonnement viennent du catalogue de modèles du runtime ; la création d'un agent conserve le niveau par défaut du modèle sélectionné.-Sur macOS, le daemon détecte aussi le point d'entrée Node intégré à ZCode Desktop ; Node.js doit être installé. Les connexions API-key/Coding Plan activées dans l'application sont importées dans une configuration temporaire propre au processus, supprimée à sa fermeture sans modifier les fichiers d'origine. Les jetons d'identité Start Plan ne sont pas des clés API et ce mode d'authentification n'est pas pris en charge. Si aucun modèle n'est découvert, configurez une connexion API fonctionnelle dans ZCode Desktop.+Sur macOS, le daemon détecte aussi le CLI intégré à ZCode Desktop ; Node.js doit être installé. Sur Linux, il détecte également ZCode Desktop et exécute son CLI intégré sans ouvrir de fenêtre ; aucune installation séparée de Node.js ni configuration manuelle de variables d'environnement n'est nécessaire. Les connexions API-key/Coding Plan activées dans l'application sont importées dans une configuration temporaire propre au processus, supprimée à sa fermeture sans modifier les fichiers d'origine. Les jetons d'identité Start Plan ne sont pas des clés API et ce mode d'authentification n'est pas pris en charge. Si aucun modèle n'est découvert, configurez une connexion API fonctionnelle dans ZCode Desktop.diff --git a/apps/docs/content/docs/providers.ja.mdx b/apps/docs/content/docs/providers.ja.mdxindex d8923aa93b..d4023436e8 100644--- a/apps/docs/content/docs/providers.ja.mdx+++ b/apps/docs/content/docs/providers.ja.mdx@@ -120,4 +120,4 @@ Codex、Hermes、OpenClaw の動作は少し異なります。ZCode はネイティブの NDJSON `app-server` プロトコルで、セッションの作成・再開・キャンセル、モデル検出、推論レベル、MCP に対応します。タスクは yolo モードで実行され、対話的なツール承認は求められません。推論レベルの選択肢はランタイムのモデルカタログから取得し、エージェント作成時には選択したモデルの既定値が維持されます。-macOS では ZCode Desktop に同梱された Node エントリーポイントも自動検出します。Node.js のインストールが必要です。デスクトップアプリで有効になっている API-key/Coding Plan 接続を、プロセス専用の一時設定へ取り込みます。この設定は終了時に削除され、元のファイルは変更されません。Start Plan の認証トークンは API キーではなく、このアカウント認証方式には対応していません。モデルが検出されない場合は、ZCode Desktop で利用可能な API 接続を設定してください。+macOS では ZCode Desktop に同梱された CLI も自動検出します。Node.js のインストールが必要です。Linux でも ZCode Desktop を自動検出し、デスクトップウィンドウを開かずに同梱 CLI を実行します。Node.js の追加インストールや環境変数の手動設定は不要です。デスクトップアプリで有効になっている API-key/Coding Plan 接続を、プロセス専用の一時設定へ取り込みます。この設定は終了時に削除され、元のファイルは変更されません。Start Plan の認証トークンは API キーではなく、このアカウント認証方式には対応していません。モデルが検出されない場合は、ZCode Desktop で利用可能な API 接続を設定してください。diff --git a/apps/docs/content/docs/providers.ko.mdx b/apps/docs/content/docs/providers.ko.mdxindex 5cb5d0ca41..21ec7eb7a7 100644--- a/apps/docs/content/docs/providers.ko.mdx+++ b/apps/docs/content/docs/providers.ko.mdx@@ -120,4 +120,4 @@ Codex, Hermes, OpenClaw의 처리는 조금 다릅니다.ZCode는 네이티브 NDJSON `app-server` 프로토콜로 세션 생성·재개·취소, 모델 검색, 추론 수준, MCP를 지원합니다. 태스크는 yolo 모드로 실행되며 대화형 도구 승인을 기다리지 않습니다. 추론 수준 선택지는 런타임 모델 카탈로그에서 가져오고, 에이전트 생성 시 선택한 모델의 기본값을 유지합니다.-macOS에서는 ZCode Desktop에 포함된 Node 진입점도 자동으로 감지합니다. Node.js가 설치되어 있어야 합니다. 데스크톱 앱에서 활성화한 API-key/Coding Plan 연결을 프로세스 전용 임시 설정으로 가져옵니다. 이 설정은 종료 시 삭제되며 원본 파일은 변경하지 않습니다. Start Plan 인증 토큰은 API 키가 아니므로 이 계정 인증 방식은 지원하지 않습니다. 모델이 검색되지 않으면 ZCode Desktop에서 작동하는 API 연결을 설정하세요.+macOS에서는 ZCode Desktop에 포함된 CLI도 자동으로 감지합니다. Node.js가 설치되어 있어야 합니다. Linux에서도 ZCode Desktop을 자동으로 감지하고 데스크톱 창을 열지 않고 내장 CLI를 실행합니다. Node.js를 별도로 설치하거나 환경 변수를 직접 설정할 필요가 없습니다. 데스크톱 앱에서 활성화한 API-key/Coding Plan 연결을 프로세스 전용 임시 설정으로 가져옵니다. 이 설정은 종료 시 삭제되며 원본 파일은 변경하지 않습니다. Start Plan 인증 토큰은 API 키가 아니므로 이 계정 인증 방식은 지원하지 않습니다. 모델이 검색되지 않으면 ZCode Desktop에서 작동하는 API 연결을 설정하세요.diff --git a/apps/docs/content/docs/providers.mdx b/apps/docs/content/docs/providers.mdxindex 93893a7e4a..3b65a95a3c 100644--- a/apps/docs/content/docs/providers.mdx+++ b/apps/docs/content/docs/providers.mdx@@ -122,5 +122,5 @@ For creating and binding skills, see [Skills](/skills).ZCode uses its native NDJSON `app-server` protocol for session creation, resumption, cancellation, model discovery, thinking levels, and MCP. Tasks run in yolo mode without interactive tool approval. Reasoning choices come from the runtime model catalog; creating an agent preserves the selected model's default level.-On macOS the daemon also discovers ZCode Desktop's bundled Node entry point; Node.js must be installed. Enabled desktop API-key/Coding Plan connections are imported into a process-private temporary provider configuration, which is removed on exit without changing the original files. Start Plan identity tokens are not API keys and this account-authentication path is not supported. Configure a working API connection in ZCode Desktop if discovery returns no models.+On macOS the daemon also discovers ZCode Desktop's bundled CLI; Node.js must be installed. On Linux it discovers ZCode Desktop and runs the bundled CLI without opening a desktop window; no separate Node.js installation or manual environment configuration is needed. Enabled desktop API-key/Coding Plan connections are imported into a process-private temporary provider configuration, which is removed on exit without changing the original files. Start Plan identity tokens are not API keys and this account-authentication path is not supported. Configure a working API connection in ZCode Desktop if discovery returns no models.diff --git a/apps/docs/content/docs/providers.zh-Hant.mdx b/apps/docs/content/docs/providers.zh-Hant.mdxindex e174120cd4..6975c245c0 100644--- a/apps/docs/content/docs/providers.zh-Hant.mdx+++ b/apps/docs/content/docs/providers.zh-Hant.mdx@@ -122,4 +122,4 @@ Codex、Hermes 和 OpenClaw 的處理稍有不同:ZCode 使用原生 NDJSON `app-server` 協定,支援會話建立、續接、取消、模型發現、思考強度和 MCP。任務透過 yolo 模式執行,無需等待互動式工具審批。每個模型的思考檔位來自執行時目錄,建立 AI 代理時會保留對應預設值。-macOS 可自動發現 ZCode Desktop 內建的 Node 入口;需要本機已安裝 Node.js。執行時讀取桌面端已啟用的 API-key/Coding Plan 連線,為當前程序生成獨佔臨時配置,退出後刪除,原配置不變。Start Plan 登入身分令牌不作為 API key 匯入,目前不支援這條帳號鑑權路徑。若模型列表為空,請先在桌面端配置一個可用的 API 連線。+macOS 可自動發現 ZCode Desktop 內建的 CLI;需要本機已安裝 Node.js。Linux 也可自動發現 ZCode Desktop,在背景執行內建 CLI,不開啟桌面視窗,無需額外安裝 Node.js 或手動設定環境變數。執行時讀取桌面端已啟用的 API-key/Coding Plan 連線,為當前程序生成獨佔臨時配置,退出後刪除,原配置不變。Start Plan 登入身分令牌不作為 API key 匯入,目前不支援這條帳號鑑權路徑。若模型列表為空,請先在桌面端配置一個可用的 API 連線。diff --git a/apps/docs/content/docs/providers.zh.mdx b/apps/docs/content/docs/providers.zh.mdxindex eae6313841..00f8a29b30 100644--- a/apps/docs/content/docs/providers.zh.mdx+++ b/apps/docs/content/docs/providers.zh.mdx@@ -122,4 +122,4 @@ Codex、Hermes 和 OpenClaw 的处理稍有不同:ZCode 使用原生 NDJSON `app-server` 协议,支持会话创建、续接、取消、模型发现、思考强度和 MCP。任务通过 yolo 模式执行,无需等待交互式工具审批。每个模型的思考档位来自运行时目录,创建智能体时会保留对应默认值。-macOS 可自动发现 ZCode Desktop 内置的 Node 入口;需要本机已安装 Node.js。运行时读取桌面端已启用的 API-key/Coding Plan 连接,为当前进程生成独占临时配置,退出后删除,原配置不变。Start Plan 登录身份令牌不作为 API key 导入,目前不支持这条账号鉴权路径。若模型列表为空,请先在桌面端配置一个可用的 API 连接。+macOS 可自动发现 ZCode Desktop 内置的 CLI;需要本机已安装 Node.js。Linux 也可自动发现 ZCode Desktop,在后台运行内置 CLI,不打开桌面窗口,无需额外安装 Node.js 或手动配置环境变量。运行时读取桌面端已启用的 API-key/Coding Plan 连接,为当前进程生成独占临时配置,退出后删除,原配置不变。Start Plan 登录身份令牌不作为 API key 导入,目前不支持这条账号鉴权路径。若模型列表为空,请先在桌面端配置一个可用的 API 连接。diff --git a/server/internal/daemon/agents_probe_zcode_bundle_test.go b/server/internal/daemon/agents_probe_zcode_bundle_test.goindex 86caf46512..04f8792bde 100644--- a/server/internal/daemon/agents_probe_zcode_bundle_test.go+++ b/server/internal/daemon/agents_probe_zcode_bundle_test.go@@ -1,10 +1,13 @@package daemonimport (+ "context""os""path/filepath""runtime""testing"++ "github.com/multica-ai/multica/server/pkg/agent")func TestProbeAgentCLIsDiscoversZCodeAppBundle(t *testing.T) {@@ -48,3 +51,65 @@ func TestProbeAgentCLIsDiscoversZCodeAppBundle(t *testing.T) {t.Fatalf("ZCode display name = %q, want ZCode", got)}}++func TestProbeAgentCLIsLinuxZcodeDesktop(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("Unix desktop entry point")+ }+ for _, source := range []string{"PATH", "login shell", "override", "default install"} {+ t.Run(source, func(t *testing.T) {+ root, err := filepath.EvalSymlinks(t.TempDir())+ if err != nil {+ t.Fatal(err)+ }+ bin := filepath.Join(root, "ZCode install", "zcode")+ script := filepath.Join(filepath.Dir(bin), "resources", "glm", "zcode.cjs")+ if err := os.MkdirAll(filepath.Dir(script), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(script, []byte("// bundled CLI\n"), 0o644); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(bin, []byte(`#!/bin/sh+[ "$ELECTRON_RUN_AS_NODE" = 1 ] && [ -f "$1" ] && [ "$2" = --version ] || exit 42+printf '0.17.1\n'+`), 0o755); err != nil {+ t.Fatal(err)+ }+ origPaths := zcodeDesktopAppBundlePaths+ t.Cleanup(func() { zcodeDesktopAppBundlePaths = origPaths })+ zcodeDesktopAppBundlePaths = func() []string {+ if source == "default install" {+ return []string{bin}+ }+ return nil+ }+ origResolve := resolveAgentsViaLoginShell+ t.Cleanup(func() { resolveAgentsViaLoginShell = origResolve })+ resolveAgentsViaLoginShell = func([]string) map[string]string { return nil }+ resetShellResolveCacheForTest(t)+ t.Setenv("PATH", root)+ t.Setenv("MULTICA_ZCODE_PATH", "")+ t.Setenv("MULTICA_ZCODE_MODEL", "zai/glm-5.3")+ switch source {+ case "PATH":+ link := filepath.Join(root, "zcode")+ if err := os.Symlink(bin, link); err != nil {+ t.Fatal(err)+ }+ case "login shell":+ resolveAgentsViaLoginShell = func([]string) map[string]string { return map[string]string{"zcode": bin} }+ case "override":+ t.Setenv("MULTICA_ZCODE_PATH", bin)+ }+ entry, ok := probeAgentCLIs()["zcode"]+ if !ok || entry.Path != bin || entry.Model != "zai/glm-5.3" {+ t.Fatalf("discovered ZCode = %+v, present = %v", entry, ok)+ }+ version, err := agent.DetectVersion(context.Background(), agent.NewCommand(entry.Path, nil).ForVersionProbe("zcode"))+ if err != nil || version != "0.17.1" {+ t.Fatalf("version = %q, err = %v", version, err)+ }+ })+ }+}diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex 6a576ae273..b0a116f965 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -972,6 +972,9 @@ var defaultAgentCommandNames = append([]string{// zcodeDesktopAppBundlePaths discovers the CLI in default Desktop installs.var zcodeDesktopAppBundlePaths = func() []string {+ if runtime.GOOS == "linux" {+ return []string{"/opt/ZCode/zcode"}+ }if runtime.GOOS != "darwin" {return nil}diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.goindex f43d3071df..358f94d59c 100644--- a/server/pkg/agent/claude.go+++ b/server/pkg/agent/claude.go@@ -1589,9 +1589,10 @@ func detectCLIVersion(ctx context.Context, runtimeCmd Command) (string, error) {//// Built through runtimeCmd.exec so a custom runtime's fixed_args prefix is// still applied (MUL-6260). Desktop ZCode ships as a Node .cjs/.mjs bundle;- // those must go through chooseZcodeInvocation (node + script) the same way- // Execute does, with a clear error when node is missing from PATH.- if isNodeScriptPath(runtimeCmd.Path) {+ // those and Linux Electron entries use the same headless invocation as+ // Execute, with a clear error when the required runtime or script is missing.+ _, zcodeDesktop := zcodeDesktopScript(runtimeCmd.Path)+ if isNodeScriptPath(runtimeCmd.Path) || zcodeDesktop {if err := requireNodeForZcodeScript(runtimeCmd.Path); err != nil {return "", err}@@ -1645,8 +1646,12 @@ func versionProbeRejectedArgs(ctx context.Context, err error) bool {// command and the exec diagnosis.func runVersionProbe(ctx context.Context, runtimeCmd Command, args []string) (string, error) {var cmd *exec.Cmd- if isNodeScriptPath(runtimeCmd.Path) {+ _, zcodeDesktop := zcodeDesktopScript(runtimeCmd.Path)+ if isNodeScriptPath(runtimeCmd.Path) || zcodeDesktop {cmd, _, _ = runtimeCmd.execVia(ctx, chooseZcodeInvocation, runtimeCmd.Path, args, runtimeCmd.logger)+ if zcodeDesktop {+ cmd.Env = zcodeRuntimeEnv(runtimeCmd.Path, os.Environ())+ }} else {cmd = runtimeCmd.exec(ctx, args...)}diff --git a/server/pkg/agent/zcode_desktop_unix_test.go b/server/pkg/agent/zcode_desktop_unix_test.gonew file mode 100644index 0000000000..d7a1953542--- /dev/null+++ b/server/pkg/agent/zcode_desktop_unix_test.go@@ -0,0 +1,123 @@+//go:build !windows++package agent++import (+ "context"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func TestZcodeLinuxDesktopHeadless(t *testing.T) {+ for _, symlink := range []bool{false, true} {+ name := "direct"+ if symlink {+ name = "PATH symlink"+ }+ t.Run(name, func(t *testing.T) {+ root, err := filepath.EvalSymlinks(t.TempDir())+ if err != nil {+ t.Fatal(err)+ }+ bin := filepath.Join(root, "ZCode install", "zcode")+ script := filepath.Join(filepath.Dir(bin), "resources", "glm", "zcode.cjs")+ if err := os.MkdirAll(filepath.Dir(script), 0o755); err != nil {+ t.Fatal(err)+ }+ guiMarker := filepath.Join(root, "gui-started")+ t.Setenv("ZCODE_GUI_MARKER", guiMarker)+ t.Setenv("ZCODE_EXPECTED_SCRIPT", script)+ t.Setenv("ELECTRON_RUN_AS_NODE", "0")+ t.Setenv("ZCODE_DATA_BASE_DIR", root)+ t.Setenv("PATH", root) // No standalone Node.js.+ if err := os.WriteFile(bin, []byte(`#!/bin/sh+if [ "$ELECTRON_RUN_AS_NODE" != 1 ] || [ "$1" != "$ZCODE_EXPECTED_SCRIPT" ]; then+ printf 'GUI launched\n' > "$ZCODE_GUI_MARKER"+ exit 1+fi+script=$1+shift+if [ "$1" = --version ]; then+ printf '0.17.1\n'+ exit 0+fi+exec /bin/sh "$script" "$@"+`), 0o755); err != nil {+ t.Fatal(err)+ }+ if symlink {+ link := filepath.Join(root, "zcode")+ if err := os.Symlink(bin, link); err != nil {+ t.Fatal(err)+ }+ bin = link+ }+ writeCLI := func(body string) {+ t.Helper()+ body = strings.ReplaceAll(body, "| sed ", "| /usr/bin/sed ")+ if err := os.WriteFile(script, []byte(body), 0o644); err != nil {+ t.Fatal(err)+ }+ }+ writeCLI(fakeZcodeDiscoveryScript)+ t.Setenv("ZCODE_DISCOVERY_CAPTURE", filepath.Join(root, "discovery.txt"))+ version, err := DetectVersion(context.Background(), NewCommand(bin, nil).ForVersionProbe("zcode"))+ if err != nil || version != "0.17.1" {+ t.Errorf("version = %q, err = %v", version, err)+ }+ catalog, err := discoverZcodeModels(context.Background(), NewCommand(bin, nil))+ if err != nil || len(catalog.Models) != 2 {+ t.Errorf("model discovery = %+v, err = %v", catalog, err)+ }+ writeCLI(fakeZcodeHappyScript(zcodeEventFrame(6, "turn.completed", `{"response":"done","resultType":"success","tokenCount":0,"toolCallCount":0,"duration":1}`)))+ session, err := newZcodeTestBackend(t, bin).Execute(context.Background(), "hello", ExecOptions{Cwd: root})+ if err != nil {+ t.Errorf("execute: %v", err)+ } else if _, res := collectZcodeSession(t, session); res.Status != "completed" {+ t.Errorf("result = %+v", res)+ }+ if _, err := os.Stat(guiMarker); !os.IsNotExist(err) {+ t.Error("desktop GUI entry point was invoked")+ }+ })+ }+}++func TestZcodeLinuxDesktopMissingCLI(t *testing.T) {+ bin := writeFakeZcodeScript(t, "#!/bin/sh\nexit 42\n")+ if err := os.MkdirAll(filepath.Join(filepath.Dir(bin), "resources", "glm"), 0o755); err != nil {+ t.Fatal(err)+ }+ _, err := DetectVersion(context.Background(), NewCommand(bin, nil).ForVersionProbe("zcode"))+ if err == nil || !strings.Contains(err.Error(), "MULTICA_ZCODE_PATH") {+ t.Fatalf("expected a headless CLI configuration error, got %v", err)+ }+}++func TestZcodeLinuxDesktopProviderConfig(t *testing.T) {+ root := t.TempDir()+ bin := filepath.Join(root, "zcode")+ script := filepath.Join(root, "resources", "glm", "zcode.cjs")+ builtin := filepath.Join(root, "resources", "config", "provider", "zcode-builtin.json")+ for _, path := range []string{script, builtin} {+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte("{}"), 0o644); err != nil {+ t.Fatal(err)+ }+ }+ env, cleanup, err := prepareZcodeRuntimeEnv(bin, []string{"ZCODE_DATA_BASE_DIR=" + root})+ if err != nil {+ t.Fatal(err)+ }+ defer cleanup()+ if got := zcodeEnvValue(env, "ZCODE_BUILTIN_PROVIDER_CONFIG_FILE"); got != builtin {+ t.Fatalf("builtin config = %q, want %q", got, builtin)+ }+ if zcodeEnvValue(env, zcodePersonalConfigEnv) == "" {+ t.Fatal("Linux Desktop did not receive its private provider snapshot")+ }+}diff --git a/server/pkg/agent/zcode_invocation.go b/server/pkg/agent/zcode_invocation.goindex b310eab5d7..73b67526fa 100644--- a/server/pkg/agent/zcode_invocation.go+++ b/server/pkg/agent/zcode_invocation.go@@ -13,24 +13,51 @@ import (// to spawn a ZCode run.//// ZCode ships as a Node bundle (zcode.cjs) inside the desktop app rather than-// as a native binary, so a resolved .cjs/.mjs path runs under `node`. Callers-// (Execute, model discovery, --version probes) must ensure `node` is on PATH-// before spawning — see requireNodeForZcodeScript. Shims and native builds-// pass through unchanged.+// as a native binary. A .cjs/.mjs path runs under `node`; the Linux desktop+// entry runs its companion script under Electron's bundled Node runtime.+// Callers must validate the entry with requireNodeForZcodeScript and apply+// zcodeRuntimeEnv for Electron. Shims and native builds pass through.func chooseZcodeInvocation(execName, lookedUp string, args []string, _ *slog.Logger) (string, []string) {+ if script, desktop := zcodeDesktopScript(lookedUp); desktop {+ return lookedUp, append([]string{script}, args...)+ }if isNodeScriptPath(lookedUp) {return "node", append([]string{lookedUp}, args...)}return execName, args}+// zcodeDesktopScript recognizes the Linux desktop layout, including PATH+// symlinks to its Electron entry point. Keep recognizing an incomplete bundle+// so a missing CLI produces an error instead of launching the GUI.+func zcodeDesktopScript(executable string) (string, bool) {+ if real, err := filepath.EvalSymlinks(executable); err == nil {+ executable = real+ }+ if filepath.Base(executable) != "zcode" {+ return "", false+ }+ resources := filepath.Join(filepath.Dir(executable), "resources")+ if info, err := os.Stat(resources); err != nil || !info.IsDir() {+ return "", false+ }+ return filepath.Join(resources, "glm", "zcode.cjs"), true+}+func isNodeScriptPath(path string) bool {return strings.HasSuffix(path, ".cjs") || strings.HasSuffix(path, ".mjs")}// requireNodeForZcodeScript reports a clear error when a Desktop .cjs/.mjs-// entry needs Node.js on PATH and none is resolvable. Native/shim paths pass.+// entry needs Node.js on PATH and none is resolvable, or a Linux Desktop entry+// has no companion CLI. Linux Desktop uses Electron's own Node runtime.func requireNodeForZcodeScript(lookedUp string) error {+ if script, desktop := zcodeDesktopScript(lookedUp); desktop {+ if info, err := os.Stat(script); err != nil || !info.Mode().IsRegular() {+ return fmt.Errorf("ZCode Desktop CLI is missing at %s; set MULTICA_ZCODE_PATH to a headless ZCode CLI or wrapper", script)+ }+ return nil+ }if !isNodeScriptPath(lookedUp) {return nil}@@ -42,8 +69,13 @@ func requireNodeForZcodeScript(lookedUp string) error {// zcodeRuntimeEnv supplies the companion config shipped in the Desktop app.// The bundled CLI's relative lookup does not cover Resources/glm in 0.17.-// Explicit environment configuration always wins.+// Explicit provider configuration always wins.func zcodeRuntimeEnv(executable string, env []string) []string {+ if script, desktop := zcodeDesktopScript(executable); desktop {+ // This must override an inherited 0: Electron otherwise starts its GUI.+ env = append(append([]string(nil), env...), "ELECTRON_RUN_AS_NODE=1")+ executable = script+ }const key = "ZCODE_BUILTIN_PROVIDER_CONFIG_FILE"for _, entry := range env {if strings.HasPrefix(entry, key+"=") {diff --git a/server/pkg/agent/zcode_runtime_config.go b/server/pkg/agent/zcode_runtime_config.goindex a82b125413..2599c863be 100644--- a/server/pkg/agent/zcode_runtime_config.go+++ b/server/pkg/agent/zcode_runtime_config.go@@ -67,6 +67,10 @@ func readZcodeConfig(path string, into any) error {// crash leftovers do not linger.func prepareZcodeRuntimeEnv(executable string, env []string) ([]string, func(), error) {noop := func() {}+ env = zcodeRuntimeEnv(executable, env)+ if script, desktop := zcodeDesktopScript(executable); desktop {+ executable = script+ }if zcodeEnvValue(env, zcodePersonalConfigEnv) != "" {return zcodeRuntimeEnv(executable, env), noop, nil}