Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9425: bind custom runtimes to the selected machine (#10746)
Multica Eve46a0c508751b
diff --git a/apps/docs/content/docs/cli.fr.mdx b/apps/docs/content/docs/cli.fr.mdxindex 283b7884e9..097edd586e 100644--- a/apps/docs/content/docs/cli.fr.mdx+++ b/apps/docs/content/docs/cli.fr.mdx@@ -298,7 +298,7 @@ multica runtime profile create --display-name "Wrapper Claude interne" \--command-name ccms --runtime-type claude```-`daemon autostart` enregistre le profil courant pour qu'il démarre à l'ouverture de session ; les différences entre plateformes sont décrites dans [Démarrage à l'ouverture de session](/daemon-runtimes#autostart). `runtime usage` couvre 90 jours par défaut, et `--days` va jusqu'à 365. `runtime update` demande au daemon de cette machine de mettre sa CLI à jour vers la version indiquée ; `--wait` attend la fin de la mise à jour et renvoie un code de sortie non nul si elle échoue ou expire, ou si l’attente elle-même expire. `runtime profile create` indique l'outil compatible avec `--runtime-type` (l'ancien `--protocol-family` fonctionne encore) ; les arguments fixes ne se définissent pour l'instant que dans l'application web.+`daemon autostart` enregistre le profil courant pour qu'il démarre à l'ouverture de session ; les différences entre plateformes sont décrites dans [Démarrage à l'ouverture de session](/daemon-runtimes#autostart). `runtime usage` couvre 90 jours par défaut, et `--days` va jusqu'à 365. `runtime update` demande au daemon de cette machine de mettre sa CLI à jour vers la version indiquée ; `--wait` attend la fin de la mise à jour et renvoie un code de sortie non nul si elle échoue ou expire, ou si l’attente elle-même expire. `runtime profile create` indique l'outil compatible avec `--runtime-type` (l'ancien `--protocol-family` fonctionne encore) ; les arguments fixes ne se définissent pour l'instant que dans l'application web. `runtime profile create` lie le profil à cette machine par défaut ; utilisez `--daemon-id <id>` pour choisir une autre machine locale enregistrée. Pour lier un ancien profil, utilisez `multica runtime profile update <profile-id> --daemon-id <id>`.La suppression d'un runtime auquel des agents actifs sont encore liés est refusée par défaut. `multica runtime delete <id> --cascade` dissocie ces agents, préserve leur configuration et leur historique, et annule leurs exécutions actives.diff --git a/apps/docs/content/docs/cli.ja.mdx b/apps/docs/content/docs/cli.ja.mdxindex 394a39ac44..ed6d899375 100644--- a/apps/docs/content/docs/cli.ja.mdx+++ b/apps/docs/content/docs/cli.ja.mdx@@ -298,7 +298,7 @@ multica runtime profile create --display-name "社内 Claude ラッパー" \--command-name ccms --runtime-type claude```-`daemon autostart` は現在のプロファイルをログイン時に起動するよう登録します。プラットフォームごとの違いは[ログイン時の自動起動](/daemon-runtimes#autostart)を参照してください。`runtime usage` は既定で 90 日分を集計し、`--days` は最大 365 です。`runtime update` はそのコンピューターのデーモンに CLI を指定のバージョンへ更新させ、`--wait` を付けると更新の完了を待ちます。更新の失敗、更新のタイムアウト、待機自体のタイムアウトでは、終了コードが非ゼロになります。`runtime profile create` は互換ツールを `--runtime-type` で指定します(古い `--protocol-family` も使えます)。固定引数は今のところ Web アプリでしか設定できません。+`daemon autostart` は現在のプロファイルをログイン時に起動するよう登録します。プラットフォームごとの違いは[ログイン時の自動起動](/daemon-runtimes#autostart)を参照してください。`runtime usage` は既定で 90 日分を集計し、`--days` は最大 365 です。`runtime update` はそのコンピューターのデーモンに CLI を指定のバージョンへ更新させ、`--wait` を付けると更新の完了を待ちます。更新の失敗、更新のタイムアウト、待機自体のタイムアウトでは、終了コードが非ゼロになります。`runtime profile create` は互換ツールを `--runtime-type` で指定します(古い `--protocol-family` も使えます)。固定引数は今のところ Web アプリでしか設定できません。 `runtime profile create` は既定で現在のマシンに紐づけます。別の登録済みローカルマシンを選択するには `--daemon-id <id>` を指定します。 既存の未設定プロファイルは `multica runtime profile update <profile-id> --daemon-id <id>` でマシンに紐づけられます。アクティブなエージェントがまだ紐付いているランタイムの削除は、デフォルトで拒否されます。`multica runtime delete <id> --cascade` は、それらのエージェントをランタイムから解除して設定と履歴を保持し、アクティブな実行をキャンセルします。diff --git a/apps/docs/content/docs/cli.ko.mdx b/apps/docs/content/docs/cli.ko.mdxindex ce401b459c..33c022ced6 100644--- a/apps/docs/content/docs/cli.ko.mdx+++ b/apps/docs/content/docs/cli.ko.mdx@@ -298,7 +298,7 @@ multica runtime profile create --display-name "사내 Claude 래퍼" \--command-name ccms --runtime-type claude```-`daemon autostart`는 현재 profile이 로그인할 때 시작되도록 등록합니다. 플랫폼별 차이는 [로그인 시 자동 시작](/daemon-runtimes#autostart)을 참고하세요. `runtime usage`는 기본적으로 90일을 집계하며 `--days`는 최대 365입니다. `runtime update`는 해당 컴퓨터의 데몬이 CLI를 지정한 버전으로 업데이트하게 하고, `--wait`를 붙이면 업데이트가 끝날 때까지 기다립니다. 업데이트 실패, 업데이트 시간 초과 또는 대기 자체의 시간 초과 시 종료 코드는 0이 아닙니다. `runtime profile create`는 호환 도구를 `--runtime-type`으로 지정합니다(예전 `--protocol-family`도 쓸 수 있음). 고정 인수는 현재 웹 앱에서만 설정할 수 있습니다.+`daemon autostart`는 현재 profile이 로그인할 때 시작되도록 등록합니다. 플랫폼별 차이는 [로그인 시 자동 시작](/daemon-runtimes#autostart)을 참고하세요. `runtime usage`는 기본적으로 90일을 집계하며 `--days`는 최대 365입니다. `runtime update`는 해당 컴퓨터의 데몬이 CLI를 지정한 버전으로 업데이트하게 하고, `--wait`를 붙이면 업데이트가 끝날 때까지 기다립니다. 업데이트 실패, 업데이트 시간 초과 또는 대기 자체의 시간 초과 시 종료 코드는 0이 아닙니다. `runtime profile create`는 호환 도구를 `--runtime-type`으로 지정합니다(예전 `--protocol-family`도 쓸 수 있음). 고정 인수는 현재 웹 앱에서만 설정할 수 있습니다. `runtime profile create`는 기본적으로 현재 컴퓨터에 연결합니다. 다른 등록된 로컬 컴퓨터를 선택하려면 `--daemon-id <id>`를 지정하세요. 기존 설정은 `multica runtime profile update <profile-id> --daemon-id <id>`로 컴퓨터에 연결할 수 있습니다.활성 에이전트가 계속 연결된 런타임을 삭제하면 명령이 기본적으로 거부됩니다. `multica runtime delete <id> --cascade`는 에이전트의 런타임 연결을 해제하고 설정과 기록을 보존하며 활성 실행을 취소합니다.diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdxindex 581fa657b5..951160112e 100644--- a/apps/docs/content/docs/cli.mdx+++ b/apps/docs/content/docs/cli.mdx@@ -313,7 +313,7 @@ multica runtime profile create --display-name "Internal Claude wrapper" \--command-name ccms --runtime-type claude```-`daemon autostart` registers the current profile to start at login; see [Start at login](/daemon-runtimes#autostart) for platform details. `runtime usage` covers 90 days by default, and `--days` goes up to 365. `runtime update` asks the daemon on that computer to update its CLI to the given version; `--wait` waits for completion and exits non-zero if the update fails or times out, or if the wait itself times out. `runtime profile create` takes the compatible tool through `--runtime-type` (the older `--protocol-family` still works); fixed arguments can currently be set only in the web app.+`daemon autostart` registers the current profile to start at login; see [Start at login](/daemon-runtimes#autostart) for platform details. `runtime usage` covers 90 days by default, and `--days` goes up to 365. `runtime update` asks the daemon on that computer to update its CLI to the given version; `--wait` waits for completion and exits non-zero if the update fails or times out, or if the wait itself times out. `runtime profile create` takes the compatible tool through `--runtime-type` (the older `--protocol-family` still works); fixed arguments can currently be set only in the web app. `runtime profile create` binds the profile to this machine by default; use `--daemon-id <id>` to select another registered local machine. Bind an older, unscoped profile with `multica runtime profile update <profile-id> --daemon-id <id>`.Deleting a runtime that still has active agents bound to it is refused by default. `multica runtime delete <id> --cascade` unbinds those agents, preserves their configuration and history, and cancels their active runs.diff --git a/apps/docs/content/docs/cli.zh-Hant.mdx b/apps/docs/content/docs/cli.zh-Hant.mdxindex b76fde504e..5ec180d5e7 100644--- a/apps/docs/content/docs/cli.zh-Hant.mdx+++ b/apps/docs/content/docs/cli.zh-Hant.mdx@@ -295,7 +295,7 @@ multica runtime profile create --display-name "內部 Claude 封裝" \--command-name ccms --runtime-type claude```-`daemon autostart` 為當前 profile 登記開機自啟,平臺差異見[開機自啟](/daemon-runtimes#autostart)。`runtime usage` 預設統計 90 天,`--days` 最多 365。`runtime update` 讓那臺電腦上的守護程序把 CLI 更新到指定版本,`--wait` 等待更新結束;更新失敗、更新逾時或等待本身逾時時,命令會以非零狀態退出。`runtime profile create` 用 `--runtime-type` 指定相容的工具(舊的 `--protocol-family` 仍可用);固定引數目前只能在網頁端填寫。+`daemon autostart` 為當前 profile 登記開機自啟,平臺差異見[開機自啟](/daemon-runtimes#autostart)。`runtime usage` 預設統計 90 天,`--days` 最多 365。`runtime update` 讓那臺電腦上的守護程序把 CLI 更新到指定版本,`--wait` 等待更新結束;更新失敗、更新逾時或等待本身逾時時,命令會以非零狀態退出。`runtime profile create` 用 `--runtime-type` 指定相容的工具(舊的 `--protocol-family` 仍可用);固定引數目前只能在網頁端填寫。 `runtime profile create` 預設綁定目前機器;使用 `--daemon-id <id>` 可以選擇另一臺已登記的本機。 舊配置可以透過 `multica runtime profile update <profile-id> --daemon-id <id>` 綁定機器。刪除仍繫結活躍 AI 代理的執行時時,命令預設拒絕。`multica runtime delete <id> --cascade` 會解綁這些 AI 代理、保留其配置與歷史記錄,並取消它們的活動執行。diff --git a/apps/docs/content/docs/cli.zh.mdx b/apps/docs/content/docs/cli.zh.mdxindex 33e82451e6..50edf9a5fe 100644--- a/apps/docs/content/docs/cli.zh.mdx+++ b/apps/docs/content/docs/cli.zh.mdx@@ -298,7 +298,7 @@ multica runtime profile create --display-name "内部 Claude 封装" \--command-name ccms --runtime-type claude```-`daemon autostart` 为当前 profile 登记开机自启,平台差异见[开机自启](/daemon-runtimes#autostart)。`runtime usage` 默认统计 90 天,`--days` 最多 365。`runtime update` 让那台电脑上的守护进程把 CLI 更新到指定版本,`--wait` 等待更新结束;更新失败、更新超时或等待本身超时时,命令会以非零状态退出。`runtime profile create` 用 `--runtime-type` 指定兼容的工具(旧的 `--protocol-family` 仍可用);固定参数目前只能在网页端填写。+`daemon autostart` 为当前 profile 登记开机自启,平台差异见[开机自启](/daemon-runtimes#autostart)。`runtime usage` 默认统计 90 天,`--days` 最多 365。`runtime update` 让那台电脑上的守护进程把 CLI 更新到指定版本,`--wait` 等待更新结束;更新失败、更新超时或等待本身超时时,命令会以非零状态退出。`runtime profile create` 用 `--runtime-type` 指定兼容的工具(旧的 `--protocol-family` 仍可用);固定参数目前只能在网页端填写。 `runtime profile create` 默认绑定当前机器;使用 `--daemon-id <id>` 可以选择另一台已登记的本地机器。 旧配置可以通过 `multica runtime profile update <profile-id> --daemon-id <id>` 绑定机器。删除仍绑定活跃智能体的运行时时,命令默认拒绝。`multica runtime delete <id> --cascade` 会解绑这些智能体、保留其配置与历史记录,并取消它们的活动运行。diff --git a/apps/docs/content/docs/daemon-runtimes.fr.mdx b/apps/docs/content/docs/daemon-runtimes.fr.mdxindex 2058ab3643..33542cfb2b 100644--- a/apps/docs/content/docs/daemon-runtimes.fr.mdx+++ b/apps/docs/content/docs/daemon-runtimes.fr.mdx@@ -91,7 +91,7 @@ Lorsqu'un runtime est hors ligne :- Les exécutions déjà en file d'attente attendent que le runtime revienne ; elles ne passent pas sur un autre ordinateur. Elles n'échouent qu'une fois que le runtime a cessé d'envoyer des signaux de présence pendant plus longtemps que le délai de grâce de reconnexion **et** que l'exécution elle-même est en file d'attente depuis aussi longtemps. Un runtime simplement occupé conserve sa file, et le travail assigné à un runtime déjà hors ligne bénéficie tout de même d'un délai de grâce complet.- Les exécutions en cours n'échouent pas tout de suite. Elles échouent avec `runtime_offline` seulement lorsque le signal de présence du runtime manque depuis plus longtemps que le délai de grâce de reconnexion (`MULTICA_RUNTIME_RECONNECT_GRACE`, 3 heures par défaut) ; les exécutions de tâche ou de discussion éligibles peuvent être relancées automatiquement.- Au redémarrage, le daemon réenregistre ses runtimes et récupère les exécutions qui ne se sont pas terminées proprement la dernière fois.-- Un runtime hors ligne depuis plus de 7 jours et auquel aucun agent n'est lié (y compris les agents archivés) est supprimé automatiquement.+- Un runtime hors ligne depuis plus de 7 jours, sans agent utilisateur actif ni tâche inachevée, est supprimé automatiquement ; les agents archivés et l’historique des tâches sont conservés. Pour les anciens profils personnalisés sans machine assignée, seules les instances sur les machines du créateur du profil sont conservées jusqu’à ce qu’un administrateur choisisse la machine.Dans la démo ci-dessous, une exécution assignée pendant que l'ordinateur est hors ligne attend dans la file et n'est prise en charge qu'une fois l'ordinateur de nouveau en ligne.@@ -234,7 +234,9 @@ Seuls les propriétaires et administrateurs de l'espace de travail peuvent crée3. Choisissez la famille de protocoles avec laquelle la commande est réellement compatible.4. Renseignez le nom, la commande et les arguments fixes, puis enregistrez.-Le profil est partagé dans tout l'espace de travail. Chaque ordinateur connecté recherche la commande de son côté ; seuls les ordinateurs capables de la résoudre dans le `PATH` enregistrent le runtime correspondant. Créer un profil n'installe pas la commande et ne connecte pas les autres membres à l'outil.+Un nouveau profil appartient uniquement à l’ordinateur sélectionné lors de sa création. Seul son daemon le télécharge et l’enregistre ; les autres ordinateurs ne sont pas concernés, même si la même commande y est installée. Si la commande est introuvable, l’erreur apparaît uniquement sur l’ordinateur sélectionné. La création du profil n’installe pas la commande et ne connecte pas l’outil.++Pour les anciens profils, **Machine (facultatif)** dans **Modifier le runtime personnalisé** est facultatif : laissez **Conserver les machines actuelles** pour modifier uniquement le nom, la commande ou les autres paramètres. Sélectionner une machine supprime les copies inutilisées sur les autres machines ; les agents actifs ou les tâches inachevées y bloquent cette affectation. Les agents archivés et l’historique des tâches sont conservés. Tant que le profil n’est pas lié, seules les instances sur les machines de son créateur sont conservées pour permettre au daemon de se reconnecter. Les copies inutilisées des autres membres suivent le nettoyage habituel après sept jours hors ligne.Le champ de commande accepte un exécutable et des arguments, pas un script shell. Les arguments simples, les guillemets et les échappements par barre oblique inverse fonctionnent ; les tubes, les redirections, `&&`, `;`, les accents graves (backticks) et l'expansion de variables d'environnement ne fonctionnent pas. Si vous avez besoin de ces comportements, placez-les dans un script d'encapsulation et utilisez ce script comme commande.diff --git a/apps/docs/content/docs/daemon-runtimes.ja.mdx b/apps/docs/content/docs/daemon-runtimes.ja.mdxindex f42db04bbc..2baa09551c 100644--- a/apps/docs/content/docs/daemon-runtimes.ja.mdx+++ b/apps/docs/content/docs/daemon-runtimes.ja.mdx@@ -91,7 +91,7 @@ multica daemon autostart disable- キュー済みの実行はランタイムの復帰を待ち、ほかのコンピュータへは移りません。失敗するのは、そのランタイムが再接続猶予を超えてハートビートを停止し、**かつ**実行自身も同じ時間キューで待った場合のみです。単に処理が詰まっているだけのランタイムは滞留分を保持し続け、すでにオフラインのランタイムに割り当てられた実行にも猶予がまるまる 1 回分あります。- 進行中の実行はすぐには失敗しません。ランタイムのハートビートの途絶が再接続猶予(`MULTICA_RUNTIME_RECONNECT_GRACE`、デフォルト 3 時間)を超えてから `runtime_offline` で失敗します。条件を満たすタスクまたはチャットの実行は自動リトライできます。- デーモンが再起動すると、ランタイムを再登録し、前回正常に終了しなかった実行を回収します。-- 7 日を超えてオフラインで、(アーカイブ済みを含め)どのエージェントにも紐づいていないランタイムは、自動的にクリーンアップされます。+- 7 日を超えてオフラインで、アクティブなユーザーエージェントや未完了タスクがないランタイムは自動的に削除されます。アーカイブ済みエージェントとタスク履歴は保持されます。所属マシンが未設定の既存カスタムプロファイルは、管理者がマシンを指定するまで、作成者自身のマシンのインスタンスのみ保持されます。下のデモでは、コンピュータがオフラインのあいだに割り当てた実行がキューで待ち続け、コンピュータがオンラインに戻ってから取得されます。@@ -234,7 +234,9 @@ Codex のネイティブサブエージェントも既定でオフです。Multi3. コマンドが実際に互換のあるプロトコルファミリーを選びます。4. 名前、コマンド、固定引数を入力して保存します。-プロファイルはワークスペース内で共有されます。接続済みの各コンピュータが自分でこのコマンドを探し、`PATH` 上で解決できたコンピュータだけが対応するランタイムを登録します。プロファイルを作成してもコマンドはインストールされず、他のメンバーのツールログインが代行されることもありません。+新しいプロファイルは、作成時に選択したコンピューターにのみ紐づきます。そのコンピューターのデーモンだけが取得・登録し、同じコマンドがインストールされていても他のコンピューターには影響しません。コマンドが見つからない場合のエラーも、選択したコンピューターにのみ表示されます。プロファイルの作成でコマンドのインストールやツールへのログインは行われません。++既存のプロファイルでは、**カスタムランタイムを編集**の**所属マシン**は省略できます。**現在のマシンを維持**のままなら、名前やコマンドなどの設定だけを変更できます。マシンを選ぶと他のマシンの未使用のコピーは削除されますが、アクティブなエージェントや未完了のタスクがある場合は紐づけが拒否されます。アーカイブ済みエージェントとタスク履歴は保持されます。マシンを指定するまでは、作成者自身のマシンのインスタンスのみ保持し、デーモンが再接続できるようにします。他のメンバーの未使用のコピーは、通常どおりオフライン期間が 7 日を超えると削除されます。ここに入力するのは実行ファイルと引数であり、shell スクリプトではありません。通常の引数、引用符、バックスラッシュによるエスケープは使えますが、パイプ、リダイレクト、`&&`、`;`、バッククォート、環境変数の展開は使えません。これらの挙動が必要な場合は wrapper script にまとめ、そのスクリプトをコマンドとして指定してください。diff --git a/apps/docs/content/docs/daemon-runtimes.ko.mdx b/apps/docs/content/docs/daemon-runtimes.ko.mdxindex a7b086970d..9235ba85b5 100644--- a/apps/docs/content/docs/daemon-runtimes.ko.mdx+++ b/apps/docs/content/docs/daemon-runtimes.ko.mdx@@ -91,7 +91,7 @@ multica daemon autostart disable- 이미 큐에 들어간 실행은 런타임이 복구될 때까지 기다리며 다른 컴퓨터로 넘어가지 않습니다. 해당 런타임이 재연결 유예를 넘겨 하트비트를 멈추고 **동시에** 실행 자체도 그만큼 기다린 뒤에만 실패합니다. 단지 바쁜 런타임은 밀린 실행을 그대로 유지하고, 이미 오프라인인 런타임에 배정된 실행도 온전한 유예를 한 번 갖습니다.- 진행 중인 실행은 바로 실패하지 않습니다. 런타임의 하트비트가 재연결 유예(`MULTICA_RUNTIME_RECONNECT_GRACE`, 기본 3시간)를 넘겨 끊긴 뒤에야 `runtime_offline`으로 실패합니다. 조건을 만족하는 태스크 또는 대화 실행은 자동으로 재시도될 수 있습니다.- 데몬이 다시 시작되면 런타임을 재등록하고 이전에 정상적으로 끝나지 않은 실행을 회수합니다.-- 7일 넘게 오프라인이고 연결된 에이전트가 하나도 없는 런타임은 보관된 에이전트까지 확인한 뒤 자동으로 정리됩니다.+- 7일 넘게 오프라인이고 활성 사용자 에이전트나 미완료 작업이 없는 런타임은 자동으로 정리됩니다. 보관된 에이전트와 작업 기록은 유지됩니다. 소속 컴퓨터가 지정되지 않은 기존 사용자 지정 설정은 관리자가 컴퓨터를 선택할 때까지 설정 작성자 소유 컴퓨터의 인스턴스만 유지됩니다.아래 데모에서는 컴퓨터가 오프라인일 때 할당한 실행이 큐에서 계속 기다리다가, 컴퓨터가 다시 온라인이 된 뒤에야 런타임에 수령됩니다.@@ -234,7 +234,9 @@ Codex 기본 하위 에이전트도 기본적으로 꺼져 있습니다. Multica3. 명령이 실제로 호환되는 프로토콜 계열을 선택합니다.4. 이름, 명령, 고정 인수를 입력하고 저장합니다.-설정은 워크스페이스에서 공유됩니다. 연결된 각 컴퓨터가 이 명령을 개별적으로 찾으며 `PATH`에서 명령을 확인할 수 있는 컴퓨터만 해당 런타임을 등록합니다. 설정을 만든다고 명령이 자동으로 설치되거나 다른 멤버의 도구 로그인이 완료되지는 않습니다.+새 설정은 만들 때 선택한 컴퓨터에만 속합니다. 해당 컴퓨터의 데몬만 설정을 가져와 등록하며, 같은 명령이 설치된 다른 컴퓨터에는 영향을 주지 않습니다. 명령을 찾지 못한 오류도 선택한 컴퓨터에만 표시됩니다. 설정을 만들어도 명령이 설치되거나 도구에 로그인되지는 않습니다.++기존 설정의 **사용자 지정 런타임 편집**에서 **소속 컴퓨터**는 생략할 수 있습니다. **현재 컴퓨터 유지**를 선택한 채 이름, 명령 또는 다른 설정만 변경할 수 있습니다. 컴퓨터를 선택하면 다른 컴퓨터의 사용하지 않는 복사본은 제거되지만 활성 에이전트나 미완료 작업이 있으면 연결이 거부됩니다. 보관된 에이전트와 작업 기록은 유지됩니다. 컴퓨터를 지정할 때까지 설정 작성자 소유 컴퓨터의 인스턴스만 유지되어 데몬이 다시 연결할 수 있습니다. 다른 멤버의 사용하지 않는 복사본은 평소처럼 7일 넘게 오프라인이면 정리됩니다.여기에는 shell script가 아니라 실행 파일과 인수를 입력합니다. 일반 인수, 따옴표, 백슬래시 이스케이프는 사용할 수 있지만 파이프, 리디렉션, `&&`, `;`, 역따옴표, 환경 변수 확장은 사용할 수 없습니다. 이런 동작이 필요하면 wrapper script에 넣고 해당 스크립트를 명령으로 입력하세요.diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdxindex b75e2bffe7..be662347e1 100644--- a/apps/docs/content/docs/daemon-runtimes.mdx+++ b/apps/docs/content/docs/daemon-runtimes.mdx@@ -91,7 +91,7 @@ When a runtime is offline:- Runs already queued wait for the runtime to recover; they do not move to another computer. A queued run fails only once the runtime has stopped heartbeating for longer than the reconnect grace **and** the run has itself been queued that long. A runtime that is merely busy keeps its backlog, and work assigned to an already-offline runtime still gets a full grace period to wait.- Runs already in progress do not fail right away. They fail with `runtime_offline` only after the runtime's heartbeat has been missing longer than the reconnect grace (`MULTICA_RUNTIME_RECONNECT_GRACE`, 3 hours by default); eligible issue or chat runs can retry automatically.- When the daemon starts again, it re-registers its runtimes and reclaims runs that did not end cleanly last time.-- A runtime offline for more than 7 days with no agents bound to it (including archived ones) is cleaned up automatically.+- A runtime offline for more than 7 days with no active user agents or unfinished tasks is cleaned up automatically; archived agents and task history are preserved. For unbound legacy custom profiles, only instances on machines owned by the profile creator are kept until an administrator selects the machine.In the demo below, a run assigned while the computer is offline waits in the queue and is claimed only after the computer comes back online.@@ -234,7 +234,9 @@ Only workspace owners and admins can create, edit, or delete custom runtime prof3. Choose the protocol family the command is actually compatible with.4. Fill in the name, command, and fixed arguments, then save.-The profile is shared across the workspace. Each connected computer looks up the command on its own; only computers that can resolve it on `PATH` register the corresponding runtime. Creating a profile does not install the command, and it does not sign other members in to the tool.+A new profile belongs only to the computer selected when you create it. Only that computer’s daemon downloads and registers it; other computers are unaffected, even if they have the same command installed. If the command cannot be resolved, its error appears only on the selected computer. Creating a profile does not install the command or sign in to the tool.++For older profiles, **Machine** in **Edit custom runtime** is optional: leave **Keep current machines** selected to change only the name, command, or other settings. Selecting a machine removes unused copies on other machines; active agents or unfinished tasks there block the binding. Archived agents and task history are preserved. Until the profile is bound, instances on machines owned by its creator are kept so the daemon can reconnect. Other members’ unused copies follow the normal seven-day offline cleanup.The command field takes an executable and arguments, not a shell script. Plain arguments, quotes, and backslash escapes work; pipes, redirects, `&&`, `;`, backticks, and environment variable expansion do not. When you need those behaviors, put them in a wrapper script and use that script as the command.diff --git a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdxindex 9416ee56a4..c9a240bb8e 100644--- a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx+++ b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx@@ -92,7 +92,7 @@ multica daemon autostart disable- 已經排隊的執行等待執行時恢復,不會轉到其他電腦。只有執行時心跳缺席超過重連寬限期,**並且**這條執行自己也已排隊滿這麼久,它才會失敗。執行時只是忙的話,積壓會一直保留;指派給已離線執行時的工作,也有完整的一個寬限期可以等。- 正在執行的執行不會馬上失敗。執行時心跳缺席超過重連寬限期(`MULTICA_RUNTIME_RECONNECT_GRACE`,預設 3 小時)後,它們才以 `runtime_offline` 失敗;符合條件的任務或對話執行可以自動重試。- 守護程序重新啟動後,會重新註冊執行時,並回收上一次沒有正常結束的執行。-- 離線超過 7 天且沒有任何 AI 代理(包括已歸檔的)繫結的執行時,會被自動清理。+- 離線超過 7 天且沒有活躍使用者 AI 代理或未完成任務的執行時會自動清理,已歸檔 AI 代理和任務歷史會保留。舊自訂配置未綁定機器時,僅保留配置建立者本人機器上的實例,直到管理員選擇所屬機器。下面的演示裡,電腦離線時分配的執行一直在佇列裡等,電腦重新上線後才被領取。@@ -235,7 +235,9 @@ Codex 原生子 AI 代理同樣預設關閉:父執行緒結束時,Multica3. 選擇命令實際相容的協議族。4. 填寫名稱、命令和固定引數,然後儲存。-配置會在工作區內共享。每臺已連線電腦會自行查詢這個命令;只有能在 `PATH` 中解析到它的電腦才會註冊對應執行時。建立配置不會自動安裝命令,也不會替其他成員完成工具登入。+新配置只屬於建立時選中的電腦。只有這臺電腦的守護程序會拉取並註冊它;其他電腦即使裝了同名命令也不受影響。命令無法解析時,失敗提示也只顯示在選中的電腦上。建立配置不會自動安裝命令或完成工具登入。++舊配置在**編輯自定義執行時**中的**所屬機器(選填)**預設選中**保留現有機器**,可以只修改名稱、命令或其他設定。選擇所屬機器後,儲存時會移除其他機器上未使用的副本;如果仍有活躍 AI 代理或未完成任務,綁定操作會被阻止。已歸檔 AI 代理和任務歷史會保留。配置完成綁定前,僅保留建立者本人機器上的實例,確保守護程序重新上線後仍能註冊;其他成員的閒置副本照常在離線超過 7 天後自動清理。這裡填寫的是可執行檔案和引數,不是 shell 指令碼。可以使用普通引數、引號和反斜槓轉義,但不能使用管道、重定向、`&&`、`;`、反引號或環境變數展開。需要這些行為時,把它們放進 wrapper script,再把該指令碼作為命令填寫。diff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdxindex 275eeb7f99..fb110307d5 100644--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx@@ -92,7 +92,7 @@ multica daemon autostart disable- 已经排队的运行等待运行时恢复,不会转到其他电脑。只有运行时心跳缺席超过重连宽限期,**并且**这条运行自己也已排队满这么久,它才会失败。运行时只是忙的话,积压会一直保留;指派给已离线运行时的工作,也有完整的一个宽限期可以等。- 正在执行的运行不会马上失败。运行时心跳缺席超过重连宽限期(`MULTICA_RUNTIME_RECONNECT_GRACE`,默认 3 小时)后,它们才以 `runtime_offline` 失败;符合条件的任务或对话运行可以自动重试。- 守护进程重新启动后,会重新注册运行时,并回收上一次没有正常结束的运行。-- 离线超过 7 天且没有任何智能体(包括已归档的)绑定的运行时,会被自动清理。+- 离线超过 7 天且没有活跃用户智能体或未完成任务的运行时会自动清理,已归档智能体和任务历史会保留。旧自定义配置未绑定机器时,仅保留配置创建者本人机器上的实例,直到管理员选择归属机器。下面的演示里,电脑离线时分配的运行一直在队列里等,电脑重新上线后才被领取。@@ -235,7 +235,9 @@ Codex 原生子智能体同样默认关闭:父线程结束时,Multica 就把3. 选择命令实际兼容的协议族。4. 填写名称、命令和固定参数,然后保存。-配置会在工作区内共享。每台已连接电脑会自行查找这个命令;只有能在 `PATH` 中解析到它的电脑才会注册对应运行时。创建配置不会自动安装命令,也不会替其他成员完成工具登录。+新配置只属于创建时选中的电脑。只有这台电脑的守护进程会拉取并注册它;其他电脑即使装了同名命令也不受影响。命令无法解析时,失败提示也只显示在选中的电脑上。创建配置不会自动安装命令或完成工具登录。++旧配置在**编辑自定义运行时**中的**归属机器(可选)**默认选中**保留现有机器**,可以只修改名称、命令或其他设置。选择归属机器后,保存时会移除其他机器上未使用的副本;如果仍有活跃智能体或未完成任务,绑定操作会被阻止。已归档智能体和任务历史会保留。配置完成绑定前,仅保留创建者本人机器上的实例,确保守护进程重新上线后仍能注册;其他成员的闲置副本照常在离线超过 7 天后自动清理。这里填写的是可执行文件和参数,不是 shell 脚本。可以使用普通参数、引号和反斜杠转义,但不能使用管道、重定向、`&&`、`;`、反引号或环境变量展开。需要这些行为时,把它们放进 wrapper script,再把该脚本作为命令填写。diff --git a/packages/core/api/runtime-profile-schema.test.ts b/packages/core/api/runtime-profile-schema.test.tsindex a1a48bc700..c569b4906a 100644--- a/packages/core/api/runtime-profile-schema.test.ts+++ b/packages/core/api/runtime-profile-schema.test.ts@@ -10,6 +10,16 @@ const profile = {command_name: "wrapper",};describe("runtime profile response compatibility", () => {+ it("reads machine bindings and tolerates older responses", () => {+ expect(+ RuntimeProfileSchema.parse({ ...profile, daemon_id: "machine-a" }).daemon_id,+ ).toBe("machine-a");+ for (const daemon_id of [undefined, null, 42]) {+ expect(+ RuntimeProfileSchema.parse({ ...profile, daemon_id }).daemon_id,+ ).toBeNull();+ }+ });it("defaults old or malformed identities to the protocol", () => {for (const runtime_type of [undefined, null, 42, ""]) {expect(diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 30b93743bd..5d34e5a24f 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -4485,6 +4485,7 @@ export const RuntimeProfileSchema = z.object({id: z.string(),workspace_id: z.string(),+ daemon_id: z.string().nullable().catch(null),display_name: z.string(),protocol_family: z.string(),runtime_type: z.string().nullish().catch(undefined),diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 65118f46bb..3f8a56ccc8 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -160,6 +160,7 @@ export type RuntimeProfileVisibility = "workspace" | "private";export interface RuntimeProfile {id: string;workspace_id: string;+ daemon_id?: string | null;display_name: string;protocol_family: RuntimeProtocolFamily;runtime_type?: RuntimeProfileType;@@ -178,6 +179,7 @@ export interface RuntimeProfile {// Optional fields are omitted entirely when unset (never sent as null/empty)// so the server applies its own defaults.export interface CreateRuntimeProfileRequest {+ daemon_id?: string;display_name: string;protocol_family?: RuntimeProtocolFamily;runtime_type?: RuntimeProfileType;@@ -191,6 +193,7 @@ export interface CreateRuntimeProfileRequest {// PATCH body — every field optional; `protocol_family` is intentionally// absent because it is immutable.export interface UpdateRuntimeProfileRequest {+ daemon_id?: string;display_name?: string;command_name?: string;description?: string | null;diff --git a/packages/views/locales/en/runtimes.json b/packages/views/locales/en/runtimes.jsonindex 3cdf14ae60..142516a01d 100644--- a/packages/views/locales/en/runtimes.json+++ b/packages/views/locales/en/runtimes.json@@ -396,10 +396,10 @@"add_custom": "Add custom runtime","this_machine": "this machine","unassigned_title": "Custom runtimes without a machine",- "unassigned_description": "These workspace runtimes are not connected to any machine. Connect a machine with the matching commands, or use a row's actions to edit or delete them.",+ "unassigned_description": "Reconnect the assigned machine, or edit an older runtime to assign its machine.","dialog_title": "Custom runtimes",- "dialog_description": "Custom runtime definitions are workspace-wide and sync to every connected machine. A machine registers the runtime when the command is available there.",- "create_dialog_description": "Set up a custom command from {{machine}}. The definition syncs workspace-wide and registers only on machines where that command is available.",+ "dialog_description": "Custom runtimes belong to one machine.",+ "create_dialog_description": "Only {{machine}} will register this custom command.","learn_more": "View setup guide","close": "Close","add_new": "New custom runtime",@@ -437,6 +437,9 @@"step_family_hint": "Select the CLI this command is compatible with.","step_details_label": "Configure the runtime","step_progress": "Step {{current}} of {{total}}",+ "machine_label": "Machine (optional)",+ "machine_placeholder": "Keep current machines",+ "machine_hint": "Selecting a machine removes unused copies on other machines.","family_label": "Base runtime","family_locked_hint": "The base runtime cannot be changed after creation.","display_name_label": "Display name",diff --git a/packages/views/locales/es/runtimes.json b/packages/views/locales/es/runtimes.jsonindex dacf57083d..4be391a631 100644--- a/packages/views/locales/es/runtimes.json+++ b/packages/views/locales/es/runtimes.json@@ -396,10 +396,10 @@"add_custom": "Añadir runtime personalizado","this_machine": "esta máquina","unassigned_title": "Runtimes personalizados sin máquina",- "unassigned_description": "Estos runtimes del espacio de trabajo no están conectados a ninguna máquina. Conecta una máquina con los comandos correspondientes, o usa las acciones de la fila para editarlos o eliminarlos.",+ "unassigned_description": "Vuelve a conectar la máquina asignada, o edita un runtime antiguo para asignarle una máquina.","dialog_title": "Runtimes personalizados",- "dialog_description": "Las definiciones de runtimes personalizados son de todo el espacio de trabajo y se sincronizan con cada máquina conectada. Una máquina registra el runtime cuando el comando está disponible allí.",- "create_dialog_description": "Configura un comando personalizado desde {{machine}}. La definición se sincroniza en todo el espacio de trabajo y solo se registra en las máquinas donde ese comando está disponible.",+ "dialog_description": "Cada runtime personalizado pertenece a una sola máquina.",+ "create_dialog_description": "Solo {{machine}} registrará este comando personalizado.","learn_more": "Ver guía de configuración","close": "Cerrar","add_new": "Runtime personalizado nuevo",@@ -437,6 +437,9 @@"step_family_hint": "Selecciona la CLI con la que es compatible este comando.","step_details_label": "Configura el runtime","step_progress": "Paso {{current}} de {{total}}",+ "machine_label": "Máquina (opcional)",+ "machine_placeholder": "Mantener las máquinas actuales",+ "machine_hint": "Al seleccionar una máquina se eliminan las copias sin uso de las otras máquinas.","family_label": "Runtime base","family_locked_hint": "El runtime base no se puede cambiar después de la creación.","display_name_label": "Nombre visible",diff --git a/packages/views/locales/fr/runtimes.json b/packages/views/locales/fr/runtimes.jsonindex ae4c75e114..5c3918456f 100644--- a/packages/views/locales/fr/runtimes.json+++ b/packages/views/locales/fr/runtimes.json@@ -396,10 +396,10 @@"add_custom": "Ajouter un runtime personnalisé","this_machine": "cette machine","unassigned_title": "Runtimes personnalisés sans machine",- "unassigned_description": "Ces runtimes de l'espace de travail ne sont connectés à aucune machine. Connectez une machine disposant des commandes correspondantes, ou utilisez les actions d'une ligne pour les modifier ou les supprimer.",+ "unassigned_description": "Reconnectez la machine assignée, ou modifiez un ancien runtime pour lui assigner une machine.","dialog_title": "Runtimes personnalisés",- "dialog_description": "Les définitions de runtimes personnalisés valent pour tout l'espace de travail et se synchronisent avec chaque machine connectée. Une machine enregistre le runtime dès que la commande y est disponible.",- "create_dialog_description": "Configurez une commande personnalisée depuis {{machine}}. La définition se synchronise dans tout l'espace de travail et ne s'enregistre que sur les machines où cette commande est disponible.",+ "dialog_description": "Un runtime personnalisé appartient à une seule machine.",+ "create_dialog_description": "Seule {{machine}} enregistrera cette commande personnalisée.","learn_more": "Voir le guide de configuration","close": "Fermer","add_new": "Nouveau runtime personnalisé",@@ -437,6 +437,9 @@"step_family_hint": "Sélectionnez le CLI compatible avec cette commande.","step_details_label": "Configurez le runtime","step_progress": "Étape {{current}} sur {{total}}",+ "machine_label": "Machine (facultatif)",+ "machine_placeholder": "Conserver les machines actuelles",+ "machine_hint": "Sélectionner une machine supprime les copies inutilisées sur les autres machines.","family_label": "Runtime de base","family_locked_hint": "Le runtime de base ne peut pas être modifié après la création.","display_name_label": "Nom affiché",diff --git a/packages/views/locales/ja/runtimes.json b/packages/views/locales/ja/runtimes.jsonindex 00e482bbc4..edc015030d 100644--- a/packages/views/locales/ja/runtimes.json+++ b/packages/views/locales/ja/runtimes.json@@ -384,10 +384,10 @@"add_custom": "カスタムランタイムを追加","this_machine": "このマシン","unassigned_title": "マシンに接続されていないカスタムランタイム",- "unassigned_description": "これらのワークスペースランタイムは、どのマシンにも接続されていません。対応するコマンドがあるマシンを接続するか、行の操作から編集または削除できます。",+ "unassigned_description": "割り当て済みのマシンを再接続してください。既存の未設定ランタイムは、編集からマシンを指定できます。","dialog_title": "カスタムランタイム",- "dialog_description": "カスタムランタイム定義はワークスペース全体に適用され、接続済みのすべてのマシンへ同期されます。コマンドが利用可能なマシンでのみランタイムが登録されます。",- "create_dialog_description": "{{machine}} からカスタムコマンドを設定します。定義はワークスペース全体に同期され、そのコマンドを利用できるマシンでのみ登録されます。",+ "dialog_description": "カスタムランタイムは 1 台のマシンに紐づきます。",+ "create_dialog_description": "このカスタムコマンドは {{machine}} でのみ登録されます。","learn_more": "設定ガイドを見る","close": "閉じる","add_new": "新しいカスタムランタイム",@@ -425,6 +425,9 @@"step_family_hint": "このコマンドと互換性のある CLI を選択します。","step_details_label": "ランタイムを設定","step_progress": "ステップ {{current}} / {{total}}",+ "machine_label": "所属マシン(任意)",+ "machine_placeholder": "現在のマシンを維持",+ "machine_hint": "マシンを選ぶと、他のマシンの未使用のコピーが削除されます。","family_label": "ベースランタイム","family_locked_hint": "作成後はベースランタイムを変更できません。","display_name_label": "表示名",diff --git a/packages/views/locales/ko/runtimes.json b/packages/views/locales/ko/runtimes.jsonindex e193632c83..c820391091 100644--- a/packages/views/locales/ko/runtimes.json+++ b/packages/views/locales/ko/runtimes.json@@ -384,10 +384,10 @@"add_custom": "사용자 지정 런타임 추가","this_machine": "이 기기","unassigned_title": "기기에 연결되지 않은 사용자 지정 런타임",- "unassigned_description": "이 워크스페이스 런타임은 현재 어떤 기기에도 연결되어 있지 않습니다. 해당 명령이 있는 기기를 연결하거나 행 작업에서 수정 또는 삭제할 수 있습니다.",+ "unassigned_description": "지정된 컴퓨터를 다시 연결하세요. 컴퓨터가 지정되지 않은 기존 런타임은 편집에서 지정할 수 있습니다.","dialog_title": "사용자 지정 런타임",- "dialog_description": "사용자 지정 런타임 정의는 워크스페이스 전체에 적용되며 연결된 모든 기기에 동기화됩니다. 해당 명령을 사용할 수 있는 기기에서만 런타임이 등록됩니다.",- "create_dialog_description": "{{machine}}에서 사용자 지정 명령을 설정합니다. 정의는 워크스페이스 전체에 동기화되며 해당 명령을 사용할 수 있는 기기에만 등록됩니다.",+ "dialog_description": "사용자 지정 런타임은 한 컴퓨터에만 속합니다.",+ "create_dialog_description": "이 사용자 지정 명령은 {{machine}}에서만 등록됩니다.","learn_more": "설정 가이드 보기","close": "닫기","add_new": "새 사용자 지정 런타임",@@ -425,6 +425,9 @@"step_family_hint": "이 명령과 호환되는 CLI를 선택하세요.","step_details_label": "런타임 구성","step_progress": "{{current}} / {{total}}단계",+ "machine_label": "소속 컴퓨터(선택 사항)",+ "machine_placeholder": "현재 컴퓨터 유지",+ "machine_hint": "컴퓨터를 선택하면 다른 컴퓨터의 사용하지 않는 복사본이 제거됩니다.","family_label": "기본 런타임","family_locked_hint": "생성 후에는 기본 런타임을 변경할 수 없습니다.","display_name_label": "표시 이름",diff --git a/packages/views/locales/ru/runtimes.json b/packages/views/locales/ru/runtimes.jsonindex cd46ccf3b7..7105d644fe 100644--- a/packages/views/locales/ru/runtimes.json+++ b/packages/views/locales/ru/runtimes.json@@ -416,10 +416,10 @@"add_custom": "Добавить пользовательскую среду выполнения","this_machine": "эта машина","unassigned_title": "Пользовательские среды выполнения без машины",- "unassigned_description": "Эти среды выполнения рабочего пространства не подключены ни к одной машине. Подключите машину с подходящими командами или используйте действия в строке, чтобы изменить или удалить их.",+ "unassigned_description": "Подключите назначенный компьютер или измените старую среду выполнения, чтобы назначить ей компьютер.","dialog_title": "Пользовательские среды выполнения",- "dialog_description": "Определения пользовательских сред выполнения действуют на весь рабочий процесс и синхронизируются со всеми подключёнными машинами. Машина регистрирует среду выполнения, когда команда доступна на ней.",- "create_dialog_description": "Настройте пользовательскую команду с {{machine}}. Определение синхронизируется по всему рабочему пространству и регистрируется только на машинах, где эта команда доступна.",+ "dialog_description": "Пользовательская среда выполнения привязана к одному компьютеру.",+ "create_dialog_description": "Эта пользовательская команда будет зарегистрирована только на {{machine}}.","learn_more": "Открыть инструкцию по настройке","close": "Закрыть","add_new": "Новая пользовательская среда выполнения",@@ -457,6 +457,9 @@"step_family_hint": "Выберите CLI, с которым совместима эта команда.","step_details_label": "Настройте среду выполнения","step_progress": "Шаг {{current}} из {{total}}",+ "machine_label": "Компьютер (необязательно)",+ "machine_placeholder": "Сохранить текущие компьютеры",+ "machine_hint": "При выборе компьютера неиспользуемые копии на других компьютерах будут удалены.","family_label": "Базовая среда выполнения","family_locked_hint": "Базовую среду выполнения нельзя изменить после создания.","display_name_label": "Отображаемое имя",diff --git a/packages/views/locales/zh-Hans/runtimes.json b/packages/views/locales/zh-Hans/runtimes.jsonindex 04ea6ed5e7..9c08212600 100644--- a/packages/views/locales/zh-Hans/runtimes.json+++ b/packages/views/locales/zh-Hans/runtimes.json@@ -384,10 +384,10 @@"add_custom": "添加自定义运行时","this_machine": "这台机器","unassigned_title": "尚未连接到机器的自定义运行时",- "unassigned_description": "这些工作区运行时目前没有连接到任何机器。你可以连接装有对应命令的机器,或通过行操作编辑、删除配置。",+ "unassigned_description": "请重新连接已绑定的机器;尚未绑定的旧运行时可通过编辑选择归属机器。","dialog_title": "自定义运行时",- "dialog_description": "自定义运行时定义属于整个工作区,会同步到所有已连接的机器。只有机器上能找到对应命令时,才会注册该运行时。",- "create_dialog_description": "从 {{machine}} 配置一个自定义命令。定义会同步到整个工作区,但只会在能找到该命令的机器上注册。",+ "dialog_description": "自定义运行时只属于一台机器。",+ "create_dialog_description": "只有 {{machine}} 会注册这个自定义命令。","learn_more": "查看配置指南","close": "关闭","add_new": "新建自定义运行时",@@ -425,6 +425,9 @@"step_family_hint": "选择此命令兼容的 CLI。","step_details_label": "配置运行时","step_progress": "第 {{current}} / {{total}} 步",+ "machine_label": "归属机器(可选)",+ "machine_placeholder": "保留现有机器",+ "machine_hint": "选择机器后,其他机器上未使用的副本将被移除。","family_label": "基础运行时","family_locked_hint": "创建后无法更改基础运行时。","display_name_label": "显示名称",diff --git a/packages/views/locales/zh-Hant/runtimes.json b/packages/views/locales/zh-Hant/runtimes.jsonindex d22e73b3a5..5d46eaa089 100644--- a/packages/views/locales/zh-Hant/runtimes.json+++ b/packages/views/locales/zh-Hant/runtimes.json@@ -384,10 +384,10 @@"add_custom": "新增自定義執行時","this_machine": "這臺機器","unassigned_title": "尚未連線到機器的自定義執行時",- "unassigned_description": "這些工作區執行時目前沒有連線到任何機器。你可以連線裝有對應命令的機器,或透過行操作編輯、刪除配置。",+ "unassigned_description": "請重新連線已綁定的機器;尚未綁定的舊執行時可透過編輯選擇所屬機器。","dialog_title": "自定義執行時",- "dialog_description": "自定義執行時定義屬於整個工作區,會同步到所有已連線的機器。只有機器上能找到對應命令時,才會註冊該執行時。",- "create_dialog_description": "從 {{machine}} 配置一個自定義命令。定義會同步到整個工作區,但只會在能找到該命令的機器上註冊。",+ "dialog_description": "自訂執行時只屬於一臺機器。",+ "create_dialog_description": "只有 {{machine}} 會註冊這個自定義命令。","learn_more": "檢視配置指南","close": "關閉","add_new": "新建自定義執行時",@@ -425,6 +425,9 @@"step_family_hint": "選擇此命令相容的 CLI。","step_details_label": "配置執行時","step_progress": "第 {{current}} / {{total}} 步",+ "machine_label": "所屬機器(選填)",+ "machine_placeholder": "保留現有機器",+ "machine_hint": "選擇機器後,其他機器上未使用的副本將被移除。","family_label": "基礎執行時","family_locked_hint": "建立後無法更改基礎執行時。","display_name_label": "顯示名稱",diff --git a/packages/views/runtimes/components/pending-runtime.test.ts b/packages/views/runtimes/components/pending-runtime.test.tsindex 5a4fa2412f..b72bea1bbc 100644--- a/packages/views/runtimes/components/pending-runtime.test.ts+++ b/packages/views/runtimes/components/pending-runtime.test.ts@@ -16,6 +16,7 @@ function profile(overrides: Partial<RuntimeProfile> = {}): RuntimeProfile {return {id: "profile-1",workspace_id: "ws-1",+ daemon_id: "daemon-1",display_name: "Team Codex",protocol_family: "codex",command_name: "team-codex",@@ -53,6 +54,29 @@ function runtime(overrides: Partial<AgentRuntime> = {}): AgentRuntime {}describe("pending custom runtime rows", () => {+ it("only adds a pending profile on its bound machine", () => {+ const profiles = [+ profile(),+ profile({ id: "other", daemon_id: "daemon-2" }),+ profile({ id: "legacy", daemon_id: null }),+ ];+ const rows = pendingRuntimesForProfiles({+ pendingProfiles: profiles.map((profile) => ({ profile, createdAt: 0 })),+ runtimes: [runtime()],+ localDaemonId: "daemon-1",+ });+ expect(rows.map((row) => row.id)).toEqual([+ "runtime-1",+ pendingRuntimeId("profile-1"),+ ]);+ expect(+ pendingRuntimesForProfiles({+ pendingProfiles: [{ profile: profile(), createdAt: 0 }],+ runtimes: [],+ }),+ ).toEqual([]);+ });+it("builds a pending runtime from the newly created profile", () => {const createdAt = Date.parse("2026-01-01T00:00:00Z");const pending = pendingRuntimeFromProfile({diff --git a/packages/views/runtimes/components/pending-runtime.ts b/packages/views/runtimes/components/pending-runtime.tsindex bb1f21799a..a6c88fbaed 100644--- a/packages/views/runtimes/components/pending-runtime.ts+++ b/packages/views/runtimes/components/pending-runtime.ts@@ -127,6 +127,9 @@ export function pendingRuntimesForProfiles({.filter((profileId): profileId is string => !!profileId),);const pendingRuntimes = pendingProfiles+ .filter(+ ({ profile }) => !!localDaemonId && profile.daemon_id === localDaemonId,+ ).filter(({ profile }) => !registeredProfileIds.has(profile.id)).map(({ profile, createdAt }) =>pendingRuntimeFromProfile({diff --git a/packages/views/runtimes/components/runtime-detail-page.test.tsx b/packages/views/runtimes/components/runtime-detail-page.test.tsxindex 574dd4b826..1546c49f4d 100644--- a/packages/views/runtimes/components/runtime-detail-page.test.tsx+++ b/packages/views/runtimes/components/runtime-detail-page.test.tsx@@ -67,7 +67,9 @@ vi.mock("./rename-machine-dialog", () => ({open ? <div role="dialog">Rename machine dialog</div> : null,}));vi.mock("./runtime-profiles-dialog", () => ({- RuntimeProfilesDialog: () => <div role="dialog">Custom runtime dialog</div>,+ RuntimeProfilesDialog: ({ daemonId }: { daemonId?: string }) => (+ <div role="dialog" data-daemon-id={daemonId}>Custom runtime dialog</div>+ ),}));const NOW = Date.now();@@ -136,6 +138,25 @@ function renderPage({}describe("RuntimeDetailPage", () => {+ it("binds creation to the selected machine when viewing another computer", () => {+ renderPage({+ runtimeId: "rt-remote",+ runtimes: [+ makeRuntime(),+ makeRuntime({+ id: "rt-remote",+ daemon_id: "daemon-remote",+ name: "Codex (Remote Mac)",+ device_info: "Remote Mac",+ }),+ ],+ });+ fireEvent.click(screen.getByRole("button", { name: /Add custom runtime/ }));+ expect(screen.getByRole("dialog")).toHaveAttribute(+ "data-daemon-id", "daemon-remote",+ );+ });+it("keeps the breadcrumb header in place while the machine loads", () => {const { container } = renderPage({ runtimes: null });diff --git a/packages/views/runtimes/components/runtime-detail-page.tsx b/packages/views/runtimes/components/runtime-detail-page.tsxindex c7709abb9f..829170e414 100644--- a/packages/views/runtimes/components/runtime-detail-page.tsx+++ b/packages/views/runtimes/components/runtime-detail-page.tsx@@ -386,6 +386,7 @@ export function RuntimeDetailPage({<RuntimeProfilesDialogwsId={wsId}intent="create"+ daemonId={machine.daemonId ?? undefined}machineName={machine.title}onClose={() => setCreateProfileOpen(false)}/>diff --git a/packages/views/runtimes/components/runtime-profiles-dialog.test.tsx b/packages/views/runtimes/components/runtime-profiles-dialog.test.tsxindex 0593b20791..026fe08449 100644--- a/packages/views/runtimes/components/runtime-profiles-dialog.test.tsx+++ b/packages/views/runtimes/components/runtime-profiles-dialog.test.tsx@@ -2,13 +2,16 @@import { describe, expect, it, beforeEach, vi } from "vitest";import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";import { I18nProvider } from "@multica/core/i18n/react";-import type { RuntimeProfile } from "@multica/core/types";+import { ApiError } from "@multica/core/api";+import type { AgentRuntime, RuntimeProfile } from "@multica/core/types";import enCommon from "../../locales/en/common.json";import enRuntimes from "../../locales/en/runtimes.json";const queryState = vi.hoisted(() => ({profiles: [] as RuntimeProfile[],+ runtimes: [] as AgentRuntime[],isLoading: false,}));const mutationState = vi.hoisted(() => ({@@ -22,8 +25,8 @@ vi.mock("@tanstack/react-query", async () => {);return {...actual,- useQuery: vi.fn(() => ({- data: queryState.profiles,+ useQuery: vi.fn((options: { queryKey: string[] }) => ({+ data: options.queryKey[0] === "runtimes" ? queryState.runtimes : queryState.profiles,isLoading: queryState.isLoading,})),};@@ -34,6 +37,7 @@ vi.mock("sonner", () => ({}));vi.mock("@multica/core/runtimes", () => ({+ deriveRuntimeHealth: () => "online",runtimeProfileListOptions: vi.fn((wsId: string) => ({queryKey: ["runtime-profiles", wsId, "list"],})),@@ -63,6 +67,7 @@ function profile(overrides: Partial<RuntimeProfile> = {}): RuntimeProfile {return {id: "prof-1",workspace_id: "ws-1",+ daemon_id: "daemon-target",display_name: "Team Codex",protocol_family: "codex",command_name: "codex",@@ -95,6 +100,7 @@ function renderDialog({<RuntimeProfilesDialogwsId="ws-1"intent={intent}+ daemonId="daemon-target"machineName={machineName}initialProfile={initialProfile}onClose={onClose}@@ -108,6 +114,7 @@ function renderDialog({describe("RuntimeProfilesDialog", () => {beforeEach(() => {queryState.profiles = [];+ queryState.runtimes = [];queryState.isLoading = false;vi.clearAllMocks();mutationState.createProfile.mockResolvedValue(@@ -119,6 +126,60 @@ describe("RuntimeProfilesDialog", () => {mutationState.updateProfile.mockResolvedValue(profile());});+ it.each([false, true])("binds an existing profile and surfaces usage conflicts (%s)", async (conflict) => {+ const user = userEvent.setup();+ queryState.runtimes = [{+ id: "rt-1", workspace_id: "ws-1", daemon_id: "keep-machine",+ name: "Codex (Studio Mac)", runtime_mode: "local", provider: "codex",+ status: "online", owner_id: "user-1", visibility: "private", metadata: {},+ launch_header: "codex", device_info: "Studio Mac", profile_id: null,+ last_seen_at: new Date().toISOString(), created_at: "", updated_at: "",+ }];+ if (conflict) mutationState.updateProfile.mockRejectedValueOnce(new ApiError(+ "Finish pending tasks on the other machine first.", 409, "Conflict", { code: "runtime_profile_machine_conflict" },+ ));+ const { onClose } = renderDialog({ intent: "edit", initialProfile: profile({ daemon_id: null }) });+ await user.click(screen.getByLabelText("Machine (optional)"));+ await user.click(await screen.findByRole("option", { name: "Studio Mac" }));+ await user.click(screen.getByRole("button", { name: "Save changes" }));+ await waitFor(() => expect(mutationState.updateProfile).toHaveBeenCalledWith({+ profileId: "prof-1", patch: expect.objectContaining({ daemon_id: "keep-machine" }),+ }));+ if (conflict) {+ expect(await screen.findByRole("alert")).toHaveTextContent("Finish pending tasks");+ expect(screen.queryByText("A runtime with this display name already exists.")).not.toBeInTheDocument();+ expect(onClose).not.toHaveBeenCalled();+ } else await waitFor(() => expect(onClose).toHaveBeenCalledOnce());+ });++ it.each([false, true])("edits a legacy profile without binding a machine (reset selection: %s)", async (resetSelection) => {+ const user = userEvent.setup();+ queryState.runtimes = [{+ id: "rt-1", workspace_id: "ws-1", daemon_id: "keep-machine",+ name: "Codex (Studio Mac)", runtime_mode: "local", provider: "codex",+ status: "online", owner_id: "user-1", visibility: "private", metadata: {},+ launch_header: "codex", device_info: "Studio Mac", profile_id: null,+ last_seen_at: new Date().toISOString(), created_at: "", updated_at: "",+ }];+ const { onClose } = renderDialog({ intent: "edit", initialProfile: profile({ daemon_id: null }) });+ if (resetSelection) {+ await user.click(screen.getByLabelText("Machine (optional)"));+ await user.click(await screen.findByRole("option", { name: "Studio Mac" }));+ await user.click(screen.getByLabelText("Machine (optional)"));+ await user.click(await screen.findByRole("option", { name: "Keep current machines" }));+ }+ fireEvent.change(screen.getByLabelText("Display name"), { target: { value: "Renamed legacy runtime" } });+ fireEvent.change(screen.getByLabelText("Command"), { target: { value: "wrapper --model custom" } });+ fireEvent.click(screen.getByRole("button", { name: "Save changes" }));+ await waitFor(() => expect(mutationState.updateProfile).toHaveBeenCalledWith({+ profileId: "prof-1", patch: {+ display_name: "Renamed legacy runtime", command_name: "wrapper",+ fixed_args: ["--model", "custom"], description: null,+ },+ }));+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());+ });+it("shows the custom empty state and keeps built-in protocols collapsed", () => {renderDialog();@@ -197,6 +258,7 @@ describe("RuntimeProfilesDialog", () => {fireEvent.click(screen.getByRole("button", { name: "Create runtime" }));await waitFor(() =>expect(mutationState.createProfile).toHaveBeenCalledWith({+ daemon_id: "daemon-target",display_name: "Custom OMP",runtime_type: "omp",command_name: "wrapper",@@ -217,6 +279,7 @@ describe("RuntimeProfilesDialog", () => {fireEvent.click(screen.getByRole("button", { name: "Create runtime" }));await waitFor(() =>expect(mutationState.createProfile).toHaveBeenCalledWith({+ daemon_id: "daemon-target",display_name: "Team Devin",runtime_type: "devin",command_name: "team-devin",@@ -250,6 +313,7 @@ describe("RuntimeProfilesDialog", () => {await waitFor(() =>expect(mutationState.createProfile).toHaveBeenCalledWith({+ daemon_id: "daemon-target",display_name: "Composer Agent",runtime_type: "codex",command_name: "agent",@@ -271,7 +335,7 @@ describe("RuntimeProfilesDialog", () => {expect(screen.getByRole("heading", { name: "New custom runtime" }),).toBeInTheDocument();- expect(screen.getByText(/from Studio Mac/)).toBeInTheDocument();+ expect(screen.getByText("Only Studio Mac will register this custom command.")).toBeInTheDocument();expect(screen.getByRole("link", { name: "View setup guide" }),).toHaveAttribute(diff --git a/packages/views/runtimes/components/runtime-profiles-dialog.tsx b/packages/views/runtimes/components/runtime-profiles-dialog.tsxindex 97b7436065..43805e61fa 100644--- a/packages/views/runtimes/components/runtime-profiles-dialog.tsx+++ b/packages/views/runtimes/components/runtime-profiles-dialog.tsx@@ -16,6 +16,7 @@ import {import { toast } from "sonner";import { useQuery } from "@tanstack/react-query";import { ApiError } from "@multica/core/api";+import { runtimeListOptions } from "@multica/core/runtimes/queries";import type {RuntimeProfile,RuntimeProfileType,@@ -38,6 +39,14 @@ import {import { Input } from "@multica/ui/components/ui/input";import { Label } from "@multica/ui/components/ui/label";import { Textarea } from "@multica/ui/components/ui/textarea";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@multica/ui/components/ui/select";+import { buildRuntimeMachines } from "./runtime-machines";import { cn } from "@multica/ui/lib/utils";import { ProviderLogo } from "./provider-logo";import { DeleteRuntimeProfileDialog } from "./delete-runtime-profile-dialog";@@ -68,6 +77,7 @@ type DialogState =export function RuntimeProfilesDialog({wsId,intent = "manage",+ daemonId,machineName,initialProfile,onProfileCreated,@@ -75,6 +85,7 @@ export function RuntimeProfilesDialog({}: {wsId: string;intent?: "create" | "edit" | "manage";+ daemonId?: string;machineName?: string;initialProfile?: RuntimeProfile;onProfileCreated?: (profile: RuntimeProfile) => void;@@ -185,6 +196,7 @@ export function RuntimeProfilesDialog({{state.surface === "form" ? (<ProfileFormViewwsId={wsId}+ daemonId={daemonId}mode={state.mode}step={state.mode === "create" ? state.step : "details"}family={@@ -637,6 +649,7 @@ function DetailRow({function ProfileFormView({wsId,+ daemonId,mode,step,family,@@ -649,6 +662,7 @@ function ProfileFormView({onSaved,}: {wsId: string;+ daemonId?: string;mode: "create" | "edit";step: "family" | "details";family: RuntimeProfileType;@@ -718,6 +732,7 @@ function ProfileFormView({return (<ProfileDetailsFormwsId={wsId}+ daemonId={daemonId}mode={mode}family={family}profile={profile}@@ -731,6 +746,7 @@ function ProfileFormView({function ProfileDetailsForm({wsId,+ daemonId,mode,family,profile,@@ -740,6 +756,7 @@ function ProfileDetailsForm({onSaved,}: {wsId: string;+ daemonId?: string;mode: "create" | "edit";family: RuntimeProfileType;profile: RuntimeProfile | null;@@ -752,6 +769,23 @@ function ProfileDetailsForm({const idPrefix = `runtime-profile-${useId().replace(/:/g, "")}`;const createProfile = useCreateRuntimeProfile(wsId);const updateProfile = useUpdateRuntimeProfile(wsId);+ const canBindMachine = mode === "edit" && !profile?.daemon_id;+ const { data: runtimes = [] } = useQuery({+ ...runtimeListOptions(wsId),+ enabled: canBindMachine,+ });+ const machineOptions = useMemo(+ () => [+ { value: "", label: t(($) => $.profiles.form.machine_placeholder) },+ ...buildRuntimeMachines(runtimes, { now: Date.now() }).flatMap((machine) =>+ machine.mode === "local" && machine.daemonId+ ? [{ value: machine.daemonId, label: machine.title }]+ : [],+ ),+ ],+ [runtimes, t],+ );+ const [bindingMachine, setBindingMachine] = useState("");const [values, setValues] = useState<ProfileFormValues>({displayName: profile?.display_name ?? "",@@ -795,6 +829,7 @@ function ProfileDetailsForm({try {if (mode === "create") {const created = await createProfile.mutateAsync({+ ...(daemonId ? { daemon_id: daemonId } : {}),display_name: values.displayName.trim(),runtime_type: family,command_name: commandName,@@ -807,6 +842,7 @@ function ProfileDetailsForm({const updated = await updateProfile.mutateAsync({profileId: profile.id,patch: {+ ...(canBindMachine && bindingMachine ? { daemon_id: bindingMachine } : {}),display_name: values.displayName.trim(),command_name: commandName,fixed_args: fixedArgs,@@ -817,8 +853,14 @@ function ProfileDetailsForm({onSaved(updated);}} catch (err) {- // 409 from create/patch means the display name collides.- if (err instanceof ApiError && err.status === 409) {+ const conflictCode =+ err instanceof ApiError && err.body &&+ typeof err.body === "object" && "code" in err.body+ ? err.body.code : undefined;+ if (+ err instanceof ApiError && err.status === 409 &&+ conflictCode !== "runtime_profile_machine_conflict"+ ) {setDuplicateName(true);return;}@@ -869,6 +911,43 @@ function ProfileDetailsForm({</h3>)}+ {canBindMachine && (+ <div className="space-y-1.5">+ <Label+ htmlFor={`${idPrefix}-machine`}+ className="text-caption text-muted-foreground"+ >+ {t(($) => $.profiles.form.machine_label)}+ </Label>+ <Select+ items={machineOptions}+ value={bindingMachine}+ onValueChange={(value) => {+ setBindingMachine(value ?? "");+ }}+ disabled={submitting}+ >+ <SelectTrigger+ id={`${idPrefix}-machine`}+ className="w-full"+ aria-describedby={`${idPrefix}-machine-hint`}+ >+ <SelectValue placeholder={t(($) => $.profiles.form.machine_placeholder)} />+ </SelectTrigger>+ <SelectContent>+ {machineOptions.map((machine) => (+ <SelectItem key={machine.value} value={machine.value}>+ {machine.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <p id={`${idPrefix}-machine-hint`} className="text-caption text-muted-foreground">+ {t(($) => $.profiles.form.machine_hint)}+ </p>+ </div>+ )}+<div className="space-y-1.5"><Label className="text-caption text-muted-foreground">{t(($) => $.profiles.form.family_label)}diff --git a/server/cmd/migrate/migrate_runtime_profile_daemon_test.go b/server/cmd/migrate/migrate_runtime_profile_daemon_test.gonew file mode 100644index 0000000000..44837b96e0--- /dev/null+++ b/server/cmd/migrate/migrate_runtime_profile_daemon_test.go@@ -0,0 +1,90 @@+package main++import (+ "context"+ "fmt"+ "math/rand/v2"+ "testing"+ "time"+)++func TestRuntimeProfileDaemonRenumberPreservesPreviewBindings(t *testing.T) {+ const version = "674_runtime_profile_daemon"+ const legacyVersion = "665_runtime_profile_daemon"+ for _, previouslyApplied := range []bool{false, true} {+ t.Run(fmt.Sprintf("previously_applied_%t", previouslyApplied), func(t *testing.T) {+ base := openTestPool(t)+ ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second)+ defer cancel()+ schema := createScratchSchema(t, ctx, base, "runtime_profile_daemon_")+ pool := openTestPoolWithSearchPath(t, schema)+ if _, err := pool.Exec(ctx, `+ CREATE TABLE runtime_profile (id TEXT PRIMARY KEY, display_name TEXT NOT NULL);+ INSERT INTO runtime_profile VALUES ('legacy', 'Keep this profile');+ CREATE TABLE schema_migrations (version TEXT PRIMARY KEY, applied_at TIMESTAMPTZ DEFAULT now())+ `); err != nil {+ t.Fatal(err)+ }+ if previouslyApplied {+ if _, err := pool.Exec(ctx, `+ ALTER TABLE runtime_profile ADD COLUMN daemon_id TEXT;+ UPDATE runtime_profile SET daemon_id = 'studio-mac' WHERE id = 'legacy'+ `); err != nil {+ t.Fatal(err)+ }+ if _, err := pool.Exec(ctx, "INSERT INTO schema_migrations (version) VALUES ($1)", legacyVersion); err != nil {+ t.Fatal(err)+ }+ }+ options := runOptions{+ Direction: "up", Files: realMigrationFiles(t, []string{version}, "up"),+ SchemaMigrationsTable: schema + ".schema_migrations",+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,+ Hooks: hooksForDirection("up"),+ }+ for range 2 {+ if err := runMigrations(ctx, pool, options); err != nil {+ t.Fatalf("apply renumbered migration: %v", err)+ }+ }+ var name string+ var daemonID *string+ if err := pool.QueryRow(ctx, "SELECT display_name, daemon_id FROM runtime_profile WHERE id = 'legacy'").Scan(&name, &daemonID); err != nil {+ t.Fatal(err)+ }+ if name != "Keep this profile" || (daemonID != nil) != previouslyApplied {+ t.Fatalf("profile changed: name=%q daemon_id=%v", name, daemonID)+ }+ if daemonID != nil && *daemonID != "studio-mac" {+ t.Fatalf("preview machine binding changed: %q", *daemonID)+ }+ for _, expected := range []struct {+ version string+ present bool+ }{{version, true}, {legacyVersion, previouslyApplied}} {+ var recorded bool+ if err := pool.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE version = $1)", expected.version).Scan(&recorded); err != nil || recorded != expected.present {+ t.Fatalf("migration %s recorded=%v, want %v: %v", expected.version, recorded, expected.present, err)+ }+ }+ options.Direction, options.Files = "down", realMigrationFiles(t, []string{version}, "down")+ options.Hooks = hooksForDirection("down")+ if err := runMigrations(ctx, pool, options); err != nil {+ t.Fatalf("rollback: %v", err)+ }+ var columns int+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.columns+ WHERE table_schema = $1 AND table_name = 'runtime_profile' AND column_name = 'daemon_id'`, schema).Scan(&columns); err != nil || columns != 0 {+ t.Fatalf("daemon_id columns after rollback=%d: %v", columns, err)+ }+ options.Direction, options.Files = "up", realMigrationFiles(t, []string{version}, "up")+ options.Hooks = hooksForDirection("up")+ if err := runMigrations(ctx, pool, options); err != nil {+ t.Fatalf("reapply after rollback: %v", err)+ }+ if err := pool.QueryRow(ctx, "SELECT display_name, daemon_id FROM runtime_profile WHERE id = 'legacy'").Scan(&name, &daemonID); err != nil || name != "Keep this profile" || daemonID != nil {+ t.Fatalf("profile after reapply: name=%q daemon_id=%v: %v", name, daemonID, err)+ }+ })+ }+}diff --git a/server/cmd/multica/cmd_runtime_profile.go b/server/cmd/multica/cmd_runtime_profile.goindex 7d29f099ac..13db4a7885 100644--- a/server/cmd/multica/cmd_runtime_profile.go+++ b/server/cmd/multica/cmd_runtime_profile.go@@ -13,6 +13,7 @@ import ("github.com/spf13/cobra""github.com/multica-ai/multica/server/internal/cli"+ "github.com/multica-ai/multica/server/internal/daemon""github.com/multica-ai/multica/server/pkg/agent")@@ -21,8 +22,8 @@ import (// A runtime profile lets a workspace declare a custom agent runtime built on// top of a supported protocol family (the routing backend) but launched via a// site-specific command_name (e.g. a wrapper that injects credentials). The-// profile lives server-side and is workspace-scoped; the daemon resolves the-// command_name on each host's PATH at registration time.+// profile lives server-side and is bound to one machine in the workspace;+// only that machine's daemon resolves command_name at registration time.//// `set-path` / `unset-path` are the per-machine escape hatch: they record a// profile_id -> absolute executable path mapping in this machine's local CLI@@ -88,6 +89,7 @@ func init() {runtimeProfileListCmd.Flags().String("output", "table", "Output format: table or json")// create+ runtimeProfileCreateCmd.Flags().String("daemon-id", "", "Machine for this profile (defaults to this machine)")runtimeProfileCreateCmd.Flags().String("runtime-type", "", "Base runtime compatibility target (e.g. pi or omp)")runtimeProfileCreateCmd.Flags().String("protocol-family", "", "Legacy base protocol family (use --runtime-type for Oh-My-Pi)")runtimeProfileCreateCmd.Flags().String("command-name", "", "Executable the daemon resolves on PATH (required)")@@ -96,6 +98,7 @@ func init() {runtimeProfileCreateCmd.Flags().String("output", "json", "Output format: table or json")// update+ runtimeProfileUpdateCmd.Flags().String("daemon-id", "", "Bind a legacy profile to this registered local machine")runtimeProfileUpdateCmd.Flags().String("display-name", "", "New display name")runtimeProfileUpdateCmd.Flags().String("command-name", "", "New command name")runtimeProfileUpdateCmd.Flags().String("description", "", "New description")@@ -204,6 +207,17 @@ func runRuntimeProfileCreate(cmd *cobra.Command, _ []string) error {"protocol_family": family,"command_name": commandName,}+ daemonID, _ := cmd.Flags().GetString("daemon-id")+ if daemonID = strings.TrimSpace(daemonID); daemonID == "" {+ daemonID = strings.TrimSpace(os.Getenv("MULTICA_DAEMON_ID"))+ }+ if daemonID == "" {+ daemonID, err = daemon.EnsureDaemonID(resolveProfile(cmd))+ if err != nil {+ return fmt.Errorf("resolve local machine: %w", err)+ }+ }+ body["daemon_id"] = daemonIDif runtimeType != "" {body["runtime_type"] = runtimeTypedelete(body, "protocol_family")@@ -226,6 +240,10 @@ func runRuntimeProfileUpdate(cmd *cobra.Command, args []string) error {profileID := args[0]body := map[string]any{}+ if cmd.Flags().Changed("daemon-id") {+ v, _ := cmd.Flags().GetString("daemon-id")+ body["daemon_id"] = v+ }if cmd.Flags().Changed("display-name") {v, _ := cmd.Flags().GetString("display-name")body["display_name"] = vdiff --git a/server/cmd/multica/cmd_runtime_profile_test.go b/server/cmd/multica/cmd_runtime_profile_test.goindex 21ae75bae1..5e047f932c 100644--- a/server/cmd/multica/cmd_runtime_profile_test.go+++ b/server/cmd/multica/cmd_runtime_profile_test.go@@ -33,6 +33,7 @@ func newProfileListTestCmd() *cobra.Command {func newProfileCreateTestCmd() *cobra.Command {cmd := &cobra.Command{Use: "create"}+ cmd.Flags().String("daemon-id", "", "")addCommonProfileFlags(cmd)cmd.Flags().String("protocol-family", "", "")cmd.Flags().String("runtime-type", "", "")@@ -45,6 +46,7 @@ func newProfileCreateTestCmd() *cobra.Command {func newProfileUpdateTestCmd() *cobra.Command {cmd := &cobra.Command{Use: "update"}+ cmd.Flags().String("daemon-id", "", "")addCommonProfileFlags(cmd)cmd.Flags().String("display-name", "", "")cmd.Flags().String("command-name", "", "")@@ -109,6 +111,7 @@ func TestRunRuntimeProfileCreate(t *testing.T) {redirectTestHome(t, t.TempDir())t.Setenv("MULTICA_TOKEN", "test-token")t.Setenv("MULTICA_WORKSPACE_ID", "ws-123")+ t.Setenv("MULTICA_DAEMON_ID", "local-machine")var gotMethod, gotPath stringvar gotBody map[string]any@@ -130,6 +133,9 @@ func TestRunRuntimeProfileCreate(t *testing.T) {if err := runRuntimeProfileCreate(cmd, nil); err != nil {t.Fatalf("runRuntimeProfileCreate: %v", err)}+ if gotBody["daemon_id"] != "local-machine" {+ t.Fatalf("wrong machine binding: %#v", gotBody)+ }if gotMethod != http.MethodPost {t.Errorf("method = %s, want POST", gotMethod)}@@ -149,6 +155,13 @@ func TestRunRuntimeProfileCreate(t *testing.T) {if _, present := gotBody["visibility"]; present {t.Errorf("visibility must not be sent by the CLI, got %#v", gotBody["visibility"])}+ _ = cmd.Flags().Set("daemon-id", "selected-machine")+ if err := runRuntimeProfileCreate(cmd, nil); err != nil {+ t.Fatal(err)+ }+ if gotBody["daemon_id"] != "selected-machine" {+ t.Fatalf("explicit machine ignored: %#v", gotBody)+ }}func TestRunRuntimeProfileCreateRejectsBadFamily(t *testing.T) {@@ -212,6 +225,15 @@ func TestRunRuntimeProfileUpdateOnlySendsChangedFlags(t *testing.T) {if _, ok := gotBody["visibility"]; ok {t.Errorf("visibility should not be sent when unchanged: %#v", gotBody)}+ bind := newProfileUpdateTestCmd()+ _ = bind.Flags().Set("daemon-id", "keep-machine")+ gotBody = nil+ if err := runRuntimeProfileUpdate(bind, []string{"prof-1"}); err != nil {+ t.Fatal(err)+ }+ if len(gotBody) != 1 || gotBody["daemon_id"] != "keep-machine" {+ t.Fatalf("binding-only update = %#v", gotBody)+ }}func TestRunRuntimeProfileUpdateNoFieldsErrors(t *testing.T) {diff --git a/server/cmd/server/chat_submission_teardown_test.go b/server/cmd/server/chat_submission_teardown_test.goindex e16f49fb17..9c5188d0ed 100644--- a/server/cmd/server/chat_submission_teardown_test.go+++ b/server/cmd/server/chat_submission_teardown_test.go@@ -93,10 +93,12 @@ func TestChatSubmissionProfileAndGCTeardown(t *testing.T) {for _, path := range []string{"profile", "gc"} {t.Run(path, func(t *testing.T) {fx := workspaceFixture(t)- runtimeID := fx.Runtime(t, "Submission "+path+" runtime", testutil.Cols{"owner_id": testUserID})+ daemonID := "submission-" + uuid.NewString()+ runtimeID := fx.Runtime(t, "Submission "+path+" runtime", testutil.Cols{"owner_id": testUserID, "daemon_id": daemonID, "runtime_mode": "local"})var profileID stringif path == "profile" {profile := submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "POST", "/api/workspaces/"+testWorkspaceID+"/runtime-profiles", map[string]any{+ "daemon_id": daemonID,"display_name": "Submission profile " + uuid.NewString(), "protocol_family": "codex", "command_name": "offline-submission-test",}, http.StatusCreated)profileID = profile["id"].(string)diff --git a/server/cmd/server/runtime_gc_test.go b/server/cmd/server/runtime_gc_test.goindex 2300e02378..a62ae8e822 100644--- a/server/cmd/server/runtime_gc_test.go+++ b/server/cmd/server/runtime_gc_test.go@@ -9,10 +9,12 @@ import ("testing""time"+ "github.com/google/uuid""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgconn""github.com/jackc/pgx/v5/pgxpool""github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -304,6 +306,7 @@ func TestRuntimeGC_ProfileBackedInstanceKeepsProfile(t *testing.T) {ctx := context.Background()profileID := createRuntimeGCFixtureProfile(t, ctx, "preserved")runtimeID := createRuntimeGCFixtureRuntime(t, ctx, "profile-backed")+ workspaceFixture(t).Exec(t, `UPDATE runtime_profile SET daemon_id = $2 WHERE id = $1`, profileID, "gc-bound-machine")if _, err := testPool.Exec(ctx, `UPDATE agent_runtime SET profile_id = $2 WHERE id = $1`, runtimeID, profileID); err != nil {t.Fatalf("bind runtime profile: %v", err)}@@ -324,6 +327,63 @@ func TestRuntimeGC_ProfileBackedInstanceKeepsProfile(t *testing.T) {}}+func TestRuntimeGC_LegacyProfileProtectsOnlyCreatorsMachines(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }+ for _, tc := range []struct {+ name, dependency string+ creatorOwns, noCreator, wantDeleted bool+ }{+ {name: "creator anchor", creatorOwns: true},+ {name: "other member copy", wantDeleted: true},+ {name: "unknown creator", noCreator: true, wantDeleted: true},+ {name: "other member active agent", dependency: "agent"},+ {name: "other member unfinished task", dependency: "task"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ fx := workspaceFixture(t)+ var creator any = testUserID+ if tc.noCreator {+ creator = nil+ } else if !tc.creatorOwns {+ creator = fx.User(t, "Profile creator", uuid.NewString()+"@example.com")+ fx.Member(t, testWorkspaceID, creator.(string), "member")+ }+ profile := fx.Insert(t, "runtime_profile", testutil.Cols{"workspace_id": testWorkspaceID, "display_name": "Legacy GC " + uuid.NewString(), "protocol_family": "codex", "command_name": "codex", "created_by": creator})+ runtime := fx.Runtime(t, "Legacy offline machine", testutil.Cols{"daemon_id": "legacy-gc-" + uuid.NewString(), "runtime_mode": "local", "profile_id": profile, "status": "offline", "last_seen_at": testutil.Raw("now()-interval '10 days'")})+ if tc.dependency != "" {+ cols := testutil.Cols{}+ if tc.dependency == "task" {+ cols["archived_at"] = testutil.Raw("now()")+ }+ agent := fx.Agent(t, "Protected agent", runtime, cols)+ if tc.dependency == "task" {+ fx.Task(t, agent, testutil.Cols{"runtime_id": runtime})+ }+ }+ candidates, err := db.New(testPool).ListStaleOfflineRuntimeGCCandidates(context.Background(), db.ListStaleOfflineRuntimeGCCandidatesParams{StaleSeconds: offlineRuntimeTTLSeconds, MaxPerTick: 1000})+ if err != nil {+ t.Fatal(err)+ }+ found := false+ for _, candidate := range candidates {+ found = found || candidate == parseUUID(runtime)+ }+ if found != tc.wantDeleted {+ t.Fatalf("GC candidate=%v, want %v", found, tc.wantDeleted)+ }+ result, err := gcRuntime(context.Background(), testPool, db.New(testPool), parseUUID(runtime))+ if err != nil || result.deleted != tc.wantDeleted {+ t.Fatalf("GC result=%+v, err=%v, want deleted=%v", result, err, tc.wantDeleted)+ }+ if n := fx.Count(t, `SELECT count(*) FROM agent_runtime WHERE id=$1`, runtime); (n == 0) != tc.wantDeleted {+ t.Fatalf("runtime rows=%d, want deleted=%v", n, tc.wantDeleted)+ }+ })+ }+}+func TestRuntimeGC_CrossWorkspaceAgentReferenceFailsClosed(t *testing.T) {if testPool == nil {t.Skip("no database connection")diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex 9f5af9bbc7..76e07b438d 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -1274,6 +1274,7 @@ func (c *Client) GetWorkspaceRepos(ctx context.Context, workspaceID string) (*Wotype RuntimeProfile struct {ID string `json:"id"`WorkspaceID string `json:"workspace_id"`+ DaemonID *string `json:"daemon_id"`DisplayName string `json:"display_name"`ProtocolFamily string `json:"protocol_family"`RuntimeType string `json:"runtime_type"`@@ -1296,9 +1297,9 @@ type RuntimeProfilesResponse struct {// Mirrors GetWorkspaceRepos. Callers must treat this as best-effort: an older// server with no profiles route returns 404, which the daemon swallows and// continues with built-in runtimes only.-func (c *Client) GetRuntimeProfiles(ctx context.Context, workspaceID string) (*RuntimeProfilesResponse, error) {+func (c *Client) GetRuntimeProfiles(ctx context.Context, workspaceID, daemonID string) (*RuntimeProfilesResponse, error) {var resp RuntimeProfilesResponse- if err := c.getJSON(ctx, fmt.Sprintf("/api/daemon/workspaces/%s/runtime-profiles", workspaceID), &resp); err != nil {+ if err := c.getJSON(ctx, fmt.Sprintf("/api/daemon/workspaces/%s/runtime-profiles?daemon_id=%s", workspaceID, url.QueryEscape(daemonID)), &resp); err != nil {return nil, err}return &resp, nildiff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 4c96f8562a..35c963c17f 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -3137,7 +3137,7 @@ func (d *Daemon) registerBuiltinRuntimesForWorkspaceLocked(ctx context.Context,// a transient 5xx would silently flip the daemon into thinking the workspace// has zero profiles).func (d *Daemon) appendProfileRuntimes(ctx context.Context, workspaceID string, runtimes *[]map[string]string, failedProfiles *[]map[string]string) string {- resp, err := d.client.GetRuntimeProfiles(ctx, workspaceID)+ resp, err := d.client.GetRuntimeProfiles(ctx, workspaceID, d.cfg.DaemonID)if err != nil {// Best-effort: never fail registration because profiles couldn't be// fetched. An older server with no profiles route returns 404.@@ -3922,7 +3922,7 @@ func (d *Daemon) refreshWorkspaceRuntimeProfiles(ctx context.Context, workspaceIrefreshCtx, cancel := context.WithTimeout(ctx, 30*time.Second)defer cancel()- resp, err := d.client.GetRuntimeProfiles(refreshCtx, workspaceID)+ resp, err := d.client.GetRuntimeProfiles(refreshCtx, workspaceID, d.cfg.DaemonID)if err != nil {// Older server (no profiles route) returns 404; let the on-demand caller// log the failure at debug level.diff --git a/server/internal/daemon/runtime_profile_test.go b/server/internal/daemon/runtime_profile_test.goindex 41d75aa593..19dfa26cf7 100644--- a/server/internal/daemon/runtime_profile_test.go+++ b/server/internal/daemon/runtime_profile_test.go@@ -35,10 +35,11 @@ func (e *osExecNotFound) Error() string { return "exec: " + e.cmd + ": not found// TestClient_GetRuntimeProfiles_RequestShape asserts the daemon GETs the// documented path and parses the server's runtime_profiles payload.func TestClient_GetRuntimeProfiles_RequestShape(t *testing.T) {- var gotMethod, gotPath string+ var gotMethod, gotPath, gotDaemon stringsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {gotMethod = r.MethodgotPath = r.URL.Path+ gotDaemon = r.URL.Query().Get("daemon_id")w.Header().Set("Content-Type", "application/json")_, _ = w.Write([]byte(`{"workspace_id":"ws-1",@@ -62,10 +63,13 @@ func TestClient_GetRuntimeProfiles_RequestShape(t *testing.T) {c := NewClient(srv.URL)c.SetToken("tok")- resp, err := c.GetRuntimeProfiles(context.Background(), "ws-1")+ resp, err := c.GetRuntimeProfiles(context.Background(), "ws-1", "daemon-1")if err != nil {t.Fatalf("GetRuntimeProfiles: %v", err)}+ if gotDaemon != "daemon-1" {+ t.Fatalf("daemon_id = %q", gotDaemon)+ }if gotMethod != http.MethodGet {t.Errorf("method = %q, want GET", gotMethod)}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 6aebc6b7e3..36d1412a3b 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -472,6 +472,7 @@ func (h *Handler) inheritMachineCustomName(ctx context.Context, q *db.Queries, r}var errRuntimeProfileDisabled = errors.New("runtime profile is disabled")+var errRuntimeProfileMachine = errors.New("runtime profile belongs to another machine")// upsertRuntimeWithProfile serializes custom-runtime registration with profile// deletion. The profile row remains KEY SHARE locked until the runtime upsert@@ -497,11 +498,32 @@ func (h *Handler) upsertRuntimeWithProfile(if err != nil {return row, profile, fmt.Errorf("lock runtime profile: %w", err)}+ params := build(profile)+ if profile.DaemonID.Valid {+ if profile.DaemonID != params.DaemonID {+ return row, profile, errRuntimeProfileMachine+ }+ } else {+ // Existing unscoped profiles may refresh only instances that already+ // exist. A stale daemon must not spread a legacy profile to a new host.+ found, err := qtx.RuntimeProfileHasDaemonInstance(ctx, db.RuntimeProfileHasDaemonInstanceParams{+ WorkspaceID: workspaceID,+ ProfileID: profileID,+ DaemonID: params.DaemonID,+ })+ if err != nil {+ return row, profile, err+ }+ if !found {+ return row, profile, errRuntimeProfileMachine+ }+ }+if !profile.Enabled {return row, profile, errRuntimeProfileDisabled}- row, err = qtx.UpsertAgentRuntimeWithProfile(ctx, build(profile))+ row, err = qtx.UpsertAgentRuntimeWithProfile(ctx, params)if err != nil {// The profile lookup above already turned "unknown profile" into// ErrNoRows; here ErrNoRows can only mean the ownership fence@@ -842,6 +864,11 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusConflict, "runtime profile is disabled: "+runtime.ProfileID)return}+ if errors.Is(err, errRuntimeProfileMachine) {+ // Old daemons may still submit a previously shared profile.+ // Ignore it without blocking built-in runtime registration.+ continue+ }if err != nil {obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.RuntimeFailed(uuidToString(ownerID),diff --git a/server/internal/handler/daemon_runtime_ownership_review_test.go b/server/internal/handler/daemon_runtime_ownership_review_test.goindex 4dbc4c4174..ff23975c96 100644--- a/server/internal/handler/daemon_runtime_ownership_review_test.go+++ b/server/internal/handler/daemon_runtime_ownership_review_test.go@@ -104,6 +104,7 @@ func TestDaemonRegister_ConcurrentDifferentProvidersAndProfilesHaveOneOwner(t *tsecond := dbfx.User(t, "race second owner", "race-"+uuid.NewString()+"@example.com")dbfx.Member(t, testWorkspaceID, second, "member")daemonID := "race-" + uuid.NewString()+ dbfx.Exec(t, `UPDATE runtime_profile SET daemon_id = $1 WHERE id = $2`, daemonID, profileID)t.Cleanup(func() {testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE workspace_id = $1 AND daemon_id = $2`, testWorkspaceID, daemonID)})diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.goindex 067412f4f4..6235daaba1 100644--- a/server/internal/handler/daemon_test.go+++ b/server/internal/handler/daemon_test.go@@ -797,6 +797,7 @@ func TestDaemonRegister_RecordsRuntimeProfileRegistrationFailure(t *testing.T) {}ctx := context.Background()profileID := insertRuntimeProfileFixture(t, ctx, "Missing Custom Codex", "codex", "missing-codex")+ dbfx.Exec(t, `UPDATE runtime_profile SET daemon_id = $1 WHERE id = $2`, "test-daemon-profile-failure", profileID)req := newOwnerDaemonRequest("POST", "/api/daemon/register", map[string]any{"workspace_id": testWorkspaceID,@@ -4959,7 +4960,7 @@ func TestDaemonRegister_ProfileUsesStoredRuntimeIdentity(t *testing.T) {}ctx := context.Background()profileID := insertRuntimeProfileFixture(t, ctx, "Custom OMP", "pi", "wrapper")- if _, err := testPool.Exec(ctx, `UPDATE runtime_profile SET runtime_type = 'omp' WHERE id = $1`, profileID); err != nil {+ if _, err := testPool.Exec(ctx, `UPDATE runtime_profile SET runtime_type = 'omp', daemon_id = 'test-omp-profile' WHERE id = $1`, profileID); err != nil {t.Fatal(err)}req := newOwnerDaemonRequest("POST", "/api/daemon/register", map[string]any{diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.goindex 71b2a91226..1a109dbaf7 100644--- a/server/internal/handler/runtime.go+++ b/server/internal/handler/runtime.go@@ -943,6 +943,7 @@ func (h *Handler) runtimeLiveProfile(ctx context.Context, rt db.AgentRuntime) (dfunc profileInstanceDeleteRefusal(rt db.AgentRuntime, profile db.RuntimeProfile, blockers profileInstanceBlockers) map[string]any {known := blockers.knownttlDays := service.OfflineRuntimeTTLDays()+ keepsLegacyAnchor := !profile.DaemonID.Valid && profile.CreatedBy.Valid && profile.CreatedBy == rt.OwnerIDname := rt.Nameif rt.CustomName.Valid && strings.TrimSpace(rt.CustomName.String) != "" {name = rt.CustomName.String@@ -956,6 +957,8 @@ func profileInstanceDeleteRefusal(rt db.AgentRuntime, profile db.RuntimeProfile,parts := []string{lead}switch {+ case keepsLegacyAnchor:+ parts = append(parts, "Edit this custom runtime and choose the machine that should keep it. Unused copies on other machines are removed when the binding is saved; move or archive their agents and finish pending tasks first. Until then, this legacy instance is kept so the machine can reconnect.")case rt.Status == "online":parts = append(parts, fmt.Sprintf("It is still online, so its daemon would register it again. Stop that daemon first; Multica then removes the runtime automatically after %d days offline, once no agent is bound to it and nothing is still running on it.",@@ -1009,6 +1012,10 @@ func profileInstanceDeleteRefusal(rt db.AgentRuntime, profile db.RuntimeProfile,"last_seen_at": timestampToPtr(rt.LastSeenAt),"auto_cleanup_after_days": ttlDays,}+ if keepsLegacyAnchor {+ resp["auto_cleanup_after_days"] = 0+ resp["requires_machine_binding"] = true+ }if known {resp["active_agent_count"] = len(blockers.agents)resp["undrained_task_count"] = blockers.undrainedTasksdiff --git a/server/internal/handler/runtime_custom_name_test.go b/server/internal/handler/runtime_custom_name_test.goindex 195d2933da..f36b3b05ef 100644--- a/server/internal/handler/runtime_custom_name_test.go+++ b/server/internal/handler/runtime_custom_name_test.go@@ -241,6 +241,7 @@ func TestDaemonRegister_FailedProfileInheritsMachineName(t *testing.T) {// A custom runtime profile fails to resolve on this machine.profileID := insertRuntimeProfileFixture(t, ctx, "Custom Codex", "codex", "missing-codex")+ dbfx.Exec(t, `UPDATE runtime_profile SET daemon_id = $1 WHERE id = $2`, daemonID, profileID)w := httptest.NewRecorder()req := newDaemonTokenRequest("POST", "/api/daemon/register", map[string]any{diff --git a/server/internal/handler/runtime_delete_guidance_test.go b/server/internal/handler/runtime_delete_guidance_test.goindex 7e5f14f617..416b24ea9b 100644--- a/server/internal/handler/runtime_delete_guidance_test.go+++ b/server/internal/handler/runtime_delete_guidance_test.go@@ -97,6 +97,52 @@ func TestDeleteAgentRuntime_OfflineProfileInstanceRefusalPointsAtAutoCleanup(t *}}+func TestDeleteAgentRuntime_LegacyProfileExplainsMachineBinding(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ runtimeID, profileID := createProfileBackedRuntime(t, context.Background(), "Legacy machine guidance")+ dbfx.Exec(t, `UPDATE runtime_profile SET daemon_id = NULL WHERE id = $1`, profileID)+ dbfx.Exec(t, `UPDATE agent_runtime SET status = 'offline' WHERE id = $1`, runtimeID)+ req := withURLParam(newRequest("DELETE", "/", nil), "runtimeId", runtimeID)+ w := httptest.NewRecorder()+ testHandler.DeleteAgentRuntime(w, req)+ if w.Code != http.StatusConflict {+ t.Fatalf("status=%d: %s", w.Code, w.Body.String())+ }+ body := decodeConflict(t, w)+ msg := conflictMessage(t, body)+ if !strings.Contains(msg, "choose the machine") || strings.Contains(msg, "automatically after") {+ t.Fatalf("incorrect legacy guidance: %s", msg)+ }+ if body["requires_machine_binding"] != true || body["auto_cleanup_after_days"] != float64(0) {+ t.Fatalf("cleanup contract=%v", body)+ }+}++func TestDeleteAgentRuntime_OtherMembersLegacyCopyExplainsAutoCleanup(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ runtimeID, profileID := createProfileBackedRuntime(t, context.Background(), "Legacy other member")+ creator := dbfx.User(t, "Another creator", "legacy-creator-"+profileID+"@example.com")+ dbfx.Exec(t, `UPDATE runtime_profile SET daemon_id = NULL, created_by = $2 WHERE id = $1`, profileID, creator)+ dbfx.Exec(t, `UPDATE agent_runtime SET status = 'offline' WHERE id = $1`, runtimeID)+ req := withURLParam(newRequest("DELETE", "/", nil), "runtimeId", runtimeID)+ w := httptest.NewRecorder()+ testHandler.DeleteAgentRuntime(w, req)+ if w.Code != http.StatusConflict {+ t.Fatalf("status=%d: %s", w.Code, w.Body.String())+ }+ body := decodeConflict(t, w)+ if msg := conflictMessage(t, body); !strings.Contains(msg, "automatically after") {+ t.Fatalf("other member copy must remain eligible for automatic cleanup: %s", msg)+ }+ if body["requires_machine_binding"] == true || body["auto_cleanup_after_days"] != float64(service.OfflineRuntimeTTLDays()) {+ t.Fatalf("cleanup contract=%v", body)+ }+}+// Online is the one case where waiting is not the answer — the daemon would// re-register the row immediately. The refusal has to say so instead of// promising a cleanup that will not happen.diff --git a/server/internal/handler/runtime_profile.go b/server/internal/handler/runtime_profile.goindex 0a784e279b..bff02dc2d4 100644--- a/server/internal/handler/runtime_profile.go+++ b/server/internal/handler/runtime_profile.go@@ -11,6 +11,7 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/pkg/agent"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -19,10 +20,10 @@ import (// Custom Runtime Profiles (MUL-3284)//-// A runtime_profile is a workspace-level, team-shared definition of a custom-// runtime — e.g. an in-house Codex wrapper. Daemons pull the enabled profiles-// for their workspace, resolve command_name on PATH, and register an-// agent_runtime instance carrying the profile_id. The profile only changes how+// A runtime_profile defines a custom runtime on one machine in a workspace.+// Its daemon pulls the enabled profiles bound to that machine, resolves+// command_name on PATH, and registers an agent_runtime instance carrying the+// profile_id. The profile only changes how// a runtime is launched/displayed. runtime_type selects a supported compatibility// target, and its descriptor determines the underlying protocol_family.//@@ -33,6 +34,7 @@ import (type RuntimeProfileResponse struct {ID string `json:"id"`WorkspaceID string `json:"workspace_id"`+ DaemonID *string `json:"daemon_id"`DisplayName string `json:"display_name"`ProtocolFamily string `json:"protocol_family"`RuntimeType string `json:"runtime_type"`@@ -57,6 +59,7 @@ func runtimeProfileToResponse(p db.RuntimeProfile) RuntimeProfileResponse {return RuntimeProfileResponse{ID: uuidToString(p.ID),WorkspaceID: uuidToString(p.WorkspaceID),+ DaemonID: textToPtr(p.DaemonID),DisplayName: p.DisplayName,ProtocolFamily: p.ProtocolFamily,RuntimeType: agent.ProfileRuntimeType(p.RuntimeType, p.ProtocolFamily),@@ -116,6 +119,7 @@ func validateRuntimeProfileCommandName(commandName string) error {}type createRuntimeProfileRequest struct {+ DaemonID string `json:"daemon_id"`DisplayName string `json:"display_name"`ProtocolFamily string `json:"protocol_family"`RuntimeType string `json:"runtime_type"`@@ -125,7 +129,7 @@ type createRuntimeProfileRequest struct {Enabled *bool `json:"enabled"`}-// CreateRuntimeProfile creates a workspace runtime profile. Admin-gated by the+// CreateRuntimeProfile creates a machine-bound runtime profile. Admin-gated by the// router. protocol_family is validated against the agent backend whitelist.func (h *Handler) CreateRuntimeProfile(w http.ResponseWriter, r *http.Request) {wsID := strings.TrimSpace(chi.URLParam(r, "id"))@@ -189,8 +193,35 @@ func (h *Handler) CreateRuntimeProfile(w http.ResponseWriter, r *http.Request) {enabled = *req.Enabled}+ // Older clients omit the machine. Prefer the caller's sole local machine;+ // never guess between multiple machines owned by that caller.+ req.DaemonID = strings.TrimSpace(req.DaemonID)+ machineParams := db.ListRuntimeProfileMachinesParams{WorkspaceID: wsUUID}+ if req.DaemonID != "" {+ machineParams.DaemonID = strToText(req.DaemonID)+ } else {+ machineParams.OwnerID = member.UserID+ }+ machines, err := h.Queries.ListRuntimeProfileMachines(r.Context(), machineParams)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to resolve runtime profile machine")+ return+ }+ if req.DaemonID == "" && len(machines) == 0 {+ machines, err = h.Queries.ListRuntimeProfileMachines(r.Context(), db.ListRuntimeProfileMachinesParams{WorkspaceID: wsUUID})+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to resolve runtime profile machine")+ return+ }+ }+ if len(machines) != 1 {+ writeError(w, http.StatusBadRequest, "daemon_id must select a registered local machine; upgrade your client or pass daemon_id explicitly")+ return+ }+profile, err := h.Queries.CreateRuntimeProfile(r.Context(), db.CreateRuntimeProfileParams{WorkspaceID: wsUUID,+ DaemonID: machines[0],DisplayName: req.DisplayName,ProtocolFamily: req.ProtocolFamily,RuntimeType: req.RuntimeType,@@ -271,6 +302,7 @@ func (h *Handler) GetRuntimeProfile(w http.ResponseWriter, r *http.Request) {}type updateRuntimeProfileRequest struct {+ DaemonID *string `json:"daemon_id"`RuntimeType *string `json:"runtime_type"`ProtocolFamily *string `json:"protocol_family"`DisplayName *string `json:"display_name"`@@ -341,8 +373,30 @@ func (h *Handler) UpdateRuntimeProfile(w http.ResponseWriter, r *http.Request) {params.Enabled = pgtype.Bool{Bool: *req.Enabled, Valid: true}}- profile, err := h.Queries.UpdateRuntimeProfile(r.Context(), params)+ var profile db.RuntimeProfile+ var err error+ var binding profileMachineBindingResult+ if req.DaemonID != nil {+ machine := strings.TrimSpace(*req.DaemonID)+ if machine == "" {+ writeError(w, http.StatusBadRequest, "daemon_id cannot be empty")+ return+ }+ params.DaemonID = strToText(machine)+ binding, err = h.bindRuntimeProfileMachine(r.Context(), params)+ profile = binding.profile+ } else {+ profile, err = h.Queries.UpdateRuntimeProfile(r.Context(), params)+ }if err != nil {+ if errors.Is(err, errProfileMachineUnavailable) {+ writeError(w, http.StatusBadRequest, err.Error())+ return+ }+ if errors.Is(err, errProfileMachineImmutable) || errors.Is(err, errProfileMachineInUse) {+ writeJSON(w, http.StatusConflict, map[string]any{"error": err.Error(), "code": "runtime_profile_machine_conflict"})+ return+ }if errors.Is(err, pgx.ErrNoRows) {writeError(w, http.StatusNotFound, "runtime profile not found")return@@ -357,6 +411,12 @@ func (h *Handler) UpdateRuntimeProfile(w http.ResponseWriter, r *http.Request) {}profileID := uuidToString(profile.ID)+ for _, runtime := range binding.removed {+ h.NotifyRuntimeGone(uuidToString(runtime.ID))+ }+ for _, teardown := range binding.teardowns {+ h.publishRuntimeTeardown(r.Context(), teardown, wsID, uuidToString(member.UserID))+ }h.requestDaemonRuntimeProfileRefresh(wsID, profileID)h.publish(protocol.EventDaemonRegister, wsID, "member", uuidToString(member.UserID), map[string]any{"runtime_profile_id": profileID,@@ -661,7 +721,42 @@ func (h *Handler) DaemonListRuntimeProfiles(w http.ResponseWriter, r *http.Requereturn}- profiles, err := h.Queries.ListEnabledRuntimeProfilesForWorkspace(r.Context(), wsUUID)+ daemonID := strings.TrimSpace(r.URL.Query().Get("daemon_id"))+ if tokenDaemonID := middleware.DaemonIDFromContext(r.Context()); tokenDaemonID != "" {+ if daemonID != "" && daemonID != tokenDaemonID {+ writeError(w, http.StatusForbidden, "daemon identity mismatch")+ return+ }+ daemonID = tokenDaemonID+ }++ if daemonID != "" {+ owners, err := h.Queries.ListRuntimeOwnersByDaemon(r.Context(), db.ListRuntimeOwnersByDaemonParams{+ WorkspaceID: wsUUID,+ DaemonID: strToText(daemonID),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to resolve runtime profile machine")+ return+ }+ for _, owner := range owners {+ if !daemonRuntimeBindingAllowed(r, strToText(daemonID), owner.OwnerID) {+ writeError(w, http.StatusNotFound, "machine not found")+ return+ }+ }+ }+ var profiles []db.RuntimeProfile+ var err error+ if daemonID == "" && requestUserID(r) != "" {+ userID, ok := parseUUIDOrBadRequest(w, requestUserID(r), "user id")+ if !ok {+ return+ }+ profiles, err = h.Queries.ListEnabledRuntimeProfilesForOwner(r.Context(), db.ListEnabledRuntimeProfilesForOwnerParams{WorkspaceID: wsUUID, OwnerID: userID})+ } else {+ profiles, err = h.Queries.ListEnabledRuntimeProfilesForDaemon(r.Context(), db.ListEnabledRuntimeProfilesForDaemonParams{WorkspaceID: wsUUID, DaemonID: strToText(daemonID)})+ }if err != nil {writeError(w, http.StatusInternalServerError, "failed to list runtime profiles")returndiff --git a/server/internal/handler/runtime_profile_binding.go b/server/internal/handler/runtime_profile_binding.gonew file mode 100644index 0000000000..b0c81c113a--- /dev/null+++ b/server/internal/handler/runtime_profile_binding.go@@ -0,0 +1,90 @@+package handler++import (+ "context"+ "errors"+ "fmt"++ "github.com/multica-ai/multica/server/internal/service"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++var (+ errProfileMachineUnavailable = errors.New("select a registered local machine")+ errProfileMachineImmutable = errors.New("this profile already belongs to another machine; create a new profile to use it there")+ errProfileMachineInUse = errors.New("move or archive agents on other machines and finish their pending tasks before binding this profile")+)++type profileMachineBindingResult struct {+ profile db.RuntimeProfile+ removed []db.AgentRuntime+ teardowns []service.RuntimeTeardownResult+}++// Binding and retirement are atomic. The profile lock also prevents a stale+// daemon from recreating a removed instance before the binding commits.+func (h *Handler) bindRuntimeProfileMachine(ctx context.Context, params db.UpdateRuntimeProfileParams) (profileMachineBindingResult, error) {+ var result profileMachineBindingResult+ tx, err := h.TxStarter.Begin(ctx)+ if err != nil {+ return result, err+ }+ defer tx.Rollback(ctx)+ qtx := h.Queries.WithTx(tx)+ profile, err := qtx.LockRuntimeProfileForDelete(ctx, db.LockRuntimeProfileForDeleteParams{ID: params.ID, WorkspaceID: params.WorkspaceID})+ if err != nil {+ return result, err+ }+ if profile.DaemonID.Valid && profile.DaemonID != params.DaemonID {+ return result, errProfileMachineImmutable+ }+ machines, err := qtx.ListRuntimeProfileMachines(ctx, db.ListRuntimeProfileMachinesParams{WorkspaceID: params.WorkspaceID, DaemonID: params.DaemonID})+ if err != nil {+ return result, err+ }+ if len(machines) != 1 {+ return result, errProfileMachineUnavailable+ }+ ids, err := qtx.ListAgentRuntimeIDsByProfile(ctx, db.ListAgentRuntimeIDsByProfileParams{ProfileID: params.ID, WorkspaceID: params.WorkspaceID})+ if err != nil {+ return result, err+ }+ for _, id := range ids {+ rt, err := qtx.GetAgentRuntime(ctx, id)+ if err != nil {+ return result, err+ }+ if rt.DaemonID == params.DaemonID {+ continue+ }+ agents, err := qtx.ListUserAgentsByRuntimeForUpdate(ctx, id)+ if err != nil {+ return result, err+ }+ for _, agent := range agents {+ if !agent.ArchivedAt.Valid {+ return result, fmt.Errorf("%w (%s)", errProfileMachineInUse, rt.Name)+ }+ }+ teardown, err := service.TeardownRuntime(ctx, qtx, id, service.RuntimeTeardownOptions{CancelNonTerminalTasks: false})+ if errors.Is(err, service.ErrRuntimeNotDrained) || errors.Is(err, service.ErrRuntimeWorkspaceMismatch) {+ return result, fmt.Errorf("%w (%s)", errProfileMachineInUse, rt.Name)+ }+ if err != nil {+ return result, err+ }+ if err := qtx.DeleteAgentRuntime(ctx, id); err != nil {+ return result, err+ }+ result.removed = append(result.removed, rt)+ result.teardowns = append(result.teardowns, teardown)+ }+ result.profile, err = qtx.UpdateRuntimeProfile(ctx, params)+ if err != nil {+ return result, err+ }+ if err := tx.Commit(ctx); err != nil {+ return result, err+ }+ return result, nil+}diff --git a/server/internal/handler/runtime_profile_binding_test.go b/server/internal/handler/runtime_profile_binding_test.gonew file mode 100644index 0000000000..4399f5b716--- /dev/null+++ b/server/internal/handler/runtime_profile_binding_test.go@@ -0,0 +1,111 @@+package handler++import (+ "context"+ "net/http"+ "testing"++ "github.com/google/uuid"+ "github.com/multica-ai/multica/server/internal/testutil"+)++func TestRuntimeProfileBinding_RetiresCopiesAndPreservesHistory(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ id := insertRuntimeProfileFixture(t, context.Background(), "Bind existing "+uuid.NewString(), "codex", "codex")+ target := "keep-" + uuid.NewString()+ kept := dbfx.Runtime(t, "Kept custom runtime", testutil.Cols{"runtime_mode": "local", "daemon_id": target, "profile_id": id})+ removed := dbfx.Runtime(t, "Other machine", testutil.Cols{"runtime_mode": "local", "daemon_id": "remove-" + uuid.NewString(), "profile_id": id})+ archived := dbfx.Agent(t, "Archived agent", removed, testutil.Cols{"archived_at": testutil.Raw("now()")})+ history := dbfx.Task(t, archived, testutil.Cols{"runtime_id": removed, "status": "completed", "completed_at": testutil.Raw("now()")})+ req := withURLParams(newRequest("PATCH", "/", map[string]any{"daemon_id": target, "display_name": "Bound " + uuid.NewString()}), "id", testWorkspaceID, "profileId", id)+ var out RuntimeProfileResponse+ testutil.Call(t, testHandler.UpdateRuntimeProfile, req).Want(http.StatusOK).JSON(&out)+ if out.DaemonID == nil || *out.DaemonID != target {+ t.Fatalf("binding = %+v", out)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_runtime WHERE profile_id=$1`, id); n != 1 {+ t.Fatalf("remaining copies=%d", n)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_runtime WHERE id=$1`, kept); n != 1 {+ t.Fatal("target instance removed")+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent WHERE id=$1 AND runtime_id IS NULL`, archived); n != 1 {+ t.Fatal("archived agent lost")+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE id=$1 AND runtime_id IS NULL`, history); n != 1 {+ t.Fatal("task history lost")+ }+ // Once bound, a stale daemon cannot restore the removed copy.+ testutil.Call(t, testHandler.DaemonRegister, newOwnerDaemonRequest("POST", "/", map[string]any{+ "workspace_id": testWorkspaceID, "daemon_id": "new-other-" + uuid.NewString(),+ "failed_profiles": []map[string]any{{"profile_id": id, "reason": "missing command"}},+ })).Want(http.StatusOK)+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_runtime WHERE profile_id=$1`, id); n != 1 {+ t.Fatal("stale registration restored a copy")+ }+ move := withURLParams(newRequest("PATCH", "/", map[string]any{"daemon_id": "different-machine"}), "id", testWorkspaceID, "profileId", id)+ testutil.Call(t, testHandler.UpdateRuntimeProfile, move).Want(http.StatusConflict)+ if n := dbfx.Count(t, `SELECT count(*) FROM runtime_profile WHERE id=$1 AND daemon_id=$2`, id, target); n != 1 {+ t.Fatal("bound profile moved to another machine")+ }+}++func TestRuntimeProfileBinding_BlocksActiveDependenciesAndRollsBack(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ for _, kind := range []string{"agent", "task"} {+ t.Run(kind, func(t *testing.T) {+ id := insertRuntimeProfileFixture(t, context.Background(), "In use "+uuid.NewString(), "codex", "codex")+ target := "target-" + uuid.NewString()+ dbfx.Runtime(t, "Target", testutil.Cols{"runtime_mode": "local", "daemon_id": target, "profile_id": id})+ busy := dbfx.Runtime(t, "Busy machine", testutil.Cols{"runtime_mode": "local", "daemon_id": "busy-" + uuid.NewString(), "profile_id": id})+ agentCols := testutil.Cols{}+ if kind == "task" {+ agentCols["archived_at"] = testutil.Raw("now()")+ }+ agent := dbfx.Agent(t, "Busy agent", busy, agentCols)+ if kind == "task" {+ dbfx.Task(t, agent, testutil.Cols{"runtime_id": busy})+ }+ req := withURLParams(newRequest("PATCH", "/", map[string]any{"daemon_id": target, "display_name": "Must roll back"}), "id", testWorkspaceID, "profileId", id)+ testutil.Call(t, testHandler.UpdateRuntimeProfile, req).Want(http.StatusConflict)+ if n := dbfx.Count(t, `SELECT count(*) FROM runtime_profile WHERE id=$1 AND daemon_id IS NULL AND display_name <> 'Must roll back'`, id); n != 1 {+ t.Fatal("failed binding changed profile")+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_runtime WHERE profile_id=$1`, id); n != 2 {+ t.Fatal("failed binding removed an instance")+ }+ // Editing settings without selecting a machine does not retire copies,+ // even when binding would be blocked by work on another machine.+ renamed := "Edited without binding " + uuid.NewString()+ edit := withURLParams(newRequest("PATCH", "/", map[string]any{+ "display_name": renamed, "command_name": "wrapper", "fixed_args": []string{"--model", "custom"},+ }), "id", testWorkspaceID, "profileId", id)+ var out RuntimeProfileResponse+ testutil.Call(t, testHandler.UpdateRuntimeProfile, edit).Want(http.StatusOK).JSON(&out)+ if out.DaemonID != nil || out.DisplayName != renamed || out.CommandName != "wrapper" {+ t.Fatalf("settings-only edit=%+v", out)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_runtime WHERE profile_id=$1`, id); n != 2 {+ t.Fatal("settings-only edit removed an instance")+ }+ })+ }+}++func TestRuntimeProfileBinding_RejectsUnknownOrForeignMachine(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ id := insertRuntimeProfileFixture(t, context.Background(), "Scope "+uuid.NewString(), "codex", "codex")+ ws := dbfx.Workspace(t, "Other workspace", "binding-other-"+uuid.NewString())+ foreign := "foreign-" + uuid.NewString()+ dbfx.Runtime(t, "Foreign", testutil.Cols{"workspace_id": ws, "daemon_id": foreign, "runtime_mode": "local"})+ for _, target := range []string{"", foreign, "missing-" + uuid.NewString()} {+ req := withURLParams(newRequest("PATCH", "/", map[string]any{"daemon_id": target}), "id", testWorkspaceID, "profileId", id)+ testutil.Call(t, testHandler.UpdateRuntimeProfile, req).Want(http.StatusBadRequest)+ }+}diff --git a/server/internal/handler/runtime_profile_handler_test.go b/server/internal/handler/runtime_profile_handler_test.goindex d3db76fc6d..ff55f2a515 100644--- a/server/internal/handler/runtime_profile_handler_test.go+++ b/server/internal/handler/runtime_profile_handler_test.go@@ -8,6 +8,7 @@ import ("strings""testing"+ "github.com/multica-ai/multica/server/internal/testutil"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -346,10 +347,12 @@ func TestCreateRuntimeProfile_ForcesWorkspaceVisibility(t *testing.T) {if testHandler == nil {t.Skip("database not available")}+ dbfx.Runtime(t, "Profile creation machine", testutil.Cols{"daemon_id": "profile-create-machine", "runtime_mode": "local"})ctx := context.Background()w := httptest.NewRecorder()req := newRequest("POST", "/api/workspaces/"+testWorkspaceID+"/runtime-profiles", map[string]any{+ "daemon_id": "profile-create-machine","display_name": "Visibility Forced Profile","protocol_family": "codex","command_name": "vis-forced-codex",@@ -385,6 +388,7 @@ func TestCreateRuntimeProfile_ValidatesCommandAndFixedArgs(t *testing.T) {if testHandler == nil {t.Skip("database not available")}+ dbfx.Runtime(t, "Profile creation machine", testutil.Cols{"daemon_id": "profile-create-machine", "runtime_mode": "local"})cases := []struct {name stringcommandName string@@ -413,6 +417,7 @@ func TestCreateRuntimeProfile_ValidatesCommandAndFixedArgs(t *testing.T) {t.Run(tc.name, func(t *testing.T) {w := httptest.NewRecorder()req := newRequest("POST", "/api/workspaces/"+testWorkspaceID+"/runtime-profiles", map[string]any{+ "daemon_id": "profile-create-machine","display_name": "Validation " + tc.name,"protocol_family": "codex","command_name": tc.commandName,@@ -443,6 +448,7 @@ func TestCreateRuntimeProfile_RuntimeIdentity(t *testing.T) {if testHandler == nil {t.Skip("database not available")}+ dbfx.Runtime(t, "Profile creation machine", testutil.Cols{"daemon_id": "profile-create-machine", "runtime_mode": "local"})for _, tc := range []struct {name, target, family, wantFamily stringstatus int@@ -456,6 +462,7 @@ func TestCreateRuntimeProfile_RuntimeIdentity(t *testing.T) {} {t.Run(tc.name, func(t *testing.T) {req := withURLParam(newRequest("POST", "/", map[string]any{+ "daemon_id": "profile-create-machine","display_name": "Identity " + tc.name, "runtime_type": tc.target,"protocol_family": tc.family, "command_name": "wrapper", "fixed_args": []string{"launch"},}), "id", testWorkspaceID)diff --git a/server/internal/handler/runtime_profile_machine_test.go b/server/internal/handler/runtime_profile_machine_test.gonew file mode 100644index 0000000000..6405f1b99a--- /dev/null+++ b/server/internal/handler/runtime_profile_machine_test.go@@ -0,0 +1,192 @@+package handler++import (+ "context"+ "net/http"+ "testing"++ "github.com/google/uuid"+ "github.com/multica-ai/multica/server/internal/testutil"+)++func TestRuntimeProfile_MachineIsolation(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ a, b := "machine-a-"+uuid.NewString(), "machine-b-"+uuid.NewString()+ for _, id := range []string{a, b} {+ dbfx.Runtime(t, id, testutil.Cols{"daemon_id": id, "runtime_mode": "local"})+ }+ create := withURLParam(newRequest("POST", "/", map[string]any{+ "display_name": "Scoped " + uuid.NewString(), "runtime_type": "codex", "command_name": "same-command", "daemon_id": a,+ }), "id", testWorkspaceID)+ var profile RuntimeProfileResponse+ testutil.Call(t, testHandler.CreateRuntimeProfile, create).Want(http.StatusCreated).JSON(&profile)+ dbfx.Cleanup(t, `DELETE FROM runtime_profile WHERE id = $1`, profile.ID)+ dbfx.Cleanup(t, `DELETE FROM agent_runtime WHERE profile_id = $1`, profile.ID)+ if profile.DaemonID == nil || *profile.DaemonID != a {+ t.Fatalf("missing machine binding: %+v", profile)+ }++ for _, machine := range []string{a, b} {+ req := withURLParam(newDaemonTokenRequest("GET", "/", nil, testWorkspaceID, machine), "workspaceId", testWorkspaceID)+ var out struct {+ Profiles []RuntimeProfileResponse `json:"runtime_profiles"`+ }+ testutil.Call(t, testHandler.DaemonListRuntimeProfiles, req).Want(http.StatusOK).JSON(&out)+ found := false+ for _, p := range out.Profiles {+ if p.ID == profile.ID {+ found = true+ }+ }+ if found != (machine == a) {+ t.Fatalf("machine %s sees profile = %v", machine, found)+ }+ }+ mismatch := withURLParam(newDaemonTokenRequest("GET", "/?daemon_id="+a, nil, testWorkspaceID, b), "workspaceId", testWorkspaceID)+ testutil.Call(t, testHandler.DaemonListRuntimeProfiles, mismatch).Want(http.StatusForbidden)++ // Older PAT daemons retain the owner's profiles; registration fences each machine.+ other := dbfx.User(t, "Other profile owner", "other-profile-"+uuid.NewString()+"@example.com")+ dbfx.Member(t, testWorkspaceID, other, "member")+ foreignMachine := "foreign-owner-" + uuid.NewString()+ dbfx.Runtime(t, "Other owner's machine", testutil.Cols{"daemon_id": foreignMachine, "runtime_mode": "local", "owner_id": other})+ foreignProfile := insertRuntimeProfileFixture(t, context.Background(), "Other owner's profile "+uuid.NewString(), "codex", "codex")+ dbfx.Exec(t, `UPDATE runtime_profile SET created_by=$2, daemon_id=$3 WHERE id=$1`, foreignProfile, other, foreignMachine)+ old := withURLParam(newOwnerDaemonRequest("GET", "/", nil), "workspaceId", testWorkspaceID)+ var oldOut struct {+ Profiles []RuntimeProfileResponse `json:"runtime_profiles"`+ }+ testutil.Call(t, testHandler.DaemonListRuntimeProfiles, old).Want(http.StatusOK).JSON(&oldOut)+ if len(oldOut.Profiles) != 1 || oldOut.Profiles[0].ID != profile.ID {+ t.Fatalf("older daemon lost its profile: %+v", oldOut.Profiles)+ }++ // Identical commands on B must not create either an online instance or an+ // offline error placeholder. Its built-in runtime still registers normally.+ for _, failed := range []bool{false, true} {+ body := map[string]any{+ "workspace_id": testWorkspaceID, "daemon_id": b,+ "runtimes": []map[string]any{{"name": "Builtin", "type": "codex", "status": "online"}},+ }+ if failed {+ body["failed_profiles"] = []map[string]any{{"profile_id": profile.ID, "reason": "missing command"}}+ } else {+ body["runtimes"] = append(body["runtimes"].([]map[string]any), map[string]any{"name": "Custom", "type": "codex", "profile_id": profile.ID, "status": "online"})+ }+ testutil.Call(t, testHandler.DaemonRegister, newOwnerDaemonRequest("POST", "/", body)).Want(http.StatusOK)+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_runtime WHERE profile_id = $1 AND daemon_id = $2`, profile.ID, b); n != 0 {+ t.Fatalf("copied profile to B: %d", n)+ }+ }+ testutil.Call(t, testHandler.DaemonRegister, newOwnerDaemonRequest("POST", "/", map[string]any{+ "workspace_id": testWorkspaceID, "daemon_id": a,+ "runtimes": []map[string]any{{"name": "Custom", "type": "codex", "profile_id": profile.ID, "status": "online"}},+ })).Want(http.StatusOK)+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_runtime WHERE profile_id = $1 AND daemon_id = $2 AND status = 'online'`, profile.ID, a); n != 1 {+ t.Fatalf("owner machine instance count = %d", n)+ }+ dbfx.Exec(t, `UPDATE runtime_profile SET enabled = false WHERE id = $1`, profile.ID)+ testutil.Call(t, testHandler.DaemonRegister, newOwnerDaemonRequest("POST", "/", map[string]any{+ "workspace_id": testWorkspaceID, "daemon_id": b,+ "runtimes": []map[string]any{+ {"name": "Builtin", "type": "codex", "status": "online"},+ {"name": "Custom", "type": "codex", "profile_id": profile.ID, "status": "online"},+ },+ })).Want(http.StatusOK)++ // A token for another workspace cannot read this workspace's profile set.+ foreign := withURLParam(newDaemonTokenRequest("GET", "/", nil, uuid.NewString(), a), "workspaceId", testWorkspaceID)+ testutil.Call(t, testHandler.DaemonListRuntimeProfiles, foreign).Want(http.StatusNotFound)+ otherReq := withURLParam(newRequest("GET", "/?daemon_id="+a, nil), "workspaceId", testWorkspaceID)+ otherReq.Header.Set("X-User-ID", other)+ testutil.Call(t, testHandler.DaemonListRuntimeProfiles, otherReq).Want(http.StatusNotFound)+}++func TestCreateRuntimeProfile_RequiresRegisteredMachine(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ // A daemon from another workspace is not a valid target here.+ foreignWS := dbfx.Workspace(t, "Foreign profile workspace", "foreign-profile-"+uuid.NewString())+ foreign := "foreign-" + uuid.NewString()+ dbfx.Runtime(t, "Foreign machine", testutil.Cols{"workspace_id": foreignWS, "daemon_id": foreign, "runtime_mode": "local"})+ for _, machine := range []string{"unknown-" + uuid.NewString(), foreign} {+ req := withURLParam(newRequest("POST", "/", map[string]any{+ "display_name": "Invalid machine " + uuid.NewString(), "runtime_type": "codex", "command_name": "wrapper", "daemon_id": machine,+ }), "id", testWorkspaceID)+ testutil.Call(t, testHandler.CreateRuntimeProfile, req).Want(http.StatusBadRequest)+ }+}++func TestCreateRuntimeProfile_OlderClientRequiresUnambiguousMachine(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ws := dbfx.Workspace(t, "Single machine workspace", "single-machine-"+uuid.NewString())+ dbfx.Member(t, ws, testUserID, "owner")+ machine := "only-machine-" + uuid.NewString()+ dbfx.Runtime(t, "Only local machine", testutil.Cols{"workspace_id": ws, "daemon_id": machine, "runtime_mode": "local"})+ create := func() *http.Request {+ return withURLParam(newRequest("POST", "/", map[string]any{+ "display_name": "Older client " + uuid.NewString(), "runtime_type": "codex", "command_name": "wrapper",+ }), "id", ws)+ }+ var out RuntimeProfileResponse+ testutil.Call(t, testHandler.CreateRuntimeProfile, create()).Want(http.StatusCreated).JSON(&out)+ dbfx.Cleanup(t, `DELETE FROM runtime_profile WHERE id = $1`, out.ID)+ if out.DaemonID == nil || *out.DaemonID != machine {+ t.Fatalf("wrong inferred machine: %+v", out)+ }+ // Older clients can still create on their sole owned machine in a multi-member workspace.+ other := dbfx.User(t, "Another machine owner", "machine-owner-"+uuid.NewString()+"@example.com")+ dbfx.Member(t, ws, other, "member")+ dbfx.Runtime(t, "Other local machine", testutil.Cols{"workspace_id": ws, "daemon_id": "other-" + uuid.NewString(), "runtime_mode": "local", "owner_id": other})+ var second RuntimeProfileResponse+ testutil.Call(t, testHandler.CreateRuntimeProfile, create()).Want(http.StatusCreated).JSON(&second)+ dbfx.Cleanup(t, `DELETE FROM runtime_profile WHERE id = $1`, second.ID)+ if second.DaemonID == nil || *second.DaemonID != machine {+ t.Fatalf("wrong owned machine: %+v", second)+ }+ dbfx.Runtime(t, "Second owned machine", testutil.Cols{"workspace_id": ws, "daemon_id": "second-" + uuid.NewString(), "runtime_mode": "local"})+ testutil.Call(t, testHandler.CreateRuntimeProfile, create()).Want(http.StatusBadRequest)+}++func TestRuntimeProfile_LegacyDoesNotSpread(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ id := insertRuntimeProfileFixture(t, context.Background(), "Legacy "+uuid.NewString(), "codex", "wrapper")+ existing, fresh := "legacy-existing-"+uuid.NewString(), "legacy-fresh-"+uuid.NewString()+ dbfx.Runtime(t, "Legacy instance", testutil.Cols{"daemon_id": existing, "runtime_mode": "local", "profile_id": id})+ dbfx.Runtime(t, "Fresh machine", testutil.Cols{"daemon_id": fresh, "runtime_mode": "local"})+ for _, machine := range []string{existing, fresh} {+ req := withURLParam(newOwnerDaemonRequest("GET", "/?daemon_id="+machine, nil), "workspaceId", testWorkspaceID)+ var out struct {+ Profiles []RuntimeProfileResponse `json:"runtime_profiles"`+ }+ testutil.Call(t, testHandler.DaemonListRuntimeProfiles, req).Want(http.StatusOK).JSON(&out)+ found := false+ for _, p := range out.Profiles {+ if p.ID == id {+ found = true+ }+ }+ if found != (machine == existing) {+ t.Fatalf("legacy profile on %s = %v", machine, found)+ }+ }+ testutil.Call(t, testHandler.DaemonRegister, newOwnerDaemonRequest("POST", "/", map[string]any{+ "workspace_id": testWorkspaceID, "daemon_id": existing,+ "runtimes": []map[string]any{{"name": "Legacy", "type": "codex", "profile_id": id, "status": "online"}},+ })).Want(http.StatusOK)+ req := newOwnerDaemonRequest("POST", "/", map[string]any{+ "workspace_id": testWorkspaceID, "daemon_id": fresh,+ "failed_profiles": []map[string]any{{"profile_id": id, "reason": "missing"}},+ })+ testutil.Call(t, testHandler.DaemonRegister, req).Want(http.StatusOK)+ if n := dbfx.Count(t, `SELECT count(*) FROM agent_runtime WHERE profile_id = $1 AND daemon_id = $2`, id, fresh); n != 0 {+ t.Fatalf("legacy placeholder spread: %d", n)+ }+}diff --git a/server/internal/handler/runtime_unbind_delete_test.go b/server/internal/handler/runtime_unbind_delete_test.goindex 665a101c63..ec318ece47 100644--- a/server/internal/handler/runtime_unbind_delete_test.go+++ b/server/internal/handler/runtime_unbind_delete_test.go@@ -609,6 +609,7 @@ func createProfileBackedRuntime(t *testing.T, ctx context.Context, name string)`, testWorkspaceID, "daemon-"+profileID, name, name+" device", testUserID, profileID).Scan(&runtimeID); err != nil {t.Fatalf("insert profile-backed runtime: %v", err)}+ dbfx.Exec(t, `UPDATE runtime_profile SET daemon_id = $2 WHERE id = $1`, profileID, "daemon-"+profileID)t.Cleanup(func() {testPool.Exec(context.Background(), `DELETE FROM agent WHERE runtime_id = $1`, runtimeID)diff --git a/server/migrations/674_runtime_profile_daemon.down.sql b/server/migrations/674_runtime_profile_daemon.down.sqlnew file mode 100644index 0000000000..096ef31fda--- /dev/null+++ b/server/migrations/674_runtime_profile_daemon.down.sql@@ -0,0 +1 @@+ALTER TABLE runtime_profile DROP COLUMN IF EXISTS daemon_id;diff --git a/server/migrations/674_runtime_profile_daemon.up.sql b/server/migrations/674_runtime_profile_daemon.up.sqlnew file mode 100644index 0000000000..b9185dd798--- /dev/null+++ b/server/migrations/674_runtime_profile_daemon.up.sql@@ -0,0 +1,3 @@+-- NULL identifies existing profiles; only their existing daemons may refresh them.+-- Do not infer a creating machine from replicated runtime rows.+ALTER TABLE runtime_profile ADD COLUMN IF NOT EXISTS daemon_id TEXT;diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 121b1021f7..c6504d8a2d 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -1614,6 +1614,7 @@ type RuntimeProfile struct {CreatedAt pgtype.Timestamptz `json:"created_at"`UpdatedAt pgtype.Timestamptz `json:"updated_at"`RuntimeType string `json:"runtime_type"`+ DaemonID pgtype.Text `json:"daemon_id"`}type RuntimeRateLimit struct {diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.goindex b2c75ef59d..de8288d573 100644--- a/server/pkg/db/generated/runtime.sql.go+++ b/server/pkg/db/generated/runtime.sql.go@@ -753,6 +753,12 @@ SELECT EXISTS (WHERE agent_runtime.id = $1AND status = 'offline'AND last_seen_at < now() - make_interval(secs => $2::double precision)+ AND NOT EXISTS (+ SELECT 1 FROM runtime_profile p+ WHERE p.id = agent_runtime.profile_id AND p.workspace_id = agent_runtime.workspace_id+ AND p.daemon_id IS NULL+ AND p.created_by = agent_runtime.owner_id+ )AND NOT EXISTS (SELECT 1FROM agent@@ -1237,6 +1243,12 @@ const listStaleOfflineRuntimeGCCandidates = `-- name: ListStaleOfflineRuntimeGCCSELECT id FROM agent_runtimeWHERE status = 'offline'AND last_seen_at < now() - make_interval(secs => $1::double precision)+ AND NOT EXISTS (+ SELECT 1 FROM runtime_profile p+ WHERE p.id = agent_runtime.profile_id AND p.workspace_id = agent_runtime.workspace_id+ AND p.daemon_id IS NULL+ AND p.created_by = agent_runtime.owner_id+ )AND NOT EXISTS (SELECT 1FROM agentdiff --git a/server/pkg/db/generated/runtime_profile.sql.go b/server/pkg/db/generated/runtime_profile.sql.goindex e7870004f2..222218061a 100644--- a/server/pkg/db/generated/runtime_profile.sql.go+++ b/server/pkg/db/generated/runtime_profile.sql.go@@ -23,9 +23,10 @@ INSERT INTO runtime_profile (visibility,created_by,enabled,- runtime_type-) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)-RETURNING id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at, runtime_type+ runtime_type,+ daemon_id+) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)+RETURNING id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at, runtime_type, daemon_id`type CreateRuntimeProfileParams struct {@@ -39,10 +40,11 @@ type CreateRuntimeProfileParams struct {CreatedBy pgtype.UUID `json:"created_by"`Enabled bool `json:"enabled"`RuntimeType string `json:"runtime_type"`+ DaemonID pgtype.Text `json:"daemon_id"`}-// Custom Runtime profiles (MUL-3284). Workspace-level definitions of a custom-// runtime; see migration 120 for the table. Relational integrity (workspace,+// Custom Runtime profiles, bound to one daemon in a workspace.+// See migrations 120 and 674. Relational integrity (workspace,// created_by) is enforced in the application layer — there are no DB FKs.func (q *Queries) CreateRuntimeProfile(ctx context.Context, arg CreateRuntimeProfileParams) (RuntimeProfile, error) {row := q.db.QueryRow(ctx, createRuntimeProfile,@@ -56,6 +58,7 @@ func (q *Queries) CreateRuntimeProfile(ctx context.Context, arg CreateRuntimeProarg.CreatedBy,arg.Enabled,arg.RuntimeType,+ arg.DaemonID,)var i RuntimeProfileerr := row.Scan(@@ -72,6 +75,7 @@ func (q *Queries) CreateRuntimeProfile(ctx context.Context, arg CreateRuntimePro&i.CreatedAt,&i.UpdatedAt,&i.RuntimeType,+ &i.DaemonID,)return i, err}@@ -148,7 +152,7 @@ func (q *Queries) DeleteRuntimeProfile(ctx context.Context, arg DeleteRuntimePro}const getRuntimeProfile = `-- name: GetRuntimeProfile :one-SELECT id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at, runtime_type FROM runtime_profile+SELECT id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at, runtime_type, daemon_id FROM runtime_profileWHERE id = $1`@@ -169,12 +173,13 @@ func (q *Queries) GetRuntimeProfile(ctx context.Context, id pgtype.UUID) (Runtim&i.CreatedAt,&i.UpdatedAt,&i.RuntimeType,+ &i.DaemonID,)return i, err}const getRuntimeProfileForWorkspace = `-- name: GetRuntimeProfileForWorkspace :one-SELECT id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at, runtime_type FROM runtime_profile+SELECT id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at, runtime_type, daemon_id FROM runtime_profileWHERE id = $1 AND workspace_id = $2`@@ -200,6 +205,7 @@ func (q *Queries) GetRuntimeProfileForWorkspace(ctx context.Context, arg GetRunt&i.CreatedAt,&i.UpdatedAt,&i.RuntimeType,+ &i.DaemonID,)return i, err}@@ -379,8 +385,114 @@ func (q *Queries) ListAgentRuntimeIDsByProfile(ctx context.Context, arg ListAgenreturn items, nil}+const listEnabledRuntimeProfilesForDaemon = `-- name: ListEnabledRuntimeProfilesForDaemon :many+SELECT p.id, p.workspace_id, p.display_name, p.protocol_family, p.command_name, p.description, p.fixed_args, p.visibility, p.created_by, p.enabled, p.created_at, p.updated_at, p.runtime_type, p.daemon_id FROM runtime_profile p+WHERE p.workspace_id = $1 AND p.enabled = true+ AND (p.daemon_id = $2 OR (p.daemon_id IS NULL AND EXISTS (+ SELECT 1 FROM agent_runtime ar+ WHERE ar.workspace_id = p.workspace_id AND ar.profile_id = p.id+ AND ar.daemon_id = $2+ )))+ORDER BY p.created_at ASC+`++type ListEnabledRuntimeProfilesForDaemonParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ DaemonID pgtype.Text `json:"daemon_id"`+}++// Legacy profiles may refresh existing instances, but cannot spread further.+func (q *Queries) ListEnabledRuntimeProfilesForDaemon(ctx context.Context, arg ListEnabledRuntimeProfilesForDaemonParams) ([]RuntimeProfile, error) {+ rows, err := q.db.Query(ctx, listEnabledRuntimeProfilesForDaemon, arg.WorkspaceID, arg.DaemonID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []RuntimeProfile{}+ for rows.Next() {+ var i RuntimeProfile+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.DisplayName,+ &i.ProtocolFamily,+ &i.CommandName,+ &i.Description,+ &i.FixedArgs,+ &i.Visibility,+ &i.CreatedBy,+ &i.Enabled,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.RuntimeType,+ &i.DaemonID,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listEnabledRuntimeProfilesForOwner = `-- name: ListEnabledRuntimeProfilesForOwner :many+SELECT p.id, p.workspace_id, p.display_name, p.protocol_family, p.command_name, p.description, p.fixed_args, p.visibility, p.created_by, p.enabled, p.created_at, p.updated_at, p.runtime_type, p.daemon_id FROM runtime_profile p+WHERE p.workspace_id = $1 AND p.enabled = true+ AND (p.created_by = $2 OR EXISTS (+ SELECT 1 FROM agent_runtime ar+ WHERE ar.workspace_id = p.workspace_id AND ar.owner_id = $2+ AND ((p.daemon_id IS NOT NULL AND ar.daemon_id = p.daemon_id)+ OR (p.daemon_id IS NULL AND ar.profile_id = p.id))+ ))+ORDER BY p.created_at ASC+`++type ListEnabledRuntimeProfilesForOwnerParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ OwnerID pgtype.UUID `json:"owner_id"`+}++// Older PAT daemons do not send their machine ID. Registration still enforces+// the profile's machine binding, so returning this owner's set cannot copy it.+func (q *Queries) ListEnabledRuntimeProfilesForOwner(ctx context.Context, arg ListEnabledRuntimeProfilesForOwnerParams) ([]RuntimeProfile, error) {+ rows, err := q.db.Query(ctx, listEnabledRuntimeProfilesForOwner, arg.WorkspaceID, arg.OwnerID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []RuntimeProfile{}+ for rows.Next() {+ var i RuntimeProfile+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.DisplayName,+ &i.ProtocolFamily,+ &i.CommandName,+ &i.Description,+ &i.FixedArgs,+ &i.Visibility,+ &i.CreatedBy,+ &i.Enabled,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.RuntimeType,+ &i.DaemonID,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listEnabledRuntimeProfilesForWorkspace = `-- name: ListEnabledRuntimeProfilesForWorkspace :many-SELECT id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at, runtime_type FROM runtime_profile+SELECT id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at, runtime_type, daemon_id FROM runtime_profileWHERE workspace_id = $1 AND enabled = trueORDER BY created_at ASC`@@ -410,6 +522,7 @@ func (q *Queries) ListEnabledRuntimeProfilesForWorkspace(ctx context.Context, wo&i.CreatedAt,&i.UpdatedAt,&i.RuntimeType,+ &i.DaemonID,); err != nil {return nil, err}@@ -421,8 +534,44 @@ func (q *Queries) ListEnabledRuntimeProfilesForWorkspace(ctx context.Context, woreturn items, nil}+const listRuntimeProfileMachines = `-- name: ListRuntimeProfileMachines :many+SELECT DISTINCT daemon_id FROM agent_runtime+WHERE workspace_id = $1 AND runtime_mode = 'local'+ AND daemon_id IS NOT NULL AND daemon_id <> ''+ AND ($2::uuid IS NULL OR owner_id = $2::uuid)+ AND ($3::text IS NULL OR daemon_id = $3::text)+LIMIT 2+`++type ListRuntimeProfileMachinesParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ OwnerID pgtype.UUID `json:"owner_id"`+ DaemonID pgtype.Text `json:"daemon_id"`+}++// A bounded result lets older clients infer an unambiguous machine.+func (q *Queries) ListRuntimeProfileMachines(ctx context.Context, arg ListRuntimeProfileMachinesParams) ([]pgtype.Text, error) {+ rows, err := q.db.Query(ctx, listRuntimeProfileMachines, arg.WorkspaceID, arg.OwnerID, arg.DaemonID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.Text{}+ for rows.Next() {+ var daemon_id pgtype.Text+ if err := rows.Scan(&daemon_id); err != nil {+ return nil, err+ }+ items = append(items, daemon_id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listRuntimeProfiles = `-- name: ListRuntimeProfiles :many-SELECT id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at, runtime_type FROM runtime_profile+SELECT id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at, runtime_type, daemon_id FROM runtime_profileWHERE workspace_id = $1ORDER BY created_at ASC`@@ -450,6 +599,7 @@ func (q *Queries) ListRuntimeProfiles(ctx context.Context, workspaceID pgtype.UU&i.CreatedAt,&i.UpdatedAt,&i.RuntimeType,+ &i.DaemonID,); err != nil {return nil, err}@@ -462,7 +612,7 @@ func (q *Queries) ListRuntimeProfiles(ctx context.Context, workspaceID pgtype.UU}const lockRuntimeProfileForDelete = `-- name: LockRuntimeProfileForDelete :one-SELECT id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at, runtime_type FROM runtime_profile+SELECT id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at, runtime_type, daemon_id FROM runtime_profileWHERE id = $1 AND workspace_id = $2FOR UPDATE`@@ -491,12 +641,13 @@ func (q *Queries) LockRuntimeProfileForDelete(ctx context.Context, arg LockRunti&i.CreatedAt,&i.UpdatedAt,&i.RuntimeType,+ &i.DaemonID,)return i, err}const lockRuntimeProfileForRegistration = `-- name: LockRuntimeProfileForRegistration :one-SELECT id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at, runtime_type FROM runtime_profile+SELECT id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at, runtime_type, daemon_id FROM runtime_profileWHERE id = $1 AND workspace_id = $2FOR KEY SHARE`@@ -527,10 +678,31 @@ func (q *Queries) LockRuntimeProfileForRegistration(ctx context.Context, arg Loc&i.CreatedAt,&i.UpdatedAt,&i.RuntimeType,+ &i.DaemonID,)return i, err}+const runtimeProfileHasDaemonInstance = `-- name: RuntimeProfileHasDaemonInstance :one+SELECT EXISTS (+ SELECT 1 FROM agent_runtime+ WHERE workspace_id = $1 AND profile_id = $2 AND daemon_id = $3+) AS present+`++type RuntimeProfileHasDaemonInstanceParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ProfileID pgtype.UUID `json:"profile_id"`+ DaemonID pgtype.Text `json:"daemon_id"`+}++func (q *Queries) RuntimeProfileHasDaemonInstance(ctx context.Context, arg RuntimeProfileHasDaemonInstanceParams) (bool, error) {+ row := q.db.QueryRow(ctx, runtimeProfileHasDaemonInstance, arg.WorkspaceID, arg.ProfileID, arg.DaemonID)+ var present bool+ err := row.Scan(&present)+ return present, err+}+const updateRuntimeProfile = `-- name: UpdateRuntimeProfile :oneUPDATE runtime_profileSET display_name = COALESCE($1, display_name),@@ -539,9 +711,10 @@ SET display_name = COALESCE($1, display_name),fixed_args = COALESCE($4, fixed_args),visibility = COALESCE($5, visibility),enabled = COALESCE($6, enabled),+ daemon_id = COALESCE($7, daemon_id),updated_at = now()-WHERE id = $7 AND workspace_id = $8-RETURNING id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at, runtime_type+WHERE id = $8 AND workspace_id = $9+RETURNING id, workspace_id, display_name, protocol_family, command_name, description, fixed_args, visibility, created_by, enabled, created_at, updated_at, runtime_type, daemon_id`type UpdateRuntimeProfileParams struct {@@ -551,6 +724,7 @@ type UpdateRuntimeProfileParams struct {FixedArgs []byte `json:"fixed_args"`Visibility pgtype.Text `json:"visibility"`Enabled pgtype.Bool `json:"enabled"`+ DaemonID pgtype.Text `json:"daemon_id"`ID pgtype.UUID `json:"id"`WorkspaceID pgtype.UUID `json:"workspace_id"`}@@ -567,6 +741,7 @@ func (q *Queries) UpdateRuntimeProfile(ctx context.Context, arg UpdateRuntimeProarg.FixedArgs,arg.Visibility,arg.Enabled,+ arg.DaemonID,arg.ID,arg.WorkspaceID,)@@ -585,6 +760,7 @@ func (q *Queries) UpdateRuntimeProfile(ctx context.Context, arg UpdateRuntimePro&i.CreatedAt,&i.UpdatedAt,&i.RuntimeType,+ &i.DaemonID,)return i, err}diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sqlindex 583b4633d6..5688f5d89d 100644--- a/server/pkg/db/queries/runtime.sql+++ b/server/pkg/db/queries/runtime.sql@@ -623,6 +623,12 @@ WHERE id = $1;SELECT id FROM agent_runtimeWHERE status = 'offline'AND last_seen_at < now() - make_interval(secs => @stale_seconds::double precision)+ AND NOT EXISTS (+ SELECT 1 FROM runtime_profile p+ WHERE p.id = agent_runtime.profile_id AND p.workspace_id = agent_runtime.workspace_id+ AND p.daemon_id IS NULL+ AND p.created_by = agent_runtime.owner_id+ )AND NOT EXISTS (SELECT 1FROM agent@@ -649,6 +655,12 @@ SELECT EXISTS (WHERE agent_runtime.id = @idAND status = 'offline'AND last_seen_at < now() - make_interval(secs => @stale_seconds::double precision)+ AND NOT EXISTS (+ SELECT 1 FROM runtime_profile p+ WHERE p.id = agent_runtime.profile_id AND p.workspace_id = agent_runtime.workspace_id+ AND p.daemon_id IS NULL+ AND p.created_by = agent_runtime.owner_id+ )AND NOT EXISTS (SELECT 1FROM agentdiff --git a/server/pkg/db/queries/runtime_profile.sql b/server/pkg/db/queries/runtime_profile.sqlindex 18082cd480..2c49e990e8 100644--- a/server/pkg/db/queries/runtime_profile.sql+++ b/server/pkg/db/queries/runtime_profile.sql@@ -1,5 +1,5 @@--- Custom Runtime profiles (MUL-3284). Workspace-level definitions of a custom--- runtime; see migration 120 for the table. Relational integrity (workspace,+-- Custom Runtime profiles, bound to one daemon in a workspace.+-- See migrations 120 and 674. Relational integrity (workspace,-- created_by) is enforced in the application layer — there are no DB FKs.-- name: CreateRuntimeProfile :one@@ -13,8 +13,9 @@ INSERT INTO runtime_profile (visibility,created_by,enabled,- runtime_type-) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)+ runtime_type,+ daemon_id+) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)RETURNING *;-- name: GetRuntimeProfile :one@@ -53,6 +54,45 @@ SELECT * FROM runtime_profileWHERE workspace_id = $1 AND enabled = trueORDER BY created_at ASC;+-- name: ListEnabledRuntimeProfilesForDaemon :many+-- Legacy profiles may refresh existing instances, but cannot spread further.+SELECT p.* FROM runtime_profile p+WHERE p.workspace_id = @workspace_id AND p.enabled = true+ AND (p.daemon_id = @daemon_id OR (p.daemon_id IS NULL AND EXISTS (+ SELECT 1 FROM agent_runtime ar+ WHERE ar.workspace_id = p.workspace_id AND ar.profile_id = p.id+ AND ar.daemon_id = @daemon_id+ )))+ORDER BY p.created_at ASC;++-- name: ListEnabledRuntimeProfilesForOwner :many+-- Older PAT daemons do not send their machine ID. Registration still enforces+-- the profile's machine binding, so returning this owner's set cannot copy it.+SELECT p.* FROM runtime_profile p+WHERE p.workspace_id = @workspace_id AND p.enabled = true+ AND (p.created_by = @owner_id OR EXISTS (+ SELECT 1 FROM agent_runtime ar+ WHERE ar.workspace_id = p.workspace_id AND ar.owner_id = @owner_id+ AND ((p.daemon_id IS NOT NULL AND ar.daemon_id = p.daemon_id)+ OR (p.daemon_id IS NULL AND ar.profile_id = p.id))+ ))+ORDER BY p.created_at ASC;++-- name: RuntimeProfileHasDaemonInstance :one+SELECT EXISTS (+ SELECT 1 FROM agent_runtime+ WHERE workspace_id = @workspace_id AND profile_id = @profile_id AND daemon_id = @daemon_id+) AS present;++-- name: ListRuntimeProfileMachines :many+-- A bounded result lets older clients infer an unambiguous machine.+SELECT DISTINCT daemon_id FROM agent_runtime+WHERE workspace_id = @workspace_id AND runtime_mode = 'local'+ AND daemon_id IS NOT NULL AND daemon_id <> ''+ AND (sqlc.narg('owner_id')::uuid IS NULL OR owner_id = sqlc.narg('owner_id')::uuid)+ AND (sqlc.narg('daemon_id')::text IS NULL OR daemon_id = sqlc.narg('daemon_id')::text)+LIMIT 2;+-- name: UpdateRuntimeProfile :one-- Partial update via COALESCE: NULL args leave the column unchanged. The-- protocol_family is intentionally NOT updatable — changing the underlying@@ -65,6 +105,7 @@ SET display_name = COALESCE(sqlc.narg('display_name'), display_name),fixed_args = COALESCE(sqlc.narg('fixed_args'), fixed_args),visibility = COALESCE(sqlc.narg('visibility'), visibility),enabled = COALESCE(sqlc.narg('enabled'), enabled),+ daemon_id = COALESCE(sqlc.narg('daemon_id'), daemon_id),updated_at = now()WHERE id = @id AND workspace_id = @workspace_idRETURNING *;