Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7232 feat(daemon): add dsh desktop(self-hosted) support (#8237)
Yushan3551e72e76d2
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdxindex ea6b7475e4..bf3f041303 100644--- a/apps/docs/content/docs/environment-variables.ja.mdx+++ b/apps/docs/content/docs/environment-variables.ja.mdx@@ -250,7 +250,7 @@ API key と base URL の両方が空の場合、このレイヤーは無効にデーモンがエージェント作業に注入する内部コンテキストについては、[作業ランタイム環境](/daemon-runtimes#作業ランタイム環境)を参照してください。-各 AI コーディングツールは `MULTICA_<PROVIDER>_PATH` でコマンドパスを上書きでき、モデル上書き対応ツールでは `MULTICA_<PROVIDER>_MODEL` も利用できます。QwenPaw と MiniMax Code にはモデル変数がなく、MiniMax Code のパス変数は `MULTICA_MCODE_PATH` です。詳しくは [AI コーディングツール比較](/providers#モデルの取得元) を参照してください。DeepSeek Harness は `MULTICA_DSH_PATH` と `MULTICA_DSH_MODEL` に対応しています(値は dsh のモデルカタログにあるモデル ID、例: `deepseek-official/deepseek-chat`)。ZeroClaw は `MULTICA_ZEROCLAW_PATH` に対応しますが、モデル変数はありません。モデルは ZeroClaw のエージェント設定で管理します。マシン全体のデフォルト引数 `MULTICA_<PROVIDER>_ARGS` は、現在 Claude Code、Codex、CodeBuddy、Qwen Code、QwenPaw の 5 ツールに対応しています。対応する変数は `MULTICA_CLAUDE_ARGS`、`MULTICA_CODEX_ARGS`、`MULTICA_CODEBUDDY_ARGS`、`MULTICA_QWEN_ARGS`、`MULTICA_QWENPAW_ARGS` です。例:+各 AI コーディングツールは `MULTICA_<PROVIDER>_PATH` でコマンドパスを上書きでき、モデル上書き対応ツールでは `MULTICA_<PROVIDER>_MODEL` も利用できます。QwenPaw と MiniMax Code にはモデル変数がなく、MiniMax Code のパス変数は `MULTICA_MCODE_PATH` です。詳しくは [AI コーディングツール比較](/providers#モデルの取得元) を参照してください。DeepSeek Harness は `MULTICA_DSH_PATH` と `MULTICA_DSH_MODEL` に対応しています(値は dsh のモデルカタログにあるモデル ID、例: `deepseek-official/deepseek-chat`)。 DeepSeek Harness はさらに `MULTICA_DSH_PROFILE_BUNDLE` に対応しています。`multica` プロファイルが存在しない場合にインストールするバンドルを指定するもので、カンマ区切りで複数の候補を順に試します。各項目は npm のパッケージ名、ディレクトリ、またはパック済み tarball です。既定では未設定です。Multica が利用する `--stdio` プロトコルはこのプロファイルが提供するため、未設定の場合は DSH のインストールには手を加えず、デーモンは使用できないランタイムを登録する代わりにプロファイルの欠落を報告します。Multica 自身のブリッジはまだ公開 npm レジストリにないため、値の選び方は[エージェントランタイムのインストール](/install-agent-runtime)を参照してください。ここに設定した値は追加の確認なしに各デーモンホストの DSH ホームへインストールされるので、サプライチェーンの判断として扱ってください。`MULTICA_DSH_PROFILE_BUNDLE` が有効にするインストールは範囲を意図的に限定しています。実行はデーモンのライフタイムにつき最大 1 回、プローブがプロファイルの不在を確認できた場合のみです。失敗時はパッケージマネージャー自身の出力をログに記録し、再試行はデーモンの再起動後のみ行います。プローブがタイムアウトした場合や、このデーモンが扱わないプロトコルバージョンを返した場合は報告のみで、上書きインストールは行いません。意図して用意されたプロファイルをデーモンが上書きすることはありません。調査はデーモンログで `DSH runtime profile` を検索してください。取り消す場合は `$DSH_HOME/profiles/multica`(既定は `~/.dsh/profiles/multica`)を削除します。`MULTICA_DSH_PLUGIN_PATH` はインストール時に pnpm を解決するディレクトリを上書きします。`dsh plugin` が転送する pnpm は macOS でも Windows でも DSH Desktop 独自の runtime-commands ディレクトリに置かれており、デーモンはそれを自動で見つけて PATH の先頭に追加します(新しい Desktop が使うバージョン付きの構成も含みます)。したがってこの変数が必要なのは、デーモンが見つけられない場所にインストールされている場合か、独自の pnpm を使わせたい場合だけです。設定すると自動探索は完全に置き換わり、指定したディレクトリが存在しなければ、インストールは同梱の pnpm ではなくデーモンの `PATH` 上の pnpm にフォールバックします。Linux には DSH Desktop がないため、常に `PATH` が使われます。ZeroClaw は `MULTICA_ZEROCLAW_PATH` に対応しますが、モデル変数はありません。モデルは ZeroClaw のエージェント設定で管理します。マシン全体のデフォルト引数 `MULTICA_<PROVIDER>_ARGS` は、現在 Claude Code、Codex、CodeBuddy、Qwen Code、QwenPaw の 5 ツールに対応しています。対応する変数は `MULTICA_CLAUDE_ARGS`、`MULTICA_CODEX_ARGS`、`MULTICA_CODEBUDDY_ARGS`、`MULTICA_QWEN_ARGS`、`MULTICA_QWENPAW_ARGS` です。例:```dotenvMULTICA_CLAUDE_PATH=/opt/bin/claudediff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdxindex 6d8d126217..0f590078c0 100644--- a/apps/docs/content/docs/environment-variables.ko.mdx+++ b/apps/docs/content/docs/environment-variables.ko.mdx@@ -250,7 +250,7 @@ API key와 base URL이 모두 비어 있으면 이 레이어가 꺼지고 업스데몬이 에이전트 작업에 주입하는 내부 컨텍스트는 [작업 런타임 환경](/daemon-runtimes#작업-런타임-환경)을 참고하세요.-각 AI 코딩 도구는 `MULTICA_<PROVIDER>_PATH`로 명령 경로를 덮어쓸 수 있으며 모델 재정의를 지원하는 도구는 `MULTICA_<PROVIDER>_MODEL`도 사용할 수 있습니다. QwenPaw와 MiniMax Code에는 모델 변수가 없고 MiniMax Code의 경로 변수는 `MULTICA_MCODE_PATH`입니다. 자세한 내용은 [AI 코딩 도구 비교](/providers#모델-출처)를 참고하세요. DeepSeek Harness는 `MULTICA_DSH_PATH`와 `MULTICA_DSH_MODEL`을 지원합니다(값은 dsh 모델 카탈로그의 모델 ID, 예: `deepseek-official/deepseek-chat`). ZeroClaw는 `MULTICA_ZEROCLAW_PATH`를 지원하지만 모델 변수는 없습니다. 모델은 ZeroClaw의 에이전트 설정에서 관리합니다. 컴퓨터 전체 기본 인수 `MULTICA_<PROVIDER>_ARGS`는 현재 Claude Code, Codex, CodeBuddy, Qwen Code, QwenPaw 다섯 도구를 지원합니다. 해당 변수는 `MULTICA_CLAUDE_ARGS`, `MULTICA_CODEX_ARGS`, `MULTICA_CODEBUDDY_ARGS`, `MULTICA_QWEN_ARGS`, `MULTICA_QWENPAW_ARGS`입니다. 예시:+각 AI 코딩 도구는 `MULTICA_<PROVIDER>_PATH`로 명령 경로를 덮어쓸 수 있으며 모델 재정의를 지원하는 도구는 `MULTICA_<PROVIDER>_MODEL`도 사용할 수 있습니다. QwenPaw와 MiniMax Code에는 모델 변수가 없고 MiniMax Code의 경로 변수는 `MULTICA_MCODE_PATH`입니다. 자세한 내용은 [AI 코딩 도구 비교](/providers#모델-출처)를 참고하세요. DeepSeek Harness는 `MULTICA_DSH_PATH`와 `MULTICA_DSH_MODEL`을 지원합니다(값은 dsh 모델 카탈로그의 모델 ID, 예: `deepseek-official/deepseek-chat`). DeepSeek Harness는 `MULTICA_DSH_PROFILE_BUNDLE`도 지원합니다. `multica` 프로필이 없을 때 설치할 번들을 지정하며, 쉼표로 구분한 여러 후보를 순서대로 시도합니다. 각 항목은 npm 패키지 이름, 디렉터리 또는 패키징된 tarball입니다. 기본값은 설정하지 않는 것입니다. Multica가 사용하는 `--stdio` 프로토콜은 이 프로필이 제공하므로, 설정하지 않으면 DSH 설치를 건드리지 않고 데몬은 사용할 수 없는 런타임을 등록하는 대신 프로필 누락을 보고합니다. Multica 자체 브리지는 아직 공개 npm 레지스트리에 없으므로 값 선택 방법은 [에이전트 런타임 설치](/install-agent-runtime)를 참고하세요. 여기에 설정한 값은 추가 확인 없이 모든 데몬 호스트의 DSH 홈에 설치되므로 공급망에 관한 결정으로 다루세요. `MULTICA_DSH_PROFILE_BUNDLE`이 활성화하는 설치는 범위를 의도적으로 제한합니다. 실행은 데몬 수명당 최대 한 번, 프로브가 프로필 부재를 확인한 경우에만 수행됩니다. 실패하면 패키지 관리자 자체의 출력을 로그에 남기고 재시도는 데몬을 재시작한 뒤에만 이루어집니다. 프로브가 시간 초과되거나 이 데몬이 다루지 않는 프로토콜 버전을 반환하면 보고만 하고 덮어쓰지 않습니다. 의도적으로 설치된 프로필을 데몬이 덮어쓰는 일은 없습니다. 진단은 데몬 로그에서 `DSH runtime profile`을 검색하세요. 되돌리려면 `$DSH_HOME/profiles/multica`(기본값 `~/.dsh/profiles/multica`)를 삭제합니다. `MULTICA_DSH_PLUGIN_PATH`는 설치 시 pnpm을 찾을 디렉터리를 덮어씁니다. `dsh plugin`이 전달하는 pnpm은 macOS와 Windows 모두 DSH Desktop 전용 runtime-commands 디렉터리에 있으며, 데몬이 이를 자동으로 찾아 PATH 앞에 추가합니다(최신 Desktop이 쓰는 버전별 구조도 포함). 따라서 이 변수는 데몬이 찾지 못하는 위치에 설치된 경우나 직접 준비한 pnpm을 쓰게 하려는 경우에만 필요합니다. 설정하면 자동 탐색을 완전히 대체하며, 지정한 디렉터리가 없으면 설치는 번들된 pnpm이 아니라 데몬 `PATH`의 pnpm으로 넘어갑니다. Linux에는 DSH Desktop이 없으므로 항상 `PATH`를 사용합니다. ZeroClaw는 `MULTICA_ZEROCLAW_PATH`를 지원하지만 모델 변수는 없습니다. 모델은 ZeroClaw의 에이전트 설정에서 관리합니다. 컴퓨터 전체 기본 인수 `MULTICA_<PROVIDER>_ARGS`는 현재 Claude Code, Codex, CodeBuddy, Qwen Code, QwenPaw 다섯 도구를 지원합니다. 해당 변수는 `MULTICA_CLAUDE_ARGS`, `MULTICA_CODEX_ARGS`, `MULTICA_CODEBUDDY_ARGS`, `MULTICA_QWEN_ARGS`, `MULTICA_QWENPAW_ARGS`입니다. 예시:```dotenvMULTICA_CLAUDE_PATH=/opt/bin/claudediff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdxindex 213fec757c..e10146ea01 100644--- a/apps/docs/content/docs/environment-variables.mdx+++ b/apps/docs/content/docs/environment-variables.mdx@@ -250,7 +250,7 @@ The variables below are read on the computer that runs your agents, not in the AFor the internal context that the daemon injects into agent tasks, see [Task runtime environment](/daemon-runtimes#task-runtime-environment).-Each AI coding tool accepts `MULTICA_<PROVIDER>_PATH` and `MULTICA_<PROVIDER>_MODEL` to override the command path and default model. QwenPaw and MiniMax Code have no model variable because Multica never sends them a model; MiniMax Code's path variable is `MULTICA_MCODE_PATH` — see [AI coding tools comparison](/providers#model-sources). DeepSeek Harness supports `MULTICA_DSH_PATH` and `MULTICA_DSH_MODEL` (a model id from the dsh catalog, e.g. `deepseek-official/deepseek-chat`). Dim supports `MULTICA_DIM_PATH` and `MULTICA_DIM_MODEL` (a model id from the dim catalog). ZeroClaw supports `MULTICA_ZEROCLAW_PATH` but has no model variable; its agent profile owns the model selection. Machine-wide default arguments via `MULTICA_<PROVIDER>_ARGS` are currently supported for five tools: Claude Code, Codex, CodeBuddy, Qwen Code, and QwenPaw. The variables are `MULTICA_CLAUDE_ARGS`, `MULTICA_CODEX_ARGS`, `MULTICA_CODEBUDDY_ARGS`, `MULTICA_QWEN_ARGS`, and `MULTICA_QWENPAW_ARGS`. For example:+Each AI coding tool accepts `MULTICA_<PROVIDER>_PATH` and `MULTICA_<PROVIDER>_MODEL` to override the command path and default model. QwenPaw and MiniMax Code have no model variable because Multica never sends them a model; MiniMax Code's path variable is `MULTICA_MCODE_PATH` — see [AI coding tools comparison](/providers#model-sources). DeepSeek Harness supports `MULTICA_DSH_PATH` and `MULTICA_DSH_MODEL` (a model id from the dsh catalog, e.g. `deepseek-official/deepseek-chat`). DeepSeek Harness additionally accepts `MULTICA_DSH_PROFILE_BUNDLE`: a comma-separated list of bundles to install into its `multica` profile when that profile is missing, tried in order, where each entry is an npm spec, a directory, or a packed tarball. It is unset by default, and the `--stdio` protocol Multica drives is what that profile supplies, so an unset variable leaves the DSH installation untouched and the daemon reports the missing profile instead of registering an unusable runtime. Multica's own bridge is not on a public npm registry yet, so choosing a value is covered in [Install an agent runtime](/install-agent-runtime); whatever you set is installed into every daemon host's DSH home without further confirmation, so treat it as a supply-chain decision. The install `MULTICA_DSH_PROFILE_BUNDLE` enables is bounded on purpose: it runs at most once per daemon lifetime, only when the probe reports the profile genuinely absent, and a failure is logged with the package manager's own output and retried only after a daemon restart. A probe that times out, or answers with a protocol version this daemon does not drive, is reported and never installed over — the daemon does not overwrite a profile that is deliberately there. To diagnose, search the daemon log for `DSH runtime profile`; to undo an install, delete `$DSH_HOME/profiles/multica` (default `~/.dsh/profiles/multica`). `MULTICA_DSH_PLUGIN_PATH` overrides the directory the install resolves pnpm from. DSH Desktop keeps the pnpm that `dsh plugin` forwards to inside its own runtime-commands directory on both macOS and Windows, and the daemon finds and prepends it automatically — including the versioned layout a newer Desktop uses — so this variable is only needed for an installation the daemon cannot find, or to make the install use a pnpm of your own. Setting it replaces the search entirely: if the directory does not exist, the install falls back to whatever pnpm is on the daemon's `PATH` rather than to the bundled one. Linux has no DSH Desktop, so there the install always uses `PATH`. Dim supports `MULTICA_DIM_PATH` and `MULTICA_DIM_MODEL` (a model id from the dim catalog). ZeroClaw supports `MULTICA_ZEROCLAW_PATH` but has no model variable; its agent profile owns the model selection. Machine-wide default arguments via `MULTICA_<PROVIDER>_ARGS` are currently supported for five tools: Claude Code, Codex, CodeBuddy, Qwen Code, and QwenPaw. The variables are `MULTICA_CLAUDE_ARGS`, `MULTICA_CODEX_ARGS`, `MULTICA_CODEBUDDY_ARGS`, `MULTICA_QWEN_ARGS`, and `MULTICA_QWENPAW_ARGS`. For example:```dotenvMULTICA_CLAUDE_PATH=/opt/bin/claudediff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdxindex 5744814736..5fcdd84f50 100644--- a/apps/docs/content/docs/environment-variables.zh.mdx+++ b/apps/docs/content/docs/environment-variables.zh.mdx@@ -250,7 +250,7 @@ API key 与 base URL 都为空时,这一层关闭,不会发出任何上游守护进程注入智能体 task 的内部上下文见 [Task 运行时环境](/daemon-runtimes#task-运行时环境)。-各 AI 编程工具可以使用 `MULTICA_<PROVIDER>_PATH` 覆盖命令路径;支持模型覆盖的工具还可以使用 `MULTICA_<PROVIDER>_MODEL`。QwenPaw 和 MiniMax Code 没有模型变量,因为 Multica 不会向它们传模型;MiniMax Code 的路径变量是 `MULTICA_MCODE_PATH`。详见 [AI 编程工具对比](/providers#模型来源)。DeepSeek Harness 支持 `MULTICA_DSH_PATH` 和 `MULTICA_DSH_MODEL`(取值为 dsh 模型目录中的模型 id,例如 `deepseek-official/deepseek-chat`)。ZeroClaw 支持 `MULTICA_ZEROCLAW_PATH`,但没有模型变量;模型由 ZeroClaw 的智能体配置管理。全机默认参数 `MULTICA_<PROVIDER>_ARGS` 目前支持 Claude Code、Codex、CodeBuddy、Qwen Code 和 QwenPaw 五款工具。对应变量是 `MULTICA_CLAUDE_ARGS`、`MULTICA_CODEX_ARGS`、`MULTICA_CODEBUDDY_ARGS`、`MULTICA_QWEN_ARGS` 和 `MULTICA_QWENPAW_ARGS`。例如:+各 AI 编程工具可以使用 `MULTICA_<PROVIDER>_PATH` 覆盖命令路径;支持模型覆盖的工具还可以使用 `MULTICA_<PROVIDER>_MODEL`。QwenPaw 和 MiniMax Code 没有模型变量,因为 Multica 不会向它们传模型;MiniMax Code 的路径变量是 `MULTICA_MCODE_PATH`。详见 [AI 编程工具对比](/providers#模型来源)。DeepSeek Harness 支持 `MULTICA_DSH_PATH` 和 `MULTICA_DSH_MODEL`(取值为 dsh 模型目录中的模型 id,例如 `deepseek-official/deepseek-chat`)。 DeepSeek Harness 另外支持 `MULTICA_DSH_PROFILE_BUNDLE`:当 `multica` profile 缺失时,用它指定要安装的 bundle,多个候选用逗号分隔、按序尝试,每项可以是 npm 包名、目录或打包好的 tarball。该变量默认不设置;Multica 驱动的 `--stdio` 协议正是由这个 profile 提供,所以不设置时不会改动 DSH 的安装,守护进程会报告缺少 profile,而不是注册一个不可用的运行时。Multica 自己的桥接还没有发布到公共 npm registry,如何选取值见[安装智能体运行时](/install-agent-runtime);这里填的东西会在没有二次确认的情况下装进每一台守护进程宿主的 DSH 家目录,请当作供应链决策来对待。`MULTICA_DSH_PROFILE_BUNDLE` 开启的安装被刻意限制了范围:每个守护进程生命周期最多执行一次,只在探测确认 profile 确实缺失时执行;失败时会把包管理器自身的输出记入日志,且只有重启守护进程后才会重试。探测超时、或返回本守护进程不支持的协议版本时,只做报告,绝不覆盖安装——守护进程不会覆盖一个明显是刻意装上去的 profile。排查时在守护进程日志中搜索 `DSH runtime profile`;要撤销安装,删除 `$DSH_HOME/profiles/multica`(默认 `~/.dsh/profiles/multica`)。`MULTICA_DSH_PLUGIN_PATH` 用于覆盖安装时解析 pnpm 的目录。`dsh plugin` 转发到的那个 pnpm 由 DSH Desktop 放在它私有的 runtime-commands 目录里,macOS 和 Windows 都是如此,守护进程会自动找到并加到 PATH 最前——包括较新版 Desktop 采用的带版本号目录结构。所以只有守护进程找不到的安装位置、或者你想让安装使用自己的 pnpm 时,才需要这个变量。一旦设置就完全取代自动查找:目录不存在时,安装会退回使用守护进程 `PATH` 上的 pnpm,而不是内置的那个。Linux 上没有 DSH Desktop,安装始终使用 `PATH`。ZeroClaw 支持 `MULTICA_ZEROCLAW_PATH`,但没有模型变量;模型由 ZeroClaw 的智能体配置管理。全机默认参数 `MULTICA_<PROVIDER>_ARGS` 目前支持 Claude Code、Codex、CodeBuddy、Qwen Code 和 QwenPaw 五款工具。对应变量是 `MULTICA_CLAUDE_ARGS`、`MULTICA_CODEX_ARGS`、`MULTICA_CODEBUDDY_ARGS`、`MULTICA_QWEN_ARGS` 和 `MULTICA_QWENPAW_ARGS`。例如:```dotenvMULTICA_CLAUDE_PATH=/opt/bin/claudediff --git a/apps/docs/content/docs/install-agent-runtime.ja.mdx b/apps/docs/content/docs/install-agent-runtime.ja.mdxindex fe41de6034..ac487d4032 100644--- a/apps/docs/content/docs/install-agent-runtime.ja.mdx+++ b/apps/docs/content/docs/install-agent-runtime.ja.mdx@@ -55,7 +55,7 @@ QwenPaw を使う場合は、QwenPaw 側の設定でプロバイダーとモデMiniMax Code を使う場合は、対応する Node.js バージョン(`>=22.19 <23` または `>=24 <27`)をインストールし、`npm install --global @minimax-ai/code@latest` を実行してください。npm のグローバルインストールによって `mcode` は npm のグローバル実行ファイルディレクトリに配置されます。`command -v mcode` または `Get-Command mcode` で見つからない場合は、そのディレクトリを `PATH` に追加してください。その後 `mcode login` を実行します。モデルは MiniMax Code が管理し、Multica から ACP 経由で上書きすることはできません。-DeepSeek Harness を使う場合は、Node.js 20+ をインストールして `npm install -g @deepseek-ai/dsh` を実行し、Multica ランタイムプロファイルを追加してください(`dsh plugin --profile multica add <bundle>`)。デーモンは `dsh --profile multica --probe` が成功した場合のみ DeepSeek Harness を登録します。デーモンを起動する前に `DEEPSEEK_API_KEY` を設定(または dsh の設定に保存)してください。+DeepSeek Harness を使う場合は、Node.js 20+ をインストールして `npm install -g @deepseek-ai/dsh` を実行し、Multica ランタイムプロファイルを追加してください。このバンドルが Multica の利用する `--stdio` プロトコルを提供しており、素の `dsh` だけでは使えない理由でもあります。`MULTICA_DSH_PROFILE_BUNDLE` にインストールするバンドルを設定すればデーモンが追加します。手動で行う場合は `dsh plugin --profile multica add <bundle>` を実行します。`<bundle>` は `dsh plugin` が受け付けるもの、つまり npm のパッケージ名、ディレクトリ、パック済み tarball のいずれかで、Multica 自身のブリッジは [multica-ai/dsh-multica-runtime](https://github.com/multica-ai/dsh-multica-runtime) にあります。これはまだ公開 npm レジストリに公開されていないため([multica#6936](https://github.com/multica-ai/multica/issues/6936))、現時点でセルフホストのチームはそのリポジトリからビルドし、変数をビルド出力のディレクトリに向けます。デーモンを動かすマシンとビルドしたマシンが別なら、`npm pack` が生成する tarball を指定してください。ブリッジが公開されれば、パッケージ名を指定するのが最も簡単になります。いずれの場合も、自チームが公開・ビルドしたものを優先してください。この値は追加の確認なしに各デーモンホストの DSH ホームへインストールされるため、素性の分からないサードパーティのパッケージを指定することは利便性の問題ではなくサプライチェーンの判断です。npm パッケージではなく DeepSeek Harness Desktop をインストールした場合、デーモンはそのアプリが生成する CLI シムも、アプリ自身のユーザーデータディレクトリから探します。macOS は `~/Library/Application Support/DSH Desktop`、Windows は `%APPDATA%\DSH Desktop` です。Windows のそれはローミングのアプリケーションデータであり、インストール先ではありません。アプリ自体は Program Files または `%LOCALAPPDATA%\Programs` に入りますが、駆動される CLI はユーザーごとの他の状態と同じ場所に置かれます。これらのパスのバージョン部分は生成された ID なので、デーモンは列挙して最新のものを優先します。PATH に他のものは必要ありません。生成されたシムはアプリ同梱のランタイムを絶対パスで起動します。DSH Desktop が既定以外の場所にある場合は `MULTICA_DSH_PATH` でそのシムを指定してください。デーモンは `dsh --profile multica --probe` が成功した場合のみ DeepSeek Harness を登録し、失敗した場合は `/health` にプロファイルの欠落を報告します。デーモンを起動する前に `DEEPSEEK_API_KEY` を設定(または dsh の設定に保存)してください。ログイン情報はツールがローカル環境に保存します。Multica が Claude、Codex、Cursor などの CLI のログイントークンを受け取ることはありません。@@ -102,7 +102,7 @@ Multica Desktop を使っている場合は、アプリを終了して開き直次に Multica の**ランタイム**ページを開きます。対象のコンピューターの下にツールが表示され、オンライン状態になっていることを確認してください。これで、エージェントを作成または編集するときにこのランタイムを選択できます。<Callout type="warning">-デーモンの起動時には、標準対応している CLI が少なくとも 1 つ検出される必要があります。カスタムランタイム設定はデーモンの起動後に同期されるため、ツールが何もないコンピューターで唯一の起動条件として使うことはできません。+デーモンの起動時には、標準対応している CLI が少なくとも 1 つ検出される必要があります。カスタムランタイム設定はデーモンの起動後に同期されるため、ツールが何もないコンピューターで唯一の起動条件として使うことはできません。例外は 1 つだけです。デーモンが DSH ランタイムプロファイルのインストール(`MULTICA_DSH_PROFILE_BUNDLE`)を開始した直後は、ランタイムが 1 つもない状態で起動し、そのインストールが完了した時点で DeepSeek Harness を登録します。そうしないと、プロファイルを必要とする DSH しかないコンピューターではインストールを完了できません。デーモンが完了前に終了し、インストール処理も道連れにしてしまうからです。</Callout>## ツールが検出されない場合diff --git a/apps/docs/content/docs/install-agent-runtime.ko.mdx b/apps/docs/content/docs/install-agent-runtime.ko.mdxindex 28e16e63e9..2956a138ff 100644--- a/apps/docs/content/docs/install-agent-runtime.ko.mdx+++ b/apps/docs/content/docs/install-agent-runtime.ko.mdx@@ -55,7 +55,7 @@ QwenPaw를 사용할 때는 QwenPaw 자체 설정에서 공급자와 모델을MiniMax Code를 사용하려면 지원되는 Node.js 버전(`>=22.19 <23` 또는 `>=24 <27`)을 설치한 뒤 `npm install --global @minimax-ai/code@latest`를 실행하세요. npm 전역 설치는 `mcode`를 npm의 전역 실행 파일 디렉터리에 추가합니다. `command -v mcode` 또는 `Get-Command mcode`에서 찾지 못하면 해당 디렉터리를 `PATH`에 추가하세요. 그다음 `mcode login`을 실행합니다. 모델은 MiniMax Code가 관리하며 Multica는 ACP를 통해 이를 덮어쓸 수 없습니다.-DeepSeek Harness를 사용하려면 Node.js 20+를 설치하고 `npm install -g @deepseek-ai/dsh`를 실행한 뒤 Multica 런타임 프로필을 추가하세요(`dsh plugin --profile multica add <bundle>`). 데몬은 `dsh --profile multica --probe`가 성공한 경우에만 DeepSeek Harness를 등록합니다. 데몬을 시작하기 전에 `DEEPSEEK_API_KEY`를 설정(또는 dsh 자체 설정에 저장)하세요.+DeepSeek Harness를 사용하려면 Node.js 20+를 설치하고 `npm install -g @deepseek-ai/dsh`를 실행한 뒤 Multica 런타임 프로필을 추가하세요. 이 번들이 Multica가 사용하는 `--stdio` 프로토콜을 제공하며, `dsh`만으로는 사용할 수 없는 이유이기도 합니다. `MULTICA_DSH_PROFILE_BUNDLE`에 설치할 번들을 설정하면 데몬이 대신 추가합니다. 직접 하려면 `dsh plugin --profile multica add <bundle>`을 실행하세요. `<bundle>`은 `dsh plugin`이 받아들이는 모든 형태 — npm 패키지 이름, 디렉터리, 패키징된 tarball — 이며, Multica 자체 브리지는 [multica-ai/dsh-multica-runtime](https://github.com/multica-ai/dsh-multica-runtime)에 있습니다. 아직 공개 npm 레지스트리에 게시되지 않았으므로([multica#6936](https://github.com/multica-ai/multica/issues/6936)), 현재 셀프호스트 팀은 해당 저장소에서 직접 빌드한 뒤 변수를 빌드 산출물 디렉터리로 지정합니다. 데몬을 실행하는 기기와 빌드한 기기가 다르면 `npm pack`이 만든 tarball을 지정하세요. 브리지가 게시되면 패키지 이름을 쓰는 것이 가장 간단합니다. 어느 쪽이든 팀이 직접 게시하거나 빌드한 산출물을 우선하세요. 이 값은 추가 확인 없이 모든 데몬 호스트의 DSH 홈에 설치되므로, 검증되지 않은 서드파티 패키지를 지정하는 것은 편의의 문제가 아니라 공급망에 관한 결정입니다. npm 패키지 대신 DeepSeek Harness Desktop을 설치했다면, 데몬은 그 앱이 생성하는 CLI 심(shim)도 앱 자체의 사용자 데이터 디렉터리에서 찾습니다. macOS는 `~/Library/Application Support/DSH Desktop`, Windows는 `%APPDATA%\DSH Desktop`입니다. Windows의 이 경로는 로밍 애플리케이션 데이터이지 설치 디렉터리가 아닙니다. 앱 자체는 Program Files 또는 `%LOCALAPPDATA%\Programs`에 설치되지만, 앱이 구동하는 CLI는 사용자별 다른 상태와 함께 저장됩니다. 이 경로의 버전 구간은 생성된 id이므로 데몬이 열거하여 가장 최신 것을 우선합니다. `PATH`에 다른 것이 필요하지 않습니다. 생성된 심은 앱에 포함된 런타임을 절대 경로로 실행합니다. DSH Desktop이 기본이 아닌 위치에 있다면 `MULTICA_DSH_PATH`로 그 심을 지정하세요. 데몬은 `dsh --profile multica --probe`가 성공한 경우에만 DeepSeek Harness를 등록하고, 실패하면 `/health`에 프로필 누락을 보고합니다. 데몬을 시작하기 전에 `DEEPSEEK_API_KEY`를 설정(또는 dsh 자체 설정에 저장)하세요.로그인 자격 증명은 도구가 로컬에 저장합니다. Multica는 Claude, Codex, Cursor 또는 다른 CLI의 로그인 token을 받지 않습니다.@@ -102,7 +102,7 @@ Multica Desktop을 사용한다면 앱을 종료한 뒤 다시 열면 됩니다.그런 다음 Multica의 **런타임** 페이지를 엽니다. 대상 컴퓨터 아래에 해당 도구가 나타나고 온라인으로 표시됩니다. 이제 에이전트를 만들거나 수정할 때 이 런타임을 선택할 수 있습니다.<Callout type="warning">-데몬이 시작될 때 기본 지원 CLI를 하나 이상 감지해야 합니다. 사용자 지정 런타임 설정은 데몬이 시작된 뒤 동기화되므로 빈 컴퓨터에서 유일한 시작 조건으로 사용할 수 없습니다.+데몬이 시작될 때 기본 지원 CLI를 하나 이상 감지해야 합니다. 사용자 지정 런타임 설정은 데몬이 시작된 뒤 동기화되므로 빈 컴퓨터에서 유일한 시작 조건으로 사용할 수 없습니다. 예외는 하나뿐입니다. 데몬이 DSH 런타임 프로필 설치(`MULTICA_DSH_PROFILE_BUNDLE`)를 막 시작한 경우에는 런타임 없이 시작하고, 그 설치가 끝나면 DeepSeek Harness를 등록합니다. 그렇지 않으면 프로필이 필요한 DSH만 설치된 컴퓨터에서는 설치를 끝낼 수 없습니다. 데몬이 완료 전에 종료하면서 설치 과정까지 함께 중단시키기 때문입니다.</Callout>## 도구가 감지되지 않을 때diff --git a/apps/docs/content/docs/install-agent-runtime.mdx b/apps/docs/content/docs/install-agent-runtime.mdxindex 1ad5187db5..c94077ceea 100644--- a/apps/docs/content/docs/install-agent-runtime.mdx+++ b/apps/docs/content/docs/install-agent-runtime.mdx@@ -55,7 +55,7 @@ For QwenPaw, choose the provider and model in QwenPaw's own configuration. MultiFor MiniMax Code, install a supported Node.js release (`>=22.19 <23` or `>=24 <27`) and run `npm install --global @minimax-ai/code@latest`. A global npm install places `mcode` on npm's global binary path; if `command -v mcode` or `Get-Command mcode` cannot find it, add that path to `PATH`. Then run `mcode login`. MiniMax Code owns the model selection; Multica cannot override it through ACP.-For DeepSeek Harness, install Node.js 20+ and run `npm install -g @deepseek-ai/dsh`, then add the Multica runtime profile to it (`dsh plugin --profile multica add <bundle>`). The daemon registers DeepSeek Harness only after `dsh --profile multica --probe` succeeds. Set `DEEPSEEK_API_KEY` (or store it in dsh's own settings) before starting the daemon.+For DeepSeek Harness, install Node.js 20+ and run `npm install -g @deepseek-ai/dsh`, then give it the Multica runtime profile — the bundle that implements the `--stdio` protocol Multica drives, and the reason a bare `dsh` is not usable on its own. Set `MULTICA_DSH_PROFILE_BUNDLE` to the bundle to install and the daemon adds it for you, or add it yourself with `dsh plugin --profile multica add <bundle>`. `<bundle>` is anything `dsh plugin` accepts — an npm package name, a directory, or a packed tarball — and Multica's own bridge lives at [multica-ai/dsh-multica-runtime](https://github.com/multica-ai/dsh-multica-runtime). It is not on a public npm registry yet ([multica#6936](https://github.com/multica-ai/multica/issues/6936)), so today a self-hosted team builds it from that repository and points the variable at the build directory, or at the tarball `npm pack` produces — the latter if the machine running the daemon is not the machine that built it. A package name becomes the simplest option once the bridge is published. Whatever you choose, prefer something your own team publishes or builds: this value is installed into every daemon host's DSH home without further confirmation, so an unvetted third-party package is a supply-chain decision, not a convenience. If you installed DeepSeek Harness Desktop instead of the npm package, the daemon also looks for the CLI shims that app generates, under its own per-user data directory — `~/Library/Application Support/DSH Desktop` on macOS, `%APPDATA%\DSH Desktop` on Windows. On Windows that is roaming application data, not the install directory: the app installs to Program Files or `%LOCALAPPDATA%\Programs`, but the CLI it drives lives beside its other per-user state. The version segment in those paths is a generated id, so the daemon enumerates them and prefers the newest. Nothing else is needed on `PATH` — a generated shim runs the Desktop app's own runtime by absolute path. If DSH Desktop is installed somewhere non-default, point `MULTICA_DSH_PATH` at the shim. The daemon registers DeepSeek Harness only after `dsh --profile multica --probe` succeeds, and reports the missing profile on `/health` when it does not. Set `DEEPSEEK_API_KEY` (or store it in dsh's own settings) before starting the daemon.Those login credentials are stored locally by the tool itself. Multica never receives login tokens from Claude, Codex, Cursor, or any other CLI.@@ -102,7 +102,7 @@ With Multica Desktop, quit and reopen the app.Then open Multica's **Runtimes** page. The tool appears under the target computer and shows as online. You can now select this runtime when creating or editing an agent.<Callout type="warning">-The daemon must detect at least one built-in supported CLI before it will start. Custom runtime profiles sync after the daemon is up, so they cannot be the sole startup condition on a blank machine.+The daemon must detect at least one built-in supported CLI before it will start. Custom runtime profiles sync after the daemon is up, so they cannot be the sole startup condition on a blank machine. There is one exception: when the daemon has just begun installing the DSH runtime profile itself (`MULTICA_DSH_PROFILE_BUNDLE`), it starts with no runtimes and registers DeepSeek Harness once that install finishes. Without it, a host whose only tool is a DSH that needs the profile could never complete the install — the daemon would exit before it finished and take it down with it.</Callout>## No tools detecteddiff --git a/apps/docs/content/docs/install-agent-runtime.zh.mdx b/apps/docs/content/docs/install-agent-runtime.zh.mdxindex 4d221b95b9..c4941ec6b8 100644--- a/apps/docs/content/docs/install-agent-runtime.zh.mdx+++ b/apps/docs/content/docs/install-agent-runtime.zh.mdx@@ -55,7 +55,7 @@ Multica 当前会检测以下命令:使用 MiniMax Code 时,请安装受支持的 Node.js 版本(`>=22.19 <23` 或 `>=24 <27`),并运行 `npm install --global @minimax-ai/code@latest`。全局 npm 安装会把 `mcode` 放入 npm 的全局可执行目录;如果 `command -v mcode` 或 `Get-Command mcode` 找不到它,请将该目录加入 `PATH`。然后运行 `mcode login`。模型由 MiniMax Code 管理,Multica 无法通过 ACP 覆盖它。-使用 DeepSeek Harness 时,请先安装 Node.js 20+ 并运行 `npm install -g @deepseek-ai/dsh`,然后为它安装 Multica 运行时 profile(`dsh plugin --profile multica add <bundle>`)。守护进程只有在 `dsh --profile multica --probe` 成功后才注册 DeepSeek Harness。启动守护进程前请设置 `DEEPSEEK_API_KEY`(或在 dsh 自身设置中保存)。+使用 DeepSeek Harness 时,请先安装 Node.js 20+ 并运行 `npm install -g @deepseek-ai/dsh`,然后为它安装 Multica 运行时 profile —— 这个 bundle 实现了 Multica 驱动的 `--stdio` 协议,也是单独的 `dsh` 无法直接使用的原因。把 `MULTICA_DSH_PROFILE_BUNDLE` 设为要安装的 bundle,守护进程会替你安装;也可以自己执行 `dsh plugin --profile multica add <bundle>`。`<bundle>` 可以是 `dsh plugin` 接受的任意形式——npm 包名、目录,或打包好的 tarball——Multica 自己的桥接实现在 [multica-ai/dsh-multica-runtime](https://github.com/multica-ai/dsh-multica-runtime)。它目前还没有发布到公共 npm registry([multica#6936](https://github.com/multica-ai/multica/issues/6936)),所以现阶段自托管团队的做法是:从该仓库自行构建,然后把变量指向构建产物目录;如果运行守护进程的机器和构建机器不是同一台,就指向 `npm pack` 产出的 tarball。等桥接发布之后,直接填包名是最省事的选择。无论选哪种,都优先用你们自己发布或构建的产物:这个值会在没有二次确认的情况下被装进每一台守护进程宿主的 DSH 家目录,填一个未经审查的第三方包是供应链决策,不是图方便。如果你装的是 DeepSeek Harness Desktop 而不是 npm 包,守护进程也会去找这个应用生成的 CLI shim,位置在它自己的用户级数据目录下:macOS 是 `~/Library/Application Support/DSH Desktop`,Windows 是 `%APPDATA%\DSH Desktop`。Windows 上这是漫游应用数据目录,不是安装目录:应用本身装在 Program Files 或 `%LOCALAPPDATA%\Programs`,但它驱动的 CLI 和其他用户级状态放在一起。这些路径里的版本层是生成出来的 id,所以守护进程会枚举并优先取最新的一份。不需要 PATH 上有别的东西——生成的 shim 会用绝对路径调用应用自带的运行时。如果 DSH Desktop 装在非默认位置,请用 `MULTICA_DSH_PATH` 指向那个 shim。守护进程只有在 `dsh --profile multica --probe` 成功后才注册 DeepSeek Harness;失败时会在 `/health` 报告缺少 profile。启动守护进程前请设置 `DEEPSEEK_API_KEY`(或在 dsh 自身设置中保存)。这些登录凭据由工具保存在本机。Multica 不会接收 Claude、Codex、Cursor 或其他 CLI 的登录 token。@@ -102,7 +102,7 @@ multica daemon restart然后打开 Multica 的**运行时**页面。目标电脑下面会出现对应工具,并显示为在线。现在可以在创建或编辑智能体时选择这条运行时。<Callout type="warning">-守护进程启动时必须先检测到至少一款内置支持的 CLI。自定义运行时配置会在守护进程启动后同步,因此不能作为一台空白机器上的唯一启动条件。+守护进程启动时必须先检测到至少一款内置支持的 CLI。自定义运行时配置会在守护进程启动后同步,因此不能作为一台空白机器上的唯一启动条件。只有一个例外:当守护进程刚开始自行安装 DSH 运行时 profile(`MULTICA_DSH_PROFILE_BUNDLE`)时,它会在没有任何运行时的情况下启动,并在安装完成后注册 DeepSeek Harness。否则,一台只装了需要该 profile 的 DSH 的机器永远装不完——守护进程会在安装结束前退出,并把安装进程一起带走。</Callout>## 未检测到工具diff --git a/packages/views/issues/blocked-trigger-copy.test.ts b/packages/views/issues/blocked-trigger-copy.test.tsindex 66efd8e72f..afaf8ae0ce 100644--- a/packages/views/issues/blocked-trigger-copy.test.ts+++ b/packages/views/issues/blocked-trigger-copy.test.ts@@ -57,6 +57,21 @@ describe("blocked trigger copy", () => {);});+ // A missing runtime profile is not a broken CLI: the CLI runs, and the+ // reinstall the unusable copy asks for fixes nothing. Sharing one label was+ // what told DSH users to reinstall a CLI that was never the problem.+ it("distinguishes a missing runtime profile from an unusable CLI", () => {+ const missingProfile = blockedReasonLabel("runtime_profile_missing", t);++ expect(missingProfile).toBe(en.comment.trigger_blocked_runtime_profile_missing);+ expect(missingProfile).not.toBe(blockedReasonLabel("runtime_unusable", t));+ expect(missingProfile).not.toBe(en.comment.trigger_blocked_generic);+ expect(missingProfile.toLowerCase()).not.toContain("reinstall");+ expect(blockedShortReasonLabel("runtime_profile_missing", t)).toBe(+ en.comment.trigger_blocked_short_runtime_profile_missing,+ );+ });+it("degrades an unknown code to the generic label", () => {expect(blockedReasonLabel("some_future_code", t)).toBe(en.comment.trigger_blocked_generic);expect(blockedShortReasonLabel("some_future_code", t)).toBe(diff --git a/packages/views/issues/blocked-trigger-copy.ts b/packages/views/issues/blocked-trigger-copy.tsindex e11165659d..dc79c65464 100644--- a/packages/views/issues/blocked-trigger-copy.ts+++ b/packages/views/issues/blocked-trigger-copy.ts@@ -23,6 +23,12 @@ import type { useT } from "../i18n";// sends the user to reconnect something that is already connected. The fix is a// reinstall on that machine, and the system comment the server leaves on the// issue carries the exact command.+//+// `runtime_profile_missing` is the fourth, and is split from `runtime_unusable`+// on the same rule: the CLI there runs perfectly and is missing a runtime+// profile (DSH's `multica` profile, which supplies the protocol Multica+// drives). "Reinstall the CLI" copy sends the user to re-run an install that+// was never broken; the fix is installing the profile.type IssuesT = ReturnType<typeof useT<"issues">>["t"];// Full sentence — for tooltips and other surfaces with room to explain.@@ -36,6 +42,8 @@ export function blockedReasonLabel(reasonCode: string, t: IssuesT): string {return t(($) => $.comment.trigger_blocked_runtime_offline);case "runtime_unusable":return t(($) => $.comment.trigger_blocked_runtime_unusable);+ case "runtime_profile_missing":+ return t(($) => $.comment.trigger_blocked_runtime_profile_missing);case "agent_runtime_required":return t(($) => $.comment.trigger_blocked_agent_runtime_required);default:@@ -55,6 +63,8 @@ export function blockedShortReasonLabel(reasonCode: string, t: IssuesT): stringreturn t(($) => $.comment.trigger_blocked_short_runtime_offline);case "runtime_unusable":return t(($) => $.comment.trigger_blocked_short_runtime_unusable);+ case "runtime_profile_missing":+ return t(($) => $.comment.trigger_blocked_short_runtime_profile_missing);case "agent_runtime_required":return t(($) => $.comment.trigger_blocked_short_agent_runtime_required);default:diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex a21b331d69..e890c2be0c 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -517,12 +517,14 @@"trigger_blocked_target_unavailable": "This target is unavailable","trigger_blocked_runtime_offline": "This target's runtime is offline","trigger_blocked_runtime_unusable": "This target's agent CLI can't run on its machine — reinstall it there",+ "trigger_blocked_runtime_profile_missing": "This target's agent CLI is missing a runtime profile on its machine — install it there","trigger_blocked_agent_runtime_required": "This target has no runtime — bind one to run it","trigger_blocked_generic": "This target won't be triggered","trigger_blocked_short_invocation_not_allowed": "Not found or no permission","trigger_blocked_short_target_unavailable": "Unavailable","trigger_blocked_short_runtime_offline": "Runtime offline","trigger_blocked_short_runtime_unusable": "CLI can't run",+ "trigger_blocked_short_runtime_profile_missing": "Runtime profile missing","trigger_blocked_short_agent_runtime_required": "Needs a runtime","trigger_blocked_short_generic": "Won't start","send_reply_failed": "Failed to send reply",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 1f13d69e58..bec50ffb7d 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -507,12 +507,14 @@"trigger_blocked_target_unavailable": "この対象は利用できません","trigger_blocked_runtime_offline": "この対象のランタイムがオフラインです","trigger_blocked_runtime_unusable": "この対象の CLI はそのマシンで実行できません — そのマシンで再インストールしてください",+ "trigger_blocked_runtime_profile_missing": "この対象の CLI はそのマシンでランタイム プロファイルが不足しています — そのマシンでインストールしてください","trigger_blocked_agent_runtime_required": "この対象にはランタイムがありません — 実行するにはバインドしてください","trigger_blocked_generic": "この対象はトリガーされません","trigger_blocked_short_invocation_not_allowed": "未検出または権限なし","trigger_blocked_short_target_unavailable": "利用不可","trigger_blocked_short_runtime_offline": "ランタイム オフライン","trigger_blocked_short_runtime_unusable": "CLI を実行できません",+ "trigger_blocked_short_runtime_profile_missing": "ランタイム プロファイル未導入","trigger_blocked_short_agent_runtime_required": "ランタイム未設定","trigger_blocked_short_generic": "トリガーされません","send_reply_failed": "返信を送信できませんでした",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex 6efc5856fd..49b687f8e2 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -507,12 +507,14 @@"trigger_blocked_target_unavailable": "이 대상을 사용할 수 없습니다","trigger_blocked_runtime_offline": "이 대상의 런타임이 오프라인입니다","trigger_blocked_runtime_unusable": "이 대상의 CLI를 해당 기기에서 실행할 수 없습니다 — 그 기기에서 다시 설치하세요",+ "trigger_blocked_runtime_profile_missing": "이 대상의 CLI에 해당 기기의 런타임 프로필이 없습니다 — 그 기기에서 설치하세요","trigger_blocked_agent_runtime_required": "이 대상에 런타임이 없습니다 — 실행하려면 런타임을 연결하세요","trigger_blocked_generic": "이 대상은 트리거되지 않습니다","trigger_blocked_short_invocation_not_allowed": "찾을 수 없음 또는 권한 없음","trigger_blocked_short_target_unavailable": "사용 불가","trigger_blocked_short_runtime_offline": "런타임 오프라인","trigger_blocked_short_runtime_unusable": "CLI 실행 불가",+ "trigger_blocked_short_runtime_profile_missing": "런타임 프로필 없음","trigger_blocked_short_agent_runtime_required": "런타임 필요","trigger_blocked_short_generic": "트리거 안 됨","send_reply_failed": "답글을 보내지 못했습니다",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex 30e5978678..55479af0e7 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -507,12 +507,14 @@"trigger_blocked_target_unavailable": "该目标不可用","trigger_blocked_runtime_offline": "该目标的运行时已离线","trigger_blocked_runtime_unusable": "该目标的 CLI 在它所在的机器上无法运行 —— 需要在那台机器上重装",+ "trigger_blocked_runtime_profile_missing": "该目标的 CLI 在它所在的机器上缺少运行时 profile —— 需要在那台机器上安装","trigger_blocked_agent_runtime_required": "该目标未绑定运行时——绑定后才能运行","trigger_blocked_generic": "该目标不会被触发","trigger_blocked_short_invocation_not_allowed": "找不到或无权限","trigger_blocked_short_target_unavailable": "不可用","trigger_blocked_short_runtime_offline": "运行时离线","trigger_blocked_short_runtime_unusable": "CLI 无法运行",+ "trigger_blocked_short_runtime_profile_missing": "缺少运行时 profile","trigger_blocked_short_agent_runtime_required": "需绑定运行时","trigger_blocked_short_generic": "不会触发","send_reply_failed": "发送回复失败",diff --git a/server/internal/daemon/agents_probe.go b/server/internal/daemon/agents_probe.goindex 3b590ea018..0551c32c1c 100644--- a/server/internal/daemon/agents_probe.go+++ b/server/internal/daemon/agents_probe.go@@ -6,10 +6,12 @@ import ("os""os/exec""path/filepath"+ "runtime""strings""sync""time"+ "github.com/multica-ai/multica/server/internal/daemon/processtree""github.com/multica-ai/multica/server/pkg/agent")@@ -149,6 +151,27 @@ var probeAgentCLIs = func() map[string]AgentEntry {}}}+ if defaultCmd == "dsh" && cmd == defaultCmd {+ // DeepSeek Harness Desktop bundles its CLI inside the macOS app+ // instead of installing `dsh` onto PATH, and the login-shell+ // fallback above cannot rescue it: no rc file knows that path.+ // The candidate is a Node script rather than a native binary, so+ // it only counts while it is executable — an entry discovered+ // without the executable bit would be advertised as a healthy+ // runtime and then fail on every spawn.+ //+ // The Multica runtime profile gate in the caller still applies:+ // a bundled CLI without the `multica` profile is not a runtime.+ for _, p := range dshDesktopAppBundlePaths() {+ if executableCandidate(p) {+ return AgentEntry{+ Path: p,+ Command: cmd,+ Model: strings.TrimSpace(os.Getenv(modelEnv)),+ }, true+ }+ }+ }return AgentEntry{}, false}@@ -222,10 +245,15 @@ var probeAgentCLIs = func() map[string]AgentEntry {if e, ok := probe("MULTICA_REASONIX_PATH", "reasonix", "MULTICA_REASONIX_MODEL"); ok {agents["reasonix"] = e}- // DSH is registered only when its Multica runtime profile is installed.- // A bare dsh binary is not enough: without the bundle it has no --stdio- // protocol and every task would fail after being advertised as healthy.- if e, ok := probe("MULTICA_DSH_PATH", "dsh", "MULTICA_DSH_MODEL"); ok && probeDshMulticaProfile(e.Path) {+ // DSH resolves here like any other CLI. Whether it is *usable* is decided+ // one layer up: the Multica runtime profile is what gives it the --stdio+ // protocol, so a bare `dsh` prints a version and still cannot run a task.+ // That check lives in probeBuiltinRuntime, where a failure produces a+ // verdict the user can actually see — /health reports it as a skipped+ // agent carrying the repair command, and the daemon logs it. Gating here+ // instead made the drop invisible: the provider vanished from the+ // availability set with nothing anywhere saying why.+ if e, ok := probe("MULTICA_DSH_PATH", "dsh", "MULTICA_DSH_MODEL"); ok {agents["dsh"] = e}if e, ok := probe("MULTICA_KIRO_PATH", "kiro-cli", "MULTICA_KIRO_MODEL"); ok {@@ -306,25 +334,156 @@ var probeAgentCLIs = func() map[string]AgentEntry {return agents}-func probeDshMulticaProfile(executablePath string) bool {- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)- defer cancel()- cmd := exec.CommandContext(ctx, executablePath, "--profile", "multica", "--probe")- cmd.WaitDelay = time.Second- output, err := cmd.Output()- if err != nil {+// executableCandidate reports whether a Desktop-app bundle candidate can be+// spawned directly. Bundle candidates reached through probe() never went+// through exec.LookPath, which is what normally enforces this.+//+// "Executable" is not the same fact on both platforms, and the difference is+// not cosmetic. On Unix it is the executable bit — the macOS candidate is a+// Node script that runs through its shebang, and one that lost its bit would be+// advertised as a healthy runtime and then fail on every spawn.+//+// Windows has no such bit: Go synthesizes a regular file's mode from the+// read-only attribute and never sets 0111 on one, so the Unix test would reject+// every candidate and the whole fallback would be dead code there. What decides+// on Windows is the extension, and exec.LookPath is the component that already+// knows the rule (PATHEXT) — the same check agentExecutablePresent makes, so a+// candidate accepted here is one the launcher can actually start.+func executableCandidate(path string) bool {+ info, err := os.Stat(path)+ if err != nil || info.IsDir() {return false}- for _, line := range strings.Split(string(output), "\n") {- var frame struct {- Version int `json:"v"`- Type string `json:"type"`- Runtime string `json:"runtime"`- ProtocolVersion int `json:"protocol_version"`+ if runtime.GOOS == "windows" {+ _, err := exec.LookPath(path)+ return err == nil+ }+ return info.Mode().Perm()&0o111 != 0+}++// dshProbeFrame is the discovery frame a Multica-capable DSH profile prints for+// `--probe`. Only these fields are read; the bundle owns everything else.+type dshProbeFrame struct {+ Version int `json:"v"`+ Type string `json:"type"`+ Runtime string `json:"runtime"`+ ProtocolVersion int `json:"protocol_version"`+}++// dshProbeVerdict is what `dsh --profile multica --probe` actually said.+//+// The distinction is the point. "The profile is not installed" is a confirmed,+// locally repairable fact that justifies installing it and taking a live+// runtime offline; a timeout or an unparseable answer is evidence about this+// instant and nothing more. Collapsing both into one bool is what let a+// momentary failure during a DSH upgrade demote a working runtime, and — with a+// bundle configured — start overwriting an installation that was already there.+type dshProbeVerdict int++const (+ // dshProbeOK: the profile answered with the protocol version this backend drives.+ dshProbeOK dshProbeVerdict = iota+ // dshProbeMissingProfile: the probe ran and no profile manifest is present,+ // which is the same fact DSH itself checks before refusing to boot. This is+ // the only verdict that may install a bundle or condemn the runtime.+ dshProbeMissingProfile+ // dshProbeIncompatible: something answered, with a protocol this daemon does+ // not drive. The profile is installed, so installing over it would replace a+ // deliberate configuration with one this daemon still cannot drive.+ dshProbeIncompatible+ // dshProbeUnavailable: nothing usable was learned — the probe timed out,+ // could not be executed, or printed something unparseable. Transient.+ dshProbeUnavailable+)++// dshProbeTimeout bounds one `--probe`.+//+// The healthy path boots a whole DSH process — on a Desktop install that means+// starting the app's Electron binary as node — and then prints one line. Five+// seconds was too thin for that on a cold VM, and cutting a slow-but-healthy+// probe short reports it as unusable. This is generous instead, because the+// cost is paid only by a probe that has nothing to say, and it stays well+// inside the daemon's own 45s startup window.+//+// A missing profile does spend the whole budget here: DSH does not refuse the+// probe, it hangs. That is bounded by construction — the state ends the moment+// someone installs the profile — and the verdict below no longer depends on+// telling that hang apart from a busy machine.+//+// A var so tests can shrink it instead of waiting out a real timeout.+var dshProbeTimeout = 15 * time.Second++// parseDshProbeFrame returns the first decodable probe frame in the output.+func parseDshProbeFrame(output string) (dshProbeFrame, bool) {+ for _, line := range strings.Split(output, "\n") {+ var frame dshProbeFrame+ if json.Unmarshal([]byte(line), &frame) != nil {+ continue}- if json.Unmarshal([]byte(line), &frame) == nil && frame.Version == 1 && frame.Type == "probe" && frame.Runtime == "dsh" && frame.ProtocolVersion == 1 {- return true+ if frame.Type == "probe" && frame.Runtime != "" {+ return frame, true}}- return false+ return dshProbeFrame{}, false+}++// probeDshMulticaProfile classifies one `--probe` attempt. See dshProbeVerdict+// for why this is not a bool.+//+// Scoped to the caller's context as well as its own timeout: `--probe` boots a+// whole DSH process, and a round abandoned by a shutting-down daemon should not+// go on holding one for the rest of the timeout — once per retry, per provider.+func probeDshMulticaProfile(ctx context.Context, executablePath string) dshProbeVerdict {+ parent := ctx+ ctx, cancel := context.WithTimeout(parent, dshProbeTimeout)+ defer cancel()+ cmd := exec.CommandContext(ctx, executablePath, "--profile", dshMulticaProfileName, "--probe")+ // processtree, not cmd.Output: `--probe` boots a whole DSH profile, so the+ // process it starts is a tree. Killing only the direct child leaves+ // grandchildren holding the stdout pipe open — which is both a leaked+ // process and, as this probe's own tests showed, a wait that outlives the+ // timeout it was supposed to be bounded by.+ output, _ := processtree.Output(ctx, cmd, time.Second)++ // The frame decides, not the exit status. A profile that printed a valid+ // answer has answered, whatever the process did on its way out — and the+ // run helper reports a lifecycle error for a tree that outlived its leader,+ // which says nothing about the protocol.+ //+ // agent.DshProtocolVersion, not a local copy: this decides whether the+ // daemon may drive the profile, and the code that drives it is the only+ // honest source for that number.+ if frame, ok := parseDshProbeFrame(string(output)); ok {+ if frame.Version == 1 && frame.Runtime == "dsh" && frame.ProtocolVersion == agent.DshProtocolVersion {+ return dshProbeOK+ }+ return dshProbeIncompatible+ }++ // No usable answer. A cancelled ROUND is the one case that says nothing+ // about the profile: the daemon is shutting down, or this round was+ // abandoned, and the probe never got to finish on its own terms.+ if parent.Err() != nil {+ return dshProbeUnavailable+ }++ // Otherwise the manifest decides, and how the probe failed does not.+ //+ // Timeouts used to be classed transient on the reasoning that a busy+ // machine is not a missing profile. That reasoning does not survive+ // contact with DSH: asked for a profile it does not have, `--probe` does+ // not refuse — it HANGS, printing nothing, until something kills it. So a+ // timeout is the ordinary way a missing profile presents, and treating it+ // as transient made the profile undetectable on exactly the host the+ // install exists for: the daemon reported "the probe returned no usable+ // answer", never started the install, and exited for want of a runtime.+ //+ // The manifest is the same file DSH's own loadProfile consults before it+ // refuses to boot, so a confirmed-absent one is evidence, not a guess —+ // while a manifest that IS present keeps every failure transient, which is+ // what protects a working install from being overwritten during an upgrade.+ if !dshMulticaProfilePresent() {+ return dshProbeMissingProfile+ }+ return dshProbeUnavailable}diff --git a/server/internal/daemon/agents_probe_dsh_test.go b/server/internal/daemon/agents_probe_dsh_test.goindex 0b0cb7ddf2..e1472cbcdf 100644--- a/server/internal/daemon/agents_probe_dsh_test.go+++ b/server/internal/daemon/agents_probe_dsh_test.go@@ -1,40 +1,223 @@package daemonimport (+ "context"+ "io"+ "log/slog""os""path/filepath""runtime"+ "strings""testing"+ "time")+// dshProbeFixture writes a fake dsh and controls the one filesystem fact the+// classification turns on: whether the `multica` profile manifest is present.+// DSH_HOME is pinned so the answer never depends on the machine running the+// test.+//+// body answers `--probe`; every other invocation reports a version. That split+// is the premise of the whole feature, not fixture decoration: a dsh whose+// profile is missing runs, resolves, and answers `--version` perfectly well —+// being unable to answer `--probe` is the ONLY thing wrong with it. A fixture+// that failed both would be a broken CLI, which the daemon now classifies as a+// failed version probe and never as a profile verdict.+func dshProbeFixture(t *testing.T, body string, manifest bool) string {+ t.Helper()+ home := t.TempDir()+ t.Setenv("DSH_HOME", home)+ if manifest {+ dir := filepath.Join(home, "profiles", dshMulticaProfileName)+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(dir, "package.json"), []byte("{}\n"), 0o644); err != nil {+ t.Fatal(err)+ }+ }+ path := filepath.Join(t.TempDir(), "dsh")+ script := "#!/bin/sh\ncase \"$*\" in\n *--probe*) " + body + " ;;\n *) printf '%s\\n' '0.1.2-rc.1' ;;\nesac\n"+ if err := os.WriteFile(path, []byte(script), 0o755); err != nil {+ t.Fatal(err)+ }+ return path+}++const dshProbeOKFrame = `printf '%s\n' '{"v":1,"type":"probe","runtime":"dsh","plugin_version":"test","protocol_version":1}'`++// Only a profile that is genuinely absent may be installed or condemned. Every+// other failure mode is a statement about this instant, and treating them alike+// is what let a momentary failure during a DSH upgrade demote a working runtime+// and start overwriting an installation that was already there.func TestProbeDshMulticaProfile(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell fixture")+ }+ tests := []struct {+ name string+ body string+ manifest bool+ want dshProbeVerdict+ }{+ {+ name: "compatible", body: dshProbeOKFrame, manifest: true, want: dshProbeOK,+ },+ {+ name: "profile absent and the probe says so",+ body: `printf '%s\n' 'profile "multica" does not exist' >&2; exit 1`,+ want: dshProbeMissingProfile,+ },+ {+ name: "profile absent and the probe fails opaquely",+ body: `printf '%s\n' 'boom' >&2; exit 3`, want: dshProbeMissingProfile,+ },+ {+ name: "manifest present but the probe exits non-zero",+ body: `printf '%s\n' 'cannot boot' >&2; exit 1`,+ manifest: true, want: dshProbeUnavailable,+ },+ {+ name: "manifest present but the probe times out",+ body: `exec sleep 30`, manifest: true, want: dshProbeUnavailable,+ },+ {+ // The case the whole classification turns on. Asked for a profile+ // it does not have, DSH does not refuse — it hangs, printing+ // nothing. Calling that transient made a missing profile+ // undetectable on the one host the automatic install exists for.+ name: "probe hangs with no manifest",+ body: `exec sleep 30`, want: dshProbeMissingProfile,+ },+ {+ name: "exit 0 printing nothing, no manifest",+ body: `exit 0`, want: dshProbeMissingProfile,+ },+ {+ // A frame is an answer even when the process exits badly+ // afterwards: the profile spoke the protocol.+ name: "valid frame followed by a non-zero exit",+ body: dshProbeOKFrame + `; exit 3`,+ manifest: true, want: dshProbeOK,+ },+ {+ name: "manifest present but the output is unparseable",+ body: `printf '%s\n' 'not json at all'`,+ manifest: true, want: dshProbeUnavailable,+ },+ {+ name: "exit 0 printing nothing",+ body: `exit 0`, manifest: true, want: dshProbeUnavailable,+ },+ {+ name: "manifset present and the protocol is newer",+ body: `printf '%s\n' '{"v":2,"type":"probe","runtime":"dsh","protocol_version":2}'`,+ manifest: true, want: dshProbeIncompatible,+ },+ {+ name: "manifest present and the runtime is something else",+ body: `printf '%s\n' '{"v":1,"type":"probe","runtime":"other","protocol_version":1}'`,+ manifest: true, want: dshProbeIncompatible,+ },+ }+ origTimeout := dshProbeTimeout+ t.Cleanup(func() { dshProbeTimeout = origTimeout })+ dshProbeTimeout = 2 * time.Second++ // A cancelled round says nothing about the profile, whatever the manifest+ // says: the probe never got to finish on its own terms.+ t.Run("a cancelled round stays transient", func(t *testing.T) {+ path := dshProbeFixture(t, `exec sleep 30`, false)+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ if got := probeDshMulticaProfile(ctx, path); got != dshProbeUnavailable {+ t.Fatalf("probeDshMulticaProfile() = %v, want %v", got, dshProbeUnavailable)+ }+ })++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ path := dshProbeFixture(t, tc.body, tc.manifest)+ if got := probeDshMulticaProfile(context.Background(), path); got != tc.want {+ t.Fatalf("probeDshMulticaProfile() = %v, want %v", got, tc.want)+ }+ })+ }+}++// The four ways a probe can fail while the profile IS installed must not+// condemn the runtime and must not install anything over it. Each previously+// collapsed into "missing profile", which demoted immediately and, with a+// bundle configured, started overwriting the operator's installation.+//+// "Not condemned" is asserted through demotableBuiltinProbeVerdict rather than+// by naming the verdicts this must not be: the property under test is that no+// route from here reaches a demotion, and a verdict added to the demotable set+// later has to fail this test rather than slip past a list of names.+func TestProbeBuiltinRuntime_DshFailureWithProfileInstalledIsNotCondemned(t *testing.T) {if runtime.GOOS == "windows" {t.Skip("shell fixture")}tests := []struct {name stringbody string- want bool}{- {name: "compatible", body: `printf '%s\n' '{"v":1,"type":"probe","runtime":"dsh","plugin_version":"test","protocol_version":1}'`, want: true},- {name: "missing plugin", body: `printf '%s\n' 'profile not installed'`, want: false},- {name: "future protocol", body: `printf '%s\n' '{"v":2,"type":"probe","runtime":"dsh","protocol_version":2}'`, want: false},+ {name: "timeout", body: `exec sleep 30`},+ {name: "non-zero exit", body: `printf '%s\n' 'cannot boot' >&2; exit 1`},+ {name: "malformed output", body: `printf '%s\n' 'not json at all'`},+ {name: "future protocol", body: `printf '%s\n' '{"v":2,"type":"probe","runtime":"dsh","protocol_version":2}'`},}+ origTimeout, origDelay, origWindow := dshProbeTimeout, runtimeVersionProbeRetryDelay, runtimeVersionProbeRetryWindow+ t.Cleanup(func() {+ dshProbeTimeout, runtimeVersionProbeRetryDelay, runtimeVersionProbeRetryWindow = origTimeout, origDelay, origWindow+ })+ dshProbeTimeout = 300 * time.Millisecond+ runtimeVersionProbeRetryDelay = time.Millisecond+ runtimeVersionProbeRetryWindow = 10 * time.Millisecond+for _, tc := range tests {t.Run(tc.name, func(t *testing.T) {- path := filepath.Join(t.TempDir(), "dsh")- script := "#!/bin/sh\nset -eu\n" + tc.body + "\n"- if err := os.WriteFile(path, []byte(script), 0o755); err != nil {- t.Fatal(err)+ path := dshProbeFixture(t, tc.body, true)+ record := filepath.Join(t.TempDir(), "provisioned.log")+ // A bundle IS configured: the assertion is that these failures never+ // reach the install path.+ t.Setenv(dshProfileBundleEnv, "@multica-ai/dsh-runtime")+ t.Setenv("DSH_TEST_RECORD", record)++ d := &Daemon{+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ agentVersions: map[string]string{},}- if got := probeDshMulticaProfile(path); got != tc.want {- t.Fatalf("probeDshMulticaProfile() = %v, want %v", got, tc.want)+ _, reason, verdict := d.probeBuiltinRuntime(context.Background(), "dsh",+ AgentEntry{Path: path, Command: "dsh"})++ if verdict == builtinProbeMissingProfile {+ t.Fatalf("verdict = missing profile (reason %q); a failing probe over an installed profile must not be installable", reason)+ }+ if verdict == builtinProbeOK {+ t.Fatalf("verdict = OK for a probe that produced no usable answer")+ }+ if demotableBuiltinProbeVerdict(verdict) {+ t.Fatalf("verdict %v (reason %q) can take a live runtime offline; "++ "an installed profile behind one failed probe is not evidence for that", verdict, reason)+ }+ // The install runs in a goroutine; give it a chance to be wrong.+ time.Sleep(200 * time.Millisecond)+ if data, err := os.ReadFile(record); err == nil {+ t.Fatalf("the provisioning path ran against an installed profile: %s", data)}})}}-func TestProbeAgentCLIsRequiresDshMulticaProfile(t *testing.T) {+// Discovery is deliberately profile-blind: probeAgentCLIs answers "is there a+// dsh binary here", and the usability gate lives one layer up in+// probeBuiltinRuntime, where a drop produces a verdict the user can see.+//+// Gating discovery on the profile instead — which this test used to assert —+// is what made a missing profile invisible: dsh vanished from the availability+// set with nothing on /health, in the log, or in `daemon status` to say why.+func TestProbeAgentCLIsDiscoversDshWithoutMulticaProfile(t *testing.T) {if runtime.GOOS == "windows" {t.Skip("shell fixture")}@@ -43,26 +226,262 @@ func TestProbeAgentCLIsRequiresDshMulticaProfile(t *testing.T) {resolveAgentsViaLoginShell = func([]string) map[string]string { return map[string]string{} }resetShellResolveCacheForTest(t)+ fakeDir := t.TempDir()+ path := filepath.Join(fakeDir, "dsh")+ body := "#!/bin/sh\nset -eu\nprintf '%s\\n' 'missing multica profile' >&2\nexit 1\n"+ if err := os.WriteFile(path, []byte(body), 0o755); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PATH", fakeDir)+ t.Setenv("MULTICA_DSH_PATH", "")++ entry, found := probeAgentCLIs()["dsh"]+ if !found {+ t.Fatal("dsh was not discovered; discovery must not depend on the Multica runtime profile")+ }+ if want := canonicalExecutablePath(path); entry.Path != want {+ t.Fatalf("dsh path = %q, want %q", entry.Path, want)+ }+}++// The gate that discovery gave up lives here now, and its verdict is what makes+// the drop visible. A dsh whose profile is missing resolves and answers+// `--version` like any healthy CLI, so without this verdict the daemon would+// register a runtime that fails every task it is handed.+//+// The manifest is what decides, so the fixture owns it: a probe that fails over+// an installed profile is not the same finding as one that fails with nothing+// installed, and only the second may be installed over.+func TestProbeBuiltinRuntime_DshWithoutMulticaProfile(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell fixture")+ }+ tests := []struct {+ name string+ probeBody string+ manifest bool+ wantVerdict builtinProbeVerdict+ }{+ {+ name: "profile installed",+ probeBody: dshProbeOKFrame,+ manifest: true,+ wantVerdict: builtinProbeOK,+ },+ {+ name: "profile missing",+ probeBody: `printf '%s\n' 'profile "multica" does not exist' >&2; exit 1`,+ wantVerdict: builtinProbeMissingProfile,+ },+ }+ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ path := dshProbeFixture(t, tc.probeBody, tc.manifest)++ d := &Daemon{+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ agentVersions: map[string]string{},+ }+ _, reason, verdict := d.probeBuiltinRuntime(+ context.Background(), "dsh", AgentEntry{Path: path, Command: "dsh"})+ if verdict != tc.wantVerdict {+ t.Fatalf("verdict = %v, want %v (reason %q)", verdict, tc.wantVerdict, reason)+ }+ if tc.wantVerdict == builtinProbeMissingProfile && !strings.Contains(reason, "profile") {+ t.Fatalf("reason = %q, want it to name the missing runtime profile", reason)+ }+ })+ }+}++// A binary that is not there must not be reported as a missing profile. The+// probe cannot tell "the profile refused" from "there was nothing to run", so+// without the executable check the reason sends the user to install a bundle+// that is not the problem, while the path that actually vanished goes+// unmentioned.+func TestProbeBuiltinRuntime_DshBinaryGoneIsNotAProfileVerdict(t *testing.T) {+ d := &Daemon{+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ agentVersions: map[string]string{},+ }+ gone := filepath.Join(t.TempDir(), "dsh-that-was-removed")+ _, reason, verdict := d.probeBuiltinRuntime(context.Background(), "dsh",+ AgentEntry{Path: gone, Command: ""})+ if verdict == builtinProbeMissingProfile {+ t.Fatalf("verdict = missing profile (reason %q), want the version-detection path to report the vanished binary", reason)+ }+}++// dshDesktopBundleFixture writes a fake DSH Desktop bundled CLI that answers+// `--probe` the way the Multica runtime profile does, and pins discovery to+// it. The DSH Desktop app ships its CLI inside the .app bundle and never+// installs `dsh` onto PATH, so neither LookPath nor the login-shell sweep can+// find it.+func dshDesktopBundleFixture(t *testing.T, mode os.FileMode) string {+ t.Helper()+ originalResolver := resolveAgentsViaLoginShell+ t.Cleanup(func() { resolveAgentsViaLoginShell = originalResolver })+ resolveAgentsViaLoginShell = func([]string) map[string]string { return map[string]string{} }+ resetShellResolveCacheForTest(t)++ bundle := filepath.Join(t.TempDir(), "DSH Desktop.app", "Contents", "Resources",+ "app.asar.unpacked", "node_modules", "@deepseek-ai", "dsh", "lib", "bin.js")+ if err := os.MkdirAll(filepath.Dir(bundle), 0o755); err != nil {+ t.Fatal(err)+ }+ script := "#!/bin/sh\nset -eu\n" + `printf '%s\n' '{"v":1,"type":"probe","runtime":"dsh","plugin_version":"test","protocol_version":1}'` + "\n"+ if err := os.WriteFile(bundle, []byte(script), mode); err != nil {+ t.Fatal(err)+ }++ originalBundles := dshDesktopAppBundlePaths+ dshDesktopAppBundlePaths = func() []string { return []string{bundle} }+ t.Cleanup(func() { dshDesktopAppBundlePaths = originalBundles })++ t.Setenv("PATH", t.TempDir())+ t.Setenv("MULTICA_DSH_PATH", "")+ t.Setenv("MULTICA_DSH_MODEL", "deepseek-official/deepseek-chat")+ return bundle+}++func TestProbeAgentCLIsUsesDshDesktopAppBundleFallback(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("the DSH Desktop app bundle fallback is macOS-only")+ }+ bundle := dshDesktopBundleFixture(t, 0o755)++ entry, found := probeAgentCLIs()["dsh"]+ if !found {+ t.Fatal("dsh was not discovered from the DSH Desktop app bundle")+ }+ if entry.Path != bundle {+ t.Fatalf("dsh path = %q, want %q", entry.Path, bundle)+ }+ if entry.Command != "dsh" {+ t.Fatalf("dsh command = %q, want dsh", entry.Command)+ }+ if entry.Model != "deepseek-official/deepseek-chat" {+ t.Fatalf("dsh model = %q, want the MULTICA_DSH_MODEL override", entry.Model)+ }+}++// A bundled CLI that exists but cannot be spawned must stay unregistered:+// registering it would advertise a healthy runtime whose every task fails.+func TestProbeAgentCLIsIgnoresNonExecutableDshBundle(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("the DSH Desktop app bundle fallback is macOS-only")+ }+ dshDesktopBundleFixture(t, 0o644)++ if _, found := probeAgentCLIs()["dsh"]; found {+ t.Fatal("dsh was registered from a non-executable app bundle path")+ }+}++// The Windows incident, as a test: DSH Desktop's CLI is a .cmd shim that+// exec.LookPath resolves happily and that exits 9009 — cmd.exe's "command not+// found" — because what it forwards to is missing. Every invocation fails,+// `--version` included.+//+// Probing the profile before version detection reported that machine as "the+// Multica runtime profile is not installed": a repair for a problem it did not+// have, sending the user to install a bundle while the actual fault was a CLI+// that cannot execute — and, with a bundle configured, starting that install+// against it. A CLI that cannot answer `--version` is not one this daemon has+// any business holding an opinion about the profile of.+func TestProbeBuiltinRuntime_DshThatCannotRunIsNotAProfileVerdict(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell fixture")+ }+ origDelay, origWindow := runtimeVersionProbeRetryDelay, runtimeVersionProbeRetryWindow+ t.Cleanup(func() {+ runtimeVersionProbeRetryDelay, runtimeVersionProbeRetryWindow = origDelay, origWindow+ })+ runtimeVersionProbeRetryDelay = time.Millisecond+ runtimeVersionProbeRetryWindow = 10 * time.Millisecond++ // No DSH_HOME profile and a CLI that fails whatever it is asked — the exact+ // shape that used to be classified as a missing profile.+ home := t.TempDir()+ t.Setenv("DSH_HOME", home)+ path := filepath.Join(t.TempDir(), "dsh")+ if err := os.WriteFile(path, []byte("#!/bin/sh\nexit 9009\n"), 0o755); err != nil {+ t.Fatal(err)+ }+ record := filepath.Join(t.TempDir(), "provisioned.log")+ // A bundle IS configured: the assertion is that an unrunnable CLI never+ // reaches the install path.+ t.Setenv(dshProfileBundleEnv, "@multica-ai/dsh-runtime")+ t.Setenv("DSH_TEST_RECORD", record)++ d := &Daemon{+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ agentVersions: map[string]string{},+ }+ _, reason, verdict := d.probeBuiltinRuntime(context.Background(), "dsh",+ AgentEntry{Path: path, Command: "dsh"})++ if verdict == builtinProbeMissingProfile {+ t.Fatalf("verdict = missing profile (reason %q); the CLI cannot run at all, "++ "and installing a bundle into it is not the repair", reason)+ }+ if demotableBuiltinProbeVerdict(verdict) {+ t.Fatalf("verdict %v (reason %q) can take a live runtime offline on one failed exec", verdict, reason)+ }+ // The reason has to name the real fault, or the user goes looking for a+ // profile problem that does not exist.+ if !strings.Contains(reason, "version detection failed") {+ t.Errorf("reason = %q, want it to name the failed version probe", reason)+ }+ time.Sleep(200 * time.Millisecond)+ if data, err := os.ReadFile(record); err == nil {+ t.Fatalf("the provisioning path ran against a CLI that cannot execute: %s", data)+ }+}++// A profile verdict has to reach the server as a structured cause, not as a+// bare "offline": without it the server classifies the runtime as merely+// offline, keeps queueing assignments behind a wait that only a human can end,+// and has no repair to show. The installing flag is the other half — it is what+// tells the server this particular wait does resolve itself.+func TestNewRuntimeVerdict_DshProfileCarriesAStructuredCause(t *testing.T) {for _, tc := range []struct {- name string- body string- want bool+ name string+ verdict builtinProbeVerdict+ installing bool}{- {name: "profile installed", body: `printf '%s\n' '{"v":1,"type":"probe","runtime":"dsh","protocol_version":1}'`, want: true},- {name: "profile missing", body: `printf '%s\n' 'missing multica profile'; exit 1`, want: false},+ {name: "missing, no install", verdict: builtinProbeMissingProfile},+ {name: "missing, install running", verdict: builtinProbeMissingProfile, installing: true},} {t.Run(tc.name, func(t *testing.T) {- fakeDir := t.TempDir()- path := filepath.Join(fakeDir, "dsh")- if err := os.WriteFile(path, []byte("#!/bin/sh\nset -eu\n"+tc.body+"\n"), 0o755); err != nil {- t.Fatal(err)+ got := newRuntimeVerdict(tc.verdict, "explained elsewhere", "/usr/local/bin/dsh", tc.installing)+ if got.offline == nil {+ t.Fatal("offline reason is nil: the server would treat this as a machine that is merely offline")+ }+ if got.offline.Code != RuntimeOfflineCodeDshProfile {+ t.Fatalf("code = %q, want %q", got.offline.Code, RuntimeOfflineCodeDshProfile)+ }+ if got.offline.Installing != tc.installing {+ t.Fatalf("installing = %v, want %v", got.offline.Installing, tc.installing)}- t.Setenv("PATH", fakeDir)- t.Setenv("MULTICA_DSH_PATH", "")- _, found := probeAgentCLIs()["dsh"]- if found != tc.want {- t.Fatalf("dsh discovered = %v, want %v", found, tc.want)+ // A repair that NAMES what is missing, and deliberately carries no+ // command: the install needs a bundle only the operator can+ // choose, and Repair.Command is rendered to the user inside a+ // shell fence as the line to run, so a placeholder there is a+ // paste-and-fail instruction.+ if got.offline.Repair == nil || got.offline.Repair.Package == "" {+ t.Fatalf("repair = %+v, want the missing package named", got.offline.Repair)+ }+ if strings.Contains(got.offline.Repair.Command, "<") {+ t.Fatalf("repair command %q hands the user a placeholder to run", got.offline.Repair.Command)}})}++ // An incompatible profile never becomes an offline reason at all: it is not+ // demotable, so nothing deregisters a runtime for it.+ if demotableBuiltinProbeVerdict(builtinProbeIncompatibleProfile) {+ t.Fatal("an incompatible profile can demote a live runtime; " ++ "the daemon may be the stale side of that protocol skew")+ }}diff --git a/server/internal/daemon/agents_refresh.go b/server/internal/daemon/agents_refresh.goindex 56fc0e02af..0f709e2f0f 100644--- a/server/internal/daemon/agents_refresh.go+++ b/server/internal/daemon/agents_refresh.go@@ -69,6 +69,9 @@ func (d *Daemon) agentDiscoveryLoop(ctx context.Context) {var (backoff time.DurationnextRetry time.Time+ // lastMismatch is the DSH profile/runtime disagreement the previous tick+ // saw, for the one direction that is throttled to a single forced round.+ lastMismatch dshProfileMismatch)for {select {@@ -77,27 +80,178 @@ func (d *Daemon) agentDiscoveryLoop(ctx context.Context) {case <-versionTicker.C:d.refreshAgentVersions(ctx)case now := <-ticker.C:- gained := d.refreshAgentAvailability()- missing := d.providersMissingRuntimes()- if len(missing) == 0 {- backoff = 0- continue- }- // A newly discovered provider always gets an immediate attempt;- // otherwise honor the backoff earned by previous failures.- if len(gained) == 0 && now.Before(nextRetry) {+ // Forced by disagreement between two live states, not by a change+ // since the last look: a profile removed between two observations,+ // or before the first one — which is what a restart produces —+ // would otherwise never be noticed. Observed in practice: a profile+ // removed a minute after startup stayed live for three minutes and+ // the server routed a chat task straight into it.+ mismatch := d.dshRuntimeProfileMismatch()+ force := mismatch.forcesEveryTick() || (mismatch != dshMismatchNone && mismatch != lastMismatch)+ lastMismatch = mismatch+ d.convergeAgentRuntimes(ctx, &backoff, &nextRetry, now, force)+ case <-d.agentDiscoveryKick:+ // A local state change (the DSH runtime profile appearing) makes a+ // provider registrable right now. Wait for nothing: the scheduled+ // attempt this replaces can be agentConvergeMaxBackoff away.+ d.convergeAgentRuntimes(ctx, &backoff, &nextRetry, time.Now(), true)+ }+ }+}++// convergeAgentRuntimes runs the expensive half of a discovery round: publish+// anything the cheap probe gained, then version-probe and register whatever is+// still missing a runtime.+//+// force ignores the backoff earned by previous failures, for a caller that+// knows the reason a provider could not register has just gone away — and, in+// the other direction, for one that knows a registered provider may just have+// gone bad. backoff and nextRetry are the loop's scheduling state, threaded+// through rather than owned here so the ticker and the kick share one backoff.+func (d *Daemon) convergeAgentRuntimes(+ ctx context.Context,+ backoff *time.Duration,+ nextRetry *time.Time,+ now time.Time,+ force bool,+) {+ gained := d.refreshAgentAvailability()+ missing := d.providersMissingRuntimes()+ // A forced round runs even with nothing missing: that is the shape of "a+ // registered provider just became unusable", which is exactly what the+ // verdict layer needs a round to notice.+ if len(missing) == 0 && !force {+ *backoff = 0+ return+ }+ // A newly discovered provider always gets an immediate attempt; otherwise+ // honor the backoff earned by previous failures unless the caller knows+ // the blocker is gone.+ if len(gained) == 0 && !force && now.Before(*nextRetry) {+ return+ }+ before := len(missing)+ d.convergeRuntimeRegistrations(ctx)+ after := len(d.providersMissingRuntimes())+ // backoff is earned by registration that keeps failing. A round that leaves+ // nothing missing has nothing to back off from — including a forced round+ // that only came here to condemn a registered provider, where before and+ // after are both zero.+ if after == 0 || after < before {+ *backoff = 0+ } else {+ *backoff = nextConvergeBackoff(*backoff)+ }+ *nextRetry = now.Add(*backoff)+}++// dshOnlyVerdicts narrows a round's demotable verdicts to dsh.+//+// Returns nil rather than an empty map when there is nothing, so the caller's+// length check reads the same either way.+func dshOnlyVerdicts(demotable map[string]runtimeVerdict) map[string]runtimeVerdict {+ verdict, ok := demotable["dsh"]+ if !ok {+ return nil+ }+ return map[string]runtimeVerdict{"dsh": verdict}+}++// dshProfileMismatch names a disagreement between the two states the daemon has+// to keep aligned: whether the Multica runtime profile is installed, and whether+// a dsh runtime is registered.+//+// The kind, rather than a bare bool, is what the caller needs, because the two+// directions have opposite termination behaviour — see forcesEveryTick.+type dshProfileMismatch string++const (+ // dshMismatchNone: the two states agree.+ dshMismatchNone dshProfileMismatch = ""+ // dshMismatchRuntimeWithoutProfile is a live runtime whose CLI can no+ // longer start. It is still "available" — discovered, and holding a+ // runtime — so nothing else in the loop looks at it, and the server keeps+ // routing work into a CLI that cannot start.+ dshMismatchRuntimeWithoutProfile dshProfileMismatch = "runtime-without-profile"+ // dshMismatchProfileWithoutRuntime is the mirror image, and is what a+ // manual `dsh plugin --profile multica add` produces.+ dshMismatchProfileWithoutRuntime dshProfileMismatch = "profile-without-runtime"+)++// forcesEveryTick reports whether this mismatch must force a converge round on+// every tick rather than only on the tick that first observed it.+//+// The asymmetry is about which direction a round is guaranteed to make progress+// on. Condemning a live runtime takes TWO probe rounds — the first only starts+// condemnedConfirmWindow — and nothing else schedules the second: with dsh still+// registered nothing is missing a runtime, so an unforced tick returns from+// convergeAgentRuntimes without probing at all. Forcing only the first sighting+// therefore leaves the runtime live and taking work forever, which is the exact+// failure the mismatch check exists to prevent.+//+// The other direction has no such guarantee and must NOT force every tick: a+// profile that is installed but answers nothing keeps that mismatch for as long+// as it is installed, and forcing on it would spend a full probe of every+// provider every agentDiscoveryInterval, permanently bypassing+// agentConvergeMaxBackoff.+func (m dshProfileMismatch) forcesEveryTick() bool {+ return m == dshMismatchRuntimeWithoutProfile+}++// dshRuntimeProfileMismatch names the current disagreement, or dshMismatchNone+// when the two states agree.+//+// Deliberately not a change detector: this is compared on every tick against+// live state, so a profile removed before the daemon's first look — or while it+// was not looking — is caught on the very next tick rather than never.+func (d *Daemon) dshRuntimeProfileMismatch() dshProfileMismatch {+ registered := d.dshRuntimeRegistered()+ if registered == dshMulticaProfilePresent() {+ return dshMismatchNone+ }+ if registered {+ return dshMismatchRuntimeWithoutProfile+ }+ // Only worth a round if there is a dsh CLI to register at all: without one+ // nothing this round does can resolve the mismatch.+ if _, discovered := d.agents()["dsh"]; discovered {+ return dshMismatchProfileWithoutRuntime+ }+ return dshMismatchNone+}++// dshRuntimeRegistered reports whether any tracked workspace still holds a+// built-in dsh runtime. Custom runtime profiles are excluded: they carry a+// ProfileID and are owned by the drift path, not by the built-in set.+func (d *Daemon) dshRuntimeRegistered() bool {+ d.mu.Lock()+ defer d.mu.Unlock()+ for _, ws := range d.workspaces {+ for _, id := range ws.runtimeIDs {+ rt, ok := d.runtimeIndex[id]+ if !ok || rt.ProfileID != "" {continue}- before := len(missing)- d.convergeRuntimeRegistrations(ctx)- if len(d.providersMissingRuntimes()) < before {- backoff = 0- } else {- backoff = nextConvergeBackoff(backoff)+ if rt.Provider == "dsh" {+ return true}- nextRetry = now.Add(backoff)}}+ return false+}++// kickAgentDiscovery asks the discovery loop for an immediate convergence+// round. Safe on a zero-value Daemon and from any goroutine: the send is+// non-blocking, so a burst of producers collapses into one round and none of+// them waits on the loop.+func (d *Daemon) kickAgentDiscovery() {+ if d.agentDiscoveryKick == nil {+ return+ }+ select {+ case d.agentDiscoveryKick <- struct{}{}:+ default:+ }}// nextConvergeBackoff doubles the retry delay, starting at one discovery@@ -394,6 +548,7 @@ func (d *Daemon) demoteUnusableRuntimes(ctx context.Context, causes map[string]rd.mu.Lock()var demoted []string+ var installWaits []dshInstallWait// Grouped per workspace because the cleanup below has to run under each// workspace's register lock — see deregisterDroppedRuntimes.demotedByWorkspace := make(map[string][]string)@@ -425,6 +580,14 @@ func (d *Daemon) demoteUnusableRuntimes(ctx context.Context, causes map[string]r// the verdict and the repair command (MUL-6164).if cause.offline != nil {offlineReasons[rid] = *cause.offline+ // A reason that says an install is running is a promise this+ // row comes back on its own. Remember it so the install can+ // take the promise back if it ends without a profile.+ if cause.offline.Installing {+ installWaits = append(installWaits, dshInstallWait{+ workspaceID: workspaceID, runtimeID: rid, reason: *cause.offline,+ })+ }}// The runtime is gone, so the record of what was registered for it// goes too. When the provider recovers, converge re-registers it and@@ -439,6 +602,7 @@ func (d *Daemon) demoteUnusableRuntimes(ctx context.Context, causes map[string]r// response would re-index the provider the moment it lands. The apply paths// consult this under the same lock, so the two are totally ordered.d.markProvidersDemotedLocked(causes)+ d.dshInstallWaits = append(d.dshInstallWaits, installWaits...)d.mu.Unlock()if len(demoted) == 0 {@@ -467,6 +631,79 @@ func (d *Daemon) demoteUnusableRuntimes(ctx context.Context, causes map[string]rd.notifyRuntimeSetChanged()}+// dshInstallWait is one runtime row whose offline reason claims an automatic+// profile install will bring it back.+type dshInstallWait struct {+ workspaceID string+ runtimeID string+ reason RuntimeOfflineReason+}++// withdrawDshInstallWait rewrites the offline reason of every runtime that was+// taken offline while an automatic profile install was still running, once that+// install has ended without producing a profile.+//+// Without it the claim is permanent. `installing` is what tells the server this+// particular offline runtime is worth queueing behind (MUL-6164), and the row+// carrying it is written exactly once, by the demotion — which also removes the+// runtime from the index, so no later round finds a runtime to condemn and no+// later deregistration is sent. An install that fails after that point leaves+// every assignment and @mention for the agent queueing behind a wait that has+// already given up, which is the failure the structured reason exists to+// prevent, not a new one to introduce.+//+// Best-effort, like every other deregistration path: the reason is a hint on a+// row that is already offline, and the row is corrected again the moment the+// provider registers.+func (d *Daemon) withdrawDshInstallWait(ctx context.Context) {+ d.mu.Lock()+ waits := d.dshInstallWaits+ d.dshInstallWaits = nil+ d.mu.Unlock()+ if len(waits) == 0 {+ return+ }++ byWorkspace := make(map[string][]dshInstallWait, len(waits))+ for _, wait := range waits {+ byWorkspace[wait.workspaceID] = append(byWorkspace[wait.workspaceID], wait)+ }+ workspaceIDs := make([]string, 0, len(byWorkspace))+ for workspaceID := range byWorkspace {+ workspaceIDs = append(workspaceIDs, workspaceID)+ }+ sort.Strings(workspaceIDs)++ for _, workspaceID := range workspaceIDs {+ _ = d.withWorkspaceRegisterLock(workspaceID, func() error {+ runtimeIDs := make([]string, 0, len(byWorkspace[workspaceID]))+ reasons := make(map[string]RuntimeOfflineReason, len(byWorkspace[workspaceID]))+ for _, wait := range byWorkspace[workspaceID] {+ reason := wait.reason+ reason.Installing = false+ reason.Detail = dshInstallGaveUpReason+ runtimeIDs = append(runtimeIDs, wait.runtimeID)+ reasons[wait.runtimeID] = reason+ }+ // Same tracking re-check every deregistration path makes: a+ // register that brought the runtime back between the demotion and+ // now is newer than this correction, and its row already says+ // online.+ runtimeIDs = d.untrackedRuntimeIDs(runtimeIDs)+ if len(runtimeIDs) == 0 {+ return nil+ }+ d.logger.Warn("automatic DSH profile install gave up; withdrawing the wait from its runtimes",+ "workspace_id", workspaceID, "runtime_ids", runtimeIDs)+ if err := d.client.Deregister(ctx, runtimeIDs, reasons); err != nil {+ d.logger.Warn("withdrawing the DSH install wait failed",+ "workspace_id", workspaceID, "runtime_ids", runtimeIDs, "error", err)+ }+ return nil+ })+ }+}+// deregisterRevivedRuntimes takes offline the rows a register response brought// back for a provider that was demoted while that register was in flight.//@@ -596,7 +833,24 @@ func (d *Daemon) convergeRuntimeRegistrations(ctx context.Context) {// detectBuiltinRuntimes version-gates the availability set and publishes// this round's drops for /health, so a provider that cannot register still// gets a visible reason even though registration is skipped.- builtins, _, _ := d.detectBuiltinRuntimes(ctx)+ builtins, demotable, _ := d.detectBuiltinRuntimes(ctx)+ // Condemned providers drop out of builtins entirely, so acting on them+ // before the early return is what keeps a dsh that goes bad mid-flight from+ // staying online: the profile removed while dsh is registered leaves nothing+ // missing a runtime, and a round reached only for that has no registration+ // left to do. demoteUnusableRuntimes owns the claim barrier and the+ // seq-stamped hold, so running it here is safe.+ //+ // Restricted to dsh on purpose. Every other provider is demoted from+ // refreshAgentVersions alone, on its own ten-minute cadence, and that is the+ // schedule their verdicts were tuned against; letting a converge round+ // condemn them too would move Claude Code, Codex and the rest onto a+ // different one as a side effect of a DSH fix. dsh is the only provider with+ // a precondition that can change without any version changing, which is why+ // it is the only one that needs a round it can be forced into.+ if dshDemotable := dshOnlyVerdicts(demotable); len(dshDemotable) > 0 {+ d.demoteUnusableRuntimes(ctx, dshDemotable)+ }if len(builtins) == 0 {return}diff --git a/server/internal/daemon/agents_refresh_test.go b/server/internal/daemon/agents_refresh_test.goindex 310534d441..4871d5d3b0 100644--- a/server/internal/daemon/agents_refresh_test.go+++ b/server/internal/daemon/agents_refresh_test.go@@ -4,8 +4,12 @@ import ("context""encoding/json""errors"+ "io"+ "log/slog""net/http""net/http/httptest"+ "os"+ "path/filepath""sort""sync""testing"@@ -14,6 +18,192 @@ import ("github.com/multica-ai/multica/server/pkg/agent")+// The loop backs off whenever a round cannot shrink the missing-runtime set,+// and dsh sits in that set for as long as its runtime profile is absent. force+// is what lets the automatic DSH install bypass that wait once it finishes:+// without it the next scheduled attempt can be agentConvergeMaxBackoff (30m)+// away, which is what made a finished install look like it had done nothing+// until a manual daemon restart.+func TestConvergeAgentRuntimes_ForceIgnoresThePendingBackoff(t *testing.T) {+ t.Setenv(dshProfileBundleEnv, "")+ stubAgentProbe(t, map[string]AgentEntry{"dsh": {Path: "/nonexistent/dsh"}})++ newDaemon := func() *Daemon {+ d := &Daemon{+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ workspaces: map[string]*workspaceState{"ws-1": {}},+ runtimeIndex: map[string]Runtime{},+ agentVersions: map[string]string{},+ }+ d.cfg.Agents = map[string]AgentEntry{"dsh": {Path: "/nonexistent/dsh"}}+ return d+ }+ now := time.Now()+ pending := now.Add(30 * time.Minute)++ // A pending backoff holds the scheduled round back...+ d := newDaemon()+ backoff, nextRetry := time.Duration(0), pending+ d.convergeAgentRuntimes(context.Background(), &backoff, &nextRetry, now, false)+ if !nextRetry.Equal(pending) {+ t.Fatalf("nextRetry = %v, want the pending backoff %v to be honored", nextRetry, pending)+ }++ // ...and a forced round runs anyway.+ d = newDaemon()+ backoff, nextRetry = time.Duration(0), pending+ d.convergeAgentRuntimes(context.Background(), &backoff, &nextRetry, now, true)+ if nextRetry.Equal(pending) {+ t.Fatal("force did not bypass the pending backoff, so a finished DSH install would wait for it")+ }+}++// The other direction force exists for: a registered provider whose runtime+// profile was removed leaves nothing missing a runtime, so its round runs only+// because it was forced — and it must not earn a backoff, because no+// registration failed. Earning one would push the very demotion that round just+// performed out to agentConvergeMaxBackoff.+func TestConvergeAgentRuntimes_ForcedRoundWithNothingMissingKeepsTheBackoffClear(t *testing.T) {+ t.Setenv(dshProfileBundleEnv, "")+ stubAgentProbe(t, map[string]AgentEntry{"dsh": {Path: "/nonexistent/dsh"}})++ d := &Daemon{+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ workspaces: map[string]*workspaceState{},+ runtimeIndex: map[string]Runtime{},+ agentVersions: map[string]string{},+ }+ d.cfg.Agents = map[string]AgentEntry{"dsh": {Path: "/nonexistent/dsh"}}++ now := time.Now()+ backoff, nextRetry := time.Duration(0), now.Add(30*time.Minute)+ d.convergeAgentRuntimes(context.Background(), &backoff, &nextRetry, now, true)++ if backoff != 0 {+ t.Fatalf("backoff = %v after a round that left nothing missing, want 0", backoff)+ }+ if nextRetry.After(now.Add(agentDiscoveryInterval)) {+ t.Fatalf("nextRetry = %v, want the next discovery tick", nextRetry)+ }+}++// The failure observed in the field: the profile is removed while dsh is+// registered, and nothing takes the runtime offline — dsh is discovered and+// holds a runtime, so no other part of the loop looks at it, and the server+// routes the next chat task into a CLI that cannot start.+//+// The mismatch must be judged from live state rather than from a change since+// the last look: the daemon that hit this had started a minute before the+// removal, so its first observation was already "no profile".+func TestDshRuntimeProfileMismatch(t *testing.T) {+ home := t.TempDir()+ t.Setenv("DSH_HOME", home)++ registered := func() *Daemon {+ d := &Daemon{+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ workspaces: map[string]*workspaceState{"ws-1": {runtimeIDs: []string{"rt-dsh"}}},+ runtimeIndex: map[string]Runtime{"rt-dsh": {ID: "rt-dsh", Provider: "dsh"}},+ }+ // A daemon that has discovered dsh, which is the only situation in+ // which registering one is possible at all.+ d.cfg.Agents = map[string]AgentEntry{"dsh": {Path: "/somewhere/dsh"}}+ return d+ }++ // A registered dsh runtime with no profile on disk: the state that has to+ // bring a round.+ d := registered()+ if d.dshRuntimeProfileMismatch() == dshMismatchNone {+ t.Fatal("a registered dsh with no profile was judged consistent; the runtime keeps taking work")+ }++ // Installing the profile makes the two agree.+ dir := filepath.Join(home, "profiles", dshMulticaProfileName)+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(dir, "package.json"), []byte("{}\n"), 0o644); err != nil {+ t.Fatal(err)+ }+ if d.dshRuntimeProfileMismatch() != dshMismatchNone {+ t.Fatal("a registered dsh with its profile installed was judged inconsistent")+ }++ // The mirror image: a profile with nothing registered, which is what a+ // manual install produces.+ d = registered()+ d.runtimeIndex = map[string]Runtime{}+ if d.dshRuntimeProfileMismatch() == dshMismatchNone {+ t.Fatal("an installed profile with no dsh runtime was judged consistent; it would never register")+ }++ // A custom runtime profile carrying the dsh provider is not the built-in+ // one. With no dsh CLI discovered there is nothing a round could register,+ // so the mismatch must not buy a full probe of every provider on every tick.+ d = registered()+ d.runtimeIndex = map[string]Runtime{"rt-dsh": {ID: "rt-dsh", Provider: "dsh", ProfileID: "prof-1"}}+ d.cfg.Agents = map[string]AgentEntry{}+ if d.dshRuntimeProfileMismatch() != dshMismatchNone {+ t.Fatal("a mismatch no round could resolve was reported as inconsistent")+ }++ // With a dsh CLI present it is actionable again: the profile is installed+ // and the built-in runtime is genuinely missing.+ d.cfg.Agents = map[string]AgentEntry{"dsh": {Path: "/somewhere/dsh"}}+ if d.dshRuntimeProfileMismatch() == dshMismatchNone {+ t.Fatal("an installed profile plus a discovered dsh should earn a registration round")+ }+}++// A registered dsh whose profile was removed has to keep forcing rounds until+// it is condemned, because condemning it takes two of them: the first sighting+// only starts condemnedConfirmWindow, and with dsh still registered nothing is+// missing a runtime — so an unforced tick returns from convergeAgentRuntimes+// without probing anything, and the second sighting never happens.+//+// Throttling this direction to one forced round (as the profile-without-runtime+// direction is throttled, where no round is guaranteed to make progress) leaves+// the runtime live and claiming work indefinitely. That is the bug this test+// exists to catch, so it asserts the FORCE SEQUENCE, not just the mismatch kind.+func TestDshRuntimeProfileMismatch_ForcingConvergesEachDirection(t *testing.T) {+ // Replays the tick body of agentDiscoveryLoop.+ forceSequence := func(mismatch dshProfileMismatch, ticks int) []bool {+ var last dshProfileMismatch+ out := make([]bool, 0, ticks)+ for i := 0; i < ticks; i++ {+ force := mismatch.forcesEveryTick() || (mismatch != dshMismatchNone && mismatch != last)+ last = mismatch+ out = append(out, force)+ }+ return out+ }++ for _, force := range forceSequence(dshMismatchRuntimeWithoutProfile, 4) {+ if !force {+ t.Fatal("a registered dsh with no profile stopped forcing rounds; " ++ "the confirmation window needs a second probe round that nothing else schedules")+ }+ }++ // The other direction stays throttled: it is the one a round cannot be+ // relied on to resolve, so forcing every tick would bypass+ // agentConvergeMaxBackoff forever.+ got := forceSequence(dshMismatchProfileWithoutRuntime, 4)+ if !got[0] {+ t.Fatal("an installed profile with no runtime never earned its first round")+ }+ for _, force := range got[1:] {+ if force {+ t.Fatalf("profile-without-runtime forced more than once: %v", got)+ }+ }++ if forceSequence(dshMismatchNone, 3)[0] {+ t.Fatal("agreeing states forced a round")+ }+}+// stubAgentProbe replaces CLI discovery for the duration of a test. The returned// setter swaps in the next probe result, simulating the user installing or// uninstalling a CLI while the daemon runs.diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex 24525602dd..c57e806ccf 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -929,6 +929,19 @@ func (c *Client) GetTaskGCCheck(ctx context.Context, taskID string) (*TaskGCStat// must be refused with an explanation (MUL-6164).const RuntimeOfflineCodeNotExecutable = "not_executable"+// RuntimeOfflineCodeDshProfile marks a runtime taken offline because the DSH+// runtime profile it depends on is not installed. Like not_executable it is not+// something waiting fixes on its own — a human installs a bundle, or configures+// the daemon to — so work for it is refused with an explanation rather than+// queued forever. The exception is an install the daemon is running right now,+// which Installing states explicitly.+//+// Only an ABSENT profile reaches this code. A profile that is present but+// answers with a protocol this daemon does not drive never takes a live runtime+// offline at all: the daemon can be the stale side of that skew, so it reports+// the incompatibility and leaves the runtime alone.+const RuntimeOfflineCodeDshProfile = "dsh_profile"+// RuntimeOfflineReason is why a runtime went offline, in the form clients can// act on: a stable code they switch on and localize, and the command that// repairs the install. Prose stays in Detail for logs — never as the thing a@@ -937,6 +950,12 @@ type RuntimeOfflineReason struct {Code string `json:"code"`Detail string `json:"detail,omitempty"`Repair *agent.ExecFormatRepair `json:"repair,omitempty"`+ // Installing reports that the daemon has an automatic install in flight for+ // this runtime. It is the difference between "a human has to act" and "this+ // comes back by itself", which the server cannot infer from the code alone:+ // without it, a successful install that is still running would look exactly+ // like a machine waiting on an operator who was never going to be told.+ Installing bool `json:"installing,omitempty"`}// Deregister takes runtimes offline. reasons is optional and keyed by runtimediff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex 3d925afbfe..6fa2dba705 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -8,6 +8,8 @@ import ("os""os/exec""path/filepath"+ "runtime"+ "sort""strings""time"@@ -994,6 +996,260 @@ var codexDesktopAppBundlePaths = func() []string {return paths}+// dshDesktopAppBundlePaths returns candidate locations for the DSH CLI that+// DeepSeek Harness Desktop manages. The app never installs `dsh` onto PATH, so+// a GUI-launched daemon misses it on exec.LookPath and the login-shell fallback+// cannot rescue it either — a user's rc files have no reason to know that path.+//+// Only DEFAULT locations are covered, and nothing here reads an install receipt+// or the registry, so an install put somewhere else still needs+// MULTICA_DSH_PATH. This is a convenience for the common case, never a contract+// — which is why a miss falls through to "dsh not found" rather than to a guess.+var dshDesktopAppBundlePaths = func() []string {+ home, err := os.UserHomeDir()+ if err != nil {+ home = ""+ }+ return dshDesktopBundlePathsFor(runtime.GOOS, os.Getenv, home)+}++// dshDesktopBundlePathsFor builds the candidate list for one platform.+//+// Taking goos/env/home as arguments, rather than reading runtime.GOOS and+// os.Getenv inline, is what makes the Windows layout assertable from any host.+// The alternative leaves the Windows branch testable only on Windows, which in+// this package has meant untested.+//+// Generated shims come first on BOTH platforms, and that order is the point: a+// shim runs the Desktop app's own Electron binary as node, by absolute path, so+// it needs nothing on PATH. The macOS app-bundle script below is the same CLI+// entered through `#!/usr/bin/env node`, so it only works on a machine that+// happens to have node installed — a last resort, not a first choice.+func dshDesktopBundlePathsFor(goos string, env func(string) string, home string) []string {+ paths := dshDesktopShimCandidates(dshDesktopAppDataDir(goos, env, home), dshDesktopShimNames(goos))+ if goos == "darwin" {+ // The CLI entry point inside the app bundle, tried last. System-wide+ // /Applications before the per-user ~/Applications, matching+ // codexDesktopAppBundlePaths.+ const bundle = "DSH Desktop.app/Contents/Resources/app.asar.unpacked/node_modules/@deepseek-ai/dsh/lib/bin.js"+ paths = append(paths, filepath.Join("/Applications", bundle))+ if home != "" {+ paths = append(paths, filepath.Join(home, "Applications", bundle))+ }+ }+ return paths+}++// dshDesktopAppDataDir returns the per-user directory DSH Desktop keeps its+// state in, which is also where it generates the CLI shims.+//+// Roaming application data on Windows, NOT the install directory: the app+// installs to Program Files or %LOCALAPPDATA%\Programs, but the CLI it drives+// lives beside its other per-user state. That also makes one lookup cover both+// install modes, since a per-machine install still generates these shims into+// each user's own roaming directory.+//+// %APPDATA% is preferred over composing from home because it is redirected on+// managed and roaming-profile machines; the home-relative form is the last+// resort for a daemon started with a stripped environment.+func dshDesktopAppDataDir(goos string, env func(string) string, home string) string {+ const app = "DSH Desktop"+ switch goos {+ case "darwin":+ if home == "" {+ return ""+ }+ return filepath.Join(home, "Library", "Application Support", app)+ case "windows":+ if appData := strings.TrimSpace(env("APPDATA")); appData != "" {+ return filepath.Join(appData, app)+ }+ if home != "" {+ return filepath.Join(home, "AppData", "Roaming", app)+ }+ }+ return ""+}++// dshDesktopShimNames are the launchable file names a generated shim directory+// can hold, most likely first.+//+// The macOS app-bundle entry point — lib/bin.js — deliberately has no Windows+// counterpart. It is a Node script macOS starts through its shebang; Windows+// has no shebang, exec.LookPath rejects a .js unless PATHEXT says otherwise,+// and CreateProcess cannot start one either. Listing it there would register a+// runtime that fails on every spawn, which is the failure executableCandidate+// exists to prevent.+func dshDesktopShimNames(goos string) []string {+ if goos == "windows" {+ return []string{"dsh.exe", "dsh.cmd", "dsh.bat"}+ }+ return []string{"dsh"}+}++// dshDesktopShimTiers are the directories under the app-data root whose+// subdirectories are generated CLI payloads, in preference order.+//+// host-commands wins because that is the layout whose shim was confirmed to+// run: it sets DSH_HOME and invokes the Desktop executable by absolute path.+// The cli payload is the other shape, kept as a fallback for a Desktop version+// that does not generate host-commands — on at least one Windows install its+// shim exits 9009 (cmd.exe's "command not found") because what it forwards to+// is not there. Ranking it second is what stops a broken-but-present shim being+// chosen over a working one; nothing here executes a candidate, so order is the+// only lever available.+//+// profiled marks the tier that keys its payloads by DSH profile+// (host-commands/<profile>/generations). The profile set is the user's, so that+// level is enumerated rather than assumed.+var dshDesktopShimTiers = []struct {+ dir string+ profiled bool+}{+ {dir: "host-commands", profiled: true},+ {dir: "cli"},+}++// dshBinDir is one generated command directory plus the keys that order it.+type dshBinDir struct {+ path string+ name string+ modTime time.Time+}++// dshDesktopBinDirsIn collects the bin directories under root, unsorted.+//+// DSH Desktop lays its generated command directories out in two shapes, and a+// host can be on either depending on which version generated them:+//+// <root>/bin — flat+// <root>/<id>/bin — one payload directory per generation+//+// The payload id is a content hash, sometimes with a generation uuid appended,+// so it is enumerated rather than composed. Only directories holding a bin are+// accepted, so a stray file or a half-extracted download is skipped rather than+// turned into a candidate.+//+// The flat directory carries a zero timestamp, which sorts it last: a host that+// has both shapes is one where the generational layout is the newer of the two.+func dshDesktopBinDirsIn(root string) []dshBinDir {+ if root == "" {+ return nil+ }+ var dirs []dshBinDir+ if entries, err := os.ReadDir(root); err == nil {+ for _, entry := range entries {+ if !entry.IsDir() || entry.Name() == "bin" {+ continue+ }+ binDir := filepath.Join(root, entry.Name(), "bin")+ if !isExistingDir(binDir) {+ continue+ }+ info, err := entry.Info()+ if err != nil {+ continue+ }+ dirs = append(dirs, dshBinDir{path: binDir, name: entry.Name(), modTime: info.ModTime()})+ }+ }+ if flat := filepath.Join(root, "bin"); isExistingDir(flat) {+ dirs = append(dirs, dshBinDir{path: flat, name: ""})+ }+ return dirs+}++// sortDshBinDirs orders generated directories newest first.+//+// This is what protects a host mid-upgrade: a new payload is written and the+// previous one can be left in place, and the newest is the one the app is+// actually driving. The name breaks ties, because two payloads written in the+// same filesystem timestamp tick must still produce one stable answer rather+// than whatever ReadDir returned — and because the answer feeds PATH and+// process launches, an order that changes between rounds is a daemon that picks+// a different CLI each time.+func sortDshBinDirs(dirs []dshBinDir) {+ sort.SliceStable(dirs, func(i, j int) bool {+ if !dirs[i].modTime.Equal(dirs[j].modTime) {+ return dirs[i].modTime.After(dirs[j].modTime)+ }+ return dirs[i].name > dirs[j].name+ })+}++// dshDesktopBinDirs returns the bin directories under root, newest first.+func dshDesktopBinDirs(root string) []string {+ dirs := dshDesktopBinDirsIn(root)+ sortDshBinDirs(dirs)+ paths := make([]string, 0, len(dirs))+ for _, dir := range dirs {+ paths = append(paths, dir.path)+ }+ return paths+}++// isExistingDir reports whether path is a directory that exists.+func isExistingDir(path string) bool {+ info, err := os.Stat(path)+ return err == nil && info.IsDir()+}++// dshDesktopShimCandidates expands the generated CLI payloads under appData+// into launchable candidate paths.+//+// Tier order is applied first and payload age second, so a working shim in the+// preferred tier always outranks a newer one in the fallback tier. Within a+// tier every root is pooled before sorting, so the newest generation wins even+// when it belongs to a different DSH profile than the one ReadDir happened to+// return first.+func dshDesktopShimCandidates(appData string, names []string) []string {+ if appData == "" || len(names) == 0 {+ return nil+ }+ var paths []string+ for _, spec := range dshDesktopShimTiers {+ var tierDirs []dshBinDir+ for _, root := range dshDesktopPayloadRoots(filepath.Join(appData, spec.dir), spec.profiled) {+ tierDirs = append(tierDirs, dshDesktopBinDirsIn(root)...)+ }+ sortDshBinDirs(tierDirs)+ for _, dir := range tierDirs {+ for _, name := range names {+ paths = append(paths, filepath.Join(dir.path, name))+ }+ }+ }+ return paths+}++// dshDesktopPayloadRoots resolves one tier to the directories whose contents+// dshDesktopBinDirsIn enumerates.+//+// A profiled tier keys its payloads by DSH profile and puts them under a+// `generations` directory (host-commands/<profile>/generations). The profile+// names belong to the user, so that level is enumerated; an unprofiled tier+// holds its payloads directly.+func dshDesktopPayloadRoots(dir string, profiled bool) []string {+ if !profiled {+ return []string{dir}+ }+ entries, err := os.ReadDir(dir)+ if err != nil {+ return nil+ }+ var roots []string+ for _, entry := range entries {+ if !entry.IsDir() {+ continue+ }+ generations := filepath.Join(dir, entry.Name(), "generations")+ if isExistingDir(generations) {+ roots = append(roots, generations)+ }+ }+ return roots+}+// loginShellResolveTimeout caps how long the daemon will wait for the user's// login shell to print canonical agent paths. A broken rc file should not// block startup — if the shell takes longer than this, we proceed withoutdiff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex c0cc418fdb..92c8c2bacd 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -53,6 +53,15 @@ var ErrRepoNotConfigured = errors.New("repo is not configured for this workspace// stale-heartbeat sweep.var ErrNoRuntimesToRegister = errors.New("no agent runtimes could be registered")+// errNoWorkspaceRuntimesRegistered is returned by syncWorkspacesFromAPI when a+// round left every workspace without a runtime. At startup that is normally+// fatal — a daemon hosting nothing has nothing to do, and failing loudly beats+// idling — which is why it is a sentinel rather than a bare string: exactly one+// caller is allowed to make an exception to it, and only for the one situation+// where the daemon knows the answer is on its way. See+// startupMayProceedWithoutRuntimes.+var errNoWorkspaceRuntimesRegistered = errors.New("failed to register runtimes")+// errTaskPrepareTimeout distinguishes the daemon's dispatched -> running// startup deadline from provider execution timeouts. handleTask maps it to the// platform-side timeout failure reason so the server's existing retry path can@@ -391,6 +400,42 @@ type Daemon struct {reloading sync.Mutex // prevents concurrent workspace syncsruntimeSet *runtimeSetWatcher // multi-subscriber pub/sub for runtime-set changes+ // lifecycleCtx is the context Run was handed, kept so background work that+ // must outlive a single probe round — the DSH profile install — is tied to+ // the daemon's lifetime instead of to whichever round happened to notice the+ // missing profile. Guarded by d.mu: it is written once in Run and read from+ // the install goroutine, and "the write happens before every reader starts"+ // is a property of statement order in Run that a later edit can quietly+ // break. Read it through daemonLifecycleCtx.+ lifecycleCtx context.Context++ // dshInstallInFlight is true while an automatic DSH profile install is+ // running. Read when a verdict becomes an offline reason, so the server can+ // tell "wait, this resolves itself" from "a human has to act".+ dshInstallInFlight atomic.Bool++ // dshInstallWaits are the runtime rows taken offline while an automatic+ // profile install was still running, so their stated cause claims the wait+ // resolves itself. An install that ends without a profile has to withdraw+ // that claim (withdrawDshInstallWait): the demotion already removed these+ // runtimes from the index, so no later round condemns them again and no+ // later deregistration would correct the row on its own. Guarded by d.mu.+ dshInstallWaits []dshInstallWait++ // dshProvisionOnce makes the automatic DSH runtime-profile install+ // once-per-daemon: it is a network install that writes into the user's DSH+ // home, so a failing registry must not be retried every discovery round.+ // See startDshProfileProvision.+ dshProvisionOnce sync.Once++ // agentDiscoveryKick asks agentDiscoveryLoop for an immediate convergence+ // round. Buffered and written non-blockingly (kickAgentDiscovery), so a+ // producer never waits on the loop and a burst collapses into one round.+ // Needed because the loop's scheduled retry can be+ // agentConvergeMaxBackoff away, which is far too long to wait after a+ // local state change that makes a provider registrable again.+ agentDiscoveryKick chan struct{}+versionsMu sync.RWMutex // guards agentVersionsagentVersions map[string]string // provider -> detected CLI version (set during registration)@@ -442,11 +487,11 @@ type Daemon struct {// "apply a response" instead of merely narrowing the window between them.demotedProviders map[string]demotionRecord // provider -> the evidence that condemned it and when- // notExecutableSince is when each provider was FIRST observed to be- // unrunnable, for the confirmation window in confirmNotExecutable. Entries- // are cleared by the round that finds the provider healthy again. Guarded- // by d.mu.- notExecutableSince map[string]time.Time+ // condemnedSince is when each provider was FIRST observed to be in a+ // condemnable state, keyed "<verdict>:<provider>" by condemnedKey, for the+ // confirmation window in confirmCondemned. Entries are cleared by the round+ // that finds the provider healthy again. Guarded by d.mu.+ condemnedSince map[string]time.Time// demotionSeq is a monotonic counter stamped onto each demotion record so a// probe round can tell whether its evidence predates a verdict.@@ -650,6 +695,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {runtimeIndex: make(map[string]Runtime),profileLaunchSpecs: make(map[string]profileLaunchSpec),runtimeSet: newRuntimeSetWatcher(),+ agentDiscoveryKick: make(chan struct{}, 1),agentVersions: make(map[string]string),skippedAgents: make(map[string]string),resolvedPaths: make(map[string]healedAgent),@@ -1678,6 +1724,25 @@ type demotionRecord struct {seq uint64}+// setLifecycleCtx records the context Run was handed.+func (d *Daemon) setLifecycleCtx(ctx context.Context) {+ d.mu.Lock()+ defer d.mu.Unlock()+ d.lifecycleCtx = ctx+}++// daemonLifecycleCtx returns the context that bounds background work outliving+// a single round. Falls back to Background so a zero-value Daemon (tests, and+// any path reached before Run) still works.+func (d *Daemon) daemonLifecycleCtx() context.Context {+ d.mu.Lock()+ defer d.mu.Unlock()+ if d.lifecycleCtx == nil {+ return context.Background()+ }+ return d.lifecycleCtx+}+// markProvidersDemoted records a CONFIRMED verdict so a register response still// in flight cannot revive the provider. Callers must hold d.mu.func (d *Daemon) markProvidersDemotedLocked(providers map[string]runtimeVerdict) {@@ -1699,44 +1764,63 @@ func (d *Daemon) markProvidersDemotedLocked(providers map[string]runtimeVerdict)}}-// notExecutableConfirmWindow is how long a "the OS will not run this file"-// verdict must keep reproducing before the daemon acts on it.+// condemnedConfirmWindow is how long a condemnable verdict must keep reproducing+// before the daemon acts on it.+//+// The verdict itself is deterministic, but the observation behind it is not. The+// repair we tell users to run for a not-executable file overwrites the bin entry+// in place, and a probe that lands mid-copy sees a truncated file; the DSH+// profile probe boots a whole process, and a DSH upgrade replaces the CLI+// underneath it. Requiring a second sighting this far apart makes those windows+// impossible to mistake for a real verdict, and costs a genuinely broken+// provider only one extra probe round.//-// The verdict itself is deterministic, but the file is not: the repair we tell-// users to run (`node <pkg>/install.cjs`) overwrites the bin entry in place, and-// a probe that lands mid-copy sees a truncated file. Requiring a second sighting-// this far apart makes an overwrite window impossible to mistake for a broken-// install, and costs a genuinely broken install only one extra probe round.+// This gates every condemnable verdict, not just the exec-format one: the+// profile verdicts rest on a single observation too, and demotion is what routes+// live work away from a machine.// A var so tests can collapse the wait.-var notExecutableConfirmWindow = time.Minute+var condemnedConfirmWindow = time.Minute-// confirmNotExecutable records that this round found provider unrunnable and-// reports whether the verdict is now old enough to act on.+// condemnedKey namespaces a confirmation clock per verdict, so a provider that+// moves between condemnable states starts a fresh window instead of inheriting+// the time earned by a different problem.+func condemnedKey(verdict builtinProbeVerdict, provider string) string {+ return strconv.Itoa(int(verdict)) + ":" + provider+}++// confirmCondemned records that this round found provider in the given+// condemnable state and reports whether the verdict is now old enough to act on.//// The first sighting only starts the clock. Two sightings are required no matter// how the window is configured, so concurrent probe rounds — four callers reach// detectBuiltinRuntimes — cannot combine into an instant demotion.-func (d *Daemon) confirmNotExecutable(provider string, now time.Time) bool {+func (d *Daemon) confirmCondemned(verdict builtinProbeVerdict, provider string, now time.Time) bool {+ key := condemnedKey(verdict, provider)d.mu.Lock()defer d.mu.Unlock()- first, seen := d.notExecutableSince[provider]+ first, seen := d.condemnedSince[key]if !seen {- if d.notExecutableSince == nil {- d.notExecutableSince = make(map[string]time.Time, 1)+ if d.condemnedSince == nil {+ d.condemnedSince = make(map[string]time.Time, 1)}- d.notExecutableSince[provider] = now+ d.condemnedSince[key] = nowreturn false}- return now.Sub(first) >= notExecutableConfirmWindow+ return now.Sub(first) >= condemnedConfirmWindow}-// clearNotExecutable forgets the pending verdict for a provider that probed OK,-// so a later unrelated failure starts its own confirmation window instead of+// clearCondemned forgets every pending verdict for a provider that probed OK, so+// a later unrelated failure starts its own confirmation window instead of// inheriting a stale one.-func (d *Daemon) clearNotExecutable(provider string) {+func (d *Daemon) clearCondemned(provider string) {+ suffix := ":" + providerd.mu.Lock()defer d.mu.Unlock()- delete(d.notExecutableSince, provider)+ for key := range d.condemnedSince {+ if strings.HasSuffix(key, suffix) {+ delete(d.condemnedSince, key)+ }+ }}// demotionSeqSnapshot returns the current demotion counter. A probe round takes@@ -1959,6 +2043,7 @@ func (d *Daemon) Run(ctx context.Context) error {// Wrap context so handleUpdate can cancel the daemon for restart.ctx, cancel := context.WithCancel(ctx)d.cancelFunc = cancel+ d.setLifecycleCtx(ctx)d.rootCtx = ctx// Bind health port early to detect another running daemon.@@ -2248,8 +2333,92 @@ const (// sense as below-minimum: the same bytes will be refused every time until// someone reinstalls, so retrying is not what fixes it.builtinProbeNotExecutable+ // builtinProbeMissingProfile: the CLI resolved and runs, but the runtime+ // profile its backend speaks through is not installed for it. DSH is the+ // case in the field: the Multica profile is what gives `dsh` its --stdio+ // protocol, so a bare binary answers `--version` and `--probe` refuses.+ // Deterministic like the two above — the same binary keeps refusing until+ // someone installs the profile — and the reason carries that repair.+ builtinProbeMissingProfile+ // builtinProbeIncompatibleProfile: something answered `--probe`, with a+ // protocol version this daemon does not drive — a bundle older than the+ // check, or a newer one this build has yet to catch up with. Reported, and+ // deliberately neither installable NOR demotable: the profile is there on+ // purpose, so installing over it would replace a considered configuration,+ // and this daemon can equally be the stale side of the skew, so taking a+ // live runtime offline over it is a destructive answer to a version+ // question. It stops a fresh registration and nothing more.+ builtinProbeIncompatibleProfile)+// demotableBuiltinProbeVerdict reports whether a verdict may take a LIVE+// runtime offline, as opposed to merely keeping an unregistered provider+// unregistered.+//+// The distinction is the whole safety property: demotion routes work away from+// a machine, so it belongs only to verdicts that say the CLI definitely cannot+// serve work AND that this daemon is in a position to judge.+//+// builtinProbeIncompatibleProfile fails the second half and is deliberately+// absent. A protocol version this daemon does not drive can equally mean the+// daemon is the stale side of the skew, and tearing down a live runtime because+// THIS build is behind is a destructive answer to a version question. It still+// blocks a fresh registration and is reported on /health; what it must not do is+// take work away from a runtime already serving it.+//+// builtinProbeUnavailable is absent for the plainer reason: it means nothing was+// learned this round.+func demotableBuiltinProbeVerdict(verdict builtinProbeVerdict) bool {+ switch verdict {+ case builtinProbeBelowMinimum, builtinProbeNotExecutable, builtinProbeMissingProfile:+ return true+ }+ return false+}++// builtinProbeNeedsConfirmation reports whether a demotable verdict must+// reproduce across two probe rounds (confirmCondemned) before it is acted on.+//+// Only builtinProbeBelowMinimum does not: it is a pure function of a version+// string this round already parsed, so a second look reaches the same+// conclusion. The other two are deterministic about the state they describe but+// rest on an observation that is not — an installer overwriting the bin entry in+// place (the very repair we tell users to run) or a DSH upgrade moving the+// profile under a probe. Requiring a second sighting a window later makes those+// windows impossible to mistake for a verdict, and costs a genuinely broken+// provider one extra round.+func builtinProbeNeedsConfirmation(verdict builtinProbeVerdict) bool {+ return verdict != builtinProbeBelowMinimum+}++// dshMissingProfileReason is the user-facing explanation for a+// builtinProbeMissingProfile drop. It names the repair because nothing else in+// the daemon's output would: the CLI itself is installed, resolvable and+// answers `--version`, so "not installed" is true only of the profile.+const dshMissingProfileReason = "the Multica runtime profile is not installed; add the Multica DSH runtime bundle to the `multica` profile with `dsh plugin`, or set MULTICA_DSH_PROFILE_BUNDLE so the daemon installs it"++// dshProfileInstallStartedReason replaces it when the operator configured a+// bundle for the daemon to install (MULTICA_DSH_PROFILE_BUNDLE), so /health+// separates "wait for the install" from "nothing is going to happen".+const dshProfileInstallStartedReason = "the Multica runtime profile is not installed; installing the configured bundle now and re-probing when it finishes"++// dshInstallGaveUpReason replaces the "installing now" detail once the+// automatic install has stopped without producing a profile. It says the+// attempt happened and ended, because a reader who saw the earlier "installing"+// reason needs to know which of the two states they are looking at.+const dshInstallGaveUpReason = "the Multica runtime profile is not installed; the automatic install failed, so it has to be installed by hand"++// dshIncompatibleProfileReason is the /health reason for a profile that answers+// with a protocol this daemon does not drive. It names both sides because+// either can be the stale one.+const dshIncompatibleProfileReason = "the Multica runtime profile answers with a protocol version this daemon does not drive; update the profile bundle or the daemon"++// dshProbeFailedReason is the transient reason: the probe did not answer with a+// probe frame at all — a timeout, a failed exec, or unparseable output. It is+// deliberately not phrased as a version problem, which would send a reader+// looking in the wrong place.+const dshProbeFailedReason = "the DSH runtime profile probe returned no usable answer"+// runtimeVerdict is one provider's confirmed verdict: the human reason that// goes to /health and the daemon log, plus — when the cause is one the user has// to act on — the structured record the server stores on the runtime row.@@ -2274,15 +2443,32 @@ type runtimeVerdict struct {// a file the OS refuses to execute is present, so the self-heal that would have// re-resolved a vanished path never runs, and the probe failed on this exact// file.-func newRuntimeVerdict(verdict builtinProbeVerdict, reason, execPath string) runtimeVerdict {- if verdict != builtinProbeNotExecutable {- return runtimeVerdict{reason: reason}- }- offline := &RuntimeOfflineReason{Code: RuntimeOfflineCodeNotExecutable, Detail: reason}- if repair, ok := agent.ExecFormatRepairFor(execPath); ok {+func newRuntimeVerdict(verdict builtinProbeVerdict, reason, execPath string, installing bool) runtimeVerdict {+ switch verdict {+ case builtinProbeNotExecutable:+ offline := &RuntimeOfflineReason{Code: RuntimeOfflineCodeNotExecutable, Detail: reason}+ if repair, ok := agent.ExecFormatRepairFor(execPath); ok {+ offline.Repair = &repair+ }+ return runtimeVerdict{reason: reason, offline: offline}+ case builtinProbeMissingProfile:+ // The same class of finding as an unrunnable file: the machine is+ // reachable and the CLI cannot serve work, so the server must refuse+ // the trigger and say what is missing rather than queue behind a wait+ // that never ends. The one exception is an install the daemon is+ // running right now, which is stated explicitly instead of being+ // implied by an absent reason — and withdrawn by+ // withdrawDshInstallWait if that install gives up.+ offline := &RuntimeOfflineReason{+ Code: RuntimeOfflineCodeDshProfile,+ Detail: reason,+ Installing: installing,+ }+ repair := dshProfileRepair()offline.Repair = &repair+ return runtimeVerdict{reason: reason, offline: offline}}- return runtimeVerdict{reason: reason, offline: offline}+ return runtimeVerdict{reason: reason}}// probeBuiltinRuntime resolves and version-detects one built-in provider,@@ -2290,7 +2476,9 @@ func newRuntimeVerdict(verdict builtinProbeVerdict, reason, execPath string) run// tells the caller how to treat a drop: builtinProbeUnavailable means the// version could not be read (or not understood) — transient, leave whatever is// registered alone — while builtinProbeBelowMinimum is a confirmed too-old-// verdict the caller may demote on. See builtinProbeVerdict.+// verdict the caller may demote on. builtinProbeMissingProfile is confirmed in+// the same way, for a CLI that runs but whose backend has no runtime profile+// installed. See builtinProbeVerdict.//// The second return value is a short human-readable reason when the verdict is// not OK. It is surfaced on /health as skipped_agents so a user can tell "CLI@@ -2300,7 +2488,13 @@ func (d *Daemon) probeBuiltinRuntime(ctx context.Context, name string, entry Agevar (lastErr errorattempts int+ // transientReason lets a provider whose probe is not a version probe+ // name its own failure. The generic tail would otherwise report "version+ // detection failed" for a dsh that answered --version perfectly well,+ // which sends a reader looking for the wrong problem.+ transientReason string)+probeLoop:for attempts < runtimeVersionProbeAttempts {if attempts > 0 {select {@@ -2315,6 +2509,13 @@ func (d *Daemon) probeBuiltinRuntime(ctx context.Context, name string, entry Age}}attempts+++ // Cleared per attempt: this names the DSH profile probe's own failure,+ // and only for a round that ENDED there. An attempt that gets past the+ // probe and then fails version detection has a more specific reason,+ // and a stale value from an earlier attempt would overwrite it at the+ // tail — reporting "the probe returned no usable answer" for a probe+ // that answered fine.+ transientReason = ""// The attempt is timed from here, not from the detect call below:// resolveAgentEntry runs a version probe of its own on the re-resolved// candidate, and that probe can burn the whole timeout by itself. Timing@@ -2387,6 +2588,67 @@ func (d *Daemon) probeBuiltinRuntime(ctx context.Context, name string, entry Age}continue}+ // DSH is the one built-in whose binary being present, and runnable, and+ // new enough still does not make it usable: the Multica runtime profile+ // supplies the --stdio protocol the backend drives, so a `dsh` without+ // it resolves, answers `--version`, clears the minimum, and then cannot+ // run a single task. Checked here rather than in probeAgentCLIs so the+ // drop produces a verdict: without it the provider disappeared from the+ // availability set silently, which is indistinguishable to a user from+ // "Multica cannot see my dsh at all".+ //+ // LAST, after version detection has succeeded, and that order is the+ // point. probeDshMulticaProfile cannot tell "the profile refused" from+ // "the thing I ran is not a working CLI", and exec.LookPath is far too+ // weak a proxy for the second: on Windows the CLI is a .cmd shim that+ // LookPath happily resolves and that exits 9009 — cmd.exe's "command+ // not found" — when what it forwards to is missing. Probing the profile+ // first reported that machine as "the Multica runtime profile is not+ // installed", which is a repair for a problem it did not have, and with+ // a bundle configured would have started installing into a DSH that+ // cannot execute. A CLI that cannot answer `--version` is not one this+ // daemon has any business holding an opinion about the profile of, so+ // its failure is reported as what it is by the version-probe path+ // above.+ if name == "dsh" {+ // What the probe said decides what may happen next. Only a+ // confirmed-absent profile may install a bundle or condemn the+ // runtime. An incompatible one is reported and neither installed+ // over nor demoted — the profile is deliberately there, and this+ // daemon may be the stale side of the skew. A probe that merely+ // failed is transient, on the same rule every other provider's+ // version probe gets.+ switch probeDshMulticaProfile(ctx, resolved.Path) {+ case dshProbeOK:+ case dshProbeMissingProfile:+ d.logger.Warn("skip registering runtime: DSH Multica runtime profile is not installed",+ "name", name, "path", resolved.Path)+ reason := dshMissingProfileReason+ if d.startDshProfileProvision(resolved.Path) {+ reason = dshProfileInstallStartedReason+ }+ return "", reason, builtinProbeMissingProfile+ case dshProbeIncompatible:+ d.logger.Warn("skip registering runtime: DSH Multica runtime profile speaks another protocol",+ "name", name, "path", resolved.Path)+ return "", dshIncompatibleProfileReason, builtinProbeIncompatibleProfile+ default:+ // Transient. Retry inside this round's budget, then leave the+ // loop for the tail, which reports it as the transient drop it+ // is. The labelled break matters: a bare one would leave only+ // the switch and fall through to registering a runtime whose+ // profile answered nothing.+ lastErr = errors.New(dshProbeFailedReason)+ transientReason = dshProbeFailedReason+ if time.Since(startedAt) >= runtimeVersionProbeRetryWindow {+ break probeLoop+ }+ if attempts < runtimeVersionProbeAttempts {+ d.logger.Debug("dsh profile probe failed; retrying", "name", name, "attempt", attempts)+ }+ continue+ }+ }d.setAgentVersion(name, version)d.refreshHealedVersion(name, resolved.Path, version)if version == "" {@@ -2419,6 +2681,9 @@ func (d *Daemon) probeBuiltinRuntime(ctx context.Context, name string, entry Ageif lastErr != nil {reason = fmt.Sprintf("version detection failed: %v", lastErr)}+ if transientReason != "" {+ reason = transientReason+ }return "", reason, builtinProbeUnavailable}@@ -2463,7 +2728,8 @@ func (d *Daemon) probeBuiltinRuntime(ctx context.Context, name string, entry Age// preserve these providers' existing runtimes: they are absent from the// payload because the probe failed, which is transient — tearing a working// runtime down over it is exactly what the unavailable/below-minimum verdict-// split exists to prevent. Only a below-minimum verdict may demote.+// split exists to prevent. demotableBuiltinProbeVerdict is the list of verdicts+// that may demote.func (d *Daemon) detectBuiltinRuntimes(ctx context.Context) ([]map[string]string, map[string]runtimeVerdict, map[string]string) {type detected struct {name string@@ -2487,25 +2753,20 @@ func (d *Daemon) detectBuiltinRuntimes(ctx context.Context) ([]map[string]stringg.Go(func() error {version, reason, verdict := d.probeBuiltinRuntime(ctx, name, entry)if verdict != builtinProbeOK {- // A not-executable verdict is deterministic, but the file can be- // unreadable for a moment while an installer overwrites it in- // place — which is exactly the repair we are telling users to- // run. Demote only once the verdict has survived a second probe- // a confirmation window later; until then it is treated as- // transient, which costs one more round and nothing else.- demote := verdict == builtinProbeBelowMinimum ||- (verdict == builtinProbeNotExecutable && d.confirmNotExecutable(name, time.Now()))+ demote := demotableBuiltinProbeVerdict(verdict) &&+ (!builtinProbeNeedsConfirmation(verdict) ||+ d.confirmCondemned(verdict, name, time.Now()))mu.Lock()skipped[name] = reasonif demote {- demotable[name] = newRuntimeVerdict(verdict, reason, entry.Path)+ demotable[name] = newRuntimeVerdict(verdict, reason, entry.Path, d.dshInstallInFlight.Load())} else {unavailable[name] = reason}mu.Unlock()return nil}- d.clearNotExecutable(name)+ d.clearCondemned(name)mu.Lock()results = append(results, detected{name: name, version: version})mu.Unlock()@@ -3726,7 +3987,59 @@ const DefaultTokenRenewalInterval = 3 * 24 * time.Hour// register runtimes once one appears.func (d *Daemon) preflightAuth(ctx context.Context) error {d.tryRenewToken(ctx)- return d.syncWorkspacesFromAPI(ctx, false)+ err := d.syncWorkspacesFromAPI(ctx, false)+ if d.startupMayProceedWithoutRuntimes(err) {+ d.logger.Warn("starting with no runtimes registered: an automatic DSH runtime profile install is still running; " ++ "the runtime registers when it finishes")+ return nil+ }+ return err+}++// startupMayProceedWithoutRuntimes reports whether a startup that registered+// nothing may continue anyway.+//+// Exactly one situation qualifies: the daemon has just started installing the+// DSH runtime profile itself. On a host whose only provider is a dsh without+// that profile, failing here is a deadlock rather than a fail-fast — the probe+// starts the install, this error kills the process milliseconds later, the+// install's process tree dies with it, and the next start repeats all of it.+// The feature exists precisely for that host, so on it the feature could never+// once complete.+//+// Nothing else is forgiven. An unreachable server, a rejected token, and a+// genuinely empty machine all still fail startup, because for those the daemon+// has no reason to believe the answer is coming.+func (d *Daemon) startupMayProceedWithoutRuntimes(err error) bool {+ return errors.Is(err, errNoWorkspaceRuntimesRegistered) && d.dshInstallInFlight.Load()+}++// trackedWorkspaceCount reports how many workspaces the daemon currently hosts.+func (d *Daemon) trackedWorkspaceCount() int {+ d.mu.Lock()+ defer d.mu.Unlock()+ return len(d.workspaces)+}++// registerAfterDshProfileInstall brings a newly usable dsh online without+// waiting for a scheduled round.+//+// A converge round is enough in the ordinary case, but not after the bootstrap+// startupMayProceedWithoutRuntimes allows: a daemon that registered nothing+// tracks no workspace, and every converge path iterates the workspaces it+// tracks, so there would be nothing for the round to look at. The workspace has+// to be picked up first, and waiting for the periodic consistency sync to do it+// would leave the runtime offline for its full interval after an install the+// user watched succeed.+func (d *Daemon) registerAfterDshProfileInstall(ctx context.Context) {+ if d.trackedWorkspaceCount() > 0 {+ d.kickAgentDiscovery()+ return+ }+ if err := d.syncWorkspacesFromAPI(ctx, false); err != nil {+ d.logger.Warn("workspace sync after the DSH runtime profile install failed; "++ "the periodic sync is the backstop", "error", err)+ }}// tokenRenewalLoop keeps the daemon's PAT alive by periodically asking the@@ -4071,7 +4384,7 @@ func (d *Daemon) syncWorkspacesFromAPI(ctx context.Context, reconcileProfiles bod.publishTrackedCoAuthoredByState()if len(d.allRuntimeIDs()) == 0 && registered == 0 && len(workspaces) > 0 {- return fmt.Errorf("failed to register runtimes for any of the %d workspace(s)", len(workspaces))+ return fmt.Errorf("%w for any of the %d workspace(s)", errNoWorkspaceRuntimesRegistered, len(workspaces))}if registered > 0 || removed > 0 {d.logger.Debug("workspace sync done", "registered", registered, "removed", removed, "tracked", len(apiIDs))diff --git a/server/internal/daemon/dsh_bundle_paths_test.go b/server/internal/daemon/dsh_bundle_paths_test.gonew file mode 100644index 0000000000..dc20e98121--- /dev/null+++ b/server/internal/daemon/dsh_bundle_paths_test.go@@ -0,0 +1,351 @@+package daemon++import (+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "testing"+ "time"+)++// envFrom turns a map into the lookup dshDesktopBundlePathsFor takes, so a test+// can describe a Windows environment without touching the host's.+func envFrom(pairs map[string]string) func(string) string {+ return func(key string) string { return pairs[key] }+}++// mkShim writes one generated CLI payload — <dir>/bin — and stamps the payload+// directory, which is what orders candidates within a tier.+func mkShim(t *testing.T, dir string, modTime time.Time) string {+ t.Helper()+ if err := os.MkdirAll(filepath.Join(dir, "bin"), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.Chtimes(dir, modTime, modTime); err != nil {+ t.Fatal(err)+ }+ return dir+}++// hostCommandsPayload writes the layout confirmed on a real Windows install:+//+// <appData>\host-commands\<profile>\generations\<hash>-<uuid>\bin\dsh.cmd+func hostCommandsPayload(t *testing.T, appData, profile, generation string, modTime time.Time) string {+ t.Helper()+ return mkShim(t, filepath.Join(appData, "host-commands", profile, "generations", generation), modTime)+}++// cliPayload writes the other shape: <appData>\cli\<hash>\bin.+func cliPayload(t *testing.T, appData, hash string, modTime time.Time) string {+ t.Helper()+ return mkShim(t, filepath.Join(appData, "cli", hash), modTime)+}++// The layout that actually works on Windows. The shim sets DSH_HOME and calls+// the Desktop executable by absolute path, so it needs nothing on PATH — which+// is why it is preferred over every other candidate.+func TestDshDesktopShimCandidates_HostCommandsLayout(t *testing.T) {+ appData := t.TempDir()+ gen := "0d077d22abfd9f6817de376152441a787680be20b8d5a17350390d72570c17ce-a67d0d81-d10b-4bbe-b1d1-2ac2eb7fcbce"+ dir := hostCommandsPayload(t, appData, "desktop", gen, time.Now())++ got := dshDesktopShimCandidates(appData, dshDesktopShimNames("windows"))+ want := []string{+ filepath.Join(dir, "bin", "dsh.exe"),+ filepath.Join(dir, "bin", "dsh.cmd"),+ filepath.Join(dir, "bin", "dsh.bat"),+ }+ if strings.Join(got, "\n") != strings.Join(want, "\n") {+ t.Fatalf("candidates =\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))+ }+}++// The tier order is load-bearing, not cosmetic. Nothing here executes a+// candidate, so a broken-but-present shim is indistinguishable from a working+// one at this layer — and on the install that prompted this, the cli shim was+// exactly that: present, resolvable by exec.LookPath, and exiting 9009. Ranking+// host-commands first is the only thing that keeps it from winning.+func TestDshDesktopShimCandidates_HostCommandsOutranksCLIEvenWhenOlder(t *testing.T) {+ appData := t.TempDir()+ // The cli payload is NEWER, so only the tier can decide this.+ hostCommandsPayload(t, appData, "desktop", "host-gen", time.Now().Add(-72*time.Hour))+ cliPayload(t, appData, "cli-hash", time.Now())++ got := dshDesktopShimCandidates(appData, dshDesktopShimNames("windows"))+ if len(got) == 0 {+ t.Fatal("no candidates")+ }+ if !strings.Contains(got[0], filepath.Join("host-commands", "desktop")) {+ t.Fatalf("first candidate = %q, want the host-commands shim", got[0])+ }+ // The cli payload still gets a turn: on a Desktop version that generates no+ // host-commands it is the only shim there is.+ if !strings.Contains(strings.Join(got, "\n"), filepath.Join("cli", "cli-hash")) {+ t.Error("the cli payload was dropped entirely rather than ranked lower")+ }+}++// The profile level belongs to the user, so it is enumerated rather than+// assumed to be "desktop".+func TestDshDesktopShimCandidates_EnumeratesEveryProfile(t *testing.T) {+ appData := t.TempDir()+ hostCommandsPayload(t, appData, "desktop", "gen-old", time.Now().Add(-time.Hour))+ newest := hostCommandsPayload(t, appData, "some-other-profile", "gen-new", time.Now())++ got := dshDesktopShimCandidates(appData, dshDesktopShimNames("windows"))+ if len(got) == 0 {+ t.Fatal("no candidates")+ }+ if !strings.HasPrefix(got[0], newest) {+ t.Fatalf("first candidate = %q, want the newest generation %q regardless of profile", got[0], newest)+ }+ if !strings.Contains(strings.Join(got, "\n"), "desktop") {+ t.Error("a profile other than the newest was dropped")+ }+}++// An upgrade writes a new generation and can leave the old one behind. The+// newest is the one the app is driving; offering an abandoned generation first+// would register a CLI the user has already replaced.+func TestDshDesktopShimCandidates_NewestGenerationWins(t *testing.T) {+ appData := t.TempDir()+ hostCommandsPayload(t, appData, "desktop", "aaaa-old", time.Now().Add(-72*time.Hour))+ current := hostCommandsPayload(t, appData, "desktop", "bbbb-current", time.Now())++ got := dshDesktopShimCandidates(appData, dshDesktopShimNames("windows"))+ if len(got) == 0 || !strings.HasPrefix(got[0], current) {+ t.Fatalf("first candidate = %v, want the newest generation %q", got, current)+ }+}++// Two payloads can share a filesystem timestamp tick. ReadDir order is not a+// promise, so the name has to break the tie or the daemon would pick a+// different CLI on different rounds.+func TestDshDesktopShimCandidates_TieBreakIsStable(t *testing.T) {+ appData := t.TempDir()+ stamp := time.Now().Add(-time.Hour)+ for _, gen := range []string{"aaaa", "cccc", "bbbb"} {+ hostCommandsPayload(t, appData, "desktop", gen, stamp)+ }++ first := dshDesktopShimCandidates(appData, dshDesktopShimNames("windows"))+ for i := 0; i < 5; i++ {+ if again := dshDesktopShimCandidates(appData, dshDesktopShimNames("windows")); strings.Join(again, "\n") != strings.Join(first, "\n") {+ t.Fatalf("order changed between calls:\n%v\nvs\n%v", first, again)+ }+ }+ if !strings.Contains(first[0], "cccc") {+ t.Errorf("first candidate = %q, want the name tie-break to pick cccc", first[0])+ }+}++// A stray file, a payload with no bin directory (a half-extracted download), a+// profile with no generations directory, and a missing app-data root are all+// "nothing to offer" rather than a candidate that fails at spawn time.+func TestDshDesktopShimCandidates_SkipsWhatCannotHoldACLI(t *testing.T) {+ appData := t.TempDir()+ if err := os.MkdirAll(filepath.Join(appData, "cli", "half-extracted"), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.MkdirAll(filepath.Join(appData, "host-commands", "desktop"), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(appData, "cli", "manifest.json"), []byte("{}"), 0o644); err != nil {+ t.Fatal(err)+ }+ if got := dshDesktopShimCandidates(appData, dshDesktopShimNames("windows")); len(got) != 0 {+ t.Fatalf("candidates = %v, want none", got)+ }+ if got := dshDesktopShimCandidates(filepath.Join(appData, "nope"), dshDesktopShimNames("windows")); len(got) != 0 {+ t.Fatalf("candidates = %v for a missing root, want none", got)+ }+ if got := dshDesktopShimCandidates("", dshDesktopShimNames("windows")); len(got) != 0 {+ t.Fatalf("candidates = %v for an empty root, want none", got)+ }+}++// %APPDATA% is redirected on managed and roaming-profile machines, so the+// environment wins; composing from home is the last resort. macOS has no such+// variable and is always home-relative.+func TestDshDesktopAppDataDir(t *testing.T) {+ fromEnv := dshDesktopAppDataDir("windows", envFrom(map[string]string{+ "APPDATA": `D:\Profiles\jane\Roaming`,+ }), `C:\Users\jane`)+ if want := filepath.Join(`D:\Profiles\jane\Roaming`, "DSH Desktop"); fromEnv != want {+ t.Errorf("windows dir = %q, want %q", fromEnv, want)+ }++ fromHome := dshDesktopAppDataDir("windows", envFrom(nil), `C:\Users\jane`)+ if want := filepath.Join(`C:\Users\jane`, "AppData", "Roaming", "DSH Desktop"); fromHome != want {+ t.Errorf("windows dir = %q, want %q", fromHome, want)+ }++ mac := dshDesktopAppDataDir("darwin", envFrom(nil), "/Users/jane")+ if want := filepath.Join("/Users/jane", "Library", "Application Support", "DSH Desktop"); mac != want {+ t.Errorf("darwin dir = %q, want %q", mac, want)+ }++ // Nothing to name, and inventing a directory would make every candidate+ // below it a false path.+ for _, goos := range []string{"windows", "darwin", "linux"} {+ if got := dshDesktopAppDataDir(goos, envFrom(nil), ""); got != "" {+ t.Errorf("%s dir = %q with no environment and no home, want empty", goos, got)+ }+ }+}++// The macOS app-bundle entry point is a Node script started through its+// shebang, so it needs node on PATH. It stays as a candidate — it works on a+// machine that has node — but it must never outrank a self-contained shim, and+// it must never appear on Windows, where nothing can start a .js.+func TestDshDesktopBundlePathsFor_ShimOutranksTheNodeScript(t *testing.T) {+ home := t.TempDir()+ appData := filepath.Join(home, "Library", "Application Support", "DSH Desktop")+ shim := hostCommandsPayload(t, appData, "desktop", "gen", time.Now())++ got := dshDesktopBundlePathsFor("darwin", envFrom(nil), home)+ if len(got) == 0 {+ t.Fatal("no candidates")+ }+ if !strings.HasPrefix(got[0], shim) {+ t.Fatalf("first candidate = %q, want the self-contained shim %q", got[0], shim)+ }+ last := got[len(got)-1]+ if !strings.HasSuffix(last, "bin.js") {+ t.Errorf("last candidate = %q, want the app-bundle script ranked last", last)+ }++ // Windows never offers it: exec.LookPath rejects a .js unless PATHEXT says+ // otherwise, and CreateProcess cannot start one either.+ for _, path := range dshDesktopBundlePathsFor("windows", envFrom(map[string]string{"APPDATA": appData}), home) {+ if strings.HasSuffix(path, ".js") {+ t.Errorf("windows candidate %q cannot be spawned there", path)+ }+ }+}++// The pnpm `dsh plugin` forwards to lives under runtime-commands in the app's+// own data directory — and the two platforms disagree about the shape. macOS+// 2.0.5 keeps a flat runtime-commands/bin; a Windows install keeps+// runtime-commands/generations/<id>/bin. Composing either path would have left+// the other reporting "pnpm not found on PATH" on exactly the machines the+// automatic install exists for, so both are searched.+func TestDshPluginPathDirs_FindsBothLayouts(t *testing.T) {+ t.Setenv(dshPluginPathEnv, "")++ t.Run("generational", func(t *testing.T) {+ home := t.TempDir()+ appData := dshDesktopAppDataDir(runtime.GOOS, os.Getenv, home)+ if appData == "" {+ t.Skip("no app-data location on this platform")+ }+ want := mkShim(t, filepath.Join(appData, "runtime-commands", "generations", "gen-1"), time.Now())+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)++ got := dshPluginPathDirs()+ if len(got) == 0 || got[0] != filepath.Join(want, "bin") {+ t.Fatalf("dirs = %v, want %q first", got, filepath.Join(want, "bin"))+ }+ })++ t.Run("flat", func(t *testing.T) {+ home := t.TempDir()+ appData := dshDesktopAppDataDir(runtime.GOOS, os.Getenv, home)+ if appData == "" {+ t.Skip("no app-data location on this platform")+ }+ flat := filepath.Join(appData, "runtime-commands", "bin")+ if err := os.MkdirAll(flat, 0o755); err != nil {+ t.Fatal(err)+ }+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)++ got := dshPluginPathDirs()+ if len(got) != 1 || got[0] != flat {+ t.Fatalf("dirs = %v, want exactly %q", got, flat)+ }+ })+}++// An explicit override is the whole answer. An operator who pinned a directory+// that does not exist is trying to bypass the bundled pnpm, and silently+// falling back to it would defeat that — they should get "pnpm not found".+func TestDshPluginPathDirs_OverrideWins(t *testing.T) {+ dir := t.TempDir()+ t.Setenv(dshPluginPathEnv, dir)+ if got := dshPluginPathDirs(); len(got) != 1 || got[0] != dir {+ t.Fatalf("dirs = %v, want exactly %q", got, dir)+ }++ t.Setenv(dshPluginPathEnv, filepath.Join(dir, "does-not-exist"))+ if got := dshPluginPathDirs(); len(got) != 0 {+ t.Fatalf("dirs = %v, want none for an override that does not exist", got)+ }+}++// An upgrade writes a new generation and can leave the old one behind; the+// newest is the one the app is driving. The flat directory ranks last, because+// a host holding both is one where the generational layout is the newer.+func TestDshDesktopBinDirs_Ordering(t *testing.T) {+ root := t.TempDir()+ mkShim(t, filepath.Join(root, "old"), time.Now().Add(-72*time.Hour))+ current := mkShim(t, filepath.Join(root, "current"), time.Now())+ flat := filepath.Join(root, "bin")+ if err := os.MkdirAll(flat, 0o755); err != nil {+ t.Fatal(err)+ }++ got := dshDesktopBinDirs(root)+ want := []string{+ filepath.Join(current, "bin"),+ filepath.Join(root, "old", "bin"),+ flat,+ }+ if strings.Join(got, "\n") != strings.Join(want, "\n") {+ t.Fatalf("dirs =\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))+ }++ // A payload with no bin, a stray file, and a missing root offer nothing.+ if err := os.MkdirAll(filepath.Join(root, "half-extracted"), 0o755); err != nil {+ t.Fatal(err)+ }+ if len(dshDesktopBinDirs(root)) != 3 {+ t.Errorf("a payload without a bin directory was offered: %v", dshDesktopBinDirs(root))+ }+ if got := dshDesktopBinDirs(filepath.Join(root, "nope")); len(got) != 0 {+ t.Errorf("dirs = %v for a missing root, want none", got)+ }+ if got := dshDesktopBinDirs(""); len(got) != 0 {+ t.Errorf("dirs = %v for an empty root, want none", got)+ }+}++// macOS keeps its app-bundle candidates: system-wide /Applications before the+// per-user ~/Applications, and only the first when there is no home.+func TestDshDesktopBundlePathsFor_DarwinAppBundle(t *testing.T) {+ const bundle = "DSH Desktop.app/Contents/Resources/app.asar.unpacked/node_modules/@deepseek-ai/dsh/lib/bin.js"+ got := dshDesktopBundlePathsFor("darwin", envFrom(nil), "/nonexistent-home")++ want := []string{+ filepath.Join("/Applications", bundle),+ filepath.Join("/nonexistent-home", "Applications", bundle),+ }+ if strings.Join(got, "\n") != strings.Join(want, "\n") {+ t.Fatalf("candidates =\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))+ }++ if paths := dshDesktopBundlePathsFor("darwin", envFrom(nil), ""); len(paths) != 1 {+ t.Errorf("with no home, want only the /Applications candidate, got %v", paths)+ }+}++// Linux ships no DSH Desktop, and a candidate list for a platform with no known+// install location can only produce false positives.+func TestDshDesktopBundlePathsFor_UnknownPlatform(t *testing.T) {+ if got := dshDesktopBundlePathsFor("linux", envFrom(nil), "/home/jane"); len(got) != 0 {+ t.Fatalf("candidates = %v, want none", got)+ }+}diff --git a/server/internal/daemon/dsh_install_wait_test.go b/server/internal/daemon/dsh_install_wait_test.gonew file mode 100644index 0000000000..0162ae640e--- /dev/null+++ b/server/internal/daemon/dsh_install_wait_test.go@@ -0,0 +1,134 @@+package daemon++import (+ "context"+ "encoding/json"+ "io"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "sync"+ "testing"+)++// deregisterRecorder captures the offline reasons a daemon sends, keyed by+// runtime id, across every deregister call.+type deregisterRecorder struct {+ mu sync.Mutex+ calls int+ reasons map[string]RuntimeOfflineReason+}++func newDeregisterRecorder(t *testing.T) (*deregisterRecorder, *Client) {+ t.Helper()+ rec := &deregisterRecorder{reasons: map[string]RuntimeOfflineReason{}}+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var body struct {+ RuntimeIDs []string `json:"runtime_ids"`+ OfflineReasons map[string]RuntimeOfflineReason `json:"offline_reasons"`+ }+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Errorf("decode deregister body: %v", err)+ }+ rec.mu.Lock()+ rec.calls+++ for id, reason := range body.OfflineReasons {+ rec.reasons[id] = reason+ }+ rec.mu.Unlock()+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"status":"ok"}`))+ }))+ t.Cleanup(srv.Close)+ return rec, NewClient(srv.URL)+}++func (r *deregisterRecorder) reasonFor(id string) (RuntimeOfflineReason, bool) {+ r.mu.Lock()+ defer r.mu.Unlock()+ reason, ok := r.reasons[id]+ return reason, ok+}++// `installing` is a promise that this offline runtime comes back by itself, and+// the server queues assignments and @mentions behind it instead of refusing+// them (MUL-6164). The row carrying it is written exactly once, by the demotion+// — which also drops the runtime from the index, so no later round has a+// runtime to condemn and no later deregistration is sent.+//+// So an install that fails after that point has to take the promise back+// itself. Left alone, every trigger for that agent queues forever behind an+// install that already gave up, which is precisely the failure the structured+// reason exists to prevent.+func TestWithdrawDshInstallWait_FailedInstallTakesTheWaitBack(t *testing.T) {+ rec, client := newDeregisterRecorder(t)+ d := &Daemon{+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ client: client,+ workspaces: map[string]*workspaceState{"ws-1": {}},+ runtimeIndex: map[string]Runtime{},+ }+ d.dshInstallWaits = []dshInstallWait{{+ workspaceID: "ws-1",+ runtimeID: "rt-dsh",+ reason: RuntimeOfflineReason{+ Code: RuntimeOfflineCodeDshProfile,+ Detail: dshProfileInstallStartedReason,+ Installing: true,+ },+ }}++ d.withdrawDshInstallWait(context.Background())++ got, ok := rec.reasonFor("rt-dsh")+ if !ok {+ t.Fatal("no corrected reason was sent; the runtime row still claims an install is running")+ }+ if got.Installing {+ t.Error("the corrected reason still says installing, so the server keeps queueing")+ }+ if got.Code != RuntimeOfflineCodeDshProfile {+ t.Errorf("code = %q, want it unchanged at %q", got.Code, RuntimeOfflineCodeDshProfile)+ }+ if got.Detail == dshProfileInstallStartedReason || got.Detail == "" {+ t.Errorf("detail = %q, want it to say the install ended", got.Detail)+ }++ // Drained, not replayed: a second call must not re-send a correction the+ // server already has, and must not undo a runtime that has since recovered.+ d.withdrawDshInstallWait(context.Background())+ rec.mu.Lock()+ calls := rec.calls+ rec.mu.Unlock()+ if calls != 1 {+ t.Errorf("deregister calls = %d, want 1", calls)+ }+}++// A runtime the daemon tracks again has been re-registered since the demotion,+// and its row already says online. Correcting it would knock a recovered+// runtime back offline on the strength of an older decision — the same+// re-check every other deregistration path makes.+func TestWithdrawDshInstallWait_SkipsARuntimeThatCameBack(t *testing.T) {+ rec, client := newDeregisterRecorder(t)+ d := &Daemon{+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ client: client,+ workspaces: map[string]*workspaceState{"ws-1": {runtimeIDs: []string{"rt-dsh"}}},+ runtimeIndex: map[string]Runtime{"rt-dsh": {ID: "rt-dsh", Provider: "dsh"}},+ }+ d.dshInstallWaits = []dshInstallWait{{+ workspaceID: "ws-1",+ runtimeID: "rt-dsh",+ reason: RuntimeOfflineReason{Code: RuntimeOfflineCodeDshProfile, Installing: true},+ }}++ d.withdrawDshInstallWait(context.Background())++ rec.mu.Lock()+ calls := rec.calls+ rec.mu.Unlock()+ if calls != 0 {+ t.Fatalf("deregister calls = %d, want 0: the runtime is tracked again and its row says online", calls)+ }+}diff --git a/server/internal/daemon/dsh_profile.go b/server/internal/daemon/dsh_profile.gonew file mode 100644index 0000000000..c0afdc7dee--- /dev/null+++ b/server/internal/daemon/dsh_profile.go@@ -0,0 +1,365 @@+package daemon++import (+ "context"+ "fmt"+ "log/slog"+ "os"+ "os/exec"+ "path/filepath"+ "regexp"+ "runtime"+ "strings"+ "time"+ "unicode/utf8"++ "github.com/multica-ai/multica/server/internal/daemon/processtree"+ "github.com/multica-ai/multica/server/pkg/agent"+ "github.com/multica-ai/multica/server/pkg/redact"+)++// The DSH backend drives `dsh --profile multica --stdio`, and that profile is+// what supplies the protocol: DSH ships no machine-drivable mode of its own.+// `--profile headless` answers one task and exits, and ACP — the one protocol+// DSH does implement — is itself a profile rather than a built-in. Every other+// built-in drives a protocol its CLI already has (`claude -p --output-format+// stream-json`, `codex app-server`, `kimi acp`), which is why dsh is the only+// provider whose integration depends on the user installing something into the+// agent's own home first.+//+// These knobs let the daemon close that gap instead of only reporting it.+const (+ // dshProfileBundleEnv names the DSH-side bundle to install into the+ // `multica` profile when a dsh CLI resolves without one. It takes a+ // comma-separated list of candidates tried in order, each of which may be+ // anything `dsh plugin --profile multica add` accepts: an npm spec, a+ // directory, or a packed tarball.+ //+ // Unset is the default and means "do not touch the user's DSH+ // installation". Installing a bundle into another product's home is a+ // side effect the operator has to ask for — and there is nothing to point+ // it at by default either, because Multica's own DSH bridge is not+ // published to npm yet (multica#6936). Setting this is what turns the+ // reported drop into a self-healing one.+ dshProfileBundleEnv = "MULTICA_DSH_PROFILE_BUNDLE"++ // dshPluginPathEnv overrides where `dsh plugin` finds pnpm. It exists+ // because DSH Desktop ships pnpm inside its own runtime-commands+ // directory and injects that directory into the PATH of the processes it+ // spawns itself. A daemon started by Multica's desktop app, by launchd or+ // from a terminal is not one of them, so the install fails with "pnpm not+ // found on PATH" on exactly the machines this feature is for.+ dshPluginPathEnv = "MULTICA_DSH_PLUGIN_PATH"++ // dshMulticaProfileName is the profile the backend launches. Kept beside+ // the install command so the two cannot drift.+ dshMulticaProfileName = "multica"+)++// dshProvisionTimeout bounds the whole install. It is a package manager+// talking to a registry, so it is generous next to the CLI probes.+const dshProvisionTimeout = 3 * time.Minute++// dshMulticaProfilePresent reports whether the `multica` profile is installed.+//+// A stat, deliberately. This is the cheap change detector the discovery loop+// runs on every tick, and both things that change the answer — `dsh plugin+// --profile multica add` and a user removing the directory — create or remove+// exactly this file. DSH decides a profile exists the same way: dsh-app-boot's+// loadProfile falls back to a built-in template, or fails, when the manifest is+// missing.+//+// The authoritative question — "does --probe actually succeed?" — costs booting+// a whole DSH process, so it stays in the probe round this signal forces.+func dshMulticaProfilePresent() bool {+ home, err := os.UserHomeDir()+ if err != nil {+ return false+ }+ // DSH_HOME is DSH's own override, and the profile store lives under it+ // either way. Same resolution local_skills.go uses to find ~/.dsh/skills.+ dshHome := strings.TrimSpace(os.Getenv("DSH_HOME"))+ if dshHome == "" {+ dshHome = filepath.Join(home, ".dsh")+ }+ _, err = os.Stat(filepath.Join(dshHome, "profiles", dshMulticaProfileName, "package.json"))+ return err == nil+}++// dshProfileBundleSpecs returns the configured install candidates, in order,+// or nil when the operator has not opted in.+func dshProfileBundleSpecs() []string {+ raw := strings.TrimSpace(os.Getenv(dshProfileBundleEnv))+ if raw == "" {+ return nil+ }+ var specs []string+ for _, spec := range strings.Split(raw, ",") {+ if spec = strings.TrimSpace(spec); spec != "" {+ specs = append(specs, spec)+ }+ }+ return specs+}++// dshPluginPathDirs returns the directories that may hold the pnpm `dsh plugin`+// forwards to, newest first. Only directories that exist are returned:+// prepending a miss to PATH buys nothing and makes the environment harder to+// read in a failure report.+//+// DSH Desktop keeps its private pnpm shim under runtime-commands in its own+// per-user data directory, on both platforms — the daemon inherits no path to+// it, and without this the install fails with "pnpm not found on PATH" on+// exactly the machines the automatic install is for.+//+// The layout is not the same on both, which is why this shares the enumerator+// with CLI-shim discovery rather than composing a path: macOS 2.0.5 keeps a+// flat runtime-commands/bin, while a Windows install keeps+// runtime-commands/generations/<id>/bin. Both shapes, and both levels, are+// searched, so neither is a version this daemon silently stops supporting.+func dshPluginPathDirs() []string {+ // An explicit override is the whole answer: an operator who pinned a+ // directory that does not exist should get "pnpm not found", not a silent+ // fallback to a bundled one they were trying to bypass.+ if override := strings.TrimSpace(os.Getenv(dshPluginPathEnv)); override != "" {+ if isExistingDir(override) {+ return []string{override}+ }+ return nil+ }+ home, err := os.UserHomeDir()+ if err != nil {+ home = ""+ }+ appData := dshDesktopAppDataDir(runtime.GOOS, os.Getenv, home)+ if appData == "" {+ return nil+ }+ root := filepath.Join(appData, "runtime-commands")+ return append(dshDesktopBinDirs(filepath.Join(root, "generations")), dshDesktopBinDirs(root)...)+}++// dshPluginEnv copies the daemon's environment with dshPluginPathDirs prepended+// to PATH, so `dsh plugin` resolves the pnpm DSH ships when the operator has no+// pnpm of their own.+//+// The PATH entry is matched case-insensitively, which is not cosmetic on+// Windows: the variable is conventionally spelled `Path`, so an exact `PATH=`+// match misses it, and the appended entry then wins under Go's+// case-insensitive de-duplication of the child environment — leaving the+// package manager with only the plugin directory and none of the system path.+// The original spelling is preserved rather than normalized so the merge cannot+// itself introduce a second entry.+func dshPluginEnv() []string {+ return mergeDshPluginPath(os.Environ(), dshPluginPathDirs())+}++// mergeDshPluginPath prepends dirs to whichever PATH-like entry env already has,+// preserving that entry's own spelling, or appends one when there is none.+//+// Split out from the environment read so the merge is testable with the exact+// shape Windows hands the daemon: matching is case-insensitive because the+// variable is conventionally spelled `Path` there, and an exact `PATH=` match+// misses it — after which the appended entry wins under Go's case-insensitive+// de-duplication of the child environment, leaving the package manager with only+// the plugin directory and none of the system path.+func mergeDshPluginPath(env, dirs []string) []string {+ if len(dirs) == 0 {+ return env+ }+ prefix := strings.Join(dirs, string(os.PathListSeparator))+ for i, kv := range env {+ eq := strings.IndexByte(kv, '=')+ if eq <= 0 || !strings.EqualFold(kv[:eq], "PATH") {+ continue+ }+ env[i] = kv[:eq+1] + prefix + string(os.PathListSeparator) + kv[eq+1:]+ return env+ }+ return append(env, "PATH="+prefix)+}++// dshProvisionOutputBytes bounds the package-manager output kept in a log line.+// pnpm prints a tree plus a summary and the useful part is the tail, so the tail+// is what survives.+const dshProvisionOutputBytes = 2048++// dshProvisionURLCredentials matches a URL carrying credentials in its+// userinfo. The scheme and host survive — which registry refused the request is+// what an operator reads, and is not the secret — and userinfo requires BOTH a+// colon and an @ before the next path separator, so "https://host:8443/p" and+// "ssh://git@host/p" are left alone.+//+// Local to provisioning rather than added to pkg/redact's shared pattern list.+// redact.Text runs over every agent's task messages, comments and error text, so+// a rule added there changes output for every provider; the case that needs it+// here is one package manager's error text, and widening a shared filter is its+// own change with its own blast radius.+var dshProvisionURLCredentials = regexp.MustCompile(`(?i)\b([a-z][a-z0-9+.\-]*)://[^/?#\s:@]+:[^/?#\s@]+@`)++// dshProvisionOutput renders captured output for a log line. Registry errors+// routinely echo the request URL back, so URL credentials are scrubbed and the+// shared redactor still runs for the token shapes it knows, before the text is+// bounded.+func dshProvisionOutput(raw []byte) string {+ text := dshProvisionURLCredentials.ReplaceAllString(+ strings.TrimSpace(string(raw)), "$1://[REDACTED URL CREDENTIALS]@")+ text = redact.Text(text)+ if len(text) <= dshProvisionOutputBytes {+ return text+ }+ // Cut on a rune boundary. Package-manager output is full of box drawing and+ // check marks, and non-ASCII paths are ordinary on the machines this runs+ // on, so a byte cut lands mid-rune often enough to matter — and what it+ // produces is an invalid-UTF-8 log line, which downstream JSON encoders+ // rewrite into replacement characters.+ tail := text[len(text)-dshProvisionOutputBytes:]+ for len(tail) > 0 && !utf8.ValidString(tail[:1]) {+ tail = tail[1:]+ }+ return "…" + tail+}++// dshProfileRepair names what is missing, and deliberately carries NO command.+//+// The install is `dsh plugin --profile multica add <bundle>`, and <bundle> is+// the operator's own choice of npm spec, directory or tarball — Multica's own+// bridge is not on a public registry yet (multica#6936). A Repair.Command is+// rendered to the user inside a shell code fence as the thing to run on that+// machine, so shipping the placeholder there hands out a line that fails when+// pasted. Package alone still tells the server which repair to explain; the+// prose that explains it lives in the server's notice, where it can name both+// ways to supply a real bundle.+func dshProfileRepair() agent.ExecFormatRepair {+ return agent.ExecFormatRepair{Package: "DeepSeek Harness runtime profile"}+}++// dshProvisionCommand builds one install invocation. Split out from the run so+// the argv and the environment it executes under are assertable on every+// platform, including the Windows ones where a shell fixture cannot stand in+// for a package manager.+func dshProvisionCommand(dshPath, spec string) *exec.Cmd {+ cmd := exec.Command(dshPath, "plugin", "--profile", dshMulticaProfileName, "add", spec)+ cmd.Env = dshPluginEnv()+ return cmd+}++// provisionDshMulticaProfile installs the configured runtime bundle into the+// `multica` profile, so a later discovery round finds a usable dsh. Candidates+// are tried in order and the first success wins.+//+// Runs the package manager through processtree: `dsh plugin` forwards to pnpm,+// which spawns node, which spawns whatever the bundle's install script needs.+// Killing only the direct child would leave that tree writing into the operator's+// DSH home after the daemon has stopped, and a daemon rollback cannot undo a+// write that already landed.+//+// Neither the spec nor the raw output is logged: a spec can be an npm URL with+// credentials in its userinfo or a path carrying a username, so the log names+// the candidate by position instead, and the output is redacted and bounded.+//+// A nil return means the profile is on disk, not merely that the package+// manager exited 0 — see the loop for why those are not the same thing.+//+// Returns nil when nothing is configured — the caller treats provisioning as+// best-effort either way, and the missing-profile verdict stands until a probe+// succeeds.+func provisionDshMulticaProfile(ctx context.Context, dshPath string, logger *slog.Logger) error {+ specs := dshProfileBundleSpecs()+ if len(specs) == 0 {+ return nil+ }+ ctx, cancel := context.WithTimeout(ctx, dshProvisionTimeout)+ defer cancel()++ var lastErr error+ for i, spec := range specs {+ output, err := processtree.CombinedOutput(ctx, dshProvisionCommand(dshPath, spec), 5*time.Second)+ switch {+ case err == nil && dshMulticaProfilePresent():+ logger.Info("installed the DSH runtime profile",+ "bundle_candidate", i+1, "candidates", len(specs),+ "path", dshPath, "profile", dshMulticaProfileName)+ return nil+ case err == nil:+ // Exit 0 with no manifest behind it. The exit status is the package+ // manager's opinion about its own run; dshMulticaProfilePresent is+ // the fact the REST of the daemon judges by — the probe+ // classification and the discovery loop's mismatch check both read+ // it — so an install allowed to report success while disagreeing+ // with it would log "installed the DSH runtime profile" and leave+ // every later round reporting that same profile as missing.+ //+ // Treating it as a failed candidate rather than as done is what+ // gives the remaining candidates their turn: a spec that resolves+ // and installs dependencies without producing a profile has not+ // done the job, and stopping on it would hide a later spec that+ // would have.+ lastErr = fmt.Errorf("dsh plugin --profile %s add (candidate %d of %d): reported success without creating the profile: %s",+ dshMulticaProfileName, i+1, len(specs), dshProvisionOutput(output))+ default:+ lastErr = fmt.Errorf("dsh plugin --profile %s add (candidate %d of %d): %w: %s",+ dshMulticaProfileName, i+1, len(specs), err, dshProvisionOutput(output))+ }+ logger.Warn("DSH runtime profile install failed",+ "bundle_candidate", i+1, "candidates", len(specs), "error", lastErr)+ }+ return lastErr+}++// startDshProfileProvision kicks off the one-time automatic install of the DSH+// runtime profile. It reports whether this call was the one that started it, so+// the caller can say so in the drop reason.+//+// Once per daemon lifetime, not once per round: the work is a network install+// that mutates the user's DSH home, and a registry or network failure would+// otherwise be retried every discovery interval forever. A restart is the+// retry.+func (d *Daemon) startDshProfileProvision(dshPath string) bool {+ if len(dshProfileBundleSpecs()) == 0 {+ return false+ }+ // The daemon's own context, not the caller's: a probe round is scoped to one+ // round, and an install killed with it would leave the operator with a+ // half-written profile and no explanation.+ ctx := d.daemonLifecycleCtx()+ started := false+ d.dshProvisionOnce.Do(func() {+ started = true+ // Set before the goroutine rather than inside it: the verdict that+ // starts the install is built in the same round, and an offline reason+ // that says "wait" has to be true from the first deregistration.+ d.dshInstallInFlight.Store(true)+ go func() {+ defer d.dshInstallInFlight.Store(false)+ // provisionDshMulticaProfile returns nil only once the profile is+ // actually on disk, so nil here means there is something new to+ // find. The exit status alone would not have meant that.+ err := provisionDshMulticaProfile(ctx, dshPath, d.logger)+ if err == nil {+ d.logger.Info("DSH runtime profile installed; re-probing to bring dsh online")+ // Re-probe now rather than at the next scheduled round. The+ // discovery loop backs off while a provider cannot register, and+ // dsh counts as "missing a runtime" for as long as the profile is+ // absent — so the attempt this replaces can be+ // agentConvergeMaxBackoff away, which is indistinguishable from+ // "it does not work" to anyone watching the runtime list. On a+ // daemon that started with nothing registered this also has to+ // pick the workspace up first; see registerAfterDshProfileInstall.+ d.registerAfterDshProfileInstall(ctx)+ return+ }+ d.logger.Warn("automatic DSH runtime profile install did not produce a profile; dsh stays unregistered until one exists",+ "path", dshPath, "error", err)+ // Withdraw the claim before returning. Any runtime taken offline+ // while this install was running says "installing" on its row, and+ // the server reads that as a wait worth queueing behind. Nothing+ // else will ever rewrite it: the demotion already removed the+ // runtime from the index, so no later round has a runtime to+ // condemn and no later deregistration is sent. Left alone, that row+ // queues work forever behind an install that has already given up.+ d.withdrawDshInstallWait(ctx)+ }()+ })+ return started+}diff --git a/server/internal/daemon/dsh_profile_test.go b/server/internal/daemon/dsh_profile_test.gonew file mode 100644index 0000000000..bbe545f542--- /dev/null+++ b/server/internal/daemon/dsh_profile_test.go@@ -0,0 +1,616 @@+package daemon++import (+ "context"+ "io"+ "log/slog"+ "os"+ "path/filepath"+ "runtime"+ "strconv"+ "strings"+ "syscall"+ "testing"+ "time"+)++// fakeDsh records every invocation and its PATH, then exits per the args it+// was handed. Failing on a spec containing FAILME is how the candidate+// fallback gets exercised.+//+// A successful `add` writes the profile manifest, because that is what the real+// command does and what the caller now judges success by. DSH_HOME is pinned+// first so the manifest lands in the test's own directory and never in the+// developer's ~/.dsh.+func fakeDsh(t *testing.T) (path, record string) {+ t.Helper()+ return fakeDshScript(t, `mkdir -p "$DSH_HOME/profiles/multica" && printf '{}' > "$DSH_HOME/profiles/multica/package.json"`)+}++// fakeDshSilentlySucceeds exits 0 from `add` and writes no profile: a package+// manager reporting success over a run that produced nothing. Whether any real+// bundle behaves this way, the daemon must not disagree with+// dshMulticaProfilePresent about whether a profile exists, because that is the+// fact every other part of it reads.+func fakeDshSilentlySucceeds(t *testing.T) (path, record string) {+ t.Helper()+ return fakeDshScript(t, ":")+}++func fakeDshScript(t *testing.T, onSuccess string) (path, record string) {+ t.Helper()+ pinnedDshHome(t)+ dir := t.TempDir()+ path = filepath.Join(dir, "dsh")+ record = filepath.Join(dir, "calls.log")+ script := "#!/bin/sh\n" ++ `printf 'args=%s\n' "$*" >> "$DSH_TEST_RECORD"` + "\n" ++ `printf 'path=%s\n' "$PATH" >> "$DSH_TEST_RECORD"` + "\n" ++ "case \"$*\" in\n" ++ " *FAILME*) printf '%s\\n' 'registry unreachable' >&2; exit 1 ;;\n" ++ "esac\n" ++ onSuccess + "\n" ++ "exit 0\n"+ if err := os.WriteFile(path, []byte(script), 0o755); err != nil {+ t.Fatal(err)+ }+ t.Setenv("DSH_TEST_RECORD", record)+ return path, record+}++// pinnedDshHome points DSH_HOME at a directory the test owns and reports it.+//+// Without this, dshMulticaProfilePresent() reads the developer's real ~/.dsh,+// so whether a test passes depends on whether the machine running it happens to+// have a `multica` profile installed. That is the ambient-agent-state+// dependency the repo forbids, and it hid here until the install path started+// checking the profile rather than only the exit status.+func pinnedDshHome(t *testing.T) string {+ t.Helper()+ home := t.TempDir()+ t.Setenv("DSH_HOME", home)+ return home+}++// installMulticaProfile creates the manifest dshMulticaProfilePresent looks for.+func installMulticaProfile(t *testing.T, dshHome string) {+ t.Helper()+ dir := filepath.Join(dshHome, "profiles", dshMulticaProfileName)+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(dir, "package.json"), []byte("{}\n"), 0o644); err != nil {+ t.Fatal(err)+ }+}++func readRecord(t *testing.T, record string) string {+ t.Helper()+ data, err := os.ReadFile(record)+ if err != nil {+ if os.IsNotExist(err) {+ return ""+ }+ t.Fatal(err)+ }+ return string(data)+}++// An unconfigured daemon must leave the user's DSH installation alone: the+// reported drop is the whole response.+func TestProvisionDshMulticaProfile_UnconfiguredIsANoOp(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell fixture")+ }+ dshPath, record := fakeDsh(t)+ t.Setenv(dshProfileBundleEnv, "")++ logger := slog.New(slog.NewTextHandler(io.Discard, nil))+ if err := provisionDshMulticaProfile(context.Background(), dshPath, logger); err != nil {+ t.Fatalf("provision returned %v, want nil", err)+ }+ if got := readRecord(t, record); got != "" {+ t.Fatalf("dsh was invoked despite no configured bundle: %q", got)+ }+}++func TestProvisionDshMulticaProfile_InstallsTheFirstWorkingCandidate(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell fixture")+ }+ dshPath, record := fakeDsh(t)+ pluginDir := t.TempDir()+ t.Setenv(dshProfileBundleEnv, " FAILME-package , @multica-ai/dsh-runtime , /tmp/local-bundle ")+ t.Setenv(dshPluginPathEnv, pluginDir)++ logger := slog.New(slog.NewTextHandler(io.Discard, nil))+ if err := provisionDshMulticaProfile(context.Background(), dshPath, logger); err != nil {+ t.Fatalf("provision returned %v, want nil once a later candidate succeeds", err)+ }++ got := readRecord(t, record)+ lines := strings.Split(strings.TrimSpace(got), "\n")+ if len(lines) != 4 {+ t.Fatalf("dsh was invoked %d time(s), want 2 (first candidate fails, second succeeds):\n%s", len(lines)/2, got)+ }+ // Candidates are trimmed and tried in order.+ first := "args=plugin --profile multica add FAILME-package"+ if lines[0] != first {+ t.Errorf("first invocation = %q, want %q", lines[0], first)+ }+ second := "args=plugin --profile multica add @multica-ai/dsh-runtime"+ if lines[2] != second {+ t.Errorf("second invocation = %q, want %q", lines[2], second)+ }+ // The third candidate must not run once one has succeeded.+ if strings.Contains(got, "local-bundle") {+ t.Errorf("a candidate was tried after one succeeded:\n%s", got)+ }+ // DSH Desktop ships pnpm, and the daemon inherits no path to it; without+ // this the install fails with "pnpm not found on PATH".+ for _, line := range []string{lines[1], lines[3]} {+ if !strings.HasPrefix(line, "path="+pluginDir+string(os.PathListSeparator)) {+ t.Errorf("PATH = %q, want %q prepended", line, pluginDir)+ }+ }+}++// The whole point of the knob is to be able to point it at a local build before+// Multica's bridge is published (multica#6936), so a directory spec must reach+// dsh unmodified.+func TestProvisionDshMulticaProfile_ForwardsTheSpecVerbatim(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell fixture")+ }+ dshPath, record := fakeDsh(t)+ t.Setenv(dshProfileBundleEnv, "/Users/someone/builds/dsh-multica-runtime")+ t.Setenv(dshPluginPathEnv, "")++ logger := slog.New(slog.NewTextHandler(io.Discard, nil))+ if err := provisionDshMulticaProfile(context.Background(), dshPath, logger); err != nil {+ t.Fatalf("provision returned %v, want nil", err)+ }+ want := "args=plugin --profile multica add /Users/someone/builds/dsh-multica-runtime"+ if got := readRecord(t, record); !strings.Contains(got, want) {+ t.Fatalf("recorded %q, want it to contain %q", got, want)+ }+}++func TestProvisionDshMulticaProfile_ReportsEveryCandidateFailure(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell fixture")+ }+ dshPath, _ := fakeDsh(t)+ t.Setenv(dshProfileBundleEnv, "FAILME-one,FAILME-two")+ t.Setenv(dshPluginPathEnv, "")++ logger := slog.New(slog.NewTextHandler(io.Discard, nil))+ err := provisionDshMulticaProfile(context.Background(), dshPath, logger)+ if err == nil {+ t.Fatal("provision returned nil, want the last failure")+ }+ // The CLI's own output is the only place "pnpm not found on PATH" and+ // registry errors surface, so it has to ride along — and the candidate is+ // named by position, because the spec itself can be an npm URL with+ // credentials in its userinfo or a path carrying a username.+ if !strings.Contains(err.Error(), "candidate 2 of 2") || !strings.Contains(err.Error(), "registry unreachable") {+ t.Fatalf("error = %q, want the failing candidate position and dsh's output", err)+ }+ if strings.Contains(err.Error(), "FAILME-two") {+ t.Fatalf("the bundle spec leaked into the error: %q", err)+ }+}++// The package manager's exit status is not the fact that matters. A candidate+// that returns 0 and writes no profile leaves the operator exactly where a+// failure does, so it must not end the loop, must not be logged as an install,+// and must let the next candidate try.+func TestProvisionDshMulticaProfile_ExitZeroWithoutAProfileIsAFailedCandidate(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell fixture")+ }+ dshPath, record := fakeDshSilentlySucceeds(t)+ t.Setenv(dshProfileBundleEnv, "quiet-one,quiet-two")+ t.Setenv(dshPluginPathEnv, "")++ logger := slog.New(slog.NewTextHandler(io.Discard, nil))+ err := provisionDshMulticaProfile(context.Background(), dshPath, logger)+ if err == nil {+ t.Fatal("provision returned nil while the profile is still absent")+ }+ if !strings.Contains(err.Error(), "without creating the profile") {+ t.Errorf("error = %q, want it to name the empty success", err)+ }+ // Both candidates get a turn: the first one's exit status bought it nothing.+ got := readRecord(t, record)+ for _, want := range []string{"add quiet-one", "add quiet-two"} {+ if !strings.Contains(got, want) {+ t.Errorf("candidate %q was never tried:\n%s", want, got)+ }+ }+}++// Once per daemon, not once per discovery round: this is a network install that+// writes into the user's DSH home, and the caller uses the return value to tell+// the user which of the two situations they are in.+func TestStartDshProfileProvision_RunsAtMostOnce(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell fixture")+ }+ dshPath, record := fakeDsh(t)+ t.Setenv(dshProfileBundleEnv, "@multica-ai/dsh-runtime")+ t.Setenv(dshPluginPathEnv, "")++ // A tracked workspace keeps the finished install on the cheap kick path;+ // the zero-workspace bootstrap it would otherwise take runs a full+ // workspace sync and has its own test.+ d := &Daemon{+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ workspaces: map[string]*workspaceState{"ws-1": {}},+ }+ if !d.startDshProfileProvision(dshPath) {+ t.Fatal("first call did not start the install")+ }+ if d.startDshProfileProvision(dshPath) {+ t.Fatal("second call started another install; the guard is per-round instead of per-daemon")+ }++ deadline := time.Now().Add(10 * time.Second)+ for time.Now().Before(deadline) {+ if strings.Contains(readRecord(t, record), "plugin --profile multica add") {+ return+ }+ time.Sleep(20 * time.Millisecond)+ }+ t.Fatalf("the install never ran; recorded %q", readRecord(t, record))+}++func TestStartDshProfileProvision_UnconfiguredNeverStarts(t *testing.T) {+ t.Setenv(dshProfileBundleEnv, "")+ d := &Daemon{logger: slog.New(slog.NewTextHandler(io.Discard, nil))}+ if d.startDshProfileProvision("/nonexistent/dsh") {+ t.Fatal("provision started with no configured bundle, which would mutate the user's DSH install unasked")+ }+}++// A finished install has to ask for an immediate round. The discovery loop+// backs off while a provider cannot register, and dsh counts as "missing a+// runtime" for as long as the profile is absent — so the scheduled attempt this+// replaces can be agentConvergeMaxBackoff (30m) away, which reads as "the+// install did nothing" to anyone watching the runtime list.+//+// What counts as "finished" is the profile on disk, not the exit status: the+// fixture writes the manifest, because an install that returns 0 without+// producing one leaves the operator exactly where a failure does.+func TestStartDshProfileProvision_KicksDiscoveryWhenTheInstallFinishes(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell fixture")+ }+ dshPath, _ := fakeDsh(t)+ t.Setenv(dshProfileBundleEnv, "@multica-ai/dsh-runtime")+ t.Setenv(dshPluginPathEnv, "")++ d := &Daemon{+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ agentDiscoveryKick: make(chan struct{}, 1),+ // A tracked workspace, so the finished install takes the cheap kick+ // rather than the workspace-sync path a zero-workspace bootstrap needs+ // (registerAfterDshProfileInstall). That path has its own test.+ workspaces: map[string]*workspaceState{"ws-1": {}},+ }+ if !d.startDshProfileProvision(dshPath) {+ t.Fatal("the install did not start")+ }+ select {+ case <-d.agentDiscoveryKick:+ case <-time.After(10 * time.Second):+ t.Fatal("the finished install never asked for a discovery round")+ }+}++// The mirror image, and the reason the check is the manifest rather than the+// exit status: an install that reports success but writes no profile must not+// buy a discovery round — the round would re-probe, find the profile still+// missing, and drop dsh again — and it must withdraw the "installing" claim it+// left on any runtime it took offline (MUL-6164).+func TestStartDshProfileProvision_SuccessWithoutAProfileWithdrawsTheWait(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell fixture")+ }+ dshPath, _ := fakeDshSilentlySucceeds(t)+ t.Setenv(dshProfileBundleEnv, "@multica-ai/dsh-runtime")+ t.Setenv(dshPluginPathEnv, "")++ rec, client := newDeregisterRecorder(t)+ d := &Daemon{+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ client: client,+ workspaces: map[string]*workspaceState{"ws-1": {}},+ runtimeIndex: map[string]Runtime{},+ agentDiscoveryKick: make(chan struct{}, 1),+ }+ d.dshInstallWaits = []dshInstallWait{{+ workspaceID: "ws-1",+ runtimeID: "rt-dsh",+ reason: RuntimeOfflineReason{+ Code: RuntimeOfflineCodeDshProfile,+ Detail: dshProfileInstallStartedReason,+ Installing: true,+ },+ }}++ if !d.startDshProfileProvision(dshPath) {+ t.Fatal("the install did not start")+ }++ deadline := time.After(10 * time.Second)+ for {+ if _, ok := rec.reasonFor("rt-dsh"); ok {+ break+ }+ select {+ case <-deadline:+ t.Fatal("the wait was never withdrawn; the runtime queues work behind an install that gave up")+ case <-time.After(20 * time.Millisecond):+ }+ }+ got, _ := rec.reasonFor("rt-dsh")+ if got.Installing {+ t.Error("the corrected reason still claims an install is running")+ }+ select {+ case <-d.agentDiscoveryKick:+ t.Error("an install that produced no profile asked for a discovery round anyway")+ default:+ }+}++// A producer must never wait on the discovery loop, and a burst has to collapse+// into one round rather than a queue of them.+func TestKickAgentDiscovery_NonBlockingAndCollapsing(t *testing.T) {+ d := &Daemon{agentDiscoveryKick: make(chan struct{}, 1)}+ done := make(chan struct{})+ go func() {+ defer close(done)+ for i := 0; i < 10; i++ {+ d.kickAgentDiscovery()+ }+ }()+ select {+ case <-done:+ case <-time.After(5 * time.Second):+ t.Fatal("kickAgentDiscovery blocked; the producer must not wait on the loop")+ }+ if got := len(d.agentDiscoveryKick); got != 1 {+ t.Fatalf("queued kicks = %d, want 1", got)+ }+ // A zero-value Daemon (tests build one directly) has no channel and must+ // not panic or block.+ (&Daemon{}).kickAgentDiscovery()+}++// The stat is what the discovery loop polls every tick to decide whether to+// force a round, so it has to mean exactly what DSH means by "this profile is+// installed" — a directory alone is not one.+func TestDshMulticaProfilePresent(t *testing.T) {+ home := t.TempDir()+ t.Setenv("DSH_HOME", home)++ if dshMulticaProfilePresent() {+ t.Fatal("profile reported installed before it exists")+ }+ dir := filepath.Join(home, "profiles", dshMulticaProfileName)+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ // DSH's loadProfile falls back to a built-in template (or fails, for a+ // profile that has none) when the manifest is missing, so a bare directory+ // is not an installed profile.+ if dshMulticaProfilePresent() {+ t.Fatal("a directory without a manifest was reported as an installed profile")+ }+ if err := os.WriteFile(filepath.Join(dir, "package.json"), []byte("{}\n"), 0o644); err != nil {+ t.Fatal(err)+ }+ if !dshMulticaProfilePresent() {+ t.Fatal("manifest present but the profile was reported missing")+ }+ if err := os.RemoveAll(dir); err != nil {+ t.Fatal(err)+ }+ if dshMulticaProfilePresent() {+ t.Fatal("removing the profile was not observed; the loop would never force a demotion round")+ }+}++// Windows spells the variable `Path`, and Go de-duplicates the child+// environment case-insensitively: a merge that only matched `PATH=` would leave+// two entries, keep the appended one, and hand the package manager a PATH of+// nothing but the plugin directory.+func TestMergeDshPluginPath(t *testing.T) {+ dirs := []string{"/plugin/dir"}+ sep := string(os.PathListSeparator)++ for _, key := range []string{"PATH", "Path", "path"} {+ t.Run(key, func(t *testing.T) {+ env := mergeDshPluginPath([]string{key + "=/system/bin"}, dirs)+ if len(env) != 1 {+ t.Fatalf("env = %q, want the existing entry merged in place rather than a second one", env)+ }+ want := key + "=" + "/plugin/dir" + sep + "/system/bin"+ if env[0] != want {+ t.Fatalf("env[0] = %q, want %q (spelling preserved, system path kept)", env[0], want)+ }+ })+ }++ t.Run("no path entry at all", func(t *testing.T) {+ env := mergeDshPluginPath([]string{"HOME=/home/x"}, dirs)+ if len(env) != 2 || env[1] != "PATH=/plugin/dir" {+ t.Fatalf("env = %q, want an appended PATH", env)+ }+ })++ t.Run("nothing to prepend leaves the env alone", func(t *testing.T) {+ env := mergeDshPluginPath([]string{"PATH=/system/bin"}, nil)+ if len(env) != 1 || env[0] != "PATH=/system/bin" {+ t.Fatalf("env = %q, want it untouched", env)+ }+ })+}++// The argv and the environment the install runs under are the contract with the+// package manager, so they are assertable without one — which is also the only+// coverage Windows can get, since the shell fixtures cannot stand in for pnpm.+func TestDshProvisionCommand(t *testing.T) {+ pluginDir := t.TempDir()+ t.Setenv(dshPluginPathEnv, pluginDir)++ cmd := dshProvisionCommand("/usr/local/bin/dsh", "@multica-ai/dsh-runtime")+ want := []string{"/usr/local/bin/dsh", "plugin", "--profile", "multica", "add", "@multica-ai/dsh-runtime"}+ if strings.Join(cmd.Args, "\x00") != strings.Join(want, "\x00") {+ t.Fatalf("argv = %q, want %q", cmd.Args, want)+ }+ if cmd.Env == nil {+ t.Fatal("Env is nil: the install would inherit nothing, not even the plugin directory")+ }+}++func TestDshProvisionOutput(t *testing.T) {+ t.Run("bounded from the tail", func(t *testing.T) {+ long := strings.Repeat("x", dshProvisionOutputBytes*2) + "THE-END"+ got := dshProvisionOutput([]byte(long))+ if len(got) > dshProvisionOutputBytes+len("…") {+ t.Fatalf("len = %d, want at most %d", len(got), dshProvisionOutputBytes+1)+ }+ if !strings.HasSuffix(got, "THE-END") || !strings.HasPrefix(got, "…") {+ t.Fatalf("got %q, want a truncated tail", got[:min(40, len(got))])+ }+ })++ // Both shapes a package manager leaks a credential in: the .npmrc-style+ // token line, which the shared redactor knows, and the request URL itself —+ // which is the one the bundle spec turns into when it is an authenticated+ // npm URL, and which is scrubbed here rather than in pkg/redact, because a+ // rule added there changes output for every provider.+ t.Run("redacts credentials a registry echoed back", func(t *testing.T) {+ for _, tc := range []struct{ raw, secret string }{+ {"npm ERR! 401 //registry.example/:_authToken=supersecret123", "supersecret123"},+ {"npm ERR! 404 https://deploy:[email protected]/@acme/dsh-runtime", "hunter2"},+ {"ERR_PNPM_FETCH_401 GET http://ci-bot:[email protected]/@corp%2fdsh", "s3cr3t"},+ } {+ got := dshProvisionOutput([]byte(tc.raw))+ if strings.Contains(got, tc.secret) {+ t.Errorf("output = %q, want %q redacted", got, tc.secret)+ }+ }+ })++ // The host has to survive: which registry refused the request is what an+ // operator reads, and it is not the secret.+ t.Run("keeps the host", func(t *testing.T) {+ got := dshProvisionOutput([]byte("npm ERR! 404 https://deploy:[email protected]/pkg"))+ if !strings.Contains(got, "registry.example.com") {+ t.Errorf("output = %q, want the host kept", got)+ }+ })++ // Userinfo needs both a colon and an @ before the next path separator. A+ // port, an scp-style git remote and a bare timestamp must not trip it.+ t.Run("leaves ordinary URLs intact", func(t *testing.T) {+ for _, raw := range []string{+ "GET https://registry.example.com:8443/@acme/pkg failed",+ "cloning ssh://[email protected]/multica-ai/multica.git",+ "see https://example.com/a:b for details",+ } {+ if got := dshProvisionOutput([]byte(raw)); got != raw {+ t.Errorf("dshProvisionOutput(%q) = %q, want it unchanged", raw, got)+ }+ }+ })+}++// processAlive reports whether a pid still refers to a running process.+func processAlive(pid int) bool {+ proc, err := os.FindProcess(pid)+ if err != nil {+ return false+ }+ return proc.Signal(syscall.Signal(0)) == nil+}++// Cancelling the daemon must stop the install's whole process tree. `dsh plugin`+// forwards to pnpm, which spawns node, which runs the bundle's install script —+// and the direct child is only the first of those. Killing just it leaves the+// rest running, still able to write into the operator's DSH home after the+// daemon is gone, and a daemon rollback cannot undo a write that already landed.+//+// The fixture hands the grandchild's pid back before the parent settles into its+// own wait, so the assertion is about survival rather than about a race: an+// unsynchronized grandchild can be killed before it publishes anything, which+// would let this pass without testing anything.+func TestProvisionDshMulticaProfile_CancellationKillsTheWholeTree(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell fixture; the tree is a Job Object there")+ }+ dir := t.TempDir()+ record := filepath.Join(dir, "late-write.log")+ pidFile := filepath.Join(dir, "grandchild.pid")+ dshPath := filepath.Join(dir, "dsh")+ // The grandchild publishes its pid, then writes the record well after the+ // cancellation below — so the file is evidence of a survivor, and the pid is+ // evidence of one that never needed to write at all.+ script := "#!/bin/sh\n" ++ "sh -c 'printf %s $$ > " + pidFile + "; sleep 2; printf late >> " + record + "' >/dev/null 2>&1 &\n" ++ "while [ ! -s " + pidFile + " ]; do sleep 0.05; done\n" ++ "exec sleep 30\n"+ if err := os.WriteFile(dshPath, []byte(script), 0o755); err != nil {+ t.Fatal(err)+ }+ t.Setenv(dshProfileBundleEnv, "@multica-ai/dsh-runtime")++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ provisionDone := make(chan error, 1)+ go func() {+ provisionDone <- provisionDshMulticaProfile(ctx, dshPath,+ slog.New(slog.NewTextHandler(io.Discard, nil)))+ }()++ deadline := time.Now().Add(10 * time.Second)+ var pid int+ for time.Now().Before(deadline) {+ if raw, err := os.ReadFile(pidFile); err == nil {+ if parsed, convErr := strconv.Atoi(strings.TrimSpace(string(raw))); convErr == nil && parsed > 0 {+ pid = parsed+ break+ }+ }+ time.Sleep(20 * time.Millisecond)+ }+ if pid == 0 {+ t.Fatal("the fixture never published its grandchild pid; the test cannot judge survival")+ }+ if !processAlive(pid) {+ t.Fatalf("grandchild %d was already gone before cancellation", pid)+ }++ cancel()+ if err := <-provisionDone; err == nil {+ t.Fatal("provision returned nil after cancellation")+ }++ // Bounded: processtree interrupts, then stops the tree, then waits for it.+ for i := 0; i < 40 && processAlive(pid); i++ {+ time.Sleep(50 * time.Millisecond)+ }+ if processAlive(pid) {+ if proc, err := os.FindProcess(pid); err == nil {+ _ = proc.Kill()+ }+ t.Fatalf("grandchild %d survived cancellation; it could still write to the DSH home", pid)+ }+ if data, err := os.ReadFile(record); err == nil {+ t.Fatalf("a grandchild outlived cancellation and wrote: %s", data)+ }+}diff --git a/server/internal/daemon/dsh_startup_bootstrap_test.go b/server/internal/daemon/dsh_startup_bootstrap_test.gonew file mode 100644index 0000000000..8b13d9ccf6--- /dev/null+++ b/server/internal/daemon/dsh_startup_bootstrap_test.go@@ -0,0 +1,135 @@+package daemon++import (+ "context"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "testing"+ "time"+)++// A host whose only provider is a dsh without the Multica runtime profile is+// the exact host the automatic install exists for, and it is the one host on+// which the install could never once finish.+//+// The sequence, from a real Windows daemon.log, is 32 milliseconds long: the+// probe reports the missing profile and starts the install, registration finds+// nothing to register, Run returns that error, and the process exits — killing+// the install's process tree with it. Every restart repeats it. Allowing+// startup to continue while that install is in flight is what breaks the loop.+func TestStartupMayProceedWithoutRuntimes(t *testing.T) {+ registerFailure := fmt.Errorf("%w for any of the %d workspace(s)", errNoWorkspaceRuntimesRegistered, 1)++ t.Run("an in-flight install earns the exception", func(t *testing.T) {+ d := &Daemon{}+ d.dshInstallInFlight.Store(true)+ if !d.startupMayProceedWithoutRuntimes(registerFailure) {+ t.Fatal("startup refused to continue while the install that would fix it is running")+ }+ })++ t.Run("nothing else does", func(t *testing.T) {+ d := &Daemon{}+ // The same failure with no install running: a genuinely empty machine+ // still fails fast, which is the documented contract.+ if d.startupMayProceedWithoutRuntimes(registerFailure) {+ t.Error("a machine with nothing installed was allowed to start")+ }++ // An install in flight does not forgive unrelated failures. A rejected+ // token or an unreachable server must still stop startup, or the+ // daemon idles forever on a problem it cannot solve.+ d.dshInstallInFlight.Store(true)+ for name, err := range map[string]error{+ "auth": errors.New("list workspaces: 401 unauthorized"),+ "network": errors.New("list workspaces: connection refused"),+ "none": nil,+ } {+ if d.startupMayProceedWithoutRuntimes(err) {+ t.Errorf("%s failure was treated as the install bootstrap", name)+ }+ }+ })+}++// The other half of the bootstrap. A daemon that started with nothing+// registered tracks no workspace, and every converge path iterates the+// workspaces it tracks — so the kick that normally brings a finished install+// online would have nothing to look at, and the runtime would wait for the+// periodic consistency sync instead.+func TestRegisterAfterDshProfileInstall_PicksUpTheWorkspaceWhenNoneIsTracked(t *testing.T) {+ fx := newBatchFixture(t)+ d := fx.daemon+ // Any provider will do: what is under test is that the workspace gets+ // picked up at all. Not dsh, deliberately — the dsh path would re-run the+ // profile probe against a fake binary and drop it again, which would make+ // this assert nothing.+ d.cfg.Agents = map[string]AgentEntry{"claude": {Path: "/fake/claude"}}+ fx.setWorkspaces(WorkspaceInfo{ID: "ws-1", Name: "one"})++ if got := d.trackedWorkspaceCount(); got != 0 {+ t.Fatalf("precondition: tracked workspaces = %d, want 0", got)+ }++ d.registerAfterDshProfileInstall(context.Background())++ if got := d.trackedWorkspaceCount(); got == 0 {+ t.Fatal("the workspace was never picked up; the runtime would wait for the periodic sync")+ }+}++// With a workspace already tracked there is something for a converge round to+// look at, so the cheap kick is enough and the install must not spend a+// workspace sync on it.+func TestRegisterAfterDshProfileInstall_KicksWhenAWorkspaceIsTracked(t *testing.T) {+ d := &Daemon{+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ workspaces: map[string]*workspaceState{"ws-1": {}},+ agentDiscoveryKick: make(chan struct{}, 1),+ // client stays nil: reaching the sync path would panic, which is the+ // assertion — this branch must not take it.+ }++ d.registerAfterDshProfileInstall(context.Background())++ select {+ case <-d.agentDiscoveryKick:+ case <-time.After(time.Second):+ t.Fatal("no discovery round was requested after the install finished")+ }+}++// A converge round may condemn dsh and nothing else.+//+// On main only refreshAgentVersions acts on demotable verdicts, on its own+// ten-minute cadence, and that is the schedule every provider's verdict was+// tuned against. dsh needs a round it can be forced into, because its+// precondition — the runtime profile — can change without any version changing;+// letting that round condemn Claude Code or Codex too would move them onto a+// different schedule as a side effect of a DSH fix.+func TestDshOnlyVerdicts(t *testing.T) {+ demotable := map[string]runtimeVerdict{+ "claude": {reason: "version too old"},+ "codex": {reason: "agent CLI is not executable"},+ "dsh": {reason: dshMissingProfileReason},+ }++ got := dshOnlyVerdicts(demotable)+ if len(got) != 1 {+ t.Fatalf("verdicts = %v, want only dsh", got)+ }+ if got["dsh"].reason != dshMissingProfileReason {+ t.Errorf("dsh verdict = %q, want it carried through unchanged", got["dsh"].reason)+ }++ // Nothing to do is nil, so the caller's length check reads the same either+ // way.+ if got := dshOnlyVerdicts(map[string]runtimeVerdict{"claude": {reason: "x"}}); got != nil {+ t.Errorf("verdicts = %v, want nil when dsh is not condemned", got)+ }+ if got := dshOnlyVerdicts(nil); got != nil {+ t.Errorf("verdicts = %v, want nil for an empty round", got)+ }+}diff --git a/server/internal/daemon/runtime_not_executable_test.go b/server/internal/daemon/runtime_not_executable_test.goindex a2d1871440..c769a60ce2 100644--- a/server/internal/daemon/runtime_not_executable_test.go+++ b/server/internal/daemon/runtime_not_executable_test.go@@ -34,9 +34,9 @@ func stubNotExecutableProbe(t *testing.T, path string) {// counts as confirmation immediately. Two rounds are still required.func stubConfirmWindow(t *testing.T, window time.Duration) {t.Helper()- orig := notExecutableConfirmWindow- t.Cleanup(func() { notExecutableConfirmWindow = orig })- notExecutableConfirmWindow = window+ orig := condemnedConfirmWindow+ t.Cleanup(func() { condemnedConfirmWindow = orig })+ condemnedConfirmWindow = window}// npmPackagedCLI stages the layout an npm-installed agent CLI has — a bin entry@@ -132,18 +132,18 @@ func TestConfirmNotExecutable_WindowStartsAtFirstSighting(t *testing.T) {d := freshDaemon("")start := time.Now()- if d.confirmNotExecutable("claude", start) {+ if d.confirmCondemned(builtinProbeNotExecutable, "claude", start) {t.Fatal("first sighting confirmed the verdict on its own")}- if d.confirmNotExecutable("claude", start.Add(59*time.Second)) {+ if d.confirmCondemned(builtinProbeNotExecutable, "claude", start.Add(59*time.Second)) {t.Error("confirmed before the window elapsed")}- if !d.confirmNotExecutable("claude", start.Add(time.Minute)) {+ if !d.confirmCondemned(builtinProbeNotExecutable, "claude", start.Add(time.Minute)) {t.Error("did not confirm after the window elapsed")}- d.clearNotExecutable("claude")- if d.confirmNotExecutable("claude", start.Add(time.Hour)) {+ d.clearCondemned("claude")+ if d.confirmCondemned(builtinProbeNotExecutable, "claude", start.Add(time.Hour)) {t.Error("a recovered provider must start a fresh window, not inherit the old one")}}diff --git a/server/internal/dispatch/reason.go b/server/internal/dispatch/reason.goindex db5bc191f8..aa4dd4d447 100644--- a/server/internal/dispatch/reason.go+++ b/server/internal/dispatch/reason.go@@ -39,6 +39,16 @@ const (// machine is already on, and the fix is a command the user runs on it, which// the daemon reports with this verdict so clients can show it.ReasonRuntimeUnusable ReasonCode = "runtime_unusable"+ // ReasonRuntimeProfileMissing: the target is bound to a reachable runtime+ // whose agent CLI runs fine, but a runtime profile that CLI needs in order+ // to speak Multica's protocol is not installed on that machine — DeepSeek+ // Harness, whose `multica` profile supplies the `--stdio` protocol, is the+ // case in the field. Blocked for the same reason as runtime_unusable+ // (MUL-6164): the machine is already on and waiting changes nothing. Kept+ // APART from runtime_unusable because the repair is different in kind — the+ // CLI is not broken and reinstalling it fixes nothing, so copy that says+ // "reinstall the CLI" sends the user to the wrong place entirely.+ ReasonRuntimeProfileMissing ReasonCode = "runtime_profile_missing"// ReasonAgentRuntimeRequired: the target is permitted but bound to no// runtime at all (agent.runtime_id IS NULL), which is where an agent lands// when its runtime is deleted (MUL-5559). Distinct from runtime_offline ondiff --git a/server/internal/handler/admission.go b/server/internal/handler/admission.goindex 3887df7460..b1f17e645a 100644--- a/server/internal/handler/admission.go+++ b/server/internal/handler/admission.go@@ -57,6 +57,7 @@ const (ReasonTargetUnavailable = dispatch.ReasonTargetUnavailableReasonRuntimeOffline = dispatch.ReasonRuntimeOfflineReasonRuntimeUnusable = dispatch.ReasonRuntimeUnusable+ ReasonRuntimeProfileMissing = dispatch.ReasonRuntimeProfileMissingReasonAgentRuntimeRequired = dispatch.ReasonAgentRuntimeRequiredReasonAttributionBlocked = dispatch.ReasonAttributionBlockedReasonAlreadyActive = dispatch.ReasonAlreadyActive@@ -119,6 +120,8 @@ func dispatchBlockedFallbackMessage(code DispatchReasonCode) string {return "the target's runtime is offline"case ReasonRuntimeUnusable:return "the target's agent CLI cannot run on its machine"+ case ReasonRuntimeProfileMissing:+ return "the target's agent CLI is missing a runtime profile on its machine"case ReasonAgentRuntimeRequired:return "the target needs a runtime"case ReasonAttributionBlocked:diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex ab54255c12..9dfb03ee55 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -3047,7 +3047,7 @@ func (h *Handler) resolveMentionedAgentCommentTriggers(ctx context.Context, issu// mention has nobody watching a response at all.blockUnusableTarget := func(targetType, targetID string, agent db.Agent, verdict service.AgentVerdict) {notice := &blockedRuntimeNotice{agent: agent, verdict: verdict}- if verdict.Reason != ReasonRuntimeUnusable {+ if !service.RuntimeBlockedNeedsNotice(verdict.Reason) {notice = nil}addTarget(commentMentionTarget{diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 07384cc9db..34ee6177d6 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -3959,7 +3959,7 @@ func (h *Handler) isAgentAssigneeReady(ctx context.Context, issue db.Issue) bool// refusal that needs human repair leaves the explanation on the issue// (MUL-6164). An unbound agent keeps its silent skip: the agent list// already shows it has no runtime, and nothing about it is new here.- if verdict.Reason == ReasonRuntimeUnusable {+ if service.RuntimeBlockedNeedsNotice(verdict.Reason) {h.noteRuntimeUnusable(ctx, issue, agent, verdict)}return falsediff --git a/server/internal/service/agent_ready.go b/server/internal/service/agent_ready.goindex a7c6060637..975ca45f33 100644--- a/server/internal/service/agent_ready.go+++ b/server/internal/service/agent_ready.go@@ -4,6 +4,7 @@ import ("context""encoding/json""fmt"+ "time""github.com/multica-ai/multica/server/internal/dispatch"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -72,6 +73,9 @@ type runtimeOfflineReason struct {Code string `json:"code"`Detail string `json:"detail"`Repair *RuntimeRepair `json:"repair"`+ // Installing: the daemon has an automatic install in flight, so this offline+ // runtime is expected to come back on its own and work may queue.+ Installing bool `json:"installing"`}// runtimeOfflineCodeNotExecutable is the daemon's code for "the OS refuses to@@ -79,6 +83,28 @@ type runtimeOfflineReason struct {// a string because the server must not import the daemon package.const runtimeOfflineCodeNotExecutable = "not_executable"+// runtimeOfflineCodeDshProfile is the daemon's code for "this runtime's DSH+// runtime profile is not installed" (daemon.RuntimeOfflineCodeDshProfile). Same+// string-comparison rule as above, and the same MUL-6164 semantics: with no+// install configured the wait never resolves, so the trigger is refused.+// runtimeOfflineReason.Installing is the exception — a daemon that is installing+// the profile right now resolves it by itself.+const runtimeOfflineCodeDshProfile = "dsh_profile"++// RuntimeBlockedNeedsNotice reports whether a blocked verdict's reason is one a+// human has to repair on the runtime's machine, and therefore one that must+// leave a durable explanation on the issue (MUL-6164).+//+// A predicate rather than an inline comparison because three admission paths+// ask it — the refused @mention, the refused assignment, and the refused+// assign-on-create — and a code added to one of them but not the others is a+// trigger that vanishes with no trace on exactly the surfaces that have no+// response for the user to read.+func RuntimeBlockedNeedsNotice(code dispatch.ReasonCode) bool {+ return code == dispatch.ReasonRuntimeUnusable ||+ code == dispatch.ReasonRuntimeProfileMissing+}+// AgentReadiness reports whether an agent can accept new work right now, and// what the caller should do when it cannot.//@@ -132,12 +158,28 @@ func runtimeVerdict(rt db.AgentRuntime) AgentVerdict {}// Offline with a reason the daemon says a human must repair: refuse rather// than queue, and carry the repair so the caller can show it.- if reason, ok := parseRuntimeOfflineReason(rt.Metadata); ok && reason.Code == runtimeOfflineCodeNotExecutable {- return AgentVerdict{- Availability: AgentBlocked,- Reason: dispatch.ReasonRuntimeUnusable,- Repair: reason.Repair,- Detail: reason.Detail,+ if reason, ok := parseRuntimeOfflineReason(rt.Metadata); ok {+ switch {+ case reason.Code == runtimeOfflineCodeNotExecutable:+ return AgentVerdict{+ Availability: AgentBlocked,+ Reason: dispatch.ReasonRuntimeUnusable,+ Repair: reason.Repair,+ Detail: reason.Detail,+ }+ // A missing runtime profile is the same shape of finding — the machine+ // is reachable and its CLI cannot serve work — but its own reason code,+ // because the CLI is not the broken part and "reinstall the CLI" copy+ // would send the user to the wrong repair. The one exception is an+ // install the daemon is running right now: that wait DOES end by+ // itself, so the work queues instead of being refused.+ case reason.Code == runtimeOfflineCodeDshProfile && !installClaimHolds(reason, rt):+ return AgentVerdict{+ Availability: AgentBlocked,+ Reason: dispatch.ReasonRuntimeProfileMissing,+ Repair: reason.Repair,+ Detail: reason.Detail,+ }}}return AgentVerdict{@@ -147,6 +189,39 @@ func runtimeVerdict(rt db.AgentRuntime) AgentVerdict {}}+// runtimeInstallClaimWindow is how long an `installing` claim on a runtime row+// is honoured before the row is read as a plain missing profile.+//+// The claim is what makes this one offline runtime worth queueing behind, so a+// claim that outlives its install recreates exactly the failure the structured+// reason exists to prevent — work queued behind something that stopped. The+// daemon withdraws the claim when an install gives up, but a withdraw cannot be+// guaranteed: the verdict is built before the runtime ids the withdraw needs are+// known, the corrective Deregister is best-effort and runs on an already-+// cancelled context during shutdown, and a daemon restarted mid-install does not+// track the row at all.+//+// So the claim is bounded rather than guaranteed. SetAgentRuntimeOfflineWithReason+// stamps updated_at, and the install it describes is itself bounded by the+// daemon's provisioning timeout; a window comfortably longer than that covers a+// real install while capping every way the claim can be left behind. The+// withdraw stays as the fast path — this is the floor under it.+const runtimeInstallClaimWindow = 5 * time.Minute++// installClaimHolds reports whether a runtime row's in-flight-install claim is+// still worth queueing behind.+//+// A row with no usable timestamp cannot be bounded, so the claim is not honoured:+// the cost of refusing during a real install is one retry the notice already+// asks for, and the cost of honouring a stale claim is work that queues until it+// expires.+func installClaimHolds(reason runtimeOfflineReason, rt db.AgentRuntime) bool {+ if !reason.Installing || !rt.UpdatedAt.Valid {+ return false+ }+ return time.Since(rt.UpdatedAt.Time) < runtimeInstallClaimWindow+}+// parseRuntimeOfflineReason reads the daemon's explanation off a runtime row.// A row with no reason, or metadata this server cannot parse, simply has no// explanation — never a different verdict.@@ -164,7 +239,8 @@ func parseRuntimeOfflineReason(metadata []byte) (runtimeOfflineReason, bool) {}// RuntimeUnusableNotice is the durable explanation left on an issue when a-// trigger is refused because the target's agent CLI cannot run on its machine.+// trigger is refused because the target's runtime cannot serve work and only a+// human on that machine can change it.//// It lives here, next to the verdict, because two layers write it: the handler// for a refused @mention and the service for a refused assignment. One text,@@ -172,11 +248,20 @@ func parseRuntimeOfflineReason(metadata []byte) (runtimeOfflineReason, bool) {// one and stays useful when it did not — a natively installed CLI has no// postinstall to re-run, and inventing a command would send the user somewhere// that does not exist.+//+// The text is chosen by the verdict's reason, not by whether a repair command+// happened to be present. The two causes have opposite repairs: an unrunnable+// CLI is reinstalled, while a CLI missing its runtime profile is working+// perfectly and reinstalling it changes nothing. One text for both told DSH+// users to reinstall a CLI that was never the problem.func RuntimeUnusableNotice(agentName string, verdict AgentVerdict) string {name := agentNameif name == "" {name = "The assigned agent"}+ if verdict.Reason == dispatch.ReasonRuntimeProfileMissing {+ return runtimeProfileMissingNotice(name)+ }if verdict.Repair != nil && verdict.Repair.Command != "" {return fmt.Sprintf("%s could not start: its CLI is installed but cannot be executed on that machine, so this trigger was not queued.\n\n"+@@ -193,6 +278,25 @@ func RuntimeUnusableNotice(agentName string, verdict AgentVerdict) string {)}+// runtimeProfileMissingNotice explains a runtime whose CLI runs but whose+// Multica runtime profile is absent.+//+// No fenced command, deliberately. The install is `dsh plugin --profile multica+// add <bundle>`, and <bundle> is the operator's own choice of package,+// directory or tarball — Multica's bridge is not on a public registry yet+// (multica#6936). Rendering that line in a code block presents a placeholder as+// something to copy and run, which is the shape of instruction people paste+// verbatim and then report as broken. Naming the two ways to supply a real+// bundle, and pointing at the docs that list them, is the honest version.+func runtimeProfileMissingNotice(name string) string {+ return fmt.Sprintf(+ "%s could not start: the DeepSeek Harness CLI is installed on that machine, but the `multica` runtime profile it needs is not, so this trigger was not queued.\n\n"++ "The profile supplies the protocol Multica drives — the CLI itself is fine, and reinstalling it changes nothing. On that machine, either add the Multica DSH runtime bundle to the profile with `dsh plugin --profile multica add`, or set `MULTICA_DSH_PROFILE_BUNDLE` for the daemon so it installs the bundle itself. See the agent runtime install docs for the bundle to use.\n\n"++ "The runtime registers on its own within a couple of minutes after that; trigger the agent again then.",+ name,+ )+}+// repairFenceLanguage labels the code block with the shell the command was// written for. A daemon too old to report one predates the Windows rendering// entirely, so its command is POSIX by construction.diff --git a/server/internal/service/issue.go b/server/internal/service/issue.goindex 06db5dd54e..f31431c049 100644--- a/server/internal/service/issue.go+++ b/server/internal/service/issue.go@@ -11,7 +11,6 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics"- "github.com/multica-ai/multica/server/internal/dispatch""github.com/multica-ai/multica/server/internal/entitlement""github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/issueguard"@@ -735,7 +734,7 @@ func (s *IssueService) maybeEnqueueOnAssign(ctx context.Context, issue db.Issue,return pgtype.UUID{}}verdict, admitted := agentAssigneeVerdict(ctx, s.runtimeLookup(s.Queries), issue)- if !admitted && verdict.Reason == dispatch.ReasonRuntimeUnusable {+ if !admitted && RuntimeBlockedNeedsNotice(verdict.Reason) {// Assignment has no response the assigner reads for this outcome, so the// refusal explains itself on the issue instead of vanishing (MUL-6164).// Only here, not in the create-with-assignee path above: that one runsdiff --git a/server/internal/service/reason_code_test.go b/server/internal/service/reason_code_test.goindex 3abb99258f..f6e1e08ef5 100644--- a/server/internal/service/reason_code_test.go+++ b/server/internal/service/reason_code_test.go@@ -5,6 +5,7 @@ import ("fmt""strings""testing"+ "time""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/dispatch"@@ -74,6 +75,72 @@ func TestAgentReadinessVerdict(t *testing.T) {if unusable.Repair == nil || unusable.Repair.Command != "cd '/pkg' && node install.cjs" {t.Errorf("unusable runtime lost the repair command: got %+v", unusable.Repair)}+ // Offline because the DSH runtime profile is missing is blocked for the same+ // reason — the machine is reachable, its CLI cannot serve work, and no+ // amount of waiting installs a bundle nobody configured — but under its OWN+ // code. Collapsing it into runtime_unusable is what made every client tell+ // the user to reinstall a CLI that runs perfectly.+ profile := runtimeVerdict(db.AgentRuntime{+ Status: "offline",+ Metadata: []byte(`{"offline_reason":{"code":"dsh_profile","detail":"the Multica runtime profile is not installed","repair":{"package":"DeepSeek Harness runtime profile"}}}`),+ })+ if !profile.Blocked() || profile.Reason != dispatch.ReasonRuntimeProfileMissing {+ t.Fatalf("missing DSH profile: got %+v, want blocked/runtime_profile_missing", profile)+ }+ if !RuntimeBlockedNeedsNotice(profile.Reason) {+ t.Error("missing DSH profile would leave no durable trace on the issue")+ }+ // The notice must describe the profile, not a broken CLI, and must not hand+ // the user a command with a placeholder in it to paste.+ notice := RuntimeUnusableNotice("Kit", profile)+ if !strings.Contains(notice, "runtime profile") {+ t.Errorf("notice does not name the missing profile: %q", notice)+ }+ for _, wrong := range []string{"cannot be executed", "postinstall", "<bundle>", "```"} {+ if strings.Contains(notice, wrong) {+ t.Errorf("notice contains %q, which belongs to the unrunnable-CLI repair: %q", wrong, notice)+ }+ }+ // The unrunnable-CLI notice keeps its own text and its fenced command.+ if unusableNotice := RuntimeUnusableNotice("Kit", unusable); !strings.Contains(unusableNotice, "node install.cjs") {+ t.Errorf("unusable-CLI notice lost its repair command: %q", unusableNotice)+ }+ // The installing claim is bounded, not trusted. A withdraw cannot be+ // guaranteed — the verdict is built before the runtime ids it needs are+ // known, the corrective Deregister is best-effort and runs on a cancelled+ // context during shutdown, and a daemon restarted mid-install does not track+ // the row at all — so a claim older than the install it describes must stop+ // buying a queue, or it recreates the failure it was added to prevent.+ installingRow := func(updatedAt time.Time) db.AgentRuntime {+ return db.AgentRuntime{+ Status: "offline",+ Metadata: []byte(`{"offline_reason":{"code":"dsh_profile","installing":true,"detail":"installing the configured bundle now"}}`),+ UpdatedAt: pgtype.Timestamptz{Time: updatedAt, Valid: true},+ }+ }+ // The one exception is an install the daemon is running right now: that wait+ // DOES end by itself, so the work queues instead of being refused.+ fresh := runtimeVerdict(installingRow(time.Now()))+ if fresh.Blocked() {+ t.Errorf("install in flight: got %+v, want the waitable verdict", fresh)+ }+ if fresh.Reason != dispatch.ReasonRuntimeOffline {+ t.Errorf("install in flight: reason = %q, want %q", fresh.Reason, dispatch.ReasonRuntimeOffline)+ }+ stale := runtimeVerdict(installingRow(time.Now().Add(-runtimeInstallClaimWindow - time.Minute)))+ if !stale.Blocked() || stale.Reason != dispatch.ReasonRuntimeProfileMissing {+ t.Fatalf("stale install claim: got %+v, want blocked/runtime_profile_missing", stale)+ }+ // No timestamp to bound it with: refuse rather than queue behind something+ // that cannot be shown to be running.+ unbounded := runtimeVerdict(db.AgentRuntime{+ Status: "offline",+ Metadata: []byte(`{"offline_reason":{"code":"dsh_profile","installing":true}}`),+ })+ if !unbounded.Blocked() {+ t.Errorf("install claim with no updated_at: got %+v, want blocked", unbounded)+ }+// An unrecognised or malformed reason must not invent a verdict: unknown// causes stay in the waitable bucket they are in today.for name, metadata := range map[string]string{diff --git a/server/pkg/agent/dsh.go b/server/pkg/agent/dsh.goindex f6e794c960..459e039a78 100644--- a/server/pkg/agent/dsh.go+++ b/server/pkg/agent/dsh.go@@ -16,8 +16,11 @@ import ()const (- dshProfile = "multica"- dshProtocolVersion = 1+ dshProfile = "multica"+ // DshProtocolVersion is the DSH stdio protocol this backend speaks. Exported+ // because the daemon's profile probe accepts or rejects a runtime profile on+ // this exact number, and a second copy of it there is a copy that can drift.+ DshProtocolVersion = 1dshCancelGrace = 3 * time.SeconddshTerminateGrace = 2 * time.Second)@@ -251,7 +254,7 @@ func (b *dshBackend) Execute(ctx context.Context, prompt string, opts ExecOptionrequestID = "multica-" + strconv.FormatInt(time.Now().UnixNano(), 10)}command := dshExecuteCommand{- Version: dshProtocolVersion, Type: "execute", RequestID: requestID,+ Version: DshProtocolVersion, Type: "execute", RequestID: requestID,Cwd: opts.Cwd, Prompt: prompt, ResumeSessionID: opts.ResumeSessionID,Model: model, ReasoningEffort: opts.ThinkingLevel, MCPServers: mcpServers,}@@ -281,7 +284,7 @@ func (b *dshBackend) Execute(ctx context.Context, prompt string, opts ExecOptionreturncase <-runCtx.Done():}- _ = writeFrame(dshCancelCommand{Version: dshProtocolVersion, Type: "cancel", RequestID: requestID})+ _ = writeFrame(dshCancelCommand{Version: DshProtocolVersion, Type: "cancel", RequestID: requestID})timer := time.NewTimer(dshCancelGrace)defer timer.Stop()select {@@ -371,7 +374,7 @@ type dshRunState struct {}func handleDshFrame(frame dshFrame, requestID string, ch chan<- Message, state *dshRunState) {- if frame.Version != dshProtocolVersion {+ if frame.Version != DshProtocolVersion {state.protocolError = fmt.Sprintf("dsh returned unsupported protocol version %d", frame.Version)return}@@ -449,7 +452,7 @@ func discoverDshModels(ctx context.Context, runtimeCmd Command) ([]Model, error)scanner := newAgentStreamScanner(stdout)for scanner.Scan() {var frame dshFrame- if json.Unmarshal(scanner.Bytes(), &frame) != nil || frame.Version != dshProtocolVersion || frame.Type != "models" {+ if json.Unmarshal(scanner.Bytes(), &frame) != nil || frame.Version != DshProtocolVersion || frame.Type != "models" {continue}for _, item := range frame.Models {