Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Worker-group list/get responses retain `workerIds` for direct membership and add
Container responses distinguish durable `desiredRuntimeStatus` (`running`/`stopped`) from the current Docker observation. Besides normal states, `starting`, `recovering`, and `unknown` may be returned; `unknown` carries only a safe retryable runtime diagnostic. `POST /api/containers/:id/recover` is the bounded, owner/lock-checked recovery endpoint for an unresponsive worker: persistent mounts are verified, only the disposable container is replaced, managed secrets are bootstrapped, and desired plugins are reconciled. It returns 409 when persistence cannot be verified and 503 when Docker cannot yet clear stale runtime state; it never removes persistent volumes. Management MCP provides the equivalent `workers.recover` tool and projects only structured safe diagnostics (code, operation/phase, retryability, timeout, and preservation state), never Docker command text, environment values, or credentials.


`POST /api/containers/:id/emergency-stop` accepts `{"confirmed":true,"lockPassword":"<when-protected>"}` and force-stops existing ordinary or administrative compute without a graceful shutdown. The authenticated owner or administrator may stop an ordinary or group administrative worker; platform administrative workspaces require an administrator. Incus uses a forced stop and Docker sends SIGKILL directly, retaining Docker's manual-stop restart-policy behavior. Persistent storage is retained, but unsaved work may be lost. Stale or unknown health does not prevent an ownership-verified attempt. Pending target lifecycle operations return 409; owner/setup serialization and unresolved recovery fences remain in effect. A missing administrative workspace is never provisioned by this endpoint.
`POST /api/containers/:id/emergency-stop` accepts `{"confirmed":true,"lockPassword":"<when-protected>"}` and force-stops existing ordinary or administrative compute without a graceful shutdown. The authenticated owner or administrator may stop an ordinary or group administrative worker; platform administrative workspaces require an administrator. Incus uses a forced stop and Docker sends SIGKILL directly, retaining Docker's manual-stop restart-policy behavior. Persistent storage is retained, but unsaved work may be lost. Stale or unknown health does not prevent an ownership-verified attempt. Stopped intent is saved even when observed state is unknown or another lifecycle request is pending. Runtime mutations remain serialized; an unconfirmed shutdown returns a bounded failure while the stop stays queued behind unresolved mutations. Success requires authoritative shutdown confirmation. A missing administrative workspace is never provisioned by this endpoint.


`POST /api/archived/:id/unarchive` accepts an optional explicit catalog recovery choice:
Expand Down Expand Up @@ -126,3 +126,18 @@ Saving backup settings first copies each additional directory into an Agentor-ma
## All API Routes

API routes return JSON unless their OpenAPI metadata explicitly documents a streaming or binary response/body (for example worker import, export artifacts, and workspace downloads). Full interactive reference is at `/api/docs` (Scalar UI) and raw spec at `/api/docs/openapi.json`.


### Recovery policy and requested runtime state

- `GET /api/containers/:id/recovery` reads the durable `maxRetries`, `attempts`, `paused`, safe `lastFailure`, and desired runtime state without guest probing.
- `PUT /api/containers/:id/recovery` accepts `{"maxRetries":3,"lockPassword":"<when-protected>"}`. The default is three automatic retries after an explicit start; `0` disables them. Values must be integers from 0 to 100, keeping automatic recovery finite. Changing the limit retains the attempt count and never starts compute.
- `PUT /api/containers/:id/desired-state` accepts `{"desiredRuntimeStatus":"stopped","confirmed":true,"lockPassword":"<when-protected>"}` (or `running`). It persists intent even if actual state cannot be observed. The response carries a warning: intent does not confirm that compute started or stopped. Explicit running intent resets the recovery counter; ordinary runtime authorization and storage/identity preflight still apply when reconciliation acts.

Automatic retry claims are persisted before attempting recovery. Exhaustion survives orchestrator restarts, stops further automatic startup attempts, and leaves persistent storage untouched. A verified successful recovery or explicit Start/Retry resets the counter. Failed probes alone never authorize a reboot. Emergency stop saves stopped intent before waiting for existing runtime mutations; a late startup cannot erase that intent. Unknown shutdown results remain unknown until the backend confirms stop. Exact runtime identity and unresolved mutation fences are retained, so emergency acceptance is not permission to act on foreign or unproven compute.

