diff --git a/CLAUDE.md b/CLAUDE.md index afa2d63103..50d8f1fc30 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -17,7 +17,7 @@ Flutter app for managing servers, in a Rust workspace monorepo. Feature notes li - `flutter test --timeout 30s` (`make test-one TEST=...`), `cargo test --workspace`. - Kotlin: from `android/`, `./gradlew :app:testDebugUnitTest -x :app:compileFlutterBuildDebug`. - `test/unit/` is split by **feature** (`ssh/`, `terminal/`, `file/`, `server/`, `virt/`, `monitor/`, …); `store/` is storage infrastructure, `app/` what belongs to no feature. Helpers: `test/helpers/`. -- Opt-in e2e, skipped when unset: `SBM_E2E_SSH_HOST` in `.env` + `cargo test -p sbm_parser --test ssh_e2e -- --ignored` (libvirt: `-p sbm_virt`); a unit's log read as accounts with and without journal access: `scripts/service-log-e2e.sh` (a privileged systemd container); RDP: `SBM_E2E_RDP_{HOST,PORT,USER,PASSWORD}` + `cargo test -p sbm_ffi --lib rdp_e2e -- --ignored` (an alpine `xrdp xorgxrdp` container serves); `flutter test test/e2e/app_mcp_real_test.dart` (the app's MCP server over real SSH, through `$SSH_AUTH_SOCK`'s agent); `flutter test test/e2e/virt_real_test.dart` (variables in its header; dartssh2 has no ssh-agent, so use `SBM_E2E_SSH_IDENTITY` or `SBM_E2E_SSH_KEY_PASSPHRASE`). +- Opt-in e2e, skipped when unset: `SBM_E2E_SSH_HOST` in `.env` + `cargo test -p sbm_parser --test ssh_e2e -- --ignored` (libvirt: `-p sbm_virt`); a unit's log read as accounts with and without journal access: `scripts/service-log-e2e.sh` (a privileged systemd container); a container action with no runtime: `SBM_E2E_NO_RUNTIME=1` and a `PATH` without docker/podman, `cargo test --test containers_api --test mcp_api` in `monitor/`; RDP: `SBM_E2E_RDP_{HOST,PORT,USER,PASSWORD}` + `cargo test -p sbm_ffi --lib rdp_e2e -- --ignored` (an alpine `xrdp xorgxrdp` container serves); `flutter test test/e2e/app_mcp_real_test.dart` (the app's MCP server over real SSH, through `$SSH_AUTH_SOCK`'s agent); `flutter test test/e2e/virt_real_test.dart` (variables in its header; dartssh2 has no ssh-agent, so use `SBM_E2E_SSH_IDENTITY` or `SBM_E2E_SSH_KEY_PASSPHRASE`). - Backups and chats end to end, each starting what it needs on loopback: `scripts/monitor-backup-e2e.sh` (the agent's, rclone + nginx WebDAV, Go's age), `scripts/app-backup-e2e.sh` (the app's sync to WebDAV, the `age` CLI), `scripts/agent-chat-encryption-e2e.sh OLD NEW` (Agent mode's chats encrypted in place, an older agent binary then this one). A test that sets up `TestWidgetsFlutterBinding` and makes real HTTP requests clears `HttpOverrides.global`: the binding answers every request 400. - Widget tests whose tree writes a store: `openTestDb()` in `setUp`, `SqliteDb.close` in `tearDown`, the store's `forTest()` — many widgets persist on their own, and a real file write in fake-async hangs. - **UI text in a test comes from the localization**, never a copied string: the instance the code reads (`l10n`, `libL10n`), else `AppLocalizationsEn()` / `LibLocalizationsEn()` / `LlmLocalizationsEn()`; panel: `get(LL).key()`. A message embedded in a longer text: `startOf` (`test/helpers/l10n.dart`). Server output and fixture data stay literal. diff --git a/crates/sbm_mcp/src/machine/containers.rs b/crates/sbm_mcp/src/machine/containers.rs index 30788ae48b..b703de8e8c 100644 --- a/crates/sbm_mcp/src/machine/containers.rs +++ b/crates/sbm_mcp/src/machine/containers.rs @@ -167,6 +167,8 @@ pub async fn listing( /// Performs one container action and answers the refreshed listing, with the /// action's own `exit_code` and `output` when it ran. +/// Refused, and recorded as refused, when a value cannot be used or no +/// runtime answers. pub async fn apply(m: &dyn Machine, action: ContainerAction) -> Result { let what = format!("containers {}", action_subject(&action)); // Refused before the runtime is probed, let alone run: a value that could @@ -176,8 +178,9 @@ pub async fn apply(m: &dyn Machine, action: ContainerAction) -> Result format!("system prune {}", flags.join(" ")) } -/// Why an action's values could not be used. +/// Why an action was refused before it ran: a value that could not be used, +/// or no runtime to run it with. /// /// A value reaches a runtime as an argument, so what is refused is what could /// stop being one: a control character that ends the line, a leading `-` the @@ -427,9 +428,17 @@ pub enum ContainerActionError { InvalidName, /// The extra arguments could not be split — an unterminated quote. InvalidArgs, + /// Neither Docker nor Podman answered: nothing to run the action with. + NoRuntime, } impl ContainerActionError { + /// Whether the refusal is about the values asked for, rather than the + /// machine. + pub fn is_input(self) -> bool { + self != Self::NoRuntime + } + /// The wire code, also what a refusal is recorded under. pub fn code(self) -> &'static str { match self { @@ -440,6 +449,7 @@ impl ContainerActionError { Self::InvalidReference => "invalid_reference", Self::InvalidName => "invalid_name", Self::InvalidArgs => "invalid_args", + Self::NoRuntime => "no_runtime", } } } @@ -454,6 +464,7 @@ impl std::fmt::Display for ContainerActionError { Self::InvalidReference => "the image reference contains a character it cannot", Self::InvalidName => "the container name is not one a runtime accepts", Self::InvalidArgs => "the extra arguments are not quoted correctly", + Self::NoRuntime => "neither Docker nor Podman answered on this machine", }) } } diff --git a/monitor/frontend/src/i18n/de/index.ts b/monitor/frontend/src/i18n/de/index.ts index 1d9260675c..8b65955f2c 100644 --- a/monitor/frontend/src/i18n/de/index.ts +++ b/monitor/frontend/src/i18n/de/index.ts @@ -157,6 +157,7 @@ const de = { containerErrControlCharacter: 'Ein Wert enthält ein Steuerzeichen (einen Zeilenumbruch oder ein NUL).', containerErrEmpty: 'Ein erforderlicher Wert ist leer.', containerErrInvalidArgs: 'Die Anführungszeichen in den zusätzlichen Argumenten sind nicht korrekt gesetzt.', + containerActionNoRuntime: 'Weder Docker noch Podman hat auf diesem Rechner geantwortet.', containerErrInvalidName: 'Die Container-Laufzeit akzeptiert diesen Namen nicht.', containerErrInvalidReference: 'Die Image-Referenz enthält ein unzulässiges Zeichen.', containerErrLeadingDash: 'Ein Wert darf nicht mit einem Bindestrich beginnen, da die Laufzeit ihn sonst als Option interpretiert.', diff --git a/monitor/frontend/src/i18n/en/index.ts b/monitor/frontend/src/i18n/en/index.ts index a6dd52458c..ee7b2484c5 100644 --- a/monitor/frontend/src/i18n/en/index.ts +++ b/monitor/frontend/src/i18n/en/index.ts @@ -160,6 +160,7 @@ const en = { containerErrControlCharacter: 'A value contains a control character (a newline or a NUL).', containerErrEmpty: 'A required value is empty.', containerErrInvalidArgs: 'Quotation marks in the extra arguments are unmatched.', + containerActionNoRuntime: 'Neither Docker nor Podman answered on this machine.', containerErrInvalidName: 'The container runtime does not accept this name.', containerErrInvalidReference: 'The image reference contains a character that is not allowed.', containerErrLeadingDash: 'A value cannot start with a hyphen because the runtime would treat it as an option.', diff --git a/monitor/frontend/src/i18n/es/index.ts b/monitor/frontend/src/i18n/es/index.ts index f791039c1c..f7c966d181 100644 --- a/monitor/frontend/src/i18n/es/index.ts +++ b/monitor/frontend/src/i18n/es/index.ts @@ -157,6 +157,7 @@ const es = { containerErrControlCharacter: 'Un valor contiene un carácter de control (un salto de línea o un NUL).', containerErrEmpty: 'Un valor obligatorio está vacío.', containerErrInvalidArgs: 'Hay comillas sin pareja en los argumentos adicionales.', + containerActionNoRuntime: 'Ni Docker ni Podman respondieron en esta máquina.', containerErrInvalidName: 'El runtime de contenedores no acepta este nombre.', containerErrInvalidReference: 'La referencia de la imagen contiene un carácter no permitido.', containerErrLeadingDash: 'Un valor no puede empezar por un guion, porque el runtime lo interpretaría como una opción.', diff --git a/monitor/frontend/src/i18n/fr/index.ts b/monitor/frontend/src/i18n/fr/index.ts index 39c62f3e65..c39ea5b887 100644 --- a/monitor/frontend/src/i18n/fr/index.ts +++ b/monitor/frontend/src/i18n/fr/index.ts @@ -157,6 +157,7 @@ const fr = { containerErrControlCharacter: 'Une valeur contient un caractère de contrôle (un saut de ligne ou un NUL).', containerErrEmpty: 'Une valeur requise est vide.', containerErrInvalidArgs: 'Les guillemets des arguments supplémentaires ne sont pas correctement appariés.', + containerActionNoRuntime: 'Ni Docker ni Podman n’a répondu sur cette machine.', containerErrInvalidName: 'Le runtime de conteneurs n’accepte pas ce nom.', containerErrInvalidReference: 'La référence de l’image contient un caractère interdit.', containerErrLeadingDash: 'Une valeur ne peut pas commencer par un tiret : le runtime l’interpréterait comme une option.', diff --git a/monitor/frontend/src/i18n/i18n-types.ts b/monitor/frontend/src/i18n/i18n-types.ts index ca931704b3..16ca093d04 100644 --- a/monitor/frontend/src/i18n/i18n-types.ts +++ b/monitor/frontend/src/i18n/i18n-types.ts @@ -674,6 +674,10 @@ type RootTranslation = { * Q​u​o​t​a​t​i​o​n​ ​m​a​r​k​s​ ​i​n​ ​t​h​e​ ​e​x​t​r​a​ ​a​r​g​u​m​e​n​t​s​ ​a​r​e​ ​u​n​m​a​t​c​h​e​d​. */ containerErrInvalidArgs: string + /** + * N​e​i​t​h​e​r​ ​D​o​c​k​e​r​ ​n​o​r​ ​P​o​d​m​a​n​ ​a​n​s​w​e​r​e​d​ ​o​n​ ​t​h​i​s​ ​m​a​c​h​i​n​e​. + */ + containerActionNoRuntime: string /** * T​h​e​ ​c​o​n​t​a​i​n​e​r​ ​r​u​n​t​i​m​e​ ​d​o​e​s​ ​n​o​t​ ​a​c​c​e​p​t​ ​t​h​i​s​ ​n​a​m​e​. */ @@ -11344,6 +11348,10 @@ export type TranslationFunctions = { * Quotation marks in the extra arguments are unmatched. */ containerErrInvalidArgs: () => LocalizedString + /** + * Neither Docker nor Podman answered on this machine. + */ + containerActionNoRuntime: () => LocalizedString /** * The container runtime does not accept this name. */ diff --git a/monitor/frontend/src/i18n/id/index.ts b/monitor/frontend/src/i18n/id/index.ts index 5050bce63c..2002c37954 100644 --- a/monitor/frontend/src/i18n/id/index.ts +++ b/monitor/frontend/src/i18n/id/index.ts @@ -157,6 +157,7 @@ const id = { containerErrControlCharacter: 'Suatu nilai berisi karakter kontrol (baris baru atau NUL).', containerErrEmpty: 'Nilai yang wajib diisi kosong.', containerErrInvalidArgs: 'Tanda kutip pada argumen tambahan tidak berpasangan.', + containerActionNoRuntime: 'Docker maupun Podman tidak merespons di mesin ini.', containerErrInvalidName: 'Nama kontainer ini tidak diterima oleh runtime.', containerErrInvalidReference: 'Referensi image mengandung karakter yang tidak diizinkan.', containerErrLeadingDash: 'Nilai tidak boleh diawali tanda hubung karena runtime akan menganggapnya sebagai opsi.', diff --git a/monitor/frontend/src/i18n/it/index.ts b/monitor/frontend/src/i18n/it/index.ts index d4070b561d..13715383a7 100644 --- a/monitor/frontend/src/i18n/it/index.ts +++ b/monitor/frontend/src/i18n/it/index.ts @@ -157,6 +157,7 @@ const it = { containerErrControlCharacter: 'Un valore contiene un carattere di controllo (un a capo o un NUL).', containerErrEmpty: 'Un valore obbligatorio è vuoto.', containerErrInvalidArgs: 'Le virgolette negli argomenti aggiuntivi non sono abbinate.', + containerActionNoRuntime: 'Né Docker né Podman hanno risposto su questa macchina.', containerErrInvalidName: 'Il runtime non accetta questo nome di container.', containerErrInvalidReference: 'Il riferimento all’immagine contiene un carattere non consentito.', containerErrLeadingDash: 'Un valore non può iniziare con un trattino: il runtime lo interpreterebbe come un’opzione.', diff --git a/monitor/frontend/src/i18n/ja/index.ts b/monitor/frontend/src/i18n/ja/index.ts index a732f1d916..2b00182cc6 100644 --- a/monitor/frontend/src/i18n/ja/index.ts +++ b/monitor/frontend/src/i18n/ja/index.ts @@ -157,6 +157,7 @@ const ja = { containerErrControlCharacter: '値に制御文字(改行や NUL)が含まれています。', containerErrEmpty: '必須の値が空です。', containerErrInvalidArgs: '追加の引数の引用符が対応していません。', + containerActionNoRuntime: 'このマシンでは Docker も Podman も応答しませんでした。', containerErrInvalidName: 'このコンテナ名はランタイムで使用できません。', containerErrInvalidReference: 'イメージ参照に使用できない文字が含まれています。', containerErrLeadingDash: '値の先頭にハイフンは使えません。ランタイムがオプションとして解釈します。', diff --git a/monitor/frontend/src/i18n/ko/index.ts b/monitor/frontend/src/i18n/ko/index.ts index 0bac4a5af8..fca54062ce 100644 --- a/monitor/frontend/src/i18n/ko/index.ts +++ b/monitor/frontend/src/i18n/ko/index.ts @@ -157,6 +157,7 @@ const ko = { containerErrControlCharacter: '값에 제어 문자(줄 바꿈 또는 NUL)가 들어 있습니다.', containerErrEmpty: '필수 값이 비어 있습니다.', containerErrInvalidArgs: '추가 인수의 따옴표가 짝을 이루지 않습니다.', + containerActionNoRuntime: '이 머신에서 Docker와 Podman 모두 응답하지 않았습니다.', containerErrInvalidName: '컨테이너 런타임에서 허용하지 않는 이름입니다.', containerErrInvalidReference: '이미지 참조에 사용할 수 없는 문자가 포함되어 있습니다.', containerErrLeadingDash: '값을 하이픈으로 시작할 수 없습니다. 런타임이 옵션으로 처리합니다.', diff --git a/monitor/frontend/src/i18n/nl/index.ts b/monitor/frontend/src/i18n/nl/index.ts index 8630dce3ab..df193cf031 100644 --- a/monitor/frontend/src/i18n/nl/index.ts +++ b/monitor/frontend/src/i18n/nl/index.ts @@ -157,6 +157,7 @@ const nl = { containerErrControlCharacter: 'Een waarde bevat een stuurteken (een nieuwe regel of een NUL).', containerErrEmpty: 'Een vereiste waarde is leeg.', containerErrInvalidArgs: 'De aanhalingstekens rond de extra argumenten zijn niet in balans.', + containerActionNoRuntime: 'Docker en Podman reageerden geen van beide op deze machine.', containerErrInvalidName: 'De containerruntime accepteert deze naam niet.', containerErrInvalidReference: 'De imagereferentie bevat een niet-toegestaan teken.', containerErrLeadingDash: 'Een waarde mag niet met een streepje beginnen; de runtime ziet dit anders als een optie.', diff --git a/monitor/frontend/src/i18n/pt/index.ts b/monitor/frontend/src/i18n/pt/index.ts index 3218ffc003..ba2b75cc9b 100644 --- a/monitor/frontend/src/i18n/pt/index.ts +++ b/monitor/frontend/src/i18n/pt/index.ts @@ -157,6 +157,7 @@ const pt = { containerErrControlCharacter: 'Um valor contém um caractere de controlo (uma nova linha ou um NUL).', containerErrEmpty: 'Um valor obrigatório está vazio.', containerErrInvalidArgs: 'As aspas dos argumentos adicionais não estão emparelhadas.', + containerActionNoRuntime: 'Nem o Docker nem o Podman responderam nesta máquina.', containerErrInvalidName: 'O runtime não aceita este nome de contêiner.', containerErrInvalidReference: 'A referência da imagem contém um carácter não permitido.', containerErrLeadingDash: 'Um valor não pode começar por hífen, pois o runtime irá interpretá-lo como uma opção.', diff --git a/monitor/frontend/src/i18n/ru/index.ts b/monitor/frontend/src/i18n/ru/index.ts index 79a11c4868..569495b570 100644 --- a/monitor/frontend/src/i18n/ru/index.ts +++ b/monitor/frontend/src/i18n/ru/index.ts @@ -157,6 +157,7 @@ const ru = { containerErrControlCharacter: 'Значение содержит управляющий символ (перевод строки или NUL).', containerErrEmpty: 'Обязательное значение пусто.', containerErrInvalidArgs: 'В дополнительных аргументах не совпадают открывающие и закрывающие кавычки.', + containerActionNoRuntime: 'На этой машине не ответили ни Docker, ни Podman.', containerErrInvalidName: 'Среда выполнения контейнеров не принимает это имя.', containerErrInvalidReference: 'В ссылке на образ есть недопустимые символы.', containerErrLeadingDash: 'Значение не может начинаться с дефиса: среда выполнения воспримет его как параметр.', diff --git a/monitor/frontend/src/i18n/tr/index.ts b/monitor/frontend/src/i18n/tr/index.ts index 7dbbdddbbc..edcd95be7a 100644 --- a/monitor/frontend/src/i18n/tr/index.ts +++ b/monitor/frontend/src/i18n/tr/index.ts @@ -157,6 +157,7 @@ const tr = { containerErrControlCharacter: 'Bir değer kontrol karakteri (satır sonu veya NUL) içeriyor.', containerErrEmpty: 'Zorunlu bir değer boş.', containerErrInvalidArgs: 'Ek bağımsız değişkenlerde açılış ve kapanış tırnakları eşleşmiyor.', + containerActionNoRuntime: 'Bu makinede ne Docker ne de Podman yanıt verdi.', containerErrInvalidName: 'Konteyner çalışma zamanı bu adı kabul etmiyor.', containerErrInvalidReference: 'İmaj başvurusu izin verilmeyen karakterler içeriyor.', containerErrLeadingDash: 'Değer tireyle başlayamaz; aksi hâlde çalışma zamanı bunu seçenek olarak algılar.', diff --git a/monitor/frontend/src/i18n/uk/index.ts b/monitor/frontend/src/i18n/uk/index.ts index 17936083f6..3aae351f32 100644 --- a/monitor/frontend/src/i18n/uk/index.ts +++ b/monitor/frontend/src/i18n/uk/index.ts @@ -157,6 +157,7 @@ const uk = { containerErrControlCharacter: 'Значення містить керуючий символ (переведення рядка або NUL).', containerErrEmpty: 'Обов\'язкове значення порожнє.', containerErrInvalidArgs: 'У додаткових аргументах не збігаються відкривальні та закривальні лапки.', + containerActionNoRuntime: 'На цій машині не відповіли ні Docker, ні Podman.', containerErrInvalidName: 'Середовище виконання контейнерів не приймає цю назву.', containerErrInvalidReference: 'Посилання на образ містить неприпустимі символи.', containerErrLeadingDash: 'Значення не може починатися з дефіса: середовище виконання сприйме його як параметр.', diff --git a/monitor/frontend/src/i18n/zh-CN/index.ts b/monitor/frontend/src/i18n/zh-CN/index.ts index 69b28855ca..a43419eb51 100644 --- a/monitor/frontend/src/i18n/zh-CN/index.ts +++ b/monitor/frontend/src/i18n/zh-CN/index.ts @@ -159,6 +159,7 @@ const zh_CN = { containerErrControlCharacter: '值中包含控制字符(换行符或 NUL)。', containerErrEmpty: '必填值为空。', containerErrInvalidArgs: '额外参数中的引号没有成对匹配。', + containerActionNoRuntime: '这台机器上的 Docker 和 Podman 都没有响应。', containerErrInvalidName: '容器运行时不接受此名称。', containerErrInvalidReference: '镜像引用包含不允许使用的字符。', containerErrLeadingDash: '值不能以连字符开头,否则运行时会将其识别为选项。', diff --git a/monitor/frontend/src/i18n/zh-TW/index.ts b/monitor/frontend/src/i18n/zh-TW/index.ts index f0792b1341..0029219e18 100644 --- a/monitor/frontend/src/i18n/zh-TW/index.ts +++ b/monitor/frontend/src/i18n/zh-TW/index.ts @@ -157,6 +157,7 @@ const zh_TW = { containerErrControlCharacter: '值中包含控制字元(換行字元或 NUL)。', containerErrEmpty: '必填值為空。', containerErrInvalidArgs: '額外引數中的引號沒有成對匹配。', + containerActionNoRuntime: '這台機器上的 Docker 和 Podman 都沒有回應。', containerErrInvalidName: '容器執行時不接受此名稱。', containerErrInvalidReference: '映像檔引用包含不允許使用的字元。', containerErrLeadingDash: '值不能以連字元開頭,否則執行時會將其識別為選項。', diff --git a/monitor/frontend/src/lib/api.ts b/monitor/frontend/src/lib/api.ts index 96010f5a78..b26aa5ebca 100644 --- a/monitor/frontend/src/lib/api.ts +++ b/monitor/frontend/src/lib/api.ts @@ -623,8 +623,8 @@ export const api = { ), /// One change, answered in one round trip with the refreshed listing and /// `exit_code`/`output`, what the runtime said about the change. A refusal - /// arrives as `ApiError.message` holding `invalid_input`, with the issue in - /// `body.issue`. + /// arrives as `ApiError.message` holding `invalid_input` (`no_runtime` when + /// no runtime answers), with the issue in `body.issue`. /// /// The agent bounds every action by `[remote_access.exec]`, which this side /// cannot read. A pull and a run fetch image layers, so they are the ones an diff --git a/monitor/frontend/src/lib/container.ts b/monitor/frontend/src/lib/container.ts index 342ed32249..5576441ba2 100644 --- a/monitor/frontend/src/lib/container.ts +++ b/monitor/frontend/src/lib/container.ts @@ -28,13 +28,16 @@ export function issueText(issue: string): string { return ll.containerErrInvalidName() case 'invalid_args': return ll.containerErrInvalidArgs() + case 'no_runtime': + return ll.containerActionNoRuntime() default: return issue } } /// A refusal from a container action: the agent answers -/// `400 {error:"invalid_input", issue:}`, which `errorFrom` turns into an +/// `400 {error:"invalid_input", issue:}` (`409 {error:"no_runtime"}` when +/// no runtime answers), which `errorFrom` turns into an /// `ApiError` whose `message` is the code and whose `body.issue` is the issue. /// Falls back to the message for anything else. export function refusalText(error: unknown): string { diff --git a/monitor/frontend/src/tests/containers.test.ts b/monitor/frontend/src/tests/containers.test.ts index 124194d1ca..5c514968db 100644 --- a/monitor/frontend/src/tests/containers.test.ts +++ b/monitor/frontend/src/tests/containers.test.ts @@ -217,6 +217,21 @@ describe('Containers page on the images tab', () => { expect(await screen.findByText(ll.containerErrInvalidReference())).toBeInTheDocument() }) + it('says no runtime answered when the action found none', async () => { + actContainer.mockRejectedValueOnce( + new ApiError('no_runtime', 409, undefined, { error: 'no_runtime', issue: 'no_runtime' }), + ) + render(Containers) + await fireEvent.click(await screen.findByRole('button', { name: ll.containerImages() })) + await fireEvent.click(await screen.findByText(/alpine/)) + + await fireEvent.click(screen.getByRole('button', { name: ll.containerRemove() })) + const buttons = await screen.findAllByRole('button', { name: ll.containerRemove() }) + await fireEvent.click(buttons.at(-1)!) + + expect(await screen.findByText(ll.containerActionNoRuntime())).toBeInTheDocument() + }) + it('drops an answer that arrives after the server changed', async () => { servers.list = [{ id: 'local', url: '', token: 't' }] servers.currentId = 'local' diff --git a/monitor/frontend/src/types/index.ts b/monitor/frontend/src/types/index.ts index d9a70c400f..ed43e0afa4 100644 --- a/monitor/frontend/src/types/index.ts +++ b/monitor/frontend/src/types/index.ts @@ -1051,9 +1051,10 @@ export interface ContainerView { logs: string | null } -/// Why an action's values were refused before anything ran +/// Why an action was refused before anything ran /// (`sbm_parser::container::ContainerActionError`), as a code the page -/// phrases. The agent answers `400 {error:"invalid_input", issue:}`. +/// phrases. The agent answers `400 {error:"invalid_input", issue:}`, or +/// `409 {error:"no_runtime", issue:"no_runtime"}`. export type ContainerIssue = | 'empty' | 'control_character' @@ -1062,6 +1063,7 @@ export type ContainerIssue = | 'invalid_reference' | 'invalid_name' | 'invalid_args' + | 'no_runtime' /// One change to one container. /// diff --git a/monitor/src/api/containers.rs b/monitor/src/api/containers.rs index 308196a8b2..f5bd22bba4 100644 --- a/monitor/src/api/containers.rs +++ b/monitor/src/api/containers.rs @@ -106,7 +106,10 @@ pub async fn act( }; match containers::apply(&Here::recorded(&state, gated.remote_ip), action).await { Ok(response) => Ok(HttpResponse::Ok().json(&response)), - Err(issue) => Ok(HttpResponse::BadRequest().json(&json!({ "error": "invalid_input", "issue": issue }))), + Err(issue) if issue.is_input() => { + Ok(HttpResponse::BadRequest().json(&json!({ "error": "invalid_input", "issue": issue }))) + } + Err(issue) => Ok(HttpResponse::Conflict().json(&json!({ "error": "no_runtime", "issue": issue }))), } } diff --git a/monitor/tests/containers_api.rs b/monitor/tests/containers_api.rs index c9414f3fee..e6d46c67d6 100644 --- a/monitor/tests/containers_api.rs +++ b/monitor/tests/containers_api.rs @@ -85,6 +85,28 @@ async fn capabilities_list_the_containers_page() { assert!(caps["features"].as_array().unwrap().iter().any(|f| f == "container_exec"), "{caps}"); } +/// An action on a machine where neither runtime answers is refused as such, +/// and recorded. Only where the listing says none is installed: on any other +/// machine the action would act on the runtime there. Run it there with a +/// `PATH` that leaves both out and `SBM_E2E_NO_RUNTIME=1`, which turns a +/// runtime found into a failure rather than a skip. +#[ntex::test] +async fn an_action_without_a_runtime_is_refused() { + let (srv, db) = server().await; + let (_, listing) = get(&srv, "").await; + if listing["reason_kind"] != "not_installed" { + assert!(std::env::var_os("SBM_E2E_NO_RUNTIME").is_none(), "a runtime answered: {listing}"); + return; + } + let (status, answer) = post(&srv, json!({ "action": "stop", "id": "sbm-no-such-container" })).await; + assert_eq!(status, 409, "{answer}"); + assert_eq!(answer["error"], "no_runtime", "{answer}"); + assert_eq!(answer["issue"], "no_runtime", "{answer}"); + let rows = audit(&db).await; + assert_eq!(rows.len(), 1, "{rows:?}"); + assert_eq!((rows[0].0.as_str(), rows[0].1.as_str()), ("denied", "denied"), "{rows:?}"); +} + /// A value the runtime would read as an option, or one it cannot take, is /// refused before the runtime is probed or anything runs. #[ntex::test] diff --git a/monitor/tests/mcp_api.rs b/monitor/tests/mcp_api.rs index fa3720eb61..8043f34f3b 100644 --- a/monitor/tests/mcp_api.rs +++ b/monitor/tests/mcp_api.rs @@ -465,6 +465,33 @@ async fn a_machine_tool_refuses_before_it_acts() { assert_eq!(body["result"]["isError"], true, "{body}"); } +/// A container action where neither runtime answers is a tool error, never a +/// listing that reads as done. Only where none is installed, as +/// `containers_api::an_action_without_a_runtime_is_refused` (and with its +/// `SBM_E2E_NO_RUNTIME`). +#[ntex::test] +async fn a_container_action_without_a_runtime_is_a_tool_error() { + let (srv, _) = server().await; + let (_, token) = mint(&srv, "t", &["read", "container"]).await; + let mcp = Mcp::new(&srv, Some(token)); + let (_, listing) = mcp + .post(rpc(1, "tools/call", json!({ "name": "containers", "arguments": {} }))) + .await; + if listing["result"]["structuredContent"]["reason_kind"] != "not_installed" { + assert!(std::env::var_os("SBM_E2E_NO_RUNTIME").is_none(), "a runtime answered: {listing}"); + return; + } + let (_, body) = mcp + .post(rpc( + 2, + "tools/call", + json!({ "name": "container_action", "arguments": { "action": "stop", "id": "sbm-no-such-container" } }), + )) + .await; + assert_eq!(body["result"]["isError"], true, "{body}"); + assert!(body.to_string().contains("no_runtime"), "{body}"); +} + #[ntex::test] async fn a_token_minted_with_read_scope_reads_the_machine() { let (srv, _) = server().await;