Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6710: fix(runtimes): revoke access when making runtime private (#7580)
m2keloopd908e4882d9b
diff --git a/apps/docs/content/docs/daemon-runtimes.fr.mdx b/apps/docs/content/docs/daemon-runtimes.fr.mdxindex a5f7a9a706..08f77b330b 100644--- a/apps/docs/content/docs/daemon-runtimes.fr.mdx+++ b/apps/docs/content/docs/daemon-runtimes.fr.mdx@@ -79,6 +79,10 @@ Un runtime local est **privé** par défaut : seul le propriétaire du runtime pSeul le propriétaire du runtime peut le rendre **public** — les administrateurs de l'espace de travail peuvent renommer ou supprimer un runtime, mais le partager relève de la décision du propriétaire. Les autres membres de l'espace de travail peuvent alors eux aussi sélectionner ce runtime ; cela ne partage pas les identifiants de connexion de l'outil de codage IA sous-jacent — cela permet seulement aux membres d'acheminer les exécutions de leurs agents vers cet ordinateur.+Lorsque le propriétaire rend un runtime public à nouveau **privé**, Multica affiche d'abord les agents et les exécutions actives concernés, y compris les conversations de création d'agents avec Agent Builder. La confirmation dissocie les agents de ces autres membres, annule leurs exécutions en file d'attente, distribuées, en cours, en attente d'un répertoire local ou différées avec le motif `runtime_access_revoked`, et met en pause les automatisations actives assignées aux agents dissociés. Les agents et exécutions du propriétaire ne sont pas affectés. Si le plan change, une nouvelle confirmation est nécessaire ; des modifications simultanées de la discussion peuvent nécessiter de réessayer. Pour reprendre le travail, associez l'agent à un runtime accessible, puis reprenez explicitement ses automatisations en pause.++L'annulation conserve l'historique de discussion et enregistre sur le serveur les données de restauration du brouillon et des pièces jointes. Les versions web et bureau utilisent l'interface de restauration existante ; la version mobile ne propose pas encore cette interface. Une exécution démarrée sans sortie attend l'accusé d'annulation du daemon ou la fin du délai de finalisation du serveur avant de décider si la saisie doit être restaurée. Un daemon connecté reçoit l'annulation lors de sa vérification habituelle. Si l'ordinateur est hors ligne, l'accès côté serveur est tout de même révoqué immédiatement, mais le processus local peut continuer jusqu'à sa reconnexion et à la réception de l'annulation ; le serveur ne peut pas garantir un arrêt à distance immédiat.+## Profils de runtime personnalisésSi votre équipe utilise un wrapper interne, un exécutable à version figée, ou a besoin d'arguments supplémentaires fixes pour un outil compatible, créez un **profil de runtime personnalisé**.diff --git a/apps/docs/content/docs/daemon-runtimes.ja.mdx b/apps/docs/content/docs/daemon-runtimes.ja.mdxindex 33572da8eb..c0c3e8d210 100644--- a/apps/docs/content/docs/daemon-runtimes.ja.mdx+++ b/apps/docs/content/docs/daemon-runtimes.ja.mdx@@ -79,6 +79,10 @@ multica daemon startランタイムを**公開**に変更できるのは所有者だけです。ワークスペースの管理者はランタイムの名前変更や削除はできますが、共有するかどうかは所有者が決めます。公開すると、ワークスペースの他のメンバーもこのランタイムを選べるようになります。これは基盤の AI コーディングツールのログイン認証情報を共有するものではなく、メンバーがエージェントの実行をこのコンピュータにルーティングできるようになるだけです。+所有者が公開ランタイムを再び**プライベート**にすると、Multica はエージェントビルダーのセッションも含め、影響を受けるエージェントとアクティブな実行を表示します。確定すると、他メンバーの該当エージェントの接続を解除し、キュー中・配信済み・実行中・ローカルディレクトリ待ち・延期中の実行を `runtime_access_revoked` としてキャンセルします。これらのエージェントに割り当てられた有効な自動化も一時停止します。所有者自身のエージェントと実行には影響しません。対象が変わった場合は再確認が必要で、同時にチャットが更新されている場合は再試行が必要になることがあります。作業を再開するには、利用可能なランタイムにエージェントを接続し、一時停止中の自動化を手動で再開してください。++キャンセル後もチャット履歴は維持され、下書き・添付ファイルの復元データはサーバーに保存されます。Web・デスクトップ版は既存の下書き復元 UI を利用しますが、モバイル版にはまだその UI がありません。開始済みで出力のない実行は、デーモンのキャンセル確認またはサーバーの猶予期間終了を待って入力の復元を判断します。接続中のデーモンは通常の確認でキャンセルを受信します。オフラインでもサーバー側のアクセスは直ちに取り消されますが、ローカルプロセスは再接続してキャンセルを受信するまで続く場合があり、即時の遠隔停止は保証できません。+## カスタムランタイムプロファイルチームで社内 wrapper やバージョン固定の実行ファイルを使う場合、あるいは互換ツールに固定引数を追加したい場合は、**カスタムランタイムプロファイル**を作成できます。diff --git a/apps/docs/content/docs/daemon-runtimes.ko.mdx b/apps/docs/content/docs/daemon-runtimes.ko.mdxindex a2196f67aa..1a082692ff 100644--- a/apps/docs/content/docs/daemon-runtimes.ko.mdx+++ b/apps/docs/content/docs/daemon-runtimes.ko.mdx@@ -79,6 +79,10 @@ multica daemon start**공개**로 바꿀 수 있는 사람은 런타임 owner뿐입니다. 워크스페이스 관리자는 런타임의 이름을 바꾸거나 삭제할 수 있지만, 공유 여부는 owner가 결정합니다. 공개하면 워크스페이스의 다른 멤버도 이 런타임을 선택할 수 있습니다. 기반 AI 코딩 도구의 로그인 자격 증명을 공유하는 것이 아니라 멤버가 에이전트 실행을 해당 컴퓨터로 라우팅할 수 있게 하는 것입니다.+소유자가 공개 런타임을 다시 **비공개**로 전환하면 Multica는 에이전트 빌더 세션을 포함하여 영향을 받는 에이전트와 활성 실행을 표시합니다. 확인하면 다른 멤버의 해당 에이전트 연결을 해제하고, 대기 중·배포됨·실행 중·로컬 디렉터리 대기·지연 중인 실행을 `runtime_access_revoked`로 취소합니다. 해당 에이전트에 할당된 활성 자동화도 일시 중지합니다. 소유자 자신의 에이전트와 실행에는 영향을 주지 않습니다. 대상이 바뀌면 다시 확인해야 하며, 채팅이 동시에 변경되는 경우 재시도가 필요할 수 있습니다. 작업을 재개하려면 에이전트를 사용 가능한 런타임에 연결한 후 일시 중지된 자동화를 직접 재개하세요.++취소해도 채팅 기록은 유지되며 초안·첨부 파일 복원 데이터는 서버에 저장됩니다. 웹과 데스크톱은 기존 초안 복원 UI를 사용하지만 모바일에는 아직 해당 UI가 없습니다. 이미 시작했지만 출력이 없는 실행은 데몬의 취소 확인 또는 서버의 유예 기간 종료 후 입력 복원 여부를 결정합니다. 연결된 데몬은 일반 확인 과정에서 취소를 받습니다. 오프라인에서도 서버의 접근 권한은 즉시 취소되지만, 로컬 프로세스는 다시 연결되어 취소를 받을 때까지 계속될 수 있으므로 즉시 원격 중단을 보장할 수 없습니다.+## 사용자 지정 런타임 설정팀에서 내부 wrapper, 고정 버전 실행 파일을 사용하거나 호환 도구에 고정 인수를 추가해야 한다면 **사용자 지정 런타임 설정**을 만들 수 있습니다.diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdxindex bb65bd0710..05225b7e2d 100644--- a/apps/docs/content/docs/daemon-runtimes.mdx+++ b/apps/docs/content/docs/daemon-runtimes.mdx@@ -79,6 +79,10 @@ A local runtime is **private** by default: only the runtime owner can create ageOnly the runtime owner can make it **public** — workspace admins can rename or delete a runtime, but sharing one is the owner's decision. Other workspace members can then select this runtime as well; that does not share the underlying AI coding tool's login credentials — it only lets members route their agents' runs to this computer.+When the owner makes a public runtime **private** again, Multica shows the affected agents and active runs, including Agent Builder sessions, before applying the change. Confirmation unbinds those teammates' agents, cancels their queued, dispatched, running, local-directory-waiting and deferred runs with `runtime_access_revoked`, and pauses active autopilots assigned to the unbound agents. The owner's own agents and runs are unaffected. A changed plan requires renewed confirmation; concurrent chat writes may require a retry. To resume work, bind the agent to an accessible runtime, then explicitly resume its paused autopilots.++Cancellation preserves chat history and stores draft/attachment recovery data on the server. Web and desktop use the existing draft recovery UI; mobile does not yet expose that recovery UI. A started turn with no output waits for the daemon's cancellation acknowledgement or the server's finalize grace period before deciding whether to restore the input. A connected daemon observes cancellation through its regular check. If the computer is offline, server-side access is still revoked immediately, but the local process may continue until it receives cancellation after reconnecting; the server cannot guarantee an immediate remote stop.+## Custom runtime profilesIf your team uses an internal wrapper, a version-pinned executable, or needs fixed extra arguments for a compatible tool, create a **custom runtime profile**.diff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdxindex eebfb0244b..99d5c26a85 100644--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx@@ -79,6 +79,10 @@ multica daemon start只有运行时所有者可以把它改为**公开**——管理员可以重命名或删除运行时,但要不要共享由所有者决定。公开后,工作区中的其他成员也可以选择这条运行时;这不会分享底层 AI 编程工具的登录凭据,只是允许成员把智能体的执行路由到这台电脑。+所有者把公开运行时重新设为**私有**时,Multica 会先展示受影响的智能体和活动运行,包括智能体构建会话。确认后会解绑其他成员的这些智能体,以 `runtime_access_revoked` 取消其排队中、已调度、执行中、等待本地目录和延迟中的运行,并暂停分配给这些智能体的已启用自动化。所有者自己的智能体和运行不受影响。影响范围变化时需要重新确认;遇到并发聊天写入时可能需要重试。恢复工作时,请先将智能体绑定到可用的运行时,再手动恢复已暂停的自动化。++取消会保留聊天历史,并在服务端保存草稿和附件恢复数据。网页端和桌面端沿用现有的草稿恢复入口;移动端暂未提供该入口。已开始但尚无输出的运行,会等待守护进程确认取消或服务端收尾宽限期结束,再决定是否恢复输入。已连接的守护进程通过常规检查接收取消。电脑离线时,服务端仍会立即撤销访问,但本地进程可能继续执行,直到重新连接并收到取消;服务端无法保证立即远程停止。+## 自定义运行时配置如果团队使用内部 wrapper、固定版本的可执行文件,或需要为一款兼容工具追加固定参数,可以创建**自定义运行时配置**。diff --git a/apps/mobile/data/realtime/use-chat-session-realtime.ts b/apps/mobile/data/realtime/use-chat-session-realtime.tsindex 2c36228588..01406636f6 100644--- a/apps/mobile/data/realtime/use-chat-session-realtime.ts+++ b/apps/mobile/data/realtime/use-chat-session-realtime.ts@@ -13,6 +13,7 @@* onto the assistant message* - task:queued / dispatch → seed / promote pendingTask* - task:cancelled → refresh pendingTask + messages+ * - chat:cancel_finalized → refresh the durable cancellation outcome* - task:completed → no-op for messages (chat:done already* wrote the assistant message); just* refresh pendingTask@@ -87,6 +88,13 @@ export function useChatSessionRealtime(invalidatePendingTask(qc, sessionId);qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });}),+ // Revocation arms durable chat settlement in its transaction. The+ // outcome may arrive after task:cancelled (including after an offline+ // daemon's ack), so refresh again when the authoritative row is ready.+ ws.on("chat:cancel_finalized", (payload) => {+ if (!isMine(payload)) return;+ invalidateMine();+ }),ws.on("task:completed", (payload) => {if (!isMine(payload)) return;invalidatePendingTask(qc, sessionId);diff --git a/apps/mobile/data/realtime/use-chat-sessions-realtime.test.ts b/apps/mobile/data/realtime/use-chat-sessions-realtime.test.tsindex d786ba2e1d..734ff0c1be 100644--- a/apps/mobile/data/realtime/use-chat-sessions-realtime.test.ts+++ b/apps/mobile/data/realtime/use-chat-sessions-realtime.test.ts@@ -26,6 +26,7 @@ vi.mock("@/data/api", () => ({ api: {} }));import { chatKeys } from "@/data/queries/chat";import { useChatSessionsRealtime } from "./use-chat-sessions-realtime";+import { useChatSessionRealtime } from "./use-chat-session-realtime";describe("useChatSessionsRealtime", () => {beforeEach(() => {@@ -33,6 +34,32 @@ describe("useChatSessionsRealtime", () => {subscriptionSetups.length = 0;});+ it("refreshes a late cancellation outcome without requiring a reconnect", () => {+ useChatSessionsRealtime();+ useChatSessionRealtime("session-1");+ const handlers = new Map<string, EventHandler[]>();+ const ws: MockWS = {+ on: vi.fn((event: string, handler: EventHandler) => {+ handlers.set(event, [...(handlers.get(event) ?? []), handler]);+ return () => {};+ }),+ onReconnect: vi.fn(() => () => {}),+ };+ for (const setup of subscriptionSetups) setup(ws, "workspace-1");+ for (const handle of handlers.get("chat:cancel_finalized") ?? []) {+ handle({ chat_session_id: "session-1", outcome: "stopped" });+ }+ expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: chatKeys.sessions("workspace-1") });+ expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: chatKeys.messages("session-1") });+ expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: chatKeys.pendingTask("session-1") });+ invalidateQueries.mockClear();+ for (const handle of handlers.get("chat:cancel_finalized") ?? []) {+ handle({ chat_session_id: "another-session", outcome: "stopped" });+ }+ expect(invalidateQueries).toHaveBeenCalledTimes(1);+ expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: chatKeys.sessions("workspace-1") });+ });+it("invalidates the workspace session list for channel-created chats", () => {useChatSessionsRealtime();expect(subscriptionSetups).toHaveLength(1);diff --git a/apps/mobile/data/realtime/use-chat-sessions-realtime.ts b/apps/mobile/data/realtime/use-chat-sessions-realtime.tsindex e23e8e6278..d961961b9b 100644--- a/apps/mobile/data/realtime/use-chat-sessions-realtime.ts+++ b/apps/mobile/data/realtime/use-chat-sessions-realtime.ts@@ -33,6 +33,7 @@ export function useChatSessionsRealtime() {// Cancellation may delete a queued prompt or append "Stopped.", both// of which change the session preview.ws.on("task:cancelled", invalidateSessions),+ ws.on("chat:cancel_finalized", invalidateSessions),// chat:session_read clears the unread flag (could be triggered from// web/desktop on the same account).ws.on("chat:session_read", invalidateSessions),diff --git a/apps/mobile/lib/failure-reason-label.test.ts b/apps/mobile/lib/failure-reason-label.test.tsindex 2f46e016ab..e1c3cf4880 100644--- a/apps/mobile/lib/failure-reason-label.test.ts+++ b/apps/mobile/lib/failure-reason-label.test.ts@@ -4,7 +4,9 @@ import { describe, expect, it } from "vitest";import chatEn from "../locales/en/chat.json";import chatZh from "../locales/zh-Hans/chat.json";import { failureReasonKey, REASONS } from "./failure-reason-label";-describe("failureReasonLabel", () => {+import { runFailureBadgeLabel } from "./run-failure-badge";++describe("failureReasonKey", () => {it("maps known reasons to i18n keys", () => {expect(failureReasonKey("runtime_access_denied")).toBe("failure_reason.runtime_access_denied",@@ -14,11 +16,22 @@ describe("failureReasonLabel", () => {).toBe("failure_reason.agent_error_provider_auth_or_access");});+ it("explains revoked access with a rebind action", () => {+ expect(failureReasonKey("runtime_access_revoked")).toBe(+ "failure_reason.runtime_access_revoked",+ );+ expect(chatEn.failure_reason.runtime_access_revoked).toBe(+ "Runtime access was revoked. Bind the agent to an accessible runtime before starting another run.",+ );+ expect(runFailureBadgeLabel("runtime_access_revoked")).toBe("Access revoked");+ });+it("falls back to a user-friendly unknown reason", () => {expect(failureReasonKey("not_known_yet")).toBe("failure_reason.default",);expect(failureReasonKey(null)).toBe("failure_reason.default");+ expect(runFailureBadgeLabel("not_known_yet")).toBeUndefined();});// The REASONS set and the locale bundles drifted once before: keys existeddiff --git a/apps/mobile/lib/failure-reason-label.ts b/apps/mobile/lib/failure-reason-label.tsindex bb5c11d7ef..9affee3a58 100644--- a/apps/mobile/lib/failure-reason-label.ts+++ b/apps/mobile/lib/failure-reason-label.ts@@ -37,6 +37,7 @@ export const REASONS = new Set(["environment_prepare_failed","invalid_task_identity","runtime_access_denied",+ "runtime_access_revoked",// Agent process side — provider."agent_error.provider_auth_or_access",diff --git a/apps/mobile/lib/run-failure-badge.ts b/apps/mobile/lib/run-failure-badge.tsindex 16885507e4..4ff2a94fcc 100644--- a/apps/mobile/lib/run-failure-badge.ts+++ b/apps/mobile/lib/run-failure-badge.ts@@ -22,6 +22,7 @@ import { RUNTIME_ACCESS_DENIED_BADGE } from "./runtime-access-copy";const FAILURE_REASON_BADGE: Record<string, string> = {queued_expired: "Queue expired",runtime_offline: "Runtime offline",+ runtime_access_revoked: "Access revoked",runtime_recovery: "Runtime recovery",timeout: "Timeout",iteration_limit: "Iteration limit",diff --git a/apps/mobile/locales/en/chat.json b/apps/mobile/locales/en/chat.jsonindex ace515ba0c..1ae626abe8 100644--- a/apps/mobile/locales/en/chat.json+++ b/apps/mobile/locales/en/chat.json@@ -120,6 +120,7 @@"runtime_cli_timeout": "Local runtime CLI timed out","environment_prepare_failed": "Couldn't prepare the execution environment","runtime_access_denied": "This agent can't run on its private runtime, so it couldn't reply. Make the runtime public, or rebind/copy the agent to a runtime its owner can use.",+ "runtime_access_revoked": "Runtime access was revoked. Bind the agent to an accessible runtime before starting another run.","invalid_task_identity": "Run identity mismatch","agent_error_provider_auth_or_access": "Provider auth failed","agent_error_provider_quota_limit": "Provider quota exhausted",diff --git a/apps/mobile/locales/zh-Hans/chat.json b/apps/mobile/locales/zh-Hans/chat.jsonindex 8b0496b2da..4ce8bb762a 100644--- a/apps/mobile/locales/zh-Hans/chat.json+++ b/apps/mobile/locales/zh-Hans/chat.json@@ -120,6 +120,7 @@"runtime_cli_timeout": "本地运行时 CLI 超时","environment_prepare_failed": "无法准备执行环境","runtime_access_denied": "该智能体无法在其私有运行时上运行,暂时无法回复。请将该运行时设为公开,或将智能体重新绑定/复制到其所有者可用的运行时。",+ "runtime_access_revoked": "运行时访问权限已被撤销。再次运行前,请为智能体绑定可用的运行时。","invalid_task_identity": "运行身份不匹配","agent_error_provider_auth_or_access": "提供商认证失败","agent_error_provider_quota_limit": "提供商配额已用尽",diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 01c906868d..5aca8cf550 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -2391,6 +2391,24 @@ export class ApiClient {});}+ // Confirmed counterpart to a public→private visibility PATCH. The PATCH+ // returns a structured 409 when teammates still have bound agents or active+ // tasks on the runtime; callers present that plan, then submit its exact+ // agent/task ID sets here. The server rechecks both sets in one transaction.+ async revokeRuntimeWorkspaceAccess(+ runtimeId: string,+ expectedNonownerAgentIds: string[],+ expectedTaskIds: string[],+ ): Promise<void> {+ await this.fetch(`/api/runtimes/${runtimeId}/revoke-workspace-access`, {+ method: "POST",+ body: JSON.stringify({+ expected_nonowner_agent_ids: expectedNonownerAgentIds,+ expected_task_ids: expectedTaskIds,+ }),+ });+ }+// Custom runtime profiles (MUL-3284). All workspace-scoped: the caller// passes the workspace id the same way the runtimes list resolves it.diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 539113259f..1252f28f40 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -2469,6 +2469,17 @@ export const DuplicateIssueErrorBodySchema = z.object({}).loose(),}).loose();+// A destructive confirmation must fail closed on an incomplete plan. Do not+// default missing arrays to empty or silently discard malformed entries.+export const RuntimeAccessRevocationPlanSchema = z.object({+ code: z.enum(["runtime_has_nonowner_dependents", "runtime_access_revocation_plan_changed"]),+ nonowner_agents: z.array(z.object({ id: z.string().uuid(), name: z.string() })),+ active_task_ids: z.array(z.string().uuid()),+}).refine((body) =>+ new Set(body.nonowner_agents.map((agent) => agent.id)).size === body.nonowner_agents.length &&+ new Set(body.active_task_ids).size === body.active_task_ids.length,+).transform((body) => ({ agents: body.nonowner_agents, activeTaskIds: body.active_task_ids }));+export interface DuplicateIssueErrorBody {code: "active_duplicate_issue";error?: string;diff --git a/packages/core/runtimes/mutations.ts b/packages/core/runtimes/mutations.tsindex 74f55b6b71..fccd3e12c5 100644--- a/packages/core/runtimes/mutations.ts+++ b/packages/core/runtimes/mutations.ts@@ -42,6 +42,34 @@ export function useUnbindAgentsAndDeleteRuntime(wsId: string) {});}+// Confirmed public→private transition. Like runtime deletion, this changes+// runtime rows, agent bindings, and task presence, so every affected server+// projection is invalidated after the transaction settles.+export function useRevokeRuntimeWorkspaceAccess(wsId: string) {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: ({+ runtimeId,+ expectedNonownerAgentIds,+ expectedTaskIds,+ }: {+ runtimeId: string;+ expectedNonownerAgentIds: string[];+ expectedTaskIds: string[];+ }) =>+ api.revokeRuntimeWorkspaceAccess(+ runtimeId,+ expectedNonownerAgentIds,+ expectedTaskIds,+ ),+ onSettled: () => {+ qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });+ qc.invalidateQueries({ queryKey: agentTaskSnapshotKeys.all(wsId) });+ },+ });+}+// useUpdateRuntime patches editable fields on a runtime (visibility, custom// name). Invalidates the runtime list so the picker disabled-state and// display names recompute.diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 38d67a6cf6..52f28360f7 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -195,6 +195,7 @@ export type TaskFailureReason =| "timeout"| "codex_semantic_inactivity"| "runtime_offline"+ | "runtime_access_revoked"| "runtime_reconnect_timeout"| "runtime_recovery"| "manual";diff --git a/packages/views/agents/components/runtime-picker.tsx b/packages/views/agents/components/runtime-picker.tsxindex 0de60d4744..a0bf336e63 100644--- a/packages/views/agents/components/runtime-picker.tsx+++ b/packages/views/agents/components/runtime-picker.tsx@@ -37,6 +37,7 @@ export function RuntimePicker({selectedRuntimeId,onSelect,disabled = false,+ autoSelect = true,}: {runtimes: RuntimeDevice[];runtimesLoading?: boolean;@@ -47,6 +48,8 @@ export function RuntimePicker({/** Blocks opening the picker while the selection cannot be honoured yet* (e.g. a builder reply or a runtime rebind is in flight). */disabled?: boolean;+ /** False when selecting also changes a live session's server-side binding. */+ autoSelect?: boolean;}) {const { t } = useT("agents");const [open, setOpen] = useState(false);@@ -83,25 +86,26 @@ export function RuntimePicker({const selectedRuntime =runtimes.find((d) => d.id === selectedRuntimeId) ?? null;- // Sole source of truth for seeding the parent's selection when it's empty+ // With autoSelect, seed the parent's selection when it's empty// — first mount with no template runtime, runtimes arriving later over// WS, or filter toggle clearing to a set with no usable item. Only fires// when `selectedRuntimeId === ""` so a duplicate-mode pre-fill (template// runtime) is never silently overwritten.useEffect(() => {- if (selectedRuntimeId !== "") return;+ if (!autoSelect || selectedRuntimeId !== "") return;const firstUsable = filteredRuntimes.find((r) =>isRuntimeUsableForUser(r, currentUserId),);if (firstUsable) onSelect(firstUsable.id);- }, [filteredRuntimes, selectedRuntimeId, currentUserId, onSelect]);+ }, [autoSelect, filteredRuntimes, selectedRuntimeId, currentUserId, onSelect]);- // On filter toggle, recompute the picker's selection to a usable item+ // With autoSelect, a filter toggle recomputes the selection to a usable item// in the new filter set. Pushes `""` when nothing matches; the seeding// effect above is a no-op in that case (correct: no usable item to pick).const handleFilterChange = (next: RuntimeFilter) => {if (next === filter) return;setFilter(next);+ if (!autoSelect) return;const nextList = computeFilteredRuntimes(runtimes, next, currentUserId);const firstUsable = nextList.find((r) =>isRuntimeUsableForUser(r, currentUserId),@@ -176,7 +180,9 @@ export function RuntimePicker({? t(($) => $.create_dialog.runtime_loading): selectedRuntime? runtimeDisplayName(selectedRuntime)- : t(($) => $.create_dialog.runtime_none)}+ : !autoSelect && runtimes.length > 0+ ? t(($) => $.model_dropdown.select_runtime_first)+ : t(($) => $.create_dialog.runtime_none)}</span>{selectedRuntime?.runtime_mode === "cloud" && (<span className="shrink-0 rounded-xs bg-info/10 px-1.5 py-0.5 text-caption font-medium text-info">diff --git a/packages/views/agents/components/tabs/task-failure.test.ts b/packages/views/agents/components/tabs/task-failure.test.tsindex a3d992840f..08d8ab2694 100644--- a/packages/views/agents/components/tabs/task-failure.test.ts+++ b/packages/views/agents/components/tabs/task-failure.test.ts@@ -73,6 +73,12 @@ describe("cancellationActorLabel", () => {// it must hold: a SERVER-cancelled row (persisted reason) reads like a failed// row. Actor provenance is handled independently by cancellationActorLabel.describe("cancelReasonLabel", () => {+ it("localizes access revocation without calling the cancelled run a failure", () => {+ for (const locale of Object.keys(AGENT_RESOURCES) as SupportedLocale[]) {+ expect(cancelReasonLabel({ status: "cancelled", failure_reason: "runtime_access_revoked" }, fixedT(locale)))+ .toBe(AGENT_RESOURCES[locale].task_failure.reasons.runtime_access_revoked);+ }+ });it("returns null for a user-initiated cancel", () => {expect(cancelReasonLabel(diff --git a/packages/views/agents/components/tabs/task-failure.ts b/packages/views/agents/components/tabs/task-failure.tsindex 2a09b6639d..50a83f0f91 100644--- a/packages/views/agents/components/tabs/task-failure.ts+++ b/packages/views/agents/components/tabs/task-failure.ts@@ -10,6 +10,7 @@ export const FAILURE_REASON_I18N_KEYS = {// Platform / scheduler side.queued_expired: "queued_expired",runtime_offline: "runtime_offline",+ runtime_access_revoked: "runtime_access_revoked",runtime_reconnect_timeout: "runtime_reconnect_timeout",runtime_recovery: "runtime_recovery",timeout: "timeout",diff --git a/packages/views/agents/create/agent-configuration-panel.tsx b/packages/views/agents/create/agent-configuration-panel.tsxindex ba840fe812..315d89ae20 100644--- a/packages/views/agents/create/agent-configuration-panel.tsx+++ b/packages/views/agents/create/agent-configuration-panel.tsx@@ -210,6 +210,7 @@ export function AgentConfigurationPanel({selectedRuntimeId={draft.runtimeId}onSelect={handleRuntimeSelect}disabled={runtimeLocked}+ autoSelect={!onRuntimeSelect}/>{/* A silently greyed-out picker is the worst version of this: theuser reaches for it exactly when the current runtime has gonediff --git a/packages/views/agents/create/builder-workspace-runtime-binding.test.tsx b/packages/views/agents/create/builder-workspace-runtime-binding.test.tsxnew file mode 100644index 0000000000..5c7a7034df--- /dev/null+++ b/packages/views/agents/create/builder-workspace-runtime-binding.test.tsx@@ -0,0 +1,124 @@+// @vitest-environment jsdom++import type { ReactNode } from "react";+import { act, cleanup, fireEvent, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { chatKeys } from "@multica/core/chat/queries";+import { runtimeKeys } from "@multica/core/runtimes/queries";+import { runtimeModelsKeys } from "@multica/core/runtimes";+import { workspaceKeys } from "@multica/core/workspace/queries";+import type { AgentBuilderSessionSummary, RuntimeDevice } from "@multica/core/types";+import { renderWithI18n } from "../../test/i18n";+import { BuilderWorkspace } from "./builder-workspace";++const apiMocks = vi.hoisted(() => ({+ switchRuntime: vi.fn(),+ saveDraft: vi.fn().mockResolvedValue(undefined),+}));+vi.mock("@multica/core/api", async (importOriginal) => ({+ ...await importOriginal<typeof import("@multica/core/api")>(),+ api: {+ switchAgentBuilderRuntime: apiMocks.switchRuntime,+ saveAgentBuilderDraft: apiMocks.saveDraft,+ },+}));+vi.mock("@multica/core/auth", () => {+ const state = { user: { id: "member-1" } };+ return {+ useAuthStore: Object.assign(+ (selector: (value: typeof state) => unknown) => selector(state),+ { getState: () => state },+ ),+ };+});+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("./use-create-agent-submit", () => ({+ useCreateAgentSubmit: () => ({ creating: false, clearNameError: vi.fn() }),+}));+vi.mock("../../chat/components/use-chat-draft-restore", () => ({+ useChatDraftRestore: () => ({ restoreDraftRequest: null, handleRestoreDraftApplied: vi.fn() }),+}));+vi.mock("./builder-conversation", () => ({ BuilderConversation: () => null }));+vi.mock("./create-agent-footer", () => ({ CreateAgentFooter: () => null }));+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));+vi.mock("../../common/avatar-upload-control", () => ({ AvatarUploadControl: () => null }));+vi.mock("../../runtimes/components/provider-logo", () => ({ ProviderLogo: () => null }));+vi.mock("../components/model-dropdown", () => ({ ModelDropdown: () => null }));+vi.mock("../components/skill-multi-select", () => ({ SkillMultiSelect: () => null }));+vi.mock("react-resizable-panels", () => ({ useDefaultLayout: () => ({}) }));+vi.mock("@multica/ui/components/ui/resizable", () => ({+ ResizablePanelGroup: ({ children }: { children: ReactNode }) => <>{children}</>,+ ResizablePanel: ({ children }: { children: ReactNode }) => <>{children}</>,+ ResizableHandle: () => null,+}));+vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));++const runtime: RuntimeDevice = {+ id: "runtime-1", workspace_id: "ws-1", daemon_id: null,+ name: "Claude (available.local)", custom_name: "Available machine",+ runtime_mode: "local", provider: "claude", launch_header: "", status: "online",+ device_info: "available.local", metadata: {}, owner_id: "member-1", visibility: "private",+ last_seen_at: null, created_at: "2026-10-15T00:00:00Z", updated_at: "2026-10-15T00:00:00Z",+};+const session: AgentBuilderSessionSummary = {+ session_id: "builder-session", title: "Unbound draft", runtime_id: "",+ created_at: "", updated_at: "", last_message_content: "", last_message_role: "", last_message_at: "",+};++function mount(runtimes: RuntimeDevice[] = [runtime]) {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });+ qc.setQueryData(runtimeKeys.list("ws-1"), runtimes);+ qc.setQueryData(workspaceKeys.members("ws-1"), []);+ qc.setQueryData(workspaceKeys.skills("ws-1"), []);+ qc.setQueryData(chatKeys.messages(session.session_id), []);+ qc.setQueryData(chatKeys.pendingTask(session.session_id), {});+ qc.setQueryData(runtimeModelsKeys.forRuntime(runtime.id), { models: [], supported: true, cached: false });+ const view = renderWithI18n(+ <QueryClientProvider client={qc}>+ <BuilderWorkspace sessionId={session.session_id} squadId={null}+ session={session} sessionSettled fallbackRuntimeId="stale-runtime-from-url"+ onDiscarded={vi.fn()} onRuntimeLabel={vi.fn()} />+ </QueryClientProvider>,+ );+ const trigger = () => {+ const button = view.container.querySelector<HTMLButtonElement>('[data-slot="popover-trigger"]');+ if (!button) throw new Error("runtime picker trigger is missing");+ return button;+ };+ return { ...view, trigger };+}++describe("unbound Builder runtime recovery", () => {+ beforeEach(() => {+ apiMocks.switchRuntime.mockReset();+ apiMocks.saveDraft.mockClear();+ });+ afterEach(cleanup);++ it("requires an explicit selection and a successful server rebind with one available runtime", async () => {+ let resolveBinding!: (result: { runtime_id: string }) => void;+ apiMocks.switchRuntime.mockImplementation(() => new Promise((resolve) => { resolveBinding = resolve; }));+ const view = mount();+ await waitFor(() => expect(view.trigger()).toBeEnabled());+ expect(view.trigger()).toHaveTextContent("Select a runtime first");+ expect(apiMocks.switchRuntime).not.toHaveBeenCalled();++ fireEvent.click(view.trigger());+ fireEvent.click(await screen.findByRole("button", { name: /Claude.*available\.local/ }));+ expect(apiMocks.switchRuntime).toHaveBeenCalledExactlyOnceWith(session.session_id, { runtime_id: runtime.id });+ expect(view.trigger()).toHaveTextContent("Select a runtime first");+ expect(view.trigger()).toBeDisabled();++ await act(async () => resolveBinding({ runtime_id: runtime.id }));+ await waitFor(() => expect(view.trigger()).toHaveTextContent("Available machine"));+ expect(view.trigger()).toBeEnabled();+ });++ it("keeps the empty picker state when there are no runtimes", () => {+ const view = mount([]);+ expect(view.trigger()).toHaveTextContent("No runtime available");+ expect(view.trigger()).toBeDisabled();+ expect(apiMocks.switchRuntime).not.toHaveBeenCalled();+ });+});diff --git a/packages/views/agents/create/builder-workspace.tsx b/packages/views/agents/create/builder-workspace.tsxindex 06b33d938b..166fde35c4 100644--- a/packages/views/agents/create/builder-workspace.tsx+++ b/packages/views/agents/create/builder-workspace.tsx@@ -87,7 +87,10 @@ export function BuilderWorkspace({const runtimeSeed = useMemo(() => ({ready: sessionSettled,- runtimeId: session?.runtime_id || fallbackRuntimeId,+ // An existing session with an empty runtime is authoritatively unbound.+ // Only a just-created, not-yet-listed session may use the URL fallback.+ runtimeId: session?.runtime_id ?? fallbackRuntimeId,+ fallbackToFirstUsable: false,}),[fallbackRuntimeId, session?.runtime_id, sessionSettled],);@@ -270,20 +273,18 @@ export function BuilderWorkspace({[builder.messages],);- // True once the draft's runtime is known to match the carrier's. Until then- // no selection may reach the server: RuntimePicker seeds an empty selection by- // calling onSelect itself, and in this pane onSelect rebinds the live- // conversation — so honouring that seed would move the conversation to- // whatever runtime sorts first, silently when idle and as "stop the current- // reply before switching runtime" when not.- const runtimeKnown = sessionSettled && draft.runtimeId.length > 0;+ // An explicitly unbound carrier is resolved too: the user must be able to+ // select a runtime and bind it, even when there is only one available.+ // Automatic selection stays disabled for live sessions so a local draft+ // cannot display a binding the server never committed.+ const runtimeResolved = sessionSettled && (session !== undefined || fallbackRuntimeId.length > 0);useEffect(() => {onRuntimeLabel(selectedRuntime ? runtimeDisplayLabel(selectedRuntime) : null);}, [onRuntimeLabel, selectedRuntime]);const handleRuntimeSelect = async (runtimeId: string) => {- if (!runtimeKnown) return;+ if (!runtimeResolved) return;if (!runtimeId || runtimeId === draft.runtimeId) return;const bound = await builder.switchRuntime(runtimeId);if (!bound) return;@@ -397,7 +398,7 @@ export function BuilderWorkspace({// Also locked while the carrier's runtime is unknown, so the// picker cannot offer a switch it would refuse to perform.runtimeSwitchInFlight={- builder.switchingRuntime || !runtimeKnown+ builder.switchingRuntime || !runtimeResolved}/></div>diff --git a/packages/views/agents/create/use-create-agent-form.ts b/packages/views/agents/create/use-create-agent-form.tsindex f9ed66ed82..3fcc2dc934 100644--- a/packages/views/agents/create/use-create-agent-form.ts+++ b/packages/views/agents/create/use-create-agent-form.ts@@ -52,8 +52,10 @@ interface RuntimeSeed {* never win a race against the authoritative answer.*/ready: boolean;- /** The runtime to adopt; empty falls back to the first usable one. */+ /** The runtime to adopt; empty may fall back to the first usable one. */runtimeId: string;+ /** Live builder sessions must be explicitly rebound before adopting one. */+ fallbackToFirstUsable?: boolean;}const IMMEDIATE_RUNTIME_SEED: RuntimeSeed = { ready: true, runtimeId: "" };@@ -114,12 +116,13 @@ export function useCreateAgentForm(options?: {const seed = options?.runtimeSeed ?? IMMEDIATE_RUNTIME_SEED;const seedReady = seed.ready;const seedRuntimeId = seed.runtimeId;+ const fallbackToFirstUsable = seed.fallbackToFirstUsable !== false;useEffect(() => {if (draft.runtimeId || !seedReady) return;- const next = seedRuntimeId || usableRuntimes[0]?.id || "";+ const next = seedRuntimeId || (fallbackToFirstUsable ? usableRuntimes[0]?.id : "") || "";if (!next) return;setDraft((current) => ({ ...current, runtimeId: next }));- }, [draft.runtimeId, seedReady, seedRuntimeId, usableRuntimes]);+ }, [draft.runtimeId, seedReady, seedRuntimeId, fallbackToFirstUsable, usableRuntimes]);const accessInvalid =draft.permissionScope === "members" &&diff --git a/packages/views/chat/components/chat-message-list.test.tsx b/packages/views/chat/components/chat-message-list.test.tsxindex 93682f9c86..a571772b1e 100644--- a/packages/views/chat/components/chat-message-list.test.tsx+++ b/packages/views/chat/components/chat-message-list.test.tsx@@ -806,6 +806,12 @@ describe("ChatMessageList failure copy (MUL-5370 regression)", () => {const FALLBACK = enChat.message_list.failure.fallback;+ it("explains revoked access with a rebind action rather than a generic retry", async () => {+ renderFailure("runtime_access_revoked");+ expect(await screen.findByText(enChat.message_list.failure.runtime_access_revoked)).toBeInTheDocument();+ expect(screen.queryByText(FALLBACK)).not.toBeInTheDocument();+ });+it("renders dedicated copy for a stalled skill bundle download", async () => {renderFailure("skill_bundle_unavailable");expect(diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsxindex 0b382f603e..3071765b67 100644--- a/packages/views/chat/components/chat-message-list.tsx+++ b/packages/views/chat/components/chat-message-list.tsx@@ -996,6 +996,7 @@ function FailureBubble({codex_semantic_inactivity: t(($) => $.message_list.failure.codex_semantic_inactivity),runtime_offline: t(($) => $.message_list.failure.runtime_offline),runtime_access_denied: t(($) => $.message_list.failure.runtime_access_denied),+ runtime_access_revoked: t(($) => $.message_list.failure.runtime_access_revoked),runtime_recovery: t(($) => $.message_list.failure.runtime_recovery),manual: t(($) => $.message_list.failure.manual),cancelled: t(($) => $.message_list.failure.manual),diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex 8f32330bb4..26d7f480d5 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -924,6 +924,7 @@"runtime_offline": "Daemon offline","runtime_reconnect_timeout": "Daemon did not reconnect in time","runtime_recovery": "Daemon restarted",+ "runtime_access_revoked": "Runtime access revoked","timeout": "Run timed out","iteration_limit": "Hit the iteration limit","agent_blocked": "Waiting on human input",diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.jsonindex 93baadea55..a479d76bc5 100644--- a/packages/views/locales/en/chat.json+++ b/packages/views/locales/en/chat.json@@ -61,6 +61,7 @@"runtime_offline": "The agent is offline right now, so it couldn't reply. Please try again once it's back online.","runtime_access_denied": "This agent can't run on its private runtime, so it couldn't reply. Make the runtime public, or rebind/copy the agent to a runtime its owner can use.","runtime_recovery": "The agent restarted before it could finish. Please try again.",+ "runtime_access_revoked": "Runtime access was revoked. Bind the agent to an accessible runtime before starting another run.","manual": "This reply was cancelled.","skill_bundle_unavailable": "The agent's skills couldn't be downloaded, so it never got started. This is usually a connection problem — please try again.","runtime_cli_timeout": "The local OpenClaw CLI didn't answer in time, so this run never started. It's a local startup timeout, not a network problem — retrying won't help until the CLI gets faster or the timeout is raised (MULTICA_OPENCLAW_CLI_TIMEOUT).",diff --git a/packages/views/locales/en/runtimes.json b/packages/views/locales/en/runtimes.jsonindex a20edab70e..f45d81cf7d 100644--- a/packages/views/locales/en/runtimes.json+++ b/packages/views/locales/en/runtimes.json@@ -141,6 +141,18 @@},"visibility_toast_updated": "Visibility set to {{visibility}}","visibility_toast_failed": "Failed to update visibility",+ "visibility_revoke_dialog": {+ "title": "Make this Runtime private?",+ "description": "Making \"{{name}}\" private will unbind {{count}} teammate agents, cancel {{taskCount}} active runs on this machine, and pause active autopilots assigned to those agents. Your own agents and runs are unaffected.",+ "warning": "Access is revoked immediately on the server. Connected daemons stop through their normal cancellation check. An offline machine cannot receive the stop request until it reconnects; its local process may continue meanwhile.",+ "plan_changed": "The access plan changed while this dialog was open. Review it and confirm again.",+ "checkbox": "I understand that the listed teammate agents will be unbound, their active runs cancelled, and their active autopilots paused.",+ "cancel": "Cancel",+ "confirm": "Make Runtime private",+ "submitting": "Revoking access...",+ "toast_success": "Runtime is now private and teammate access was revoked",+ "toast_failed": "Failed to revoke runtime access"+ },"delete_dialog": {"self_heal_notice": "This runtime is managed by a running local daemon. Deleting it will succeed, but the daemon will re-register a fresh runtime within seconds — stop the daemon process first to remove it permanently.","profile_backed_notice": "This runtime was registered from a custom runtime profile. Deleting it removes only the current runtime instance; a running daemon can register it again while the profile remains. Delete the custom runtime profile from Custom runtimes to remove it permanently.",diff --git a/packages/views/locales/fr/agents.json b/packages/views/locales/fr/agents.jsonindex 77339e6ece..cf2579bf7e 100644--- a/packages/views/locales/fr/agents.json+++ b/packages/views/locales/fr/agents.json@@ -924,6 +924,7 @@"runtime_offline": "Daemon hors ligne","runtime_reconnect_timeout": "Le démon ne s'est pas reconnecté à temps","runtime_recovery": "Daemon redémarré",+ "runtime_access_revoked": "Accès au runtime révoqué","timeout": "Délai d'exécution dépassé","iteration_limit": "Limite d'itérations atteinte","agent_blocked": "En attente d'une réponse humaine",diff --git a/packages/views/locales/fr/chat.json b/packages/views/locales/fr/chat.jsonindex eac139f26c..4f2b0517c3 100644--- a/packages/views/locales/fr/chat.json+++ b/packages/views/locales/fr/chat.json@@ -61,6 +61,7 @@"runtime_offline": "L'agent est actuellement hors ligne et n'a donc pas pu répondre. Veuillez réessayer dès son retour en ligne.","runtime_access_denied": "Cet agent ne peut pas s'exécuter sur son runtime privé et n'a donc pas pu répondre. Passez le runtime en public, ou réassociez/copiez l'agent vers un runtime que son propriétaire peut utiliser.","runtime_recovery": "L'agent a redémarré avant d'avoir pu terminer. Veuillez réessayer.",+ "runtime_access_revoked": "L'accès au runtime a été révoqué. Associez l'agent à un runtime accessible avant de lancer une nouvelle exécution.","manual": "Cette réponse a été annulée.","skill_bundle_unavailable": "Les skills de l'agent n'ont pas pu être téléchargés : il n'a donc jamais démarré. C'est généralement un problème de connexion — veuillez réessayer.","runtime_cli_timeout": "L'outil OpenClaw local n'a pas répondu à temps, l'exécution n'a donc jamais démarré. C'est un délai de démarrage local, pas un problème de réseau — réessayer ne servira à rien tant que l'outil ne démarrera pas plus vite ou que le délai ne sera pas allongé (MULTICA_OPENCLAW_CLI_TIMEOUT).",diff --git a/packages/views/locales/fr/runtimes.json b/packages/views/locales/fr/runtimes.jsonindex 3d0194b374..6978aebdf9 100644--- a/packages/views/locales/fr/runtimes.json+++ b/packages/views/locales/fr/runtimes.json@@ -141,6 +141,18 @@},"visibility_toast_updated": "Visibilité définie sur {{visibility}}","visibility_toast_failed": "Échec de la mise à jour de la visibilité",+ "visibility_revoke_dialog": {+ "title": "Rendre ce runtime privé ?",+ "description": "Rendre « {{name}} » privé dissociera {{count}} agents d'autres membres, annulera {{taskCount}} exécutions actives sur cette machine et mettra en pause les automatisations actives assignées à ces agents. Vos propres agents et exécutions ne seront pas affectés.",+ "warning": "L'accès est révoqué immédiatement sur le serveur. Les daemons connectés s'arrêtent lors de leur vérification habituelle des annulations. Une machine hors ligne ne recevra la demande d'arrêt qu'à sa reconnexion ; son processus local peut continuer entre-temps.",+ "plan_changed": "Le plan d'accès a changé pendant que cette boîte de dialogue était ouverte. Vérifiez-le et confirmez à nouveau.",+ "checkbox": "Je comprends que les agents des autres membres listés seront dissociés, leurs exécutions actives annulées et leurs automatisations actives mises en pause.",+ "cancel": "Annuler",+ "confirm": "Rendre le runtime privé",+ "submitting": "Révocation de l'accès...",+ "toast_success": "Le runtime est désormais privé et l'accès des autres membres a été révoqué",+ "toast_failed": "Échec de la révocation de l'accès au runtime"+ },"delete_dialog": {"self_heal_notice": "Ce runtime est géré par un daemon local en cours d'exécution. Sa suppression aboutira, mais le daemon en réenregistrera un nouveau en quelques secondes — arrêtez d'abord le processus du daemon pour le supprimer définitivement.","profile_backed_notice": "Ce runtime a été enregistré depuis un profil de runtime personnalisé. Sa suppression ne retire que l'instance actuelle ; un daemon en cours d'exécution peut l'enregistrer de nouveau tant que le profil subsiste. Supprimez le profil dans Runtimes personnalisés pour l'éliminer définitivement.",diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex 3a65141709..626eeb179c 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -802,6 +802,7 @@"runtime_offline": "デーモンがオフライン","runtime_reconnect_timeout": "デーモンが時間内に再接続しませんでした","runtime_recovery": "デーモンが再起動しました",+ "runtime_access_revoked": "ランタイムへのアクセスが取り消されました","timeout": "実行がタイムアウトしました","iteration_limit": "反復回数の上限に達しました","agent_blocked": "人による入力を待機中",diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.jsonindex f86a0e4bf4..e065acad00 100644--- a/packages/views/locales/ja/chat.json+++ b/packages/views/locales/ja/chat.json@@ -59,6 +59,7 @@"runtime_offline": "エージェントは現在オフラインのため、返信できませんでした。オンラインに戻ってから再度お試しください。","runtime_access_denied": "このエージェントはプライベートランタイムで実行できないため、返信できませんでした。ランタイムを公開にするか、所有者が利用できるランタイムへエージェントを再設定/コピーしてください。","runtime_recovery": "完了する前にエージェントが再起動しました。もう一度お試しください。",+ "runtime_access_revoked": "ランタイムへのアクセスが取り消されました。新しい実行を開始する前に、エージェントを利用可能なランタイムに接続してください。","manual": "この返信はキャンセルされました。","skill_bundle_unavailable": "エージェントの skill をダウンロードできず、返信を開始できませんでした。多くの場合はネットワークの問題です。もう一度お試しください。","runtime_cli_timeout": "ローカルの OpenClaw CLI が時間内に応答せず、この実行は開始されませんでした。ネットワークではなくローカルの起動タイムアウトです。CLI が速くなるか、タイムアウト(MULTICA_OPENCLAW_CLI_TIMEOUT)を延ばすまで再試行しても成功しません。",diff --git a/packages/views/locales/ja/runtimes.json b/packages/views/locales/ja/runtimes.jsonindex aa8c233326..e9ff895cb5 100644--- a/packages/views/locales/ja/runtimes.json+++ b/packages/views/locales/ja/runtimes.json@@ -136,6 +136,18 @@},"visibility_toast_updated": "公開範囲を {{visibility}} に設定しました","visibility_toast_failed": "公開範囲を更新できませんでした",+ "visibility_revoke_dialog": {+ "title": "この Runtime を private にしますか?",+ "description": "\"{{name}}\" を private にすると、他のメンバーのエージェント {{count}} 件の接続を解除し、このマシン上のアクティブな実行 {{taskCount}} 件をキャンセルします。これらのエージェントに割り当てられた有効な自動化も一時停止します。自分のエージェントと実行には影響しません。",+ "warning": "サーバー上のアクセスは直ちに取り消されます。接続中のデーモンは通常のキャンセル確認で停止します。オフラインのマシンは再接続するまで停止要求を受信できず、その間ローカルプロセスが続く場合があります。",+ "plan_changed": "このダイアログを開いている間にアクセス計画が変わりました。内容を確認して、もう一度確定してください。",+ "checkbox": "一覧の他メンバーのエージェントの接続が解除され、アクティブな実行がキャンセルされ、有効な自動化が一時停止することを理解しました。",+ "cancel": "キャンセル",+ "confirm": "Runtime を private にする",+ "submitting": "アクセスを取り消しています...",+ "toast_success": "Runtime を private にし、他メンバーのアクセスを取り消しました",+ "toast_failed": "Runtime アクセスを取り消せませんでした"+ },"delete_dialog": {"self_heal_notice": "このランタイムは実行中のローカルデーモンに管理されています。削除自体は成功しますが、デーモンプロセスを停止しない限り、数秒以内に新しいランタイムとして再登録されます。完全に削除するには先にデーモンを停止してください。","profile_backed_notice": "このランタイムはカスタムランタイムプロファイルから登録されています。ここで削除しても現在のランタイムインスタンスだけが削除され、プロファイルが残っている間は実行中のデーモンが再登録できます。完全に削除するには、Custom runtimes からカスタムランタイムプロファイルを削除してください。",diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex e772236a03..8c38196863 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -810,6 +810,7 @@"runtime_offline": "데몬 오프라인","runtime_reconnect_timeout": "데몬이 제시간에 다시 연결되지 않음","runtime_recovery": "데몬 재시작됨",+ "runtime_access_revoked": "런타임 접근이 취소됨","timeout": "실행 시간 초과","iteration_limit": "반복 횟수 제한에 도달함","agent_blocked": "사용자 입력 대기 중",diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.jsonindex 8a966ba846..851ab8b4d0 100644--- a/packages/views/locales/ko/chat.json+++ b/packages/views/locales/ko/chat.json@@ -59,6 +59,7 @@"runtime_offline": "에이전트가 현재 오프라인 상태여서 답변할 수 없습니다. 다시 온라인이 되면 시도해 주세요.","runtime_access_denied": "이 에이전트는 비공개 런타임에서 실행할 수 없어 답변할 수 없습니다. 런타임을 공개로 변경하거나, 소유자가 사용할 수 있는 런타임으로 에이전트를 다시 연결/복사하세요.","runtime_recovery": "완료 전에 에이전트가 다시 시작되었습니다. 다시 시도해 주세요.",+ "runtime_access_revoked": "런타임 접근이 취소되었습니다. 새 실행을 시작하기 전에 에이전트를 사용 가능한 런타임에 연결하세요.","manual": "이 답변이 취소되었습니다.","skill_bundle_unavailable": "에이전트의 skill을 내려받지 못해 답변을 시작하지 못했습니다. 대개 네트워크 연결 문제입니다. 다시 시도해 주세요.","runtime_cli_timeout": "로컬 OpenClaw CLI가 제한 시간 안에 응답하지 않아 이번 실행이 시작되지 못했습니다. 네트워크 문제가 아니라 로컬 실행 지연입니다. CLI가 빨라지거나 제한 시간(MULTICA_OPENCLAW_CLI_TIMEOUT)을 늘리기 전에는 다시 시도해도 실패합니다.",diff --git a/packages/views/locales/ko/runtimes.json b/packages/views/locales/ko/runtimes.jsonindex f49ac0c787..9d4580faa5 100644--- a/packages/views/locales/ko/runtimes.json+++ b/packages/views/locales/ko/runtimes.json@@ -136,6 +136,18 @@},"visibility_toast_updated": "공개 범위를 {{visibility}}(으)로 설정했습니다","visibility_toast_failed": "공개 범위를 업데이트하지 못했습니다",+ "visibility_revoke_dialog": {+ "title": "이 Runtime을 private으로 전환할까요?",+ "description": "\"{{name}}\"을 private으로 전환하면 다른 멤버의 에이전트 {{count}}개 연결이 해제되고 이 컴퓨터의 활성 실행 {{taskCount}}개가 취소됩니다. 해당 에이전트에 할당된 활성 자동화도 일시 중지됩니다. 본인의 에이전트와 실행에는 영향을 주지 않습니다.",+ "warning": "서버의 접근 권한은 즉시 취소됩니다. 연결된 데몬은 일반 취소 확인 과정에서 중단합니다. 오프라인 컴퓨터는 다시 연결될 때까지 중단 요청을 받을 수 없으므로 그동안 로컬 프로세스가 계속 실행될 수 있습니다.",+ "plan_changed": "이 대화 상자가 열린 동안 접근 계획이 변경되었습니다. 내용을 검토하고 다시 확인하세요.",+ "checkbox": "목록의 다른 멤버 에이전트 연결이 해제되고 활성 실행이 취소되며 활성 자동화가 일시 중지됨을 이해했습니다.",+ "cancel": "취소",+ "confirm": "Runtime을 private으로 전환",+ "submitting": "접근을 취소하는 중...",+ "toast_success": "Runtime이 private으로 전환되었고 다른 멤버의 접근이 취소되었습니다",+ "toast_failed": "Runtime 접근을 취소하지 못했습니다"+ },"delete_dialog": {"self_heal_notice": "이 런타임은 실행 중인 로컬 데몬이 관리합니다. 삭제는 성공하지만, 데몬 프로세스를 멈추지 않으면 몇 초 안에 새 런타임이 다시 등록됩니다. 완전히 제거하려면 먼저 데몬을 중지하세요.","profile_backed_notice": "이 런타임은 사용자 지정 런타임 프로필에서 등록되었습니다. 여기서 삭제하면 현재 런타임 인스턴스만 제거되며, 프로필이 남아 있는 동안 실행 중인 데몬이 다시 등록할 수 있습니다. 완전히 제거하려면 Custom runtimes에서 사용자 지정 런타임 프로필을 삭제하세요.",diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex 3864b4cad0..adc367cc19 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -905,6 +905,7 @@"runtime_offline": "守护进程离线","runtime_reconnect_timeout": "守护进程未及时重新连接","runtime_recovery": "守护进程已重启",+ "runtime_access_revoked": "运行时访问已撤销","timeout": "运行超时","iteration_limit": "达到迭代次数上限","agent_blocked": "等待人工输入",diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.jsonindex e7f78fb076..c835de785d 100644--- a/packages/views/locales/zh-Hans/chat.json+++ b/packages/views/locales/zh-Hans/chat.json@@ -59,6 +59,7 @@"runtime_offline": "智能体当前离线,暂时无法回复。等它恢复在线后再试。","runtime_access_denied": "该智能体无法在其私有运行时上运行,暂时无法回复。请将该运行时设为公开,或将智能体重新绑定/复制到其所有者可用的运行时。","runtime_recovery": "智能体在完成前重启了。请重试。",+ "runtime_access_revoked": "运行时访问已撤销。请先将智能体绑定到可用的运行时,再开始新的运行。","manual": "这次回复已取消。","skill_bundle_unavailable": "没能下载到智能体的 skill,这次回复没有启动。通常是网络连接问题,请重试。","runtime_cli_timeout": "本机 OpenClaw CLI 没能在超时时间内响应,这次运行没有启动。这是本地启动超时,不是网络问题——除非 CLI 变快或调大超时(MULTICA_OPENCLAW_CLI_TIMEOUT),否则重试也不会成功。",diff --git a/packages/views/locales/zh-Hans/runtimes.json b/packages/views/locales/zh-Hans/runtimes.jsonindex 1a7e162904..75dfbd1a3d 100644--- a/packages/views/locales/zh-Hans/runtimes.json+++ b/packages/views/locales/zh-Hans/runtimes.json@@ -136,6 +136,18 @@},"visibility_toast_updated": "可见性已设为\"{{visibility}}\"","visibility_toast_failed": "更新可见性失败",+ "visibility_revoke_dialog": {+ "title": "将此运行时设为私有?",+ "description": "将 \"{{name}}\" 设为私有后,会解绑 {{count}} 个其他成员的智能体、取消此机器上的 {{taskCount}} 次活动运行,并暂停分配给这些智能体的已启用自动化。你自己的智能体和运行不受影响。",+ "warning": "服务端会立即撤销访问。已连接的守护进程会在常规取消检查时停止运行。离线机器需重新连接才能收到停止请求,本地进程在此期间可能继续执行。",+ "plan_changed": "弹窗打开期间,访问方案发生了变化。请重新确认。",+ "checkbox": "我已了解:列表中的其他成员智能体会被解绑,其活动运行会被取消,已启用的自动化会被暂停。",+ "cancel": "取消",+ "confirm": "设为私有",+ "submitting": "正在撤销访问...",+ "toast_success": "运行时已设为私有,其他成员的访问已撤销",+ "toast_failed": "撤销运行时访问失败"+ },"delete_dialog": {"self_heal_notice": "该运行时由正在运行的本地守护进程托管。删除会成功,但守护进程会在数秒内重新注册一个新的运行时——若想彻底移除,请先停止守护进程。","profile_backed_notice": "该运行时来自自定义运行时配置。删除它只会移除当前运行时实例;只要配置仍存在,运行中的守护进程就可以再次注册它。若要彻底移除,请在“自定义运行时”中删除对应配置。",diff --git a/packages/views/runtimes/components/revoke-runtime-access-dialog.test.tsx b/packages/views/runtimes/components/revoke-runtime-access-dialog.test.tsxnew file mode 100644index 0000000000..b0bf5adac8--- /dev/null+++ b/packages/views/runtimes/components/revoke-runtime-access-dialog.test.tsx@@ -0,0 +1,66 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { I18nProvider } from "@multica/core/i18n/react";+import { ApiError } from "@multica/core/api";+import type { AgentRuntime } from "@multica/core/types";+import enRuntimes from "../../locales/en/runtimes.json";+import { RevokeRuntimeAccessDialog, parseRuntimeAccessRevocationPlan } from "./revoke-runtime-access-dialog";++const revoke = vi.hoisted(() => vi.fn());+vi.mock("@multica/core/api", async (importOriginal) => ({+ ...await importOriginal<typeof import("@multica/core/api")>(),+ api: { revokeRuntimeWorkspaceAccess: revoke },+}));+vi.mock("sonner", () => ({ toast: { error: vi.fn(), success: vi.fn() } }));++const agentId = "00000000-0000-4000-8000-000000000001";+const taskId = "00000000-0000-4000-8000-000000000002";+const nextTaskId = "00000000-0000-4000-8000-000000000003";+const body = { code: "runtime_has_nonowner_dependents", nonowner_agents: [{ id: agentId, name: "Teammate" }], active_task_ids: [taskId] };+const conflict = (value: unknown) => new ApiError("conflict", 409, "Conflict", value);++describe("runtime access revocation confirmation", () => {+ beforeEach(() => { revoke.mockReset(); });++ it("rejects missing, malformed, duplicate and unknown confirmation data", () => {+ for (const value of [+ null, {}, { ...body, code: "future_code" },+ { ...body, nonowner_agents: undefined }, { ...body, active_task_ids: undefined },+ { ...body, nonowner_agents: [{ id: agentId }] },+ { ...body, nonowner_agents: [null] }, { ...body, active_task_ids: ["not-a-uuid"] },+ { ...body, active_task_ids: [taskId, taskId] },+ ]) expect(parseRuntimeAccessRevocationPlan(conflict(value))).toBeNull();+ expect(parseRuntimeAccessRevocationPlan(new ApiError("error", 500, "Error", body))).toBeNull();+ expect(parseRuntimeAccessRevocationPlan(conflict(body))).toEqual({ agents: body.nonowner_agents, activeTaskIds: [taskId] });+ });++ it("requires renewed consent and submits the refreshed exact plan after a 409", async () => {+ const close = vi.fn();+ revoke.mockRejectedValueOnce(conflict({ ...body, code: "runtime_access_revocation_plan_changed", active_task_ids: [taskId, nextTaskId] })).mockResolvedValueOnce(undefined);+ const runtime: AgentRuntime = {+ id: "runtime-1", workspace_id: "ws-1", name: "Local Runtime", custom_name: "My machine",+ daemon_id: null, runtime_mode: "local", provider: "claude", launch_header: "", status: "online",+ device_info: "", metadata: {}, owner_id: "owner", visibility: "public", last_seen_at: null,+ created_at: "2026-09-05T00:00:00Z", updated_at: "2026-09-05T00:00:00Z",+ };+ render(<I18nProvider locale="en" resources={{ en: { runtimes: enRuntimes } }}>+ <QueryClientProvider client={new QueryClient({ defaultOptions: { mutations: { retry: false } } })}>+ <RevokeRuntimeAccessDialog open onOpenChange={close} runtime={runtime} wsId="ws-1" initialPlan={{ agents: body.nonowner_agents, activeTaskIds: [taskId] }} />+ </QueryClientProvider>+ </I18nProvider>);+ expect(screen.getByRole("alertdialog", { name: "Make this Runtime private?" })).toHaveAccessibleDescription(/pause active autopilots/);+ const confirm = screen.getByRole("button", { name: "Make Runtime private" });+ expect(confirm).toBeDisabled();+ fireEvent.click(screen.getByRole("checkbox"));+ fireEvent.click(confirm);+ expect(await screen.findByRole("status")).toHaveTextContent("Review it and confirm again");+ expect(confirm).toBeDisabled();+ expect(close).not.toHaveBeenCalled();+ expect(revoke).toHaveBeenNthCalledWith(1, runtime.id, [agentId], [taskId]);+ fireEvent.click(screen.getByRole("checkbox"));+ fireEvent.click(confirm);+ await waitFor(() => expect(close).toHaveBeenCalledWith(false));+ expect(revoke).toHaveBeenNthCalledWith(2, runtime.id, [agentId], [taskId, nextTaskId]);+ });+});diff --git a/packages/views/runtimes/components/revoke-runtime-access-dialog.tsx b/packages/views/runtimes/components/revoke-runtime-access-dialog.tsxnew file mode 100644index 0000000000..74610e0004--- /dev/null+++ b/packages/views/runtimes/components/revoke-runtime-access-dialog.tsx@@ -0,0 +1,160 @@+"use client";++import { useEffect, useState } from "react";+import { AlertTriangle } from "lucide-react";+import { toast } from "sonner";+import type { AgentRuntime } from "@multica/core/types";+import { ApiError, parseWithFallback } from "@multica/core/api";+import { RuntimeAccessRevocationPlanSchema } from "@multica/core/api/schemas";+import { runtimeDisplayLabel } from "@multica/core/runtimes";+import { useRevokeRuntimeWorkspaceAccess } from "@multica/core/runtimes/mutations";+import {+ AlertDialog,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogTitle,+} from "@multica/ui/components/ui/alert-dialog";+import { Button } from "@multica/ui/components/ui/button";+import { Checkbox } from "@multica/ui/components/ui/checkbox";+import { useT } from "../../i18n";++export interface RuntimeAccessRevocationPlan {+ agents: Array<{ id: string; name: string }>;+ activeTaskIds: string[];+}++// The 409 body is an API error payload, so parse only the fields this dialog+// consumes. Older servers do not send this code and simply retain the existing+// direct visibility-switch experience.+export function parseRuntimeAccessRevocationPlan(+ error: unknown,+): RuntimeAccessRevocationPlan | null {+ if (!(error instanceof ApiError) || error.status !== 409) {+ return null;+ }+ return parseWithFallback<RuntimeAccessRevocationPlan | null>(+ error.body, RuntimeAccessRevocationPlanSchema, null,+ { endpoint: "runtime-access-revocation-plan" },+ );+}++export function RevokeRuntimeAccessDialog({+ open,+ onOpenChange,+ runtime,+ wsId,+ initialPlan,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ runtime: AgentRuntime;+ wsId: string;+ initialPlan: RuntimeAccessRevocationPlan | null;+}) {+ const { t } = useT("runtimes");+ const revokeAccess = useRevokeRuntimeWorkspaceAccess(wsId);+ const [plan, setPlan] = useState<RuntimeAccessRevocationPlan | null>(initialPlan);+ const [confirmed, setConfirmed] = useState(false);+ const [notice, setNotice] = useState<string | null>(null);++ useEffect(() => {+ if (!open) return;+ setPlan(initialPlan);+ setConfirmed(false);+ setNotice(null);+ }, [open, initialPlan]);++ const submitting = revokeAccess.isPending;+ const handleConfirm = () => {+ if (!plan) return;+ revokeAccess.mutate(+ {+ runtimeId: runtime.id,+ expectedNonownerAgentIds: plan.agents.map((agent) => agent.id),+ expectedTaskIds: plan.activeTaskIds,+ },+ {+ onSuccess: () => {+ onOpenChange(false);+ toast.success(t(($) => $.detail.visibility_revoke_dialog.toast_success));+ },+ onError: (error) => {+ const updatedPlan = parseRuntimeAccessRevocationPlan(error);+ if (updatedPlan) {+ setPlan(updatedPlan);+ setConfirmed(false);+ setNotice(t(($) => $.detail.visibility_revoke_dialog.plan_changed));+ return;+ }+ toast.error(+ error instanceof Error && error.message+ ? error.message+ : t(($) => $.detail.visibility_revoke_dialog.toast_failed),+ );+ },+ },+ );+ };++ return (+ <AlertDialog open={open} onOpenChange={(next) => !submitting && onOpenChange(next)}>+ <AlertDialogContent className="w-[calc(100vw-2rem)] !max-w-[560px] gap-0 overflow-hidden rounded-lg p-0">+ <div className="px-5 pb-4 pt-5">+ <AlertDialogTitle className="text-title-sm font-semibold">+ {t(($) => $.detail.visibility_revoke_dialog.title)}+ </AlertDialogTitle>+ <AlertDialogDescription className="mt-1 text-body leading-5 text-muted-foreground">+ {t(($) => $.detail.visibility_revoke_dialog.description, {+ name: runtimeDisplayLabel(runtime),+ count: plan?.agents.length ?? 0,+ taskCount: plan?.activeTaskIds.length ?? 0,+ })}+ </AlertDialogDescription>+ <div+ role="alert"+ className="mt-3 flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-caption text-destructive"+ >+ <AlertTriangle className="mt-0.5 size-3.5 shrink-0" />+ <span>{t(($) => $.detail.visibility_revoke_dialog.warning)}</span>+ </div>+ {notice && (+ <div role="status" className="mt-2 rounded-md border bg-muted/40 px-3 py-2 text-caption">+ {notice}+ </div>+ )}+ {plan && plan.agents.length > 0 && (+ <ul className="mt-3 max-h-40 space-y-1 overflow-y-auto rounded-md border bg-muted/20 p-2 text-body">+ {plan.agents.map((agent) => <li key={agent.id}>{agent.name}</li>)}+ </ul>+ )}+ </div>+ <div className="border-t bg-muted/25 px-5 py-4">+ <label className="flex cursor-pointer items-start gap-2 text-body text-foreground">+ <Checkbox+ className="mt-0.5"+ checked={confirmed}+ onCheckedChange={(next) => setConfirmed(next === true)}+ disabled={submitting}+ />+ <span className="leading-5">+ {t(($) => $.detail.visibility_revoke_dialog.checkbox, {+ count: plan?.agents.length ?? 0,+ taskCount: plan?.activeTaskIds.length ?? 0,+ })}+ </span>+ </label>+ <div className="mt-3 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">+ <Button type="button" variant="outline" className="w-full sm:w-auto" onClick={() => onOpenChange(false)} disabled={submitting}>+ {t(($) => $.detail.visibility_revoke_dialog.cancel)}+ </Button>+ <Button type="button" variant="destructive" className="w-full sm:w-auto" onClick={handleConfirm} disabled={!confirmed || submitting || !plan}>+ {submitting+ ? t(($) => $.detail.visibility_revoke_dialog.submitting)+ : t(($) => $.detail.visibility_revoke_dialog.confirm)}+ </Button>+ </div>+ </div>+ </AlertDialogContent>+ </AlertDialog>+ );+}diff --git a/packages/views/runtimes/components/runtime-detail-visibility.test.tsx b/packages/views/runtimes/components/runtime-detail-visibility.test.tsxindex 74eb23ccfd..3c28c3b655 100644--- a/packages/views/runtimes/components/runtime-detail-visibility.test.tsx+++ b/packages/views/runtimes/components/runtime-detail-visibility.test.tsx@@ -15,6 +15,7 @@ const TEST_RESOURCES = {};const mockUpdateRuntime = vi.hoisted(() => vi.fn());+const mockUpdateRuntimeError = vi.hoisted(() => ({ value: null as unknown }));const mockDeleteRuntimeProfile = vi.hoisted(() => vi.fn());const mockQueryData = vi.hoisted(() => ({members: [] as Array<Record<string, unknown>>,@@ -25,15 +26,16 @@ vi.mock("@multica/core/hooks", () => ({useWorkspaceId: () => "ws-1",}));-vi.mock("@multica/core/api", () => ({+vi.mock("@multica/core/api", async (importOriginal) => ({+ ...await importOriginal<typeof import("@multica/core/api")>(),api: {updateRuntime: (...args: unknown[]) => mockUpdateRuntime(...args),+ revokeRuntimeWorkspaceAccess: vi.fn(),deleteRuntime: vi.fn(),unbindAgentsAndDeleteRuntime: vi.fn(),deleteRuntimeProfile: (...args: unknown[]) =>mockDeleteRuntimeProfile(...args),},- ApiError: class ApiError extends Error {},}));vi.mock("sonner", () => ({@@ -86,6 +88,8 @@ vi.mock("@multica/core/runtimes", async () => ({deriveRuntimeHealth: () => "online",runtimeDisplayName: (rt: { name: string; custom_name?: string | null }) =>rt.custom_name?.trim() || rt.name,+ runtimeDisplayLabel: (rt: { name: string; custom_name?: string | null }) =>+ rt.custom_name?.trim() || rt.name,runtimeProfileListOptions: (wsId: string) => ({queryKey: ["runtime-profiles", wsId],}),@@ -112,13 +116,21 @@ vi.mock("@multica/core/runtimes/mutations", () => ({useUpdateRuntime: () => ({mutate: (args: { runtimeId: string; patch: Record<string, unknown> },- opts?: { onSuccess?: () => void; onError?: () => void },+ opts?: { onSuccess?: () => void; onError?: (error: unknown) => void },) => {mockUpdateRuntime(args.runtimeId, args.patch);- opts?.onSuccess?.();+ if (mockUpdateRuntimeError.value) {+ opts?.onError?.(mockUpdateRuntimeError.value);+ } else {+ opts?.onSuccess?.();+ }},isPending: false,}),+ useRevokeRuntimeWorkspaceAccess: () => ({+ mutate: vi.fn(),+ isPending: false,+ }),useDeleteRuntime: () => ({ mutate: vi.fn(), isPending: false, mutateAsync: vi.fn() }),useUnbindAgentsAndDeleteRuntime: () => ({mutate: vi.fn(),@@ -145,6 +157,7 @@ vi.mock("../../navigation", () => ({}));import { RuntimeDetail } from "./runtime-detail";+import { ApiError } from "@multica/core/api";function makeRuntime(overrides: Partial<AgentRuntime>): AgentRuntime {return {@@ -207,6 +220,7 @@ describe("RuntimeDetail visibility section", () => {vi.clearAllMocks();mockQueryData.members = [];mockQueryData.profiles = [];+ mockUpdateRuntimeError.value = null;mockDeleteRuntimeProfile.mockResolvedValue(undefined);});@@ -217,6 +231,22 @@ describe("RuntimeDetail visibility section", () => {expect(screen.getByText("Public")).toBeInTheDocument();});+ it("opens a reviewed revocation plan instead of silently making an in-use public runtime private", async () => {+ mockUpdateRuntimeError.value = new ApiError("conflict", 409, "Conflict", {+ code: "runtime_has_nonowner_dependents",+ nonowner_agents: [{ id: "00000000-0000-4000-8000-000000000001", name: "Teammate Agent" }],+ active_task_ids: ["00000000-0000-4000-8000-000000000002"],+ });+ renderDetail(makeRuntime({ visibility: "public" }));++ fireEvent.click(screen.getByText("Private"));++ expect(await screen.findByText("Make this Runtime private?")).toBeInTheDocument();+ expect(screen.getByText("Teammate Agent")).toBeInTheDocument();+ expect(screen.getByText(/Your own agents and runs are unaffected/)).toBeInTheDocument();+ expect(screen.getByText(/pause active autopilots assigned to those agents/)).toBeInTheDocument();+ });+it("keeps daemon CLI version details without rendering update controls", () => {renderDetail(makeRuntime({diff --git a/packages/views/runtimes/components/runtime-detail.tsx b/packages/views/runtimes/components/runtime-detail.tsxindex e0fdbc0933..524168266b 100644--- a/packages/views/runtimes/components/runtime-detail.tsx+++ b/packages/views/runtimes/components/runtime-detail.tsx@@ -45,6 +45,11 @@ import { HealthBadge } from "./shared";import { ProviderLogo } from "./provider-logo";import { UsageSection } from "./usage-section";import { DeleteRuntimeDialog } from "./delete-runtime-dialog";+import {+ RevokeRuntimeAccessDialog,+ parseRuntimeAccessRevocationPlan,+ type RuntimeAccessRevocationPlan,+} from "./revoke-runtime-access-dialog";import { DeleteRuntimeProfileDialog } from "./delete-runtime-profile-dialog";import { runtimeRowLabel } from "./runtime-machines";import { useT, useTimeAgo } from "../../i18n";@@ -572,6 +577,8 @@ function VisibilityEditor({ runtime }: { runtime: AgentRuntime }) {const wsId = useWorkspaceId();const updateRuntime = useUpdateRuntime(wsId);const current = runtime.visibility === "public" ? "public" : "private";+ const [revokePlan, setRevokePlan] = useState<RuntimeAccessRevocationPlan | null>(null);+ const [revokeOpen, setRevokeOpen] = useState(false);const flip = (next: "private" | "public") => {if (next === current) return;@@ -584,35 +591,51 @@ function VisibilityEditor({ runtime }: { runtime: AgentRuntime }) {visibility: t(($) => $.detail.visibility_label[next]),}),),- onError: (err) =>+ onError: (err) => {+ const plan = parseRuntimeAccessRevocationPlan(err);+ if (plan) {+ setRevokePlan(plan);+ setRevokeOpen(true);+ return;+ }toast.error(err instanceof Error && err.message? err.message: t(($) => $.detail.visibility_toast_failed),- ),+ );+ },},);};return (- <div className="inline-flex items-center gap-0.5 rounded-md bg-muted p-0.5">- <VisibilityChoice- active={current === "private"}- icon={<Lock className="h-3 w-3" />}- label={t(($) => $.detail.visibility_label.private)}- tooltip={t(($) => $.detail.visibility_hint.private)}- disabled={updateRuntime.isPending}- onClick={() => flip("private")}- />- <VisibilityChoice- active={current === "public"}- icon={<Globe className="h-3 w-3" />}- label={t(($) => $.detail.visibility_label.public)}- tooltip={t(($) => $.detail.visibility_hint.public)}- disabled={updateRuntime.isPending}- onClick={() => flip("public")}+ <>+ <div className="inline-flex items-center gap-0.5 rounded-md bg-muted p-0.5">+ <VisibilityChoice+ active={current === "private"}+ icon={<Lock className="h-3 w-3" />}+ label={t(($) => $.detail.visibility_label.private)}+ tooltip={t(($) => $.detail.visibility_hint.private)}+ disabled={updateRuntime.isPending}+ onClick={() => flip("private")}+ />+ <VisibilityChoice+ active={current === "public"}+ icon={<Globe className="h-3 w-3" />}+ label={t(($) => $.detail.visibility_label.public)}+ tooltip={t(($) => $.detail.visibility_hint.public)}+ disabled={updateRuntime.isPending}+ onClick={() => flip("public")}+ />+ </div>+ <RevokeRuntimeAccessDialog+ open={revokeOpen}+ onOpenChange={setRevokeOpen}+ runtime={runtime}+ wsId={wsId}+ initialPlan={revokePlan}/>- </div>+ </>);}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 707351265d..e11dfe4b9b 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2363,6 +2363,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// the strict DELETE refused with// `runtime_has_active_agents` and the user confirmed.r.Post("/unbind-agents-and-delete", h.UnbindAgentsAndDeleteRuntime)+ // Confirmed public-to-private transition. The normal PATCH+ // returns a structured plan when teammates still have agents+ // or active work on the runtime; this route applies that plan+ // atomically after the owner reviews it.+ r.Post("/revoke-workspace-access", h.RevokeRuntimeWorkspaceAccess)// Legacy path for installed clients built against the// archive-and-delete contract (MUL-5559 renamed the// behaviour, not just the route). Same handler.diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex bbaee6dafa..d021502a7c 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -17,6 +17,7 @@ import ("unicode/utf8""github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgconn""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics"@@ -1580,6 +1581,27 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {defer tx.Rollback(r.Context())qtx := h.Queries.WithTx(tx)+ // The preflight runtime can become private while validation is in flight.+ // Serialize with revocation and keep the authorization lock through INSERT.+ // Workspace teardown takes workspace -> runtime/agent locks in that order.+ if _, err := qtx.LockWorkspaceForChatSessionCreate(r.Context(), wsUUID); err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusNotFound, "workspace not found")+ } else {+ writeError(w, http.StatusInternalServerError, "failed to lock workspace")+ }+ return+ }+ runtime, err = qtx.LockAgentRuntimeForAccessChange(r.Context(), runtimeUUID)+ if err != nil || runtime.WorkspaceID != wsUUID {+ writeError(w, http.StatusBadRequest, "invalid runtime_id")+ return+ }+ if !canUseRuntimeForAgent(member, runtime) {+ writeError(w, http.StatusForbidden, "this runtime is private; only its owner can create agents on it")+ return+ }+created, err := qtx.CreateAgent(r.Context(), db.CreateAgentParams{WorkspaceID: wsUUID,Name: req.Name,@@ -2251,7 +2273,43 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {}}- updated, err := h.Queries.UpdateAgent(r.Context(), params)+ // Only binding writes need this transaction. Hold the same runtime lock as+ // revocation until the new binding commits; a preflight-only check is stale+ // as soon as a public runtime becomes private.+ updateQueries := h.Queries+ var bindingTx pgx.Tx+ if req.RuntimeID != nil {+ member, ok := h.workspaceMember(w, r, uuidToString(existing.WorkspaceID))+ if !ok {+ return+ }+ bindingTx, err = h.TxStarter.Begin(r.Context())+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to start agent binding transaction")+ return+ }+ defer bindingTx.Rollback(r.Context())+ updateQueries = h.Queries.WithTx(bindingTx)+ if _, err := updateQueries.LockWorkspaceForChatSessionCreate(r.Context(), existing.WorkspaceID); err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusNotFound, "workspace not found")+ } else {+ writeError(w, http.StatusInternalServerError, "failed to lock workspace")+ }+ return+ }+ runtime, err := updateQueries.LockAgentRuntimeForAccessChange(r.Context(), params.RuntimeID)+ if err != nil || runtime.WorkspaceID != existing.WorkspaceID {+ writeError(w, http.StatusBadRequest, "invalid runtime_id")+ return+ }+ if !canUseRuntimeForAgent(member, runtime) {+ writeError(w, http.StatusForbidden, "this runtime is private; only its owner can move agents onto it")+ return+ }+ params.RuntimeMode = pgtype.Text{String: runtime.RuntimeMode, Valid: true}+ }+ updated, err := updateQueries.UpdateAgent(r.Context(), params)if err != nil {// Unique constraint on (workspace_id, name) — mirror CreateAgent and// return a clear conflict instead of a 500 that leaks the raw@@ -2273,6 +2331,13 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {return}+ if bindingTx != nil {+ if err := bindingTx.Commit(r.Context()); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to commit agent binding")+ return+ }+ }+// Nullable runtime overrides: null/empty in the request means explicitly// clear the field. COALESCE in UpdateAgent cannot set a column to NULL, so// mcp_config, thinking_level, and service_tier use dedicated clear queries.diff --git a/server/internal/handler/agent_builder.go b/server/internal/handler/agent_builder.goindex 014eb59052..db7ff26360 100644--- a/server/internal/handler/agent_builder.go+++ b/server/internal/handler/agent_builder.go@@ -104,6 +104,17 @@ func (h *Handler) CreateAgentBuilderSession(w http.ResponseWriter, r *http.Requereturn}+ // Hold the runtime's access lock through creation so a concurrent privacy+ // change cannot commit between authorization and the new binding.+ runtime, err = qtx.LockAgentRuntimeForAccessChange(r.Context(), runtime.ID)+ if err != nil || runtime.WorkspaceID != workspaceUUID {+ writeError(w, http.StatusBadRequest, "invalid runtime_id")+ return+ }+ if !h.authorizeBuilderRuntime(w, r, workspaceID, runtime, "start") {+ return+ }+builder, err := qtx.CreateAgentBuilder(r.Context(), db.CreateAgentBuilderParams{WorkspaceID: workspaceUUID,Name: fmt.Sprintf(".multica-agent-builder-%s", flowID),@@ -358,19 +369,26 @@ func (h *Handler) resolveBuilderRuntime(w http.ResponseWriter, r *http.Request,writeError(w, http.StatusBadRequest, "invalid runtime_id")return db.AgentRuntime{}, false}+ if !h.authorizeBuilderRuntime(w, r, workspaceID, runtime, verb) {+ return db.AgentRuntime{}, false+ }+ return runtime, true+}++func (h *Handler) authorizeBuilderRuntime(w http.ResponseWriter, r *http.Request, workspaceID string, runtime db.AgentRuntime, verb string) bool {member, ok := h.workspaceMember(w, r, workspaceID)if !ok {- return db.AgentRuntime{}, false+ return false}if !canUseRuntimeForAgent(member, runtime) {writeError(w, http.StatusForbidden, "this runtime is private; only its owner can use it")- return db.AgentRuntime{}, false+ return false}if runtime.Status != "online" {writeError(w, http.StatusConflict, fmt.Sprintf("runtime must be online to %s an agent builder session", verb))- return db.AgentRuntime{}, false+ return false}- return runtime, true+ return true}type SwitchAgentBuilderRuntimeRequest struct {@@ -456,6 +474,25 @@ func (h *Handler) SwitchAgentBuilderRuntime(w http.ResponseWriter, r *http.Requedefer tx.Rollback(r.Context())qtx := h.Queries.WithTx(tx)+ // Access changes take the runtime lock before locking dependent sessions.+ // Follow that order and authorize the committed runtime under the lock.+ if _, err := qtx.LockWorkspaceForChatSessionCreate(r.Context(), workspaceUUID); err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusNotFound, "workspace not found")+ } else {+ writeError(w, http.StatusInternalServerError, "failed to lock workspace")+ }+ return+ }+ runtime, err = qtx.LockAgentRuntimeForAccessChange(r.Context(), runtime.ID)+ if err != nil || runtime.WorkspaceID != workspaceUUID {+ writeError(w, http.StatusBadRequest, "invalid runtime_id")+ return+ }+ if !h.authorizeBuilderRuntime(w, r, workspaceID, runtime, "switch") {+ return+ }+if _, err := qtx.LockChatSessionForRuntimeBind(r.Context(), session.ID); err != nil {if errors.Is(err, pgx.ErrNoRows) {writeError(w, http.StatusNotFound, "chat session not found")diff --git a/server/internal/handler/mika_agent.go b/server/internal/handler/mika_agent.goindex 623061431d..51f33f2c67 100644--- a/server/internal/handler/mika_agent.go+++ b/server/internal/handler/mika_agent.go@@ -177,6 +177,26 @@ func (h *Handler) resolveMikaAgent(w http.ResponseWriter, r *http.Request, worksreturn db.Agent{}, false, false}+ // Existing Mika requests return above without changing a binding. A new+ // Mika must serialize authorization and INSERT with runtime revocation.+ if _, err := qtx.LockWorkspaceForChatSessionCreate(r.Context(), wsUUID); err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusNotFound, "workspace not found")+ } else {+ writeError(w, http.StatusInternalServerError, "failed to lock workspace")+ }+ return db.Agent{}, false, false+ }+ runtime, err = qtx.LockAgentRuntimeForAccessChange(r.Context(), runtimeID)+ if err != nil || runtime.WorkspaceID != wsUUID {+ writeError(w, http.StatusBadRequest, "runtime not found in this workspace")+ return db.Agent{}, false, false+ }+ if !canUseRuntimeForAgent(member, runtime) {+ writeError(w, http.StatusForbidden, "you cannot bind an agent to this runtime")+ return db.Agent{}, false, false+ }+created, err := qtx.CreateSystemUserAgent(r.Context(), db.CreateSystemUserAgentParams{WorkspaceID: wsUUID,Name: service.MikaDefaultName,diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.goindex 03c762e2a3..02524cc24d 100644--- a/server/internal/handler/runtime.go+++ b/server/internal/handler/runtime.go@@ -13,6 +13,7 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn""github.com/jackc/pgx/v5/pgtype"obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/service"@@ -20,6 +21,7 @@ import ("github.com/multica-ai/multica/server/pkg/agent"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol"+ "github.com/multica-ai/multica/server/pkg/taskfailure")type AgentRuntimeResponse struct {@@ -538,7 +540,6 @@ func (h *Handler) UpdateAgentRuntime(w http.ResponseWriter, r *http.Request) {needVisibility = true}}-if req.CustomName != nil {if len([]rune(strings.TrimSpace(*req.CustomName))) > maxRuntimeCustomNameLen {writeError(w, http.StatusBadRequest, "custom name is too long")@@ -548,6 +549,29 @@ func (h *Handler) UpdateAgentRuntime(w http.ResponseWriter, r *http.Request) {changed := false+ // The no-dependencies fast path must lock and re-check before changing+ // visibility. A plain read followed by UPDATE would leave a narrow window+ // where another member could bind an agent to the still-public runtime.+ if needVisibility && rt.Visibility == "public" && newVisibility == "private" {+ updated, plan, didChange, err := h.makeRuntimePrivateIfNoWorkspaceDependencies(r.Context(), rt, member)+ if err != nil {+ if errors.Is(err, errRuntimeOwnerChanged) {+ writeError(w, http.StatusForbidden, "only the runtime owner can change its visibility")+ return+ }+ slog.Error("make runtime private without dependencies failed", "error", err, "runtime_id", runtimeID)+ writeError(w, http.StatusInternalServerError, "failed to check runtime dependencies")+ return+ }+ if plan.hasDependencies() {+ writeJSON(w, http.StatusConflict, h.runtimeWorkspaceAccessRevocationResponse(plan, "runtime_has_nonowner_dependents"))+ return+ }+ rt = updated+ needVisibility = false+ changed = didChange+ }+if needVisibility {updated, err := h.Queries.UpdateAgentRuntimeVisibility(r.Context(), db.UpdateAgentRuntimeVisibilityParams{ID: runtimeUUID,@@ -654,6 +678,121 @@ func (h *Handler) runtimeLookup(source string) service.RuntimeLookup {return service.RuntimeLookup{Queries: h.Queries, Metrics: h.Metrics, Source: source}}+// runtimeWorkspaceAccessRevocationPlan is the owner-visible snapshot of work+// that a public-to-private transition must revoke. It intentionally excludes+// the runtime owner's agents. Hidden Builder agents owned by teammates also+// represent work borrowing the owner's machine and must lose access.+type runtimeWorkspaceAccessRevocationPlan struct {+ Agents []db.Agent+ Tasks []db.AgentTaskQueue+}++var errRuntimeOwnerChanged = errors.New("runtime owner changed during request")++func writeRuntimeRevocationBusy(w http.ResponseWriter, err error) bool {+ var pgErr *pgconn.PgError+ if !errors.As(err, &pgErr) || pgErr.Code != "55P03" {+ return false+ }+ writeJSON(w, http.StatusConflict, map[string]any{+ "code": "runtime_access_revocation_busy",+ "error": "runtime work is changing; retry to review the current plan.",+ })+ return true+}++func (p runtimeWorkspaceAccessRevocationPlan) hasDependencies() bool {+ return len(p.Agents) > 0 || len(p.Tasks) > 0+}++// makeRuntimePrivateIfNoWorkspaceDependencies handles the non-disruptive+// public-to-private path. Binding writers take the same runtime lock and+// recheck visibility before inserting/updating their agent.+//+// A non-empty plan is deliberately returned without committing. The caller+// turns it into the same confirmation response used by the disruptive path;+// the confirmed endpoint will take a fresh locked snapshot before revoking.+func (h *Handler) makeRuntimePrivateIfNoWorkspaceDependencies(ctx context.Context, rt db.AgentRuntime, member db.Member) (db.AgentRuntime, runtimeWorkspaceAccessRevocationPlan, bool, error) {+ tx, err := h.TxStarter.Begin(ctx)+ if err != nil {+ return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, fmt.Errorf("begin transaction: %w", err)+ }+ defer tx.Rollback(ctx)+ qtx := h.Queries.WithTx(tx)++ lockedRuntime, err := qtx.LockAgentRuntimeForAccessChange(ctx, rt.ID)+ if err != nil {+ return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, fmt.Errorf("lock runtime: %w", err)+ }+ if !canSetRuntimeVisibility(member, lockedRuntime) {+ return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, errRuntimeOwnerChanged+ }+ // Another request may have made the runtime private while this PATCH was+ // waiting for its lock. The requested end state is already satisfied.+ if lockedRuntime.Visibility != "public" {+ return lockedRuntime, runtimeWorkspaceAccessRevocationPlan{}, false, nil+ }++ agents, err := qtx.ListNonOwnerAgentsByRuntime(ctx, db.ListNonOwnerAgentsByRuntimeParams{+ RuntimeID: lockedRuntime.ID,+ RuntimeOwnerID: lockedRuntime.OwnerID,+ })+ if err != nil {+ return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, fmt.Errorf("list non-owner agents: %w", err)+ }+ tasks, err := qtx.ListNonOwnerActiveTasksByRuntime(ctx, db.ListNonOwnerActiveTasksByRuntimeParams{+ RuntimeID: lockedRuntime.ID,+ RuntimeOwnerID: lockedRuntime.OwnerID,+ })+ if err != nil {+ return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, fmt.Errorf("list non-owner tasks: %w", err)+ }+ plan := runtimeWorkspaceAccessRevocationPlan{Agents: agents, Tasks: tasks}+ if plan.hasDependencies() {+ return lockedRuntime, plan, false, nil+ }++ updated, err := qtx.UpdateAgentRuntimeVisibility(ctx, db.UpdateAgentRuntimeVisibilityParams{+ ID: lockedRuntime.ID,+ Visibility: "private",+ })+ if err != nil {+ return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, fmt.Errorf("update runtime visibility: %w", err)+ }+ if err := tx.Commit(ctx); err != nil {+ return db.AgentRuntime{}, runtimeWorkspaceAccessRevocationPlan{}, false, fmt.Errorf("commit transaction: %w", err)+ }+ return updated, plan, true, nil+}++// runtimeWorkspaceAccessRevocationResponse is returned for both the initial+// confirmation requirement and a stale confirmation plan. Task IDs are not+// rendered by the UI, but carrying the precise set lets the confirmed request+// fail closed if a dispatcher adds, finishes, or claims work while the dialog+// is open.+func (h *Handler) runtimeWorkspaceAccessRevocationResponse(plan runtimeWorkspaceAccessRevocationPlan, code string) map[string]any {+ // Runtime ownership does not grant access to a teammate's private agent+ // configuration. Only expose the identity needed to review the impact.+ type affectedAgent struct {+ ID string `json:"id"`+ Name string `json:"name"`+ }+ agents := make([]affectedAgent, len(plan.Agents))+ for i, agent := range plan.Agents {+ agents[i] = affectedAgent{ID: uuidToString(agent.ID), Name: agent.Name}+ }+ taskIDs := make([]string, len(plan.Tasks))+ for i, task := range plan.Tasks {+ taskIDs[i] = uuidToString(task.ID)+ }+ return map[string]any{+ "error": "making this runtime private will unbind teammates' agents, cancel their active runs, and pause their active autopilots; review and confirm first.",+ "code": code,+ "nonowner_agents": agents,+ "active_task_ids": taskIDs,+ }+}+// requireRuntimeReadAccess protects runtime data and machine-triggering// capabilities. Governance access is deliberately separate: workspace owners// and admins may list, rename, or delete another member's private runtime,@@ -897,6 +1036,194 @@ func canSetRuntimeVisibility(member db.Member, rt db.AgentRuntime) bool {return rt.OwnerID.Valid && uuidToString(rt.OwnerID) == uuidToString(member.UserID)}+type revokeRuntimeWorkspaceAccessRequest struct {+ ExpectedNonownerAgentIDs []string `json:"expected_nonowner_agent_ids"`+ ExpectedTaskIDs []string `json:"expected_task_ids"`+}++// RevokeRuntimeWorkspaceAccess confirms the disruptive half of changing a+// public runtime back to private. The normal PATCH endpoint remains a direct+// update when no teammate is using the runtime; otherwise it returns a+// structured 409 and this endpoint applies the reviewed plan atomically.+//+// Server-side cancellation is authoritative even while the daemon is offline.+// A connected daemon observes its cancelled task through its existing polling+// path; a disconnected machine cannot receive a stop signal until it returns,+// but it cannot claim new work after the database transition commits.+func (h *Handler) RevokeRuntimeWorkspaceAccess(w http.ResponseWriter, r *http.Request) {+ runtimeID := chi.URLParam(r, "runtimeId")+ runtimeUUID, ok := parseUUIDOrBadRequest(w, runtimeID, "runtime_id")+ if !ok {+ return+ }++ var req revokeRuntimeWorkspaceAccessRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ expectedAgents, ok := parseExpectedUUIDIDs(req.ExpectedNonownerAgentIDs)+ if !ok {+ writeError(w, http.StatusBadRequest, "expected_nonowner_agent_ids must be a list of valid UUIDs")+ return+ }+ expectedTasks, ok := parseExpectedUUIDIDs(req.ExpectedTaskIDs)+ if !ok {+ writeError(w, http.StatusBadRequest, "expected_task_ids must be a list of valid UUIDs")+ return+ }++ rt, err := h.getAgentRuntime(r.Context(), obsmetrics.RuntimeLookupSourceRuntimeAPI, runtimeUUID)+ if err != nil {+ writeError(w, http.StatusNotFound, "runtime not found")+ return+ }+ wsID := uuidToString(rt.WorkspaceID)+ member, ok := h.requireWorkspaceMember(w, r, wsID, "runtime not found")+ if !ok {+ return+ }+ if !canSetRuntimeVisibility(member, rt) {+ writeError(w, http.StatusForbidden, "only the runtime owner can change its visibility")+ return+ }++ tx, err := h.TxStarter.Begin(r.Context())+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to start transaction")+ return+ }+ defer tx.Rollback(r.Context())+ qtx := h.Queries.WithTx(tx)++ // Bindings take the same access-change lock; claim and delivery revalidate+ // authorization before executing work. Do not rely on FK checks for access.+ lockedRuntime, err := qtx.LockAgentRuntimeForAccessChange(r.Context(), rt.ID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to lock runtime")+ return+ }+ if !canSetRuntimeVisibility(member, lockedRuntime) {+ writeError(w, http.StatusForbidden, "only the runtime owner can change its visibility")+ return+ }+ if lockedRuntime.Visibility != "public" {+ writeJSON(w, http.StatusConflict, map[string]any{+ "error": "this runtime is already private; refresh before trying again.",+ "code": "runtime_access_revocation_not_required",+ })+ return+ }++ currentAgents, err := qtx.ListNonOwnerAgentsByRuntimeForUpdate(r.Context(), db.ListNonOwnerAgentsByRuntimeForUpdateParams{+ RuntimeID: lockedRuntime.ID,+ RuntimeOwnerID: lockedRuntime.OwnerID,+ })+ if err != nil {+ if writeRuntimeRevocationBusy(w, err) {+ return+ }+ writeError(w, http.StatusInternalServerError, "failed to lock runtime agents")+ return+ }+ if _, err := qtx.LockRuntimeRevocationChatSessions(r.Context(), db.LockRuntimeRevocationChatSessionsParams{+ RuntimeID: lockedRuntime.ID, RuntimeOwnerID: lockedRuntime.OwnerID,+ }); err != nil {+ if !writeRuntimeRevocationBusy(w, err) {+ writeError(w, http.StatusInternalServerError, "failed to lock runtime chats")+ }+ return+ }+ currentTasks, err := qtx.ListNonOwnerActiveTasksByRuntimeForUpdate(r.Context(), db.ListNonOwnerActiveTasksByRuntimeForUpdateParams{+ RuntimeID: lockedRuntime.ID,+ RuntimeOwnerID: lockedRuntime.OwnerID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to lock runtime tasks")+ return+ }+ plan := runtimeWorkspaceAccessRevocationPlan{Agents: currentAgents, Tasks: currentTasks}+ if !agentSetMatches(currentAgents, expectedAgents) || !taskSetMatches(currentTasks, expectedTasks) {+ body := h.runtimeWorkspaceAccessRevocationResponse(plan, "runtime_access_revocation_plan_changed")+ body["error"] = "the runtime access plan changed; please review and confirm again."+ writeJSON(w, http.StatusConflict, body)+ return+ }++ updated, err := qtx.UpdateAgentRuntimeVisibility(r.Context(), db.UpdateAgentRuntimeVisibilityParams{+ ID: lockedRuntime.ID,+ Visibility: "private",+ })+ if err != nil {+ slog.Error("make runtime private failed", "error", err, "runtime_id", runtimeID)+ writeError(w, http.StatusInternalServerError, "failed to update runtime")+ return+ }+ cancelled, err := qtx.CancelNonOwnerTasksByRuntime(r.Context(), db.CancelNonOwnerTasksByRuntimeParams{+ RuntimeID: lockedRuntime.ID,+ RuntimeOwnerID: lockedRuntime.OwnerID,+ FailureReason: string(taskfailure.ReasonRuntimeAccessRevoked),+ })+ if err != nil {+ slog.Error("cancel non-owner runtime tasks failed", "error", err, "runtime_id", runtimeID)+ writeError(w, http.StatusInternalServerError, "failed to cancel runtime tasks")+ return+ }+ readyChats, err := service.PrepareRuntimeAccessCancellation(r.Context(), qtx, cancelled)+ if err != nil {+ slog.Error("prepare runtime cancellation chat settlement failed", "error", err, "runtime_id", runtimeID)+ writeError(w, http.StatusInternalServerError, "failed to settle runtime chats")+ return+ }+ unbound, err := qtx.UnbindNonOwnerAgentsFromRuntime(r.Context(), db.UnbindNonOwnerAgentsFromRuntimeParams{+ RuntimeID: lockedRuntime.ID,+ RuntimeOwnerID: lockedRuntime.OwnerID,+ })+ if err != nil {+ slog.Error("unbind non-owner runtime agents failed", "error", err, "runtime_id", runtimeID)+ writeError(w, http.StatusInternalServerError, "failed to unbind runtime agents")+ return+ }+ unboundIDs := make([]pgtype.UUID, len(unbound))+ for i, agent := range unbound {+ unboundIDs[i] = agent.ID+ }+ paused, err := qtx.PauseAutopilotsByUnboundAgents(r.Context(), unboundIDs)+ if err != nil {+ slog.Error("pause autopilots for runtime privacy failed", "error", err, "runtime_id", runtimeID)+ writeError(w, http.StatusInternalServerError, "failed to pause affected autopilots")+ return+ }+ if err := tx.Commit(r.Context()); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to commit runtime privacy change")+ return+ }++ result := service.RuntimeTeardownResult{+ UnboundAgents: unbound,+ CancelledTasks: cancelled,+ PausedAutopilots: paused,+ }+ h.PublishRuntimeTeardown(r.Context(), result, wsID, "member", uuidToString(member.UserID), "update", true)+ for _, taskID := range readyChats {+ h.TaskService.FinalizeDeferredCancelledChat(r.Context(), taskID)+ }+ slog.Info("runtime made private and workspace access revoked",+ "runtime_id", runtimeID,+ "changed_by", uuidToString(member.UserID),+ "agents_unbound", len(unbound),+ "tasks_cancelled", len(cancelled),+ "autopilots_paused", len(paused),+ )++ writeJSON(w, http.StatusOK, map[string]any{+ "runtime": runtimeToResponse(updated),+ "agents_unbound": len(unbound),+ "tasks_cancelled": len(cancelled),+ "autopilots_paused": len(paused),+ })+}+func (h *Handler) ListAgentRuntimes(w http.ResponseWriter, r *http.Request) {workspaceID := h.resolveWorkspaceID(r)userID, ok := requireUserID(w, r)@@ -1357,6 +1684,13 @@ func (h *Handler) UnbindAgentsAndDeleteRuntime(w http.ResponseWriter, r *http.Re// any malformed UUID so the handler responds 400 instead of silently// matching a different set.func parseExpectedActiveAgentIDs(raw []string) (map[string]struct{}, bool) {+ return parseExpectedUUIDIDs(raw)+}++// parseExpectedUUIDIDs validates a confirmation snapshot sent by a client.+// Duplicates intentionally collapse into one set member: the server compares+// the effect set, not its transport ordering.+func parseExpectedUUIDIDs(raw []string) (map[string]struct{}, bool) {out := make(map[string]struct{}, len(raw))for _, s := range raw {u, err := util.ParseUUID(s)@@ -1373,6 +1707,10 @@ func parseExpectedActiveAgentIDs(raw []string) (map[string]struct{}, bool) {// because the front-end may render in any order; size + membership is what// matters for "did the plan change?".func activeAgentSetMatches(current []db.Agent, expected map[string]struct{}) bool {+ return agentSetMatches(current, expected)+}++func agentSetMatches(current []db.Agent, expected map[string]struct{}) bool {if len(current) != len(expected) {return false}@@ -1383,3 +1721,15 @@ func activeAgentSetMatches(current []db.Agent, expected map[string]struct{}) boo}return true}++func taskSetMatches(current []db.AgentTaskQueue, expected map[string]struct{}) bool {+ if len(current) != len(expected) {+ return false+ }+ for _, task := range current {+ if _, ok := expected[uuidToString(task.ID)]; !ok {+ return false+ }+ }+ return true+}diff --git a/server/internal/handler/runtime_binding_lock_order_test.go b/server/internal/handler/runtime_binding_lock_order_test.gonew file mode 100644index 0000000000..866ad4b5f5--- /dev/null+++ b/server/internal/handler/runtime_binding_lock_order_test.go@@ -0,0 +1,96 @@+package handler++import (+ "context"+ "net/http"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestRuntimeBindingLocksWorkspaceBeforeRuntime(t *testing.T) {+ if testHandler == nil {+ t.Fatal("database-backed handler fixture is required")+ }+ for _, tt := range []struct {+ entry string+ wantStatus int+ }{+ {entry: "user create", wantStatus: http.StatusCreated},+ {entry: "user rebind", wantStatus: http.StatusOK},+ {entry: "mika create", wantStatus: http.StatusCreated},+ {entry: "builder create", wantStatus: http.StatusCreated},+ {entry: "builder switch", wantStatus: http.StatusOK},+ } {+ t.Run(tt.entry, func(t *testing.T) {+ h := *testHandler+ fx, runtimeID, handler, req := runtimeBindingVisibilityRequest(t, &h, tt.entry)+ fx.Cleanup(t, `DELETE FROM agent WHERE workspace_id = $1`, fx.WorkspaceID)+ fx.Cleanup(t, `DELETE FROM chat_session WHERE workspace_id = $1`, fx.WorkspaceID)+ ctx, cancel := context.WithTimeout(req.Context(), 20*time.Second)+ defer cancel()+ req = req.WithContext(ctx)+ holder, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin workspace delete lock: %v", err)+ }+ defer holder.Rollback(context.Background())+ if _, err := db.New(holder).LockWorkspaceForDelete(ctx, parseUUID(fx.WorkspaceID)); err != nil {+ t.Fatalf("lock workspace as deletion would: %v", err)+ }+ holderPID := holderBackendPID(t, ctx, holder)+ responses := make(chan *testutil.Response, 1)+ done := make(chan struct{})+ go func() {+ defer close(done)+ responses <- testutil.Call(t, handler, req)+ }()+ defer func() {+ cancel()+ _ = holder.Rollback(context.Background())+ select {+ case <-done:+ case <-time.After(5 * time.Second):+ t.Error("binding request did not exit after cancellation")+ }+ }()+ if !waitForWaiterBlockedBy(t, holderPID, 10*time.Second) {+ select {+ case response := <-responses:+ t.Fatalf("binding returned %d while workspace was locked: %s", response.Code, response.Text())+ default:+ t.Fatal("binding did not wait for the workspace lock")+ }+ }++ // While the binding waits for the workspace, another transaction+ // must still be able to lock the runtime. Otherwise deletion can+ // hold workspace -> wait runtime while binding does the reverse.+ probe, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin runtime lock probe: %v", err)+ }+ defer probe.Rollback(context.Background())+ if _, err := probe.Exec(ctx, `SELECT id FROM agent_runtime WHERE id = $1 FOR NO KEY UPDATE NOWAIT`, runtimeID); err != nil {+ t.Fatalf("runtime was locked before binding acquired workspace: %v", err)+ }+ if err := probe.Rollback(ctx); err != nil {+ t.Fatalf("release runtime lock probe: %v", err)+ }+ if err := holder.Commit(ctx); err != nil {+ t.Fatalf("release workspace lock: %v", err)+ }+ select {+ case response := <-responses:+ response.Want(tt.wantStatus)+ case <-ctx.Done():+ t.Fatal("binding did not finish after workspace lock was released")+ }+ if got := fx.Count(t, `SELECT count(*) FROM agent WHERE runtime_id = $1`, runtimeID); got != 1 {+ t.Fatalf("successful binding left %d agents on the runtime, want 1", got)+ }+ })+ }+}diff --git a/server/internal/handler/runtime_binding_visibility_test.go b/server/internal/handler/runtime_binding_visibility_test.gonew file mode 100644index 0000000000..0b10db17b0--- /dev/null+++ b/server/internal/handler/runtime_binding_visibility_test.go@@ -0,0 +1,210 @@+package handler++import (+ "context"+ "net/http"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5"++ "github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Each case gets its own workspace so Mika's one-per-workspace lookup cannot+// turn a binding check into the existing-agent fast path.+func runtimeBindingVisibilityRequest(t *testing.T, h *Handler, entry string) (*testutil.Fixture, string, http.HandlerFunc, *http.Request) {+ t.Helper()+ workspaceID := dbfx.Workspace(t, "Runtime binding visibility", "runtime-binding-"+uuid.NewString())+ ownerID := dbfx.User(t, "Runtime binding owner", uuid.NewString()+"@multica.test")+ memberID := dbfx.User(t, "Runtime binding member", uuid.NewString()+"@multica.test")+ dbfx.Member(t, workspaceID, ownerID, "member")+ dbfx.Member(t, workspaceID, memberID, "member")+ fx := testutil.New(testPool, workspaceID, memberID)+ runtimeID := fx.Runtime(t, "Shared binding runtime", testutil.Cols{+ "owner_id": ownerID, "visibility": "public",+ })+ method, path, handler := http.MethodPost, "/api/agent-builder/sessions", h.CreateAgentBuilderSession+ body := map[string]any{"runtime_id": runtimeID}+ sessionID := ""+ agentID := ""+ switch entry {+ case "user create":+ path, handler = "/api/agents", h.CreateAgent+ body["name"] = "Runtime binding agent"+ case "user rebind":+ agentID = fx.Agent(t, "Unbound user agent", "")+ method, path, handler = http.MethodPatch, "/api/agents/"+agentID, h.UpdateAgent+ case "builder create":+ case "builder switch":+ builderID := fx.Agent(t, "Unbound builder", "", testutil.Cols{+ "kind": "system", "system_key": agentBuilderSystemKeyPrefix + uuid.NewString(),+ })+ sessionID = fx.ChatSession(t, builderID)+ method, path, handler = http.MethodPatch, "/api/agent-builder/sessions/"+sessionID+"/runtime", h.SwitchAgentBuilderRuntime+ case "mika create":+ path, handler = "/api/agents/mika", h.CreateMikaAgent+ body["language"] = "en"+ default:+ t.Fatalf("unknown binding entry %q", entry)+ }+ req := newRequestAs(memberID, method, path, body)+ req.Header.Set("X-Workspace-ID", workspaceID)+ member, err := h.Queries.GetMemberByUserAndWorkspace(req.Context(), db.GetMemberByUserAndWorkspaceParams{+ UserID: parseUUID(memberID), WorkspaceID: parseUUID(workspaceID),+ })+ if err != nil {+ t.Fatalf("load binding member: %v", err)+ }+ req = req.WithContext(middleware.SetMemberContext(req.Context(), workspaceID, member))+ if sessionID != "" {+ req = testutil.WithURLParams(req, "sessionId", sessionID)+ }+ if agentID != "" {+ req = testutil.WithURLParams(req, "id", agentID)+ }+ return fx, runtimeID, handler, req+}++func TestSystemAgentBindingRechecksRuntimeVisibilityInTransaction(t *testing.T) {+ if testHandler == nil {+ t.Fatal("database-backed handler fixture is required")+ }+ for _, entry := range []string{"builder create", "builder switch", "mika create"} {+ t.Run(entry, func(t *testing.T) {+ h := *testHandler+ fx, runtimeID, handler, req := runtimeBindingVisibilityRequest(t, &h, entry)+ agentsBefore := fx.Count(t, `SELECT count(*) FROM agent WHERE workspace_id = $1`, fx.WorkspaceID)+ sessionsBefore := fx.Count(t, `SELECT count(*) FROM chat_session WHERE workspace_id = $1`, fx.WorkspaceID)+ began := false+ h.TxStarter = privacyBeginHook(func(ctx context.Context) (pgx.Tx, error) {+ began = true+ fx.Exec(t, `UPDATE agent_runtime SET visibility = 'private' WHERE id = $1`, runtimeID)+ return testPool.Begin(ctx)+ })++ testutil.Call(t, handler, req).Want(http.StatusForbidden)+ if !began {+ t.Fatal("request did not reach the transaction after public-runtime preflight")+ }+ if got := fx.Count(t, `SELECT count(*) FROM agent WHERE runtime_id = $1`, runtimeID); got != 0 {+ t.Fatalf("private runtime received %d new bindings", got)+ }+ if got := fx.Count(t, `SELECT count(*) FROM agent WHERE workspace_id = $1`, fx.WorkspaceID); got != agentsBefore {+ t.Fatalf("rejected binding changed agent count from %d to %d", agentsBefore, got)+ }+ if got := fx.Count(t, `SELECT count(*) FROM chat_session WHERE workspace_id = $1`, fx.WorkspaceID); got != sessionsBefore {+ t.Fatalf("rejected binding changed session count from %d to %d", sessionsBefore, got)+ }+ })+ }+}++func TestSystemAgentBindingWaitsForRuntimeAccessChange(t *testing.T) {+ if testHandler == nil {+ t.Fatal("database-backed handler fixture is required")+ }+ for _, entry := range []string{"builder create", "builder switch", "mika create"} {+ t.Run(entry, func(t *testing.T) {+ h := *testHandler+ fx, runtimeID, handler, req := runtimeBindingVisibilityRequest(t, &h, entry)+ ctx, cancel := context.WithTimeout(req.Context(), 20*time.Second)+ defer cancel()+ req = req.WithContext(ctx)+ tx, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin runtime holder: %v", err)+ }+ defer tx.Rollback(context.Background())+ if _, err := db.New(tx).LockAgentRuntimeForAccessChange(ctx, parseUUID(runtimeID)); err != nil {+ t.Fatalf("lock runtime for access change: %v", err)+ }+ holderPID := holderBackendPID(t, ctx, tx)+ responses := make(chan *testutil.Response, 1)+ go func() { responses <- testutil.Call(t, handler, req) }()++ if !waitForWaiterBlockedBy(t, holderPID, 10*time.Second) {+ select {+ case response := <-responses:+ t.Fatalf("binding returned %d while the runtime access lock was held: %s", response.Code, response.Text())+ default:+ t.Fatal("binding did not wait for the runtime access lock")+ }+ }+ if _, err := tx.Exec(ctx, `UPDATE agent_runtime SET visibility = 'private' WHERE id = $1`, runtimeID); err != nil {+ t.Fatalf("make locked runtime private: %v", err)+ }+ if err := tx.Commit(ctx); err != nil {+ t.Fatalf("commit runtime access change: %v", err)+ }+ select {+ case response := <-responses:+ response.Want(http.StatusForbidden)+ case <-ctx.Done():+ t.Fatal("binding did not finish after the runtime access lock was released")+ }+ if got := fx.Count(t, `SELECT count(*) FROM agent WHERE runtime_id = $1`, runtimeID); got != 0 {+ t.Fatalf("binding survived committed revocation: count=%d", got)+ }+ })+ }+}++func TestAgentBuilderBindingRechecksRuntimeOnlineInTransaction(t *testing.T) {+ if testHandler == nil {+ t.Fatal("database-backed handler fixture is required")+ }+ for _, entry := range []string{"builder create", "builder switch"} {+ t.Run(entry, func(t *testing.T) {+ h := *testHandler+ fx, runtimeID, handler, req := runtimeBindingVisibilityRequest(t, &h, entry)+ h.TxStarter = privacyBeginHook(func(ctx context.Context) (pgx.Tx, error) {+ fx.Exec(t, `UPDATE agent_runtime SET status = 'offline' WHERE id = $1`, runtimeID)+ return testPool.Begin(ctx)+ })+ testutil.Call(t, handler, req).Want(http.StatusConflict)+ if got := fx.Count(t, `SELECT count(*) FROM agent WHERE runtime_id = $1`, runtimeID); got != 0 {+ t.Fatalf("offline runtime received %d new bindings", got)+ }+ })+ }+}++func TestMikaExistingAgentRecheckDoesNotRequireRuntimeAccess(t *testing.T) {+ if testHandler == nil {+ t.Fatal("database-backed handler fixture is required")+ }+ h := *testHandler+ fx, runtimeID, _, req := runtimeBindingVisibilityRequest(t, &h, "mika create")+ existingID := ""+ h.TxStarter = privacyBeginHook(func(ctx context.Context) (pgx.Tx, error) {+ // Another provisioning request wins after this request's fast lookup.+ existingID = fx.Agent(t, service.MikaDefaultName, "", testutil.Cols{+ "system_key": service.MikaSystemKey,+ })+ fx.Exec(t, `UPDATE agent_runtime SET visibility = 'private' WHERE id = $1`, runtimeID)+ return testPool.Begin(ctx)+ })+ var response struct {+ AgentID string `json:"agent_id"`+ Created bool `json:"created"`+ }+ testutil.Call(t, func(w http.ResponseWriter, r *http.Request) {+ agent, created, ok := h.resolveMikaAgent(w, r, fx.WorkspaceID, fx.UserID, createMikaAgentRequest{+ RuntimeID: runtimeID, Language: "en",+ })+ if ok {+ writeJSON(w, http.StatusOK, map[string]any{"agent_id": uuidToString(agent.ID), "created": created})+ }+ }, req).Want(http.StatusOK).JSON(&response)+ if response.AgentID != existingID || response.Created {+ t.Fatalf("existing Mika was not reused: response=%+v existing=%q", response, existingID)+ }+ if got := fx.Count(t, `SELECT count(*) FROM agent WHERE workspace_id = $1`, fx.WorkspaceID); got != 1 {+ t.Fatalf("idempotent Mika request left %d agents, want 1", got)+ }+}diff --git a/server/internal/handler/runtime_visibility_revocation_test.go b/server/internal/handler/runtime_visibility_revocation_test.gonew file mode 100644index 0000000000..6738a72db0--- /dev/null+++ b/server/internal/handler/runtime_visibility_revocation_test.go@@ -0,0 +1,476 @@+package handler++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "slices"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// privacyBeginHook changes committed state after the HTTP preflight but before+// the mutation transaction. No sleeps or scheduling assumptions are needed to+// reproduce a stale authorization decision.+type privacyBeginHook func(context.Context) (pgx.Tx, error)++func (hook privacyBeginHook) Begin(ctx context.Context) (pgx.Tx, error) { return hook(ctx) }++func TestRuntimePrivacyRechecksOwnerInTransaction(t *testing.T) {+ if testHandler == nil {+ t.Fatal("database-backed handler fixture is required")+ }+ for _, confirmed := range []bool{false, true} {+ t.Run(map[bool]string{false: "patch", true: "confirmed"}[confirmed], func(t *testing.T) {+ runtimeID, oldOwner, newOwner := runtimeVisibilityFixture(t)+ dbfx.Exec(t, `UPDATE agent_runtime SET visibility = 'public' WHERE id = $1`, runtimeID)+ h := *testHandler+ h.TxStarter = privacyBeginHook(func(ctx context.Context) (pgx.Tx, error) {+ dbfx.Exec(t, `UPDATE agent_runtime SET owner_id = $2 WHERE id = $1`, runtimeID, newOwner)+ return testPool.Begin(ctx)+ })+ method, path, handler := http.MethodPatch, "/api/runtimes/"+runtimeID, h.UpdateAgentRuntime+ body := map[string]any{"visibility": "private"}+ if confirmed {+ method, path, handler = http.MethodPost, path+"/revoke-workspace-access", h.RevokeRuntimeWorkspaceAccess+ body = map[string]any{"expected_nonowner_agent_ids": []string{}, "expected_task_ids": []string{}}+ }+ req := newRequestAs(oldOwner, method, path, body)+ testutil.Call(t, handler, testutil.WithURLParams(req, "runtimeId", runtimeID)).Want(http.StatusForbidden)+ runtime, err := testHandler.Queries.GetAgentRuntime(context.Background(), mustTestUUID(t, runtimeID))+ if err != nil || runtime.Visibility != "public" {+ t.Fatalf("stale owner changed visibility: runtime=%+v err=%v", runtime, err)+ }+ })+ }+}++func TestAgentBindingRechecksRuntimeVisibilityInTransaction(t *testing.T) {+ if testHandler == nil {+ t.Fatal("database-backed handler fixture is required")+ }+ for _, create := range []bool{true, false} {+ t.Run(map[bool]string{true: "create", false: "rebind"}[create], func(t *testing.T) {+ runtimeID, _, memberID := runtimeVisibilityFixture(t)+ dbfx.Exec(t, `UPDATE agent_runtime SET visibility = 'public' WHERE id = $1`, runtimeID)+ h := *testHandler+ h.TxStarter = privacyBeginHook(func(ctx context.Context) (pgx.Tx, error) {+ dbfx.Exec(t, `UPDATE agent_runtime SET visibility = 'private' WHERE id = $1`, runtimeID)+ return testPool.Begin(ctx)+ })+ body := map[string]any{"name": "Delayed Runtime Binding", "runtime_id": runtimeID}+ method, path, param, id, handler := http.MethodPost, "/api/workspaces/"+testWorkspaceID+"/agents", "workspaceId", testWorkspaceID, h.CreateAgent+ if !create {+ id = createRuntimePrivacyAgent(t, runtimeID, memberID, "Delayed Runtime Rebind")+ dbfx.Exec(t, `UPDATE agent SET runtime_id = NULL WHERE id = $1`, id)+ method, path, param, handler = http.MethodPatch, "/api/agents/"+id, "id", h.UpdateAgent+ }+ req := newRequestAs(memberID, method, path, body)+ testutil.Call(t, handler, testutil.WithURLParams(req, param, id)).Want(http.StatusForbidden)+ var count int+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM agent WHERE runtime_id = $1 AND owner_id = $2`, runtimeID, memberID).Scan(&count); err != nil || count != 0 {+ t.Fatalf("delayed binding persisted: count=%d err=%v", count, err)+ }+ })+ }+}++func TestRuntimeRevocationSettlesChats(t *testing.T) {+ if testHandler == nil {+ t.Fatal("database-backed handler fixture is required")+ }+ for _, tc := range []struct {+ name, status string+ started, output, channel bool+ builder bool+ }{+ {name: "queued", status: "queued"},+ {name: "dispatched", status: "dispatched"},+ {name: "running output", status: "running", started: true, output: true},+ {name: "running empty offline", status: "running", started: true},+ {name: "channel empty", status: "running", started: true, channel: true},+ {name: "local directory wait", status: "waiting_local_directory", started: true},+ {name: "deferred", status: "deferred"},+ {name: "builder running output", status: "running", started: true, output: true, builder: true},+ {name: "builder running empty offline", status: "running", started: true, builder: true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ ctx := context.Background()+ runtimeID, ownerID, memberID := runtimeVisibilityFixture(t)+ dbfx.Exec(t, `UPDATE agent_runtime SET visibility = 'public' WHERE id = $1`, runtimeID)+ agentID := createRuntimePrivacyAgent(t, runtimeID, memberID, "Revoked Chat Agent")+ if tc.builder {+ dbfx.Exec(t, `UPDATE agent SET kind = 'system', system_key = 'agent_builder:revoked-chat' WHERE id = $1`, agentID)+ }+ sessionID := dbfx.ChatSession(t, agentID, testutil.Cols{"creator_id": memberID})+ cols := testutil.Cols{"runtime_id": runtimeID, "chat_session_id": sessionID, "status": tc.status, "initiator_user_id": memberID}+ if tc.started {+ cols["started_at"], cols["session_id"] = time.Now().Add(-time.Minute), "revoked-provider-session"+ }+ taskID := dbfx.Task(t, agentID, cols)+ dbfx.Exec(t, `UPDATE agent_task_queue SET chat_input_task_id = id WHERE id = $1`, taskID)+ messageID := dbfx.Insert(t, "chat_message", testutil.Cols{"chat_session_id": sessionID, "role": "user", "content": "keep this prompt", "task_id": taskID, "channel_ingested": tc.channel})+ attachmentID := dbfx.Insert(t, "attachment", testutil.Cols{+ "workspace_id": testWorkspaceID, "uploader_type": "member", "uploader_id": memberID,+ "filename": "input.txt", "url": "https://example.com/input.txt", "content_type": "text/plain", "size_bytes": 1,+ "chat_session_id": sessionID, "chat_message_id": messageID,+ })+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_draft_restore WHERE task_id = $1`, taskID) })+ if tc.output {+ dbfx.Insert(t, "task_message", testutil.Cols{"task_id": taskID, "seq": 0, "type": "text", "content": "partial answer"})+ }+ runtimePrivacyRequest(t, runtimeID, ownerID, map[string]any{+ "expected_nonowner_agent_ids": []string{agentID}, "expected_task_ids": []string{taskID},+ }).Want(http.StatusOK)+ task, err := testHandler.Queries.GetAgentTask(ctx, mustTestUUID(t, taskID))+ if err != nil || task.Status != "cancelled" || task.FailureReason.String != "runtime_access_revoked" {+ t.Fatalf("revoked task=%+v err=%v", task, err)+ }+ deferred := tc.started && !tc.output && !tc.channel+ if task.ChatFinalizeDeferredAt.Valid != deferred {+ t.Fatalf("deferred marker=%v want %v", task.ChatFinalizeDeferredAt.Valid, deferred)+ }+ if tc.started {+ session, err := testHandler.Queries.GetChatSession(ctx, mustTestUUID(t, sessionID))+ if err != nil || session.SessionID.String != "revoked-provider-session" {+ t.Fatalf("cancelled resume pointer=%q err=%v", session.SessionID.String, err)+ }+ }+ if deferred && !testHandler.TaskService.FinalizeDeferredCancelledChat(ctx, task.ID) {+ t.Fatal("cancel ack did not settle the durable marker")+ }+ if testHandler.TaskService.FinalizeDeferredCancelledChat(ctx, task.ID) {+ t.Fatal("duplicate ack settled the same turn twice")+ }+ var restores, outcomes int+ dbfx.QueryRow(t, `SELECT count(*) FROM chat_draft_restore WHERE task_id = $1 AND content = 'keep this prompt' AND $2::uuid = ANY(attachment_ids)`, taskID, attachmentID).Scan(&restores)+ dbfx.QueryRow(t, `SELECT count(*) FROM chat_message WHERE task_id = $1 AND role = 'assistant' AND failure_reason = 'runtime_access_revoked'`, taskID).Scan(&outcomes)+ if tc.output || tc.channel {+ if restores != 0 || outcomes != 1 {+ t.Fatalf("restores=%d outcomes=%d, want 0/1", restores, outcomes)+ }+ } else if restores != 1 || outcomes != 0 {+ t.Fatalf("restores=%d outcomes=%d, want 1/0", restores, outcomes)+ }+ })+ }+}++func TestRuntimeRevocationRollsBackChatAndBindings(t *testing.T) {+ if testHandler == nil {+ t.Fatal("database-backed handler fixture is required")+ }+ ctx := context.Background()+ runtimeID, ownerID, memberID := runtimeVisibilityFixture(t)+ dbfx.Exec(t, `UPDATE agent_runtime SET visibility = 'public' WHERE id = $1`, runtimeID)+ agentID := createRuntimePrivacyAgent(t, runtimeID, memberID, "Rollback Chat Agent")+ sessionID := dbfx.ChatSession(t, agentID)+ taskID := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "chat_session_id": sessionID, "status": "running", "session_id": "must-not-advance"})+ h := *testHandler+ h.TxStarter = rollbackOnCommitTxStarter{pool: testPool}+ req := newRequestAs(ownerID, http.MethodPost, "/api/runtimes/"+runtimeID+"/revoke-workspace-access", map[string]any{+ "expected_nonowner_agent_ids": []string{agentID}, "expected_task_ids": []string{taskID},+ })+ testutil.Call(t, h.RevokeRuntimeWorkspaceAccess, testutil.WithURLParams(req, "runtimeId", runtimeID)).Want(http.StatusInternalServerError)+ var unchanged bool+ dbfx.QueryRow(t, `SELECT r.visibility = 'public' AND a.runtime_id = r.id AND t.status = 'running' AND t.chat_finalize_deferred_at IS NULL AND cs.session_id IS NULL+ FROM agent_runtime r JOIN agent a ON a.id = $2 JOIN agent_task_queue t ON t.id = $3 JOIN chat_session cs ON cs.id = t.chat_session_id WHERE r.id = $1`, runtimeID, agentID, taskID).Scan(&unchanged)+ if !unchanged {+ t.Fatal("failed commit partially revoked runtime access or chat state")+ }+ if testHandler.TaskService.FinalizeDeferredCancelledChat(ctx, mustTestUUID(t, taskID)) {+ t.Fatal("rolled-back marker was finalized")+ }+}++func TestRuntimeRevocationSettlesTaskSupplements(t *testing.T) {+ for _, status := range []string{"pending", "delivering"} {+ t.Run(status, func(t *testing.T) {+ _, ownerID, memberID := runtimeVisibilityFixture(t)+ fixture := newSupplementFixture(t, "codex", "running", true)+ var supplement CommentResponse+ supplementRequest(t, fixture, "0199a4e8-22ce-7b01-bba5-999999999999", "Supplement for the current run").Want(http.StatusCreated).JSON(&supplement)+ dbfx.Exec(t, `UPDATE agent_runtime SET owner_id = $2, visibility = 'public' WHERE id = $1`, fixture.runtimeID, ownerID)+ dbfx.Exec(t, `UPDATE agent SET owner_id = $2 WHERE id = $1`, fixture.agentID, memberID)+ dbfx.Exec(t, `UPDATE task_supplement SET status = $2 WHERE comment_id = $1`, supplement.ID, status)+ runtimePrivacyRequest(t, fixture.runtimeID, ownerID, map[string]any{+ "expected_nonowner_agent_ids": []string{fixture.agentID}, "expected_task_ids": []string{fixture.taskID},+ }).Want(http.StatusOK)+ receipt, err := testHandler.Queries.GetTaskSupplementForRun(t.Context(), db.GetTaskSupplementForRunParams{+ CommentID: parseUUID(supplement.ID), TaskID: parseUUID(fixture.taskID), WorkspaceID: parseUUID(testWorkspaceID),+ })+ if err != nil || receipt.Status != "failed" || receipt.FailureReason.String != "turn_ended" {+ t.Fatalf("revocation left an unresolved supplement: %#v, error=%v", receipt, err)+ }+ })+ }+}++func TestRuntimeRevocationDoesNotDeadlockChatWriter(t *testing.T) {+ if testHandler == nil {+ t.Fatal("database-backed handler fixture is required")+ }+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ runtimeID, ownerID, memberID := runtimeVisibilityFixture(t)+ dbfx.Exec(t, `UPDATE agent_runtime SET visibility = 'public' WHERE id = $1`, runtimeID)+ agentID := createRuntimePrivacyAgent(t, runtimeID, memberID, "Busy Chat Agent")+ sessionID := dbfx.ChatSession(t, agentID)+ taskID := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "chat_session_id": sessionID, "status": "running"})+ writer, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatal(err)+ }+ defer writer.Rollback(context.Background())+ if _, err := db.New(writer).LockChatSessionForDelete(ctx, mustTestUUID(t, sessionID)); err != nil {+ t.Fatal(err)+ }+ body := map[string]any{"expected_nonowner_agent_ids": []string{agentID}, "expected_task_ids": []string{taskID}}+ req := newRequestAs(ownerID, http.MethodPost, "/api/runtimes/"+runtimeID+"/revoke-workspace-access", body).WithContext(ctx)+ var response struct {+ Code string `json:"code"`+ }+ testutil.Call(t, testHandler.RevokeRuntimeWorkspaceAccess, testutil.WithURLParams(req, "runtimeId", runtimeID)).Want(http.StatusConflict).JSON(&response)+ if response.Code != "runtime_access_revocation_busy" {+ t.Fatalf("busy response=%+v", response)+ }+ // A chat writer can finish in its normal session -> agent order after the+ // revocation has released its provisional agent lock.+ if _, err := db.New(writer).GetAgentForClaimUpdate(ctx, mustTestUUID(t, agentID)); err != nil {+ t.Fatal(err)+ }+ if err := writer.Commit(ctx); err != nil {+ t.Fatal(err)+ }+ runtimePrivacyRequest(t, runtimeID, ownerID, body).Want(http.StatusOK)+}++func createRuntimePrivacyAgent(t *testing.T, runtimeID, ownerID, name string) string {+ t.Helper()+ return dbfx.Agent(t, name, runtimeID, testutil.Cols{+ "owner_id": ownerID,+ })+}++func TestRuntimeRevocationPlanExposesOnlyAgentIdentity(t *testing.T) {+ if testHandler == nil {+ t.Fatal("database-backed handler fixture is required")+ }+ runtimeID, ownerID, memberID := runtimeVisibilityFixture(t)+ dbfx.Exec(t, `UPDATE agent_runtime SET visibility = 'public' WHERE id = $1`, runtimeID)+ agentID := dbfx.Agent(t, "Private teammate agent", runtimeID, testutil.Cols{+ "owner_id": memberID, "visibility": "private", "instructions": "private instructions",+ "runtime_config": testutil.Raw(`'{"private_setting":"private value"}'::jsonb`),+ "mcp_config": testutil.Raw(`'{"private_server":{"command":"private-command"}}'::jsonb`),+ })+ // Check both the first preview and a stale confirmed plan: both responses+ // are visible to the machine owner, who need not own the private agent.+ for _, confirmed := range []bool{false, true} {+ method, path, handler := http.MethodPatch, "/api/runtimes/"+runtimeID, testHandler.UpdateAgentRuntime+ body := map[string]any{"visibility": "private"}+ if confirmed {+ method, path, handler = http.MethodPost, path+"/revoke-workspace-access", testHandler.RevokeRuntimeWorkspaceAccess+ body = map[string]any{"expected_nonowner_agent_ids": []string{}, "expected_task_ids": []string{}}+ }+ req := newRequestAs(ownerID, method, path, body)+ var plan struct {+ Agents []map[string]json.RawMessage `json:"nonowner_agents"`+ }+ testutil.Call(t, handler, testutil.WithURLParams(req, "runtimeId", runtimeID)).Want(http.StatusConflict).JSON(&plan)+ if len(plan.Agents) != 1 || len(plan.Agents[0]) != 2 || string(plan.Agents[0]["id"]) != `"`+agentID+`"` || string(plan.Agents[0]["name"]) != `"Private teammate agent"` {+ t.Fatalf("confirmation plan must expose only the affected agent's id and name: %+v", plan)+ }+ }+}++func runtimePrivacyRequest(t *testing.T, runtimeID, actorID string, body map[string]any) *testutil.Response {+ t.Helper()+ req := newRequestAs(actorID, http.MethodPost, "/api/runtimes/"+runtimeID+"/revoke-workspace-access", body)+ return testutil.Call(t, testHandler.RevokeRuntimeWorkspaceAccess, testutil.WithURLParams(req, "runtimeId", runtimeID))+}++// TestRevokeRuntimeWorkspaceAccess verifies the full public-to-private+// contract: a teammate's user and Builder agents are unbound and their work becomes a+// durable cancellation, while the machine owner's agent and work continue.+func TestRevokeRuntimeWorkspaceAccess(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ runtimeID, runtimeOwnerID, memberID := runtimeVisibilityFixture(t)+ dbfx.Exec(t, `UPDATE agent_runtime SET visibility = 'public' WHERE id = $1`, runtimeID)++ ownerAgentID := createRuntimePrivacyAgent(t, runtimeID, runtimeOwnerID, "Runtime Privacy Owner Agent")+ memberAgentID := createRuntimePrivacyAgent(t, runtimeID, memberID, "Runtime Privacy Member Agent")+ ownerBuilderID := dbfx.Agent(t, "Runtime Privacy Owner Builder", runtimeID, testutil.Cols{+ "owner_id": runtimeOwnerID, "kind": "system", "system_key": "agent_builder:privacy-owner",+ })+ memberBuilderID := dbfx.Agent(t, "Runtime Privacy Member Builder", runtimeID, testutil.Cols{+ "owner_id": memberID, "kind": "system", "system_key": "agent_builder:privacy-member",+ })+ ownerBuilderTaskID := dbfx.Task(t, ownerBuilderID, testutil.Cols{"runtime_id": runtimeID, "status": "running"})+ memberBuilderTaskID := dbfx.Task(t, memberBuilderID, testutil.Cols{"runtime_id": runtimeID, "status": "running"})+ memberAutopilotID := dbfx.Insert(t, "autopilot", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "title": "Runtime Privacy Member Autopilot",+ "assignee_type": "agent",+ "assignee_id": memberAgentID,+ "status": "active",+ "execution_mode": "run_only",+ "created_by_type": "member",+ "created_by_id": testUserID,+ })+ ownerTaskID := dbfx.Task(t, ownerAgentID, testutil.Cols{+ "runtime_id": runtimeID,+ "status": "running",+ })+ memberTaskID := dbfx.Task(t, memberAgentID, testutil.Cols{+ "runtime_id": runtimeID,+ "status": "running",+ })++ // A regular PATCH cannot silently revoke a teammate's execution. It returns+ // the plan the owner must explicitly confirm instead.+ patch := newRequestAs(runtimeOwnerID, http.MethodPatch, "/api/runtimes/"+runtimeID, map[string]any{"visibility": "private"})+ var plan struct {+ Code string `json:"code"`+ NonownerAgents []AgentResponse `json:"nonowner_agents"`+ ActiveTaskIDs []string `json:"active_task_ids"`+ }+ testutil.Call(t, testHandler.UpdateAgentRuntime, testutil.WithURLParams(patch, "runtimeId", runtimeID)).Want(http.StatusConflict).JSON(&plan)+ if plan.Code != "runtime_has_nonowner_dependents" || len(plan.NonownerAgents) != 2 || !slices.ContainsFunc(plan.NonownerAgents, func(a AgentResponse) bool { return a.ID == memberAgentID }) || !slices.ContainsFunc(plan.NonownerAgents, func(a AgentResponse) bool { return a.ID == memberBuilderID }) {+ t.Fatalf("unexpected privacy plan: %+v", plan)+ }+ if len(plan.ActiveTaskIDs) != 2 || !slices.Contains(plan.ActiveTaskIDs, memberTaskID) || !slices.Contains(plan.ActiveTaskIDs, memberBuilderTaskID) {+ t.Fatalf("unexpected active task plan: %+v", plan.ActiveTaskIDs)+ }++ // A stale/empty confirmation is rejected rather than applying a partial+ // privacy transition.+ var stale struct {+ Code string `json:"code"`+ }+ runtimePrivacyRequest(t, runtimeID, runtimeOwnerID, map[string]any{+ "expected_nonowner_agent_ids": []string{},+ "expected_task_ids": []string{},+ }).Want(http.StatusConflict).JSON(&stale)+ if stale.Code != "runtime_access_revocation_plan_changed" {+ t.Fatalf("stale plan code = %q, want runtime_access_revocation_plan_changed", stale.Code)+ }++ runtimePrivacyRequest(t, runtimeID, runtimeOwnerID, map[string]any{+ "expected_nonowner_agent_ids": []string{memberAgentID, memberBuilderID},+ "expected_task_ids": []string{memberTaskID, memberBuilderTaskID},+ }).Want(http.StatusOK)++ var visibility string+ if err := testPool.QueryRow(ctx, `SELECT visibility FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&visibility); err != nil {+ t.Fatalf("read runtime visibility: %v", err)+ }+ if visibility != "private" {+ t.Fatalf("runtime visibility = %q, want private", visibility)+ }+ var memberBound, ownerBound bool+ if err := testPool.QueryRow(ctx, `SELECT runtime_id IS NOT NULL FROM agent WHERE id = $1`, memberAgentID).Scan(&memberBound); err != nil {+ t.Fatalf("read teammate binding: %v", err)+ }+ if err := testPool.QueryRow(ctx, `SELECT runtime_id IS NOT NULL FROM agent WHERE id = $1`, ownerAgentID).Scan(&ownerBound); err != nil {+ t.Fatalf("read owner binding: %v", err)+ }+ if memberBound || !ownerBound {+ t.Fatalf("bindings after revocation: member=%v owner=%v; want false/true", memberBound, ownerBound)+ }+ var autopilotStatus, autopilotPauseReason string+ if err := testPool.QueryRow(ctx, `SELECT status, COALESCE(pause_reason, '') FROM autopilot WHERE id = $1`, memberAutopilotID).Scan(&autopilotStatus, &autopilotPauseReason); err != nil {+ t.Fatalf("read teammate autopilot: %v", err)+ }+ if autopilotStatus != "paused" || autopilotPauseReason != string(ReasonAgentRuntimeRequired) {+ t.Fatalf("teammate autopilot = %s/%s, want paused/%s", autopilotStatus, autopilotPauseReason, ReasonAgentRuntimeRequired)+ }++ var memberStatus, memberReason, ownerStatus string+ if err := testPool.QueryRow(ctx, `SELECT status, COALESCE(failure_reason, '') FROM agent_task_queue WHERE id = $1`, memberTaskID).Scan(&memberStatus, &memberReason); err != nil {+ t.Fatalf("read teammate task: %v", err)+ }+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, ownerTaskID).Scan(&ownerStatus); err != nil {+ t.Fatalf("read owner task: %v", err)+ }+ if memberStatus != "cancelled" || memberReason != "runtime_access_revoked" || ownerStatus != "running" {+ t.Fatalf("task states after revocation: member=%s/%s owner=%s", memberStatus, memberReason, ownerStatus)+ }++ // Hidden Builder carriers borrow the same machine. Their owner, rather than+ // their kind, determines whose binding and execution must be preserved.+ for _, tc := range []struct {+ agentID, taskID string+ owner bool+ }{+ {ownerBuilderID, ownerBuilderTaskID, true},+ {memberBuilderID, memberBuilderTaskID, false},+ } {+ var bound bool+ var status, reason string+ dbfx.QueryRow(t, `SELECT a.runtime_id IS NOT NULL, task.status, COALESCE(task.failure_reason, '') FROM agent a JOIN agent_task_queue task ON task.agent_id = a.id WHERE a.id = $1 AND task.id = $2`, tc.agentID, tc.taskID).Scan(&bound, &status, &reason)+ if tc.owner {+ if !bound || status != "running" {+ t.Fatalf("owner Builder changed: bound=%v status=%s", bound, status)+ }+ } else if bound || status != "cancelled" || reason != "runtime_access_revoked" {+ t.Fatalf("teammate Builder retained access: bound=%v status=%s reason=%s", bound, status, reason)+ }+ }++ // A daemon that completed just after its cancellation poll cannot revive the+ // task: CompleteAgentTask only transitions a still-running row.+ _, err := testHandler.Queries.CompleteAgentTask(ctx, db.CompleteAgentTaskParams{+ ID: mustTestUUID(t, memberTaskID),+ Result: []byte(`{"late":true}`),+ SessionRolloutMissing: false,+ })+ if !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("late completion error = %v, want pgx.ErrNoRows", err)+ }+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, memberTaskID).Scan(&memberStatus); err != nil {+ t.Fatalf("re-read teammate task: %v", err)+ }+ if memberStatus != "cancelled" {+ t.Fatalf("late completion revived task to %q", memberStatus)+ }+}++// TestUpdateAgentRuntimePrivateWithoutTeammateDependencies exercises the+// direct path. It must use the same locked snapshot as the confirmed path,+// even though it has nothing disruptive to revoke.+func TestUpdateAgentRuntimePrivateWithoutTeammateDependencies(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ runtimeID, runtimeOwnerID, _ := runtimeVisibilityFixture(t)+ dbfx.Exec(t, `UPDATE agent_runtime SET visibility = 'public' WHERE id = $1`, runtimeID)++ req := newRequestAs(runtimeOwnerID, http.MethodPatch, "/api/runtimes/"+runtimeID, map[string]any{"visibility": "private"})+ testutil.Call(t, testHandler.UpdateAgentRuntime, testutil.WithURLParams(req, "runtimeId", runtimeID)).Want(http.StatusOK)+ var visibility string+ if err := testPool.QueryRow(ctx, `SELECT visibility FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&visibility); err != nil {+ t.Fatalf("read runtime visibility: %v", err)+ }+ if visibility != "private" {+ t.Fatalf("runtime visibility = %q, want private", visibility)+ }+}++func mustTestUUID(t *testing.T, raw string) pgtype.UUID {+ t.Helper()+ value, err := uuidFromString(raw)+ if err != nil {+ t.Fatalf("parse test UUID %q: %v", raw, err)+ }+ return value+}diff --git a/server/internal/handler/workspace_delete_fence_test.go b/server/internal/handler/workspace_delete_fence_test.goindex 605d47d8b9..7bbf9b628e 100644--- a/server/internal/handler/workspace_delete_fence_test.go+++ b/server/internal/handler/workspace_delete_fence_test.go@@ -304,16 +304,17 @@ VALUES ($1, $2, 'member', $3, $4) RETURNING iderrs := make([]error, 2*rounds)for i := 0; i < rounds; i++ {wg.Add(2)- // Owners drawn from both workspaces, in mirrored roles.+ // Owners drawn from both workspaces, in mirrored roles. Keep each+ // runtime matched to its agent: enqueue now rejects stale bindings.go func(i int) {defer wg.Done()errs[2*i] = enqueueViaRealQuery(ctx, testHandler.Queries,- f.victimAgent, f.neighbourRuntime, neighbourIssues[i])+ f.victimAgent, f.victimRuntime, neighbourIssues[i])}(i)go func(i int) {defer wg.Done()errs[2*i+1] = enqueueViaRealQuery(ctx, testHandler.Queries,- f.neighbourAgent, f.victimRuntime, victimIssues[i])+ f.neighbourAgent, f.neighbourRuntime, victimIssues[i])}(i)}wg.Wait()@@ -332,7 +333,7 @@ VALUES ($1, $2, 'member', $3, $4) RETURNING idif _, err := testPool.Exec(ctx, `DELETE FROM agent_task_queueWHERE (agent_id = $1 AND runtime_id = $2) OR (agent_id = $3 AND runtime_id = $4)-`, f.victimAgent, f.neighbourRuntime, f.neighbourAgent, f.victimRuntime); err != nil {+`, f.victimAgent, f.victimRuntime, f.neighbourAgent, f.neighbourRuntime); err != nil {t.Fatalf("clean up: %v", err)}}diff --git a/server/internal/service/builtin_skills/multica-platform/references/runtimes.md b/server/internal/service/builtin_skills/multica-platform/references/runtimes.mdindex dd42ec56e9..00938d127e 100644--- a/server/internal/service/builtin_skills/multica-platform/references/runtimes.md+++ b/server/internal/service/builtin_skills/multica-platform/references/runtimes.md@@ -24,6 +24,21 @@ The chain is:## CLI+Making a public runtime private requires its owner's confirmation when other+members have bound agents or active runs, including Agent Builder sessions.+Confirmation unbinds those agents,+cancels their active runs (`runtime_access_revoked`), and pauses their active+autopilots; the runtime owner's own work is unaffected. A changed dependency+plan requires renewed confirmation. Treat a busy chat conflict as retryable,+not as a successful visibility change. Rebind the affected agent to an+accessible runtime before starting another run, and explicitly resume paused+autopilots. Chat cancellation persists input/attachment recovery data; the+existing recovery UI is available on web/desktop, not yet on mobile.+Offline daemons cannot receive the stop request until reconnecting, so+server-side revocation does not guarantee immediate termination of a local+process. The existing CLI exposes rebind and cancellation status; it does not+provide a runtime-visibility switch or bypass the confirmation flow.+```bashmultica runtime list --output jsonmultica runtime usage <runtime-id> --output jsondiff --git a/server/internal/service/runtime_access_cancellation.go b/server/internal/service/runtime_access_cancellation.gonew file mode 100644index 0000000000..f75e5746ea--- /dev/null+++ b/server/internal/service/runtime_access_cancellation.go@@ -0,0 +1,53 @@+package service++import (+ "context"+ "fmt"++ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// PrepareRuntimeAccessCancellation makes chat settlement durable in the same+// transaction as access revocation. The caller already holds the affected+// session and task locks. No events or nested transactions may run here.+//+// Every chat gets the existing finalize marker, so a crash after commit cannot+// strand its input. Started, empty turns wait for cancel-ack (or the sweeper's+// grace period); all others can use FinalizeDeferredCancelledChat immediately+// after commit. That single idempotent finalizer owns transcript messages,+// attachment detachment and persisted draft restores for disconnected clients.+func PrepareRuntimeAccessCancellation(ctx context.Context, qtx *db.Queries, tasks []db.AgentTaskQueue) ([]pgtype.UUID, error) {+ if err := SettleTerminalTaskState(ctx, qtx, tasks...); err != nil {+ return nil, err+ }+ var ready []pgtype.UUID+ for _, task := range tasks {+ if !task.ChatSessionID.Valid {+ continue+ }+ if err := qtx.AdvanceCancelledChatSessionPointer(ctx, task.ID); err != nil {+ return nil, fmt.Errorf("advance cancelled chat pointer: %w", err)+ }+ if _, err := qtx.MarkChatFinalizeDeferred(ctx, task.ID); err != nil {+ return nil, fmt.Errorf("mark revoked chat for settlement: %w", err)+ }+ if task.StartedAt.Valid {+ messages, err := qtx.ListTaskMessages(ctx, task.ID)+ if err != nil {+ return nil, fmt.Errorf("read revoked chat output: %w", err)+ }+ if len(messages) == 0 {+ channelIngested, err := qtx.TaskHasChannelIngestedMessages(ctx, chatInputOwnerID(task))+ if err != nil {+ return nil, fmt.Errorf("read revoked chat provenance: %w", err)+ }+ if !channelIngested {+ continue+ }+ }+ }+ ready = append(ready, task.ID)+ }+ return ready, nil+}diff --git a/server/internal/service/runtime_retry_binding_test.go b/server/internal/service/runtime_retry_binding_test.gonew file mode 100644index 0000000000..0d06a3e2f3--- /dev/null+++ b/server/internal/service/runtime_retry_binding_test.go@@ -0,0 +1,133 @@+package service++import (+ "context"+ "errors"+ "fmt"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ "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"+)++// A retry retains its parent's runtime even when the agent's binding changes.+// Enqueue must preserve that recovery attempt; claim enforces the current binding.+func TestRetryPreservesChildAcrossRuntimeBindingChanges(t *testing.T) {+ for _, tt := range []struct {+ name string+ atomicFailure bool+ unbound bool+ }{+ {name: "FailTask/rebound", atomicFailure: true},+ {name: "FailTask/unbound", atomicFailure: true, unbound: true},+ {name: "MaybeRetryFailedTask/rebound"},+ {name: "MaybeRetryFailedTask/unbound", unbound: true},+ } {+ t.Run(tt.name, func(t *testing.T) {+ ctx := context.Background()+ pool := newResolveOriginatorPool(t)+ q := db.New(pool)+ bootstrap := testutil.New(pool, "", "")+ suffix := time.Now().UnixNano()+ userID := bootstrap.User(t, "retry-owner", fmt.Sprintf("retry-owner-%[email protected]", suffix))+ workspaceID := bootstrap.Workspace(t, "runtime retry binding", fmt.Sprintf("runtime-retry-%d", suffix))+ fx := testutil.New(pool, workspaceID, userID)+ fx.Member(t, workspaceID, userID, "owner")+ runtimeA := fx.Runtime(t, "original runtime")+ runtimeB := fx.Runtime(t, "replacement runtime")+ agentID := fx.Agent(t, "retry agent", runtimeA)+ issueID := fx.Issue(t, "retry after runtime binding change")+ status := "failed"+ if tt.atomicFailure {+ status = "running"+ }+ parentID := fx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeA,+ "issue_id": issueID,+ "status": status,+ "attempt": 1,+ "max_attempts": 2,+ "failure_reason": "timeout",+ })+ fx.Cleanup(t, `DELETE FROM agent_task_queue WHERE parent_task_id = $1`, parentID)++ // Both private runtimes belong to this agent's owner, so the rebind+ // is legal. Unbinding is the other state the enqueue guard rejected.+ var nextRuntime any = runtimeB+ if tt.unbound {+ nextRuntime = nil+ }+ fx.Exec(t, `UPDATE agent SET runtime_id = $1 WHERE id = $2`, nextRuntime, agentID)+ svc := NewTaskService(q, pool, nil, events.New())+ parentUUID := util.MustParseUUID(parentID)+ triggerRetry := func() {+ t.Helper()+ if tt.atomicFailure {+ if _, err := svc.FailTask(ctx, parentUUID, "runtime timed out", "", "", "", "timeout", false, "", ""); err != nil {+ t.Fatalf("FailTask: %v", err)+ }+ return+ }+ parent, err := q.GetAgentTask(ctx, parentUUID)+ if err != nil {+ t.Fatalf("load failed parent: %v", err)+ }+ if _, err := svc.MaybeRetryFailedTask(ctx, parent); err != nil {+ t.Fatalf("MaybeRetryFailedTask: %v", err)+ }+ }+ triggerRetry()+ triggerRetry()++ var childID pgtype.UUID+ var children int+ fx.QueryRow(t, `SELECT count(*) FROM agent_task_queue WHERE parent_task_id = $1`, parentID).Scan(&children)+ if children != 1 {+ t.Fatalf("retry children = %d, want exactly one after repeated failure/recovery", children)+ }+ fx.QueryRow(t, `SELECT id FROM agent_task_queue WHERE parent_task_id = $1`, parentID).Scan(&childID)+ child, err := q.GetAgentTask(ctx, childID)+ if err != nil {+ t.Fatalf("load retry child: %v", err)+ }+ if child.RuntimeID != util.MustParseUUID(runtimeA) || child.Status != "queued" || child.Attempt != 2 {+ t.Fatalf("retry child = runtime:%s status:%q attempt:%d, want original runtime %s, queued, attempt 2",+ util.UUIDToString(child.RuntimeID), child.Status, child.Attempt, runtimeA)+ }+ var parentStatus string+ fx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id = $1`, parentID).Scan(&parentStatus)+ if parentStatus != "failed" {+ t.Fatalf("parent status = %q, want failed", parentStatus)+ }++ claimParams := db.ClaimAgentTaskParams{+ AgentID: util.MustParseUUID(agentID),+ RuntimeID: util.MustParseUUID(runtimeA),+ PrepareLeaseSecs: 60,+ RuntimeStaleSecs: RuntimeClaimFreshnessSeconds,+ }+ if _, err := q.ClaimAgentTask(ctx, claimParams); !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("claim on old runtime with changed binding = %v, want no rows", err)+ }+ var childStatus string+ fx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id = $1`, childID).Scan(&childStatus)+ if childStatus != "queued" {+ t.Fatalf("rejected claim changed retry status to %q, want queued", childStatus)+ }++ fx.Exec(t, `UPDATE agent SET runtime_id = $1 WHERE id = $2`, runtimeA, agentID)+ claimed, err := q.ClaimAgentTask(ctx, claimParams)+ if err != nil {+ t.Fatalf("claim retry after restoring original runtime: %v", err)+ }+ if claimed.ID != childID {+ t.Fatalf("claimed task = %s, want existing retry %s", util.UUIDToString(claimed.ID), util.UUIDToString(childID))+ }+ })+ }+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 5893204d90..1dc8d4184a 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -3456,6 +3456,7 @@ func (s *TaskService) FinalizeDeferredCancelledChat(ctx context.Context, taskIDContent: "Stopped.",TaskID: claimed.ID,ElapsedMs: computeChatElapsedMs(claimed),+ FailureReason: claimed.FailureReason,})if err != nil {return fmt.Errorf("create cancelled chat message: %w", err)diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 62aab47fa0..03ae31691a 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -5642,6 +5642,137 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListCreturn items, nil}+const listNonOwnerAgentsByRuntime = `-- name: ListNonOwnerAgentsByRuntime :many+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters FROM agent+WHERE runtime_id = $1+ AND owner_id IS DISTINCT FROM $2+ORDER BY name ASC+`++type ListNonOwnerAgentsByRuntimeParams struct {+ RuntimeID pgtype.UUID `json:"runtime_id"`+ RuntimeOwnerID pgtype.UUID `json:"runtime_owner_id"`+}++// Returns every agent bound to a runtime whose owner differs from its owner,+// including hidden Builder execution carriers. This is the dependency plan shown before a public+// runtime is made private: owner-owned agents keep their binding, while every+// teammate-owned agent loses machine access.+func (q *Queries) ListNonOwnerAgentsByRuntime(ctx context.Context, arg ListNonOwnerAgentsByRuntimeParams) ([]Agent, error) {+ rows, err := q.db.Query(ctx, listNonOwnerAgentsByRuntime, arg.RuntimeID, arg.RuntimeOwnerID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []Agent{}+ for rows.Next() {+ var i Agent+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Name,+ &i.AvatarUrl,+ &i.RuntimeMode,+ &i.RuntimeConfig,+ &i.Visibility,+ &i.Status,+ &i.MaxConcurrentTasks,+ &i.OwnerID,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.Description,+ &i.RuntimeID,+ &i.Instructions,+ &i.ArchivedAt,+ &i.ArchivedBy,+ &i.CustomEnv,+ &i.CustomArgs,+ &i.McpConfig,+ &i.Model,+ &i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,+ &i.Kind,+ &i.SystemKey,+ &i.DisabledRuntimeSkills,+ &i.ServiceTier,+ &i.ConversationStarters,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listNonOwnerAgentsByRuntimeForUpdate = `-- name: ListNonOwnerAgentsByRuntimeForUpdate :many+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters FROM agent+WHERE runtime_id = $1+ AND owner_id IS DISTINCT FROM $2+ORDER BY id+FOR UPDATE NOWAIT+`++type ListNonOwnerAgentsByRuntimeForUpdateParams struct {+ RuntimeID pgtype.UUID `json:"runtime_id"`+ RuntimeOwnerID pgtype.UUID `json:"runtime_owner_id"`+}++// Runtime access-change locking serializes new bindings. NOWAIT avoids waiting+// behind a writer that already holds an agent and needs the runtime row.+func (q *Queries) ListNonOwnerAgentsByRuntimeForUpdate(ctx context.Context, arg ListNonOwnerAgentsByRuntimeForUpdateParams) ([]Agent, error) {+ rows, err := q.db.Query(ctx, listNonOwnerAgentsByRuntimeForUpdate, arg.RuntimeID, arg.RuntimeOwnerID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []Agent{}+ for rows.Next() {+ var i Agent+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Name,+ &i.AvatarUrl,+ &i.RuntimeMode,+ &i.RuntimeConfig,+ &i.Visibility,+ &i.Status,+ &i.MaxConcurrentTasks,+ &i.OwnerID,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.Description,+ &i.RuntimeID,+ &i.Instructions,+ &i.ArchivedAt,+ &i.ArchivedBy,+ &i.CustomEnv,+ &i.CustomArgs,+ &i.McpConfig,+ &i.Model,+ &i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,+ &i.Kind,+ &i.SystemKey,+ &i.DisabledRuntimeSkills,+ &i.ServiceTier,+ &i.ConversationStarters,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listPendingDelegatedFailureRecoveries = `-- name: ListPendingDelegatedFailureRecoveries :manySELECT recovery.id, recovery.issue_id, recovery.author_type, recovery.author_id, recovery.content, recovery.type, recovery.created_at, recovery.updated_at, recovery.parent_id, recovery.workspace_id, recovery.resolved_at, recovery.resolved_by_type, recovery.resolved_by_id, recovery.source_task_id, recovery.quick_action_id, recovery.via_plugin_id, recovery.revision, recovery.recovery_settled_at, recovery.deleted_at, recovery.suppressed_agent_idsFROM comment recoverydiff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.goindex b0d972774e..02f60629d2 100644--- a/server/pkg/db/generated/runtime.sql.go+++ b/server/pkg/db/generated/runtime.sql.go@@ -128,6 +128,114 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Cancreturn items, nil}+const cancelNonOwnerTasksByRuntime = `-- name: CancelNonOwnerTasksByRuntime :many+UPDATE agent_task_queue AS task+SET status = 'cancelled',+ completed_at = now(), prepare_lease_expires_at = NULL,+ error = 'runtime access was revoked',+ failure_reason = $1::text,+ cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULL,+ wait_reason = NULL+FROM agent+WHERE task.agent_id = agent.id+ AND task.runtime_id = $2+ AND agent.owner_id IS DISTINCT FROM $3+ AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step+`++type CancelNonOwnerTasksByRuntimeParams struct {+ FailureReason string `json:"failure_reason"`+ RuntimeID pgtype.UUID `json:"runtime_id"`+ RuntimeOwnerID pgtype.UUID `json:"runtime_owner_id"`+}++// Server-side execution revocation for a public runtime made private. The+// join deliberately classifies work by its agent owner rather than cancelling+// every task on the runtime, so the runtime owner's own tasks keep running.+// cancellation polling on an online daemon observes the state change; an+// offline daemon cannot run new work and will observe it after reconnecting.+func (q *Queries) CancelNonOwnerTasksByRuntime(ctx context.Context, arg CancelNonOwnerTasksByRuntimeParams) ([]AgentTaskQueue, error) {+ rows, err := q.db.Query(ctx, cancelNonOwnerTasksByRuntime, arg.FailureReason, arg.RuntimeID, arg.RuntimeOwnerID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []AgentTaskQueue{}+ for rows.Next() {+ var i AgentTaskQueue+ if err := rows.Scan(+ &i.ID,+ &i.AgentID,+ &i.IssueID,+ &i.Status,+ &i.Priority,+ &i.DispatchedAt,+ &i.StartedAt,+ &i.CompletedAt,+ &i.Result,+ &i.Error,+ &i.CreatedAt,+ &i.Context,+ &i.RuntimeID,+ &i.SessionID,+ &i.WorkDir,+ &i.TriggerCommentID,+ &i.ChatSessionID,+ &i.AutopilotRunID,+ &i.Attempt,+ &i.MaxAttempts,+ &i.ParentTaskID,+ &i.FailureReason,+ &i.TriggerSummary,+ &i.ForceFreshSession,+ &i.IsLeaderTask,+ &i.WaitReason,+ &i.InitiatorUserID,+ &i.HandoffNote,+ &i.PrepareLeaseExpiresAt,+ &i.SquadID,+ &i.RuntimeMcpOverlay,+ &i.EscalationForTaskID,+ &i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,+ &i.DeliveredCommentIds,+ &i.ChatInputTaskID,+ &i.ChatFinalizeDeferredAt,+ &i.OriginatorSource,+ &i.DelegatedFromTaskID,+ &i.RetryOfTaskID,+ &i.RerunOfTaskID,+ &i.RuleVersionID,+ &i.TriggerEvidenceKind,+ &i.TriggerEvidenceRefID,+ &i.AccountableUserID,+ &i.SessionRolloutMissing,+ &i.RetiredSessionID,+ &i.QuickActionsDisabled,+ &i.RegenerateQuickActionsFor,+ &i.BranchName,+ &i.DurableWorkDir,+ &i.ChannelContextRevision,+ &i.CommentThreadID,+ &i.CancelledByType,+ &i.CancelledByID,+ &i.CancelledByName,+ &i.IssueSnapshot,+ &i.WorkflowStep,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const countActiveAgentsByRuntime = `-- name: CountActiveAgentsByRuntime :oneSELECT count(*) FROM agent WHERE runtime_id = $1 AND archived_at IS NULL`@@ -777,6 +885,205 @@ func (q *Queries) ListDaemonCustomNames(ctx context.Context, arg ListDaemonCustoreturn items, nil}+const listNonOwnerActiveTasksByRuntime = `-- name: ListNonOwnerActiveTasksByRuntime :many+SELECT task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step+FROM agent_task_queue AS task+JOIN agent ON agent.id = task.agent_id+WHERE task.runtime_id = $1+ AND agent.owner_id IS DISTINCT FROM $2+ AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+ORDER BY task.id+`++type ListNonOwnerActiveTasksByRuntimeParams struct {+ RuntimeID pgtype.UUID `json:"runtime_id"`+ RuntimeOwnerID pgtype.UUID `json:"runtime_owner_id"`+}++// Lists live tasks targeting a public runtime but belonging to somebody other+// than its owner, including hidden Builder execution carriers. It forms part of the public-to-private+// confirmation plan so the owner explicitly approves cancelling work that+// could otherwise keep running after machine access is revoked.+func (q *Queries) ListNonOwnerActiveTasksByRuntime(ctx context.Context, arg ListNonOwnerActiveTasksByRuntimeParams) ([]AgentTaskQueue, error) {+ rows, err := q.db.Query(ctx, listNonOwnerActiveTasksByRuntime, arg.RuntimeID, arg.RuntimeOwnerID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []AgentTaskQueue{}+ for rows.Next() {+ var i AgentTaskQueue+ if err := rows.Scan(+ &i.ID,+ &i.AgentID,+ &i.IssueID,+ &i.Status,+ &i.Priority,+ &i.DispatchedAt,+ &i.StartedAt,+ &i.CompletedAt,+ &i.Result,+ &i.Error,+ &i.CreatedAt,+ &i.Context,+ &i.RuntimeID,+ &i.SessionID,+ &i.WorkDir,+ &i.TriggerCommentID,+ &i.ChatSessionID,+ &i.AutopilotRunID,+ &i.Attempt,+ &i.MaxAttempts,+ &i.ParentTaskID,+ &i.FailureReason,+ &i.TriggerSummary,+ &i.ForceFreshSession,+ &i.IsLeaderTask,+ &i.WaitReason,+ &i.InitiatorUserID,+ &i.HandoffNote,+ &i.PrepareLeaseExpiresAt,+ &i.SquadID,+ &i.RuntimeMcpOverlay,+ &i.EscalationForTaskID,+ &i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,+ &i.DeliveredCommentIds,+ &i.ChatInputTaskID,+ &i.ChatFinalizeDeferredAt,+ &i.OriginatorSource,+ &i.DelegatedFromTaskID,+ &i.RetryOfTaskID,+ &i.RerunOfTaskID,+ &i.RuleVersionID,+ &i.TriggerEvidenceKind,+ &i.TriggerEvidenceRefID,+ &i.AccountableUserID,+ &i.SessionRolloutMissing,+ &i.RetiredSessionID,+ &i.QuickActionsDisabled,+ &i.RegenerateQuickActionsFor,+ &i.BranchName,+ &i.DurableWorkDir,+ &i.ChannelContextRevision,+ &i.CommentThreadID,+ &i.CancelledByType,+ &i.CancelledByID,+ &i.CancelledByName,+ &i.IssueSnapshot,+ &i.WorkflowStep,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listNonOwnerActiveTasksByRuntimeForUpdate = `-- name: ListNonOwnerActiveTasksByRuntimeForUpdate :many+SELECT task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision, task.comment_thread_id, task.cancelled_by_type, task.cancelled_by_id, task.cancelled_by_name, task.issue_snapshot, task.workflow_step+FROM agent_task_queue AS task+JOIN agent ON agent.id = task.agent_id+WHERE task.runtime_id = $1+ AND agent.owner_id IS DISTINCT FROM $2+ AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+ORDER BY task.id+FOR UPDATE OF task+`++type ListNonOwnerActiveTasksByRuntimeForUpdateParams struct {+ RuntimeID pgtype.UUID `json:"runtime_id"`+ RuntimeOwnerID pgtype.UUID `json:"runtime_owner_id"`+}++// Acquired after the affected agent and chat-session locks. Bindings serialize+// on LockAgentRuntimeForAccessChange; claim/delivery rechecks authorization.+func (q *Queries) ListNonOwnerActiveTasksByRuntimeForUpdate(ctx context.Context, arg ListNonOwnerActiveTasksByRuntimeForUpdateParams) ([]AgentTaskQueue, error) {+ rows, err := q.db.Query(ctx, listNonOwnerActiveTasksByRuntimeForUpdate, arg.RuntimeID, arg.RuntimeOwnerID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []AgentTaskQueue{}+ for rows.Next() {+ var i AgentTaskQueue+ if err := rows.Scan(+ &i.ID,+ &i.AgentID,+ &i.IssueID,+ &i.Status,+ &i.Priority,+ &i.DispatchedAt,+ &i.StartedAt,+ &i.CompletedAt,+ &i.Result,+ &i.Error,+ &i.CreatedAt,+ &i.Context,+ &i.RuntimeID,+ &i.SessionID,+ &i.WorkDir,+ &i.TriggerCommentID,+ &i.ChatSessionID,+ &i.AutopilotRunID,+ &i.Attempt,+ &i.MaxAttempts,+ &i.ParentTaskID,+ &i.FailureReason,+ &i.TriggerSummary,+ &i.ForceFreshSession,+ &i.IsLeaderTask,+ &i.WaitReason,+ &i.InitiatorUserID,+ &i.HandoffNote,+ &i.PrepareLeaseExpiresAt,+ &i.SquadID,+ &i.RuntimeMcpOverlay,+ &i.EscalationForTaskID,+ &i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,+ &i.DeliveredCommentIds,+ &i.ChatInputTaskID,+ &i.ChatFinalizeDeferredAt,+ &i.OriginatorSource,+ &i.DelegatedFromTaskID,+ &i.RetryOfTaskID,+ &i.RerunOfTaskID,+ &i.RuleVersionID,+ &i.TriggerEvidenceKind,+ &i.TriggerEvidenceRefID,+ &i.AccountableUserID,+ &i.SessionRolloutMissing,+ &i.RetiredSessionID,+ &i.QuickActionsDisabled,+ &i.RegenerateQuickActionsFor,+ &i.BranchName,+ &i.DurableWorkDir,+ &i.ChannelContextRevision,+ &i.CommentThreadID,+ &i.CancelledByType,+ &i.CancelledByID,+ &i.CancelledByName,+ &i.IssueSnapshot,+ &i.WorkflowStep,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listStaleOfflineRuntimeGCCandidates = `-- name: ListStaleOfflineRuntimeGCCandidates :manySELECT id FROM agent_runtimeWHERE status = 'offline'@@ -925,6 +1232,79 @@ func (q *Queries) LockAgentRuntime(ctx context.Context, id pgtype.UUID) (AgentRureturn i, err}+const lockAgentRuntimeForAccessChange = `-- name: LockAgentRuntimeForAccessChange :one+SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name FROM agent_runtime WHERE id = $1 FOR NO KEY UPDATE+`++// Binding and visibility writers share this lock and recheck access under it.+// NO KEY UPDATE deliberately permits legacy FK KEY SHARE locks: a chat enqueue+// holding session/agent locks must not wait here while revocation locks them.+func (q *Queries) LockAgentRuntimeForAccessChange(ctx context.Context, id pgtype.UUID) (AgentRuntime, error) {+ row := q.db.QueryRow(ctx, lockAgentRuntimeForAccessChange, id)+ var i AgentRuntime+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.DaemonID,+ &i.Name,+ &i.RuntimeMode,+ &i.Provider,+ &i.Status,+ &i.DeviceInfo,+ &i.Metadata,+ &i.LastSeenAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.OwnerID,+ &i.LegacyDaemonID,+ &i.Visibility,+ &i.ProfileID,+ &i.CustomName,+ )+ return i, err+}++const lockRuntimeRevocationChatSessions = `-- name: LockRuntimeRevocationChatSessions :many+SELECT cs.id FROM chat_session cs+WHERE EXISTS (+ SELECT 1 FROM agent_task_queue task JOIN agent ON agent.id = task.agent_id+ WHERE task.chat_session_id = cs.id+ AND task.runtime_id = $1+ AND agent.owner_id IS DISTINCT FROM $2+ AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+)+ORDER BY cs.id+FOR UPDATE OF cs NOWAIT+`++type LockRuntimeRevocationChatSessionsParams struct {+ RuntimeID pgtype.UUID `json:"runtime_id"`+ RuntimeOwnerID pgtype.UUID `json:"runtime_owner_id"`+}++// Revocation already holds affected agents. Never wait in the reverse of the+// normal session -> agent/task order: a concurrent chat writer yields a 409+// and the entire revocation rolls back before changing anything.+func (q *Queries) LockRuntimeRevocationChatSessions(ctx context.Context, arg LockRuntimeRevocationChatSessionsParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, lockRuntimeRevocationChatSessions, arg.RuntimeID, arg.RuntimeOwnerID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ items = append(items, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const lockRuntimesForMerge = `-- name: LockRuntimesForMerge :manySELECT id FROM agent_runtimeWHERE id = ANY($1::uuid[])@@ -1332,6 +1712,72 @@ func (q *Queries) TouchAgentRuntimesLastSeenBatch(ctx context.Context, ids []pgtreturn items, nil}+const unbindNonOwnerAgentsFromRuntime = `-- name: UnbindNonOwnerAgentsFromRuntime :many+UPDATE agent+SET runtime_id = NULL, updated_at = now()+WHERE runtime_id = $1+ AND owner_id IS DISTINCT FROM $2+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+`++type UnbindNonOwnerAgentsFromRuntimeParams struct {+ RuntimeID pgtype.UUID `json:"runtime_id"`+ RuntimeOwnerID pgtype.UUID `json:"runtime_owner_id"`+}++// The companion to CancelNonOwnerTasksByRuntime for a public-to-private+// transition. Only teammates lose the binding; the runtime owner's agents+// remain bound and usable after the machine becomes private again.+func (q *Queries) UnbindNonOwnerAgentsFromRuntime(ctx context.Context, arg UnbindNonOwnerAgentsFromRuntimeParams) ([]Agent, error) {+ rows, err := q.db.Query(ctx, unbindNonOwnerAgentsFromRuntime, arg.RuntimeID, arg.RuntimeOwnerID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []Agent{}+ for rows.Next() {+ var i Agent+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Name,+ &i.AvatarUrl,+ &i.RuntimeMode,+ &i.RuntimeConfig,+ &i.Visibility,+ &i.Status,+ &i.MaxConcurrentTasks,+ &i.OwnerID,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.Description,+ &i.RuntimeID,+ &i.Instructions,+ &i.ArchivedAt,+ &i.ArchivedBy,+ &i.CustomEnv,+ &i.CustomArgs,+ &i.McpConfig,+ &i.Model,+ &i.ThinkingLevel,+ &i.ComposioToolkitAllowlist,+ &i.PermissionMode,+ &i.Kind,+ &i.SystemKey,+ &i.DisabledRuntimeSkills,+ &i.ServiceTier,+ &i.ConversationStarters,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const unbindTasksFromRuntime = `-- name: UnbindTasksFromRuntime :execrowsUPDATE agent_task_queueSET runtime_id = NULL@@ -1542,8 +1988,9 @@ type UpdateAgentRuntimeVisibilityParams struct {// Toggles a runtime between 'private' (only owner can bind agents) and// 'public' (any workspace member can). Default for new rows is 'private'-// (see migration 083). Gated at the handler layer to owner / workspace-// admin only.+// (see migration 083). Gated at the handler layer to the runtime owner only:+// visibility is consent to use that person's machine, not a workspace-governance+// setting.func (q *Queries) UpdateAgentRuntimeVisibility(ctx context.Context, arg UpdateAgentRuntimeVisibilityParams) (AgentRuntime, error) {row := q.db.QueryRow(ctx, updateAgentRuntimeVisibility, arg.Visibility, arg.ID)var i AgentRuntimediff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex c0bf634d04..ceef11884d 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -280,6 +280,25 @@ WHERE runtime_id = $1 AND kind = 'user'ORDER BY idFOR UPDATE;+-- name: ListNonOwnerAgentsByRuntime :many+-- Returns every agent bound to a runtime whose owner differs from its owner,+-- including hidden Builder execution carriers. This is the dependency plan shown before a public+-- runtime is made private: owner-owned agents keep their binding, while every+-- teammate-owned agent loses machine access.+SELECT * FROM agent+WHERE runtime_id = @runtime_id+ AND owner_id IS DISTINCT FROM @runtime_owner_id+ORDER BY name ASC;++-- name: ListNonOwnerAgentsByRuntimeForUpdate :many+-- Runtime access-change locking serializes new bindings. NOWAIT avoids waiting+-- behind a writer that already holds an agent and needs the runtime row.+SELECT * FROM agent+WHERE runtime_id = @runtime_id+ AND owner_id IS DISTINCT FROM @runtime_owner_id+ORDER BY id+FOR UPDATE NOWAIT;+-- name: RestoreAgent :oneUPDATE agent SET archived_at = NULL, archived_by = NULL, updated_at = now()WHERE id = $1diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sqlindex f38213541a..46c7528b71 100644--- a/server/pkg/db/queries/runtime.sql+++ b/server/pkg/db/queries/runtime.sql@@ -129,8 +129,9 @@ RETURNING *, (xmax = 0) AS inserted;-- name: UpdateAgentRuntimeVisibility :one-- Toggles a runtime between 'private' (only owner can bind agents) and-- 'public' (any workspace member can). Default for new rows is 'private'--- (see migration 083). Gated at the handler layer to owner / workspace--- admin only.+-- (see migration 083). Gated at the handler layer to the runtime owner only:+-- visibility is consent to use that person's machine, not a workspace-governance+-- setting.UPDATE agent_runtimeSET visibility = @visibility, updated_at = now()WHERE id = @id@@ -351,6 +352,72 @@ WHERE (runtime_id = ANY(@runtime_ids::uuid[]) OR agent_id = ANY(@agent_ids::uuidAND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')RETURNING *;+-- name: ListNonOwnerActiveTasksByRuntime :many+-- Lists live tasks targeting a public runtime but belonging to somebody other+-- than its owner, including hidden Builder execution carriers. It forms part of the public-to-private+-- confirmation plan so the owner explicitly approves cancelling work that+-- could otherwise keep running after machine access is revoked.+SELECT task.*+FROM agent_task_queue AS task+JOIN agent ON agent.id = task.agent_id+WHERE task.runtime_id = @runtime_id+ AND agent.owner_id IS DISTINCT FROM @runtime_owner_id+ AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+ORDER BY task.id;++-- name: ListNonOwnerActiveTasksByRuntimeForUpdate :many+-- Acquired after the affected agent and chat-session locks. Bindings serialize+-- on LockAgentRuntimeForAccessChange; claim/delivery rechecks authorization.+SELECT task.*+FROM agent_task_queue AS task+JOIN agent ON agent.id = task.agent_id+WHERE task.runtime_id = @runtime_id+ AND agent.owner_id IS DISTINCT FROM @runtime_owner_id+ AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+ORDER BY task.id+FOR UPDATE OF task;++-- name: LockAgentRuntimeForAccessChange :one+-- Binding and visibility writers share this lock and recheck access under it.+-- NO KEY UPDATE deliberately permits legacy FK KEY SHARE locks: a chat enqueue+-- holding session/agent locks must not wait here while revocation locks them.+SELECT * FROM agent_runtime WHERE id = $1 FOR NO KEY UPDATE;++-- name: LockRuntimeRevocationChatSessions :many+-- Revocation already holds affected agents. Never wait in the reverse of the+-- normal session -> agent/task order: a concurrent chat writer yields a 409+-- and the entire revocation rolls back before changing anything.+SELECT cs.id FROM chat_session cs+WHERE EXISTS (+ SELECT 1 FROM agent_task_queue task JOIN agent ON agent.id = task.agent_id+ WHERE task.chat_session_id = cs.id+ AND task.runtime_id = @runtime_id+ AND agent.owner_id IS DISTINCT FROM @runtime_owner_id+ AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+)+ORDER BY cs.id+FOR UPDATE OF cs NOWAIT;++-- name: CancelNonOwnerTasksByRuntime :many+-- Server-side execution revocation for a public runtime made private. The+-- join deliberately classifies work by its agent owner rather than cancelling+-- every task on the runtime, so the runtime owner's own tasks keep running.+-- cancellation polling on an online daemon observes the state change; an+-- offline daemon cannot run new work and will observe it after reconnecting.+UPDATE agent_task_queue AS task+SET status = 'cancelled',+ completed_at = now(), prepare_lease_expires_at = NULL,+ error = 'runtime access was revoked',+ failure_reason = @failure_reason::text,+ cancelled_by_type = 'system', cancelled_by_id = NULL, cancelled_by_name = NULL,+ wait_reason = NULL+FROM agent+WHERE task.agent_id = agent.id+ AND task.runtime_id = @runtime_id+ AND agent.owner_id IS DISTINCT FROM @runtime_owner_id+ AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+RETURNING task.*;+-- name: CountUndrainedTasksByRuntimeOrAgent :one-- Belt-and-braces gate for the runtime-delete transaction: after cancelling,-- every task on this runtime OR owned by an agent being unbound must be terminal@@ -393,6 +460,16 @@ SET runtime_id = NULL, updated_at = now()WHERE runtime_id = $1 AND kind = 'user'RETURNING *;+-- name: UnbindNonOwnerAgentsFromRuntime :many+-- The companion to CancelNonOwnerTasksByRuntime for a public-to-private+-- transition. Only teammates lose the binding; the runtime owner's agents+-- remain bound and usable after the machine becomes private again.+UPDATE agent+SET runtime_id = NULL, updated_at = now()+WHERE runtime_id = @runtime_id+ AND owner_id IS DISTINCT FROM @runtime_owner_id+RETURNING *;+-- name: DeleteAgentRuntime :execDELETE FROM agent_runtime WHERE id = $1;diff --git a/server/pkg/taskfailure/failure.go b/server/pkg/taskfailure/failure.goindex 4e50a0937d..530f275b9f 100644--- a/server/pkg/taskfailure/failure.go+++ b/server/pkg/taskfailure/failure.go@@ -73,6 +73,10 @@ const (// task went offline. Written by FailTasksForOfflineRuntimes.ReasonRuntimeOffline Reason = "runtime_offline"+ // ReasonRuntimeAccessRevoked: the runtime owner withdrew workspace access.+ // This is a cancellation, not a runner failure or a retryable outage.+ ReasonRuntimeAccessRevoked Reason = "runtime_access_revoked"+// ReasonRuntimeReconnectTimeout: a retry waiting for an offline runtime// remained deferred for the full reconnect grace. Non-retryable: the// runtime must return before a user starts another attempt. Written by@@ -280,6 +284,7 @@ var allReasons = []Reason{// Platform / scheduler side.ReasonQueuedExpired,ReasonRuntimeOffline,+ ReasonRuntimeAccessRevoked,ReasonRuntimeReconnectTimeout,ReasonRuntimeRecovery,ReasonTimeout,