The worker settings panel exposes these controls with a warning acknowledgement. Cards show exhausted retry budgets. Official logs report accepted intent, attempt/limit, safe failing phase and exit code, exhausted budgets, cleanup outcomes, and confirmed versus unconfirmed emergency stops. Raw guest stderr and secret values are excluded.

Management MCP exposes `workers.recovery.get`, `workers.recovery.set`, `workers.desired-state.set`, and `workers.emergency-stop` to platform administrators and to group administrators for ordinary workers in their live group subtree. The state and emergency tools require `confirmed:true`; mutation tools enforce worker protection locks. `admin-workspace.emergency-stop` is platform-only and requires the exact `workerId`. `groups.admin-workspace.emergency-stop` accepts an authorized `groupId`, confirmation, and any required lock password; it can target the bound group or a descendant, and never provisions a missing administrative workspace. Group membership and hierarchy are rechecked when executing, so sibling, ungrouped, foreign-owner and platform-administrative workers remain outside group scope.

Guest GPU driver installation/repair remains the guest administrator's responsibility. A shared guest udev wait causing unrelated storage preparation to fail is a separate hypothesis requiring disposable reproduction; these controls do not replace drivers or weaken storage validation.
3 changes: 3 additions & 0 deletions orchestrator/app/components/ContainerCard.vue
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,9 @@ function onHScrollWheel(e: WheelEvent) {
<WorkerRuntimeIcon :runtime-kind="container.runtimeKind" />
</div>

<p v-if="container.recovery && container.recovery.attempts >= container.recovery.maxRetries" role="status" class="mb-2 text-xs text-amber-700 dark:text-amber-400">
Automatic recovery paused ({{ container.recovery.attempts }}/{{ container.recovery.maxRetries }}). Open settings to retry.
</p>
<!-- Per-worker live metrics: non-wrapping, scrollable when the card is narrow -->
<div
v-if="isRunning"
Expand Down
2 changes: 2 additions & 0 deletions orchestrator/app/components/ContainerDetailModal.vue
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,8 @@ const formattedCreatedAt = computed(() => {
</div>
</div>

<WorkerRecoveryPanel v-if="!container.administrativeKind" :worker-id="container.id" />

<!-- Pending rebuild banner -->
<div
v-if="container.pendingRebuild"
Expand Down
2 changes: 1 addition & 1 deletion orchestrator/app/components/WorkerEmergencyStopButton.vue
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ async function emergencyStop() {
needsPassword.value = needsPassword.value || status === 423;
error.value = status === 423
? 'Enter the worker lock password to confirm the emergency stop.'
: (cause?.data?.statusMessage || cause?.data?.message || 'The emergency stop has no confirmed outcome. Refresh worker status before retrying.');
: (cause?.data?.statusMessage || cause?.data?.message || 'Stopped state was requested, but shutdown is not confirmed. In-flight work may still be settling. Refresh status before retrying.');
if (status !== 423) await refreshStatus();
return;
} finally {
Expand Down
48 changes: 48 additions & 0 deletions orchestrator/app/components/WorkerRecoveryPanel.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<script setup lang="ts">
import { UNKNOWN_STATE_WARNING, type WorkerRecoveryState } from '../../shared/worker-recovery';
const props = defineProps<{ workerId: string }>();
const state = ref<WorkerRecoveryState & { paused: boolean; desiredRuntimeStatus?: string }>();
const maxRetries = ref(3), busy = ref(false), confirmed = ref(false), password = ref(''), needsPassword = ref(false), error = ref(''), outcome = ref('');
async function refresh() {
state.value = await $fetch(`/api/containers/${encodeURIComponent(props.workerId)}/recovery`);
maxRetries.value = state.value!.maxRetries;
}
onMounted(() => refresh().catch(() => { error.value = 'Recovery status is unavailable. Retry opening settings.'; }));
async function change(desiredRuntimeStatus?: 'running' | 'stopped') {
busy.value = true; error.value = ''; outcome.value = '';
try {
const result = await $fetch<any>(`/api/containers/${encodeURIComponent(props.workerId)}/${desiredRuntimeStatus ? 'desired-state' : 'recovery'}`, {
method: 'PUT', retry: 0, timeout: 20_000,
body: { ...(desiredRuntimeStatus ? { desiredRuntimeStatus, confirmed: confirmed.value } : { maxRetries: Number(maxRetries.value) }), lockPassword: password.value },
});
outcome.value = desiredRuntimeStatus ? `Requested ${result.desiredRuntimeStatus}; runtime confirmation is pending.` : 'Retry limit saved; attempt count retained.';
await refresh(); await refreshNuxtData('workers');
} catch (cause: any) {
needsPassword.value ||= (cause?.statusCode ?? cause?.response?.status) === 423;
error.value = cause?.data?.statusMessage || cause?.data?.message || 'Change could not be confirmed. Refresh status before retrying.';
} finally { busy.value = false; password.value = ''; }
}
</script>

<template>
<section class="my-4 space-y-3 rounded border border-gray-300 p-3 dark:border-gray-700" aria-label="Runtime recovery controls">
<h3 class="font-semibold">Runtime recovery</h3>
<p v-if="state" class="text-sm">Requested: {{ state.desiredRuntimeStatus || 'unknown' }}. Automatic attempts: {{ state.attempts }}/{{ state.maxRetries }}. {{ state.paused ? 'Automatic recovery paused.' : '' }}</p>
<p v-if="state?.lastFailure" role="status" class="text-sm text-amber-700 dark:text-amber-400">{{ state.lastFailure.message }}</p>
<div class="flex items-end gap-2">
<UFormField label="Maximum automatic retries" description="0 disables automatic retries. Start/Retry resets the counter.">
<UInput v-model.number="maxRetries" type="number" :min="0" :max="100" :disabled="busy" />
</UFormField>
<UButton :disabled="busy || !state" @click="change()">Save limit</UButton>
</div>
<p class="text-sm text-amber-700 dark:text-amber-400">{{ UNKNOWN_STATE_WARNING }}</p>
<UCheckbox v-model="confirmed" label="I understand that the requested state does not confirm the current state." :disabled="busy" />
<UFormField v-if="needsPassword" label="Worker lock password"><UInput v-model="password" type="password" autocomplete="off" :disabled="busy" /></UFormField>
<div class="flex gap-2">
<UButton :disabled="busy || !confirmed" @click="change('stopped')">Request stopped</UButton>
<UButton :disabled="busy || !confirmed" @click="change('running')">Request running / Retry</UButton>
</div>
<p v-if="outcome" role="status" class="text-sm">{{ outcome }}</p>
<p v-if="error" role="alert" class="text-sm text-red-600">{{ error }}</p>
</section>
</template>
22 changes: 22 additions & 0 deletions orchestrator/server/api/containers/[id]/desired-state.put.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
defineRouteMeta({ openAPI: {
tags: ['Containers'], summary: 'Set desired runtime state', operationId: 'setWorkerDesiredState',
description: 'Persist desiredRuntimeStatus running or stopped with confirmed true, even when observation is unknown. Warning: intent does not confirm runtime state. Protection locks apply.',
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
responses: { 200: { description: 'Requested policy or intent; observed runtime state is independent' }, 400: { description: 'Invalid retry limit, desired state or missing confirmation' }, 403: { description: 'Access denied' }, 404: { description: 'Worker not found' }, 423: { description: 'Protection lock required' } },
} });

import { requireContainerAccess } from '../../../utils/auth-helpers';
import { useContainerManager } from '../../../utils/services';
import { useWorkerProtectionLockStore } from '../../../utils/worker-protection-lock';
import { rethrowAsHttpError } from '../../../utils/http-errors';

export default defineEventHandler(async event => {
try {
const id = getRouterParam(event, 'id')!, manager = useContainerManager();
requireContainerAccess(event, manager.get(id));
const body = await readBody(event);
await useWorkerProtectionLockStore().verify(id, body?.lockPassword);
if (body?.confirmed !== true) throw createError({ statusCode: 400, statusMessage: 'Confirm the warning: changing desired state does not confirm runtime state' });
return await manager.setDesiredState(id, body?.desiredRuntimeStatus);
} catch (error) { rethrowAsHttpError(error); }
});
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ defineRouteMeta({
openAPI: {
tags: ['Containers'],
summary: 'Emergency stop a worker',
description: 'Immediately force-stops the existing worker without a graceful shutdown. Requires explicit confirmation and the protection-lock password when protected. Administrative workspaces retain their dedicated authorization. Pending lifecycle or recovery operations must settle before this action is allowed.',
description: 'Immediately force-stops the existing worker without a graceful shutdown. Requires explicit confirmation and the protection-lock password when protected. Administrative workspaces retain their dedicated authorization. Requests are accepted while lifecycle status is unknown; stopped intent is retained while pending runtime operations settle.',
operationId: 'emergencyStopContainer',
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
requestBody: { required: true, content: { 'application/json': { schema: {
Expand Down Expand Up @@ -30,7 +30,6 @@ import { useWorkerProtectionLockStore } from '../../../utils/worker-protection-l
import { readAdministrativeRuntimeRecord } from '../../../utils/admin-native-authority';
import { useAdminWorkspaceStore } from '../../../utils/admin-workspace-store';
import { useGroupAdminWorkspaceStore, type GroupAdministrativeWorkspaceRecord } from '../../../utils/group-admin-workspace-store';
import { isWorkerLifecycleMutationPending } from '../../../utils/worker-lifecycle-coordinator';
import { rethrowAsHttpError } from '../../../utils/http-errors';

export default defineEventHandler(async (event) => {
Expand All @@ -48,8 +47,6 @@ export default defineEventHandler(async (event) => {
if (body?.confirmed !== true)
throw createError({ statusCode: 400, statusMessage: 'Explicit confirmation is required for emergency stop' });
await useWorkerProtectionLockStore().verify(id, body.lockPassword);
if (isWorkerLifecycleMutationPending(id))
throw createError({ statusCode: 409, statusMessage: 'Worker lifecycle operation is still pending; refresh status before retrying emergency stop' });
if (administrative?.kind === 'administrative') await useAdminWorkspaceStore().setStatus('stopped', true, id);
else if (administrative) {
const groupId = (administrative as GroupAdministrativeWorkspaceRecord).groupId;
Expand Down
19 changes: 19 additions & 0 deletions orchestrator/server/api/containers/[id]/recovery.get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
defineRouteMeta({ openAPI: {
tags: ['Containers'], summary: 'Get recovery status', operationId: 'getWorkerRecovery',
description: 'Read durable retry policy, attempt count and safe last failure without runtime probing.',
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
responses: { 200: { description: 'Requested policy or intent; observed runtime state is independent' }, 400: { description: 'Invalid retry limit, desired state or missing confirmation' }, 403: { description: 'Access denied' }, 404: { description: 'Worker not found' }, 423: { description: 'Protection lock required' } },
} });

import { requireContainerAccess } from '../../../utils/auth-helpers';
import { useContainerManager } from '../../../utils/services';
import { useWorkerProtectionLockStore } from '../../../utils/worker-protection-lock';
import { rethrowAsHttpError } from '../../../utils/http-errors';

export default defineEventHandler(async event => {
try {
const id = getRouterParam(event, 'id')!, manager = useContainerManager();
requireContainerAccess(event, manager.get(id));
return await manager.getRecovery(id);
} catch (error) { rethrowAsHttpError(error); }
});
21 changes: 21 additions & 0 deletions orchestrator/server/api/containers/[id]/recovery.put.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
defineRouteMeta({ openAPI: {
tags: ['Containers'], summary: 'Set recovery retry limit', operationId: 'setWorkerRecovery',
description: 'Set maxRetries from 0 to 100; zero disables automatic retries. Attempts are retained and no runtime action is requested.',
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
responses: { 200: { description: 'Requested policy or intent; observed runtime state is independent' }, 400: { description: 'Invalid retry limit, desired state or missing confirmation' }, 403: { description: 'Access denied' }, 404: { description: 'Worker not found' }, 423: { description: 'Protection lock required' } },
} });

import { requireContainerAccess } from '../../../utils/auth-helpers';
import { useContainerManager } from '../../../utils/services';
import { useWorkerProtectionLockStore } from '../../../utils/worker-protection-lock';
import { rethrowAsHttpError } from '../../../utils/http-errors';

export default defineEventHandler(async event => {
try {
const id = getRouterParam(event, 'id')!, manager = useContainerManager();
requireContainerAccess(event, manager.get(id));
const body = await readBody(event);
await useWorkerProtectionLockStore().verify(id, body?.lockPassword);
return await manager.setRecovery(id, body?.maxRetries);
} catch (error) { rethrowAsHttpError(error); }
});
Loading
Loading